Bladeren bron

eip pom 及公共类合并

huangzhiyong 6 jaren geleden
bovenliggende
commit
e49f50a429
100 gewijzigde bestanden met toevoegingen van 13184 en 3 verwijderingen
  1. 18 0
      commons-admin-gateway-model/src/main/java/com/yihu/ehr/agModel/standard/cdadocument/CDAModel.java
  2. 21 0
      commons-data-redis/src/main/java/com/yihu/ehr/redis/client/RedisClient.java
  3. 11 0
      commons-data-redis/src/main/java/com/yihu/ehr/redis/schema/StdDataSetKeySchema.java
  4. 14 1
      commons-data-redis/src/main/java/com/yihu/ehr/redis/schema/StdMetaDataKeySchema.java
  5. 180 0
      commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MCDADocument.java
  6. 117 0
      commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MCDAType.java
  7. 66 0
      commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MCdaDataSet.java
  8. 58 0
      commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MCdaDataSetRelationship.java
  9. 118 0
      commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MSTDVersion.java
  10. 158 0
      commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MStdDataSet.java
  11. 134 0
      commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MStdDatasetRelation.java
  12. 146 0
      commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MStdDict.java
  13. 101 0
      commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MStdDictEntry.java
  14. 76 0
      commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MStdIndex.java
  15. 210 0
      commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MStdMetaData.java
  16. 109 0
      commons-rest-model/src/main/java/com/yihu/ehr/model/syspermission/MSystemMenu.java
  17. 221 2
      ehr-cloud-parent/pom.xml
  18. 216 0
      hos-web-framework/pom.xml
  19. 208 0
      hos-web-framework/src/main/java/com.yihu.hos.core/compress/Zipper.java
  20. 13 0
      hos-web-framework/src/main/java/com.yihu.hos.core/constants/CoreConstant.java
  21. 28 0
      hos-web-framework/src/main/java/com.yihu.hos.core/constants/ExceptionConstant.java
  22. 33 0
      hos-web-framework/src/main/java/com.yihu.hos.core/constants/MicroServices.java
  23. 286 0
      hos-web-framework/src/main/java/com.yihu.hos.core/constants/ServiceApi.java
  24. 23 0
      hos-web-framework/src/main/java/com.yihu.hos.core/datatype/ByteUtil.java
  25. 382 0
      hos-web-framework/src/main/java/com.yihu.hos.core/datatype/ClassFileUtil.java
  26. 18 0
      hos-web-framework/src/main/java/com.yihu.hos.core/datatype/CollectionUtil.java
  27. 104 0
      hos-web-framework/src/main/java/com.yihu.hos.core/datatype/DateFormatter.java
  28. 1486 0
      hos-web-framework/src/main/java/com.yihu.hos.core/datatype/DateUtil.java
  29. 88 0
      hos-web-framework/src/main/java/com.yihu.hos.core/datatype/ListSortUtil.java
  30. 661 0
      hos-web-framework/src/main/java/com.yihu.hos.core/datatype/NumberUtil.java
  31. 33 0
      hos-web-framework/src/main/java/com.yihu.hos.core/datatype/PinyinUtil.java
  32. 1424 0
      hos-web-framework/src/main/java/com.yihu.hos.core/datatype/StringUtil.java
  33. 132 0
      hos-web-framework/src/main/java/com.yihu.hos.core/encode/Base64.java
  34. 62 0
      hos-web-framework/src/main/java/com.yihu.hos.core/encode/EscapeUtil.java
  35. 29 0
      hos-web-framework/src/main/java/com.yihu.hos.core/encode/HexEncode.java
  36. 36 0
      hos-web-framework/src/main/java/com.yihu.hos.core/encrypt/DES.java
  37. 91 0
      hos-web-framework/src/main/java/com.yihu.hos.core/encrypt/MD5.java
  38. 123 0
      hos-web-framework/src/main/java/com.yihu.hos.core/encrypt/RSA.java
  39. 424 0
      hos-web-framework/src/main/java/com.yihu.hos.core/file/FileUtil.java
  40. 460 0
      hos-web-framework/src/main/java/com.yihu.hos.core/file/FtpFileUtil.java
  41. 15 0
      hos-web-framework/src/main/java/com.yihu.hos.core/http/AllowAllHostnameVerifier.java
  42. 100 0
      hos-web-framework/src/main/java/com.yihu.hos.core/http/CustomTrustClientClientImpl.java
  43. 336 0
      hos-web-framework/src/main/java/com.yihu.hos.core/http/DefaultClientImpl.java
  44. 54 0
      hos-web-framework/src/main/java/com.yihu.hos.core/http/HTTPClient.java
  45. 23 0
      hos-web-framework/src/main/java/com.yihu.hos.core/http/HTTPResponse.java
  46. 155 0
      hos-web-framework/src/main/java/com.yihu.hos.core/http/HttpClientKit.java
  47. 55 0
      hos-web-framework/src/main/java/com.yihu.hos.core/log/LogService.java
  48. 83 0
      hos-web-framework/src/main/java/com.yihu.hos.core/log/Logger.java
  49. 66 0
      hos-web-framework/src/main/java/com.yihu.hos.core/log/LoggerFactory.java
  50. 151 0
      hos-web-framework/src/main/java/com.yihu.hos.core/log/impl/Sl4jLoggerFactory.java
  51. 115 0
      hos-web-framework/src/main/java/com.yihu.hos.core/net/IPChoiceUtils.java
  52. 108 0
      hos-web-framework/src/main/java/com.yihu.hos.core/token/TokenUtil.java
  53. 220 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/baseservice/BaseJpaService.java
  54. 152 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/baseservice/BaseService.java
  55. 14 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/ApiVersionPrefix.java
  56. 13 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/ArchivesConstant.java
  57. 31 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/BizObject.java
  58. 31 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/ContextAttributes.java
  59. 86 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/DateConvert.java
  60. 16 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/EndPointConstant.java
  61. 293 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/ErrorCode.java
  62. 46 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/ErrorType.java
  63. 31 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/EventType.java
  64. 23 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/JobType.java
  65. 25 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/MycatConstant.java
  66. 14 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/PageArg.java
  67. 14 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/QcResultConstant.java
  68. 26 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/SSHConstant.java
  69. 41 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/ServiceFlowConstant.java
  70. 12 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/SessionAttributeKeys.java
  71. 88 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/SqlConstants.java
  72. 49 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/SystemDictId.java
  73. 1008 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/dao/SQLGeneralDAO.java
  74. 80 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/dao/XSQLGeneralDAO.java
  75. 97 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/ehrModel/BaseResult.java
  76. 102 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/ehrModel/ListResult.java
  77. 26 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/ehrModel/ObjectResult.java
  78. 12 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/AnalyzerException.java
  79. 42 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/ApiErrorEcho.java
  80. 41 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/ApiException.java
  81. 114 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/EsbApiException.java
  82. 15 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/IllegalEmptyCheckException.java
  83. 14 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/IllegalFormatCheckException.java
  84. 11 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/IllegalJsonDataException.java
  85. 13 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/IllegalJsonFileException.java
  86. 14 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/IllegalTypeCheckException.java
  87. 15 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/IllegalValueCheckException.java
  88. 28 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/LegacyPackageException.java
  89. 11 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/ResolveException.java
  90. 42 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/ResourceError.java
  91. 65 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/fastdfs/FastDFSClientPool.java
  92. 301 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/fastdfs/FastDFSUtil.java
  93. 61 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/model/AccessToken.java
  94. 33 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/model/ActionResult.java
  95. 124 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/model/DataGridResult.java
  96. 102 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/model/DetailModelResult.java
  97. 37 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/model/DictItem.java
  98. 54 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/model/DictionaryResult.java
  99. 118 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/model/Envelop.java
  100. 0 0
      hos-web-framework/src/main/java/com/yihu/hos/web/framework/model/EnvelopExt.java

+ 18 - 0
commons-admin-gateway-model/src/main/java/com/yihu/ehr/agModel/standard/cdadocument/CDAModel.java

@ -36,6 +36,8 @@ public class CDAModel {
    private String type;
    private String staged;
    private Long standardId;           //标准ID
    private String stdVersion;
    public String getCode() {
        return code;
@ -164,4 +166,20 @@ public class CDAModel {
    public void setStaged(String staged) {
        this.staged = staged;
    }
    public Long getStandardId() {
        return standardId;
    }
    public void setStandardId(Long standardId) {
        this.standardId = standardId;
    }
    public String getStdVersion() {
        return stdVersion;
    }
    public void setStdVersion(String stdVersion) {
        this.stdVersion = stdVersion;
    }
}

+ 21 - 0
commons-data-redis/src/main/java/com/yihu/ehr/redis/client/RedisClient.java

@ -75,6 +75,27 @@ public class RedisClient {
        });
    }
    /**
     * 批量设置key-value值。
     *
     * @param data
     */
    public void multiSetData(Map<String, Serializable> data){
        redisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                for (String key : data.keySet()) {
                    byte[] key_ = key.getBytes();
                    byte[] value_ = SerializationUtils.serialize(data.get(key));
                    connection.setNX(key_, value_);
                }
                return null;
            }
        });
    }
    /**
     * 获取数据
     *

+ 11 - 0
commons-data-redis/src/main/java/com/yihu/ehr/redis/schema/StdDataSetKeySchema.java

@ -23,6 +23,9 @@ public class StdDataSetKeySchema extends KeySchema {
    private String DataSetIsMultiRecordColumn = "multi_record";
    private String MetadataColumn = "metada_code";
    public String dataSetCode(String version, String id){
        return redisClient.get(makeKey(DataSetTable + version, id, DataSetCodeColumn));
    }
@ -54,4 +57,12 @@ public class StdDataSetKeySchema extends KeySchema {
    public void setDataSetMultiRecord(String version, String code,boolean value){
        redisClient.set(makeKey(DataSetTable + version, code, DataSetIsMultiRecordColumn),value);
    }
    public void setMetadataCode(String version, String code,String value){
        redisClient.set(makeKey(DataSetTable + version, code, MetadataColumn),value);
    }
    public String metadataCodes(String version, String datasetCode) {
        return redisClient.get(makeKey(DataSetTable + version, datasetCode, MetadataColumn));
    }
}

+ 14 - 1
commons-data-redis/src/main/java/com/yihu/ehr/redis/schema/StdMetaDataKeySchema.java

@ -13,6 +13,7 @@ public class StdMetaDataKeySchema extends KeySchema {
    private String MetaDataDictIdColumn = "dict_id";
    private String MetaDataTypeColumn = "type";
    private String MetaDataNameColumn = "name";
    private String MetaDataFormatColumn = "format";
    private String MetaDataNullableColumn = "nullable";
@ -77,7 +78,7 @@ public class StdMetaDataKeySchema extends KeySchema {
                code != null && code.length() != 0;
        String nullable = redisClient.get(makeKey(MetaDataTable + version, dataSetCode + "." + code, MetaDataNullableColumn));
        return nullable.equals("1");
        return "1".equals(nullable);
    }
    public void setMetaDataNullable(String version, String dataSetCode, String code, String value) {
@ -127,4 +128,16 @@ public class StdMetaDataKeySchema extends KeySchema {
        return redisClient.hasKey(makeKey(DictEntryTable + version, dictId + "." + entryValue, DictEntryValueColumn));
    }
    public void setMetaDataName(String version, String dataSetCode, String innerCode, String name) {
        redisClient.set(makeKey(MetaDataTable + version, dataSetCode + "." + innerCode, MetaDataNameColumn),name);
    }
    public String metaName(String version, String dataSetCode, String innerCode) {
        assert version != null && version.length() != 0 &&
                dataSetCode != null && dataSetCode.length() != 0 &&
                innerCode != null && innerCode.length() != 0;
        return redisClient.get(makeKey(MetaDataTable + version, dataSetCode + "." + innerCode, MetaDataNameColumn));
    }
}

+ 180 - 0
commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MCDADocument.java

@ -0,0 +1,180 @@
package com.yihu.ehr.model.standard;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
/**
 * @author AndyCai
 * @version 1.0
 * @created 01-9月-2015 16:54:17
 */
