first commit

This commit is contained in:
circle xing 2024-07-03 19:49:48 +08:00
parent 6e6f4f1e75
commit f30e06da33
627 changed files with 69831 additions and 0 deletions

52
health_common/.project Normal file
View File

@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>health_common</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.genuitec.eclipse.j2eedt.core.DeploymentDescriptorValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.genuitec.eclipse.springframework.springbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.boot.validation.springbootbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.genuitec.eclipse.springframework.springnature</nature>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
</natures>
</projectDescription>

152
health_common/pom.xml Normal file
View File

@ -0,0 +1,152 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>cn.health.service</groupId>
<artifactId>health-parent</artifactId>
<version>1.0.2</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>health_common</artifactId>
<name>health_common</name>
<url>http://maven.apache.org</url>
<!-- <packaging>jar</packaging> -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>utf-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<!-- <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId>
<scope>test</scope> </dependency> -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<!-- <version>1.2.37</version> -->
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<!-- <version>5.1.7.RELEASE</version> -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<!-- <version>3.1</version> -->
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<!-- <version>4.0.1</version> -->
<!-- <scope>provided</scope> -->
</dependency>
<!--<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<!-- <version>4.3.2</version> -->
</dependency>
<!-- <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId>
</dependency> -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<!-- <version>1.6.1</version> -->
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<!-- <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId>
</dependency> -->
<!-- <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-ui</artifactId>
<version>2.0.8</version> </dependency> -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<!-- mybatis分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<!-- <version>1.3.0</version> -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId>
<exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId>
</exclusion> </exclusions> </dependency> -->
<!-- <dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency> -->
<!-- pool 对象池 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.bouncycastle</groupId>-->
<!-- <artifactId>bcprov-jdk15on</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,117 @@
package cn.card.health.bean.hospital;
import java.io.Serializable;
import java.util.Date;
/**
* 医院信息表
*
* @author xinggm
* @email
* @date 2021-08-16 10:07:33
*/
public class YcHospital implements Serializable {
private static final long serialVersionUID = 1L;
/** 医院主键 */
private Long hospid;
/** 医院名称 */
private String hospname;
/** 腾讯健康医院标识 */
private String wechathospid;
/** his医院编码 */
private String hospcode;
/** */
private Integer delFlag;
/** 创建时间 */
private Date createtime;
/** 创建人 */
private String createby;
/** 修改时间 */
private Date updatetime;
/** 修改人 */
private String updateby;
public Long getHospid() {
return hospid;
}
public void setHospid(Long hospid) {
this.hospid = hospid;
}
public String getHospname() {
return hospname;
}
public void setHospname(String hospname) {
this.hospname = hospname;
}
public String getWechathospid() {
return wechathospid;
}
public void setWechathospid(String wechathospid) {
this.wechathospid = wechathospid;
}
public String getHospcode() {
return hospcode;
}
public void setHospcode(String hospcode) {
this.hospcode = hospcode;
}
public Integer getDelFlag() {
return delFlag;
}
public void setDelFlag(Integer delFlag) {
this.delFlag = delFlag;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getCreateby() {
return createby;
}
public void setCreateby(String createby) {
this.createby = createby;
}
public Date getUpdatetime() {
return updatetime;
}
public void setUpdatetime(Date updatetime) {
this.updatetime = updatetime;
}
public String getUpdateby() {
return updateby;
}
public void setUpdateby(String updateby) {
this.updateby = updateby;
}
}

View File

@ -0,0 +1,193 @@
package cn.card.health.bean.hospital;
import com.alibaba.fastjson.JSONObject;
import sun.applet.Main;
import java.io.Serializable;
/**
* HIS病人健康卡对照表
*
* @author xinggm
* @email
* @date 2021-07-14 09:05:22
*/
public class YcPatient implements Serializable {
private static final long serialVersionUID = 1L;
/** 主键 */
private Long patientid;
/** 患者姓名 */
private String patientName;
/** 患者性别 */
private String patientSex;
/** */
private String oppatno;
/** HIS卡号 */
private String hiscardno;
/** 卡号 */
private String cardno;
/** 卡类型 */
private String cardtype;
/** 手机号 */
private String phone;
/** 家庭住址 */
private String address;
/** 微信健康卡主键 */
private String cardid;
/** 医院主键 */
private Long hospid;
/** 医院标志 */
private String hisid;
/** openid */
private String openid;
/** 渠道 */
private String channel;
/** 是否新用户 */
private String isnew;
/** 删除标志 */
private Integer delFlag;
public YcPatient() {
}
public static YcPatient getInstance(JSONObject params){
YcPatient patient = new YcPatient();
patient.patientName = params.getString("name");
patient.cardno = params.getString("idcard");
patient.address = params.getString("address");
patient.phone = params.getString("phone");
patient.patientSex = params.getString("sex");
patient.channel = params.getString("nation");
// patient.isnew = params.getString("")
return patient;
}
public Long getPatientid() {
return patientid;
}
public void setPatientid(Long patientid) {
this.patientid = patientid;
}
public String getPatientName() {
return patientName;
}
public String getPatientSex() {
return patientSex;
}
public void setPatientSex(String patientSex) {
this.patientSex = patientSex;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
public String getHisid() {
return hisid;
}
public void setHisid(String hisid) {
this.hisid = hisid;
}
public String getOppatno() {
return oppatno;
}
public void setOppatno(String oppatno) {
this.oppatno = oppatno;
}
public String getHiscardno() {
return hiscardno;
}
public void setHiscardno(String hiscardno) {
this.hiscardno = hiscardno;
}
public String getCardno() {
return cardno;
}
public void setCardno(String cardno) {
this.cardno = cardno;
}
public String getCardtype() {
return cardtype;
}
public void setCardtype(String cardtype) {
this.cardtype = cardtype;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCardid() {
return cardid;
}
public void setCardid(String cardid) {
this.cardid = cardid;
}
public Long getHospid() {
return hospid;
}
public void setHospid(Long hospid) {
this.hospid = hospid;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getChannel() {
return channel;
}
public void setChannel(String channel) {
this.channel = channel;
}
public String getIsnew() {
return isnew;
}
public void setIsnew(String isnew) {
this.isnew = isnew;
}
public Integer getDelFlag() {
return delFlag;
}
public void setDelFlag(Integer delFlag) {
this.delFlag = delFlag;
}
}

View File

@ -0,0 +1,195 @@
package cn.card.health.bean.user;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.Set;
public class LoginUser implements UserDetails {
private static final long serialVersionUID = 1L;
private String username;
/**
* 用户唯一标识
*/
private String token;
/**
* 医院配置
*/
private String hisid;
/**
* 登录时间
*/
private Long loginTime;
/**
* 过期时间
*/
private Long expireTime;
/**
* 微信登录专用
*/
private String code;
/**
* 平台
*/
private String platform;
private Long userid;
/**
* 用户
*/
private YcUser user;
/**
* 医院id
*/
private Long hospitalid;
public LoginUser(YcUser user) {
this.user = user;
}
public LoginUser() {
}
public LoginUser(Long userid, Long deptId, YcUser user, Set<String> permissions)
{
this.userid = userid;
// this.deptId = deptId;
this.user = user;
// this.permissions = permissions;
}
public LoginUser(Long userid, YcUser user)
{
this.userid = userid;
this.user = user;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public String getPassword() {
return null;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return false;
}
@Override
public boolean isAccountNonLocked() {
return false;
}
@Override
public boolean isCredentialsNonExpired() {
return false;
}
@Override
public boolean isEnabled() {
return false;
}
public void setUsername(String username) {
this.username = username;
}
public Long getLoginTime() {
return loginTime;
}
public void setLoginTime(Long loginTime) {
this.loginTime = loginTime;
}
public Long getExpireTime() {
return expireTime;
}
public void setExpireTime(Long expireTime) {
this.expireTime = expireTime;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public YcUser getUser() {
return user;
}
public void setUser(YcUser user) {
this.user = user;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getHisid() {
return hisid;
}
public void setHisid(String hisid) {
this.hisid = hisid;
}
public Long getHospitalid() {
return hospitalid;
}
public void setHospitalid(Long hospitalid) {
this.hospitalid = hospitalid;
}
public Long getUserid() {
return userid;
}
public void setUserid(Long userid) {
this.userid = userid;
}
@Override
public String toString() {
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.writeValueAsString(this);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
}

View File

@ -0,0 +1,51 @@
package cn.card.health.bean.user;
import java.io.Serializable;
import java.util.Date;
/**
* 授权表
*
* @author xinggm
* @email
* @date 2021-08-30 17:59:54
*/
public class YcAuthority implements Serializable {
private static final long serialVersionUID = 1L;
/** 主键 */
private Long authorityid;
/** 权限 */
private String authority;
/** 备注 */
private String remark;
public Long getAuthorityid() {
return authorityid;
}
public void setAuthorityid(Long authorityid) {
this.authorityid = authorityid;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}

View File

@ -0,0 +1,327 @@
package cn.card.health.bean.user;
import java.io.Serializable;
import java.util.Date;
/**
* 住院病人信息
*
* @author user
* @email
* @date 2021-09-06 09:02:37
*/
public class YcInhospPatient implements Serializable {
private static final long serialVersionUID = 1L;
/** */
private Long patientid;
/** 用户主键 */
private Long userid;
/** 第三方标志 */
private String openid;
/** 医院标志 */
private Long hospid;
/** 患者主索引 */
private String patid;
/** 住院病人id */
private String ippatid;
/** 住院病人号 */
private String ippatno;
/** 身份证号 */
private String idcardno;
/** 卡类型 */
private String cardtype;
/** 患者诊疗卡号 */
private String patmedno;
/** 患者姓名 */
private String patname;
/** HIS当前住院就诊流水号 */
private String visitid;
/** 性别 */
private String patsex;
/** 生日 */
private String birthday;
/** 手机号 */
private String phone;
/** 家庭住址 */
private String address;
/** 人员 */
private String contactperson;
/** 关系 */
private String contactrelation;
/** 手机号 */
private String contactphone;
/** 区域名称 */
private String areaname;
/** 床号 */
private String bedno;
/** 入住日期 */
private String admitdate;
/** 总金额 */
private Long totalamount;
/** */
private String totaldeposit;
/** 金额 */
private Long closedamount;
/** */
private String uncovereddeposit;
/** 状态 */
private String patstate;
/** HIS医院标志 */
private String hospitalid;
/** 删除标志 */
private Integer delFlag;
/** 创建时间 */
private Date createtime;
/** 创建人 */
private String createby;
public Long getPatientid() {
return patientid;
}
public void setPatientid(Long patientid) {
this.patientid = patientid;
}
public Long getHospid() {
return hospid;
}
public void setHospid(Long hospid) {
this.hospid = hospid;
}
public String getPatid() {
return patid;
}
public void setPatid(String patid) {
this.patid = patid;
}
public String getIppatid() {
return ippatid;
}
public void setIppatid(String ippatid) {
this.ippatid = ippatid;
}
public String getIppatno() {
return ippatno;
}
public void setIppatno(String ippatno) {
this.ippatno = ippatno;
}
public String getIdcardno() {
return idcardno;
}
public void setIdcardno(String idcardno) {
this.idcardno = idcardno;
}
public String getCardtype() {
return cardtype;
}
public void setCardtype(String cardtype) {
this.cardtype = cardtype;
}
public String getPatmedno() {
return patmedno;
}
public void setPatmedno(String patmedno) {
this.patmedno = patmedno;
}
public String getPatname() {
return patname;
}
public void setPatname(String patname) {
this.patname = patname;
}
public Long getUserid() {
return userid;
}
public void setUserid(Long userid) {
this.userid = userid;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getVisitid() {
return visitid;
}
public void setVisitid(String visitid) {
this.visitid = visitid;
}
public String getPatsex() {
return patsex;
}
public void setPatsex(String patsex) {
this.patsex = patsex;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContactperson() {
return contactperson;
}
public void setContactperson(String contactperson) {
this.contactperson = contactperson;
}
public String getContactrelation() {
return contactrelation;
}
public void setContactrelation(String contactrelation) {
this.contactrelation = contactrelation;
}
public String getContactphone() {
return contactphone;
}
public void setContactphone(String contactphone) {
this.contactphone = contactphone;
}
public String getAreaname() {
return areaname;
}
public void setAreaname(String areaname) {
this.areaname = areaname;
}
public String getBedno() {
return bedno;
}
public void setBedno(String bedno) {
this.bedno = bedno;
}
public String getAdmitdate() {
return admitdate;
}
public void setAdmitdate(String admitdate) {
this.admitdate = admitdate;
}
public Long getTotalamount() {
return totalamount;
}
public void setTotalamount(Long totalamount) {
this.totalamount = totalamount;
}
public String getTotaldeposit() {
return totaldeposit;
}
public void setTotaldeposit(String totaldeposit) {
this.totaldeposit = totaldeposit;
}
public Long getClosedamount() {
return closedamount;
}
public void setClosedamount(Long closedamount) {
this.closedamount = closedamount;
}
public String getUncovereddeposit() {
return uncovereddeposit;
}
public void setUncovereddeposit(String uncovereddeposit) {
this.uncovereddeposit = uncovereddeposit;
}
public String getPatstate() {
return patstate;
}
public void setPatstate(String patstate) {
this.patstate = patstate;
}
public String getHospitalid() {
return hospitalid;
}
public void setHospitalid(String hospitalid) {
this.hospitalid = hospitalid;
}
public Integer getDelFlag() {
return delFlag;
}
public void setDelFlag(Integer delFlag) {
this.delFlag = delFlag;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getCreateby() {
return createby;
}
public void setCreateby(String createby) {
this.createby = createby;
}
}

View File

@ -0,0 +1,87 @@
package cn.card.health.bean.user;
import java.io.Serializable;
import java.util.Date;
/**
* 用户表
*
* @author xinggm
* @email
* @date 2021-08-24 15:41:43
*/
public class YcOAuth implements Serializable {
private static final long serialVersionUID = 1L;
/** 主键 */
private Long authid;
/** 用户主键 */
private Long userid;
/** 授权类型 */
private String authType;
/** APPID */
private String appid;
/** 微信openid */
private String openid;
/** 创建时间 */
private Date createtime;
/** 修改时间 */
private Date updatetime;
public Long getAuthid() {
return authid;
}
public void setAuthid(Long authid) {
this.authid = authid;
}
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public Long getUserid() {
return userid;
}
public void setUserid(Long userid) {
this.userid = userid;
}
public String getAuthType() {
return authType;
}
public void setAuthType(String authType) {
this.authType = authType;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public Date getUpdatetime() {
return updatetime;
}
public void setUpdatetime(Date updatetime) {
this.updatetime = updatetime;
}
}

View File

@ -0,0 +1,145 @@
package cn.card.health.bean.user;
import java.io.Serializable;
import java.util.Date;
/**
* 用户表
*
* @author xinggm
* @email
* @date 2021-08-28 10:47:55
*/
public class YcUser implements Serializable {
private static final long serialVersionUID = 1L;
/** 主键 */
private Long userid;
/** 用户名 */
private String username;
/** 用户类型 */
private String userType;
/** 激活码 */
private String activeKey;
/** 是否可用 */
private boolean isActivated;
/** 密码 */
private String password;
/** 手机号 */
private String phonenum;
/** 邮件 */
private String email;
/** 创建时间 */
private Date createtime;
/** 更新时间 */
private Date updatetime;
/** 说明 */
private String remark;
/** 授权 */
private YcOAuth auth;
public YcOAuth getAuth() {
return auth;
}
public void setAuth(YcOAuth auth) {
this.auth = auth;
}
public Long getUserid() {
return userid;
}
public void setUserid(Long userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public String getActiveKey() {
return activeKey;
}
public void setActiveKey(String activeKey) {
this.activeKey = activeKey;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhonenum() {
return phonenum;
}
public boolean isActivated() {
return isActivated;
}
public void setActivated(boolean isActivated) {
this.isActivated = isActivated;
}
public void setPhonenum(String phonenum) {
this.phonenum = phonenum;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public Date getUpdatetime() {
return updatetime;
}
public void setUpdatetime(Date updatetime) {
this.updatetime = updatetime;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Override
public String toString() {
return "YcUser [userid=" + userid + ", username=" + username + ", userType=" + userType + ", activeKey="
+ activeKey + ", isActivated=" + isActivated + ", password=" + password + ", phonenum=" + phonenum
+ ", email=" + email + ", createtime=" + createtime + ", updatetime=" + updatetime + ", remark="
+ remark + ", auth=" + auth + "]";
}
}

View File

@ -0,0 +1,139 @@
package cn.card.health.common.constant;
/**
* 通用常量信息
*
* @author yc
*/
public class Constants {
/**
* UTF-8 字符集
*/
public static final String UTF8 = "UTF-8";
/**
* GBK 字符集
*/
public static final String GBK = "GBK";
/**
* http请求
*/
public static final String HTTP = "http://";
/**
* https请求
*/
public static final String HTTPS = "https://";
/**
* 通用成功标识
*/
public static final String SUCCESS = "0";
/**
* 通用失败标识
*/
public static final String FAIL = "1";
/**
* 登录成功
*/
public static final String LOGIN_SUCCESS = "Success";
/**
* 注销
*/
public static final String LOGOUT = "Logout";
/**
* 登录失败
*/
public static final String LOGIN_FAIL = "Error";
/**
* 验证码 redis key
*/
public static final String CAPTCHA_CODE_KEY = "captcha_codes:";
/**
* 登录用户 redis key
*/
public static final String LOGIN_TOKEN_KEY = "login_tokens:";
/**
* 防重提交 redis key
*/
public static final String REPEAT_SUBMIT_KEY = "repeat_submit:";
/**
* 验证码有效期分钟
*/
public static final Integer CAPTCHA_EXPIRATION = 2;
/**
* 令牌
*/
public static final String TOKEN = "token";
/**
* 令牌前缀
*/
public static final String TOKEN_PREFIX = "yc_health ";
/**
* 令牌前缀
*/
public static final String LOGIN_USER_KEY = "login_user_key";
/**
* 用户ID
*/
public static final String JWT_USERID = "userid";
/**
* 用户名称
*/
public static final String JWT_USERNAME = "sub";
/**
* 用户头像
*/
public static final String JWT_AVATAR = "avatar";
/**
* 创建时间
*/
public static final String JWT_CREATED = "created";
/**
* 用户权限
*/
public static final String JWT_AUTHORITIES = "authorities";
/**
* 参数管理 cache key
*/
public static final String SYS_CONFIG_KEY = "sys_config:";
/**
* 字典管理 cache key
*/
public static final String SYS_DICT_KEY = "sys_dict:";
/**
* 医院类 cache key
*/
public static final String HOSP_KEY = "hosp_key_";
/**
* 资源映射路径 前缀
*/
public static final String RESOURCE_PREFIX = "/profile";
/** 是否腾讯用户 */
public static final String PATIENT_ISQQ = "PATIENT_ISQQ";
/** 服务地址 */
// public static final String SERVER_URL = "https://zhyy.bjbhkj.top";// TODO 正式服务地址
public static final String SERVER_URL = "https://www.hbyctr.com";
}

View File

@ -0,0 +1,26 @@
package cn.card.health.common.core;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextUtil.applicationContext = applicationContext;
}
public static <T> T getBean(String beanName) {
return (T) applicationContext.getBean(beanName);
}
}

View File

@ -0,0 +1,120 @@
package cn.card.health.common.core;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import cn.card.health.common.utils.Convert;
import cn.card.health.common.utils.StringUtils;
/**
* 客户端工具类
*
* @author yc
*/
public class ServletUtils {
/**
* 获取String参数
*/
public static String getParameter(String name) {
return getRequest().getParameter(name);
}
/**
* 获取String参数
*/
public static String getParameter(String name, String defaultValue) {
return Convert.toStr(getRequest().getParameter(name), defaultValue);
}
/**
* 获取Integer参数
*/
public static Integer getParameterToInt(String name) {
return Convert.toInt(getRequest().getParameter(name));
}
/**
* 获取Integer参数
*/
public static Integer getParameterToInt(String name, Integer defaultValue) {
return Convert.toInt(getRequest().getParameter(name), defaultValue);
}
/**
* 获取request
*/
public static HttpServletRequest getRequest() {
return getRequestAttributes().getRequest();
}
/**
* 获取response
*/
public static HttpServletResponse getResponse() {
return getRequestAttributes().getResponse();
}
/**
* 获取session
*/
public static HttpSession getSession() {
return getRequest().getSession();
}
public static ServletRequestAttributes getRequestAttributes() {
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
return (ServletRequestAttributes) attributes;
}
/**
* 将字符串渲染到客户端
*
* @param response 渲染对象
* @param string 待渲染的字符串
* @return null
*/
public static String renderString(HttpServletResponse response, String string) {
try {
response.setStatus(200);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().print(string);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 是否是Ajax异步请求
*
* @param request
*/
public static boolean isAjaxRequest(HttpServletRequest request) {
String accept = request.getHeader("accept");
if (accept != null && accept.indexOf("application/json") != -1) {
return true;
}
String xRequestedWith = request.getHeader("X-Requested-With");
if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) {
return true;
}
String uri = request.getRequestURI();
if (StringUtils.inStringIgnoreCase(uri, ".json", ".xml")) {
return true;
}
String ajax = request.getParameter("__ajax");
if (StringUtils.inStringIgnoreCase(ajax, "json", "xml")) {
return true;
}
return false;
}
}

View File

@ -0,0 +1,38 @@
package cn.card.health.common.core;
import cn.card.health.common.utils.StringUtils;
/**
* sql操作工具类
*
* @author yc
*/
public class SqlUtil
{
/**
* 仅支持字母数字下划线空格逗号小数点支持多个字段排序
*/
public static String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,\\.]+";
/**
* 检查字符防止注入绕过
*/
public static String escapeOrderBySql(String value)
{
if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value))
{
//TODO 抛出异常
return null;
// throw new BaseException("参数不符合规范,不能进行查询");
}
return value;
}
/**
* 验证 order by 语法是否符合规范
*/
public static boolean isValidOrderBySql(String value)
{
return value.matches(SQL_PATTERN);
}
}

View File

@ -0,0 +1,5 @@
package cn.card.health.common.enums;
public enum EnumMethod {
GET, POST;
}

View File

@ -0,0 +1,97 @@
package cn.card.health.common.exception.base;
import cn.card.health.common.utils.MessageUtils;
import cn.card.health.common.utils.StringUtils;
/**
* 基础异常
*
* @author ruoyi
*/
public class BaseException extends RuntimeException
{
private static final long serialVersionUID = 1L;
/**
* 所属模块
*/
private String module;
/**
* 错误码
*/
private String code;
/**
* 错误码对应的参数
*/
private Object[] args;
/**
* 错误消息
*/
private String defaultMessage;
public BaseException(String module, String code, Object[] args, String defaultMessage)
{
this.module = module;
this.code = code;
this.args = args;
this.defaultMessage = defaultMessage;
}
public BaseException(String module, String code, Object[] args)
{
this(module, code, args, null);
}
public BaseException(String module, String defaultMessage)
{
this(module, null, null, defaultMessage);
}
public BaseException(String code, Object[] args)
{
this(null, code, args, null);
}
public BaseException(String defaultMessage)
{
this(null, null, null, defaultMessage);
}
@Override
public String getMessage()
{
String message = null;
if (!StringUtils.isEmpty(code))
{
message = MessageUtils.message(code, args);
}
if (message == null)
{
message = defaultMessage;
}
return message;
}
public String getModule()
{
return module;
}
public String getCode()
{
return code;
}
public Object[] getArgs()
{
return args;
}
public String getDefaultMessage()
{
return defaultMessage;
}
}

View File

@ -0,0 +1,73 @@
package cn.card.health.common.exception.base;
/**
* 业务异常
*
* @author ruoyi
*/
public final class ServiceException extends RuntimeException
{
private static final long serialVersionUID = 1L;
/**
* 错误码
*/
private Integer code;
/**
* 错误提示
*/
private String message;
/**
* 错误明细内部调试错误
*
* {@link CommonResult#getDetailMessage()} 一致的设计
*/
private String detailMessage;
/**
* 空构造方法避免反序列化问题
*/
public ServiceException()
{
}
public ServiceException(String message)
{
this.message = message;
}
public ServiceException(String message, Integer code)
{
this.message = message;
this.code = code;
}
public String getDetailMessage()
{
return detailMessage;
}
public String getMessage()
{
return message;
}
public Integer getCode()
{
return code;
}
public ServiceException setMessage(String message)
{
this.message = message;
return this;
}
public ServiceException setDetailMessage(String detailMessage)
{
this.detailMessage = detailMessage;
return this;
}
}

View File

@ -0,0 +1,72 @@
package cn.card.health.common.page;
import cn.card.health.common.utils.StringUtils;
/**
* 分页数据
*
* @author yc
*/
public class PageDomain
{
/** 当前记录起始索引 */
private Integer pageNum;
/** 每页显示记录数 */
private Integer pageSize;
/** 排序列 */
private String orderByColumn;
/** 排序的方向desc或者asc */
private String isAsc = "asc";
public String getOrderBy()
{
if (StringUtils.isEmpty(orderByColumn))
{
return "";
}
return StringUtils.toUnderScoreCase(orderByColumn) + " " + isAsc;
}
public Integer getPageNum()
{
return pageNum;
}
public void setPageNum(Integer pageNum)
{
this.pageNum = pageNum;
}
public Integer getPageSize()
{
return pageSize;
}
public void setPageSize(Integer pageSize)
{
this.pageSize = pageSize;
}
public String getOrderByColumn()
{
return orderByColumn;
}
public void setOrderByColumn(String orderByColumn)
{
this.orderByColumn = orderByColumn;
}
public String getIsAsc()
{
return isAsc;
}
public void setIsAsc(String isAsc)
{
this.isAsc = isAsc;
}
}

View File

@ -0,0 +1,85 @@
package cn.card.health.common.page;
import java.io.Serializable;
import java.util.List;
/**
* 表格分页数据对象
*
* @author yc
*/
public class TableDataInfo implements Serializable
{
private static final long serialVersionUID = 1L;
/** 总记录数 */
private long total;
/** 列表数据 */
private List<?> rows;
/** 消息状态码 */
private int code;
/** 消息内容 */
private String msg;
/**
* 表格数据对象
*/
public TableDataInfo()
{
}
/**
* 分页
*
* @param list 列表数据
* @param total 总记录数
*/
public TableDataInfo(List<?> list, int total)
{
this.rows = list;
this.total = total;
}
public long getTotal()
{
return total;
}
public void setTotal(long total)
{
this.total = total;
}
public List<?> getRows()
{
return rows;
}
public void setRows(List<?> rows)
{
this.rows = rows;
}
public int getCode()
{
return code;
}
public void setCode(int code)
{
this.code = code;
}
public String getMsg()
{
return msg;
}
public void setMsg(String msg)
{
this.msg = msg;
}
}

View File

@ -0,0 +1,49 @@
package cn.card.health.common.page;
import cn.card.health.common.core.ServletUtils;
/**
* 表格数据处理
*
* @author yc
*/
public class TableSupport
{
/**
* 当前记录起始索引
*/
public static final String PAGE_NUM = "pageNum";
/**
* 每页显示记录数
*/
public static final String PAGE_SIZE = "pageSize";
/**
* 排序列
*/
public static final String ORDER_BY_COLUMN = "orderByColumn";
/**
* 排序的方向 "desc" 或者 "asc".
*/
public static final String IS_ASC = "isAsc";
/**
* 封装分页对象
*/
public static PageDomain getPageDomain()
{
PageDomain pageDomain = new PageDomain();
pageDomain.setPageNum(ServletUtils.getParameterToInt(PAGE_NUM));
pageDomain.setPageSize(ServletUtils.getParameterToInt(PAGE_SIZE));
pageDomain.setOrderByColumn(ServletUtils.getParameter(ORDER_BY_COLUMN));
pageDomain.setIsAsc(ServletUtils.getParameter(IS_ASC));
return pageDomain;
}
public static PageDomain buildPageRequest()
{
return getPageDomain();
}
}

View File

@ -0,0 +1,73 @@
package cn.card.health.common.redis;
import java.nio.charset.Charset;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.util.Assert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
/**
* Redis使用FastJson序列化
*
* @author yc
*/
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T>
{
@SuppressWarnings("unused")
private ObjectMapper objectMapper = new ObjectMapper();
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
static
{
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
}
public FastJson2JsonRedisSerializer(Class<T> clazz)
{
super();
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException
{
if (t == null)
{
return new byte[0];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException
{
if (bytes == null || bytes.length <= 0)
{
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return JSON.parseObject(str, clazz);
}
public void setObjectMapper(ObjectMapper objectMapper)
{
Assert.notNull(objectMapper, "'objectMapper' must not be null");
this.objectMapper = objectMapper;
}
protected JavaType getJavaType(Class<?> clazz)
{
return TypeFactory.defaultInstance().constructType(clazz);
}
}

View File

@ -0,0 +1,51 @@
//package cn.card.health.common.redis;
//
//import java.rmi.UnknownHostException;
//
//import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
//import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
//import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
//import org.springframework.boot.context.properties.EnableConfigurationProperties;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.context.annotation.Import;
//import org.springframework.data.redis.connection.RedisConnectionFactory;
//import org.springframework.data.redis.core.RedisOperations;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.data.redis.core.StringRedisTemplate;
//
//@Configuration
//@ConditionalOnClass(RedisOperations.class)
//@EnableConfigurationProperties(RedisProperties.class)
////@Import({ LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class })
//public class RedisAutoConfiguration {
//
// @Bean
//// @ConditionalOnMissingBean(name = "redisTemplate")
// public RedisTemplate<Object, Object> redisTemplate(
//
// RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
//
// RedisTemplate<Object, Object> template = new RedisTemplate<>();
//
// template.setConnectionFactory(redisConnectionFactory);
//
// return template;
//
// }
//
// @Bean
// @ConditionalOnMissingBean
// public StringRedisTemplate stringRedisTemplate(
//
// RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
//
// StringRedisTemplate template = new StringRedisTemplate();
//
// template.setConnectionFactory(redisConnectionFactory);
//
// return template;
//
// }
//
//}

View File

@ -0,0 +1,234 @@
package cn.card.health.common.redis;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
/**
* spring redis 工具类
*
* @author yc
**/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisCache
{
@Autowired
public RedisTemplate redisTemplate;
/**
* 缓存基本的对象IntegerString实体类等
*
* @param key 缓存的键值
* @param value 缓存的值
*/
public <T> void setCacheObject(final String key, final T value)
{
redisTemplate.opsForValue().set(key, value);
}
/**
* 缓存基本的对象IntegerString实体类等
*
* @param key 缓存的键值
* @param value 缓存的值
* @param timeout 时间
* @param timeUnit 时间颗粒度
*/
public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
{
redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
}
/**
* 设置有效时间
*
* @param key Redis键
* @param timeout 超时时间
* @return true=设置成功false=设置失败
*/
public boolean expire(final String key, final long timeout)
{
return expire(key, timeout, TimeUnit.SECONDS);
}
/**
* 设置有效时间
*
* @param key Redis键
* @param timeout 超时时间
* @param unit 时间单位
* @return true=设置成功false=设置失败
*/
public boolean expire(final String key, final long timeout, final TimeUnit unit)
{
return redisTemplate.expire(key, timeout, unit);
}
/**
* 获得缓存的基本对象
*
* @param key 缓存键值
* @return 缓存键值对应的数据
*/
public <T> T getCacheObject(final String key)
{
ValueOperations<String, T> operation = redisTemplate.opsForValue();
return operation.get(key);
}
/**
* 删除单个对象
*
* @param key
*/
public boolean deleteObject(final String key)
{
return redisTemplate.delete(key);
}
/**
* 删除集合对象
*
* @param collection 多个对象
* @return
*/
public long deleteObject(final Collection collection)
{
return redisTemplate.delete(collection);
}
/**
* 缓存List数据
*
* @param key 缓存的键值
* @param dataList 待缓存的List数据
* @return 缓存的对象
*/
public <T> long setCacheList(final String key, final List<T> dataList)
{
Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
return count == null ? 0 : count;
}
/**
* 获得缓存的list对象
*
* @param key 缓存的键值
* @return 缓存键值对应的数据
*/
public <T> List<T> getCacheList(final String key)
{
return redisTemplate.opsForList().range(key, 0, -1);
}
/**
* 缓存Set
*
* @param key 缓存键值
* @param dataSet 缓存的数据
* @return 缓存数据的对象
*/
public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet)
{
BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
Iterator<T> it = dataSet.iterator();
while (it.hasNext())
{
setOperation.add(it.next());
}
return setOperation;
}
/**
* 获得缓存的set
*
* @param key
* @return
*/
public <T> Set<T> getCacheSet(final String key)
{
return redisTemplate.opsForSet().members(key);
}
/**
* 缓存Map
*
* @param key
* @param dataMap
*/
public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
{
if (dataMap != null) {
redisTemplate.opsForHash().putAll(key, dataMap);
}
}
/**
* 获得缓存的Map
*
* @param key
* @return
*/
public <T> Map<String, T> getCacheMap(final String key)
{
return redisTemplate.opsForHash().entries(key);
}
/**
* 往Hash中存入数据
*
* @param key Redis键
* @param hKey Hash键
* @param value
*/
public <T> void setCacheMapValue(final String key, final String hKey, final T value)
{
redisTemplate.opsForHash().put(key, hKey, value);
}
/**
* 获取Hash中的数据
*
* @param key Redis键
* @param hKey Hash键
* @return Hash中的对象
*/
public <T> T getCacheMapValue(final String key, final String hKey)
{
HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
return opsForHash.get(key, hKey);
}
/**
* 获取多个Hash中的数据
*
* @param key Redis键
* @param hKeys Hash键集合
* @return Hash对象集合
*/
public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
{
return redisTemplate.opsForHash().multiGet(key, hKeys);
}
/**
* 获得缓存的基本对象列表
*
* @param pattern 字符串前缀
* @return 对象列表
*/
public Collection<String> keys(final String pattern)
{
return redisTemplate.keys(pattern);
}
}

View File

@ -0,0 +1,115 @@
package cn.card.health.common.redis;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
/**
* redis配置类
*
* @author ZENG.XIAO.YAN
* @date 2018年6月6日
*
*/
@Configuration
public class RedisConfig {
// @Bean
// @ConfigurationProperties(prefix = "spring.redis.pool")
// public JedisPoolConfig getRedisConfig() {
// JedisPoolConfig config = new JedisPoolConfig();
// return config;
// }
//
// @Bean
// @ConfigurationProperties(prefix = "spring.redis")
// public JedisConnectionFactory getConnectionFactory() {
// JedisConnectionFactory factory = new JedisConnectionFactory();
// factory.setUsePool(true);
// JedisPoolConfig config = getRedisConfig();
// factory.setPoolConfig(config);
// return factory;
// }
//
// @Bean
// public RedisTemplate<?, ?> getRedisTemplate() {
// JedisConnectionFactory factory = getConnectionFactory();
// RedisTemplate<?, ?> template = new StringRedisTemplate(factory);
// return template;
// }
//
// @Bean
// public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// RedisTemplate<Object, Object> template = new RedisTemplate<>();
// template.setConnectionFactory(redisConnectionFactory);
// Jackson2JsonRedisSerializer<Object> ser = new Jackson2JsonRedisSerializer<>(Object.class);
// template.setDefaultSerializer(ser);
// return template;
// }
@Bean
@SuppressWarnings(value = { "unchecked", "rawtypes" })
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
{
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
serializer.setObjectMapper(mapper);
template.setValueSerializer(serializer);
// 使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
// @Bean
// @SuppressWarnings("all")
// public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
//
// RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
//
// template.setConnectionFactory(factory);
//
// Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//
// ObjectMapper om = new ObjectMapper();
//
// om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//
// om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//
// jackson2JsonRedisSerializer.setObjectMapper(om);
//
// StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//
// // key采用String的序列化方式
// template.setKeySerializer(stringRedisSerializer);
//
// // hash的key也采用String的序列化方式
// template.setHashKeySerializer(stringRedisSerializer);
//
// // value序列化方式采用jackson
// template.setValueSerializer(jackson2JsonRedisSerializer);
//
// // hash的value序列化方式采用jackson
// template.setHashValueSerializer(jackson2JsonRedisSerializer);
// template.afterPropertiesSet();
// return template;
// }
}

View File

@ -0,0 +1,49 @@
package cn.card.health.common.redis;
//package cn.card.health.common.redis;
//
//import org.springframework.cache.annotation.CachingConfigurerSupport;
//import org.springframework.cache.annotation.EnableCaching;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.data.redis.connection.RedisConnectionFactory;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.data.redis.serializer.RedisSerializer;
//import org.springframework.data.redis.serializer.StringRedisSerializer;
//
//import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
//import com.fasterxml.jackson.annotation.JsonAutoDetect;
//import com.fasterxml.jackson.annotation.JsonTypeInfo;
//import com.fasterxml.jackson.annotation.PropertyAccessor;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
//
///**
// * redis配置
// *
// * @author yc
// */
//@Configuration
//@EnableCaching
//public class RedisConfig extends CachingConfigurerSupport
//{
// @Bean
// @SuppressWarnings(value = { "unchecked", "rawtypes" })
// public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
// {
// RedisTemplate<Object, Object> template = new RedisTemplate<>();
// template.setConnectionFactory(connectionFactory);
//
// RedisSerializer serializer = new FastJsonRedisSerializer(Object.class);
//
// ObjectMapper mapper = new ObjectMapper();
// mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
//// serializer.setObjectMapper(mapper);
//
// template.setValueSerializer(serializer);
// // 使用StringRedisSerializer来序列化和反序列化redis的key值
// template.setKeySerializer(new StringRedisSerializer());
// template.afterPropertiesSet();
// return template;
// }
//}

View File

@ -0,0 +1,875 @@
package cn.card.health.common.redis;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
/**
* Redis工具类
*
* @author ZENG.XIAO.YAN
* @date 2018年6月7日
*/
@Component
public final class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
// =============================common============================
/**
*
* 指定缓存失效时间
*
* @param key
*
* @param time 时间()
*
* @return
*
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
* 根据key 获取过期时间
*
* @param key 不能为null
*
* @return 时间() 返回0代表为永久有效
*
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
*
* 判断key是否存在
*
* @param key
*
* @return true 存在 false不存在
*
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
* 删除缓存
*
* @param key 可以传一个值 或多个
*
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
// ============================String=============================
/**
*
* 普通缓存获取
*
* @param key
*
* @return
*
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
*
* 普通缓存放入
*
* @param key
*
* @param value
*
* @return true成功 false失败
*
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
* 普通缓存放入并设置时间
*
* @param key
*
* @param value
*
* @param time 时间() time要大于0 如果time小于等于0 将设置无限期
*
* @return true成功 false 失败
*
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
* 递增
*
* @param key
*
* @param delta 要增加几(大于0)
*
* @return
*
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
*
* 递减
*
* @param key
*
* @param delta 要减少几(小于0)
*
* @return
*
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
// ================================Map=================================
/**
*
* HashGet
*
* @param key 不能为null
*
* @param item 不能为null
*
* @return
*
*/
public <T> T hget(String key, String item) {
// return redisTemplate.opsForHash().get(key, item);
HashOperations<String,String, T> operation = redisTemplate.opsForHash();
return operation.get(key, item);
}
/**
*
* 获取hashKey对应的所有键值
*
* @param key
*
* @return 对应的多个键值
*
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
*
* HashSet
*
* @param key
*
* @param map 对应多个键值
*
* @return true 成功 false 失败
*
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
* HashSet 并设置时间
*
* @param key
*
* @param map 对应多个键值
*
* @param time 时间()
*
* @return true成功 false失败
*
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key
*
* @param item
*
* @param value
*
* @return true 成功 false失败
*
*/
public <T> boolean hset(String key, String item, T value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key
*
* @param item
*
* @param value
*
* @param time 时间() 注意:如果已存在的hash表有时间,这里将会替换原有的时间
*
* @return true 成功 false失败
*
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
* 删除hash表中的值
*
* @param key 不能为null
*
* @param item 可以使多个 不能为null
*
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
*
* 判断hash表中是否有该项的值
*
* @param key 不能为null
*
* @param item 不能为null
*
* @return true 存在 false不存在
*
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
*
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
*
* @param key
*
* @param item
*
* @param by 要增加几(大于0)
*
* @return
*
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
*
* hash递减
*
* @param key
*
* @param item
*
* @param by 要减少记(小于0)
*
* @return
*
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
// ============================set=============================
/**
*
* 根据key获取Set中的所有值
*
* @param key
*
* @return
*
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
*
* 根据value从一个set中查询,是否存在
*
* @param key
*
* @param value
*
* @return true 存在 false不存在
*
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
* 将数据放入set缓存
*
* @param key
*
* @param values 可以是多个
*
* @return 成功个数
*
*/
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
*
* 将set数据放入缓存
*
* @param key
*
* @param time 时间()
*
* @param values 可以是多个
*
* @return 成功个数
*
*/
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0)
expire(key, time);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
*
* 获取set缓存的长度
*
* @param key
*
* @return
*
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
*
* 移除值为value的
*
* @param key
*
* @param values 可以是多个
*
* @return 移除的个数
*
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ===============================list=================================
/**
*
* 获取list缓存的内容
*
* @param key
*
* @param start 开始
*
* @param end 结束 0 -1代表所有值
*
* @return
*
*/
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
*
* 获取list缓存的长度
*
* @param key
*
* @return
*
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
*
* 通过索引 获取list中的值
*
* @param key
*
* @param index 索引 index>=0时 0 表头1 第二个元素依次类推index<0时-1表尾-2倒数第二个元素依次类推
*
* @return
*
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
*
* 将list放入缓存
*
* @param key
*
* @param value
*
* @param time 时间()
*
* @return
*
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
* 将list放入缓存
*
* @param key
*
* @param value
*
* @param time 时间()
*
* @return
*
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
* 将list放入缓存
*
* @param key
*
* @param value
*
* @param time 时间()
*
* @return
*
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
* 将list放入缓存
*
*
*
* @param key
*
* @param value
*
* @param time 时间()
*
* @return
*
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
* 根据索引修改list中的某条数据
*
* @param key
*
* @param index 索引
*
* @param value
*
* @return
*
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*
* 移除N个值为value
*
* @param key
*
* @param count 移除多少个
*
* @param value
*
* @return 移除的个数
*
*/
public long lRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}

View File

@ -0,0 +1,161 @@
package cn.card.health.common.utils;
import com.alibaba.fastjson.JSONObject;
/**
* 返回类型
*
* @author xinggm
* @date 2021年5月27日
*/
public class BaseResultJSON extends JSONObject {
private static final long serialVersionUID = 1L;
/** 状态码 */
public static final String CODE_TAG = "code";
/** 返回内容 */
public static final String MSG_TAG = "msg";
/** 数据对象 */
public static final String DATA_TAG = "data";
/**
* 初始化一个新创建的 BaseResultJSON 对象使其表示一个空消息
*/
public BaseResultJSON()
{
}
/**
* 初始化一个新创建的 BaseResultJSON 对象
*
* @param code 状态码
* @param msg 返回内容
*/
public BaseResultJSON(int code, String msg)
{
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
}
/**
* 初始化一个新创建的 BaseResultJSON 对象
*
* @param code 状态码
* @param msg 返回内容
* @param data 数据对象
*/
public BaseResultJSON(int code, String msg, Object data)
{
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
if (StringUtils.isNotNull(data))
{
super.put(DATA_TAG, data);
}
}
/**
* 返回成功消息
*
* @return 成功消息
*/
public static BaseResultJSON success()
{
return BaseResultJSON.success("操作成功");
}
/**
* 返回成功数据
*
* @return 成功消息
* @throws Exception
*/
public static BaseResultJSON success(Object data)
{
if(data == null){
return BaseResultJSON.error(HttpStatus.NO_CONTENT, "未查到数据");
}
return BaseResultJSON.success("操作成功", data);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @return 成功消息
*/
public static BaseResultJSON success(String msg)
{
return BaseResultJSON.success(msg, null);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 成功消息
*/
public static BaseResultJSON success(String msg, Object data)
{
return new BaseResultJSON(HttpStatus.SUCCESS, msg, data);
}
/**
* 返回错误消息
*
* @return
*/
public static BaseResultJSON error()
{
return BaseResultJSON.error("操作失败");
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @return 警告消息
*/
public static BaseResultJSON error(String msg)
{
return BaseResultJSON.error(msg, null);
}
/**
* 返回错误消息
*
* @param data 返回内容
* @return 警告消息
*/
public static BaseResultJSON error(Object data)
{
return BaseResultJSON.error("", data);
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 警告消息
*/
public static BaseResultJSON error(String msg, Object data)
{
return new BaseResultJSON(HttpStatus.ERROR, msg, data);
}
/**
* 返回错误消息
*
* @param code 状态码
* @param msg 返回内容
* @return 警告消息
*/
public static BaseResultJSON error(int code, String msg)
{
return new BaseResultJSON(code, msg, null);
}
}

View File

@ -0,0 +1,77 @@
package cn.card.health.common.utils;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* 字符集工具类
*
* @author yc
*/
public class CharsetKit {
/** ISO-8859-1 */
public static final String ISO_8859_1 = "ISO-8859-1";
/** UTF-8 */
public static final String UTF_8 = "UTF-8";
/** GBK */
public static final String GBK = "GBK";
/** ISO-8859-1 */
public static final Charset CHARSET_ISO_8859_1 = Charset.forName(ISO_8859_1);
/** UTF-8 */
public static final Charset CHARSET_UTF_8 = Charset.forName(UTF_8);
/** GBK */
public static final Charset CHARSET_GBK = Charset.forName(GBK);
/**
* 转换为Charset对象
*
* @param charset 字符集为空则返回默认字符集
* @return Charset
*/
public static Charset charset(String charset) {
return StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset);
}
/**
* 转换字符串的字符集编码
*
* @param source 字符串
* @param srcCharset 源字符集默认ISO-8859-1
* @param destCharset 目标字符集默认UTF-8
* @return 转换后的字符集
*/
public static String convert(String source, String srcCharset, String destCharset) {
return convert(source, Charset.forName(srcCharset), Charset.forName(destCharset));
}
/**
* 转换字符串的字符集编码
*
* @param source 字符串
* @param srcCharset 源字符集默认ISO-8859-1
* @param destCharset 目标字符集默认UTF-8
* @return 转换后的字符集
*/
public static String convert(String source, Charset srcCharset, Charset destCharset) {
if (null == srcCharset) {
srcCharset = StandardCharsets.ISO_8859_1;
}
if (null == destCharset) {
destCharset = StandardCharsets.UTF_8;
}
if (StringUtils.isEmpty(source) || srcCharset.equals(destCharset)) {
return source;
}
return new String(source.getBytes(srcCharset), destCharset);
}
/**
* @return 系统字符集编码
*/
public static String systemCharset() {
return Charset.defaultCharset().name();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,171 @@
package cn.card.health.common.utils;
import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils;
/**
* 时间工具类
*
* @author yc
*/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
public static String YYYY = "yyyy";
public static String YYYY_MM = "yyyy-MM";
public static String YYYY_MM_DD = "yyyy-MM-dd";
public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
public static String YYYYMMDDHHMMSSsss = "yyyyMMddHHmmssSSS";
public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss",
"yyyy.MM.dd HH:mm", "yyyy.MM" };
/**
* 获取当前Date型日期
*
* @return Date() 当前日期
*/
public static Date getNowDate() {
return new Date();
}
/**
* 获取当前日期, 默认格式为yyyy-MM-dd
*
* @return String
*/
public static String getDate() {
return dateTimeNow(YYYY_MM_DD);
}
public static final String getTime() {
return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
}
public static final String getDateTimes() {
return dateTimeNow(YYYYMMDDHHMMSSsss);
}
public static final String dateTimeNow() {
return dateTimeNow(YYYYMMDDHHMMSS);
}
public static final String dateTimeNow(final String format) {
return parseDateToStr(format, new Date());
}
public static final String dateTime(final Date date) {
return parseDateToStr(YYYY_MM_DD, date);
}
public static final String dateTimeHMS(final Date date) {
return parseDateToStr(YYYY_MM_DD_HH_MM_SS, date);
}
public static final String parseDateToStr(final String format, final Date date) {
return new SimpleDateFormat(format).format(date);
}
public static final Date dateTime(final String format, final String ts) {
try {
return new SimpleDateFormat(format).parse(ts);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
/**
* 日期路径 即年// 如2018/08/08
*/
public static final String datePath() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyy/MM/dd");
}
/**
* 日期路径 即年// 如20180808
*/
public static final String dateTime() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyyMMdd");
}
/**
* 日期型字符串转化为日期 格式
*/
public static Date parseDate(Object str) {
if (str == null) {
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}
/**
* 获取服务器启动时间
*/
public static Date getServerStartDate() {
long time = ManagementFactory.getRuntimeMXBean().getStartTime();
return new Date(time);
}
/**
* 计算两个时间差
*/
public static String getDatePoor(Date endDate, Date nowDate) {
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
// long ns = 1000;
// 获得两个时间的毫秒时间差异
long diff = endDate.getTime() - nowDate.getTime();
// 计算差多少天
long day = diff / nd;
// 计算差多少小时
long hour = diff % nd / nh;
// 计算差多少分钟
long min = diff % nd % nh / nm;
// 计算差多少秒//输出结果
// long sec = diff % nd % nh % nm / ns;
return day + "" + hour + "小时" + min + "分钟";
}
/**
* 返回轨迹rangeid
*
* @param rangetime
* @return
* @throws ParseException
*/
public static int getDateRangeid(String rangetime) throws ParseException {
String[] ranges = rangetime.split(",");
int rangeid = 1;
long now = System.currentTimeMillis();
String yyyyMMdd = LocalDate.now().getYear() + "-" + LocalDate.now().getMonthValue() + "-"
+ LocalDate.now().getDayOfMonth() + " ";
for (String range : ranges) {
String[] rangeHours = range.split("-");
long begin = parseDate(yyyyMMdd + rangeHours[0], YYYY_MM_DD_HH_MM).getTime();
long end = parseDate(yyyyMMdd + rangeHours[1], YYYY_MM_DD_HH_MM).getTime();
if (now > begin && now < end) {
break;
} else {
rangeid++;
}
}
return rangeid;
}
}

View File

@ -0,0 +1,40 @@
package cn.card.health.common.utils;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.commons.lang3.exception.ExceptionUtils;
/**
* 错误信息处理类
*
* @author yc
*/
public class ExceptionUtil
{
/**
* 获取exception的详细错误信息
*/
public static String getExceptionMessage(Throwable e)
{
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw, true));
String str = sw.toString();
return str;
}
public static String getRootErrorMseeage(Exception e)
{
Throwable root = ExceptionUtils.getRootCause(e);
root = (root == null ? e : root);
if (root == null)
{
return "";
}
String msg = root.getMessage();
if (msg == null)
{
return "null";
}
return StringUtils.defaultString(msg);
}
}

View File

@ -0,0 +1,60 @@
package cn.card.health.common.utils;
/**
* 返回状态码
*
* @author yc
*/
public class HttpStatus
{
/** 操作成功 */
public static final int SUCCESS = 200;
/** 对象创建成功 */
public static final int CREATED = 201;
/** 请求已经被接受 */
public static final int ACCEPTED = 202;
/** 操作已经执行成功,但是没有返回数据 */
public static final int NO_CONTENT = 204;
/** 资源已被移除 */
public static final int MOVED_PERM = 301;
/** 重定向 */
public static final int SEE_OTHER = 303;
/** 资源没有被修改 */
public static final int NOT_MODIFIED = 304;
/** 参数列表错误(缺少,格式不匹配)*/
public static final int BAD_REQUEST = 400;
/** 未授权 */
public static final int UNAUTHORIZED = 401;
/** 访问受限,授权过期 */
public static final int FORBIDDEN = 403;
/** 资源,服务未找到 */
public static final int NOT_FOUND = 404;
/** 不允许的http方法 */
public static final int BAD_METHOD = 405;
/** 资源冲突,或者资源被锁 */
public static final int CONFLICT = 409;
/** 不支持的数据,媒体类型 */
public static final int UNSUPPORTED_TYPE = 415;
/** 系统内部错误 */
public static final int ERROR = 500;
/** 接口未实现 */
public static final int NOT_IMPLEMENTED = 501;
/** 自定义错误 */
public static final int ERROR_CUSTOM = 503;
}

View File

@ -0,0 +1,360 @@
package cn.card.health.common.utils;
import java.io.*;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 通用http发送方法
*
* @author yc
*/
public class HttpUtils {
private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
/**
* 向指定 URL 发送GET方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数请求参数应该是 name1=value1&name2=value2 的形式
* @return 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
return sendGet(url, param, "utf-8");
}
/**
* 向指定 URL 发送GET方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数请求参数应该是 name1=value1&name2=value2 的形式
* @param contentType 编码类型
* @return 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param, String contentType) {
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
log.info("sendGet - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.connect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
log.info("recv - {}", result);
} catch (ConnectException e) {
log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
} catch (Exception e) {
log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception ex) {
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
return result.toString();
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数请求参数应该是 name1=value1&name2=value2 的形式
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
String urlNameString = url;
log.info("sendPost - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
log.info("recv - {}", result);
} catch (ConnectException e) {
log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
} catch (Exception e) {
log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
return result.toString();
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数请求参数应该是 name1=value1&name2=value2 的形式
* @return 所代表远程资源的响应结果
*/
public static String sendWeChatPost(String url, String sign, String param) {
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
String urlNameString = url;
log.info("sendPost - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection conn = realUrl.openConnection();
// conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("contentType", "utf-8");
conn.setRequestProperty("User-Agent", "Windows 10-Chrome 8");
conn.setRequestProperty("Authorization", sign);
conn.setRequestProperty("Content-type", "application/json");
conn.setRequestProperty("Accept-Language", "zh-CN");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
log.info("recv - {}", result);
} catch (ConnectException e) {
log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
} catch (Exception e) {
log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
return result.toString();
}
public static String sendSSLPost(String url, String param) {
StringBuilder result = new StringBuilder();
String urlNameString = url + "?" + param;
try {
log.info("sendSSLPost - {}", urlNameString);
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
URL console = new URL(urlNameString);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String ret = "";
while ((ret = br.readLine()) != null) {
if (ret != null && !"".equals(ret.trim())) {
result.append(new String(ret.getBytes("ISO-8859-1"), "utf-8"));
}
}
log.info("recv - {}", result);
conn.disconnect();
br.close();
} catch (ConnectException e) {
log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
} catch (Exception e) {
log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
}
return result.toString();
}
private static class TrustAnyTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
private static class TrustAnyHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
public String doPost(String url, String params, String token) {
org.apache.http.client.HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try {
httpClient = new SSLClient();
httpPost = new HttpPost(url);
// 设置参数
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("User-Agent", "Windows 10-Chrome 8");
// httpPost.addHeader("Authorization", token);
httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
StringEntity stringEntity = new StringEntity(params);
stringEntity.setContentEncoding("UTF-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
HttpResponse response = httpClient.execute(httpPost);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, "utf-8");
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数请求参数应该是json格式
* @return 所代表远程资源的响应结果
*/
public static String sendJSONPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
String urlNameString = url;
log.info("sendPost - {}", urlNameString);
URL realUrl = new URL(urlNameString);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("contentType", "UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
// out = new PrintWriter(conn.getOutputStream());
// 定义请求数据utf-8编码
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
out.print(param);
out.flush();
// in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
// 定义返回数据 utf-8编码
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
// log.info("recv - {}", result);
} catch (ConnectException e) {
log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
} catch (SocketTimeoutException e) {
log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
} catch (IOException e) {
log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
} catch (Exception e) {
log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
}
}
return result.toString();
}
}

View File

@ -0,0 +1,209 @@
package cn.card.health.common.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @Author: 维斯
* @Date: 2022/6/30 14:55
* @Description: Json排序工具
* @Version: v1.0
*/
public class JSONUtils {
/**
* 对单词列表进行冒泡排序
* 直接操作对象地址 无需返回
*
* @param words ["name","age"]
*/
private static void wordSort(ArrayList<String> words) {
for (int i = words.size() - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (words.get(j).compareToIgnoreCase(words.get(j + 1)) > 0) {
String temp = words.get(j);
words.set(j, words.get(j + 1));
words.set(j + 1, temp);
}
}
}
}
/**
* 对单层json排序
*
* @param json
*/
private static JSONObject getAloneKeys(JSONObject json) {
ArrayList<String> aloneKeys = new ArrayList<>();
for (String key : json.keySet()) {
aloneKeys.add(key);
}
// 排序
JSONUtils.wordSort(aloneKeys);
// 整理排序后的json
JSONObject newJson = new JSONObject(new LinkedHashMap<>());
for (String key : aloneKeys) {
newJson.put(key, json.get(key));
}
return newJson;
}
/**
* 递归每一层当前是判断下一层是JSONObject类型的场景
*
* @param json
* @return
*/
private static JSONObject getAloneKeysRec(JSONObject json) {
JSONObject newJson = getAloneKeys(json);
for (Map.Entry<String, Object> entry : newJson.entrySet()) {
// JSONObject类型
// System.out.println(entry);
if (entry.getValue() == null) {
continue;
}
if (entry.getValue().getClass().equals(JSONObject.class)) {
newJson.put(entry.getKey(), getAloneKeysRec((JSONObject) entry.getValue()));
}
}
return newJson;
}
/**
* 对JSONObject的key根据首字母排序 若首字母相同对比下一个字母 依次类推
* 备注当前未覆盖JSONArray的场景
*
* @param json
* @return 排序后的新json
*/
public static JSONObject startSort(JSONObject json) {
// 第1层
JSONObject jsonAlone = getAloneKeys(json);
// 第2-n层
for (Map.Entry<String, Object> entry : jsonAlone.entrySet()) {
// 这里仅判断JSONObject类型的场景若需要覆盖JSONArray场景 对应添加即可
if (entry.getValue() == null || StringUtils.isBlank(entry.getValue().toString())) {
continue;
}
if (entry.getValue().getClass().equals(JSONObject.class)) {
jsonAlone.put(entry.getKey(), getAloneKeysRec((JSONObject) entry.getValue()));
} else if (entry.getValue().getClass().equals(JSONArray.class)) {
JSONArray jsonArray = new JSONArray();
JSONArray array = (JSONArray) entry.getValue();
for (int i = 0; i < array.size(); i++) {
JSONObject jOb = new JSONObject();
JSONObject jData = array.getJSONObject(i);
jOb = startSort(jData);
jsonArray.add(jOb);
}
jsonAlone.put(entry.getKey(), jsonArray);
}
}
return jsonAlone;
}
private Object traverseJson(Object json) {
// check null
if (json == null) {
return null;
}
try {
if (json instanceof JSONObject) {// if json is a Map
JSONObject jsonObj = (JSONObject) json;
List
keyList = new ArrayList();
for (String k : jsonObj.keySet()) {
String value = jsonObj.get(k).toString();
if (StringUtils.isEmpty(value)) {
keyList.add(k);
//jsonObj.remove(k);
} else {
if (isJsonObj(value)) {
jsonObj.put(k, traverseJson(JSONObject.parseObject(value)));
} else {
if (isJsonArr(value)) {
//value=;
jsonObj.put(k, traverseJson(JSONArray.parseArray(value)));
}
}
}
}
for (Object k : keyList) {
jsonObj.remove(k);
}
return jsonObj;
} else if (json instanceof JSONArray) {// if json is an Array
JSONArray jsonArr = (JSONArray) json;
int len = jsonArr.size();
for (int i = 0; i < len; ++i) {
// TODO: do something here
jsonArr.set(i, traverseJson(jsonArr.get(i)));
}
// return retArr;
//
// } else {// if json is just a raw element
//
// // TODO: do something here
// return json;
return jsonArr;
//
}
} catch (Exception e) {
e.printStackTrace();// deal Exception or throw it
}
return null;
}
public boolean isJsonObj(Object o) {
try {
JSONObject js = JSONObject.parseObject(o.toString());
return true;
} catch (Exception e) {
return false;
}
}
public boolean isJsonArr(Object o) {
try {
JSONArray js = JSONArray.parseArray(o.toString());
return true;
} catch (Exception e) {
return false;
}
}
public static String toKeyValue(JSONObject params) {
StringBuffer sbf = new StringBuffer();
for (Map.Entry<String, Object> entry : params.entrySet()) {
sbf.append(entry.getKey());
sbf.append("=");
sbf.append(entry.getValue());
sbf.append("&");
}
return sbf.substring(0, sbf.length() - 2);
// return sbf.toString();
}
}

View File

@ -0,0 +1,18 @@
package cn.card.health.common.utils;
/**
* 处理并记录日志文件
*
* @author yc
*/
public class LogUtils
{
public static String getBlock(Object msg)
{
if (msg == null)
{
msg = "";
}
return "[" + msg.toString() + "]";
}
}

View File

@ -0,0 +1,269 @@
package cn.card.health.common.utils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 描述MapUtils <br/>
* 版本0.1 <br/>
* 作者tancheng <br/>
* 修改日期2015年11月3日 上午10:55:08
*/
public class MapUtils {
private static final String Splitor = "\\.|/|\\\\|->";
public static boolean isExpression(String exp) {
return exp.split(Splitor).length > 0;
}
/**
* 描述使用类似EL表达式形式获得Map中的值 <br/>
* 举例MapUtils.getValue(xml2Map, "response.returnresult.returncode") <br/>
* 作者tancheng <br/>
* 修改日期2015年11月3日 上午11:52:52
*
* @param map Map
* @param expression 表达式(支持".","/","\","->")
*/
public static Object getValue(Map<String, Object> map, String expression) {
return getValue(map, expression, "");
}
/**
* 描述使用类似EL表达式形式获得Map中的值 <br/>
* 举例MapUtils.getValue(xml2Map, "response.returnresult.returncode") <br/>
* 作者tancheng <br/>
* 修改日期2015年11月3日 上午11:52:52
*
* @param map Map
* @param expression 表达式(支持".","/","\","->")
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object getValue(Map<String, Object> map, String expression, Class clazz) {
Object o = getValue(map, expression, "");
if (o == null || "".equals(o)) {
return null;
} else if (o instanceof List) {
return o;
} else if (clazz.getName().equals(List.class.getName())) {
List list = new ArrayList();
list.add(o);
return list;
} else {
return o;
}
}
/**
* 描述使用类似EL表达式形式获得Map中的值 <br/>
* 举例MapUtils.getValue(xml2Map, "response.returnresult.returncode") <br/>
* 作者tancheng <br/>
* 修改日期2015年11月3日 上午11:52:52
*
* @param map Map
* @param defaultValue 默认值
* @param expression 表达式(支持".","/","\","->")
*/
@SuppressWarnings("unchecked")
public static Object getValue(Map<String, Object> map, String expression, Object defaultValue) {
Object value = null;
String[] props = expression.split(Splitor);
for (int i = 0; i < props.length; i++) {
String prop = props[i];
if (i == 0) {
value = map.get(prop);
} else {
if (value instanceof Map) {
value = ((Map<String, Object>) value).get(prop);
} else {
value = null;
break;
}
}
}
if (value == null) {
value = defaultValue;
}
return value;
}
/**
* 描述使用类似EL表达式形式获得Map中的值 <br/>
* 举例MapUtils.getValue(xml2Map, "response.returnresult.returncode")
*
* @author cheng.li 2016年3月18日
* @param map
* @param expression
* @param defaultValue
* @return
*/
public static String getStringValue(Map<String, Object> map, String expression, String defaultValue) {
Object value = getValue(map, expression, defaultValue);
if (defaultValue == null && value == null) {
return null;
} else {
return value.toString();
}
}
/**
* 描述使用类似EL表达式形式向Map中传值 <br/>
* 举例MapUtils.putValue(xml2Map, "response.returnresult.returncode", "1") <br/>
* 作者tancheng <br/>
* 修改日期2015年11月3日 上午11:52:52
*
* @param map Map
* @param expression 表达式("."分割)
* @param value
*/
@SuppressWarnings({ "unchecked" })
public static Map<String, Object> putValue(Map<String, Object> map, String expression, Object value) {
int index = expression.indexOf(".");
if (index == -1) {
String prop = expression;
map.put(prop, value);
} else {
String prop = expression.substring(0, index);
Object sub_map = map.get(prop);
if (sub_map == null) {
map.put(prop, new HashMap<String, Object>());
map = putValue((Map<String, Object>) map.get(prop), expression.substring(index + 1), value);
} else if (sub_map instanceof Map) {
map = putValue((Map<String, Object>) sub_map, expression.substring(index + 1), value);
} else {
// TODO
return map;
}
}
return map;
}
/**
* 描述实体类转换Map <br/>
* 作者tancheng <br/>
* 修改日期2015年11月5日 下午3:04:55
*/
public static Map<String, Object> BeanToMap(Object bean) {
Map<String, Object> result = new HashMap<String, Object>();
if (bean == null) {
return result;
}
Class<? extends Object> clazz = bean.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
String name = field.getName();
Object value = null;
try {
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, clazz);
value = propertyDescriptor.getReadMethod().invoke(bean);
} catch (Exception e) {
continue;
}
if (value != null) {
if (!isComplexType(field)) {
result.put(name, value);
} else {
result.put(name, MapUtils.BeanToMap(value));
}
}
}
return result;
}
/**
* bean 追加参数添加到 map
*
* @author cheng.li 2016年6月24日
* @param bean
* @param result
* @return
*/
public static Map<String, Object> BeanAddToMap(Object bean, Map<String, Object> result) {
if (bean == null || result == null) {
return result;
}
Class<? extends Object> clazz = bean.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
String name = field.getName();
Object value = null;
try {
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, clazz);
value = propertyDescriptor.getReadMethod().invoke(bean);
} catch (Exception e) {
continue;
}
if (value != null) {
if (!isComplexType(field)) {
result.put(name, value);
} else {
result.put(name, MapUtils.BeanToMap(value));
}
}
}
return result;
}
/**
* 方法名称: isComplexType<br>
* 描述判断是否为复合类型<br>
* 作者: wanhonghui<br>
* 修改日期2013年8月15日下午2:25:52<br>
*
* @param field<br>
* @return false基本类型 true复合类型
*/
private static boolean isComplexType(Field field) {
Class<? extends Object> clazz = field.getType();
if (byte.class.isAssignableFrom(clazz) || Byte.class.isAssignableFrom(clazz)
|| char.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz)
|| short.class.isAssignableFrom(clazz) || Short.class.isAssignableFrom(clazz)
|| int.class.isAssignableFrom(clazz) || Integer.class.isAssignableFrom(clazz)
|| long.class.isAssignableFrom(clazz) || Long.class.isAssignableFrom(clazz)
|| float.class.isAssignableFrom(clazz) || Float.class.isAssignableFrom(clazz)
|| double.class.isAssignableFrom(clazz) || Double.class.isAssignableFrom(clazz)
|| boolean.class.isAssignableFrom(clazz) || Boolean.class.isAssignableFrom(clazz)
|| String.class.isAssignableFrom(clazz)) {
return false;
}
return true;
}
/**
* 自定义拼接返回一个设定的Map集合
*
* @author xinggm 2016年11月15日
* @param reqMap
* @return
*/
public static Map<String, Object> comboMap(Map<String, Object> reqMap, String... keys) {
Map<String, Object> params = new HashMap<String, Object>();
if (reqMap == null || keys == null || keys.length == 0) {
return null;
}
for (String key : keys) {
params.put(key, reqMap.get(key));
}
return params;
}
// /**
// * 自定义拼接返回一个设定的Map集合
// * @author xinggm
// * 2016年11月15日
// * @param reqMap
// * @return
// */
// public static MapUtils putValue(Map<String, Object> reqMap, String key, String value)
// {
// reqMap.put(key, value);
// return new MapUtils();
// }
}

View File

@ -0,0 +1,92 @@
package cn.card.health.common.utils;
import java.security.MessageDigest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Md5加密方法
*
* @author yc
*/
public class Md5Utils
{
private static final Logger log = LoggerFactory.getLogger(Md5Utils.class);
private static byte[] md5(String s)
{
MessageDigest algorithm;
try
{
algorithm = MessageDigest.getInstance("MD5");
algorithm.reset();
algorithm.update(s.getBytes("UTF-8"));
byte[] messageDigest = algorithm.digest();
return messageDigest;
}
catch (Exception e)
{
log.error("MD5 Error...", e);
}
return null;
}
private static final String toHex(byte hash[])
{
if (hash == null)
{
return null;
}
StringBuffer buf = new StringBuffer(hash.length * 2);
int i;
for (i = 0; i < hash.length; i++)
{
if ((hash[i] & 0xff) < 0x10)
{
buf.append("0");
}
buf.append(Long.toString(hash[i] & 0xff, 16));
}
return buf.toString();
}
public static String getMD5(String s)
{
try
{
return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
}
catch (Exception e)
{
log.error("not supported charset...{}", e);
return s;
}
}
public static String getMD5(Long l)
{
try
{
return new String(toHex(md5(l+"")).getBytes(), "UTF-8");
}
catch (Exception e)
{
log.error("not supported charset...{}", e);
return null;
}
}
public static String hash(String s)
{
try
{
return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
}
catch (Exception e)
{
log.error("not supported charset...{}", e);
return s;
}
}
}

View File

@ -0,0 +1,21 @@
package cn.card.health.common.utils;
import cn.card.health.common.utils.spring.SpringUtils;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
public class MessageUtils
{
/**
* 根据消息键和参数 获取消息 委托给spring messageSource
*
* @param code 消息键
* @param args 参数
* @return 获取国际化翻译值
*/
public static String message(String code, Object... args)
{
MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
}
}

View File

@ -0,0 +1,23 @@
package cn.card.health.common.utils;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
/**
* 证书信任管理器用于HTTPS请求
*
*/
public class MyX509TrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}

View File

@ -0,0 +1,83 @@
package cn.card.health.common.utils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
public class SSLClient extends DefaultHttpClient {
@SuppressWarnings("deprecation")
public SSLClient() throws Exception {
super();
// 传输协议需要根据自己的判断
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
X509TrustManager sunJSSEX509TrustManager;
public void X509TrustManager () throws Exception {
try {
// create a "default" JSSE X509TrustManager.
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("trustedCerts"), "passphrase".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
tmf.init(ks);
TrustManager tms[] = tmf.getTrustManagers();
/*
* Iterate over the returned trustmanagers, look for an instance of
* X509TrustManager. If found, use that as our "default" trust manager.
*/
for (int i = 0; i < tms.length; i++) {
if (tms[i] instanceof X509TrustManager) {
sunJSSEX509TrustManager = (X509TrustManager) tms[i];
return;
}
}
} catch (Exception e) {
/*
* Find some other way to initialize, or else we have to fail the constructor.
*/
throw new Exception("Couldn't initialize");
}
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
try {
sunJSSEX509TrustManager.checkServerTrusted(chain, authType);
} catch (java.security.cert.CertificateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}

View File

@ -0,0 +1,91 @@
package cn.card.health.common.utils;
/**
* 字符串格式化
*
* @author yc
*/
public class StrFormatter
{
public static final String EMPTY_JSON = "{}";
public static final char C_BACKSLASH = '\\';
public static final char C_DELIM_START = '{';
public static final char C_DELIM_END = '}';
/**
* 格式化字符串<br>
* 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
* 如果想输出 {} 使用 \\转义 { 即可如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
* <br>
* 通常使用format("this is {} for {}", "a", "b") -> this is a for b<br>
* 转义{} format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
* 转义\ format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
*
* @param strPattern 字符串模板
* @param argArray 参数列表
* @return 结果
*/
public static String format(final String strPattern, final Object... argArray)
{
if (StringUtils.isEmpty(strPattern) || StringUtils.isEmpty(argArray))
{
return strPattern;
}
final int strPatternLength = strPattern.length();
// 初始化定义好的长度以获得更好的性能
StringBuilder sbuf = new StringBuilder(strPatternLength + 50);
int handledPosition = 0;
int delimIndex;// 占位符所在位置
for (int argIndex = 0; argIndex < argArray.length; argIndex++)
{
delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition);
if (delimIndex == -1)
{
if (handledPosition == 0)
{
return strPattern;
}
else
{ // 字符串模板剩余部分不再包含占位符加入剩余部分后返回结果
sbuf.append(strPattern, handledPosition, strPatternLength);
return sbuf.toString();
}
}
else
{
if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH)
{
if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH)
{
// 转义符之前还有一个转义符占位符依旧有效
sbuf.append(strPattern, handledPosition, delimIndex - 1);
sbuf.append(Convert.utf8Str(argArray[argIndex]));
handledPosition = delimIndex + 2;
}
else
{
// 占位符被转义
argIndex--;
sbuf.append(strPattern, handledPosition, delimIndex - 1);
sbuf.append(C_DELIM_START);
handledPosition = delimIndex + 1;
}
}
else
{
// 正常占位符
sbuf.append(strPattern, handledPosition, delimIndex);
sbuf.append(Convert.utf8Str(argArray[argIndex]));
handledPosition = delimIndex + 2;
}
}
}
// 加入最后一个占位符后所有的字符
sbuf.append(strPattern, handledPosition, strPattern.length());
return sbuf.toString();
}
}

View File

@ -0,0 +1,458 @@
package cn.card.health.common.utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 字符串工具类
*
* @author yc
*/
public class StringUtils extends org.apache.commons.lang3.StringUtils
{
/** 空字符串 */
private static final String NULLSTR = "";
/** 下划线 */
private static final char SEPARATOR = '_';
/**
* 获取参数不为空值
*
* @param value defaultValue 要判断的value
* @return value 返回值
*/
public static <T> T nvl(T value, T defaultValue)
{
return value != null ? value : defaultValue;
}
/**
* * 判断一个Collection是否为空 包含ListSetQueue
*
* @param coll 要判断的Collection
* @return true为空 false非空
*/
public static boolean isEmpty(Collection<?> coll)
{
return isNull(coll) || coll.isEmpty();
}
/**
* * 判断一个Collection是否非空包含ListSetQueue
*
* @param coll 要判断的Collection
* @return true非空 false
*/
public static boolean isNotEmpty(Collection<?> coll)
{
return !isEmpty(coll);
}
/**
* * 判断一个对象数组是否为空
*
* @param objects 要判断的对象数组
** @return true为空 false非空
*/
public static boolean isEmpty(Object[] objects)
{
return isNull(objects) || (objects.length == 0);
}
/**
* * 判断一个对象数组是否非空
*
* @param objects 要判断的对象数组
* @return true非空 false
*/
public static boolean isNotEmpty(Object[] objects)
{
return !isEmpty(objects);
}
/**
* * 判断一个Map是否为空
*
* @param map 要判断的Map
* @return true为空 false非空
*/
public static boolean isEmpty(Map<?, ?> map)
{
return isNull(map) || map.isEmpty();
}
/**
* * 判断一个Map是否为空
*
* @param map 要判断的Map
* @return true非空 false
*/
public static boolean isNotEmpty(Map<?, ?> map)
{
return !isEmpty(map);
}
/**
* * 判断一个字符串是否为空串
*
* @param str String
* @return true为空 false非空
*/
public static boolean isEmpty(String str)
{
return isNull(str) || NULLSTR.equals(str.trim());
}
/**
* * 判断一个字符串是否为非空串
*
* @param str String
* @return true非空串 false空串
*/
public static boolean isNotEmpty(String str)
{
return !isEmpty(str);
}
/**
* * 判断一个对象是否为空
*
* @param object Object
* @return true为空 false非空
*/
public static boolean isNull(Object object)
{
return object == null;
}
/**
* * 判断一个对象是否非空
*
* @param object Object
* @return true非空 false
*/
public static boolean isNotNull(Object object)
{
return !isNull(object);
}
/**
* * 判断一个对象是否是数组类型Java基本型别的数组
*
* @param object 对象
* @return true是数组 false不是数组
*/
public static boolean isArray(Object object)
{
return isNotNull(object) && object.getClass().isArray();
}
/**
* 去空格
*/
public static String trim(String str)
{
return (str == null ? "" : str.trim());
}
/**
* 截取字符串
*
* @param str 字符串
* @param start 开始
* @return 结果
*/
public static String substring(final String str, int start)
{
if (str == null)
{
return NULLSTR;
}
if (start < 0)
{
start = str.length() + start;
}
if (start < 0)
{
start = 0;
}
if (start > str.length())
{
return NULLSTR;
}
return str.substring(start);
}
/**
* 截取字符串
*
* @param str 字符串
* @param start 开始
* @param end 结束
* @return 结果
*/
public static String substring(final String str, int start, int end)
{
if (str == null)
{
return NULLSTR;
}
if (end < 0)
{
end = str.length() + end;
}
if (start < 0)
{
start = str.length() + start;
}
if (end > str.length())
{
end = str.length();
}
if (start > end)
{
return NULLSTR;
}
if (start < 0)
{
start = 0;
}
if (end < 0)
{
end = 0;
}
return str.substring(start, end);
}
/**
* 格式化文本, {} 表示占位符<br>
* 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
* 如果想输出 {} 使用 \\转义 { 即可如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
* <br>
* 通常使用format("this is {} for {}", "a", "b") -> this is a for b<br>
* 转义{} format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
* 转义\ format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
*
* @param template 文本模板被替换的部分用 {} 表示
* @param params 参数值
* @return 格式化后的文本
*/
public static String format(String template, Object... params)
{
if (isEmpty(params) || isEmpty(template))
{
return template;
}
return StrFormatter.format(template, params);
}
/**
* 字符串转set
*
* @param str 字符串
* @param sep 分隔符
* @return set集合
*/
public static final Set<String> str2Set(String str, String sep)
{
return new HashSet<String>(str2List(str, sep, true, false));
}
/**
* 字符串转list
*
* @param str 字符串
* @param sep 分隔符
* @param filterBlank 过滤纯空白
* @param trim 去掉首尾空白
* @return list集合
*/
public static final List<String> str2List(String str, String sep, boolean filterBlank, boolean trim)
{
List<String> list = new ArrayList<String>();
if (StringUtils.isEmpty(str))
{
return list;
}
// 过滤空白字符串
if (filterBlank && StringUtils.isBlank(str))
{
return list;
}
String[] split = str.split(sep);
for (String string : split)
{
if (filterBlank && StringUtils.isBlank(string))
{
continue;
}
if (trim)
{
string = string.trim();
}
list.add(string);
}
return list;
}
/**
* 下划线转驼峰命名
*/
public static String toUnderScoreCase(String str)
{
if (str == null)
{
return null;
}
StringBuilder sb = new StringBuilder();
// 前置字符是否大写
boolean preCharIsUpperCase = true;
// 当前字符是否大写
boolean curreCharIsUpperCase = true;
// 下一字符是否大写
boolean nexteCharIsUpperCase = true;
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
if (i > 0)
{
preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
}
else
{
preCharIsUpperCase = false;
}
curreCharIsUpperCase = Character.isUpperCase(c);
if (i < (str.length() - 1))
{
nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
}
if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase)
{
sb.append(SEPARATOR);
}
else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase)
{
sb.append(SEPARATOR);
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
/**
* 是否包含字符串
*
* @param str 验证字符串
* @param strs 字符串组
* @return 包含返回true
*/
public static boolean inStringIgnoreCase(String str, String... strs)
{
if (str != null && strs != null)
{
for (String s : strs)
{
if (str.equalsIgnoreCase(trim(s)))
{
return true;
}
}
}
return false;
}
/**
* 将下划线大写方式命名的字符串转换为驼峰式如果转换前的下划线大写方式命名的字符串为空则返回空字符串 例如HELLO_WORLD->HelloWorld
*
* @param name 转换前的下划线大写方式命名的字符串
* @return 转换后的驼峰式命名的字符串
*/
public static String convertToCamelCase(String name)
{
StringBuilder result = new StringBuilder();
// 快速检查
if (name == null || name.isEmpty())
{
// 没必要转换
return "";
}
else if (!name.contains("_"))
{
// 不含下划线仅将首字母大写
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
// 用下划线将原始字符串分割
String[] camels = name.split("_");
for (String camel : camels)
{
// 跳过原始字符串中开头结尾的下换线或双重下划线
if (camel.isEmpty())
{
continue;
}
// 首字母大写
result.append(camel.substring(0, 1).toUpperCase());
result.append(camel.substring(1).toLowerCase());
}
return result.toString();
}
/**
* 驼峰式命名法 例如user_name->userName
*/
public static String toCamelCase(String s)
{
if (s == null)
{
return null;
}
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if (c == SEPARATOR)
{
upperCase = true;
}
else if (upperCase)
{
sb.append(Character.toUpperCase(c));
upperCase = false;
}
else
{
sb.append(c);
}
}
return sb.toString();
}
@SuppressWarnings("unchecked")
public static <T> T cast(Object obj)
{
return (T) obj;
}
}

View File

@ -0,0 +1,248 @@
package cn.card.health.common.utils;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.QName;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
* 描述XMLUtils <br/>
* 版本0.1 <br/>
* 作者tancheng <br/>
* 修改日期2015年11月2日 下午6:00:05
*/
public class XMLUtils
{
/**
* 描述检测 <br/>
* 作者tancheng <br/>
* 修改日期2016年1月14日 下午2:12:10
*/
public static boolean isXML(String xml)
{
return xml.startsWith("<?xml");
}
/**
* 描述XML转Map <br/>
* 作者tancheng <br/>
* 修改日期2015年11月2日 下午9:32:32
*/
public static Map<String, Object> Xml2Map(String xml)
{
Map<String, Object> map = null;
Document doc;
try
{
doc = DocumentHelper.parseText(xml);
Element rootElement = doc.getRootElement();
if (rootElement.hasContent())
{
map = new HashMap<String, Object>();
map.put(rootElement.getName(), Xml2Map(rootElement));
}
}
catch (DocumentException e)
{
e.printStackTrace();
}
return map;
}
/**
* 描述XML转Map <br/>
* 作者xuelianbobo <br/>
* 原文http://xuelianbobo.iteye.com/blog/2153384?utm_source=tuicool&utm_medium=referral <br/>
* 修改日期2015年11月2日 下午9:32:08
*/
@SuppressWarnings("unchecked")
private static Object Xml2Map(Element element)
{
Map<String, Object> map = new HashMap<String, Object>();
List<Element> elements = element.elements();
if (elements.size() == 0)
{
map.put(element.getName(), element.getText());
if (!element.isRootElement())
{
return element.getText();
}
}
else if (elements.size() == 1)
{
map.put(elements.get(0).getName(), Xml2Map(elements.get(0)));
}
else if (elements.size() > 1)
{
// 多个子节点的话就得考虑list的情况了比如多个子节点有节点名称相同的
// 构造一个map用来去重
Map<String, Element> tempMap = new HashMap<String, Element>();
for (Element ele : elements)
{
tempMap.put(ele.getName(), ele);
}
Set<String> keySet = tempMap.keySet();
for (String string : keySet)
{
Namespace namespace = tempMap.get(string).getNamespace();
List<Element> elements2 = element.elements(new QName(string, namespace));
// 如果同名的数目大于1则表示要构建list
if (elements2.size() > 1)
{
List<Object> list = new ArrayList<Object>();
for (Element ele : elements2)
{
list.add(Xml2Map(ele));
}
map.put(string, list);
}
else
{
// 同名的数量不大于1则直接递归去
map.put(string, Xml2Map(elements2.get(0)));
}
}
}
return map;
}
/**
* XML格式化 记录日志用
* @author cheng.li
* 2016年3月30日
* @param inputXML
* @return
* @throws Exception
*/
public static String formatXML(String inputXML)
{
SAXReader reader = new SAXReader();
XMLWriter writer = null;
String requestXML = null;
try
{
Document document = reader.read(new StringReader(inputXML));
if (document != null)
{
StringWriter stringWriter = new StringWriter();
OutputFormat format = new OutputFormat(" ", true);
writer = new XMLWriter(stringWriter, format);
writer.write(document);
writer.flush();
requestXML = stringWriter.getBuffer().toString();
}
}
catch (Exception e)
{
// TODO: handle exception
}
finally
{
if (writer != null)
{
try
{
writer.close();
}
catch (IOException e)
{
}
}
}
return requestXML;
}
/**
* 根据定义的文档返回一个map,满足下面格式才能用
* @author cheng.li
* 2016年6月12日
* @param xmlMap
* @return
*/
public static Map<String, Object> getHisResult(Map<String, Object> xmlMap)
{
@SuppressWarnings("unchecked")
Map<String, Object> returnresult = (Map<String, Object>) MapUtils.getValue(xmlMap, "response.returnresult");
@SuppressWarnings("unchecked")
Map<String, Object> outputvalues = (Map<String, Object>) MapUtils.getValue(xmlMap, "response.outputvalues");
Map<String, Object> hisResult = new HashMap<String, Object>();
hisResult.put("returncode", returnresult.get("returncode"));
hisResult.put("errormsg", returnresult.get("errormsg"));
if (outputvalues == null)
{
hisResult.put("hasResult", false);
}
else
{
hisResult.put("hasResult", true);
//单层map复制对应循环嵌套的使用MapUtils.getValue等方法自取需要的值
for (Entry<String, Object> entry : outputvalues.entrySet())
{
hisResult.put(entry.getKey(), entry.getValue());
}
}
return hisResult;
}
// public static void main(String[] args) {
// String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><response><returnresult><returncode>返回代码</returncode><errormsg>出错信息</errormsg></returnresult><pageactionout><currentpagenum>当期页码</currentpagenum><rowcountall>总行数</rowcountall><pagecountall>总页数</pagecountall><currentpagecount>当前页的行数</currentpagecount></pageactionout><data><data_row><hospitalid>医院代码</hospitalid><inputcode>拼音输入码</inputcode><hospitalname>医院名称</hospitalname><hospitallevel>医院级别代码</hospitallevel><hospitallevelname>医院级别名称</hospitallevelname><hospitalsmallpicurl>医院图片(小)</hospitalsmallpicurl><hospitalmiddlepicurl>医院图片(中)</hospitalmiddlepicurl><hospitalbigpicurl>医院图片(大)</hospitalbigpicurl><hospitaladdr>医院地址</hospitaladdr><hospitaldes>医院简介</hospitaldes><zipcode>邮政编码</zipcode><provcode>省份代码</provcode><provname>省份名称</provname><citycode>城市代码</citycode><cityname>城市名称</cityname><phone>公司电话</phone><website>公司网站</website><orderextinfo><orderextinfo_row><fieldcode>字段代码</fieldcode><fieldname>字段名称</fieldname><fieldtype> 字段类型 </fieldtype><fieldformat>字段格式 </fieldformat></orderextinfo_row></orderextinfo><ordernum>排序数字</ordernum><createtime>创建时间</createtime><lastmodify>修改时间</lastmodify></data_row><data_row><hospitalid>医院代码</hospitalid><inputcode>拼音输入码</inputcode><hospitalname>医院名称</hospitalname><hospitallevel>医院级别代码</hospitallevel><hospitallevelname>医院级别名称</hospitallevelname><hospitalsmallpicurl>医院图片(小)</hospitalsmallpicurl><hospitalmiddlepicurl>医院图片(中)</hospitalmiddlepicurl><hospitalbigpicurl>医院图片(大)</hospitalbigpicurl><hospitaladdr>医院地址</hospitaladdr><hospitaldes>医院简介</hospitaldes><zipcode>邮政编码</zipcode><provcode>省份代码</provcode><provname>省份名称</provname><citycode>城市代码</citycode><cityname>城市名称</cityname><phone>公司电话</phone><website>公司网站</website><orderextinfo><orderextinfo_row><fieldcode>字段代码</fieldcode><fieldname>字段名称</fieldname><fieldtype> 字段类型 </fieldtype><fieldformat>字段格式 </fieldformat></orderextinfo_row></orderextinfo><ordernum>排序数字</ordernum><createtime>创建时间</createtime><lastmodify>修改时间</lastmodify></data_row><data_row><hospitalid>医院代码</hospitalid><inputcode>拼音输入码</inputcode><hospitalname>医院名称</hospitalname><hospitallevel>医院级别代码</hospitallevel><hospitallevelname>医院级别名称</hospitallevelname><hospitalsmallpicurl>医院图片(小)</hospitalsmallpicurl><hospitalmiddlepicurl>医院图片(中)</hospitalmiddlepicurl><hospitalbigpicurl>医院图片(大)</hospitalbigpicurl><hospitaladdr>医院地址</hospitaladdr><hospitaldes>医院简介</hospitaldes><zipcode>邮政编码</zipcode><provcode>省份代码</provcode><provname>省份名称</provname><citycode>城市代码</citycode><cityname>城市名称</cityname><phone>公司电话</phone><website>公司网站</website><orderextinfo><orderextinfo_row><fieldcode>字段代码</fieldcode><fieldname>字段名称</fieldname><fieldtype> 字段类型 </fieldtype><fieldformat>字段格式 </fieldformat></orderextinfo_row></orderextinfo><ordernum>排序数字</ordernum><createtime>创建时间</createtime><lastmodify>修改时间</lastmodify></data_row></data></response>";
//
// // Gson sGson = new Gson();
//
// Map<String, Object> xml2Map = XMLUtils.Xml2Map(xml);
// // System.out.println(sGson.toJson(xml2Map));
//
// // Bean <-> Xml 映射
// @SuppressWarnings("serial")
// Map<String, Object> mapper = new HashMap<String, Object>() {
// {
// this.put("hospitalId", new UserCustomConvertor("hospitalid") {
// @Override
// public Object convert(Object sourceValue) {
// return "c1001zhyc-" + (String) sourceValue;
// }
// });
//
// // this.put("areaid", value);
// this.put("hospitalname", "hospitalname");
// this.put("hospitallevel", "hospitallevel");
// this.put("hospitallevelname", "hospitallevelname");
// this.put("hospitalsmallpicurl", "hospitalsmallpicurl");
// this.put("hospitalmiddlepicurl", "hospitalmiddlepicurl");
// this.put("hospitalbigpicurl", "hospitalbigpicurl");
// this.put("hospitaladdr", "hospitaladdr");
// // this.put("hospitaldes", value);
// this.put("zipcode", "zipcode");
// this.put("phone", "phone");
// this.put("website", "website");
// // this.put("ordernum", value);
// // this.put("ghinfo", value);
// this.put("createTime", new Date());
// this.put("modifyTime", new Date());
// this.put("dr", 2);
// }
// };
// List<Map> sources = (List<Map>) MapUtils.getValue(xml2Map, "response->data->data_row");
// for (Map source : sources) {
// Object obj = ConvertUtils.convertByMap(Hospital.class, mapper, source);
// System.out.println(obj);
// }
// // System.out.println(sources);
// }
}

View File

@ -0,0 +1,160 @@
package cn.card.health.common.utils.http;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import cn.card.health.common.enums.EnumMethod;
import cn.card.health.common.utils.MyX509TrustManager;
public class HttpRequestUtil {
/**
* 发起https请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式GETPOST
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
System.err.println(requestMethod + "\toutputStr=" + outputStr);
// JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式GET/POST
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
// System.out.println("jsonObject="+jsonObject);
} catch (ConnectException ce) {
ce.printStackTrace();
System.out.println("网络链接失败!");
} catch (UnknownHostException uhe) {
uhe.printStackTrace();
System.out.println("微信API无法访问....");
// httpRequest(requestUrl, requestMethod, outputStr);
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString();
}
/**
* 发起https请求并获取字节数组结果
*
* @param requestUrl
* @param requestMethod
* @param data
* @return
*/
public static byte[] httpRequest_byte(String requestUrl, String requestMethod, byte[] data) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
if (requestMethod == EnumMethod.GET.name() && data != null && data.length > 0) {
if (requestUrl.indexOf('?') > 0) {
requestUrl += '&';
} else {
requestUrl += '?';
}
requestUrl += new String(data);
}
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
if (httpUrlConn instanceof HttpsURLConnection) {
// 创建SSLContext对象并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
((HttpsURLConnection) httpUrlConn).setSSLSocketFactory(ssf);
}
boolean truePost = requestMethod == EnumMethod.POST.name() && data != null && data.length > 0;
httpUrlConn.setDoOutput(truePost);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式GET/POST
httpUrlConn.setRequestMethod(requestMethod);
if (requestMethod == EnumMethod.GET.name()) {
httpUrlConn.connect();
} else if (truePost) {
// 提交数据
OutputStream outputStream = httpUrlConn.getOutputStream();
outputStream.write(data);
outputStream.close();
}
// 读取返回数据
InputStream inputStream = httpUrlConn.getInputStream();
byte[] buf = new byte[1024 * 2];
int len;
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
// 释放资源
out.close();
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
} catch (ConnectException ce) {
} catch (Exception e) {
}
return out.toByteArray();
}
}

View File

@ -0,0 +1,33 @@
package cn.card.health.common.utils.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Https {
public static String https(String url, String method) throws IOException {
URL serverUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();
conn.setRequestMethod(method);
conn.setRequestProperty("Content-type", "application/json");
// 必须设置false否则会自动redirect到重定向后的地址
conn.setInstanceFollowRedirects(false);
conn.connect();
StringBuffer buffer = new StringBuffer();
// 将返回的输入流转换成字符串
try (InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);) {
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
String result = buffer.toString();
return result;
}
}
}

View File

@ -0,0 +1,227 @@
package cn.card.health.common.utils.sign;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* AES加密
* by poplar created on 2020/1/26
*/
public class AESHelper {
// private static final String _KEY = "C6EE3AFB0AE8715615A7C4B15386F0B2";
private static final String _KEY = "EFB19D8AD100E310404A9A34AF01E7BC";
// private static final String _KEY = AbandonConfig.getAESSecretKey();
// private static final String ARITHMETIC = "AES/ECB/PKCS5Padding";
private static final String ARITHMETIC = "AES/ECB/PKCS5Padding";
private static Cipher cipherEncrypt;
private static Cipher cipherDecrypt;
static{
// String key = _KEY.substring(6, 6+16);
String key = _KEY;
try {
// 1.构造密钥生成器指定为AES算法,不区分大小写
KeyGenerator kgen = KeyGenerator.getInstance("AES");
// 2.根据ecnodeRules规则初始化密钥生成器
// 生成一个128位的随机源,根据传入的字节数组
kgen.init(128);
cipherEncrypt = Cipher.getInstance(ARITHMETIC);
cipherEncrypt.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes(),
"AES"));
cipherDecrypt = Cipher.getInstance(ARITHMETIC);
cipherDecrypt.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(),
"AES"));
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}
public static String encrypt(String content) {
try {
byte[] encrypted = cipherEncrypt.doFinal(content
.getBytes(StandardCharsets.UTF_8));
return Base64.encode(encrypted);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String encrypt(byte[] bytes) {
try {
// // 1.构造密钥生成器指定为AES算法,不区分大小写
// KeyGenerator kgen = KeyGenerator.getInstance("AES");
// // 2.根据ecnodeRules规则初始化密钥生成器
// // 生成一个128位的随机源,根据传入的字节数组
// kgen.init(128);
// Cipher cipher = Cipher.getInstance(ARITHMETIC);
// cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(_KEY.getBytes(),
// "AES"));
byte[] encrypted = cipherEncrypt.doFinal(bytes);
return Base64.encode(encrypted);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String decrypt(String encrypted) {
try {
// // 1.构造密钥生成器指定为AES算法,不区分大小写
// KeyGenerator kgen = KeyGenerator.getInstance("AES");
// // 2.根据ecnodeRules规则初始化密钥生成器
// // 生成一个128位的随机源,根据传入的字节数组
// kgen.init(128);
// Cipher cipher = Cipher.getInstance(ARITHMETIC);
// cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(_KEY.getBytes(),
// "AES"));
// 采用base64算法进行转码,避免出现中文乱码
byte[] encrypt = Base64.decode(encrypted);
byte[] decryptBytes = cipherDecrypt.doFinal(encrypt);
return new String(decryptBytes, StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 微信手机号解密
* @param encrypted
* @param session_key
* @return
*/
public static String decrypt_wechat(String encrypted, String session_key, String iv_key) {
try {
// Security.addProvider(new BouncyCastleProvider());
// 1.构造密钥生成器指定为AES算法,不区分大小写
// KeyGenerator kgen = KeyGenerator.getInstance("AES");
// // 2.根据ecnodeRules规则初始化密钥生成器
// // 生成一个128位的随机源,根据传入的字节数组
// kgen.init(128);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec IV = new IvParameterSpec(Base64.decode(iv_key));
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64.decode(session_key),
"AES"), IV);
// 采用base64算法进行转码,避免出现中文乱码
byte[] encrypt = Base64.decode(encrypted);
byte[] decryptBytes = cipher.doFinal(encrypt);
return new String(decryptBytes, StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// /**
// * 解密工具直接放进去即可
// */
// public static String decryptS5(String sSrc, String encodingFormat, String sKey, String ivParameter) throws Exception {
// try {
//// BASE64Decoder decoder = new BASE64Decoder();
//// byte[] raw = decoder.decodeBuffer(sKey);
// Base64 decoder = new Base64();
// byte[] raw = decoder.decode(sKey);
// SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
//// IvParameterSpec iv = new IvParameterSpec(decoder.decodeBuffer(ivParameter));
// IvParameterSpec iv = new IvParameterSpec(decoder.decode(ivParameter));
// Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
// byte[] myendicod = decoder.decode(sSrc);
//// byte[] myendicod = decoder.decodeBuffer(sSrc);
// byte[] original = cipher.doFinal(myendicod);
// String originalString = new String(original, encodingFormat);
// return originalString;
// } catch (Exception ex) {
// return null;
// }
// }
// public static void main(String[] args) {
// String text = "dVnYjCxTSRkx54Zd4It5jldn238zSaVEjfVgHLolDD3JwqAzkXkZ+epL8wGPR/ifBeqQH3lo90dRKCArsTu7zvTnQqMbKfj00NVhr4bGZbgvaq4PmrBzxKMwQpRxICosEaPKS5u2a6CFIPKBBs2lrKvRsQs/QZZu4uqKJepQp4FNYzqO+/vOvYU9PCC4+bNhHXPmdCUvF+ST2gvnuYWpHA==";
// String session_key="EIU73GaUaFffHvVdVnCl3Q==";
// String iv_key="aq8zLWK2gmrS3+PUYmI7aQ==";
// String phone = AESHelper.decrypt_wechat(text, session_key, iv_key);
//// String phone;
// try {
//// phone = AESHelper.decryptS5(text, "utf-8",session_key,iv_key);
// System.out.println(phone);
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// // String str = "{\"hospid\":\"103\",\"errtype\":2}";
// // //
// // String content = "";
// // // // for (int i = 0; i < 20; i++) {
// // // // content += str;
// // // // }
// // content = str;
// // // content = "123";
// // System.out.println("加密前: " + content);
// // System.out.println("压缩后: " + content);
// // String content = "aaa";
// // content = GZIPUtils.compress(content);
// // String encryptContent = encrypt(content);
// // String encryptContent =
// // "RS2pBJWokiCT6qWlv+vj5aKToElvcMA/GCNqj4LVNAf0CqblZCuVA1Mjax56sMCJDFNpftTi3EYnkTGr4ydb2g==";
// // "aE9gkp2MJ3cOXc7n8sOMho4BnsCxl3BE7HZvULJPNw8diCo+OizCNVvzr8lhYcO1QSCKo4M7tlx7RkadtzmFvYquAYBczw+fY2REi1xNElo=";
//
// // System.out.println("加密后:" + encryptContent);
// // //
// // String decryptContent = decrypt(encryptContent);
// // System.out.println("解密后:" + decryptContent);
// // decryptContent = GZIPUtils.unCompress(decryptContent);
// // System.out.println("解缩后:" + decryptContent);
// //
//// String content = "{\"hospid\":\"103\",\"errtype\":好好学习,天天向上}";
//// content = GZIPUtils.compress(content);
////// byte[] bytes = GZIPUtils.compressBytes(content);
//// System.out.println("压缩后:" + content);
//// String encryptContent = encrypt(content);
//// System.out.println("加密后:" + encryptContent);
// // encryptContent = "AA" + encryptContent + "YC";
// // encryptContent = encryptContent.substring(2,
// // encryptContent.length()-2);
// // // encryptContent =
// // "pc8jUHKcM5HmbsVQrCkDvPGqGEuruOov411cbEQVHpG5VjooH0ZPmspQ2PR2AmNbVDwv39uRU1SbChp6syZYSg==";
//
// // String ctext = "FwWKGN5hcyb62X_kEHIYybV5lk_fABHgG52udowS0-0=";
// // String encryptContent = ctext;
// // System.out.println("解密前:" + encryptContent);
// // String encryptContent =
// // "RS2pBJWokiCT6qWlv+vj5aKToElvcMA/GCNqj4LVNAegp3eKR1uZB86DSHyZZBcwL3/TJqh0y8ZsA2NoYQObKg==";
//// String decryptContent = decrypt(encryptContent);
//// System.out.println("解密后:" + decryptContent);
//// decryptContent = GZIPUtils.unCompress(decryptContent);
//// System.out.println("解压后:" + decryptContent);
//
// // System.out.println(KEY);
// // String content = "102";
// // content = encrypt(content);
// // System.out.println(content);
// }
// public static void main(String args[]) {
// String content = "D+SLU8Bvp7LfTAAxF8Z/98U2vVmxdbYQ28YOYAUEJlzXxfoNL1e25wNE2xlIZ2iE5wYBzetY2OacscW/nHGBiFo1efLbhCjBIym5x0xGPR8AEZxZrYNZ5ZgtBgt+tj6GZAvIUCnGn2AkZVDRp6lNGpPveldug5SIYI7gVezWa0Ue/CoplZFbzpsXzAQ9iiJY4W+tqp0GMDUfLHjEsx+WoqA6jbw7AKgenOiZVdgFs+GeuSFmHXa+ccaJg3DEe43xvwhddfduHSrIBUnYcC0VmNzm5WSUzlyY4jm4OunEgozwcAARR/u0efXOEGjhTYm9aYhd/s8fvkc1SeZ+VmQuqzzXQrP+n+KfRgK8ZrEvn0FWj65zXi/D4a6b2XeLpdD9hwbE+l1D5ayn5zcpKsQ/0V2DM/QyySqQ2FbSI6rjQ+rfIMGvhjt7EdRZNodUTUuHgWJZ2ZOOHHHvCg9t57e+3suI7boCDNs3ktsEnlyPaqqW7uAcXeSZ/Kw3YEBlGuI9fyK7X9qEZUeVfVXJBZkmuI5GA/w05UuhuJ96/wAn4CluyNemScRnR5xoJ96+HVQfIIvKfGvzBJoa0QB9AHEeGowmnUYRKbIK9x3/ReAbrVWFaSqh2Bmp+8exwvcRnNqk23jtc7cZtpyLgAkEXaozdRtTje4L7wGs/AzerZ17TvJnOJN9HMd1eWOZ6rBtN2A3tNavkEDRY9stVLEexFG+jnLvEfGMkGiEP1bT/H+Cwe8jMubCDGQV7Q+DCBFmqpghxrTl84UD7SFgmCS7O5MFM0lhbKVnWf3o7VcKlbxjrjVvzpfmhsk/rZIPocyVUiD2HbKHx1yDjUBH4xGM/PRqQm57p0L+ho3sW548e6Rl9olntnMgw7zYnRM1W/8fU+w9GQKm4HpF/27IEiJBA31rpNTBA2af51W41hup8xuUVvbba171Zw5C9Jdqp+eIKuWCZX4WnHZfTyMZzY48eUlRekDQsizDYOSVyW/Z2ojRsE6vBU/6sojGZrHXqft5SO52Wng3vTEdswvrTgom2bDG0s2xE/VyUQlI6WbThNDZX1JNvvPhIr1bkVjBvsgRZLQK+hD/BtjWzYZxFeBAU85LQwDsNyxCNGIOqxpmosagIYWG625QLqgsdo+EEu+hvN1cuk9O+aMt2zKYiwuilEjV3o2rKKwua1NrpptJQval5SaFbYgSVeskEZzXt/uZ6BlLoUwxdrEptpYc5YG476silhRDCnzsN3ZRK125JXj35nbLhbWFmAVsSEunL747yWMgUO5KvBQ539Sx2qEmEOmfGblY7QSsHXDaHA17DU/seUtWX63iE13DxaCe3ZY9cbuR2H12BEcEwSyBNNG4df2MpPI6FXgCH1NwfcjOHlZCouiXHKj4m5FqpLadcsSdT2XMU9gXhsU9royssA0Hus7YAmIcWgLLgpWOl8IOukc5omDJHdioI0GaUFM9IDO3KwpkLh/HqoJCy21sgKUHN/+UvNmpb6Jlw++d1MulsqsabNO1TGN1RP6+7fJwY/xQBE9WkW14Z4T9NpRO0TaZxoylBLYCzDROlGARPLZgeaWgzHebZKQTl48qMLxUdDKaNHXMueX/Or/hCwZvLa70XHEGdHbeSkL1lR+sWvta8iu2xijkfd3HWIwJoq7R2CKdU9w8irRzP8QWvAGJOBQcuMH13Q6LYcNIYjSSiUTtlWb5dAnfVbX4I0zIcBo0//UopYtRhkGIpUjavop70j1KEOR2dW+s8WdihNHvf4YUUUO6WJ0+RfHHgQd7UZgnsXMsdNLS3WZZZnHd6/WK9mi13CzVeSk+/7PNRu4Bkx1wRZkzOdFtmfXcD+tXRcTBuC6uMOuwYyqMeLnM0uRDQx45hC+BW3ACVogFbw==";
//// System.out.println(content);
// System.out.println(_KEY.length());
// System.out.println(decrypt(content));
// }
}

View File

@ -0,0 +1,53 @@
//package cn.card.health.common.utils.sign;
//
//import java.io.IOException;
//import java.security.GeneralSecurityException;
//import java.security.InvalidAlgorithmParameterException;
//import java.security.InvalidKeyException;
//import java.security.NoSuchAlgorithmException;
//
//import javax.crypto.Cipher;
//import javax.crypto.NoSuchPaddingException;
//import javax.crypto.spec.GCMParameterSpec;
//import javax.crypto.spec.SecretKeySpec;
//import java.util.Base64;
//
//public class AESUtil
//{
// static final int KEY_LENGTH_BYTE = 32;
// static final int TAG_LENGTH_BIT = 128;
// private final byte[] aesKey;
//
// public AESUtil(byte[] key)
// {
// if (key.length != 32) {
// throw new IllegalArgumentException("无效的ApiV3Key长度必须为32个字节");
// }
// this.aesKey = key;
// }
//
// public String decryptToString(byte[] associatedData, byte[] nonce, String ciphertext)
// throws GeneralSecurityException, IOException
// {
// try
// {
// Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
//
// SecretKeySpec key = new SecretKeySpec(this.aesKey, "AES");
// GCMParameterSpec spec = new GCMParameterSpec(128, nonce);
//
// cipher.init(2, key, spec);
// cipher.updateAAD(associatedData);
//
// return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), "utf-8");
// }
// catch (NoSuchAlgorithmException|NoSuchPaddingException e)
// {
// throw new IllegalStateException(e);
// }
// catch (InvalidKeyException|InvalidAlgorithmParameterException e)
// {
// throw new IllegalArgumentException(e);
// }
// }
//}

View File

@ -0,0 +1,291 @@
package cn.card.health.common.utils.sign;
/**
* Base64工具类
*
* @author yc
*/
public final class Base64
{
static private final int BASELENGTH = 128;
static private final int LOOKUPLENGTH = 64;
static private final int TWENTYFOURBITGROUP = 24;
static private final int EIGHTBIT = 8;
static private final int SIXTEENBIT = 16;
static private final int FOURBYTE = 4;
static private final int SIGN = -128;
static private final char PAD = '=';
static final private byte[] base64Alphabet = new byte[BASELENGTH];
static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];
static
{
for (int i = 0; i < BASELENGTH; ++i)
{
base64Alphabet[i] = -1;
}
for (int i = 'Z'; i >= 'A'; i--)
{
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--)
{
base64Alphabet[i] = (byte) (i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--)
{
base64Alphabet[i] = (byte) (i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i <= 25; i++)
{
lookUpBase64Alphabet[i] = (char) ('A' + i);
}
for (int i = 26, j = 0; i <= 51; i++, j++)
{
lookUpBase64Alphabet[i] = (char) ('a' + j);
}
for (int i = 52, j = 0; i <= 61; i++, j++)
{
lookUpBase64Alphabet[i] = (char) ('0' + j);
}
lookUpBase64Alphabet[62] = (char) '+';
lookUpBase64Alphabet[63] = (char) '/';
}
private static boolean isWhiteSpace(char octect)
{
return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
}
private static boolean isPad(char octect)
{
return (octect == PAD);
}
private static boolean isData(char octect)
{
return (octect < BASELENGTH && base64Alphabet[octect] != -1);
}
/**
* Encodes hex octects into Base64
*
* @param binaryData Array containing binaryData
* @return Encoded Base64 array
*/
public static String encode(byte[] binaryData)
{
if (binaryData == null)
{
return null;
}
int lengthDataBits = binaryData.length * EIGHTBIT;
if (lengthDataBits == 0)
{
return "";
}
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
char encodedData[] = null;
encodedData = new char[numberQuartet * 4];
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
int encodedIndex = 0;
int dataIndex = 0;
for (int i = 0; i < numberTriplets; i++)
{
b1 = binaryData[dataIndex++];
b2 = binaryData[dataIndex++];
b3 = binaryData[dataIndex++];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
}
// form integral number of 6-bit groups
if (fewerThan24bits == EIGHTBIT)
{
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex++] = PAD;
encodedData[encodedIndex++] = PAD;
}
else if (fewerThan24bits == SIXTEENBIT)
{
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
encodedData[encodedIndex++] = PAD;
}
return new String(encodedData);
}
/**
* Decodes Base64 data into octects
*
* @param encoded string containing Base64 data
* @return Array containind decoded data.
*/
public static byte[] decode(String encoded)
{
if (encoded == null)
{
return null;
}
char[] base64Data = encoded.toCharArray();
// remove white spaces
int len = removeWhiteSpace(base64Data);
if (len % FOURBYTE != 0)
{
return null;// should be divisible by four
}
int numberQuadruple = (len / FOURBYTE);
if (numberQuadruple == 0)
{
return new byte[0];
}
byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
char d1 = 0, d2 = 0, d3 = 0, d4 = 0;
int i = 0;
int encodedIndex = 0;
int dataIndex = 0;
decodedData = new byte[(numberQuadruple) * 3];
for (; i < numberQuadruple - 1; i++)
{
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++]))
|| !isData((d3 = base64Data[dataIndex++])) || !isData((d4 = base64Data[dataIndex++])))
{
return null;
} // if found "no data" just return null
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
if (!isData((d1 = base64Data[dataIndex++])) || !isData((d2 = base64Data[dataIndex++])))
{
return null;// if found "no data" just return null
}
b1 = base64Alphabet[d1];
b2 = base64Alphabet[d2];
d3 = base64Data[dataIndex++];
d4 = base64Data[dataIndex++];
if (!isData((d3)) || !isData((d4)))
{// Check if they are PAD characters
if (isPad(d3) && isPad(d4))
{
if ((b2 & 0xf) != 0)// last 4 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 1];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
return tmp;
}
else if (!isPad(d3) && isPad(d4))
{
b3 = base64Alphabet[d3];
if ((b3 & 0x3) != 0)// last 2 bits should be zero
{
return null;
}
byte[] tmp = new byte[i * 3 + 2];
System.arraycopy(decodedData, 0, tmp, 0, i * 3);
tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
return tmp;
}
else
{
return null;
}
}
else
{ // No PAD e.g 3cQl
b3 = base64Alphabet[d3];
b4 = base64Alphabet[d4];
decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
}
return decodedData;
}
/**
* remove WhiteSpace from MIME containing encoded Base64 data.
*
* @param data the byte array of base64 data (with WS)
* @return the new length
*/
private static int removeWhiteSpace(char[] data)
{
if (data == null)
{
return 0;
}
// count characters that's not whitespace
int newSize = 0;
int len = data.length;
for (int i = 0; i < len; i++)
{
if (!isWhiteSpace(data[i]))
{
data[newSize++] = data[i];
}
}
return newSize;
}
}

View File

@ -0,0 +1,105 @@
package cn.card.health.common.utils.spring;
import cn.card.health.bean.user.LoginUser;
import cn.card.health.common.exception.base.ServiceException;
import cn.card.health.common.utils.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* 安全服务工具类
*
* @author ruoyi
*/
public class SecurityUtils
{
/**
* 用户ID
**/
public static Long getUserId()
{
try
{
return getLoginUser().getUserid();
}
catch (Exception e)
{
throw new ServiceException("获取用户ID异常", HttpStatus.UNAUTHORIZED);
}
}
/**
* 获取用户账户
**/
public static String getUsername()
{
try
{
return getLoginUser().getUsername();
}
catch (Exception e)
{
throw new ServiceException("获取用户账户异常", HttpStatus.UNAUTHORIZED);
}
}
/**
* 获取用户
**/
public static LoginUser getLoginUser()
{
try
{
return (LoginUser) getAuthentication().getPrincipal();
}
catch (Exception e)
{
throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
}
}
/**
* 获取Authentication
*/
public static Authentication getAuthentication()
{
return SecurityContextHolder.getContext().getAuthentication();
}
/**
* 生成BCryptPasswordEncoder密码
*
* @param password 密码
* @return 加密字符串
*/
public static String encryptPassword(String password)
{
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.encode(password);
}
/**
* 判断密码是否相同
*
* @param rawPassword 真实密码
* @param encodedPassword 加密后字符
* @return 结果
*/
public static boolean matchesPassword(String rawPassword, String encodedPassword)
{
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.matches(rawPassword, encodedPassword);
}
/**
* 是否为管理员
*
* @param userId 用户ID
* @return 结果
*/
public static boolean isAdmin(Long userId)
{
return userId != null && 1L == userId;
}
}

View File

@ -0,0 +1,146 @@
package cn.card.health.common.utils.spring;
import cn.card.health.common.utils.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* spring工具类 方便在非spring管理环境中获取bean
*
* @author ruoyi
*/
@Component
public final class SpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware
{
/** Spring应用上下文环境 */
private static ConfigurableListableBeanFactory beanFactory;
private static ApplicationContext applicationContext;
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
{
SpringUtils.beanFactory = beanFactory;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
SpringUtils.applicationContext = applicationContext;
}
/**
* 获取对象
*
* @param name
* @return Object 一个以所给名字注册的bean的实例
* @throws BeansException
*
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException
{
return (T) beanFactory.getBean(name);
}
/**
* 获取类型为requiredType的对象
*
* @param clz
* @return
* @throws BeansException
*
*/
public static <T> T getBean(Class<T> clz) throws BeansException
{
T result = (T) beanFactory.getBean(clz);
return result;
}
/**
* 如果BeanFactory包含一个与所给名称匹配的bean定义则返回true
*
* @param name
* @return boolean
*/
public static boolean containsBean(String name)
{
return beanFactory.containsBean(name);
}
/**
* 判断以给定名字注册的bean定义是一个singleton还是一个prototype 如果与给定名字相应的bean定义没有被找到将会抛出一个异常NoSuchBeanDefinitionException
*
* @param name
* @return boolean
* @throws NoSuchBeanDefinitionException
*
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.isSingleton(name);
}
/**
* @param name
* @return Class 注册对象的类型
* @throws NoSuchBeanDefinitionException
*
*/
public static Class<?> getType(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.getType(name);
}
/**
* 如果给定的bean名字在bean定义中有别名则返回这些别名
*
* @param name
* @return
* @throws NoSuchBeanDefinitionException
*
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException
{
return beanFactory.getAliases(name);
}
/**
* 获取aop代理对象
*
* @param invoker
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getAopProxy(T invoker)
{
return (T) AopContext.currentProxy();
}
/**
* 获取当前的环境配置无配置返回null
*
* @return 当前的环境配置
*/
public static String[] getActiveProfiles()
{
return applicationContext.getEnvironment().getActiveProfiles();
}
/**
* 获取当前的环境配置当有多个环境配置时只获取第一个
*
* @return 当前的环境配置
*/
public static String getActiveProfile()
{
final String[] activeProfiles = getActiveProfiles();
return StringUtils.isNotEmpty(activeProfiles) ? activeProfiles[0] : null;
}
}

View File

@ -0,0 +1,78 @@
package cn.card.health.common.utils.wechat;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
public class AESUtils {
static final int KEY_LENGTH_BYTE = 32;
static final int TAG_LENGTH_BIT = 128;
private final byte[] aesKey;
private final static String keyv3 = "BE3F4E196937F9308899D7CA4C8664AA";
//private final static String keyv3 = WechatConfig.service_app_secret_v3;
public AESUtils(byte[] key) {
if (key.length != 32) {
throw new IllegalArgumentException("无效的ApiV3Key长度必须为32个字节");
}
this.aesKey = key;
}
public AESUtils() {
this.aesKey = keyv3.getBytes();
}
public String decryptToString(byte[] associatedData, byte[] nonce, String ciphertext)
throws GeneralSecurityException, IOException {
try {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec key = new SecretKeySpec(this.aesKey, "AES");
GCMParameterSpec spec = new GCMParameterSpec(128, nonce);
// Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(2, key, spec);
cipher.updateAAD(associatedData);
return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), "utf-8");
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new IllegalStateException(e);
} catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
throw new IllegalArgumentException(e);
}
}
// public static void main(String[] args) {
//// System.out.println("11");
// String associatedData = "transaction";
// String nonce = "60wDrk25d4fo";
// String ciphertext = "G9zwQQvWMRUO27R+ko8c3bhGupbL0c/9OUPHPiH6bF9xXYJG0yXbnl25v6kC/Il+k0qOnDXFa5ifsVOVN2UCpDFK/EdoAsFMvm7+xOQV4Ala0oFgiaOQyy63WGeCH6KODDvpJS7ujVJ+Z3rmt+up3dgrhzv57wc0MOqNI0xvzBIAPoYwSI8P3FLdzS28+8/WfeoC4cbLfDZGAkmjmdsxIdLDbWfFL2RYa4B3PnBrcp2dTwfGLjb0V1phY4jwBxI5McKChFY3spp7GKLpmJ1cBYZ5E3vbpZEARXXTPS0Ql6cqeMBL9vizkECAe4AxH38MbO+c+kL/+ofvdLJvJe0XBOfpGFjM8squ66oi3y7BlNw3vOx5sdnQ0WggZWEzsFaKDmcGoDe9xD+4NYe7lvcgYCBpmYRdjQWa9nlQ36q9ind4FJwdGVZiBx8DnVabGtPlpnyrKpE+soucF9Z0Ne+B68zCzBnhXL9i2rH24D07ul+ah1Wdna9ioaZG1P1Rszp2MFqA//Yxbs3fHQbq/jZ917Qjh8vUPu9EYpsMgDiIyrcU5V2+HodJnKnYZib1D3uNjfw5PugBD37jkSfZIEs4dA==";
// AESUtils aes = new AESUtils(keyv3.getBytes());
// String content;
// try {
// content = aes.decryptToString(associatedData.getBytes(), nonce.getBytes(), ciphertext);
// System.out.println(content);
// } catch (GeneralSecurityException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
//// String content = "鏀粯鎴愬姛";
//// try {
//// System.out.println(new String(content.getBytes("GBK"), "utf-8"));
//// } catch (UnsupportedEncodingException e) {
//// // TODO Auto-generated catch block
//// e.printStackTrace();
//// }
// }
}

View File

@ -0,0 +1,161 @@
package cn.card.health.common.utils.wechat;
import com.alibaba.fastjson.JSONObject;
import cn.card.health.common.utils.BaseResultJSON;
/**
* 用来接收微信返回参数
*
* @author xinggm
* @date 2021年5月27日
*/
public class ResponseWechatJSON {
/** 返回json */
private JSONObject jsonResp;
/** 返回commonOutjson */
private JSONObject jsonCommonOut;
/** 返回json */
private JSONObject jsonRsp;
/** 请求requestId */
private String requestId;
/** 返回值 */
private int resultCode = -1;
private BaseResultJSON baseResultJSON;
/** 错误消息 */
private String errMsg;
ResponseWechatJSON() {
}
ResponseWechatJSON(JSONObject json) {
this.jsonResp = json;
if (this.jsonResp == null || !this.jsonResp.containsKey("commonOut")) {
JSONObject retJson = new JSONObject();
this.jsonCommonOut = retJson;
this.baseResultJSON = new BaseResultJSON(resultCode, "微信返回数据为空");
return;
}
this.setJsonCommonOut(this.jsonResp.getJSONObject("commonOut"));
this.setJsonRsp(this.getJsonResp().getJSONObject("rsp"));
this.baseResultJSON.putAll(this.getJsonRsp());
}
ResponseWechatJSON(JSONObject json, String[] keys) {
this.jsonResp = json;
if (this.jsonResp == null || !this.jsonResp.containsKey("commonOut")) {
JSONObject retJson = new JSONObject();
this.jsonCommonOut = retJson;
this.baseResultJSON = new BaseResultJSON(resultCode, "微信返回数据为空");
return;
}
this.setJsonCommonOut(this.jsonResp.getJSONObject("commonOut"));
if (this.resultCode == 0) {
this.setJsonRsp(this.getJsonResp().getJSONObject("rsp"));
JSONObject retJson = this.getJsonRsp(keys);
this.getBaseResultJSON().putAll(retJson);
}
}
/** 初始化 */
public static ResponseWechatJSON getInstance() {
return new ResponseWechatJSON();
}
/** 初始化 */
public static ResponseWechatJSON getInstance(JSONObject json) {
return new ResponseWechatJSON(json);
}
/** 初始化 */
public static ResponseWechatJSON getInstance(JSONObject json, String... keys) {
return new ResponseWechatJSON(json, keys);
}
/** 获得公共参数 */
public void getCommonOut(JSONObject json) {
if (json != null) {
}
}
/** 获得公共参数 */
public void getCommonOut() {
}
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
public JSONObject getJsonResp() {
return jsonResp;
}
public void setJsonResp(JSONObject jsonResp) {
this.jsonResp = jsonResp;
}
public JSONObject getJsonCommonOut() {
return jsonCommonOut;
}
public void setJsonCommonOut(JSONObject jsonCommonOut) {
this.jsonCommonOut = jsonCommonOut;
if (this.jsonCommonOut != null) {
this.resultCode = jsonCommonOut.getIntValue("resultCode");
this.requestId = jsonCommonOut.getString("requestId");
this.errMsg = jsonCommonOut.getString("errMsg");
}
this.baseResultJSON = new BaseResultJSON(this.resultCode, this.errMsg);
}
public JSONObject getJsonRsp(String... keys) {
if (keys == null || keys.length == 0)
return jsonRsp;
else {
JSONObject retJson = this.jsonRsp;
for (String key : keys) {
retJson = retJson.getJSONObject(key);
}
return retJson;
}
}
public void setJsonRsp(JSONObject jsonRsp) {
this.jsonRsp = jsonRsp;
// if (this.jsonResp == null) {
// this.baseResultJSON = BaseResultJSON.error(this.resultCode, "微信返回错误");
// return;
// }
// if (this.jsonResp.containsKey("commonOut")) {
// this.setJsonCommonOut(jsonResp.getJSONObject("commonOut"));
// }
}
public BaseResultJSON getBaseResultJSON() {
return baseResultJSON;
}
}

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