public class MCDADocument {
    //------------------ehr 字段
    private String id;
    private String code;
    private String name;
    private Date createDate;
    private String createUser;
    private String description;
    private Date updateDate;
    private String updateUser;
    private String versionCode;
    private String type;
    private String printOut;
    private String schema;
    private String sourceId;
    private int hashCode;
    private String fileGroup;
    //-------------------ehr 字段
    private String staged;
    private Long standardId;           //标准ID
    private String stdVersion;
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    public String getCreateUser() {
        return createUser;
    }
    public void setCreateUser(String createUser) {
        this.createUser = createUser;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    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;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getUpdateDate() {
        return updateDate;
    }
    public void setUpdateDate(Date updateDate) {
        this.updateDate = updateDate;
    }
    public String getUpdateUser() {
        return updateUser;
    }
    public void setUpdateUser(String updateUser) {
        this.updateUser = updateUser;
    }
    public String getVersionCode() {
        return versionCode;
    }
    public void setVersionCode(String versionCode) {
        this.versionCode = versionCode;
    }
    public String getPrintOut() {
        return printOut;
    }
    public void setPrintOut(String printOut) {
        this.printOut = printOut;
    }
    public String getSchema() {
        return schema;
    }
    public void setSchema(String schema) {
        this.schema = schema;
    }
    public String getSourceId() {
        return sourceId;
    }
    public void setSourceId(String sourceId) {
        this.sourceId = sourceId;
    }
    public int getHashCode() {
        return hashCode;
    }
    public void setHashCode(int hashCode) {
        this.hashCode = hashCode;
    }
    public String getFileGroup() {
        return fileGroup;
    }
    public void setFileGroup(String fileGroup) {
        this.fileGroup = fileGroup;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public String getStaged() {
        return staged;
    }
    public void setStaged(String staged) {
        this.staged = staged;
    }
    public Long getStandardId() {
        return standardId;
    }
    public void setStandardId(Long standardId) {
        this.standardId = standardId;
    }
    public String getStdVersion() {
        return stdVersion;
    }
    public void setStdVersion(String stdVersion) {
        this.stdVersion = stdVersion;
    }
}

+ 117 - 0
commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MCDAType.java

@ -0,0 +1,117 @@
package com.yihu.ehr.model.standard;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
import java.util.Objects;
/**
 * CDA类型
 *
 * @author AndyCai
 * @version 1.0
 * @created 11-12月-2015 15:52:22
 */
public class MCDAType {
    //-------------ehr 字段
    private String id;
    private String code;
    private String name;
    private String parentId;
    private Date createDate;
    private String createUser;
    private Date updateDate;
    private String updateUser;
    private String description;
    //-----------ehr   字段
    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 getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getParentId() {
        return parentId;
    }
    public void setParentId(String parentId) {
        this.parentId = parentId;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    public String getCreateUser() {
        return createUser;
    }
    public void setCreateUser(String createUser) {
        this.createUser = createUser;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getUpdateDate() {
        return updateDate;
    }
    public void setUpdateDate(Date updateDate) {
        this.updateDate = updateDate;
    }
    public String getUpdateUser() {
        return updateUser;
    }
    public void setUpdateUser(String updateUser) {
        this.updateUser = updateUser;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MCDAType mcdaType = (MCDAType) o;
        return Objects.equals(id, mcdaType.id) &&
                Objects.equals(code, mcdaType.code);
    }
    @Override
    public int hashCode() {
        return Objects.hash(id, code);
    }
}

+ 66 - 0
commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MCdaDataSet.java

@ -0,0 +1,66 @@
package com.yihu.ehr.model.standard;
/**
 * @author linaz
 * @created 2016.06.08 16:50
 */
public class MCdaDataSet {
	//---------------ehr -----------------------
	private String id;
	private String cdaId;
	private String dataSetId;
	private String dataSetCode;
	private String multiRecord;
	//------------ehr--------------------------
	private Long standardId;           //标准ID
	public String getDataSetId() {
		return dataSetId;
	}
	public void setDataSetId(String dataSetId) {
		this.dataSetId = dataSetId;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getCdaId() {
		return cdaId;
	}
	public void setCdaId(String cdaId) {
		this.cdaId = cdaId;
	}
	public String getDataSetCode() {
		return dataSetCode;
	}
	public void setDataSetCode(String dataSetCode) {
		this.dataSetCode = dataSetCode;
	}
	public String getMultiRecord() {
		return multiRecord;
	}
	public void setMultiRecord(String multiRecord) {
		this.multiRecord = multiRecord;
	}
	public Long getStandardId() {
		return standardId;
	}
	public void setStandardId(Long standardId) {
		this.standardId = standardId;
	}
}

+ 58 - 0
commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MCdaDataSetRelationship.java

@ -0,0 +1,58 @@
package com.yihu.ehr.model.standard;
/**
 * @author AndyCai
 * @version 1.0
 * @created 01-9月-2015 17:08:41
 */
public class MCdaDataSetRelationship {
	//------------------ehr
	private String id;
	private String cdaId;
	private String dataSetId;
	//-----------------ehr
	private Long standardId;           //标准ID
	private String stdVersion;
	public String getDataSetId() {
		return dataSetId;
	}
	public void setDataSetId(String dataSetId) {
		this.dataSetId = dataSetId;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getCdaId() {
		return cdaId;
	}
	public void setCdaId(String cdaId) {
		this.cdaId = cdaId;
	}
	public Long getStandardId() {
		return standardId;
	}
	public void setStandardId(Long standardId) {
		this.standardId = standardId;
	}
	public String getStdVersion() {
		return stdVersion;
	}
	public void setStdVersion(String stdVersion) {
		this.stdVersion = stdVersion;
	}
}

+ 118 - 0
commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MSTDVersion.java

@ -0,0 +1,118 @@
package com.yihu.ehr.model.standard;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
/**
 * @author lincl
 * @version 1.0
 * @created 2016.2.3
 */
public class MSTDVersion {
    private Long id;
    //-------------------------ehr 字段
    private String version;
    private String versionName;
    private String baseVersion;//基础版本
    private boolean inStage;
    private String author;
    private Date commitTime;//发布时间
    //------------------------ehr 字段
    private Long standardId;
    private String publishUser;//发布者
    private String primaryVersion;//主版本号
    private String path;
    public String getVersion() {
        return version;
    }
    public void setVersion(String version) {
        this.version = version;
    }
    public String getVersionName() {
        return versionName;
    }
    public void setVersionName(String versionName) {
        this.versionName = versionName;
    }
    public Long getStandardId() {
        return standardId;
    }
    public void setStandardId(Long standardId) {
        this.standardId = standardId;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getCommitTime() {
        return commitTime;
    }
    public void setCommitTime(Date commitTime) {
        this.commitTime = commitTime;
    }
    public String getPublishUser() {
        return publishUser;
    }
    public void setPublishUser(String publishUser) {
        this.publishUser = publishUser;
    }
    public String getBaseVersion() {
        return baseVersion;
    }
    public void setBaseVersion(String baseVersion) {
        this.baseVersion = baseVersion;
    }
    public String getPrimaryVersion() {
        return primaryVersion;
    }
    public void setPrimaryVersion(String primaryVersion) {
        this.primaryVersion = primaryVersion;
    }
    public boolean isInStage() {
        return inStage;
    }
    public void setInStage(boolean inStage) {
        this.inStage = inStage;
    }
    public String getPath() {
        return path;
    }
    public void setPath(String path) {
        this.path = path;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
}

+ 158 - 0
commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MStdDataSet.java

@ -0,0 +1,158 @@
package com.yihu.ehr.model.standard;
/**
 * 数据集
 * @author lincl
 * @version 1.0
 * @created 2016.2.1
 */
public class MStdDataSet {
    //---------------ehr   字段
    private Long id;
    private Long documentId;
    private String code;
    private String name;
    private Integer catalog;
    private String summary;
    private Integer lang;
    private Integer publisher;
    private boolean multiRecord;
    private String stdVersion;
    private Integer hashCode;
    private String reference;
    private String innerVersionId;
    //------------- ehr 字段
    private String classModel;
    private String language;
    private Long standardId;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public Long getDocumentId() {
        return documentId;
    }
    public void setDocumentId(Long documentId) {
        this.documentId = documentId;
    }
    public Integer getCatalog() {
        return catalog;
    }
    public void setCatalog(Integer catalog) {
        this.catalog = catalog;
    }
    public Integer getHashCode() {
        return hashCode;
    }
    public void setHashCode(Integer hashCode) {
        this.hashCode = hashCode;
    }
    public Integer getLang() {
        return lang;
    }
    public void setLang(Integer lang) {
        this.lang = lang;
    }
    public String getReference() {
        return reference;
    }
    public void setReference(String reference) {
        this.reference = reference;
    }
    public Integer getPublisher() {
        return publisher;
    }
    public void setPublisher(Integer publisher) {
        this.publisher = publisher;
    }
    public String getStdVersion() {
        return stdVersion;
    }
    public void setStdVersion(String stdVersion) {
        this.stdVersion = stdVersion;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSummary() {
        return summary;
    }
    public void setSummary(String summary) {
        this.summary = summary;
    }
    public String getInnerVersionId() {
        return innerVersionId;
    }
    public void setInnerVersionId(String innerVersionId) {
        this.innerVersionId = innerVersionId;
    }
    public boolean isMultiRecord() {
        return multiRecord;
    }
    public void setMultiRecord(boolean multiRecord) {
        this.multiRecord = multiRecord;
    }
    public String getLanguage() {
        return language;
    }
    public void setLanguage(String language) {
        this.language = language;
    }
    public String getClassModel() {
        return classModel;
    }
    public void setClassModel(String classModel) {
        this.classModel = classModel;
    }
    public Long getStandardId() {
        return standardId;
    }
    public void setStandardId(Long standardId) {
        this.standardId = standardId;
    }
}

+ 134 - 0
commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MStdDatasetRelation.java

@ -0,0 +1,134 @@
package com.yihu.ehr.model.standard;
import java.io.Serializable;
public class MStdDatasetRelation implements Serializable {
    private Integer id;
    private Long parentDatasetId;
    private String parentDatasetCode;
    private String parentDatasetName;
    private Long parentMetadataId;
    private String parentMetadataCode;
    private String parentMetadataName;
    private String relation;
    private Long childDatasetId;
    private String childDatasetCode;
    private String childDatasetName;
    private Long childMetadataId;
    private String childMetadataCode;
    private String childMetadataName;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public Long getParentDatasetId() {
        return parentDatasetId;
    }
    public void setParentDatasetId(Long parentDatasetId) {
        this.parentDatasetId = parentDatasetId;
    }
    public String getParentDatasetCode() {
        return parentDatasetCode;
    }
    public void setParentDatasetCode(String parentDatasetCode) {
        this.parentDatasetCode = parentDatasetCode;
    }
    public String getParentDatasetName() {
        return parentDatasetName;
    }
    public void setParentDatasetName(String parentDatasetName) {
        this.parentDatasetName = parentDatasetName;
    }
    public Long getParentMetadataId() {
        return parentMetadataId;
    }
    public void setParentMetadataId(Long parentMetadataId) {
        this.parentMetadataId = parentMetadataId;
    }
    public String getParentMetadataCode() {
        return parentMetadataCode;
    }
    public void setParentMetadataCode(String parentMetadataCode) {
        this.parentMetadataCode = parentMetadataCode;
    }
    public String getParentMetadataName() {
        return parentMetadataName;
    }
    public void setParentMetadataName(String parentMetadataName) {
        this.parentMetadataName = parentMetadataName;
    }
    public String getRelation() {
        return relation;
    }
    public void setRelation(String relation) {
        this.relation = relation;
    }
    public Long getChildDatasetId() {
        return childDatasetId;
    }
    public void setChildDatasetId(Long childDatasetId) {
        this.childDatasetId = childDatasetId;
    }
    public String getChildDatasetCode() {
        return childDatasetCode;
    }
    public void setChildDatasetCode(String childDatasetCode) {
        this.childDatasetCode = childDatasetCode;
    }
    public String getChildDatasetName() {
        return childDatasetName;
    }
    public void setChildDatasetName(String childDatasetName) {
        this.childDatasetName = childDatasetName;
    }
    public Long getChildMetadataId() {
        return childMetadataId;
    }
    public void setChildMetadataId(Long childMetadataId) {
        this.childMetadataId = childMetadataId;
    }
    public String getChildMetadataCode() {
        return childMetadataCode;
    }
    public void setChildMetadataCode(String childMetadataCode) {
        this.childMetadataCode = childMetadataCode;
    }
    public String getChildMetadataName() {
        return childMetadataName;
    }
    public void setChildMetadataName(String childMetadataName) {
        this.childMetadataName = childMetadataName;
    }
}

+ 146 - 0
commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MStdDict.java

@ -0,0 +1,146 @@
package com.yihu.ehr.model.standard;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
/**
 * 字典数据模型
 *
 * @version 1.0
 * @created 2016.2.22
 */
public class MStdDict {
    //----------------ehr 字段
    private Long id;
    private String code;//字典代码
    private String name;//字典名称
    private String description;//字典描述
    private Long baseDict;//参考/继承的字典
    private String author;// 作者
    private Date createDate;//创建日期
    private String sourceId;
    private String stdVersion;// 标准化版本
    private Integer hashCode;
    private String innerVersion;
    private Integer inStage;
    //----------------ehr 字段
    private Long standardId;
    private String define;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public Long getStandardId() {
        return standardId;
    }
    public void setStandardId(Long standardId) {
        this.standardId = standardId;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDefine() {
        return define;
    }
    public void setDefine(String define) {
        this.define = define;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public Long getBaseDict() {
        return baseDict;
    }
    public void setBaseDict(Long baseDict) {
        this.baseDict = baseDict;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getCreateDate() {
        return createDate;
    }
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
    public String getSourceId() {
        return sourceId;
    }
    public void setSourceId(String sourceId) {
        this.sourceId = sourceId;
    }
    public String getStdVersion() {
        return stdVersion;
    }
    public void setStdVersion(String stdVersion) {
        this.stdVersion = stdVersion;
    }
    public Integer getHashCode() {
        return hashCode;
    }
    public void setHashCode(Integer hashCode) {
        this.hashCode = hashCode;
    }
    public String getInnerVersion() {
        return innerVersion;
    }
    public void setInnerVersion(String innerVersion) {
        this.innerVersion = innerVersion;
    }
    public Integer getInStage() {
        return inStage;
    }
    public void setInStage(Integer inStage) {
        this.inStage = inStage;
    }
}

+ 101 - 0
commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MStdDictEntry.java

@ -0,0 +1,101 @@
package com.yihu.ehr.model.standard;
import java.util.Objects;
/**
 * 字典项数据模型
 *
 * @author lincl
 * @version 1.0
 * @created 2016.2.22
 */
public class MStdDictEntry {
    //------------------ehr   字段
    private Long id;
    private Long dictId;//字典ID
    private String code;
    private String value;
    private String desc;
    private Integer hashCode;
    //-----------------ehr   字段
    private String OperationType;
    private Long standardId;
    private String stdVersion;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public Long getDictId() {
        return dictId;
    }
    public void setDictId(Long dictId) {
        this.dictId = dictId;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
    public Integer getHashCode() {
        hashCode = Objects.hash(dictId, code, value, desc);
        return hashCode;
    }
    public void setHashCode(Integer hashCode) {
        this.hashCode = hashCode;
    }
    public Long getStandardId() {
        return standardId;
    }
    public void setStandardId(Long standardId) {
        this.standardId = standardId;
    }
    public String getOperationType() {
        return OperationType;
    }
    public void setOperationType(String operationType) {
        OperationType = operationType;
    }
    public String getStdVersion() {
        return stdVersion;
    }
    public void setStdVersion(String stdVersion) {
        this.stdVersion = stdVersion;
    }
}

+ 76 - 0
commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MStdIndex.java

@ -0,0 +1,76 @@
package com.yihu.ehr.model.standard;
public class MStdIndex {
    private Integer id;//主键id
    private Long stdDatasetId;//所属的数据集id
    private String stdDatasetCode;//所属的数据集code
    private String indexName;//索引名
    private String indexField;//字段,多个用,分割
    private String indexType;//索引类型   字典名: INDEX_TYPE
    private String indexMethod;//索引方法   字典名: INDEX_METHOD
    private String version;//版本号
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public Long getStdDatasetId() {
        return stdDatasetId;
    }
    public void setStdDatasetId(Long stdDatasetId) {
        this.stdDatasetId = stdDatasetId;
    }
    public String getStdDatasetCode() {
        return stdDatasetCode;
    }
    public void setStdDatasetCode(String stdDatasetCode) {
        this.stdDatasetCode = stdDatasetCode;
    }
    public String getIndexName() {
        return indexName;
    }
    public void setIndexName(String indexName) {
        this.indexName = indexName;
    }
    public String getIndexField() {
        return indexField;
    }
    public void setIndexField(String indexField) {
        this.indexField = indexField;
    }
    public String getIndexType() {
        return indexType;
    }
    public void setIndexType(String indexType) {
        this.indexType = indexType;
    }
    public String getIndexMethod() {
        return indexMethod;
    }
    public void setIndexMethod(String indexMethod) {
        this.indexMethod = indexMethod;
    }
    public String getVersion() {
        return version;
    }
    public void setVersion(String version) {
        this.version = version;
    }
}

+ 210 - 0
commons-rest-model/src/main/java/com/yihu/ehr/model/standard/MStdMetaData.java

@ -0,0 +1,210 @@
package com.yihu.ehr.model.standard;
import java.util.Objects;
/**
 * 数据元数据模型
 *
 * @author lincl
 * @version 1.0
 * @created 2016.2.22
 */
public class MStdMetaData {
    //--------------------ehr      字段
    private Long id;                    // 数据元ID
    private Long dataSetId;
    private String innerCode;           // 内部代码
    private String code;                 // 标准元编码
    private String name;                // 名称
    private String type;                // 数据元数据类型
    private String format;              // 表示格式
    private Long dictId;
    private String definition;          // 标准元定义, 即说明
    private boolean nullable;           // 是否可为空
    private String columnLength;         // 数据长度
    private String columnType;          // 数据类型
    private String columnName;          // 字段名
    private boolean primaryKey;         // 是否为主键
    private Integer hashCode;
    boolean isHbaseFullTextRetrieval;       // Hbase 全文检索字段
    boolean isHbasePrimaryKey;              // Hbase 主键字段
    private String dictName;
    private String dictCode;
    //--------------------ehr      字段
    private Long standardId;           //标准ID
    private String stdVersion;
    public Long getDictId() {
        return dictId;
    }
    public void setDictId(Long dictId) {
        this.dictId = dictId;
    }
    public Long getDataSetId() {
        return dataSetId;
    }
    public void setDataSetId(Long dataSetId) {
        this.dataSetId = dataSetId;
    }
    public String getColumnLength() {
        return columnLength;
    }
    public void setColumnLength(String length) {
        this.columnLength = length;
    }
    public String getColumnType() {
        return columnType;
    }
    public void setColumnType(String type) {
        this.columnType = type;
    }
    public String getColumnName() {
        return columnName;
    }
    public void setColumnName(String columnName) {
        this.columnName = columnName;
    }
    public boolean isNullable() {
        return nullable;
    }
    public void setNullable(boolean nullable) {
        this.nullable = nullable;
    }
    public boolean isPrimaryKey() {
        return primaryKey;
    }
    public void setPrimaryKey(boolean isPrimaryKey) {
        this.primaryKey = isPrimaryKey;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getDefinition() {
        return definition;
    }
    public void setDefinition(String definition) {
        this.definition = definition;
    }
    public String getFormat() {
        return format;
    }
    public void setFormat(String format) {
        this.format = format;
    }
    public Integer getHashCode() {
        hashCode = Objects.hash(dataSetId, dictId, code, definition, format, innerCode, name,
                type, columnLength, columnType, nullable, primaryKey);
        return hashCode;
    }
    public void setHashCode(Integer hashCode) {
        this.hashCode = hashCode;
    }
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getInnerCode() {
        return innerCode;
    }
    public void setInnerCode(String innerCode) {
        this.innerCode = innerCode;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
    public boolean isHbaseFullTextRetrieval() {
        return isHbaseFullTextRetrieval;
    }
    public void setHbaseFullTextRetrieval(boolean as) {
        isHbaseFullTextRetrieval = as;
    }
    public boolean isHbasePrimaryKey() {
        return isHbasePrimaryKey;
    }
    public void setHbasePrimaryKey(boolean as) {
        isHbasePrimaryKey = as;
    }
    public String getDictCode() {
        return dictCode;
    }
    public void setDictCode(String dictCode) {
        this.dictCode = dictCode;
    }
    public String getDictName() {
        return dictName;
    }
    public void setDictName(String dictName) {
        this.dictName = dictName;
    }
    public Long getStandardId() {
        return standardId;
    }
    public void setStandardId(Long standardId) {
        this.standardId = standardId;
    }
    public String getStdVersion() {
        return stdVersion;
    }
    public void setStdVersion(String stdVersion) {
        this.stdVersion = stdVersion;
    }
}

+ 109 - 0
commons-rest-model/src/main/java/com/yihu/ehr/model/syspermission/MSystemMenu.java

@ -0,0 +1,109 @@
package com.yihu.ehr.model.syspermission;
import java.io.Serializable;
/**
 * 菜单 Model
 */
public class MSystemMenu implements Serializable {
	private Integer id; // 主键
	private Integer pid; // 父主键
	private String code; // 编码
	private String name; // 名称
	private String type; // 类型,1:模块、2:菜单、3:功能。
	private String url; // 菜单相对地址
	private String icon; // icon地址
	private Integer sort; // 排序
	private String status; // 状态,1:启用,0:禁用。
	private String remark; // 说明
	private String content; // 页面菜单拼接对象
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Integer getPid() {
		return pid;
	}
	public void setPid(Integer pid) {
		this.pid = pid;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getIcon() {
		return icon;
	}
	public void setIcon(String icon) {
		this.icon = icon;
	}
	public Integer getSort() {
		return sort;
	}
	public void setSort(Integer sort) {
		this.sort = sort;
	}
	public String getStatus() {
		return status;
	}
	public void setStatus(String status) {
		this.status = status;
	}
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
}

+ 221 - 2
ehr-cloud-parent/pom.xml

@ -139,6 +139,24 @@
        <version.spring.boot.admin>1.5.7</version.spring.boot.admin>
        <version.jettison>1.3.7</version.jettison>
        <version.springside>4.2.3-GA</version.springside>
        <!-- eip -->
        <mine-util-version>2.1.3</mine-util-version>
        <sigar-version>1.6.4</sigar-version>
        <jsch-version>0.1.53</jsch-version>
        <commons-fileupload-version>1.3.1</commons-fileupload-version>
        <commons-collections4-version>4.1</commons-collections4-version>
        <zip4j-version>1.3.2</zip4j-version>
        <okhttp-version>3.4.1</okhttp-version>
        <pinyin4j-version>2.5.0</pinyin4j-version>
        <camel-version>2.19.1</camel-version>
        <activemq-version>5.7.0</activemq-version>
        <xbean-version>3.18</xbean-version>
        <slf4j-version>1.7.21</slf4j-version>
        <zbus-version>0.11.5</zbus-version>
        <jolokia-version>1.3.5</jolokia-version>
        <spring-securit-version>4.2.3.RELEASE</spring-securit-version>
        <hos-version>1.3.0</hos-version>
        <hos-web-framework>${hos-version}</hos-web-framework>
    </properties>
    <dependencyManagement>
@ -249,7 +267,16 @@
                <artifactId>commons-compress</artifactId>
                <version>${version.commons-compress}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-collections4</artifactId>
                <version>${commons-collections4-version}</version>
            </dependency>
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>${commons-fileupload-version}</version>
            </dependency>
            <!-- Mysql library -->
            <dependency>
                <groupId>mysql</groupId>
@ -599,6 +626,193 @@
                <artifactId>common-rest-model</artifactId>
                <version>${version.eip}</version>
            </dependency>
            <!-- Camel -->
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-parent</artifactId>
                <version>${camel-version}</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-spring-boot-starter</artifactId>
                <version>${camel-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-core</artifactId>
                <version>${camel-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>spi-annotations</artifactId>
                <version>${camel-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-jetty</artifactId>
                <version>${camel-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-jms</artifactId>
                <version>${camel-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-http4</artifactId>
                <version>${camel-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-cxf</artifactId>
                <version>${camel-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-quartz</artifactId>
                <version>${camel-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-quartz2</artifactId>
                <version>${camel-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-xmljson</artifactId>
                <version>${camel-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-stream</artifactId>
                <version>${camel-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-mongodb</artifactId>
                <version>${camel-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-restlet</artifactId>
                <version>${camel-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-servlet</artifactId>
                <version>${camel-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-jdbc</artifactId>
                <version>${camel-version}</version>
            </dependency>
            <!-- camel end -->
            <!-- ActiveMQ -->
            <dependency>
                <groupId>org.apache.activemq</groupId>
                <artifactId>activemq-core</artifactId>
                <version>${activemq-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.activemq</groupId>
                <artifactId>activemq-camel</artifactId>
                <version>${activemq-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.activemq</groupId>
                <artifactId>activemq-pool</artifactId>
                <version>${activemq-version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.xbean</groupId>
                <artifactId>xbean-spring</artifactId>
                <version>${xbean-version}</version>
                <exclusions>
                    <exclusion>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>io.zbus</groupId>
                <artifactId>zbus</artifactId>
                <version>${zbus-version}</version>
            </dependency>
            <!-- Logging -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>${slf4j-version}</version>
            </dependency>
            <!-- Testing -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${version.junit}</version>
            </dependency>
            <!-- Jolokia -->
            <dependency>
                <groupId>org.jolokia</groupId>
                <artifactId>jolokia-core</artifactId>
                <version>${jolokia-version}</version>
            </dependency>
            <dependency>
                <groupId>com.squareup.okhttp3</groupId>
                <artifactId>okhttp</artifactId>
                <version>${okhttp-version}</version>
            </dependency>
            <dependency>
                <groupId>eu.medsea.mimeutil</groupId>
                <artifactId>mime-util</artifactId>
                <version>${mine-util-version}</version>
            </dependency>
            <dependency>
                <groupId>org.fusesource</groupId>
                <artifactId>sigar</artifactId>
                <version>${sigar-version}</version>
            </dependency>
            <dependency>
                <groupId>com.jcraft</groupId>
                <artifactId>jsch</artifactId>
                <version>${jsch-version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-web</artifactId>
                <version>${spring-securit-version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-config</artifactId>
                <version>${spring-securit-version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-core</artifactId>
                <version>${spring-securit-version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.security</groupId>
                <artifactId>spring-security-crypto</artifactId>
                <version>${spring-securit-version}</version>
            </dependency>
            <dependency>
                <groupId>com.yihu.ehr</groupId>
                <artifactId>hos-web-framework</artifactId>
                <version>${hos-version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
@ -630,13 +844,18 @@
        </pluginRepository>
    </pluginRepositories>
    <!--用于发布到服务器 对应setting的对应server表情里面的id -->
    <distributionManagement>
        <repository>
            <id>jkzlRepositories</id>
            <name>jkzlRepositories</name>
            <url>http://172.19.103.43:8081/nexus/content/repositories/jkzlRepositories/</url>
        </repository>
        <snapshotRepository>
            <id>snapshots</id>
            <name>Snapshots</name>
            <url>http://172.19.103.43:8081/nexus/content/repositories/snapshots/</url>
        </snapshotRepository>
    </distributionManagement>
    <build>

+ 216 - 0
hos-web-framework/pom.xml

@ -0,0 +1,216 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.yihu.ehr</groupId>
        <artifactId>ehr-cloud-parent</artifactId>
        <version>1.13.1</version>
        <relativePath>../ehr-cloud-parent/pom.xml</relativePath>
    </parent>
    <artifactId>hos-web-framework</artifactId>
    <version>1.3.0</version>
    <description>原eip公共包</description>
    <dependencies>
        <dependency>
            <groupId>happy.fish</groupId>
            <artifactId>fastDFS</artifactId>
            <version>1.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-logging</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- swagger start -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>classmate</artifactId>
                    <groupId>com.fasterxml</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <scope>${dependency.scope}</scope>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
        </dependency>
        <!-- swagger end -->
        <!-- test start -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- test end -->
        <dependency>
            <groupId>eu.medsea.mimeutil</groupId>
            <artifactId>mime-util</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- old ho-core start-->
        <!--zip start-->
        <dependency>
            <groupId>net.lingala.zip4j</groupId>
            <artifactId>zip4j</artifactId>
        </dependency>
        <!--zip end-->
        <!--commons start-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
        </dependency>
        <!--commons end-->
        <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
        </dependency>
        <!--pinyin4j start-->
        <dependency>
            <groupId>com.belerweb</groupId>
            <artifactId>pinyin4j</artifactId>
        </dependency>
        <!--pinyin4j end-->
        <!--jackson start-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>
        <!--jackson 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>
        <!--=============httpclient end=============-->
        <!-- Log framework start-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.10</version>
        </dependency>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>fontbox</artifactId>
            <version>2.0.10</version>
        </dependency>
    </dependencies>
</project>

+ 208 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/compress/Zipper.java

@ -0,0 +1,208 @@
package com.yihu.hos.core.compress;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
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 {
    private static final Logger logger = LoggerFactory.getLogger(Zipper.class);
    /**
     * 使用给定密码解压指定的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 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);
    }
    /**
     * @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
     */
    public File zipFile(File unzipFile, String zipFileName, String pwd) throws ZipException {
        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());
        }
        try {
            ZipFile zipFile = new ZipFile(zipFileName);
            if (!unzipFile.exists()) {
                unzipFile.mkdirs();
            }
            if (unzipFile.isDirectory()) {
                zipFile.addFolder(unzipFile, parameters);
            } else {
                zipFile.addFile(unzipFile, parameters);
            }
            return new File(zipFileName);
        } catch (ZipException ex) {
            logger.error(ex.getMessage());
        }
        return null;
    }
    public File zipFileForAll(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 File unzipFile(File zipFile, String unzipDirectory) throws ZipException {
        return unzipFile(zipFile, unzipDirectory, null);
    }
}

+ 13 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/constants/CoreConstant.java

@ -0,0 +1,13 @@
package com.yihu.hos.core.constants;
/**
 * Created by Administrator on 2016/4/13.
 */
public class CoreConstant {
    public static String DOT = ".";
    public static String EMPTY = "";
    public static String HTTP = "http";
    public static String COLON = ":";
    public static String BACKSLASH = "/";
}

+ 28 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/constants/ExceptionConstant.java

@ -0,0 +1,28 @@
package com.yihu.hos.core.constants;
/**
 * Created by chenweida on 2016/1/27.
 */
public class ExceptionConstant {
    //===========================系统异常 3开头=============================
    public static String EHREXCEPTION_SYSTEMEXCEPTION = "30000";
    public static String EHREXCEPTION_SYSTEMEXCEPTION_MESSAGE = "系统异常,请联系管理员";
    public static String EHREXCEPTION_SYSTEM_TRANSFER = "30100";
    public static String EHREXCEPTION_SYSTEM_TRANSFER_MESSAGE = "目标服务异常,请稍后再试";
    //=============================业务异常 2开头=============================
    public static String EHREXCEPTION_BUSINESS_EXCEPTION = "20000";
    public static String EHREXCEPTION_BUSINESS_PARAMS_EXCEPTION = "20100";//请求的参数格式有错
    public static String EHREXCEPTION_BUSINESS_PARAMS_EXCEPTION_MESSAGE = "请求的参数格式错误";
    public static String EHREXCEPTION_BUSINESS_REOURCE_TYPE_EXCEPTION = "20200";//数据库的参数格式有错
    public static String EHREXCEPTION_BUSINESS_REOURCE_TYPE_EXCEPTION_MESSAGE = "业务资源类型格式错误";
    //=============================返回成功 10000=============================
    public static String EHREXCEPTION_SUCCESS = "10000";
    public static String EHREXCEPTION_SUCCESS_MESSAGE = "成功";
}

+ 33 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/constants/MicroServices.java

@ -0,0 +1,33 @@
package com.yihu.hos.core.constants;
/**
 * 全局微服务名称枚举。用于Feign及Thrift客户端。
 *
 * @author Sand
 * @version 1.0
 * @created 2016.01.11 8:54
 */
public class MicroServices {
    // 微服务名称汇总
    public static final String HosAdmin = "hos-admin";
    public static final String Standard = "hos-admin"; // 标准规范
    public static final String ServiceBus = "hos-admin"; // 服务总线
    public static final String DataCollection = "hos-admin"; // 数据采集
    public static final String Monitor = "hos-admin"; // 运行监控
    public static final String SysPermission = "hos-admin"; // 系统权限
    public static final String QualityControl = "hos-admin"; // 质控管理
    public static final String SysSetting = "hos-admin"; // 系统配置
    public static final String TenementControl = "hos-admin"; // 租户管理
    public static final String EhrApp = "svr-basic";
    public static final String SvrResource = "svr-resource";
    public class ApiVersion {
        public static final String Version1_0 = "/api/v1.0";
        public ApiVersion() {
        }
    }
}

+ 286 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/constants/ServiceApi.java

@ -0,0 +1,286 @@
package com.yihu.hos.core.constants;
public class ServiceApi {
    // 菜单管理
    public static class SystemMenu {
        public static final String Prefix = "/systemMenu/";
        public static final String Create = "/systemMenu/create";
        public static final String Update = "/systemMenu/update";
        public static final String Delete = "/systemMenu/delete";
        public static final String GetById = "/systemMenu/{id}";
        public static final String List = "/systemMenu/list";
        public static final String ListNoPage = "/systemMenu/listNoPage";
        public static final String ListByLoginCode = "/systemMenu/listByLoginCode";
        public static final String IsUniqueCode = "/systemMenu/isUniqueCode";
        public static final String IsUniqueName = "/systemMenu/isUniqueName";
    }
    public static class AppApiResponse {
        public static final String AppApiResponses = "/appApiResponse";
        public static final String AppApiResponse = "/appApiResponse/{id}";
    }
    public static class AppApiParameter {
        public static final String AppApiParameters = "/appApiParameter";
        public static final String AppApiParameter = "/appApiParameter/{id}";
    }
    public static class AppFeature {
        public static final String AppFeatures = "/appFeature";
        public static final String FilterFeatureList = "/filterFeatureList";
        public static final String FilterFeatureNoPage = "/filterFeatureNoPage";
        public static final String FilterFeatureNoPageSorts = "/filterFeatureNoPageSorts";
        public static final String AppFeature = "/appFeature/{id}";
        public static final String FindAppMenus = "/appFeature/findAppMenus";
        public static final String IsExist = "/appFeature/isExist";
    }
    public static class AppApi {
        public static final String AppApis = "/appApi";
        public static final String AppApi = "/appApi/{id}";
        public static final String AppApisNoPage = "/appApiNoPage";
        public static final String AppApiSearch = "/appApi/search";
        public static final String AppApiAuth = "/appApiAuth";
    }
    public static class Apps {
        public static final String Apps = "/apps";
        public static final String GetApp = "/app";
        public static final String GetList = "/getList";
        public static final String AppsNoPage = "/apps/no_paging";
        public static final String App = "/apps/{app_id}";
        public static final String AppExistence = "/apps/{app_id}/existence";
        public static final String AppStatus = "/apps/{app_id}/status";
        public static final String AppNameExistence = "/app/{app_name}/existence";
        public static final String FilterList = "/apps/filterList";
        public static final String getAppTreeByType = "/getAppTreeByType";
    }
    public static class AppService {
        public static final String Create = "/service";
        public static final String Update = "/service";
        public static final String GetById = "/service/{id}";
        public static final String DeleteById = "/service/{id}";
        public static final String List = "/service/list";
    }
    public static class StdIndex {
        public static final String Create = "/stdIndex";
        public static final String Update = "/stdIndex";
        public static final String GetById = "/stdIndex/{id}";
        public static final String DeleteById = "/stdIndex/{ids}";
        public static final String List = "stdIndex/list";
        public static final String IsUnique = "stdIndex/isUnique";
    }
    public static class StdRelation {
        public static final String Modify = "/stdRelation";
        public static final String DeleteById = "/stdRelation/{ids}";
        public static final String List = "stdRelation/list";
        public static final String ListNoPage = "stdRelation/listNoPage";
        public static final String IsUnique = "stdRelation/isUnique";
    }
    public static class Standards {
        public static final String Caches = "/std/caches";
        public static final String Cache = "/std/caches/{version}";
        public static final String Sources = "/std/sources";
        public static final String NoPageSources = "/std/sources/no_paging";
        public static final String Source = "/std/sources/{id}";
        public static final String IsSourceCodeExist = "/std/sources/code_is_exist";
        public static final String NoPageTypes = "/std/types/no_paging";
        public static final String Types = "/std/types";
        public static final String Type = "/std/types/{id}";
        public static final String TypesCodeExistence = "/std/type/code/existence";
        public static final String TypeChildren = "/std/types/parent_id/childrens";
        public static final String TypesChildren = "/std/types/childrens";
        public static final String TypeList = "/cda_types/code_name";
        public static final String TypeParent = "/std/types/parent";
        public static final String TypeOther = "/std/types/{id}/other";
        public static final String Versions = "/std/versions";
        public static final String Version = "/std/versions/{version}";
        public static final String VersionInStageExist = "/std/versions/in_stage/existence";
        public static final String VersionCache = "/std/versions/{version}/cache";
        public static final String VersionNameExistence = "/std/version/name/existence";
        public static final String VersionBackStage = "/std/versions/{version}/back";
        public static final String VersionCommit = "/std/versions/{version}/commit";
        public static final String VersionRevert = "/std/versions/{version}/revert";
        public static final String VersionLatest = "/std/versions/latest";
        public static final String VersionLatestExistence = "/std/versions/{version}/latest/existence";
        public static final String Documents = "/std/documents";
        public static final String Document = "/std/documents/{id}";
        public static final String DocumentList = "/std/documentsList";
        public static final String DocumentFileExistence = "/std/documents/{id}/file/existence";
        public static final String DocumentCreateFile = "/std/documents/{id}/file/create";
        public static final String DocumentGetFile = "/std/documents/{id}/file";
        public static final String DocumentDataSet = "/std/documents/data_set";
        public static final String DocumentDataSetList = "/std/documents/data_set_list";
        public static final String DataSetRelationships = "/std/documents/data_set_relationships";
        public static final String DataSetRelationship = "/std/documents/data_set_relationships/{id}";
        public static final String Dictionaries = "/std/dictionaries";
        public static final String NoPageDictionaries = "/std/dictionaries/no_paging";
        public static final String Dictionary = "/std/dictionaries/{id}";
        public static final String DictionaryCode = "/std/dictionaries/code";
        public static final String MetaDataWithDict = "/std/data_set/{data_set_id}/meta_datas/{meta_data_id}/dictionaries";
        public static final String DictCodeIsExist = "/std/dictionaries/is_exist/code";
        public static final String DictOther = "/std/dictionaries/{id}/other";
        public static final String DictParent = "/std/dictionaries/{id}/parent";
        public static final String DictCodesExistence = "/dict/codes/existence";
        public static final String DictEntryBatch = "/dict/entry/batch";
        public static final String Entry = "/std/dictionaries/entries/{id}";
        public static final String Entries = "/std/dictionaries/entries";
        public static final String EntriesWithDictionary = "/std/dictionary/{dict_id}/entries";
        public static final String EntryCodeIsExist = "/std/dictionaries/entries/is_exist/code";
        public static final String DataSets = "/std/data_sets";
        public static final String NoPageDataSets = "/std/data_sets/no_paging";
        public static final String DataSet = "/std/data_sets/{id}";
        public static final String DataSetsName = "/std/data_sets/name";
        public static final String DataSetCodeIsExist = "/std/data_set/is_exist/code";
        public static final String DataSetsIds = "/std/{ids}data_sets";
        public static final String DataSetsBatch = "/std/data_set/bacth";
        public static final String MetaDatas = "/std/data_sets/meta_datas";
        public static final String MetaData = "/std/data_sets/meta_datas/{id}";
        public static final String MetaDataCodeExistence = "/std/data_sets/{data_set_id}/meta_data/inner_code/existence";
        public static final String MetaDataNameExistence = "/std/data_sets/{data_set_id}/meta_data/name/existence";
        public static final String MetaDatasName = "/std/data_sets/meta_datas/name";
        public static final String MetaDatasWithDataSet = "/std/data_sets/{data_set_id}/meta_datas";
        public static final String DispatchLogs = "/std/dispatches/logs";
        public static final String Dispatch = "/std/dispatches/{id}";
        public static final String Dispatches = "/std/dispatches";
        public static final String AdaptMeta = "/std/adapt/meta";
        public static final String AdaptDict = "/std/adapt/dict";
        public static class Specialdict{
            public static class Icd10{
                public static final String ListPage = "/dict/icd10s";
                public static final String Create = "/dict/icd10";
                public static final String Update = "/dict/icd10";
                public static final String GetById = "/dict/icd10/{id}";
                public static final String Delete = "/dict/icd10s";
                public static final String DeleteById = "/dict/icd10/{id}";
                public static final String IsCodeExist = "/dict/icd10/existence/code/{code}";
                public static final String IsNameExist = "/dict/icd10/existence/name";
                public static final String Icd10DictIsUsage = "/dict/icd10/hp/{id}";
                public static final String FindByCode = "/dict/icd10/code/{code}";
                public static final String FindByCodeList = "/dict/icd10/codeList";
                public static final String GetIcd10DictListByIds = "/dict/icd10/ids";
            }
            public static class IndicatorDict{
                public static final String ListPage = "/dict/indicators";
                public static final String Create = "/dict/indicator";
                public static final String Update = "/dict/indicator";
                public static final String GetById = "/dict/indicator/{id}";
                public static final String Delete = "/dict/indicators";
                public static final String DeleteById = "/dict/indicator/{id}";
                public static final String IsCodeExist = "/dict/indicator/existence/code/{code}";
                public static final String IsNameExist = "/dict/indicator/existence/name";
                public static final String IsUsage = "/dict/indicator/icd10/{id}";
                public static final String GetByCode = "/dict/indicators/code";
                public static final String GetByCodeList = "/dict/indicators/codeList";
                public static final String GetByIds = "/dict/indicators/ids";
            }
            public static class Drug{
                public static final String ListPage = "/dict/drugs";
                public static final String Create = "/dict/drug";
                public static final String Update = "/dict/drug";
                public static final String GetById = "/dict/drug/{id}";
                public static final String Delete = "/dict/drugs";
                public static final String DeleteById = "/dict/drug/{id}";
                public static final String IsCodeExist = "/dict/drug/existence/code/{code}";
                public static final String IsNameExist = "/dict/drug/existence/name";
                public static final String IsUsage = "/dict/drug/icd10/{id}";
                public static final String GetByIds = "/drugs/ids";
            }
            public static class HealthProblemDict{
                public static final String ListPage = "/dict/hps";
                public static final String Create = "/dict/hp";
                public static final String Update = "/dict/hp";
                public static final String GetById = "/getHpDict/hp/{id}";
                public static final String Delete = "/dict/hps";
                public static final String IsCodeExist = "/dict/hp/existence/code/{code}";
                public static final String IsNameExist = "/dict/hp/existence/name";
                public static final String GetHpDictByCode = "/dict/hp/{code}";
                public static final String GetDrugDictListByHpCode = "/dict/hp/{code}/drug";
                public static final String GetIndicatorsByHpCode = "/dict/hp/{code}/indicators";
                public static final String GetIcd10ByHpCode = "/dict/hp/{code}/icd10";
            }
            public static class Icd10DrugRelation{
                public static final String Create   = "/dict/icd10/drug";
                public static final String Creates  = "/dict/icd10/drugs";
                public static final String Update  = "/dict/icd10/drug";
                public static final String DeleteById  = "/dict/icd10/drug";
                public static final String Delete  = "/dict/icd10/drugs";
                public static final String ListPage  = "/dict/icd10/drugs";
                public static final String ListNoPage  = "/dict/icd10/drugs/no_paging";
                public static final String IsExist  = "/dict/icd10/drug/existence";
                public static final String GetByIcd10Ids  = "/icd10_drug_relations/icd10_ids";
            }
            public static class Icd10HpRelation{
                public static final String Create   = "/dict/hp/icd10";
                public static final String Creates  = "/dict/hp/icd10s";
                public static final String Update  = "/dict/hp/icd10";
                public static final String DeleteById  = "/dict/hp/icd10";
                public static final String Delete  = "/dict/hp/icd10s";
                public static final String ListPage  = "/dict/hp/icd10s";
                public static final String ListNoPage  = "/dict/hp/icd10s/no_paging";
                public static final String IsExist  = "/dict/hp/icd10/existence";
                public static final String GetByHpId  = "/hp_icd10_relation/hp_id";
            }
            public static class Icd10IndicatorRelation{
                public static final String Create   = "/dict/icd10/indicator";
                public static final String Creates  = "/dict/icd10/indicators";
                public static final String Update  = "/dict/icd10/indicator";
                public static final String DeleteById  = "/dict/icd10/indicator";
                public static final String Delete  ="/dict/icd10/indicators";
                public static final String ListPage  = "/dict/icd10/indicators";
                public static final String ListNoPage  = "/dict/icd10/indicators/no_paging";
                public static final String IsExist  = "/dict/icd10/indicator/existence";
                public static final String GetByIcd10Ids  = "/icd10_indicator_relations/icd10_ids";
            }
        }
    }
    //redis相关
    public static class Redis {
        public static final String InitDataSet = "/redis/init/dataset";
        public static final String InitMetada = "/redis/init/metada";
        public static final String InitDict = "/redis/init/dict";
        public static final String InitVersions = "/redis/init/versions";
        public static final String StdVersion = "/redis/stdVersion";
        public static final String StdDataSetCode = "/redis/stdDataSetCode";
        public static final String StdDataSetName = "/redis/stdDataSetName";
        public static final String StdDataSetNameByCode = "/redis/stdDataSetNameByCode";
        public static final String StdDataSetMultiRecord = "/redis/stdDataSetMultiRecord";
        public static final String StdMetadataType = "/redis/stdMetaDataType";
        public static final String StdMetadataDict = "/redis/stdMetaDataDict";
        public static final String StdDictEntryValue = "/redis/stdDictEntryValue";
        public static final String StdMetadataCodes = "/redis/stdMetadataCodes";
        public static final String StdMetadataName = "/redis/stdMetadataName";
        public static final String StdMetadataNullable = "/redis/stdMetaData/nullable";
        public static final String StdMetadataFormat = "/redis/stdMetadataFormat";
        public static final String StdDictEntryCodeExist = "/redis/stdDictEntry/CodeExist";
        public static final String StdDictEntryValueExist = "/redis/stdDictEntry/ValueExist";
        //清除缓存
        public static final String Delete = "/redis/delete";
        public static final String InitAdapterVersions = "/redis/init/adapterVersions";
        public static final String AdapterDataSetCode =  "/redis/adapterDataSetCode";
        public static final String AdapterMetadataCode =  "/redis/adapterMetadataCode";
        public static final String AdapterDictCode =  "/redis/adapterDictCode";
        public static final String AdapterDictEntryCode =  "/redis/adapterDictEntryCode";
    }
}

+ 23 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/datatype/ByteUtil.java

@ -0,0 +1,23 @@
package com.yihu.hos.core.datatype;
/**
 * @author Sand
 * @version 1.0
 * @created 2015.08.29 14:41
 */
public class ByteUtil {
//    public static byte[] longToBytes(long x) {
//        ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
//        buffer.putLong(0, x);
//
//        return buffer.array();
//    }
//    public static long bytesToLong(byte[] bytes) {
//        ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
//        buffer.put(bytes, 0, bytes.length);
//        buffer.flip();//need flip
//
//        return buffer.getLong();
//    }
}

+ 382 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/datatype/ClassFileUtil.java

@ -0,0 +1,382 @@
package com.yihu.hos.core.datatype;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.core.file.FileUtil;
import com.yihu.hos.core.http.HTTPResponse;
import com.yihu.hos.core.http.HttpClientKit;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;
public class ClassFileUtil {
    public static final String CLASS_FILE = ".class";
    public static final Logger logger = LoggerFactory.getLogger(ClassFileUtil.CLASS_FILE);
    public static final String JAVA_FILE = ".java";
    /**
     * 工具类不允许进行实例化
     */
    private ClassFileUtil() {
    }
    /**
     * 通过这个工具方法,可以进行class文件的创建
     *
     * @param url         本次进行系统创建的system业务系统存储class文件的根目录
     * @param packageName class文件的包信息
     * @param className   class文件的类名信息
     * @param path        class文件的路径
     */
    public static Boolean createClassfile(URL url, String packageName, String className, String path) {
        // 开始输出文件内容
        try {
            FileInputStream in = new FileInputStream(new File(path));
            File systemFlowFile = new File(url.getPath());
            if (!systemFlowFile.exists()) {
                systemFlowFile.mkdirs();
            }
            packageName = StringUtil.replaceStrAll(packageName, ".", "/");
            File packageFile = new File(url.getPath() + "/" + packageName);
            if (!packageFile.exists()) {
                packageFile.mkdirs();
            }
            String classPath = packageFile + "/" + className + ".class";
            File file = new File(classPath);
            if (file.isFile() && file.exists()) {
                file.delete();
            }
            file.createNewFile();
            FileOutputStream out = new FileOutputStream(classPath);
            int n = 0;// 每次读取的字节长度
            byte[] bb = new byte[1024];// 存储每次读取的内容
            while ((n = in.read(bb)) != -1) {
                out.write(bb, 0, n);// 将读取的内容,写入到输出流当中
            }
            out.close();
            in.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    public static Boolean updateClassfile(String classPath, String path) {
        // 开始输出文件内容
        try {
            FileInputStream in = new FileInputStream(new File(path));
            File file = new File(classPath);
            if (file.isFile() && file.exists()) {
                file.delete();
            } else {
                file.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(classPath);
            int n = 0;// 每次读取的字节长度
            byte[] bb = new byte[1024];// 存储每次读取的内容
            while ((n = in.read(bb)) != -1) {
                out.write(bb, 0, n);// 将读取的内容,写入到输出流当中
            }
            out.close();
            in.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    public static Boolean deleteClassfile(String classPath) {
        // 开始输出文件内容
        try {
            boolean succ = false;
            File file = new File(classPath);
            if (file.isFile() && file.exists()) {
                succ = file.delete();
            }
            return succ;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 通过这个工具方法,可以进行class文件的创建
     *
     * @param url         本次进行系统创建的system业务系统存储class文件的根目录
     * @param packageName class文件的包信息
     * @param className   class文件的类名信息
     */
    public static FileOutputStream createClassfile(URL url, String packageName, String className) {
        // 开始输出文件内容
        try {
            String packagePath = StringUtil.replaceStrAll(packageName, ".", "/");
            File packageFile = new File(url.getPath() + "/" + packagePath);
            if (!packageFile.exists()) {
                packageFile.mkdirs();
            }
            String classPath = packageFile.getPath() + "/" + className + CLASS_FILE;
            File file = new File(classPath);
            if (file.isFile() && file.exists()) {
                file.delete();
            }
            file.createNewFile();
            FileOutputStream out = new FileOutputStream(classPath);
            return out;
        } catch (Exception e) {
            return null;
        }
    }
    public static FileOutputStream createFile(URL url, String packageName, String className, String fileType) {
        try {
            String packagePath = StringUtil.replaceStrAll(packageName, ".", "/");
            File packageFile = new File(url.getPath() + "/" + packagePath);
            if (!packageFile.exists()) {
                boolean mkdirs = packageFile.mkdirs();
                if (!mkdirs) {
                    return null;
                }
            }
            String classPath = packageFile.getPath() + "/" + className + fileType;
            File file = new File(classPath);
            if (file.isFile() && file.exists()) {
                boolean delete = file.delete();
                if (!delete) {
                    //Logger;
                    logger.warn("can't delete file, " + file.getAbsolutePath());
                }
            }
            boolean created = file.createNewFile();
            if (!created) {
                return null;
            }
            return new FileOutputStream(classPath);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static String getFilePath(URL url, String packageName, String className, String fileType) {
        String packagePath = StringUtil.replaceStrAll(packageName, ".", "/");
        return url.getPath() + packagePath + "/" + className + fileType;
    }
    /**
     * 下载文件,返回下载后的文件地址
     *
     * @param downUrl     http请求地址
     * @param url         本地保存根目录
     * @param packageName 包名
     * @param className   类名
     * @param fileType    文件类型
     * @return
     */
    public static String downFile(String downUrl, URL url, String packageName, String className, String fileType) {
        try {
            String packagePath = StringUtil.replaceStrAll(packageName, ".", "/");
            File packageFile = new File(url.getPath() + "/" + packagePath);
            if (!packageFile.exists()) {
                boolean mkdirs = packageFile.mkdirs();
                if (!mkdirs) {
                    return null;
                }
            }
            String classPath = packageFile.getPath() + "/" + className + fileType;
            byte[] bytes = down(downUrl);//文件内容
            boolean succ = FileUtil.writeFile(classPath, bytes, "UTF-8");//写入文件
            if (succ) {
                return classPath;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static String uploadFile(String uploadUrl, File file, String fileName) {
        try {
            return upload(uploadUrl, file);
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * http接口下载文件
     *
     * @param url 请求地址
     * @return
     */
    public static byte[] down(String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        try {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000 * 60 * 5).setConnectTimeout(1000 * 60 * 5).build();//设置请求和传输超时时间
            httpget.setConfig(requestConfig);
            response = httpClient.execute(httpget);
            response.setHeader("Content-Type", "application/octet-stream;charset=UTF-8");
            entity = response.getEntity();
            byte[] bytes = FileUtil.getBytesByStream(entity.getContent());
            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                EntityUtils.consume(entity);
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static String upload(String url, File file) {
        HTTPResponse response = HttpClientKit.postFile(url, "file", file.toString(), "text/plain");
        if (response.getStatusCode() != 200) {
            System.out.println("上传文件失败,status:"+response.getStatusCode()+" body: "+response.getBody());
            return null;
        }
        return response.getBody();
    }
    public static String upload(String url, String filePath) {
        HTTPResponse response = HttpClientKit.postFile(url, "file", filePath, "text/plain");
        if (response.getStatusCode() != 200) {
            System.out.println("上传文件失败,status:"+response.getStatusCode()+" body: "+response.getBody());
            return null;
        }
        return response.getBody();
    }
    /**
     * http 上传文件到中心请求
     *
     * @param url  请求地址
     * @param file 文件名
     * @return
     */
    public static String upload(String url, File file, String fileName) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        try {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000 * 60 * 5).setConnectTimeout(1000 * 60 * 5).build();//设置请求和传输超时时间
            httpPost.setConfig(requestConfig);
            MultipartEntityBuilder reqEntity1 = MultipartEntityBuilder.create();
            reqEntity1.addBinaryBody("file", file);
            reqEntity1.addTextBody("fileName", fileName, ContentType.create("text/plain", Charset.forName("UTF-8")));
            httpPost.setEntity(reqEntity1.build());
            response = httpClient.execute(httpPost);
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            entity = response.getEntity();
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                System.out.println("请求成功,上传成功!entry:" + response.getEntity().getContent().toString());
                ;
                return response.getEntity().getContent().toString();
            } else {
                System.out.println("上传请求失败,status:" + code);
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                EntityUtils.consume(entity);
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
     * http请求 从管理中心删除文件
     *
     * @param url
     * @return
     */
    public static boolean deleteFile(String url) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpDelete httpDelete = new HttpDelete(url);
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        try {
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000 * 60 * 5).setConnectTimeout(1000 * 60 * 5).build();//设置请求和传输超时时间
            httpDelete.setConfig(requestConfig);
            response = httpClient.execute(httpDelete);
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            entity = response.getEntity();
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                System.out.println("请求成功,文件删除成功!body:" + response.getEntity().toString());
                return true;
            } else {
                System.out.println("删除请求失败,status:" + code);
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                EntityUtils.consume(entity);
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
    public static Map<String, Object> parseRespon(HttpEntity entity) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
        String line = null;
        while ((line = br.readLine()) != null) {
            stringBuilder.append(line);
        }
        String responseText = stringBuilder.toString();
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> map = objectMapper.readValue(responseText, Map.class);
        return map;
    }
}

+ 18 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/datatype/CollectionUtil.java

@ -0,0 +1,18 @@
package com.yihu.hos.core.datatype;
import org.apache.commons.collections4.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);
    }
}

+ 104 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/datatype/DateFormatter.java

@ -0,0 +1,104 @@
package com.yihu.hos.core.datatype;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * ????????????????????????????????????????????????
 * @author Sand
 * @version 1.0
 * @created 2015.08.26 8:49
 */
public class DateFormatter {
    static final String simpleDateTimePattern = "yyyy-MM-dd HH:mm:ss";
    static final String utcDateTimePattern = "yyyy-MM-dd'T'HH:mm:ss'Z'";
    static final String slashDateTimePattern = "yyyy/MM/dd HH:mm:ss";
    static final String simpleDatePattern = "yyyy-MM-dd";
    static final String simpleDateTimeShortPattern = "yyyy/MM/dd HH:mm";
    private static ThreadLocal<SimpleDateFormat> simpleDateTimeShortFormat = new ThreadLocal<SimpleDateFormat>(){
        @Override
        protected synchronized SimpleDateFormat initialValue(){
            return new SimpleDateFormat(simpleDateTimeShortPattern);
        }
    };
    private static ThreadLocal<SimpleDateFormat> simpleDateTimeFormat = new ThreadLocal<SimpleDateFormat>(){
        @Override
        protected synchronized SimpleDateFormat initialValue(){
            return new SimpleDateFormat(simpleDateTimePattern);
        }
    };
    private static ThreadLocal<SimpleDateFormat> utcDateTimeFormat = new ThreadLocal<SimpleDateFormat>(){
        @Override
        protected synchronized SimpleDateFormat initialValue(){
            return new SimpleDateFormat(utcDateTimePattern);
        }
    };
    private static ThreadLocal<SimpleDateFormat> slashDateTimeFormat = new ThreadLocal<SimpleDateFormat>(){
        @Override
        protected synchronized SimpleDateFormat initialValue(){
            return new SimpleDateFormat(slashDateTimePattern);
        }
    };
    private static ThreadLocal<SimpleDateFormat> simpleDateFormat = new ThreadLocal<SimpleDateFormat>(){
        @Override
        protected synchronized SimpleDateFormat initialValue(){
            return new SimpleDateFormat(simpleDatePattern);
        }
    };
    public static String simpleDateTimeFormat(final Date date){
        String time = simpleDateTimeFormat.get().format(date);
        return time;
    }
    public static Date simpleDateTimeParse(final String date) throws ParseException {
        Date parsedDate = simpleDateTimeFormat.get().parse(date);
        return parsedDate;
    }
    public static String utcDateTimeFormat(final Date date){
        String time = utcDateTimeFormat.get().format(date);
        return time;
    }
    public static Date utcDateTimeParse(final String date) throws ParseException {
        Date parsedDate = utcDateTimeFormat.get().parse(date);
        return parsedDate;
    }
    public static String slashDateTimeFormat(final Date date){
        String result = slashDateTimeFormat.get().format(date);
        return result;
    }
    public static Date slashDateTimeParse(final String date) throws ParseException {
        Date parsedDate = slashDateTimeFormat.get().parse(date);
        return parsedDate;
    }
    public static String simpleDateFormat(final Date date){
        String result = simpleDateFormat.get().format(date);
        return result;
    }
    public static Date simpleDateParse(final String date) throws ParseException {
        Date parsedDate = simpleDateFormat.get().parse(date);
        return parsedDate;
    }
    public static String simpleDateTimeShortFormat(final Date date){
        String result = simpleDateTimeShortFormat.get().format(date);
        return result;
    }
    public static Date simpleDateTimeShortParse(final String date) throws ParseException {
        Date parsedDate = simpleDateTimeShortFormat.get().parse(date);
        return parsedDate;
    }
}

+ 1486 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/datatype/DateUtil.java

@ -0,0 +1,1486 @@
/****************************************************************************
 * 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.hos.core.datatype;
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 final String DATE_WORLD_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
    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 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 Date addHours(int add, java.util.Date d) {
        return addHours(add, new Date(d.getTime()));
    }
    public static Date addHours(int add, Date d) {
        if (d == null) {
            return null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime((java.util.Date) d);
        cal.setTimeZone(TimeZone.getDefault());
        cal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY) +add);
        return new Date(cal.getTime().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;
    }
    /**
     *  日期加减天数 (可优化)
     * @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 String getUtcDate(String dateStr,String format){
        SimpleDateFormat sdf1 = new SimpleDateFormat(DATE_WORLD_FORMAT);
        SimpleDateFormat sdf2 = new SimpleDateFormat(format);
        String date= null;
        try {
            date = sdf1.format(sdf2.parse(dateStr));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
    public static String getUtcDate(java.util.Date date){
        SimpleDateFormat sdf1 = new SimpleDateFormat(DATE_WORLD_FORMAT);
        String utcDate = sdf1.format(date);
        return utcDate;
    }
    //utc时间转换
    public static String utcToDate(String utcTime,String format){
        SimpleDateFormat utcSdf = new SimpleDateFormat(DATE_WORLD_FORMAT);
        SimpleDateFormat newSdf = new SimpleDateFormat(format);
        String date= null;
        try {
            if (!StringUtil.isEmpty(utcTime)){
                java.util.Date parse = utcSdf.parse(utcTime);
                date = newSdf.format(parse);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
    //utc时间转换
    public static java.util.Date utcTimeToDate(String utcTime,String format){
        SimpleDateFormat utcSdf = new SimpleDateFormat(DATE_WORLD_FORMAT);
        SimpleDateFormat newSdf = new SimpleDateFormat(format);
        java.util.Date utcDate = null;
        try {
            if (!StringUtil.isEmpty(utcTime)) {
                  utcDate = utcSdf.parse(utcTime);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return utcDate;
    }
}

+ 88 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/datatype/ListSortUtil.java

@ -0,0 +1,88 @@
/******************************************************************************/
/* SYSTEM     : Commons                                                       */
/*                                                                            */
/* SUBSYSTEM  : Util                                                          */
/******************************************************************************/
package com.yihu.hos.core.datatype;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections4.comparators.ComparatorChain;
import org.apache.commons.collections4.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()),
                    reverse);
        }
        if (cc.size() != 0) {
            // ���`��
            Collections.sort(list, cc);
        }
        return list;
    }
}

+ 661 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/datatype/NumberUtil.java

@ -0,0 +1,661 @@
package com.yihu.hos.core.datatype;
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 BigDecimal subtractBigDecimal(BigDecimal dec1, BigDecimal dec2) {
        return (dec1 != null ? dec1 : DEFAULT_NUMBER).subtract(dec2 != null ? dec2 : DEFAULT_NUMBER);
    }
    public static boolean isZero(BigDecimal num) {
        if (num == null) {
            return false;
        }
        if (equals(num, BigDecimal.ZERO)) {
            return true;
        }
        return false;
    }
    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 boolean isZero(Integer num) {
        if (num == null) {
            return true;
        }
        if (num == 0) {
            return true;
        }
        return false;
    }
    public static boolean isZero(Long num) {
        if (num == null) {
            return true;
        }
        if (num == 0L) {
            return true;
        }
        return false;
    }
    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;
    }
}

+ 33 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/datatype/PinyinUtil.java

@ -0,0 +1,33 @@
package com.yihu.hos.core.datatype;
import net.sourceforge.pinyin4j.PinyinHelper;
/**
 * 拼音工具包装。
 *
 * @author Sand
 * @version 1.0
 * @created 2015.07.30 15:33
 */
public class PinyinUtil {
    /**
     * 提取汉字的首字母
     * @param str
     * @return
     */
    public static String getPinYinHeadChar(String str, boolean upperCase) {
        String convert = "";
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        return upperCase ? convert.toUpperCase() : convert;
    }
}

+ 1424 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/datatype/StringUtil.java

@ -0,0 +1,1424 @@
package com.yihu.hos.core.datatype;
import org.apache.commons.lang3.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:????????? ????????? ?? ???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:????????? ????????? ??
     * ???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:?????????�A??
     * ????????? ?? ???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;
            }
        }
    }
    /**
     * ***************************************************** ?? ????????????�I????
     * ????????param strSource ???�I?????????param strFrom ????????param strTo ???????? ????????? ??
     * ????�I???????? <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;
    }
    /**
     * ***************************************************** ?? ?????????????��???�I???????
     * ????????param String strTarget, String strNew ????????? ?? ???return String
     * ????????�I????? <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;
    }
    /**
     * ***************************************************** ??
     * ????????????��????????????????????...???? ????????param src ???????????,param len ?????�� ????????? ??
     * ???return String ??��????????????????????...??????????? <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;
        }
        // ???????????????????�I??????????????????????????????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 ex) {
            //LogService.getLogger(StringUtil.class).error(ex.getMessage());
            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) { // ?��?????????
            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) {
            System.out.println("????????????????" + ex.getMessage());
        }
        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;
    }
    /**
     * ***************************************************** ??
     * ??????��??????????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;
        }
    }
}

+ 132 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/encode/Base64.java

@ -0,0 +1,132 @@
package com.yihu.hos.core.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;
    }
}

+ 62 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/encode/EscapeUtil.java

@ -0,0 +1,62 @@
package com.yihu.hos.core.encode;
/**
 * Created by cws on 2015/7/30.
 * 用于URL特殊符号转义。
 */
public class EscapeUtil {
    public static String escape(String src) {
        int i;
        char j;
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length() * 6);
        for (i = 0; i < src.length(); i++) {
            j = src.charAt(i);
            if (Character.isDigit(j) || Character.isLowerCase(j)
                    || Character.isUpperCase(j))
                tmp.append(j);
            else if (j < 256) {
                tmp.append("%");
                if (j < 16)
                    tmp.append("0");
                tmp.append(Integer.toString(j, 16));
            } else {
                tmp.append("%u");
                tmp.append(Integer.toString(j, 16));
            }
        }
        return tmp.toString();
    }
    public static String unescape(String src) {
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length());
        int lastPos = 0, pos = 0;
        char ch;
        while (lastPos < src.length()) {
            pos = src.indexOf("%", lastPos);
            if (pos == lastPos) {
                if (src.charAt(pos + 1) == 'u') {
                    ch = (char) Integer.parseInt(src
                            .substring(pos + 2, pos + 6), 16);
                    tmp.append(ch);
                    lastPos = pos + 6;
                } else {
                    ch = (char) Integer.parseInt(src
                            .substring(pos + 1, pos + 3), 16);
                    tmp.append(ch);
                    lastPos = pos + 3;
                }
            } else {
                if (pos == -1) {
                    tmp.append(src.substring(lastPos));
                    lastPos = src.length();
                } else {
                    tmp.append(src.substring(lastPos, pos));
                    lastPos = pos;
                }
            }
        }
        return tmp.toString();
    }
}

+ 29 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/encode/HexEncode.java

@ -0,0 +1,29 @@
package com.yihu.hos.core.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;
    }
}

+ 36 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/encrypt/DES.java

@ -0,0 +1,36 @@
package com.yihu.hos.core.encrypt;
import com.yihu.hos.core.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 COMMON_PASSWORD = "12345678";
    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)));
    }
}

+ 91 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/encrypt/MD5.java

@ -0,0 +1,91 @@
package com.yihu.hos.core.encrypt;
import com.yihu.hos.core.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("UTF-8"));
        return HexEncode.toHexString(messageDigest.digest());
    }
//    // 可逆的加密算法
//    public static String encrypt(String inStr) {
//        char[] a = inStr.toCharArray();
//        for (int i = 0; i < a.length; i++) {
//            a[i] = (char) (a[i] ^ 't');
//        }
//        String encryptStr = new String(a);
//        return encryptStr;
//    }
//    // 加密后解密
//    public static String decrypt(String inStr) {
//        char[] a = inStr.toCharArray();
//        for (int i = 0; i < a.length; i++) {
//            a[i] = (char) (a[i] ^ 't');
//        }
//        String decryptStr = new String(a);
//        return decryptStr;
//    }
    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;
            }
        });
    }
}

+ 123 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/encrypt/RSA.java

@ -0,0 +1,123 @@
package com.yihu.hos.core.encrypt;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.encode.Base64;
import com.yihu.hos.core.log.LoggerFactory;
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";
    private static Logger logger = LoggerFactory.getLogger(RSA.class);
    /**
     * 生成公钥和私钥
     *
     * @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 = Base64.decode(key);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(bytes);
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            return keyFactory.generatePrivate(pkcs8KeySpec);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
            logger.error(ex.getMessage());
        }
        return null;
    }
    public static Key genPublicKey(String key) {
        byte[] bytes = Base64.decode(key);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(bytes);
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            return keyFactory.generatePublic(x509KeySpec);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
            logger.error(ex.getMessage());
        }
        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)));
    }
    /**
     * 私钥加密
     *
     * @param data       明文
     * @param privateKey 私钥
     * @return 密文
     * @throws Exception
     */
    public static String encryptByPriKey(String data, String privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, genPrivateKey(privateKey));
        return Base64.encode(cipher.doFinal(data.getBytes()));
    }
}

+ 424 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/file/FileUtil.java

@ -0,0 +1,424 @@
package com.yihu.hos.core.file;
import com.yihu.hos.core.encode.Base64;
import org.springframework.web.multipart.MultipartFile;
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 writeFileDecode(String filePath, String data, String encoding) throws IOException {
        File file = new File(filePath);
//        if (file.exists()) {
//            return false;
//        }
        if (!file.getParentFile().exists()) {
            if (!file.getParentFile().mkdirs()) {
                return false;
            }
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, encoding);
        byte[] bytes = Base64.decode(data);
        byte[] bbuf = new byte[1024];
        InputStream fis = new ByteArrayInputStream(bytes);
        int hasRead = 0;
        while ((hasRead = fis.read(bbuf)) > 0) {
            //每读取一次,即写入文件输出流,读了多少,就写多少
            fileOutputStream.write(bbuf, 0, hasRead);
        }
        outputStreamWriter.flush();
        fileOutputStream.close();
        outputStreamWriter.close();
        return true;
    }
    /**
     * 将文件的String类型二进制流转成文件
     *
     * @param filePath
     * @param data
     * @param encoding
     * @return
     * @throws IOException
     */
    public static boolean writeFileByString(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);
        byte[] bytes = Base64.decode(data);
        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, 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;
    }
    /**
     * InputStream 转 byte[]
     *
     * @param input
     * @return
     * @throws IOException
     */
    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }
    /**
     * 通过文件途径,将文件转成byte[] 流
     *
     * @param filepath 文件路径
     * @return
     * @throws IOException
     */
    public static byte[] toByteArray(String filepath) throws IOException {
        File file = new File(filepath);
        InputStream input = new FileInputStream(file);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        byte[] bytes =output.toByteArray();
        input.close();
        output.close();
        return bytes;
    }
    /**
     * 通过文件途径,将文件转成String二进制流  流
     *
     * @param filepath 文件路径
     * @return
     * @throws IOException
     */
    public static String file2Base64String(String filepath) throws IOException {
        File file = new File(filepath);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return Base64.encode(buffer);
    }
    /**
     * file转string
     * @param fileName 文件名
     * @return string类型流
     */
    public static String convertFileToString(String fileName) {
        File file = new File(fileName);
        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 path 复制文件路径
     * @param toPath 文件路径
     */
    public static void copyAllFileByPath(String path, String toPath) throws IOException {
        File file = new File(path);
        File toFile = new File(toPath);
        byte[] b = new byte[(int) file.length()];
        if(file.isFile()){
            try {
                FileInputStream is= new FileInputStream(file);
                FileOutputStream ps= new FileOutputStream(toFile);
                is.read(b);
                ps.write(b);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(file.isDirectory()){
            if(!file.exists()) {
                file.mkdir();
            }
            if(!toFile.exists()) {
                toFile.mkdir();
            }
            String[] list = file.list();
            for(int i=0;i<list.length;i++){
                copyAllFileByPath(path + "/" + list[i], toPath + "/" + list[i]);
            }
        }
    }
    /**
     * 删除整个目录
     *
     * @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();
    }
    /**
     * InputStream转string
     * @param is 输入流
     * @return Base64编码 文件字节流
     */
    public static String streamToBase64String(InputStream is) {
        byte[] bytes= FileUtil.getBytesByStream(is);
        return Base64.encode(bytes);
    }
    public static  byte[] getBytesByStream(InputStream inputStream){
        byte[] buffer = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1024];
            int n;
            while ((n = inputStream.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }
    /**
     * 读取文本文件内容
     * @param file  文件路径
     * @return
     */
    public static String readFileText(File file) {
        return readFileText(file, "UTF-8");
    }
    public static String readFileText(File file, String charset) {
        StringBuilder stringBuilder = new StringBuilder();
        InputStream in = null;
        BufferedReader br = null;
        try {
            in = new FileInputStream(file);
            br = new BufferedReader(new InputStreamReader(in, charset));
            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();
    }
    /**
     * 读取文件内容
     * @param bytes
     * @return
     */
    public static String readFileText(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder();
        InputStream in = null;
        BufferedReader br = null;
        try {
            in = new ByteArrayInputStream(bytes);
            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 String readFileText(InputStream in) {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader br = null;
        try {
            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();
    }
    /**
     * 获取文件名后缀
     * @param file
     * @return
     */
    public static String getFileSuffix(File file) {
        String fileName = file.getName();
        int index = fileName.indexOf(".");
        return fileName.substring(index);
    }
    /**
     * 获取文件名后缀
     * @param file
     * @return
     */
    public static String getFileSuffix(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        int index = fileName.indexOf(".");
        return fileName.substring(index);
    }
    public static String getCharSet(String fileName) throws Exception {
        BufferedInputStream bin = new BufferedInputStream(new FileInputStream(fileName));
        int p = (bin.read() << 8) + bin.read();
        bin.close();
        String code = null;
        switch (p) {
            case 0xefbb:
                code = "UTF-8";
                break;
            case 0xfffe:
                code = "Unicode";
                break;
            case 0xfeff:
                code = "UTF-16BE";
                break;
            default:
                code = "GBK";
        }
        return code;
    }
}

+ 460 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/file/FtpFileUtil.java

@ -0,0 +1,460 @@
package com.yihu.hos.core.file;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import java.io.*;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * ftp 操作工具类
 * Created by HZY on 2015/8/12.
 */
public class FtpFileUtil {
    static final private Logger logger = LoggerFactory.getLogger(FtpFileUtil.class);
    private int port = 21;      // 端口号
    private String username;    //ftp  登录名
    private String password;    //ftp  登录密码
    private String ftpHostName; //ftp  主机名(IP)
    private FTPClient ftpClient = new FTPClient();
    private FileOutputStream fos = null;
    public FtpFileUtil(String username, String password, String ftpHostName, int port) {
        this.username = username;
        this.password = password;
        this.ftpHostName = ftpHostName;
        this.port = port;
    }
    /**
     * 建立ftp连接
     */
    public void connect() {
        try {
            // 连接
            ftpClient.connect(ftpHostName, port);
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
            }
            // 登录
            ftpClient.login(username, password);
            ftpClient.setBufferSize(1024 * 1024 * 1);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
//            ftpClient.setControlEncoding("GBK");
            ftpClient.setDefaultTimeout(60 * 1000);
            ftpClient.setConnectTimeout(60 * 1000);
            ftpClient.setDataTimeout(60 * 1000);
            ftpClient.setRemoteVerificationEnabled(false);
        } catch (SocketException e) {
            logger.error("连接Ftp服务器异常:", e);
        } catch (IOException e) {
            logger.error("连接Ftp服务器异常:", e);
        }
    }
    /**
     * 关闭输入输出流
     */
    public void closeConnect() {
        try {
            if (fos != null) {
                fos.close();
            }
            ftpClient.logout();
            ftpClient.disconnect();
        } catch (IOException e) {
            logger.error("关闭Ftp连接失败:", e);
        }
    }
    /**
     * 下载文件
     *
     * @param ftpFileName ftp文件路径
     * @param localDir    本地保存路径
     */
    public boolean down(String ftpFileName, String localDir) {
        connect();
        boolean flag = downFile(ftpFileName, localDir);
        closeConnect();
        return flag;
    }
    /**
     * 上传文件
     *
     * @param localDir    本地文件
     * @param ftpFileName ftp上传路径
     * @return 是否上传成功
     * @throws Exception
     */
    public boolean upload(String localDir, String ftpFileName) throws Exception {
        connect();
        boolean flag = uploadFile(localDir, ftpFileName);
        closeConnect();
        return flag;
    }
    /**
     * 下载单个ftp上文件
     *
     * @param ftpFileName ftp文件路径
     * @param localDir    本地保存路径
     * @return 是否下载成功
     */
    public boolean downFile(String ftpFileName, String localDir) {
        boolean success = false;
        try {
            File file = new File(ftpFileName);
            File temp = new File(localDir);
            if (!temp.exists()) {
                temp.mkdirs();
            }
            File localfile = new File(localDir + File.separator + file.getName());
            if (!localfile.exists()) {
                fos = new FileOutputStream(localfile);
                success = ftpClient.retrieveFile(ftpFileName, fos);
            }
            ftpClient.changeToParentDirectory();
        } catch (SocketException e) {
            logger.error("Ftp服务器连接失败!", e);
        } catch (IOException e) {
            logger.error("Ftp文件下载失败!", e);
        }
        return success;
    }
    /**
     * 写入文件至ftp
     *
     * @param local  写入到FTP服务器上的文件
     * @param remote FTP服务器保存目录
     * @return 是否上传成功
     * @throws Exception
     */
    public boolean uploadFile(String local, String remote) {
        boolean success = false;
        File localFile = new File(local);
        InputStream in = null;
        try {
            if (!localFile.exists()) {
                return success;
            } else {
                in = new BufferedInputStream(new FileInputStream(localFile));
            }
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return success;
            }
            createDir(remote);
            ftpClient.changeWorkingDirectory(remote);
            success = ftpClient.storeFile(localFile.getName(), in);
            in.close();
        } catch (IOException e) {
            logger.error("Ftp文件上传失败!", e);
        }
        return success;
    }
    /**
     * 判断是否是目录
     *
     * @param fileName ftp文件路径
     * @return true 是目录 false 不是
     */
    public boolean isDir(String fileName) {
        try {
            //切换目录,若当前是目录则返回true,否则返回false。
            return ftpClient.changeWorkingDirectory(fileName);
        } catch (Exception e) {
            logger.error("Ftp判断是否是目录失败!", e);
        }
        return false;
    }
    /**
     * 递归创建远程服务器目录
     *
     * @param remote 远程服务器文件绝对路径
     * @return 目录创建是否成功
     * @throws IOException
     */
    public boolean createDir(String remote) throws IOException {
        boolean success = true;
        String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
        // 如果远程目录不存在,则递归创建远程服务器目录
        if (!directory.equalsIgnoreCase("/")
                && !ftpClient.changeWorkingDirectory(new String(directory))) {
            int start = 0;
            int end = 0;
            if (directory.startsWith("/")) {
                start = 1;
            } else {
                start = 0;
            }
            end = directory.indexOf("/", start);
            while (true) {
                String subDirectory = new String(remote.substring(start, end));
                if (!ftpClient.changeWorkingDirectory(subDirectory)) {
                    if (ftpClient.makeDirectory(subDirectory)) {
                        ftpClient.changeWorkingDirectory(subDirectory);
                    } else {
                        logger.debug("创建Ftp目录失败");
                        return false;
                    }
                }
                start = end + 1;
                end = directory.indexOf("/", start);
                // 检查所有目录是否创建完毕
                if (end <= start) {
                    break;
                }
            }
        }
        return success;
    }
    /**
     * 删除文件-FTP方式
     *
     * @param path     FTP服务器上传地址
     * @param fileName FTP服务器上要删除的文件名
     * @return
     */
    public boolean deleteFile(String path, String fileName) {
        boolean success = false;
        try {
            ftpClient.changeWorkingDirectory(path);//转移到指定FTP服务器目录
            ftpClient.deleteFile(fileName);
            ftpClient.logout();
            success = true;
        } catch (Exception e) {
            logger.error("Ftp文件删除失败!", e);
        }
        return success;
    }
    /**
     * 上传文件夹或文件至ftp
     *
     * @param filename   要上传的文件
     * @param uploadpath ftp文件路径
     * @return
     * @throws Exception
     */
    public boolean uploadDir(String filename, String uploadpath) {
        boolean success = false;
        File file = new File(filename);
        try {
            // 要上传的是否存在
            if (!file.exists()) {
                return success;
            }
            // 要上传的是否是文件夹
            if (!file.isDirectory()) {
                return uploadFile(filename, uploadpath);
            }
            File[] flles = file.listFiles();
            if (flles != null) {
                for (File files : flles) {
                    if (files.exists()) {
                        if (files.isDirectory()) {
                            uploadDir(files.getAbsoluteFile().toString(),
                                    uploadpath);
                        } else {
                            String local = files.getCanonicalPath().replaceAll("\\\\", "/");
                            String remote = uploadpath + local.substring(local.indexOf("/") + 1, local.lastIndexOf("/") + 1);
                            ftpClient.changeWorkingDirectory("/");
                            uploadFile(local, remote);
                            ftpClient.changeWorkingDirectory("/");
                        }
                    }
                }
            }
        } catch (IOException e) {
            logger.error("Ftp文件上传失败!", e);
        }
        return true;
    }
    /**
     * 读取病人信息并封装成List<String>
     *
     * @param path 远程ftp文件路径
     * @return List<String>病人信息集合
     */
    public List<String> readFileData(String path) {
        connect();
        List<String> list = new ArrayList<>();
        InputStream inputStream = null;
        try {
            ftpClient.changeWorkingDirectory(path);
            String[] filenames = ftpClient.listNames();
            if (filenames != null && filenames.length > 0) {
                for (String filenanme : filenames) {
                    inputStream = ftpClient.retrieveFileStream(path + "/" + filenanme);
                    if (inputStream == null) {
                        logger.info("读取Ftp文件路径错误:" + (path + "/" + filenanme));
                        return list;
                    }//流为null,文件读取失败
                    String json = FileUtil.streamToBase64String(inputStream);
                    list.add(json);
                    inputStream.close();
                    ftpClient.completePendingCommand();
                }
            }
        } catch (SocketException e) {
            logger.error("Ftp服务器异常!", e);
        } catch (IOException e) {
            logger.error("Ftp文件读取失败!", e);
        } finally {
            closeConnect();
        }
        return list;
    }
    /**
     * 获取病人列表信息
     *
     * @param basePath 根目录下病人数据文件夹 eg:/home/test/patient/
     * @param agencyNo 机构编码
     * @return 病人信息map集合
     */
    public List<Map<String, String>> getPatientList(String basePath, String agencyNo) {
        connect();
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> map = null;
        String base = basePath + agencyNo;
        try {
            ftpClient.changeWorkingDirectory(base);//病人ID集合
            int reply = ftpClient.getReplyCode();
            if (FTPReply.isPositiveCompletion(reply)) {
                String[] patientnames = ftpClient.listNames();
                if (patientnames != null && patientnames.length > 0) {
                    for (String patientname : patientnames) {
                        String jsonPath = base + "/" + patientname;//json文件夹
                        ftpClient.changeWorkingDirectory(jsonPath);
                        String[] eventNames = ftpClient.listNames();//获取json文件遍历
                        for (String event : eventNames) {
                            map = new HashMap<>();
                            map.put("agency_code", agencyNo);
                            map.put("patient_id", patientname);
                            map.put("event_no", event);
                            list.add(map);
                        }
//                    ftpClient.changeWorkingDirectory("..");
                    }
                }
            } else {
                logger.debug("agency编码:" + agencyNo + " 对应的数据不存在,获取病人列表信息失败");
            }
        } catch (SocketException e) {
            logger.error("Ftp-服务器连接失败!", e);
        } catch (IOException e) {
            logger.error("Ftp-获取病人数据失败!", e);
        } finally {
            closeConnect();
        }
        return list;
    }
    /**
     * 清空文件夹中文件
     *
     * @param pathname ftp文件夹路径
     * @return
     */
    public boolean removeData(String pathname) {
        try {
            FTPFile[] files = ftpClient.listFiles(pathname);
            for (FTPFile f : files) {
                if (f.isDirectory()) {
                    removeData(pathname + "/" + f.getName());
                    ftpClient.removeDirectory(pathname);
                }
                if (f.isFile()) {
                    ftpClient.deleteFile(pathname + "/" + f.getName());
                }
            }
        } catch (IOException e) {
            logger.error("Ftp-清空文件夹失败!", e);
            return false;
        }
        return true;
    }
    /**
     * 下载ftp文件夹
     *
     * @param ftpFileName ftp文件或文件夹名
     * @param localDir    本地保存路径
     */
    private boolean downDir(String ftpFileName, String localDir) {
        boolean success = false;
        try {
            File file = new File(ftpFileName);
            File temp = new File(localDir);
            if (!temp.exists()) {
                temp.mkdirs();
            }
            // 判断是否是目录
            if (isDir(ftpFileName)) {
                String dirPath = localDir + "/" + ftpFileName;
                File dirFile = new File(dirPath);
                if (!dirFile.exists()) {
                    dirFile.mkdirs();
                }
                String[] names = ftpClient.listNames();
                for (int i = 0; i < names.length; i++) {
                    if (isDir(names[i])) {
                        downDir(ftpFileName + '/' + names[i], dirPath
                                + File.separator + names[i]);
                        ftpClient.changeToParentDirectory();
                    } else {
                        File localfile = new File(dirPath + File.separator
                                + names[i]);
                        if (!localfile.exists()) {
                            fos = new FileOutputStream(localfile);
                            ftpClient.retrieveFile(names[i], fos);
                        }
                    }
                }
            } else {
                File localfile = new File(localDir + File.separator + file.getName());
                if (!localfile.exists()) {
                    fos = new FileOutputStream(localfile);
                    success = ftpClient.retrieveFile(ftpFileName, fos);
                }
                ftpClient.changeToParentDirectory();
            }
        } catch (SocketException e) {
            logger.error("Ftp服务器连接异常!", e);
        } catch (IOException e) {
            logger.error("Ftp文件下载失败!", e);
        }
        return success;
    }
}

+ 15 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/http/AllowAllHostnameVerifier.java

@ -0,0 +1,15 @@
package com.yihu.hos.core.http;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
/**
 * @author Air
 * @version 1.0
 * @created 2015.07.02 15:48
 */
public class AllowAllHostnameVerifier implements HostnameVerifier {
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
}

+ 100 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/http/CustomTrustClientClientImpl.java

@ -0,0 +1,100 @@
package com.yihu.hos.core.http;
import okhttp3.OkHttpClient;
import javax.net.ssl.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collection;
/**
 * 用于非受信证书的HTTPS访问
 *
 * @created Airhead 2016/8/24.
 */
class CustomTrustClientClientImpl extends DefaultClientImpl {
    CustomTrustClientClientImpl() {
        try {
            final TrustManager[] trustManagers = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                        }
                        @Override
                        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                        }
                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[0];
                        }
                    }
            };
            final SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagers, new SecureRandom());
            SSLSocketFactory socketFactory = sslContext.getSocketFactory();
            OkHttpClient httpClient = new OkHttpClient.Builder()
                    .sslSocketFactory(socketFactory, (X509TrustManager) trustManagers[0])
                    .hostnameVerifier(new AllowAllHostnameVerifier()).build();
            setHttpClient(httpClient);
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
    }
    CustomTrustClientClientImpl(String path, String password) {
        try {
            InputStream inputStream = new FileInputStream(new File(path));
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(inputStream);
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            InputStream in = null;
            keyStore.load(in, password.toCharArray());
            int index = 0;
            for (Certificate certificate : certificates) {
                String certificateAlias = Integer.toString(index++);
                keyStore.setCertificateEntry(certificateAlias, certificate);
            }
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, password.toCharArray());
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(inputStream, password.toCharArray());
            trustManagerFactory.init(trustStore);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509KeyManager)) {
                throw new IllegalStateException("Unexpectd default trust managers:" + Arrays.toString(trustManagers));
            }
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustManagers, new SecureRandom());
            SSLSocketFactory socketFactory = sslContext.getSocketFactory();
            OkHttpClient httpClient = new OkHttpClient.Builder()
                    .sslSocketFactory(socketFactory, (X509TrustManager) trustManagers[0])
                    .hostnameVerifier(new AllowAllHostnameVerifier()).build();
            setHttpClient(httpClient);
        } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException | KeyManagementException | UnrecoverableKeyException e) {
            e.printStackTrace();
        }
    }
}

+ 336 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/http/DefaultClientImpl.java

@ -0,0 +1,336 @@
package com.yihu.hos.core.http;
import okhttp3.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
 * @author Airhead
 * @since 2016/8/24.
 */
class DefaultClientImpl implements HTTPClient {
    private static final Log log = LogFactory.getLog(DefaultClientImpl.class);
    private OkHttpClient httpClient;
    DefaultClientImpl() {
        this.httpClient = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS).build();
    }
    public HTTPResponse get(String url) {
        return get(url, null);
    }
    public HTTPResponse get(String url, Map<String, String> params) {
        return get(url, params, null);
    }
    public HTTPResponse get(String url, Map<String, String> params, Map<String, String> headers) {
        try {
            Request.Builder builder = new Request.Builder();
            if (headers != null) {
                builder.headers(Headers.of(headers));
            }
            Request request = builder
                    .url(formatURL(url, params))
                    .build();
            Response response = httpClient.newCall(request).execute();
            return new HTTPResponse(response.code(), response.body().string());
        } catch (IOException ex) {
            // ?? 怎么把异常处理了??  应该交由调用者处理
            ex.printStackTrace();
            log.error(ex.getMessage());
            return new HTTPResponse(417,ex.getMessage());
        }
    }
    public HTTPResponse post(String url) {
        return post(url, (Map<String, String>) null);
    }
    public HTTPResponse post(String url, Map<String, String> params) {
        return post(url, params, null);
    }
    public HTTPResponse post(String url, Map<String, String> params, Map<String, String> headers) {
        try {
            FormBody.Builder fromBodyBuilder = new FormBody.Builder();
            if (params != null) {
                params.forEach(fromBodyBuilder::add);
            }
            RequestBody requestBody = fromBodyBuilder
                    .build();
            Request.Builder builder = new Request.Builder();
            if (headers != null) {
                builder.headers(Headers.of(headers));
            }
            Request request = builder
                    .url(url)
                    .post(requestBody)
                    .build();
            Response response = httpClient.newCall(request).execute();
            return new HTTPResponse(response.code(), response.body().string());
        } catch (IOException ex) {
            //讲异常信息返回,交由调用者处理
            log.error(ex.getMessage());
            return new HTTPResponse(417,ex.getMessage());
        }
    }
    @Override
    public HTTPResponse post(String url, String json, Map<String, String> headers) {
        try {
            Request.Builder builder = new Request.Builder();
            if (headers != null) {
                builder.headers(Headers.of(headers));
            }
            final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(JSON, json);
            Request request = builder
                    .url(url)
                    .post(body)
                    .build();
            Response response = httpClient.newCall(request).execute();
            return new HTTPResponse(response.code(), response.body().string());
        } catch (IOException ex) {
            log.error(ex.getMessage());
            return new HTTPResponse(417, ex.getMessage());
        }
    }
    public HTTPResponse postFile(String url, String path) {
        return postFile(url, path, null);
    }
    public HTTPResponse postFile(String url, String path, Map<String, String> params) {
        return postFile(url, path, params, null);
    }
    public HTTPResponse postFile(String url, String path, Map<String, String> params, Map<String, String> headers) {
        try {
            File file = new File(path);
            final MediaType type = MediaType.parse("application/zip");
            Request.Builder requestBuilder = new Request.Builder();
            if (headers != null) {
                requestBuilder.headers(Headers.of(headers));
            }
            MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
            multipartBuilder.setType(MultipartBody.FORM)
                    .addFormDataPart("pack", file.getName(), RequestBody.create(type, file));
            for (String key : params.keySet()) {
                multipartBuilder.addFormDataPart(key, params.get(key));
            }
            Request request = requestBuilder
                    .url(url)
                    .post(multipartBuilder.build())
                    .build();
            Response response = httpClient.newCall(request).execute();
            return new HTTPResponse(response.code(), response.body().string());
        } catch (IOException ex) {
            log.error(ex.getMessage());
            return new HTTPResponse(417, ex.getMessage());
        }
    }
    @Override
    public HTTPResponse postFile(String url, String key, String path, String contentType) {
        try {
            File file = new File(path);
            final MediaType type = MediaType.parse(contentType);
            Request.Builder requestBuilder = new Request.Builder();
            MultipartBody.Builder multipartBuilder = new MultipartBody.Builder();
            multipartBuilder.setType(MultipartBody.FORM)
                    .addFormDataPart(key, file.getName(), RequestBody.create(type, file));
            Request request = requestBuilder
                    .url(url)
                    .post(multipartBuilder.build())
                    .build();
            Response response = httpClient.newCall(request).execute();
            return new HTTPResponse(response.code(), response.body().string());
        } catch (IOException ex) {
            log.error(ex.getMessage());
            return new HTTPResponse(417, ex.getMessage());
        }
    }
    public HTTPResponse put(String url) {
        return put(url, (Map<String, String>) null);
    }
    public HTTPResponse put(String url, Map<String, String> params) {
        return put(url, params, null);
    }
    @Override
    public HTTPResponse put(String url, String json) {
        try {
            final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder()
                    .url(url)
                    .put(body)
                    .build();
            Response response = httpClient.newCall(request).execute();
            return new HTTPResponse(response.code(), response.body().string());
        } catch (IOException ex) {
            ex.printStackTrace();
            log.error(ex.getMessage());
            return new HTTPResponse(417, ex.getMessage());
        }
    }
    public HTTPResponse put(String url, Map<String, String> params, Map<String, String> headers) {
        try {
            FormBody.Builder fromBodyBuilder = new FormBody.Builder();
            if (params != null) {
                params.forEach(fromBodyBuilder::add);
            }
            RequestBody requestBody = fromBodyBuilder
                    .build();
            Request.Builder builder = new Request.Builder();
            if (headers != null) {
                builder.headers(Headers.of(headers));
            }
            Request request = builder
                    .url(url)
                    .put(requestBody)
                    .build();
            Response response = httpClient.newCall(request).execute();
            return new HTTPResponse(response.code(), response.body().string());
        } catch (IOException ex) {
            log.error(ex.getMessage());
            return new HTTPResponse(417, ex.getMessage());
        }
    }
    public HTTPResponse delete(String url) {
        return delete(url, (Map<String, String>) null);
    }
    public HTTPResponse delete(String url, Map<String, String> params) {
        return delete(url, params, null);
    }
    @Override
    public HTTPResponse delete(String url, String json) {
        try {
            final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder()
                    .url(url)
                    .delete(body)
                    .build();
            Response response = httpClient.newCall(request).execute();
            return new HTTPResponse(response.code(), response.body().string());
        } catch (IOException ex) {
            log.error(ex.getMessage());
            return new HTTPResponse(417, ex.getMessage());
        }
    }
    public HTTPResponse delete(String url, Map<String, String> params, Map<String, String> headers) {
        try {
            FormBody.Builder fromBodyBuilder = new FormBody.Builder();
            if (params != null) {
                params.forEach(fromBodyBuilder::add);
            }
            RequestBody requestBody = fromBodyBuilder
                    .build();
            Request.Builder builder = new Request.Builder();
            if (headers != null) {
                builder.headers(Headers.of(headers));
            }
            Request request = builder
                    .url(url)
                    .delete(requestBody)
                    .build();
            Response response = httpClient.newCall(request).execute();
            return new HTTPResponse(response.code(), response.body().string());
        } catch (IOException ex) {
            log.error(ex.getMessage());
            return new HTTPResponse(417, ex.getMessage());
        }
    }
    public HTTPResponse request(String method, String url, Map<String, String> params, Map<String, String> headers) {
        if (method.equals(POST)) {
            return post(url, params, headers);
        }
        if (method.equals(GET)) {
            return get(url, params, headers);
        }
        if (method.equals(PUT)) {
            return put(url, params, headers);
        }
        if (method.equals(DELETE)) {
            return delete(url, params, headers);
        }
        return get(url, params, headers);
    }
    protected void setHttpClient(OkHttpClient okHttpClient) {
        this.httpClient = okHttpClient;
    }
    private String formatURL(String url, Map<String, String> params) {
        if (params == null) {
            return url;
        }
        final String[] query = {""};
        params.forEach((name, value) -> {
            try {
                query[0] += "&" + name + "=" + URLEncoder.encode(value, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("encode url ");
            }
        });
        if (url.contains("?")) {
            return url + query[0];
        }
        return url + "?" + query[0].substring(1);
    }
}

+ 54 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/http/HTTPClient.java

@ -0,0 +1,54 @@
package com.yihu.hos.core.http;
import java.util.Map;
/**
 * @created Airhead 2016/8/24.
 */
public interface HTTPClient {
    //主要的几种方法,其他的暂时未使用
    String GET = "GET";
    String POST = "POST";
    String PUT = "PUT";
    String DELETE = "DELETE";
    HTTPResponse get(String url);
    HTTPResponse get(String url, Map<String, String> params);
    HTTPResponse get(String url, Map<String, String> params, Map<String, String> headers);
    HTTPResponse post(String url);
    HTTPResponse post(String url, Map<String, String> params);
    HTTPResponse post(String url, Map<String, String> params, Map<String, String> headers);
    HTTPResponse post(String url, String json, Map<String, String> headers);
    HTTPResponse postFile(String url, String path);
    HTTPResponse postFile(String url, String path, Map<String, String> params);
    HTTPResponse postFile(String url, String path, Map<String, String> params, Map<String, String> headers);
    HTTPResponse postFile(String url, String key, String path, String contentType);
    HTTPResponse put(String url);
    HTTPResponse put(String url, Map<String, String> params);
    HTTPResponse put(String url, String json);
    HTTPResponse put(String url, Map<String, String> params, Map<String, String> headers);
    HTTPResponse delete(String url);
    HTTPResponse delete(String url, Map<String, String> params);
    HTTPResponse delete(String url, String json);
    HTTPResponse delete(String url, Map<String, String> params, Map<String, String> headers);
    HTTPResponse request(String method, String url, Map<String, String> params, Map<String, String> headers);
}

+ 23 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/http/HTTPResponse.java

@ -0,0 +1,23 @@
package com.yihu.hos.core.http;
/**
 * @created Airhead 2016/8/24.
 */
public class HTTPResponse {
    private final int statusCode;// e.g. 200
    private final String body;
    public HTTPResponse(int statusCode, String body) {
        this.statusCode = statusCode;
        this.body = body;
    }
    public int getStatusCode() {
        return statusCode;
    }
    public String getBody() {
        return body;
    }
}

+ 155 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/http/HttpClientKit.java

@ -0,0 +1,155 @@
package com.yihu.hos.core.http;
import javafx.util.Pair;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import java.util.HashMap;
import java.util.Map;
/**
 * @created Airhead 2016/8/24.
 */
public class HttpClientKit {
    private static Map<String, Pair<String, String>> keyStoreMap = new HashMap<>();
    private static Map<String, SSLConnectionSocketFactory> keyStoreSSLMap = new HashMap<>();
    /**
     * 用于HTTP和受信HTTPS
     *
     * @return
     */
    public static HTTPClient use() {
        return new DefaultClientImpl();
    }
    /**
     * 用于非受信HTTPS
     *
     * @param host host正常情况是不需要包含端口号的。
     *             但在非域名(或开发)时,不同的端口会使用不同证书,
     *             在添加host时,可以增加端口号
     *             格式:
     *             1.ip:port
     *             2.domain
     * @return
     */
    public static HTTPClient custom(String host) {
        if (host != null) {
            Pair<String, String> keyStore = keyStoreMap.get(host);
            if (keyStore != null) {
                return new CustomTrustClientClientImpl(keyStore.getKey(), keyStore.getValue());
            }
        }
        return new CustomTrustClientClientImpl();
    }
    public static void addKeyStore(String host, String file, String password) throws Exception {
        keyStoreMap.put(host, new Pair<>(file, password));
    }
    public static void addKeyStoreSSL(String host, SSLConnectionSocketFactory sslConnectionSocketFactory) throws Exception {
        keyStoreSSLMap.put(host, sslConnectionSocketFactory);
    }
    public static HTTPResponse get(String url) {
        return use().get(url);
    }
    public static HTTPResponse get(String url, Map<String, String> params) {
        return use().get(url, params);
    }
    public static HTTPResponse get(String url, Map<String, String> params, Map<String, String> headers) {
        return use().get(url, params, headers);
    }
    public static HTTPResponse post(String url) {
        return use().post(url);
    }
    public static HTTPResponse post(String url, Map<String, String> params) {
        return use().post(url, params);
    }
    public static HTTPResponse post(String url, String json) {
        return use().post(url, json, null);
    }
    public static HTTPResponse post(String url, String json, Map<String, String> headers) {
        return use().post(url, json, headers);
    }
    public static HTTPResponse post(String url, Map<String, String> params, Map<String, String> headers) {
        return use().post(url, params, headers);
    }
    public static HTTPResponse postFile(String url, String path) {
        return use().postFile(url, path);
    }
    public static HTTPResponse postFile(String url, String path, Map<String, String> params) {
        if (url.startsWith("https")) {
            return custom(url).postFile(url, path, params);
        } else {
            return use().postFile(url, path, params);
        }
    }
    public static HTTPResponse postFile(String url, String key, String path, String contentType) {
        if (url.startsWith("https")) {
            return custom(url).postFile(url, key, path, contentType);
        } else {
            return use().postFile(url, key, path, contentType);
        }
    }
    public static HTTPResponse postFile(String url, String path, Map<String, String> params, Map<String, String> headers) {
        if (url.startsWith("https")) {
            return custom(url).postFile(url, path, params, headers);
        } else {
            return use().postFile(url, path, params, headers);
        }
    }
    public static HTTPResponse put(String url) {
        return use().put(url);
    }
    public static HTTPResponse put(String url, Map<String, String> params) {
        return use().put(url, params);
    }
    public static HTTPResponse put(String url, String json) {
        return use().put(url, json);
    }
    public static HTTPResponse put(String url, Map<String, String> params, Map<String, String> headers) {
        return use().put(url, params, headers);
    }
    public static HTTPResponse delete(String url) {
        return use().delete(url);
    }
    public static HTTPResponse delete(String url, Map<String, String> params) {
        return use().delete(url, params);
    }
    public static HTTPResponse delete(String url, String json) {
        return use().delete(url, json);
    }
    public static HTTPResponse delete(String url, Map<String, String> params, Map<String, String> headers) {
        return use().delete(url, params, headers);
    }
    public static HTTPResponse request(String method, String url, Map<String, String> params, Map<String, String> headers) {
        if (url.startsWith("https")) {
            return custom(url).request(method, url, params, headers);
        } else {
            return use().request(method, url, params, headers);
        }
    }
}

+ 55 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/log/LogService.java

@ -0,0 +1,55 @@
package com.yihu.hos.core.log;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Configurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
/**
 * 日志服务类。目前使用的是 log4j2,即2.X版本的log4j,不能与其他版本混淆,因为它们的配置文件加载方式不一致.
 *
 * @apiNote 由于涉及到Spring框架的初始化, 它会先于log4j的初始化. 如果在log4j配置未初始化之前在Spring Bean内先生成
 * log4j对象, 可能会造成错误. 例如: Spring MVC 的Controller部分可能会缓存一个Logger对象,但此时log4j是未配置的, 所以会出现异常.
 * 正确的作法是Spring的Bean内不要缓存这个Logger对象,并在lo4j初始化后在运行时去获取Logger对象.
 *
 * @author Air
 * @author Sand
 * @version 1.0
 * @created 2015.06.18 16:59
 */
public class LogService {
    static{
        try {
            String configPath = LogService.class.getResource("/").getPath() + "log4j/log4j2.xml";
            ConfigurationSource source;
            source = new ConfigurationSource(new FileInputStream(configPath));
            Configurator.initialize(null, source);
        } catch (Exception ex) {
            // 此处不能再调用自身作为日志记录服务, 因为此时初始化失败了
            LogManager.getLogger(LogService.class).error(ex.getMessage());
        }
    }
    public static Logger getLogger(final Class<?> clazz){
        return LoggerFactory.getLogger(clazz);
    }
    public static Logger getLogger(final String name){
        return LoggerFactory.getLogger(name);
    }
    public static Logger getLogger(){
        StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
        if(stackTraceElements == null && stackTraceElements.length > 3){
            return LoggerFactory.getLogger(LogService.class);
        } else{
            return LoggerFactory.getLogger(stackTraceElements[2].getClassName());
        }
    }
}

+ 83 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/log/Logger.java

@ -0,0 +1,83 @@
/**
 * The MIT License (MIT)
 * Copyright (c) 2009-2015 HONG LEIMING
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.yihu.hos.core.log;
public abstract class Logger {  
	public void debug(String format, Object... args){
		debug(String.format(format, args));
	} 
	
	public void info(String format, Object... args){
		info(String.format(format, args));
	}
	
	public void warn(String format, Object... args){
		warn(String.format(format, args));
	}
	
	public void error(String format, Object... args){
		error(String.format(format, args));
	} 
	
	public void trace(String format, Object... args){
		trace(String.format(format, args));
	} 
	
	public abstract void debug(String message);
	
	public abstract void debug(String message, Throwable t); 
	
	public abstract void info(String message);
	
	public abstract void info(String message, Throwable t);
	
	public abstract void warn(String message);
	
	public abstract void warn(String message, Throwable t);
	
	public abstract void error(String message);
	
	public abstract void error(String message, Throwable t);
	
	public abstract void fatal(String message);
	
	public abstract void fatal(String message, Throwable t);
	
	public abstract void trace(String message);
	
	public abstract void trace(String message, Throwable t);
	
	public abstract boolean isDebugEnabled();
	public abstract boolean isInfoEnabled();
	public abstract boolean isWarnEnabled();
	public abstract boolean isErrorEnabled();
	
	public abstract boolean isFatalEnabled();
	
	public abstract boolean isTraceEnabled();
	
}

+ 66 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/log/LoggerFactory.java

@ -0,0 +1,66 @@
/**
 * The MIT License (MIT)
 * Copyright (c) 2009-2015 HONG LEIMING
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.yihu.hos.core.log;
public class LoggerFactory {
	public static interface InternalLoggerFactory {
		Logger getLogger(Class<?> clazz);
		Logger getLogger(String name);
	}
	
	private static InternalLoggerFactory factory;
	static {
		initDefaultFactory();
	}
	
	public static void setLoggerFactory(InternalLoggerFactory factory) {
		if (factory != null) {
			LoggerFactory.factory = factory;
		}
	}
	
	public static Logger getLogger(Class<?> clazz) {
		return factory.getLogger(clazz);
	}
	
	public static Logger getLogger(String name) {
		return factory.getLogger(name);
	}
	
	
	public static void initDefaultFactory() {
		if (factory != null){
			return ;
		}
		try {
			//try slf4j
			Class.forName("org.slf4j.Logger");
			String defaultFactory = String.format("%s.impl.Sl4jLoggerFactory", Logger.class.getPackage().getName());
			Class<?> factoryClass = Class.forName(defaultFactory);
			factory = (InternalLoggerFactory)factoryClass.newInstance();
		} catch (Exception ignored) {
		}
	} 
}

+ 151 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/log/impl/Sl4jLoggerFactory.java

@ -0,0 +1,151 @@
/**
 * The MIT License (MIT)
 * Copyright (c) 2009-2015 HONG LEIMING
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.yihu.hos.core.log.impl;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import org.slf4j.spi.LocationAwareLogger;
public class Sl4jLoggerFactory implements LoggerFactory.InternalLoggerFactory {
	
	public Logger getLogger(Class<?> clazz) {
		return new Sl4jLogger(clazz);
	}
	
	public Logger getLogger(String name) {
		return new Sl4jLogger(name);
	} 
}
class Sl4jLogger extends Logger { 
	private org.slf4j.Logger log; 
	private final String FQCN = Sl4jLogger.class.getName();
	
	Sl4jLogger(Class<?> clazz) { 
		log = org.slf4j.LoggerFactory.getLogger(clazz);
	}
	
	Sl4jLogger(String name) {
		log = org.slf4j.LoggerFactory.getLogger(name);
	}
	
	public void info(String message) { 
		info(message, (Throwable)null);
	}
	
	public void info(String message, Throwable t) {
		if (log instanceof LocationAwareLogger) {
	        ((LocationAwareLogger) log).log(null, FQCN,
	        		LocationAwareLogger.INFO_INT, message, null, t);
	    } else {
	        log.info(message, t);
	    } 
	}
	
	public void debug(String message) {
		debug(message, (Throwable)null);
	}
	
	public void debug(String message, Throwable t) {
		if (log instanceof LocationAwareLogger) {
	        ((LocationAwareLogger) log).log(null, FQCN,
	        		LocationAwareLogger.DEBUG_INT, message, null, t);
	    } else {
	        log.debug(message, t);
	    } 
	}
	
	public void warn(String message) {
		warn(message, (Throwable)null);
	}
	
	public void warn(String message, Throwable t) {
		if (log instanceof LocationAwareLogger) {
	        ((LocationAwareLogger) log).log(null, FQCN,
	        		LocationAwareLogger.WARN_INT, message, null, t);
	    } else {
	        log.warn(message);
	    } 
	}
	
	public void error(String message) {
		error(message, (Throwable)null);
	}
	
	public void error(String message, Throwable t) {
		if (log instanceof LocationAwareLogger) {
	        ((LocationAwareLogger) log).log(null, FQCN,
	        		LocationAwareLogger.ERROR_INT, message, null, t);
	    } else {
	        log.error(message);
	    } 
	}
	
	public void fatal(String message) {
		error(message);
	}
	
	public void fatal(String message, Throwable t) {
		error(message, t);
	}
	
	public boolean isDebugEnabled() {
		return log.isDebugEnabled();
	}
	
	public boolean isInfoEnabled() {
		return log.isInfoEnabled();
	}
	
	public boolean isWarnEnabled() {
		return log.isWarnEnabled();
	}
	
	public boolean isErrorEnabled() {
		return log.isErrorEnabled();
	}
	
	public boolean isFatalEnabled() {
		return log.isErrorEnabled();
	}
	@Override
	public void trace(String message) {
		trace(message, (Throwable)null);	}
	@Override
	public void trace(String message, Throwable t) {
		if (log instanceof LocationAwareLogger) {
	        ((LocationAwareLogger) log).log(null, FQCN,
	        		LocationAwareLogger.TRACE_INT, message, null, t);
	    } else {
	        log.error(message);
	    } 
	}
	@Override
	public boolean isTraceEnabled() { 
		return log.isTraceEnabled();
	}
}

+ 115 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/net/IPChoiceUtils.java

@ -0,0 +1,115 @@
package com.yihu.hos.core.net;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
/**
 * IP选择工具,用于在本机多个IP中,选择一个可用于内网访问的IP
 *
 * @author yinwenjie
 */
public class IPChoiceUtils {
    private static final Logger logger = LoggerFactory.getLogger(IPChoiceUtils.class);
    /**
     * 内网IP范围
     */
    private static final String LOCAL_IP_RANGES[] = new String[]{
            "10.0.0.0-10.255.255.255", "172.16.0.0-172.131.255.255", "192.168.0.0-192.168.255.255"
    };
    /**
     * A、B、C类IP范围,不包括广播IP,但是包括内网IP范围
     */
    private static final String REMOTE_IP_RANGES[] = new String[]{
            "1.0.0.1-126.255.255.254", "128.0.0.1-191.255.255.254", "192.0.0.1-223.255.255.254"
    };
    /**
     * 该方法用于在本机多个IP中,选择一个提供给ESB-Client进行访问的IP
     *
     * @return
     */
    public static String getSourceIP() {
        Enumeration<NetworkInterface> interfaces = null;
        try {
            interfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        // 首先拿到本机可用的IPV4地址。
        List<String> allIPs = new ArrayList<>();
        while (interfaces.hasMoreElements()) {
            NetworkInterface networkInterface = interfaces.nextElement();
            // 注意,一个网络设备可能绑定了多个IP,也可能一个IP都没有
            // 还有可能是IPV6的格式
            // 就算是IPV4的格式,也可能是loop形式的ip
            Enumeration<InetAddress> addressEnumeration = networkInterface.getInetAddresses();
            while (addressEnumeration.hasMoreElements()) {
                InetAddress inetAddress = addressEnumeration.nextElement();
                if (!(inetAddress instanceof Inet4Address)
                        || inetAddress.isLoopbackAddress()
                        || inetAddress.isMulticastAddress()) {
                    continue;
                }
                String ip = inetAddress.getHostAddress();
                allIPs.add(ip);
            }
        }
        Collections.reverse(allIPs); // 倒序排列
        // 开始从可用的IP中优先选择一个IP
        // 选择规则为:首先选择一个低位的内网IP。如果内网IP无效,则依次优先选择A类、B类、C类IP
        // 开发人员可以视自己的需求对选择规则进行更改
        for (String sourceIP : allIPs) {
            for (String localIPRange : LOCAL_IP_RANGES) {
                if (ipExistsInRange(sourceIP, localIPRange)) {
                    logger.info("======选择到IP:" + sourceIP);
                    return sourceIP;
                }
            }
        }
        return null;
    }
    /**
     * 判断给定的IP是否在一个范围内
     *
     * @param ip
     * @param ipSection
     * @return 如果是在一个范围内,则返回true;其它情况返回false
     */
    private static boolean ipExistsInRange(String ip, String ipSection) {
        String[] ipSections = ipSection.split("\\-");
        String beginIP = ipSections[0];
        String endIP = ipSections[1];
        return getIp2long(beginIP) <= getIp2long(ip) && getIp2long(ip) <= getIp2long(endIP);
    }
    /**
     * 这个私有方法将字符串形式的ip,转换为一个对应的长整型
     * 以便进行比较
     *
     * @param ip
     * @return
     */
    private static long getIp2long(String ip) {
        String[] ips = ip.split("\\.");
        long ip2long = 0L;
        for (int i = 0; i < 4; ++i) {
            ip2long = ip2long << 8 | Integer.parseInt(ips[i]);
        }
        return ip2long;
    }
}

+ 108 - 0
hos-web-framework/src/main/java/com.yihu.hos.core/token/TokenUtil.java

@ -0,0 +1,108 @@
package com.yihu.hos.core.token;
import com.yihu.hos.core.encrypt.DES;
import com.yihu.hos.core.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 = "ha_passw0rd";
    //随机数生成
    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 {
        //生成16位的随机数种子
        String seed  = getRandomNumberSeed(16);
        //MD5加密生成Token值
        String token = MD5.hash(seed);
        return token;
    }
    /**
     * 2. 生成授权码
     * 2-1 将createDate换算成秒数 + expiresIn = 失效的日期的秒数,
     * 2-2 秒数 + userId + appId进行组合DES加密。
     *
     * @throws Exception
     */
    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;
    }
    /**
     * 3. 校验请求的签名是否合法
     * token校验流程:
     * 1. 将token值进行解密分解
     * 2. 将三个参数字符串放入数组中,分解为userId,appId,expiredTime
     *
     * @param token
     * @return
     */
    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;
    }
}

+ 220 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/baseservice/BaseJpaService.java

@ -0,0 +1,220 @@
package com.yihu.hos.web.framework.baseservice;
import com.yihu.hos.web.framework.constant.PageArg;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import com.yihu.hos.web.framework.query.URLQueryParser;
import com.yihu.hos.web.framework.util.springutil.SpringBeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.EntityType;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
 * Service基础类。此类基于Spring Data JPA进行封装(Spring Data JPA又是基于JPA封装,EHR平台使用Hibernate作为JPA实现者)。
 * 需要注意的是,部分功能会跳过JPA接口而直接使用Hibernate接口,比如访问Hibernate的Session接口,因为它把JPA的EntityManager功能强大。
 *
 * @author lincl
 * @author Sand
 * @version 1.0
 * @created 2016.2.3
 */
@Transactional(propagation = Propagation.SUPPORTS)
public class BaseJpaService<T, R> extends SQLGeneralDAO{
    Class<R> repoClass;
    @PersistenceContext
    protected EntityManager entityManager;
    public BaseJpaService(){
        Type genType = getClass().getGenericSuperclass();
        if ((genType instanceof ParameterizedType)) {
            Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
            if (params.length==2) {
                repoClass = (Class) params[1];
            }
        }
    }
    public T save(T entity) {
        return (T) getRepository().save(entity);
    }
    public T retrieve(Serializable id) {
        return (T) getRepository().findOne(id);
    }
    public void delete(Serializable id) {
        getRepository().delete(id);
    }
    public void delete(T entity) {
        getRepository().delete(entity);
    }
    public void delete(Iterable ids) {
        Iterable list = getRepository().findAll(ids);
        getRepository().delete(list);
    }
    public Class<T> getEntityClass() {
        Type genType = this.getClass().getGenericSuperclass();
        Type[] parameters = ((ParameterizedType) genType).getActualTypeArguments();
        return (Class) parameters[0];
    }
    public List search(String fields, String filters, String sorts, Integer page, Integer size) throws ParseException {
        URLQueryParser queryParser = createQueryParser(fields, filters, sorts);
        CriteriaQuery query = queryParser.makeCriteriaQuery();
        if (page == null || page <= 0) page = PageArg.DefaultPage;
        if (size == null || size <= 0 || size > 10000) size = PageArg.DefaultSize;
        return entityManager
                .createQuery(query)
                .setFirstResult((page - 1) * size)
                .setMaxResults(size)
                .getResultList();
    }
    public List search(String filters) throws ParseException {
        URLQueryParser queryParser = createQueryParser("", filters, "");
        CriteriaQuery query = queryParser.makeCriteriaQuery();
        return entityManager
                .createQuery(query)
                .getResultList();
    }
    public List search(String filters,String sorts) throws ParseException {
        URLQueryParser queryParser = createQueryParser("", filters, sorts);
        CriteriaQuery query = queryParser.makeCriteriaQuery();
        return entityManager
                .createQuery(query)
                .getResultList();
    }
    public long getCount(String filters) throws ParseException {
        URLQueryParser queryParser = createQueryParser(filters);
        CriteriaQuery query = queryParser.makeCriteriaCountQuery();
        return (long) entityManager.createQuery(query).getSingleResult();
    }
    protected <T> URLQueryParser createQueryParser(String fields, String filters, String orders) {
        URLQueryParser queryParser = new URLQueryParser<T>(fields, filters, orders)
                .setEntityManager(entityManager)
                .setEntityClass(getEntityClass());
        return queryParser;
    }
    protected <T> URLQueryParser createQueryParser(String filters) {
        URLQueryParser queryParser = new URLQueryParser<T>(filters)
                .setEntityManager(entityManager)
                .setEntityClass(getEntityClass());
        return queryParser;
    }
    protected Sort parseSorts(String sorter){
        if (StringUtils.isNotEmpty(sorter)) {
            String[] orderArray = sorter.split(",");
            List<Sort.Order> orderList = new ArrayList<>(orderArray.length);
            Arrays.stream(orderArray).forEach(
                    elem -> orderList.add(
                            elem.startsWith("+") ? new Sort.Order(Sort.Direction.ASC, elem.substring(1)):
                                    new Sort.Order(Sort.Direction.DESC, elem.substring(1))));
            return new Sort(orderList);
        }
        return null;
    }
    protected Session currentSession() {
        return entityManager.unwrap(Session.class);
    }
    public PagingAndSortingRepository getRepository() {
        return (PagingAndSortingRepository) SpringBeanUtil.getService(repoClass);
    }
    public JpaRepository getJpaRepository(){
        return (JpaRepository) SpringBeanUtil.getService(repoClass);
    }
    public List<T> findByField(String field, Object value){
        return findByFields(
                new String[]{field},
                new Object[]{value}
        );
    }
    public List<T> findByFields(String[] fields, Object[] values){
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery query = criteriaBuilder.createQuery(getEntityClass());
        Root<T> root = query.from(getEntityClass());
        List<Predicate> ls = new ArrayList<>();
        for(int i=0; i< fields.length; i++){
            if(values[i].getClass().isArray())
                ls.add(criteriaBuilder.in(root.get(fields[i]).in((Object[])values[i])));
            else
                ls.add(criteriaBuilder.equal(root.get(fields[i]), values[i]));
        }
        query.where(ls.toArray(new Predicate[ls.size()]));
        return entityManager
                .createQuery(query)
                .getResultList() ;
    }
    public String getClzName(){
        return getEntityClass().getName();
    }
    public String getEntityIdFiled(){
        EntityType entityType = entityManager.getMetamodel().entity(getEntityClass());
        javax.persistence.metamodel.Type type = entityType.getIdType();
        String s = entityType.getId(type.getJavaType()).getName();
        return s;
    }
    public int delete(Object[] ids){
        String hql = " DELETE FROM "+getEntityClass().getName()+" WHERE "+getEntityIdFiled()+" in(:ids)";
        Query query = currentSession().createQuery(hql);
        query.setParameterList("ids", ids);
        return query.executeUpdate();
    }
    public void batchInsert(List list) {
        for (int i = 0; i < list.size(); i++) {
            entityManager.persist(list.get(i));
            if (i % 30 == 0) {
                entityManager.flush();
                entityManager.clear();
            }
        }
    }
}

+ 152 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/baseservice/BaseService.java

@ -0,0 +1,152 @@
package com.yihu.hos.web.framework.baseservice;
import com.yihu.hos.web.framework.dao.SQLGeneralDAO;
import com.yihu.hos.web.framework.query.URLHqlQueryParser;
import org.hibernate.Criteria;
import org.hibernate.FlushMode;
import org.hibernate.criterion.Projections;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.util.List;
public class BaseService<T> extends SQLGeneralDAO{
    /**
     * 查询列表(不分页)
     * @param filters
     * @return
     * @throws ParseException
     */
    public List search(String filters,String sorts) throws ParseException {
        return search(null,filters,sorts,null,null);
    }
    /**
     * 查询列表(不分页)
     * @param filters
     * @return
     * @throws ParseException
     */
    public List search(String filters) throws ParseException {
        return search(null,filters,null,null,null);
    }
    /**
     * 查询列表(不分页)
     * @param fields
     * @param filters
     * @param sorts
     * @return
     * @throws ParseException
     */
    public List search(String fields, String filters, String sorts) throws ParseException {
        return search(fields,filters,sorts,null,null);
    }
    /**
     * 查询列表(page,size都不为空,为分页查询)
     * @param fields
     * @param filters
     * @param sorts
     * @param page
     * @param size
     * @return
     * @throws ParseException
     */
    public List search(String fields, String filters, String sorts, Integer page, Integer size) throws ParseException {
        URLHqlQueryParser queryParser = createQueryParser(fields, filters, sorts);
        Criteria criteria = queryParser.makeCriteriaQuery();
        if(page!=null&&size!=null){
            criteria.setFirstResult((page - 1) * size).setMaxResults(size);
        }
        return criteria.list();
    }
    /**
     * 获取总条数
     * @param filters
     * @return
     * @throws ParseException
     */
    public long getCount(String filters) throws ParseException {
        URLHqlQueryParser queryParser = createQueryParser(null, filters, null);
        Criteria criteria = queryParser.makeCriteriaQuery();
        Criteria criteria1 = criteria.setProjection(Projections.rowCount());
        Long i = Long.parseLong(criteria1.uniqueResult().toString());
        return i;
    }
    private <T> URLHqlQueryParser createQueryParser(String fields, String filters, String orders) {
        if("\"\"".equals(fields)){
            fields=null;
        }
        if("\"\"".equals(filters)){
            filters="";
        }
        if("\"\"".equals(orders)){
            orders="";
        }
        URLHqlQueryParser queryParser = new URLHqlQueryParser<T>(fields, filters, orders)
                .setSession(getCurrentSession())
                .setEntityClass(getEntityClass());
        return queryParser;
    }
    public Class<T> getEntityClass() {
        Type genType = this.getClass().getGenericSuperclass();
        Type[] parameters = ((ParameterizedType) genType).getActualTypeArguments();
        return (Class) parameters[0];
    }
    public int delete(Object[] ids) {
        return delete(ids, getEntityClass());
    }
    public int delete(Object id) {
        Object[] obj;
        //判断是否是 List ,如果是list,则封装成obj数组在删除,
        if(id instanceof java.util.List){
            List idList =(List)id;
            obj = new Object[idList.size()];
            obj= idList.toArray();
        }else{
            obj = new Object[1];
            obj[0] = id;
        }
        return delete(obj, getEntityClass());
    }
    public int delete(Object[] ids, Class entity) {
        if(ids==null || ids.length==0)
            return 0;
        String hql =
                "DELETE FROM "+ entity.getSimpleName() +
                        " WHERE " + sessionFactory().getClassMetadata(entity).getIdentifierPropertyName() + " in(:ids) ";
        return currentSession().createQuery(hql)
                .setParameterList("ids", ids)
                .executeUpdate();
    }
    public T retrieve(Serializable id, Class entityClass) {
        return (T) currentSession().get(entityClass, id);
    }
    public T retrieve(Serializable id) {
        return (T) currentSession().get(getEntityClass(), id);
    }
    public List findAll(){
        return findAll(getEntityClass());
    }
    public List findAll(Class entityClass){
        currentSession().setFlushMode(FlushMode.MANUAL);
        return currentSession().createCriteria(entityClass).list();
    }
}

+ 14 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/ApiVersionPrefix.java

@ -0,0 +1,14 @@
package com.yihu.hos.web.framework.constant;
/**
 * API版本前缀。用于适配Rest控制器的版本。定义好适用的版本之后,可以方便API版本编写。
 *
 * API版本格式为:v大版本.小版本。
 *
 * @author Sand
 * @version 1.0
 * @created 2015.11.05 11:29
 */
public class ApiVersionPrefix {
    public static final String CommonVersion = "/rest/{api_version:^v[0-9]\\d*\\.\\d*$}";   // 通用
}

+ 13 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/ArchivesConstant.java

@ -0,0 +1,13 @@
package com.yihu.hos.web.framework.constant;
/**
 * @author HZY
 * @since 2017/06/23.
 */
public interface ArchivesConstant {
    String ACTIVE_MQ = "runtime.archive";   //active-mq消息,arbiter到broker的通讯
    String CAMEL_COMPONENT = "event.archive";  //camel组件命名
    String CAMEL_ENDPOINT = CAMEL_COMPONENT + ":queue:" + ACTIVE_MQ;   //camel的Endpoint
}

+ 31 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/BizObject.java

@ -0,0 +1,31 @@
package com.yihu.hos.web.framework.constant;
/**
 * 业务对象划分, 全局唯一ID会使用此划分. 因为 ObjectId 中仅使用一个short作为
 * ID的一部分, 因为枚举值会在 0 ~ 2^16 - 1之间.
 *
 * @author Sand
 * @version 1.0
 * @created 2015.06.19 14:38
 */
public enum BizObject {
    Geography((short)0x0001),
    Organization((short)0x0002),
    User((short)0x0003),
    Card((short)0x0004),
    JsonPackage((short)0x0005),
    StdArchive((short)0x0006),
    HealthEvent((short)0x0007),
    CdaType((short)18),
    STANDARD((short)9),
    ADAPTER((short)0x0008);
    public short getBizObject(){
        return bizObject;
    }
    private short bizObject;
    private BizObject(short bizObject){
        this.bizObject = bizObject;
    }
}

+ 31 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/ContextAttributes.java

@ -0,0 +1,31 @@
package com.yihu.hos.web.framework.constant;
/**
 * @created Airhead 2016/11/14.
 */
public interface ContextAttributes {
    String TENANT = "Tenant";//租户名称
    String SCHEMA = "schema";//schema数据库名称
    String SCHEMA_TEMP = "schema_temp";//schema副本,用于在租户库和中心库之前切换的中间件
    String TENANT_NAME = "tenant_name";//租户tenant名称
    String USER_INFO = "userInfo";
    String TENANT_SESSION = "tenantSession";//session缓存的的schema 和 tenant
    String GLOBAL_DB = "global_db";//平台管理中心库
    String BASE_DB = "base_db";//基础库,用于新增租户后的库复制
    String TABLE_NAME = "TABLE_NAME";//表名
    String SHELL_RESPONSE = "shell_repsonse.";
    //集成参数
    String ACCESSTOKEN = "accessToken";
    String CLIENTID = "clientId";
    String LOGIN_NAME = "loginName";
    //用户角色
    String ROLE_USER = "USER";
}

+ 86 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/DateConvert.java

@ -0,0 +1,86 @@
package com.yihu.hos.web.framework.constant;
import org.apache.commons.beanutils.Converter;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * Created by hzp on 2016/1/25.
 */
public class DateConvert implements Converter{
    public static String dateFormat ="yyyy-MM-dd HH:mm:ss";
    /**
     * 时间转化函数
     */
    public Object convert(Class arg0, Object arg1) {
        String str = (String)arg1;
        return toDate(str);
    }
    /*
        字符串转时间格式
     */
    public static Date toDate(String str)
    {
        if(str== null || str.trim().length()==0){
            return null;
        }
        try{
            String dateFormat ="yyyy-MM-dd HH:mm:ss";
            int l = str.length();
            if(l == 7)
            {
                dateFormat ="yyyy-MM";
            }
            else if(l == 10)
            {
                dateFormat ="yyyy-MM-dd";
            }
            else if(l == 13)
            {
                dateFormat ="yyyy-MM-dd HH";
            }
            else if(l == 16)
            {
                dateFormat ="yyyy-MM-dd HH:mm";
            }
            if(str.indexOf("/")>0)
            {
                str=str.replace("/","-");
            }
            SimpleDateFormat df = new SimpleDateFormat(dateFormat);
            return df.parse(str);
        }
        catch(Exception e){
            return null;
        }
    }
    /*
        时间格式转字符串
    */
    public static String toString(Date date)
    {
        return toString(date,"yyyy-MM-dd HH:mm:ss");
    }
    /*
        时间格式转字符串
    */
    public static String toString(Date date,String format)
    {
        if(date== null){
            return "";
        }
        try{
            SimpleDateFormat df = new SimpleDateFormat(format);
            return df.format(date);
        }
        catch (Exception ex)
        {
            return "";
        }
    }
}

+ 16 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/EndPointConstant.java

@ -0,0 +1,16 @@
package com.yihu.hos.web.framework.constant;
/**
 * @author Airhead
 * @since 2017/2/6.
 */
public interface EndPointConstant {
    String ZBUS_MQ = "endpoint";        //zbus消息,admin到arbiter上的通讯
    String ACTIVE_MQ = "runtime.endpoint";   //active-mq消息,arbiter到broker的通讯
    String CAMEL_COMPONENT = "event.endpoint";  //camel组件命名
    String CAMEL_ENDPOINT = CAMEL_COMPONENT + ":queue:" + ACTIVE_MQ;   //camel的Endpoint
    String ADD_ENDPOINT = "addEndpoint";
    String DELETE_ENDPOINT = "deleteEndpoint";
    String OFF_SERVER = "offServer";
}

+ 293 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/ErrorCode.java

@ -0,0 +1,293 @@
package com.yihu.hos.web.framework.constant;
/**
 * @author Sand
 * @version 1.0
 * @created 2015.08.10 17:49
 */
public enum ErrorCode {
    MissMethod("ehr.common.miss.method"),
    MissTimestamp("ehr.common.miss.timestamp"),
    MissAppKey("ehr.common.miss.appid"),
    MissVersion("ehr.common.miss.version"),
    MissSign("ehr.common.miss.sign"),
    MissSignMethod("ehr.common.miss.signMethod"),
    InvalidMethod("ehr.common.invalid.method"),
    InvalidTimestamp("ehr.common.invalid.timestamp"),
    InvalidAppId("ehr.common.invalid.appid"),
    InvalidApiVersion("ehr.common.invalid.version"),
    InvalidSign("ehr.common.invalid.sign"),
    InvalidSignMethod("ehr.common.invalid.signMethod"),
    InvalidParameterFormat("ehr.common.invalid.parameterFormat"),
    MissRequiredArgument("ehr.common.miss.required.argument"),
    MissParameter("ehr.common.miss.parameter"),
    InvalidParameter("ehr.common.invalid.parameter"),
    AppTokenExpired("ehr.common.appToken.expired"),
    QueryNoData("ehr.common.query.null"),
    QueryTotalCount("ehr.common.query.count"),
    SuccessSave("ehr.common.success.update"),
    InvalidUpdate("ehr.common.invalid.update"),
    RepeatCode("ehr.commons.repeat.code"),
    NotFoundObj("ehr.common.query.not.found"),
    SuccessAdd("ehr.common.success.create"),
    SuccessDelete("ehr.common.success.delete"),
    InvalidDelete("ehr.common.invalid.delete"),
    InputRequestSingle("ehr.common.input.request.single"),
    InputRequestMultiple("ehr.common.input.request.multiple"),
    InvalidUser("ehr.invalid.user"),
    GetUserSecurityFailed("ehr.get.user.security.failed"),
    InvalidUserNameOrPwd("ehr.invalid.username.or.pwd"),
    InvalidValidateCode("ehr.login.validatecode.invalid"),
    ExpireValidateCode("ehr.login.validatecode.expire"),
    MailHasValidate("ehr.login.mail.hasinvaild"),
    InvalidMail("ehr.login.mail.invaild"),
    ExistUserForCreate("ehr.user.exist.create"),
    SuccessPublicKeyCreate("ehr.publicKey.success.create"),
    ExistOrgForCreate("ehr.org.exist.create"),
    ExistOrgForStandard("ehr.org.exist.standard"),
    InvalidAppRegister("ehr.app.register.invalid"),
    MissIdentityNo("ehr.patient.miss.identity.no"),
    InvalidIdentityNo("ehr.patient.invalid.identity.no"),
    PatientRegisterFailed("ehr.patient.register.failed"),
    InvalidFormatPatientRegister("ehr.patient.invalid.register.info"),
    PatientRegisterFailedForExist("ehr.patient.exist.create"),
    MissArchiveFile("ehr.archive.miss.file"),
    MissArchiveCrypto("ehr.archive.miss.cryptograph"),
    ParseArchiveCryptoFailed("ehr.archive.parse.cryptograph.failed"),
    SaveArchiveFailed("ehr.archive.save.failed"),
    RepeatSysDictName("ehr.sysDict.name.repeat"),
    RepeatOrgDict("ehr.orgDict.repeat"),
    RepeatOrgDictItem("ehr.orgDictItem.repeat"),
    RepeatOrgDataSet("ehr.orgDataSet.repeat"),
    RepeatOrgMetaData("ehr.orgMetaData.repeat"),
    InvalidCreateSysDict("ehr.sysDict.create.invalid"),
    NotExistSysDict("ehr.sysDict.exist.invalid"),
    InvalidDelSysDict("ehr.sysDict.del.invalid "),
    InvalidUpdateSysDict("ehr.sysDict.update.invalid"),
    RepeatSysDictEntryName("ehr.sysDictEntry.name.repeat"),
    InvalidCreateSysDictEntry("ehr.sysDictEntry.create.invalid"),
    InvalidSysDictEntry("ehr.sysDictEntry.name.invalid"),
    InvalidDelSysDictEntry("ehr.sysDictEntry.del.invalid"),
    InvalidUpdateSysDictEntry("ehr.sysDictEntry.update.invalid"),
    ParamError("ehr.std.param.error"),
    InvalidStdVersion("ehr.std.invalid.version"),
    GenerateArchiveFailed("ehr.std.generate.schema.file.failed"),
    GenerateArchiveFileStreamFailed("ehr.std.file.stream.generate.failed"),
    DownArchiveFileFailed("ehr.std.file.down.failed"),
    GenerateFileCryptographStreamFailed("ehr.std.file.cryptograph.generate.failed"),
    GenerateFileCryptographFailed("ehr.std.file.cryptograph.generate.failed"),
    GetStdVersionFailed("ehr.std.get.version.fail"),
    UnknownStdVersion("ehr.std.version.unknown"),
    GetCDAVersionListFailed("ehr.cda.version.list.get.failed"),
    GetCDAVersionFailed("ehr.cda.version.get.failed"),
    SaveCDAVersionFailed("ehr.cda.version.save.failed"),
    GetCDAInfoFailed("ehr.std.get.CDA.list.failed"),
    InValidCDAVersionStage("ehr.std.version.invalid.stage"),
    StdVersionHasPublished("ehr.cda.version.published"),
    GetSchemeVersionListFailed("ehr.scheme.version.list.get.failed"),
    GetSchemeVersionFailed("ehr.scheme.version.get.failed"),
    SaveSchemeVersionFailed("ehr.scheme.version.save.failed"),
    UpdateSchemeVersionFailed("ehr.scheme.version.update.failed"),
    DeleteSchemeVersionFailed("ehr.scheme.version.delete.failed"),
    ExistSchemeVersionName("ehr.scheme.version.name.exist"),
    GetSchemeListFailed("ehr.schemeList.Get.failed"),
    GetSchemeFailed("ehr.scheme.Get.failed"),
    SaveSchemeFailed("ehr.scheme.Save.failed"),
    UpdateSchemeFailed("ehr.scheme.update.failed"),
    DeleteSchemeFailed("ehr.scheme.delete.failed"),
    ExistSchemeVersion("ehr.scheme.version.exist"),
    ExistSchemeName("ehr.scheme.name.exist"),
    GetSchemeDispatchListFailed("ehr.schemeDispatchList.Get.failed"),
    GetSchemeDispatchFailed("ehr.schemeDispatch.Get.failed"),
    SaveSchemeDispatchFailed("ehr.schemeDispatch.Save.failed"),
    UpdateSchemeDispatchFailed("ehr.schemeDispatch.update.failed"),
    DeleteSchemeDispatchFailed("ehr.schemeDispatch.delete.failed"),
    StandardGetListFailed("ehr.standard.getlist.failed"),
    StandardSaveFailed("ehr.standard.save.failed"),
    StandardDeleteFailed("ehr.standard.delete.failed"),
    StandardDeletePublished("ehr.standard.delete.published"),
    StandardUpdateFailed("ehr.standard.update.failed"),
    StandardGetFailed("ehr.standard.get.failed"),
    StandardForkFailed("ehr.standard.fork.failed"),
    StandardImportFailed("ehr.standard.import.failed"),
    StandardExportFailed("ehr.standard.export.failed"),
    ExistStandardCode("ehr.standard.code.exist"),
    ExistStandardName("ehr.standard.name.exist"),
    ExistStandardVersion("ehr.standard.version.exist"),
    StandardVersionGetListFailed("ehr.standard.version.getlist.failed"),
    StandardVersionSaveFailed("ehr.standard.version.save.failed"),
    StandardVersionDeleteFailed("ehr.standard.version.delete.failed"),
    StandardVersionDeletePublished("ehr.standard.version.delete.published"),
    StandardVersionUpdateFailed("ehr.standard.version.update.failed"),
    StandardVersionGetFailed("ehr.standard.version.get.failed"),
    StandardVersionForkFailed("ehr.standard.version.fork.failed"),
    StandardVersionPublishFailed("ehr.standard.version.publish.failed"),
    ExistStandardVersionName("ehr.standard.version.name.exist"),
    StandardVersionUsedDeleteFailed("ehr.standard.version.used.delete.failed"),
    StandardCDACatalogGetListFailed("ehr.standard.cda.catalog.getlist.failed"),
    StandardCDACatalogSaveFailed("ehr.standard.cda.catalog.save.failed"),
    StandardCDACatalogDeleteFailed("ehr.standard.cda.catalog.delete.failed"),
    StandardCDACatalogUpdateFailed("ehr.standard.cda.catalog.update.failed"),
    StandardCDACatalogGetFailed("ehr.standard.cda.catalog.get.failed"),
    StandardCDADatasetMissVersion("ehr.standard.cda.dataset.miss.verison"),
    StandardCDADatasetMissID("ehr.standard.cda.dataset.miss.id"),
    StandardCDADatasetGetListFailed("ehr.standard.cda.dataset.getlist.failed"),
    StandardCDADatasetSaveFailed("ehr.standard.cda.dataset.save.failed"),
    StandardCDADatasetDeleteFailed("ehr.standard.cda.dataset.delete.failed"),
    StandardCDADatasetUpdateFailed("ehr.standard.cda.dataset.update.failed"),
    StandardCDADatasetGetFailed("ehr.standard.cda.dataset.get.failed"),
    StandardCDAMissVersion("ehr.standard.cda.miss.verison"),
    StandardCDAMissID("ehr.standard.cda.miss.id"),
    StandardCDAGetListFailed("ehr.standard.cda.getlist.failed"),
    StandardCDASaveFailed("ehr.standard.cda.save.failed"),
    StandardCDADeleteFailed("ehr.standard.cda.delete.failed"),
    StandardCDAUpdateFailed("ehr.standard.cda.update.failed"),
    StandardCDAGetFailed("ehr.standard.cda.get.failed"),
    StandardDatasetCatalogMissID("ehr.standard.dataset.catalog.miss.id"),
    StandardDatasetCatalogGetListFailed("ehr.standard.dataset.catalog.getlist.failed"),
    StandardDatasetCatalogSaveFailed("ehr.standard.dataset.catalog.save.failed"),
    StandardDatasetCatalogDeleteFailed("ehr.standard.dataset.catalog.delete.failed"),
    StandardDatasetCatalogUpdateFailed("ehr.standard.dataset.catalog.update.failed"),
    StandardDatasetCatalogGetFailed("ehr.standard.dataset.catalog.get.failed"),
    StandardDatasetMissVersion("ehr.standard.dataset.miss.version"),
    StandardDatasetMissID("ehr.standard.dataset.miss.id"),
    StandardDatasetGetListFailed("ehr.standard.dataset.getlist.failed"),
    StandardDatasetSaveFailed("ehr.standard.dataset.save.failed"),
    StandardDatasetDeleteFailed("ehr.standard.dataset.delete.failed"),
    StandardDatasetUpdateFailed("ehr.standard.dataset.update.failed"),
    StandardDatasetGetFailed("ehr.standard.dataset.get.failed"),
    ExistStandardDatasetCode("ehr.standard.dataset.code.exist"),
    StandardMetaDataMissVersion("ehr.standard.metadatamiss.version"),
    StandardMetaDataMissID("ehr.standard.metadatamiss.id"),
    StandardMetaDataGetListFailed("ehr.standard.metadatagetlist.failed"),
    StandardMetaDataSaveFailed("ehr.standard.metadatasave.failed"),
    StandardMetaDataDeleteFailed("ehr.standard.metadatadelete.failed"),
    StandardMetaDataUpdateFailed("ehr.standard.metadataupdate.failed"),
    StandardMetaDataGetFailed("ehr.standard.metadataget.failed"),
    ExistStandardMetaDataCode("ehr.standard.metaData.code.exist"),
    StandardDictMissVersion("ehr.standard.dict.miss.version"),
    StandardDictMissID("ehr.standard.dict.miss.id"),
    StandardDictGetListFailed("ehr.standard.dict.getlist.failed"),
    StandardDictSaveFailed("ehr.standard.dict.save.failed"),
    StandardDictDeleteFailed("ehr.standard.dict.delete.failed"),
    StandardDictUpdateFailed("ehr.standard.dict.update.failed"),
    StandardDictGetFailed("ehr.standard.dict.get.failed"),
    ExistStandardDictCode("ehr.standard.dict.code.exist"),
    StandardDictEntryMissVersion("ehr.standard.dict.entry.miss.version"),
    StandardDictEntryMissID("ehr.standard.dict.entry.miss.id"),
    StandardDictEntryGetListFailed("ehr.standard.dict.entry.getlist.failed"),
    StandardDictEntrySaveFailed("ehr.standard.dict.entry.save.failed"),
    StandardDictEntryDeleteFailed("ehr.standard.dict.entry.delete.failed"),
    StandardDictEntryUpdateFailed("ehr.standard.dict.entry.update.failed"),
    StandardDictEntryGetFailed("ehr.standard.dict.entry.get.failed"),
    ExistStandardDictEntryCode("ehr.standard.dict.entry.code.exist"),
    GetDataSetListFailed("ehr.datasetlist.Get.failed"),
    GetDataSetFailed("ehr.dataset.Get.failed"),
    SavedatasetFailed("ehr.dataset.Save.failed"),
    UpdateDatasetFailed("ehr.dataset.update.failed"),
    DeleteDataSetFailed("ehr.dataset.delete.failed"),
    GetDataSetRelationListFailed("ehr.datasetRelationlist.Get.failed"),
    GetDataSetRelationFailed("ehr.datasetRelation.Get.failed"),
    SaveDatasetRelationFailed("ehr.datasetRelation.Save.failed"),
    UpdateatasetRelationFailed("ehr.datasetRelation.update.failed"),
    DeleteDataSetRelationFailed("ehr.datasetRelation.delete.failed"),
    GetMetaDataListFaield("ehr.metadatalist.Get.failed"),
    GetMetaDataFailed("ehr.metadata.Get.failed"),
    SaveMetaDataFailed("ehr.metadata.save.failed"),
    UpdateMetaDataFailed("ehr.metadata.update.failed"),
    DeleteMetaDataFailed("ehr.metadata.delete.failed"),
    GetDictListFaild("ehr.dictlist.Get.failed"),
    GetDictFaild("ehr.dict.Get.failed"),
    GetDictEntryListFailed("ehr.dict.entries.get.failed"),
    GetDictEntryFailed("ehr.dict.entry.get.failed"),
    SaveDictFailed("ehr.dict.Save.failed"),
    UpdateDictFailed("ehr.dict.update.failed"),
    DeleteDictFailed("ehr.dict.delete.failed"),
    saveDictEntryFailed("ehr.dict.entry.save.failed"),
    UpdateDictEntryFailed("ehr.dict.entry.update.failed"),
    DeleteDictEntryFailed("ehr.dict.entry.delete.failed"),
    GetPublisherListFaield("ehr.publisherList.get.failed"),
    GetPublisherFailed("ehr.publisher.get.failed"),
    SavePublisherFailed("ehr.publisher.save.failed"),
    UpdatePublisherFailed("ehr.publisher.update.failed"),
    DeletePublisherFailed("ehr.publisher.delete.failed"),
    GetStandardSourceFailed("ehr.std.get.source.list.failed"),
    GenerateUserKeyFailed("ehr.security.generate.user.key.failed"),
    GetUserKeyFailed("ehr.security.get.user.key.failed"),
    UserAccessTokenExpired("ehr.security.token.expired"),
    UserRefreshTokenError("ehr.security.token.refreshError"),
    UserRevokeTokenFailed("ehr.security.token.revoke"),
    CodeIsNull("ehr.system.code.null"),
    NameIsNull("ehr.system.name.null"),
    VersionCodeIsNull("ehr.system.versioncode.null"),
    GetEhrArchiveFailed("ehr.ehr.get.archive"),
    GetEhrDataSetFailed("ehr.ehr.get.data.set"),
    CreateEhrDataSetTableFailed("ehr.ehr.create.data.set.table.failed"),
    TruncateTableFailed("ehr.hbase.truncate.table.failed"),
    GetTableFailed("ehr.hbase.get.table.failed"),
    ClearSolrDataFailed("ehr.clear.solr.data.failed"),
    //
    UnknownJsonPackageId("ehr.json.package.unknown"),
    // Quartz Scheduler
    SchedulerStartFailed("ehr.scheduler.start.failed"),
    SchedulerShutdownFailed("ehr.scheduler.shutdown.failed"),
    SchedulerAddJobFailed("ehr.scheduler.add.job"),
    SchedulerRemoveJobFailed("ehr.scheduler.remove.job"),
    GetJobDetailFailed("ehr.scheduler.get.job.failed"),
    GetTriggerFailed("ehr.scheduler.get.trigger.failed"),
    //Other
    SystemError("ehr.system.error");
    private final String errorCode;
    private ErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }
    public String getErrorCode() {
        return errorCode;
    }
}

+ 46 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/ErrorType.java

@ -0,0 +1,46 @@
package com.yihu.hos.web.framework.constant;
import com.fasterxml.jackson.annotation.JsonValue;
/**
 * @Author: zhengwei
 * @Date: 2018/5/25 18:01
 * @Description:质控错误类型
 */
public enum ErrorType {
        Normal(0, "验证正常"),
        EmptyError(1, "字段值为空"),
        ValueError(2, "值域超出"),
        TypeError(3, "类型错误"),
        FormatError(4, "格式错误"),
        FieldAdaptationError(5, "资源适配错误"),
        DictAdaptationError(6, "字典适配错误"),
        ExceptionError(7, "转换异常错误");
        private String name;
        private int type;
        ErrorType(int type, String name){
            this.type = type;
            this.name = name;
        }
        @JsonValue
        public int getType(){
            return type;
        }
        @JsonValue
        public String getName(){
            return name;
        }
        public static ErrorType create(String ordinal){
            return create(Integer.parseInt(ordinal));
        }
        public static ErrorType create(int ordinal){
            return ErrorType.values()[ordinal];
        }
}

+ 31 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/EventType.java

@ -0,0 +1,31 @@
package com.yihu.hos.web.framework.constant;
import com.fasterxml.jackson.annotation.JsonValue;
/**
 * 0门诊 1住院 2体检
 */
public enum EventType {
    Clinic(0),              // 门诊
    Resident(1),            // 住院
    MedicalExam(2);         // 体检
    int type;
    EventType(int type){
        this.type = type;
    }
    @JsonValue
    public int getType(){
        return type;
    }
    public static EventType create(String ordinal){
        return create(Integer.parseInt(ordinal));
    }
    public static EventType create(int ordinal){
        return EventType.values()[ordinal];
    }
}

+ 23 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/JobType.java

@ -0,0 +1,23 @@
package com.yihu.hos.web.framework.constant;
/**
 * @author Sand
 * @version 1.0
 * @created 2015.09.22 11:54
 */
public enum JobType {
    EhrArchiver("EhrArchiver"),
    EhrIndexer("EhrIndexer");
    //
    private String jobType;
    JobType(String jobType){
        this.jobType = jobType;
    }
    public String toString(){
        return jobType;
    }
}

+ 25 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/MycatConstant.java

@ -0,0 +1,25 @@
package com.yihu.hos.web.framework.constant;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/1/24.
 */
public interface MycatConstant {
    String ZBUS_MQ = "mycat"; //zbus消息,admin到arbiter上的通讯
    String ACTIVE_MQ = "operation.mycat";   //active-mq消息,arbiter到broker的通讯
    String CAMEL_COMPONENT = "event.mycat";  //camel组件命名
    String CAMEL_ENDPOINT = CAMEL_COMPONENT + ":queue:" + ACTIVE_MQ;   //camel的Endpoint
    //Arbiter mycat 操作事件
    String EXECUTE_MYCAT = "execute_mycat"; //shell 命令执行消息
    //arbiter mycat修改 消息队列
    String DATA_NODE = "dn_";   // mycat dataNode前缀
    String DATA_BASE = "db_";   // mycat database前缀
}

+ 14 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/PageArg.java

@ -0,0 +1,14 @@
package com.yihu.hos.web.framework.constant;
/**
 * @author Sand
 * @version 1.0
 * @created 2016.02.14 17:47
 */
public class PageArg {
    public static final Integer DefaultPage = 1;
    public static final Integer DefaultSize = 30;
    public static final String DefaultPageS = "1";
    public static final String DefaultSizeS = "30";
}

+ 14 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/QcResultConstant.java

@ -0,0 +1,14 @@
package com.yihu.hos.web.framework.constant;
/**
 *  质控-规则检验-常量类
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/5/16.
 */
public interface QcResultConstant {
    String VALUE_EMPTY = "empty";//空
    String VALUE_ILLEGAL = "illegal";//非法
    String VALUE_ERROR = "error";//错误
}

+ 26 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/SSHConstant.java

@ -0,0 +1,26 @@
package com.yihu.hos.web.framework.constant;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2017/1/24.
 */
public interface SSHConstant {
    String ZBUS_MQ = "shell"; //zbus消息,admin到arbiter上的通讯
    String ACTIVE_MQ = "operation.shell";   //active-mq消息,arbiter到broker的通讯
    String CAMEL_COMPONENT = "event.shell";  //camel组件命名
    String CAMEL_ENDPOINT = CAMEL_COMPONENT + ":queue:" + ACTIVE_MQ;   //camel的Endpoint
    //Arbiter shell
    String ARBITER_SHELL_SEND = "arbiterShellSend"; //shell 命令执行消息
    //arbiter 发送shell命令 消息队列
    String SHELL_REQUEST = "shell_request";
    // hos-admin 接收shell执行结果
    String SHELL_RESPONSE = "shell_response";
}

+ 41 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/ServiceFlowConstant.java

@ -0,0 +1,41 @@
package com.yihu.hos.web.framework.constant;
/**
 * @author Airhead
 * @since 2016/12/6.
 */
public interface ServiceFlowConstant {
    String ZBUS_MQ = "serviceFlow"; //zbus消息,admin到arbiter上的通讯
    String ACTIVE_MQ = "runtime.serviceFlow";   //active-mq消息,arbiter到broker的通讯
    String CAMEL_COMPONENT = "event.serviceFlow";  //camel组件命名
    String CAMEL_ENDPOINT = CAMEL_COMPONENT + ":queue:" + ACTIVE_MQ;   //camel的Endpoint
    
    //流程-模板类型
    String JAVA = "java";
    String CLASS = "class";
    String JAVA_FILE = ".java";
    String CLASS_FILE = ".class";
    //流程-路由类型
    String FLOW_TYPE_ROUTE = "route";
    String FLOW_TYPE_PROCESSOR = "processor";
    //流程-路由类型
    String FLOW_OP_UPDATE = "update";
    String FLOW_OP_DELETE = "delete";
    String FLOW_OP_ADD = "add";
    //流程-操作消息
    String SERVICE_FLOW_STARTED = "serviceFlowStarted"; //启动服务流程
    String SERVICE_FLOW_STOPPED = "serviceFlowStopped"; //停止服务流程
    String SERVICE_FLOW_ADDED = "serviceFlowAdded"; //添加服务流程
    String SERVICE_FLOW_MODIFIED_ADD = "serviceFlowModifiedAdd";    //修改服务流程,修改或增加Router,Processor
    String SERVICE_FLOW_MODIFIED_REDUCE = "serviceFlowModifiedReduce";//修改服务流程,删除Router,Processor
    String SERVICE_FLOW_DELETED = "serviceFlowModifiedDelete";  //删除服务流程
    //BrokerServer
    String BROKER_SERVER_ON = "brokerServerOn"; //Broker启动
    String BROKER_SERVER_OFF = "brokerServerOff";//Broker停止
}

+ 12 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/SessionAttributeKeys.java

@ -0,0 +1,12 @@
package com.yihu.hos.web.framework.constant;
/**
 * Spring MVC 的Web会话常用会话属性常量。
 *
 * @author Sand
 * @version 1.0
 * @created 2015.11.07 16:29
 */
public class SessionAttributeKeys {
    public final static String CurrentUser = "current_user";
}

+ 88 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/SqlConstants.java

@ -0,0 +1,88 @@
package com.yihu.hos.web.framework.constant;
/**
 * Created by lingfeng on 2015/6/23.
 */
public class SqlConstants {
    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 DROP_TABLE = " DROP 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 COUNT = " COUNT(*) ";
    public static final String ASTERISK = "*";
    public static final String IN = " IN ";
    public static final String BETWEEN = " BETWEEN ";
    public static final String BEGIN = "begin";
    public static final String END = "end";
    public static final String LIKE = " LIKE ";
    public static final String OR = " OR ";
    public static final String EQUAL_MARK = " = ";
    public static final String NE_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 BLANK = " ";
    public static final String PRIMARY_KEY = "PRIMARY_KEY ";
    public static final String PERCENT = "%";
    public static final String LEFT_BRACKET = "(";
    public static final String RIGHT_BRACKET = ")";
    public static final String COMMA = ",";
    public static final String SEMICOLON = ";";
    public static final String COLON = ":";
    public static final String UNION = " UNION ";
    public static final String VALUES = " VALUES ";
    public static final String ORDER_BY = " ORDER BY ";
    public static final String ASC = "ASC";
    public static final String DESC = "DESC";
    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 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 STANDARD = "standard";
    public static final String STANDARD_EHR = "standard_ehr";
    public static final String STANDARD_ORG = "standard_org";
    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 PATIENT_ID = "JDSA00_01_001";
    public static final String EVENT_NO = "event_no";
    public static final String EVENT_TIME = "event_time";
    public static final String EVENT_REF_TIME = "ref_time";
    public static final String ORG_CODE = "rscom_org_code";
    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";
}

+ 49 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/constant/SystemDictId.java

@ -0,0 +1,49 @@
package com.yihu.hos.web.framework.constant;
/**
 * 通用字典ID。
 *
 * @author Sand
 * @version 1.0
 * @created 2015.07.29 14:38
 */
public class SystemDictId {
/*    public final static long Nation = 1;                         // 民族字典
    public final static long Gender = 2;                         // 性别字典
    public final static long Country = 3;                       // 国家字典
    public final static long MartialStatus = 4;                 // 婚姻状态字典
    public final static long FamilyMemberRelation = 5;          // 家庭关系
    public final static long ResidenceType = 6;                // 户口类型
    public final static long OrganizationType = 7;             // 组织机构类型
    public final static long OrganizationSettledWay = 8;       // 机构接入平台方式
    public final static long CardStatus = 9;                          // 卡状态
    public final static long CardType = 10;                      // 卡类型
    public final static long RSAKeyType = 11;                       // 公私钥类型
    public final static long UserType = 12;                      // 用户类型
    public final static long UserRole = 13;                      // 用户角色*/
    public final static long AppStatus = 1;                                 // app状态
    public final static long AppCatalog = 2;                             // app类型
    public final static long Gender = 3;                                    // 用户性别
    public final static long MartialStatus = 4;                       // 婚姻状况
    public final static long Nation = 5;                                    // 民族
    public final static long ResidenceType = 6;                  // 户口类型
    public final static long OrgType = 7;                               // 机构类型
    public final static long SettledWay = 8;                        // 结算方式
    public final static long CardStatus = 9;                          // 卡状态
    public final static long CardType = 10;                         // 卡类型
    public final static long RequestState = 11;                       // 请求状态
    public final static long KeyType = 12;                              // 用户区分
    public final static long MedicalRole = 13;                      // 医疗角色
    public final static long UserRole = 14;                         // 用户角色
    public final static long UserType = 15;                         // 用户类别
    public final static long FamilyMemberRelation = 16;                      // 家庭成员关系
    public final static long tags = 17;                                     // 标签
    public final static long yesNo = 18;                                 // 是否
    public final static long hosTableList = 19;                    // 集成开放平台数据收集表
    public final static long loginAddress = 20;                    // 登入地址API Id
    public final static String AddressAPI = "baidu_APIStore_API";       //登入地址API
    public final static String Apikey = "baidu_apikey";                                 //登入地址apikey
}

+ 1008 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/dao/SQLGeneralDAO.java

@ -0,0 +1,1008 @@
package com.yihu.hos.web.framework.dao;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.yihu.hos.core.datatype.NumberUtil;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import com.yihu.hos.web.framework.model.DataGridResult;
import com.yihu.hos.web.framework.model.Result;
import com.yihu.hos.web.framework.model.standard.AdapterVersion;
import com.yihu.hos.web.framework.model.standard.StandardVersion;
import com.yihu.hos.web.framework.util.sql.SqlCreator;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.*;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.Table;
import java.io.IOException;
import java.io.Serializable;
import java.math.BigInteger;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/8/8.
 */
@Transactional
@Repository("sqlGeneralDAO")
public class SQLGeneralDAO implements XSQLGeneralDAO {
    static private final Logger logger = LoggerFactory.getLogger(SQLGeneralDAO.class);
    @Autowired
    protected LocalSessionFactoryBean localSessionFactoryBean;
    @Autowired
    protected ObjectMapper objectMapper;
    @Autowired
    protected JdbcTemplate jdbcTemplate;
    @Autowired
    protected HibernateTemplate hibernateTemplate;
    public SQLGeneralDAO() {
    }
    protected SessionFactory sessionFactory() {
        return localSessionFactoryBean.getObject();
    }
    protected Session currentSession() {
        return localSessionFactoryBean.getObject().getCurrentSession();
    }
    public JdbcTemplate getJdbcTemplate() {
        return this.jdbcTemplate;
    }
    public HibernateTemplate getHibernateTemplate() {
        return this.hibernateTemplate;
    }
    public void beginTransaction() throws Exception {
        this.hibernateTemplate.getSessionFactory().getCurrentSession().getTransaction().begin();
    }
    public void commitTransaction() throws Exception {
        this.hibernateTemplate.getSessionFactory().getCurrentSession().getTransaction().commit();
    }
    public Session openSession() {
        return this.getHibernateTemplate().getSessionFactory().openSession();
    }
    public Session getCurrentSession() {
        return this.getHibernateTemplate().getSessionFactory().getCurrentSession();
    }
    public String getTableName(Class<?> clazz) {
        Table table = (Table) clazz.getAnnotation(Table.class);
        return table.name();
    }
    public DataGridResult getDataGridResult(String hql, Integer page, Integer rows) {
        DataGridResult dataGridResult = new DataGridResult();
        Query query = this.hibernateTemplate.getSessionFactory().getCurrentSession().createQuery(hql);
        if (page != null && rows != null) {
            dataGridResult.setPageSize(rows.intValue());
            dataGridResult.setCurrPage(page.intValue());
            dataGridResult.setTotalCount(query.list().size());
            query.setMaxResults(rows.intValue());
            query.setFirstResult((page.intValue() - 1) * rows.intValue());
            dataGridResult.setDetailModelList(query.list());
        } else {
            List list = query.list();
            dataGridResult.setDetailModelList(list);
            dataGridResult.setTotalCount(list.size());
        }
        return dataGridResult;
    }
    public DataGridResult getDataGridResult(Query query, Integer page, Integer rows) {
        DataGridResult dataGridResult = new DataGridResult();
        if (page != null && rows != null) {
            dataGridResult.setPageSize(rows.intValue());
            dataGridResult.setCurrPage(page.intValue());
            dataGridResult.setTotalCount(query.list().size());
            query.setMaxResults(rows.intValue());
            query.setFirstResult((page.intValue() - 1) * rows.intValue());
            dataGridResult.setDetailModelList(query.list());
        } else {
            List list = query.list();
            dataGridResult.setDetailModelList(list);
            dataGridResult.setTotalCount(list.size());
        }
        return dataGridResult;
    }
    public <T> T saveEntity(T entity) throws Exception {
        if (entity != null) {
            this.hibernateTemplate.save(entity);
        }
        return entity;
    }
    public <T> T updateEntity(T entity) throws Exception {
        if (entity != null) {
            this.hibernateTemplate.update(entity);
        }
        return entity;
    }
    public void saveOrUpdateEntity(Object entity) throws Exception {
        if (entity != null) {
            this.hibernateTemplate.saveOrUpdate(entity);
        }
    }
    public void mergeEntity(Object entity) throws Exception {
        if (entity != null) {
            this.hibernateTemplate.merge(entity);
        }
    }
    public void deleteEntity(Object entity) throws Exception {
        if (entity != null) {
            this.hibernateTemplate.delete(entity);
        }
    }
    public <T> void deleteEntity(Class<T> cls, Serializable id) throws Exception {
        Object obj = this.hibernateTemplate.load(cls, id);
        this.hibernateTemplate.delete(obj);
    }
    public <T> T getEntity(Class<T> cls, Serializable id) throws Exception {
        return this.hibernateTemplate.get(cls, id);
    }
    public List<Map<String, Object>> queryListBySql(String sql) throws Exception {
        List result = this.jdbcTemplate.queryForList(sql);
        return result;
    }
    public List<Map<String, Object>> queryListBySql(String sql, List params) throws Exception {
        List result = this.jdbcTemplate.queryForList(sql, params.toArray());
        return result;
    }
    public <T> List<T> queryListBySql(String sql, Class obj) throws Exception {
        RowMapper<T> rowMapper = BeanPropertyRowMapper.newInstance(obj);
        List result = this.jdbcTemplate.query(sql, rowMapper);
        return result;
    }
    public <T> List<T> queryListBySql(String sql, List params, Class obj) throws Exception {
        RowMapper<T> rowMapper = BeanPropertyRowMapper.newInstance(obj);
        List result = this.jdbcTemplate.query(sql, params.toArray(), rowMapper);
        return result;
    }
    public <T> T queryObjBySql(String sql, List params, Class obj) throws Exception {
        RowMapper<T> rowMapper = BeanPropertyRowMapper.newInstance(obj);
        T result = this.jdbcTemplate.queryForObject(sql, params.toArray(), rowMapper);
        return result;
    }
    public <T> T queryObjBySql(String sql, Class obj) throws Exception {
        RowMapper<T> rowMapper = BeanPropertyRowMapper.newInstance(obj);
        T result = this.jdbcTemplate.queryForObject(sql, rowMapper);
        return result;
    }
    public <T> T scalarBySql(String sql, Class cls) throws Exception {
        T result = (T) this.jdbcTemplate.queryForObject(sql, cls);
        return result;
    }
    public void execute(String sql) throws Exception {
        this.jdbcTemplate.execute(sql);
    }
    public <T> List getEntityList(Class<T> cls, String hql) {
        Query query = this.getCurrentSession().createQuery(hql);
        return query.list();
    }
    public <T> List getEntityList(Class<T> cls, String condition, String order, Integer limit, Integer offset) throws IOException {
        Session session = this.getCurrentSession();
        Criteria criteria = session.createCriteria(cls);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode;
        Iterator fieldNames;
        String fieldName;
        if (!StringUtil.isEmpty(condition)) {
            jsonNode = objectMapper.readTree(condition);
            fieldNames = jsonNode.fieldNames();
            while (fieldNames.hasNext()) {
                fieldName = (String) fieldNames.next();
                if (jsonNode.get(fieldName).isInt()) {
                    criteria.add(Restrictions.eq(fieldName, Integer.valueOf(jsonNode.get(fieldName).asInt())));
                } else {
                    criteria.add(Restrictions.eq(fieldName, jsonNode.get(fieldName).asText()));
                }
            }
        }
        if (!StringUtil.isEmpty(order)) {
            jsonNode = objectMapper.readTree(order);
            fieldNames = jsonNode.fieldNames();
            while (fieldNames.hasNext()) {
                fieldName = (String) fieldNames.next();
                String value = jsonNode.get(fieldName).asText().toUpperCase();
                if (value.equals("ASC")) {
                    criteria.addOrder(Order.asc(fieldName));
                } else if (value.equals("DESC")) {
                    criteria.addOrder(Order.desc(fieldName));
                }
            }
        }
        if (limit != null) {
            criteria.setMaxResults(limit.intValue());
            if (offset != null) {
                criteria.setFirstResult((offset.intValue() - 1) * limit.intValue());
            }
        }
        return criteria.list();
    }
    public <T> Long getEntitysCount(Class<T> cls, String condition) throws IOException {
        Session session = this.getCurrentSession();
        Criteria criteria = session.createCriteria(cls);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode;
        Iterator fieldNames;
        String fieldName;
        if (!StringUtil.isEmpty(condition)) {
            jsonNode = objectMapper.readTree(condition);
            fieldNames = jsonNode.fieldNames();
            while (fieldNames.hasNext()) {
                fieldName = (String) fieldNames.next();
                if (jsonNode.get(fieldName).isInt()) {
                    criteria.add(Restrictions.eq(fieldName, Integer.valueOf(jsonNode.get(fieldName).asInt())));
                } else {
                    criteria.add(Restrictions.eq(fieldName, jsonNode.get(fieldName).asText()));
                }
            }
        }
        Long size = 0l;
        if (criteria.list() != null && criteria.list().size() > 0) {
            size = Long.valueOf(criteria.list().size());
        }
        return size;
    }
    public <T> List getEntityListByParentId(Class<T> cls, String parentFiledName, Long patentId, String condition, String order, Integer limit, Integer offset) throws IOException {
        Session session = this.getCurrentSession();
        Criteria criteria = session.createCriteria(cls);
        criteria.add(Restrictions.eq(parentFiledName, patentId));
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode;
        Iterator fieldNames;
        String fieldName;
        if (!StringUtil.isEmpty(condition)) {
            jsonNode = objectMapper.readTree(condition);
            fieldNames = jsonNode.fieldNames();
            while (fieldNames.hasNext()) {
                fieldName = (String) fieldNames.next();
                if (jsonNode.get(fieldName).isInt()) {
                    criteria.add(Restrictions.eq(fieldName, Integer.valueOf(jsonNode.get(fieldName).asInt())));
                } else {
                    criteria.add(Restrictions.eq(fieldName, jsonNode.get(fieldName).asText()));
                }
            }
        }
        if (!StringUtil.isEmpty(order)) {
            jsonNode = objectMapper.readTree(order);
            fieldNames = jsonNode.fieldNames();
            while (fieldNames.hasNext()) {
                fieldName = (String) fieldNames.next();
                String value = jsonNode.get(fieldName).asText().toUpperCase();
                if (value.equals("ASC")) {
                    criteria.addOrder(Order.asc(fieldName));
                } else if (value.equals("DESC")) {
                    criteria.addOrder(Order.desc(fieldName));
                }
            }
        }
        if (limit != null) {
            criteria.setMaxResults(limit.intValue());
            if (offset != null) {
                criteria.setFirstResult((offset.intValue() - 1) * limit.intValue());
            }
        }
        return criteria.list();
    }
    public <T> List getEntityListByParentId(Class<T> cls, String parentFiledName, Integer patentId, String condition, String order, Integer limit, Integer offset) throws IOException {
        Session session = this.getCurrentSession();
        Criteria criteria = session.createCriteria(cls);
        criteria.add(Restrictions.eq(parentFiledName, patentId));
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode;
        Iterator fieldNames;
        String fieldName;
        if (!StringUtil.isEmpty(condition)) {
            jsonNode = objectMapper.readTree(condition);
            fieldNames = jsonNode.fieldNames();
            while (fieldNames.hasNext()) {
                fieldName = (String) fieldNames.next();
                if (jsonNode.get(fieldName).isInt()) {
                    criteria.add(Restrictions.eq(fieldName, Integer.valueOf(jsonNode.get(fieldName).asInt())));
                } else {
                    criteria.add(Restrictions.eq(fieldName, jsonNode.get(fieldName).asText()));
                }
            }
        }
        if (!StringUtil.isEmpty(order)) {
            jsonNode = objectMapper.readTree(order);
            fieldNames = jsonNode.fieldNames();
            while (fieldNames.hasNext()) {
                fieldName = (String) fieldNames.next();
                String value = jsonNode.get(fieldName).asText().toUpperCase();
                if (value.equals("ASC")) {
                    criteria.addOrder(Order.asc(fieldName));
                } else if (value.equals("DESC")) {
                    criteria.addOrder(Order.desc(fieldName));
                }
            }
        }
        if (limit != null) {
            criteria.setMaxResults(limit.intValue());
            if (offset != null) {
                criteria.setFirstResult((offset.intValue() - 1) * limit.intValue());
            }
        }
        return criteria.list();
    }
    public List getList(Class tClass, String tableName, String condition, String order, Integer limit, Integer offset) {
        SqlCreator sqlCreator = new SqlCreator(tClass);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode sql;
            Iterator query;
            String fieldName;
            String value;
            if (!StringUtil.isEmpty(condition)) {
                sql = objectMapper.readTree(condition);
                query = sql.fieldNames();
                while (query.hasNext()) {
                    fieldName = (String) query.next();
                    value = sql.get(fieldName).asText();
                    if (sql.get(fieldName).getNodeType().equals(JsonNodeType.NUMBER)) {
                        sqlCreator.equalCondition(fieldName, Integer.valueOf(Integer.parseInt(value)));
                    } else {
                        sqlCreator.equalCondition(fieldName, value);
                    }
                }
            }
            if (!StringUtil.isEmpty(order)) {
                sql = objectMapper.readTree(order);
                query = sql.fieldNames();
                while (query.hasNext()) {
                    fieldName = (String) query.next();
                    value = sql.get(fieldName).asText().toUpperCase();
                    sqlCreator.order(fieldName, value);
                }
            }
        } catch (Exception var13) {
            var13.printStackTrace();
        }
        String sql1 = sqlCreator.selectData(tableName);
        Query query1 = this.getQuery(sqlCreator, sql1);
        if (limit != null) {
            query1.setMaxResults(limit.intValue());
            if (offset != null) {
                query1.setFirstResult(offset.intValue() * limit.intValue());
            }
        }
        return query1.list();
    }
    public List getListByIdList(Class tClass, String tableName, String fieldName, List idList) {
        SqlCreator sqlCreator = new SqlCreator(tClass);
        try {
            sqlCreator.inCondition(fieldName, idList);
        } catch (Exception var8) {
            var8.printStackTrace();
            return null;
        }
        String sql = sqlCreator.selectData(tableName);
        Query query = this.getQuery(sqlCreator, sql);
        return query.list();
    }
    public Integer getDataSetInt(Class tClass, String tableName, String condition) {
        SqlCreator sqlCreator = new SqlCreator(tClass);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (!StringUtil.isEmpty(condition)) {
                JsonNode sql = objectMapper.readTree(condition);
                Iterator query = sql.fieldNames();
                while (query.hasNext()) {
                    String count = (String) query.next();
                    String value = sql.get(count).asText();
                    if (NumberUtil.isInteger(value)) {
                        sqlCreator.equalCondition(count, Integer.valueOf(Integer.parseInt(value)));
                    } else {
                        sqlCreator.equalCondition(count, value);
                    }
                }
            }
        } catch (Exception var10) {
            var10.printStackTrace();
        }
        String sql1 = sqlCreator.countData(tableName);
        Query query1 = this.getQuery(sqlCreator, sql1);
        Integer count1 = Integer.valueOf(Integer.parseInt(StringUtil.toString(query1.list().get(0))));
        return count1;
    }
    public Object get(Class tClass, String tableName, Object id) {
        SqlCreator sqlCreator = new SqlCreator(tClass);
        sqlCreator.equalCondition("id", id);
        String sql = sqlCreator.selectData(tableName);
        Query query = this.getQuery(sqlCreator, sql);
        return query.uniqueResult();
    }
    public Object findByfield(Class tClass, String tableName, String fieldName, Object id) {
        SqlCreator sqlCreator = new SqlCreator(tClass);
        try {
            sqlCreator.inCondition(fieldName, id);
        } catch (Exception var8) {
            var8.printStackTrace();
            return null;
        }
        String sql = sqlCreator.selectData(tableName);
        Query query = this.getQuery(sqlCreator, sql);
        return query.uniqueResult();
    }
    public Query getQuery(SqlCreator sqlCreator, String sql) {
        SQLQuery query = this.getCurrentSession().createSQLQuery(sql);
        Iterator var4 = sqlCreator.getKeyValueMap().keySet().iterator();
        while (var4.hasNext()) {
            String key = (String) var4.next();
            Object value = sqlCreator.getKeyValueMap().get(key);
            if (value instanceof Collection) {
                query.setParameterList(key, (Collection) value);
            } else {
                query.setParameter(key, value);
            }
        }
        query.setResultTransformer(sqlCreator.getTransformer());
        return query;
    }
    public void insertBatch(final List<String> insertSqlList) {
//        Session session = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
        String[] sqlStr = new String[insertSqlList.size()];
        String[] sqlArr = insertSqlList.toArray(sqlStr);
        this.jdbcTemplate.batchUpdate(sqlArr);
    }
    public Integer getMaxId(String tableName) {
        String sql = "select max(id) from " + tableName;
        SQLQuery query = this.getCurrentSession().createSQLQuery(sql);
        Object object = query.uniqueResult();
        Integer maxId = Integer.valueOf(object == null ? 1 : Integer.parseInt(object.toString()) + 1);
        return maxId;
    }
    public Query getExeuteQuery(SqlCreator sqlCreator, String sql) {
        SQLQuery query = this.getCurrentSession().createSQLQuery(sql);
        Iterator var4 = sqlCreator.getKeyValueMap().keySet().iterator();
        while (var4.hasNext()) {
            String key = (String) var4.next();
            Object value = sqlCreator.getKeyValueMap().get(key);
            if (value instanceof Collection) {
                query.setParameterList(key, (Collection) value);
            } else {
                query.setParameter(key, value);
            }
        }
        return query;
    }
    public List findInList(String hql , String[] params , Object[] values) {
        Query query = this.getCurrentSession().createQuery(hql);
        if (params == null || values == null){
            return null;
        }
        for (int i=0;i <params.length;i++){
            if (values[i] instanceof Collection) {
                query.setParameterList(params[i], (Collection) values[i]);
            } else {
                query.setParameter(params[i], values[i]);
            }
        }
        return query.list();
    }
    public Boolean tableIsExist(String sql) {
        BigInteger tableNum = (BigInteger) this.getCurrentSession().createSQLQuery(sql).uniqueResult();
        if (tableNum.intValue() > 0) {
            return true;
        }
        return false;
    }
    protected void doClose(Session session, Statement stmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
                rs = null;
            } catch (Exception var6) {
                rs = null;
                logger.error("close-ResultSet ", var6);
                var6.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
                stmt = null;
            } catch (Exception var5) {
                stmt = null;
                logger.error("close-ResultSet ", var5);
                var5.printStackTrace();
            }
        }
    }
    //region 标准相关
    public List searchVersionData(Class tClass, String stdVersion,String dataType, String condition) throws IOException {
        return searchVersionData(tClass,stdVersion,dataType,condition,null,null,null);
    }
    public List searchVersionData(Class tClass, String stdVersion,String dataType, String condition, String order, Integer page, Integer size) throws IOException {
        String tableName = null;
        if (!StringUtil.isEmpty(stdVersion)) {
            StandardVersion standardVersion = new StandardVersion(stdVersion);
            tableName = standardVersion.getTableName(dataType);
        } else {
            tableName = getTableName(tClass);
        }
        SqlCreator sqlCreator = new SqlCreator(tClass);
        //where
        if (!StringUtil.isEmpty(condition)) {
            String[] filterArray = condition.split(";");
            for (int i = 0; i < filterArray.length; ++i) {
                String[] tokens = filterArray[i].split("=");
                if (tokens.length > 2) {
                    for (int j = 1; j < tokens.length; j++) {
                        if (j == tokens.length - 1)
                            tokens[1] = tokens[j];
                        else
                            tokens[0] += " " + tokens[j];
                    }
                }
//            if (tokens.length > 2) throw new IllegalArgumentException("无效过滤参数");
                String group = null;
                if (tokens.length >= 2) group = tokens[1];
                if (group == null)
                    group = Integer.toString(i);
                sqlCreator.likeCondition(tokens[0], tokens[1]);
            }
        }
        //order
        if (StringUtils.isNotEmpty(order)) {
            String[] orderArray = order.split(",");
            for (String elem : orderArray) {
                String value = elem.startsWith("+") ? "ASC" : "DESC";
                sqlCreator.order(elem.substring(1), value);
            }
        }
        String sql = sqlCreator.selectData(tableName);
        Query query = getQuery(sqlCreator, sql);
        if (size != null) {
            query.setMaxResults(size);
            if (page != null) {
                query.setFirstResult((page - 1) * size);
            }
        }
        return query.list();
    }
    public Long searchVersionCount(Class tClass, String stdVersion, String dataType, String condition) throws IOException {
        String tableName = null;
        if (!StringUtil.isEmpty(stdVersion)) {
            StandardVersion standardVersion = new StandardVersion(stdVersion);
            tableName = standardVersion.getTableName(dataType);
        } else {
            tableName = getTableName(tClass);
        }
        SqlCreator sqlCreator = new SqlCreator(tClass);
        //where
        if (!StringUtil.isEmpty(condition)) {
            String[] filterArray = condition.split(";");
            for (int i = 0; i < filterArray.length; ++i) {
                String[] tokens = filterArray[i].split("=");
                if (tokens.length > 2) {
                    for (int j = 1; j < tokens.length; j++) {
                        if (j == tokens.length - 1)
                            tokens[1] = tokens[j];
                        else
                            tokens[0] += " " + tokens[j];
                    }
                }
//            if (tokens.length > 2) throw new IllegalArgumentException("无效过滤参数");
                String group = null;
                if (tokens.length >= 2) group = tokens[1];
                if (group == null)
                    group = Integer.toString(i);
                sqlCreator.likeCondition(tokens[0], tokens[1]);
            }
        }
        String sql = sqlCreator.countData(tableName);
        Query query = getCurrentSession().createSQLQuery(sql);
        for (String key : sqlCreator.getKeyValueMap().keySet()) {
            query.setParameter(key, sqlCreator.getKeyValueMap().get(key));
        }
        Long count = Long.valueOf(StringUtil.toString(query.list().get(0)));
        return count;
    }
    public Long searchCount(Class tClass, String stdVersion, String dataType, String condition) throws IOException {
        String tableName = null;
        if (!StringUtil.isEmpty(stdVersion)) {
            StandardVersion standardVersion = new StandardVersion(stdVersion);
            tableName = standardVersion.getTableName(dataType);
        } else {
            tableName = getTableName(tClass);
        }
        SqlCreator sqlCreator = new SqlCreator(tClass);
        //where
        if (!StringUtil.isEmpty(condition)) {
            Map<String, List<String>> whereMap = new HashMap<>();
            String[] filterArray = condition.split(";");
            for (int i = 0; i < filterArray.length; ++i) {
                String[] tokens = filterArray[i].split(" ");
                if (tokens.length > 2) {
                    for (int j = 1; j < tokens.length; j++) {
                        if (j == tokens.length - 1)
                            tokens[1] = tokens[j];
                        else
                            tokens[0] += " " + tokens[j];
                    }
                }
                String group = null;
                if (tokens.length >= 2)
                    group = tokens[1];
                if (group == null)
                    group = Integer.toString(i);
                List<String> list = whereMap.get(group);
                if(list==null || list.size()==0){
                    list = new ArrayList<String>();
                    list.add(tokens[0]);
                }else{
                    list.add(tokens[0]);
                }
                whereMap.put(group,list);
            }
            Collection<List<String>> lists = whereMap.values();
            for(List<String> whereCondition :lists){
                sqlCreator.makeWhere(whereCondition);
            }
        }
        String sql = sqlCreator.countData(tableName);
        Query query = getCurrentSession().createSQLQuery(sql);
        for (String key : sqlCreator.getKeyValueMap().keySet()) {
            query.setParameter(key, sqlCreator.getKeyValueMap().get(key));
        }
        Long count = Long.valueOf(StringUtil.toString(query.list().get(0)));
        return count;
    }
    //这边不支持分组条件查询,如需要分组查询
    //因为调用的地方太多,未做大改造,新增了  searchPage 方法
    public List searchPageData(Class tClass,String dataType, String stdVersion, String condition, String order, Integer offset, Integer limit) throws IOException {
        StandardVersion standardVersion = new StandardVersion(stdVersion);
        String tableName = standardVersion.getTableName(dataType);
        SqlCreator sqlCreator = new SqlCreator(tClass);
        //where
        if (!StringUtil.isEmpty(condition)) {
            String[] filterArray = condition.split(";");
            for (int i = 0; i < filterArray.length; ++i) {
                String[] tokens = filterArray[i].split("=");
                if (tokens.length > 2){
                    for(int j=1; j<tokens.length; j++){
                        if(j==tokens.length-1)
                            tokens[1] = tokens[j];
                        else
                            tokens[0] += " " + tokens[j] ;
                    }
                }
//            if (tokens.length > 2) throw new IllegalArgumentException("无效过滤参数");
                String group = null;
                if (tokens.length >= 2) group = tokens[1];
                if (group == null)
                    group = Integer.toString(i);
                if(tokens[1].contains(",")){
                    sqlCreator.inCondition(tokens[0],tokens[1]);
                }else{
                    sqlCreator.equalConditionQue(tokens[0],tokens[1]);
                }
            }
        }
        //order
        if (StringUtils.isNotEmpty(order)) {
            String[] orderArray = order.split(",");
            for(String elem : orderArray){
                String value = elem.startsWith("-") ? "DESC" : "ASC";
                sqlCreator.order(elem.substring(1), value);
            }
        }
        String sql = sqlCreator.selectData(tableName);
        Query query = getQuery(sqlCreator, sql);
        if (limit != null) {
            query.setMaxResults(limit);
            if (offset != null) {
                query.setFirstResult((offset - 1) * limit);
            }
        }
        return query.list();
    }
    public List searchPage(Class tClass,String dataType, String version, String condition, String order, Integer offset, Integer limit,boolean isStandard) throws IOException {
        String tableName;
        if(isStandard){
            StandardVersion standardVersion = new StandardVersion(version);
            tableName = standardVersion.getTableName(dataType);
        }else{
            AdapterVersion adapterVersion = new AdapterVersion(version);
            tableName = adapterVersion.getTableName(dataType);
        }
        SqlCreator sqlCreator = new SqlCreator(tClass);
        //where
        if (!StringUtil.isEmpty(condition)) {
            Map<String, List<String>> whereMap = new HashMap<>();
            String[] filterArray = condition.split(";");
            for (int i = 0; i < filterArray.length; ++i) {
                String[] tokens = filterArray[i].split(" ");
                if (tokens.length > 2) {
                    for (int j = 1; j < tokens.length; j++) {
                        if (j == tokens.length - 1)
                            tokens[1] = tokens[j];
                        else
                            tokens[0] += " " + tokens[j];
                    }
                }
                String group = null;
                if (tokens.length >= 2)
                    group = tokens[1];
                if (group == null)
                    group = Integer.toString(i);
                List<String> list = whereMap.get(group);
                if(list==null || list.size()==0){
                    list = new ArrayList<String>();
                    list.add(tokens[0]);
                }else{
                    list.add(tokens[0]);
                }
                whereMap.put(group,list);
            }
            Collection<List<String>> lists = whereMap.values();
            for(List<String> whereCondition :lists){
                sqlCreator.makeWhere(whereCondition);
            }
        }
        //order
        if (StringUtils.isNotEmpty(order)) {
            String[] orderArray = order.split(",");
            for(String elem : orderArray){
                String value = elem.startsWith("-") ? "DESC" : "ASC";
                sqlCreator.order(elem.substring(1), value);
            }
        }
        String sql = sqlCreator.selectData(tableName);
        Query query = getQuery(sqlCreator, sql);
        if (limit != null) {
            query.setMaxResults(limit);
            if (offset != null) {
                query.setFirstResult((offset - 1) * limit);
            }
        }
        return query.list();
    }
    public boolean isExistByField(Class tClass, String stdVersion,String dataType,String field, Object val) throws IOException {
        return isExistByFields(
                tClass,
                stdVersion,
                dataType,
                new String[]{field},
                new Object[]{val}
        );
    }
    public boolean isExistByFields(Class tClass, String stdVersion,String dataType,String[] fields, Object[] vals) throws IOException {
        String tableName = null;
        if (!StringUtil.isEmpty(stdVersion)) {
            StandardVersion standardVersion = new StandardVersion(stdVersion);
            tableName = standardVersion.getTableName(dataType);
        } else {
            tableName = getTableName(tClass);
        }
        SqlCreator sqlCreator = new SqlCreator(tClass);
        //where
        if (!StringUtil.isEmpty(fields) && !StringUtil.isEmpty(vals)) {
            for (int i = 0; i < fields.length; ++i) {
                if(fields[i]!=null){
                    sqlCreator.equalConditionQue(fields[i], vals[i]);
                }
            }
        }
        String sql = sqlCreator.selectData(tableName);
        Query query = getQuery(sqlCreator, sql);
        Long count = Long.valueOf(StringUtil.toString(query.list().size()));
        return count>0;
    }
    public <T> T retrieve(Class<T> tclass,String tableName,Object id){
        return (T) get(tclass,tableName,id);
    }
    public Object get(Class tClass, String stdVersion, String dataType, String id) {
        try {
            StandardVersion standardVersion = new StandardVersion(stdVersion);
            if (id != null) {
                String tableName = standardVersion.getTableName(dataType);
                SqlCreator sqlCreator = new SqlCreator(tClass);
                sqlCreator.equalCondition("id", id);
                String sql = sqlCreator.selectData(tableName);
                Query query = getQuery(sqlCreator, sql);
                return query.uniqueResult();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("获取标准数据元失败");
    }
    public  <T> List<T> findByFields(Class<T> tClass, String stdVersion, String[] fields, Object[] vals) throws IOException {
        String tableName = null;
        if (!StringUtil.isEmpty(stdVersion)) {
            StandardVersion standardVersion = new StandardVersion(stdVersion);
            tableName = standardVersion.getDataSetTableName();
        } else {
            tableName = getTableName(tClass);
        }
        SqlCreator sqlCreator = new SqlCreator(tClass);
        //where
        if (!StringUtil.isEmpty(fields) && !StringUtil.isEmpty(vals)) {
            for (int i = 0; i < fields.length; ++i) {
                if(fields[i]!=null){
                    sqlCreator.likeCondition(fields[i], vals[i]);
                }
            }
        }
        String sql = sqlCreator.selectData(tableName);
        Query query = getQuery(sqlCreator, sql);
        return query.list();
    }
    public boolean delete(Class tclass, Object[] ids, String dataType, String version) {
        if (ids == null || ids.length == 0)
            return false;
        StandardVersion standardVersion = new StandardVersion(version);
        String tableName = standardVersion.getTableName(dataType);
        String idField = sessionFactory().getClassMetadata(tclass).getIdentifierPropertyName();
        String hql =
                "DELETE FROM " + tableName +
                        " WHERE " + idField + " in (:ids) ";
        Query query = this.getCurrentSession().createQuery(hql);
        query.setParameterList("ids", ids);
        return query.executeUpdate() > 0;
    }
    public boolean deleteByField(String field, Object[] ids, String dataType, String version) {
        if (ids == null || ids.length == 0)
            return false;
        StandardVersion standardVersion = new StandardVersion(version);
        String tableName = standardVersion.getTableName(dataType);
        String sql =
                "DELETE FROM " + tableName +
                        " WHERE " + field + " in (:ids) ";
        Query query = this.getCurrentSession().createSQLQuery(sql);
        query.setParameterList("ids", ids);
        return query.executeUpdate() > 0;
    }
}

+ 80 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/dao/XSQLGeneralDAO.java

@ -0,0 +1,80 @@
package com.yihu.hos.web.framework.dao;
import com.yihu.hos.web.framework.model.DataGridResult;
import com.yihu.hos.web.framework.util.sql.SqlCreator;
import org.hibernate.Query;
import org.hibernate.Session;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
 * @author HZY
 * @vsrsion 1.0
 * Created at 2016/8/8.
 */
public interface XSQLGeneralDAO {
    void beginTransaction() throws Exception;
    void commitTransaction() throws Exception;
    <T> T saveEntity(T var1) throws Exception;
    <T> T updateEntity(T var1) throws Exception;
    void mergeEntity(Object var1) throws Exception;
    void deleteEntity(Object var1) throws Exception;
    <T> void deleteEntity(Class<T> var1, Serializable var2) throws Exception;
    void saveOrUpdateEntity(Object var1) throws Exception;
    <T> T getEntity(Class<T> var1, Serializable var2) throws Exception;
    DataGridResult getDataGridResult(String var1, Integer var2, Integer var3) throws Exception;
    List<Map<String, Object>> queryListBySql(String var1) throws Exception;
    List<Map<String, Object>> queryListBySql(String var1, List var2) throws Exception;
    <T> List<T> queryListBySql(String var1, Class var2) throws Exception;
    <T> List<T> queryListBySql(String var1, List var2, Class var3) throws Exception;
    <T> T queryObjBySql(String var1, List var2, Class var3) throws Exception;
    <T> T queryObjBySql(String var1, Class var2) throws Exception;
    <T> T scalarBySql(String var1, Class var2) throws Exception;
    void execute(String var1) throws Exception;
    <T> List getEntityList(Class<T> var1, String var2);
    <T> List getEntityList(Class<T> var1, String var2, String var3, Integer var4, Integer var5) throws IOException;
    <T> List getEntityListByParentId(Class<T> var1, String var2, Long var3, String var4, String var5, Integer var6, Integer var7) throws IOException;
    <T> List getList(Class<T> var1, String var2, String var3, String var4, Integer var5, Integer var6);
    <T> Integer getDataSetInt(Class<T> var1, String var2, String var3);
    <T> Object get(Class<T> var1, String var2, Object var3);
    Session getCurrentSession();
    Session openSession();
    Query getQuery(SqlCreator var1, String var2);
    Query getExeuteQuery(SqlCreator var1, String var2);
    Integer getMaxId(String var1);
    void insertBatch(List<String> var1);
    List getListByIdList(Class var1, String var2, String var3, List<Integer> var4);
}

+ 97 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/ehrModel/BaseResult.java

@ -0,0 +1,97 @@
package com.yihu.hos.web.framework.ehrModel;
import java.lang.reflect.Field;
/**
 * Created by hzp on 2017/03/07.
 * 基础对象
 */
public class BaseResult {
    protected boolean successFlg = true;
    protected String message;
    protected int code;
    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 getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }
    /**
     * 错误消息
     */
    public static BaseResult error(String message) {
        BaseResult re= new BaseResult();
        re.successFlg = false;
        re.message = message;
        re.code = -1;
        return re;
    }
    /**
     * 错误消息
     */
    public static BaseResult error(int code, String message) {
        BaseResult re= new BaseResult();
        re.successFlg = false;
        re.message = message;
        re.code = code;
        return re;
    }
    /**
     * 成功消息
     */
    public static BaseResult success(String message) {
        BaseResult re= new BaseResult();
        re.successFlg = true;
        re.message = message;
        re.code = 200;
        return re;
    }
    /**
     * 成功消息
     */
    public static ObjectResult success(String message,Object data) {
        ObjectResult re= new ObjectResult();
        re.successFlg = true;
        re.message = message;
        re.code = 200;
        re.setData(data);
        return re;
    }
    public void checkValue() {
        try {
            Field[] fields = this.getClass().getDeclaredFields();
            for (int j = 0; j < fields.length; j++) {
                fields[j].setAccessible(true);
                if (fields[j].getType().getName().equals(String.class.getTypeName())
                        && fields[j].get(this) == null){
                    fields[j].set(this, "");//设置为空字串
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

+ 102 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/ehrModel/ListResult.java

@ -0,0 +1,102 @@
package com.yihu.hos.web.framework.ehrModel;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
/**
 * 列表对象
 */
public class ListResult extends BaseResult implements Serializable {
    private int pageSize = 10;
    private int currPage = 1;
    private int totalPage;
    private int totalCount;
    private List detailModelList;
    public ListResult() {
    }
    public ListResult(int currPage, int pageSize) {
        this.pageSize = pageSize;
        this.currPage = currPage;
    }
    public static ListResult fromJson(String json) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(json, ListResult.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public String toJson() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "";
        }
    }
    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 getTotalCount() {
        if (totalCount == 0 && detailModelList != null) {
            totalCount = detailModelList.size();
        }
        return totalCount;
    }
    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }
    public List getDetailModelList() {
        return detailModelList;
    }
    public void setDetailModelList(List detailModelList) {
        this.detailModelList = detailModelList;
    }
}

+ 26 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/ehrModel/ObjectResult.java

@ -0,0 +1,26 @@
package com.yihu.hos.web.framework.ehrModel;
/**
 * Created by hzp on 20170315.
 */
public class ObjectResult extends BaseResult {
    private Object data;
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }
    public ObjectResult()
    {}
    public ObjectResult(boolean successFlg, String message){
        super.setSuccessFlg(successFlg);
        super.setMessage(message);
    }
}

+ 12 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/AnalyzerException.java

@ -0,0 +1,12 @@
package com.yihu.hos.web.framework.exception;
/**
 * Created by progr1mmer on 2018/6/14.
 */
public class AnalyzerException extends RuntimeException {
    public AnalyzerException(String message) {
        super(message);
    }
}

+ 42 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/ApiErrorEcho.java

@ -0,0 +1,42 @@
package com.yihu.hos.web.framework.exception;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.hos.web.framework.util.springutil.SpringBeanUtil;
import java.io.Serializable;
/**
 * REST API return value, it's a json expression.
 * Created by Sand Wen on 2015.8.12.
 */
public class ApiErrorEcho implements Serializable {
    private final static String MESSAGE_NODE = "message";
    private final static String DOCUMENTATION_URL = "documentation_url";
    private ObjectNode root;
    public ApiErrorEcho() {
    }
    public ApiErrorEcho(String message, String documentationUrl) {
        ObjectMapper objectMapper = SpringBeanUtil.getService(ObjectMapper.class);
        root = objectMapper.createObjectNode();
        root.put(MESSAGE_NODE, message);
        root.put(DOCUMENTATION_URL, documentationUrl);
    }
    public String getCode() {
        return root.get(DOCUMENTATION_URL).asText();
    }
    public String getMessage() {
        return root.get(MESSAGE_NODE).asText();
    }
    @Override
    public String toString() {
        return this.root.toString();
    }
}

+ 41 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/ApiException.java

@ -0,0 +1,41 @@
package com.yihu.hos.web.framework.exception;
import com.yihu.hos.web.framework.constant.ErrorCode;
/**
 * @author Sand
 * @version 1.0
 * @created 2015.12.20 16:05
 */
public class ApiException extends RuntimeException {
    private static final long serialVersionUID = 1464313464798414L;
    private ErrorCode errCode;
    private String errMsg;
    public ErrorCode getErrorCode() {
        return errCode;
    }
    public void setErrCode(ErrorCode errCode) {
        this.errCode = errCode;
    }
    public String getErrMsg() {
        return errMsg;
    }
    public void setErrMsg(String errMsg) {
        this.errMsg = errMsg;
    }
    public ApiException(ErrorCode errCode) {
        this.errCode = errCode;
    }
    public ApiException(ErrorCode errCode, String errMsg) {
        this.errCode = errCode;
        this.errMsg = errMsg;
    }
}

+ 114 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/EsbApiException.java

@ -0,0 +1,114 @@
package com.yihu.hos.web.framework.exception;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.hos.web.framework.constant.ErrorCode;
import com.yihu.hos.web.framework.util.StringBuilderEx;
import com.yihu.hos.web.framework.util.springutil.SpringBeanUtil;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import java.util.List;
/**
 * API 异常。使用错误代码初始化,并可接收用于补充错误消息的参数。
 * 用于描述错误代码的信息配置在各服务配置文件中,并由服务配置中心统一管理。
 *
 * 错误描述结构,结构(字段errors对资源而言,REST规范错误不包含此结构):
 * {
 *    "message": "Validation Failed",
 *    "document_url": "https://ehr.yihu.com/docs/api/somewhere"
 *    "errors": [
 *        {
 *            "resource": "User",
 *            "field": "title",
 *            "code": "missing_field"
 *        }
 *    ]
 * }
 *
 * @author Sand
 * @version 1.0
 * @created 2015.12.20 16:05
 */
public class EsbApiException extends RuntimeException {
    public HttpStatus getHttpStatus() {
        return httpStatus;
    }
    HttpStatus httpStatus;
    ErrorCode errorCode;        // 用于从配置环境中提取错误信息
    String[] errorArgs;         // 格式化配置环境中的错误信息
    String documentURL;
    String message;             // 错误消息
    List<ResourceError> resourceErrors;         // 资源具体错误描述
    private EsbApiException(HttpStatus httpStatus, ErrorCode errorCode, String documentURL, List<ResourceError> resourceErrors, String... errorArgs){
        this.httpStatus = httpStatus;
        this.errorCode = errorCode;
        this.errorArgs = errorArgs;
        this.documentURL = documentURL;
        this.resourceErrors = resourceErrors;
    }
    public EsbApiException(HttpStatus httpStatus, ErrorCode errorCode, String documentURL, String... errorArgs){
        this(httpStatus, errorCode, documentURL, null, errorArgs);
    }
    public EsbApiException(HttpStatus httpStatus, ErrorCode errorCode){
        this(httpStatus, errorCode, null, null, null);
    }
    public EsbApiException(HttpStatus httpStatus, String message){
        this(httpStatus, null, null, null, null);
        this.message = message;
    }
    public EsbApiException(ErrorCode errorCode, String... errorArgs) {
        this(HttpStatus.FORBIDDEN, errorCode, null, null, errorArgs);
    }
    // legacy support
    public EsbApiException(ErrorCode errorCode) {
        this(HttpStatus.FORBIDDEN, errorCode, null, null, null);
    }
    @Override
    public String toString(){
        try {
            return toJson();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }
    private String toJson() throws JsonProcessingException {
        Environment environment = SpringBeanUtil.getService(Environment.class);
        message = errorCode == null ? message : environment.getProperty(errorCode.getErrorCode());
        if (null != message && null != errorArgs && errorArgs.length > 0){
            StringBuilderEx util = new StringBuilderEx(message);
            for (int i = 0; i < errorArgs.length; ++i){
                util.replace("{" + i + "}", errorArgs[i]);
            }
            message = util.toString();
        }
        ObjectMapper objectMapper = SpringBeanUtil.getService(ObjectMapper.class);
        ObjectNode objectNode = objectMapper.createObjectNode();
        objectNode.put("message", message != null ? message : "");
        objectNode.put("document_url", documentURL != null ? documentURL : "");
        if (resourceErrors != null) objectNode.put("errors", objectMapper.writeValueAsString(resourceErrors));
        return objectNode.toString();
    }
}

+ 15 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/IllegalEmptyCheckException.java

@ -0,0 +1,15 @@
package com.yihu.hos.web.framework.exception;
import java.io.IOException;
/**
 * @Author: zhengwei
 * @Date: 2018/5/25 17:49
 * @Description:质控非空异常
 */
public class IllegalEmptyCheckException extends IOException {
    public IllegalEmptyCheckException(String messgae) {
        super(messgae);
    }
}

+ 14 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/IllegalFormatCheckException.java

@ -0,0 +1,14 @@
package com.yihu.hos.web.framework.exception;
import java.io.IOException;
/**
 * Created by progr1mmer on 2018/6/14.
 */
public class IllegalFormatCheckException extends IOException {
    public IllegalFormatCheckException(String message) {
        super(message);
    }
}

+ 11 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/IllegalJsonDataException.java

@ -0,0 +1,11 @@
package com.yihu.hos.web.framework.exception;
/**
 * Created by progr1mmer on 2018/5/5.
 */
public class IllegalJsonDataException extends IllegalArgumentException {
    public IllegalJsonDataException(String message) {
        super(message);
    }
}

+ 13 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/IllegalJsonFileException.java

@ -0,0 +1,13 @@
package com.yihu.hos.web.framework.exception;
import java.io.IOException;
/**
 * Created by progr1mmer on 2018/5/5.
 */
public class IllegalJsonFileException extends IOException {
    public IllegalJsonFileException(String messgae) {
        super(messgae);
    }
}

+ 14 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/IllegalTypeCheckException.java

@ -0,0 +1,14 @@
package com.yihu.hos.web.framework.exception;
import java.io.IOException;
/**
 * Created by progr1mmer on 2018/6/14.
 */
public class IllegalTypeCheckException extends IOException {
    public IllegalTypeCheckException(String message) {
        super(message);
    }
}

+ 15 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/IllegalValueCheckException.java

@ -0,0 +1,15 @@
package com.yihu.hos.web.framework.exception;
import java.io.IOException;
/**
 * @Author: zhengwei
 * @Date: 2018/5/25 17:49
 * @Description: 质控值域异常
 */
public class IllegalValueCheckException extends IOException {
    public IllegalValueCheckException(String messgae) {
        super(messgae);
    }
}

+ 28 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/LegacyPackageException.java

@ -0,0 +1,28 @@
package com.yihu.hos.web.framework.exception;
/**
 * 历史档案包异常。当解析EHR 0.1版本采集的数据时会出现此异常。
 *
 * @author Sand
 * @created 2016.05.27 16:14
 */
public class LegacyPackageException extends RuntimeException {
    /**
     * Constructs an LegacyPackageException
     *
     * @param message Message explaining the exception condition
     */
    public LegacyPackageException(String message) {
        super( message );
    }
    /**
     * Constructs an LegacyPackageException
     *
     * @param message Message explaining the exception condition
     * @param cause The underlying cause
     */
    public LegacyPackageException(String message, Throwable cause) {
        super( message, cause );
    }
}

+ 11 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/ResolveException.java

@ -0,0 +1,11 @@
package com.yihu.hos.web.framework.exception;
/**
 * Created by progr1mmer on 2018/5/5.
 */
public class ResolveException extends RuntimeException {
    public ResolveException(String message) {
        super(message);
    }
}

+ 42 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/exception/ResourceError.java

@ -0,0 +1,42 @@
package com.yihu.hos.web.framework.exception;
/**
 * @author Sand
 * @version 1.0
 * @created 2016.02.27 15:14
 */
public class ResourceError {
    String resource;
    String field;
    String code;
    public ResourceError(String resource, String field, String code) {
        this.resource = resource;
        this.field = field;
        this.code = code;
    }
    public String getResource() {
        return resource;
    }
    public void setResource(String resource) {
        this.resource = resource;
    }
    public String getField() {
        return field;
    }
    public void setField(String field) {
        this.field = field;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
}

+ 65 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/fastdfs/FastDFSClientPool.java

@ -0,0 +1,65 @@
package com.yihu.hos.web.framework.fastdfs;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
 * Created by szx on 2015/9/19.
 */
public class FastDFSClientPool {
    private int maxPoolSize;
    private Map<StorageClient, Boolean> map = new HashMap<>();
    public void setMaxPoolSize(int poolSize){
        this.maxPoolSize = poolSize;
    }
    public TrackerServer getTrackerServer() throws IOException {
        TrackerClient tracker = new TrackerClient();
        return tracker.getConnection();
    }
    private StorageClient getNewStorageClient() throws IOException {
        TrackerClient tracker = new TrackerClient();
        TrackerServer trackerServer = tracker.getConnection();
        StorageClient client = new StorageClient(trackerServer, null);
        return client;
    }
    public synchronized StorageClient getStorageClient() throws IOException {
        StorageClient client = null;
        for (Entry<StorageClient, Boolean> entry : map.entrySet()) {
            if (entry.getValue()) {
                client = entry.getKey();
                map.put(client, false);
                break;
            }
        }
        if (client == null) {
            if (map.size() < maxPoolSize) {
                client = getNewStorageClient();
                map.put(client, false);
            }
        }
        return client;
    }
    public void releaseStorageClient(StorageClient client) {
        if (client == null) return;
        if (map.containsKey(client)) {
            map.put(client, true);
        } else {
            client = null;
        }
    }
}

+ 301 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/fastdfs/FastDFSUtil.java

@ -0,0 +1,301 @@
package com.yihu.hos.web.framework.fastdfs;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.InputStream;
import java.net.InetSocketAddress;
/**
 * FastDFS 客户端工具.
 *
 * 作为Bean方式来调用。
 *
 * @author szx
 * @author Sand
 */
public class FastDFSUtil {
    private static Logger logger = LoggerFactory.getLogger(FastDFSUtil.class);
    public final static String GroupField = "groupName";
    public final static String RemoteFileField = "remoteFileName";
    public final static String FileIdField = "fid";
    public final static String FileUrlField = "fileUrl";
    
    @Autowired
    FastDFSClientPool clientPool;
    /**
     * 以输入流的方式上传文件
     * InputStream in = new FileInputStream("C://Desert.jpg");
     * ObjectNode msg = FileUtil.upload(in,"jpg", "沙漠");
     * in.close();
     *
     * @param in            输入流
     * @param fileExtension 文件扩展名,不要带“.”
     * @param description   文件名称(中文)
     * @return 返回值的格式如下:
     * {
     * "groupName": "healthArchiveGroup",
     * "remoteFileName": "/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg",
     * "fid": "group1/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg",
     * "fileURL": "http://172.19.103.13/healthArchiveGroup/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg"
     * }
     * <p>
     * groupName 及 remoteFileName 可以用于查询在 fastDFS 中文件的信息,如果只是图片显示,可以忽略这两个值。
     * fid 保存了在 fastDFS 上的完整路径,为了避免将来服务器域名发生变更,最好使用本值.服务器的域名另外配置。
     * fileURL 保存了完整的 web 访问路径,为了避免将来服务器域名发生变更,最好不要直接使用本值。
     * 如果需要在下载时,可以显示原始文件名,请在访问file_url时,增加 attname 参数,如:
     * <p>
     * http://host/healthArchiveGroup/M00/00/00/rBFuH1XdIseAUTZZAA1rIuRd3Es062.jpg?attname=a.jpg
     * @throws Exception
     */
    public ObjectNode upload(InputStream in, String fileExtension, String description) throws Exception {
        NameValuePair[] fileMetaData = new NameValuePair[1];
        fileMetaData[0] = new NameValuePair("description", description == null ? "" : description);
        return upload(in,fileExtension,fileMetaData);
    }
    /**
     * 以输入流的方式上传文件
     */
    public ObjectNode upload(InputStream in, String fileExtension, NameValuePair[] fileMetaData) throws Exception {
        StorageClient client = clientPool.getStorageClient();
        ObjectNode message = new ObjectMapper().createObjectNode();
        try {
            byte fileBuffer[] = new byte[in.available()];
            int len = 0;
            int temp = 0;                             //所有读取的内容都使用temp接收
            while ((temp = in.read()) != -1) {            //当没有读取完时,继续读取
                fileBuffer[len] = (byte) temp;
                len++;
            }
            in.close();
            TrackerServer trackerServer = clientPool.getTrackerServer();
            String[] results = client.upload_file(fileBuffer, fileExtension, fileMetaData);
            if (results != null) {
                String fileId;
                int ts;
                String token;
                String fileURl;
                InetSocketAddress socketAddress;
                String groupName = results[0];
                String remoteFile = results[1];
                message.put(GroupField, groupName);
                message.put(RemoteFileField, remoteFile);
                fileId = groupName + StorageClient1.SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR + remoteFile;
                message.put(FileIdField, fileId);
                socketAddress = trackerServer.getInetSocketAddress();
                fileURl = "http://" + socketAddress.getAddress().getHostAddress();
                if (ClientGlobal.g_tracker_http_port != 80) {
                    fileURl += ":" + ClientGlobal.g_tracker_http_port;
                }
                fileURl += "/" + fileId;
                if (ClientGlobal.g_anti_steal_token) {
                    ts = (int) (System.currentTimeMillis() / 1000);
                    token = ProtoCommon.getToken(fileId, ts, ClientGlobal.g_secret_key);
                    fileURl += "?token=" + token + "&ts=" + ts;
                }
                message.put(FileUrlField, fileURl);
                logger.info(client.get_file_info(groupName, remoteFile).toString());
            }
        } finally {
            clientPool.releaseStorageClient(client);
        }
        return message;
    }
    /**
     * 上传文件,从文件
     */
    public ObjectNode upload(String group_name, String master_filename, String prefix_name, byte[] file_buff, String file_ext_name, NameValuePair[] meta_list) throws Exception{
        StorageClient client = clientPool.getStorageClient();
        ObjectNode message = new ObjectMapper().createObjectNode();
        try {
            TrackerServer trackerServer = clientPool.getTrackerServer();
            String[] results = client.upload_file(group_name,master_filename,prefix_name,file_buff, file_ext_name, meta_list);
            if (results != null) {
                String fileId;
                int ts;
                String token;
                String fileURl;
                InetSocketAddress socketAddress;
                String groupName = results[0];
                String remoteFile = results[1];
                message.put(GroupField, groupName);
                message.put(RemoteFileField, remoteFile);
                fileId = groupName + StorageClient1.SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR + remoteFile;
                message.put(FileIdField, fileId);
                socketAddress = trackerServer.getInetSocketAddress();
                fileURl = "http://" + socketAddress.getAddress().getHostAddress();
                if (ClientGlobal.g_tracker_http_port != 80) {
                    fileURl += ":" + ClientGlobal.g_tracker_http_port;
                }
                fileURl += "/" + fileId;
                if (ClientGlobal.g_anti_steal_token) {
                    ts = (int) (System.currentTimeMillis() / 1000);
                    token = ProtoCommon.getToken(fileId, ts, ClientGlobal.g_secret_key);
                    fileURl += "?token=" + token + "&ts=" + ts;
                }
                message.put(FileUrlField, fileURl);
                System.out.print(client.get_file_info(groupName, remoteFile).toString());
            }
        } finally {
            clientPool.releaseStorageClient(client);
        }
        return message;
    }
    /**
     * 上传本地文件
     * ObjectNode  a = FileUtil.upload("C://Desert.jpg", "沙漠");
     * System.out.println(a.toString());
     *
     * @param fileName    本地文件的绝对路径,如 C://Desert.jpg
     * @param description 文件备注, 可以为空
     * @return {"groupName":"group1","remoteFileName":"/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg"
     * {
     * "groupName": "healthArchiveGroup",
     * "remoteFileName": "/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg",
     * "fid": "group1/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg",
     * "fileURL": "http://172.19.103.13/healthArchiveGroup/M00/00/24/rBFuH1XdQC6AP3CDAAzodQCbVVc052.jpg"
     * }
     * <p>
     * groupName 及 remoteFileName 可以用于查询在 fastDFS 中文件的信息,如果只是图片显示,可以忽略这两个值。
     * fid 保存了在 fastDFS 上的完整路径,为了避免将来服务器域名发生变更,最好使用本值.服务器的域名另外配置。
     * fileURL 保存了完整的 web 访问路径,为了避免将来服务器域名发生变更,最好不要直接使用本值。
     * 如果需要在下载时,可以显示原始文件名,请在访问file_url时,增加 attname 参数,如:
     * <p>
     * http://host/healthArchiveGroup/M00/00/00/rBFuH1XdIseAUTZZAA1rIuRd3Es062.jpg?attname=a.jpg
     * @throws Exception
     */
    public ObjectNode upload(String fileName, String description) throws Exception {
        StorageClient client = clientPool.getStorageClient();
        try {
            NameValuePair[] fileMetaData;
            fileMetaData = new NameValuePair[1];
            fileMetaData[0] = new NameValuePair("description", description == null ? "" : description);
//            ObjectMapper objectMapper = SpringContext.getService(ObjectMapper.class);
            ObjectNode message = new ObjectMapper().createObjectNode();
            String fileExtension = "";
            if (fileName.contains(".")) {
                fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
            } else {
                throw new RuntimeException("上传失败, 文件缺失扩展名.");
            }
            TrackerServer trackerServer = clientPool.getTrackerServer();
            String[] results = client.upload_file(fileName, fileExtension, fileMetaData);
            if (results != null) {
                String fileId;
                int ts;
                String token;
                String fileUrl;
                InetSocketAddress inetSockAddr;
                String groupName = results[0];
                String remoteFileName = results[1];
                message.put(GroupField, groupName);
                message.put(RemoteFileField, remoteFileName);
                fileId = groupName + StorageClient1.SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR + remoteFileName;
                message.put(FileIdField, fileId);
                inetSockAddr = trackerServer.getInetSocketAddress();
                fileUrl = "http://" + inetSockAddr.getAddress().getHostAddress();
                if (ClientGlobal.g_tracker_http_port != 80) {
                    fileUrl += ":" + ClientGlobal.g_tracker_http_port;
                }
                fileUrl += "/" + fileId;
                if (ClientGlobal.g_anti_steal_token) {
                    ts = (int) (System.currentTimeMillis() / 1000);
                    token = ProtoCommon.getToken(fileId, ts, ClientGlobal.g_secret_key);
                    fileUrl += "?token=" + token + "&ts=" + ts;
                }
                message.put(FileUrlField, fileUrl);
                logger.info(client.get_file_info(groupName, remoteFileName).toString());
                return message;
            } else {
                return null;
            }
        } finally {
            clientPool.releaseStorageClient(client);
        }
    }
    /**
     * 下载文件, 返回文件字节数组.
     *
     * @param groupName      在fastdfs上的卷名
     * @param remoteFileName 在fastdfs上的路径
     * @return 文件的字节码
     * @throws Exception
     */
    public byte[] download(String groupName, String remoteFileName) throws Exception {
        StorageClient client = clientPool.getStorageClient();
        try {
            byte[] b = client.download_file(groupName, remoteFileName);
            return b;
        } finally {
            clientPool.releaseStorageClient(client);
        }
    }
    /**
     * 下载文件到本地路径上.
     *
     * @param groupName      在 fastDFS 上的卷名
     * @param remoteFileName 在 fastDFS 上的路径
     * @param localPath      本地路径
     * @return 是否下载成功
     */
    public String download(String groupName, String remoteFileName, String localPath) throws Exception {
        StorageClient client = clientPool.getStorageClient();
        try {
            String localFileName = localPath + remoteFileName.replaceAll("/", "_");
            client.download_file(groupName, remoteFileName, 0, 0, localFileName);
            return localFileName;
        } finally {
            clientPool.releaseStorageClient(client);
        }
    }
    /**
     * 删除文件。
     *
     * @param groupName
     * @param remoteFileName
     */
    public void delete(String groupName, String remoteFileName) throws Exception {
        StorageClient client = clientPool.getStorageClient();
        try {
            client.delete_file(groupName, remoteFileName);
        } finally {
            clientPool.releaseStorageClient(client);
        }
    }
}

+ 61 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/model/AccessToken.java

@ -0,0 +1,61 @@
package com.yihu.hos.web.framework.model;
/**
 * Created by hzp on 2017/3/28.
 */
public class AccessToken {
    private String accessToken;
    private String refreshToken;
    private String tokenType;
    private String user;
    private String userId;
    private int expiresIn;
    public String getTokenType() {
        return tokenType;
    }
    public void setTokenType(String tokenType) {
        this.tokenType = tokenType;
    }
    public String getAccessToken() {
        return accessToken;
    }
    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }
    public String getRefreshToken() {
        return refreshToken;
    }
    public void setRefreshToken(String refreshToken) {
        this.refreshToken = refreshToken;
    }
    public int getExpiresIn() {
        return expiresIn;
    }
    public void setExpiresIn(int expiresIn) {
        this.expiresIn = expiresIn;
    }
    public String getUser() {
        return user;
    }
    public void setUser(String user) {
        this.user = user;
    }
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
}

+ 33 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/model/ActionResult.java

@ -0,0 +1,33 @@
package com.yihu.hos.web.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 static ActionResult error(String message) {
        ActionResult re= new ActionResult();
        re.successFlg = false;
        re.message = message;
        return re;
    }
    public ActionResult(boolean successFlg,String message){
        super.setSuccessFlg(successFlg);
        super.setMessage(message);
    }
}

+ 124 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/model/DataGridResult.java

@ -0,0 +1,124 @@
package com.yihu.hos.web.framework.model;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.hos.core.log.Logger;
import com.yihu.hos.core.log.LoggerFactory;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
/**
 * 列表对象
 */
public class DataGridResult extends Result implements Serializable {
    private static final Logger logger = LoggerFactory.getLogger(DataGridResult.class);
    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;
    }
    /**
     * Json�ַ���תʵ��
     *
     * @return
     */
    public static DataGridResult fromJson(String json) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(json, DataGridResult.class);
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        return null;
    }
    public String toJson() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage());
            return "";
        }
    }
    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 int getTotalCount() {
        if (totalCount == 0 && detailModelList != null) {
            totalCount = detailModelList.size();
        }
        return totalCount;
    }
    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }
    public List getDetailModelList() {
        return detailModelList;
    }
    public void setDetailModelList(List detailModelList) {
        this.detailModelList = detailModelList;
    }
}

+ 102 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/model/DetailModelResult.java

@ -0,0 +1,102 @@
package com.yihu.hos.web.framework.model;
import java.io.Serializable;
import java.util.List;
public class DetailModelResult extends Result implements Serializable{
	private static final long serialVersionUID = 2076324875575488461L;
	private int pageSize = 10;
	private int currPage;
	private int totalPage;
	private int totalCount;
	private List detailModelList;
	private Object obj;
	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 Object getObj() {
		return obj;
	}
	public void setObj(Object obj) {
		this.obj = obj;
	}
	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 static DetailModelResult success(String message) {
		DetailModelResult detailModelResult = new DetailModelResult();
		detailModelResult.setSuccessFlg(true);
		detailModelResult.setMessage(message);
		return detailModelResult;
	}
	public static DetailModelResult error(String message) {
		DetailModelResult detailModelResult = new DetailModelResult();
		detailModelResult.setSuccessFlg(false);
		detailModelResult.setMessage(message);
		return detailModelResult;
	}
	public int getTotalCount() {
		return totalCount;
	}
	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}
	public List getDetailModelList() {
		return detailModelList;
	}
	public void setDetailModelList(List detailModelList) {
		this.detailModelList = detailModelList;
	}
}

+ 37 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/model/DictItem.java

@ -0,0 +1,37 @@
package com.yihu.hos.web.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;
    }
}

+ 54 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/model/DictionaryResult.java

@ -0,0 +1,54 @@
package com.yihu.hos.web.framework.model;
import java.io.Serializable;
import java.util.List;
/**
 * 返回字典对象
 * Created by chenweida on 2016/1/13.
 */
public class DictionaryResult extends Result implements Serializable {
    private String name;
    private List<DictItem> detailModelList;
    public DictionaryResult()
    {}
    public static DictionaryResult success(String message) {
        DictionaryResult dictionaryResult = new DictionaryResult();
        dictionaryResult.setSuccessFlg(true);
        dictionaryResult.setMessage(message);
        return dictionaryResult;
    }
    public static DictionaryResult error(String message) {
        DictionaryResult dictionaryResult = new DictionaryResult();
        dictionaryResult.setSuccessFlg(false);
        dictionaryResult.setMessage(message);
        return 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;
    }
}

+ 118 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/model/Envelop.java

@ -0,0 +1,118 @@
package com.yihu.hos.web.framework.model;
import java.io.Serializable;
import java.util.List;
/**
 * 信封对象,封装REST接口的返回值内容。包括:
 * - 页码
 * - 页大小
 * - 错误消息
 * - 错误代码
 * - 对象模型
 *
 * 信封对象的返回场景:
 * - API使用者确实无法访问返回头,即一些语言库无法处理HTTP的响应消息,这时候需要以这种形式提供返回值。
 * - API需要支持交叉域请求(通过JSONP)。
 *
 * @author llh
 */
public class Envelop implements Serializable{
    private static final long serialVersionUID = 2076324875575488461L;
    private boolean successFlg;
    private int pageSize = 10;
    private int currPage;
    private int totalPage;
    private int totalCount;
    private List detailModelList;
    private Object obj;
    private String errorMsg;
    private int errorCode;
    public Object getObj() {
        return obj;
    }
    public void setObj(Object obj) {
        this.obj = obj;
    }
    public int getTotalCount() {
        return totalCount;
    }
    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }
    public boolean isSuccessFlg() {
        return successFlg;
    }
    public void setSuccessFlg(boolean successFlg) {
        this.successFlg = successFlg;
    }
    public List getDetailModelList() {
        return detailModelList;
    }
    public void setDetailModelList(List detailModelList) {
        this.detailModelList = detailModelList;
    }
    public String getErrorMsg() {
        return errorMsg;
    }
    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }
    public int getErrorCode() {
        return errorCode;
    }
    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }
    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;
    }
}

+ 0 - 0
hos-web-framework/src/main/java/com/yihu/hos/web/framework/model/EnvelopExt.java


Some files were not shown because too many files changed in this diff