LiTaohong vor 6 Jahren
Ursprung
Commit
6bbcc6919d
100 geänderte Dateien mit 6850 neuen und 1874 gelöschten Zeilen
  1. 2 2
      common/common-entity/src/main/java/com/yihu/jw/entity/base/patient/BasePatientDO.java
  2. 56 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/patient/BasePatientFamilyMemberDO.java
  3. 46 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/score/BaseEvaluateDO.java
  4. 136 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/score/BaseEvaluateScoreDO.java
  5. 2 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/sms/SmsDO.java
  6. 32 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/statistics/JobConfigDO.java
  7. 90 0
      common/common-entity/src/main/java/com/yihu/jw/entity/base/statistics/JobLogDO.java
  8. 1 1
      common/common-entity/src/main/java/com/yihu/jw/entity/base/team/BaseTeamDO.java
  9. 36 0
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/HospitalServiceItemDO.java
  10. 1 1
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/SpecialistServiceItemDO.java
  11. 2 1
      common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/RehabilitationOperateRecordsDO.java
  12. 21 0
      common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseRequestMapping.java
  13. 8 0
      common/common-request-mapping/src/main/java/com/yihu/jw/rm/specialist/SpecialistMapping.java
  14. 61 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/patient/PatientFamilyMemberVO.java
  15. 17 15
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/servicePackage/ServicePackagePropvalueDO.java
  16. 3 1
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/sms/SmsVO.java
  17. 62 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/team/TeamMemberVO.java
  18. 80 0
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/team/TeamVO.java
  19. 21 1
      common/common-rest-model/src/main/java/com/yihu/jw/restmodel/specialist/PatientDisseaseInfoVO.java
  20. 182 0
      common/common-util/src/main/java/com/yihu/jw/util/idcard/IdCardUtil.java
  21. 1 1
      gateway/ag-basic/src/main/resources/application.yml
  22. 10 0
      server/svr-authentication/src/main/java/com/yihu/AuthServer.java
  23. 2 0
      server/svr-authentication/src/main/java/com/yihu/jw/security/config/WlyyWebSecurityConfigurerAdapter.java
  24. 4 0
      server/svr-authentication/src/main/java/com/yihu/jw/security/core/userdetails/SaltUser.java
  25. 36 10
      server/svr-authentication/src/main/java/com/yihu/jw/security/core/userdetails/jdbc/WlyyUserDetailsService.java
  26. 42 0
      server/svr-authentication/src/main/java/com/yihu/jw/security/model/Captcha.java
  27. 2 1
      server/svr-authentication/src/main/java/com/yihu/jw/security/model/Oauth2Envelop.java
  28. 31 0
      server/svr-authentication/src/main/java/com/yihu/jw/security/model/PublicKey.java
  29. 2 1
      server/svr-authentication/src/main/java/com/yihu/jw/security/model/WlyyUserSimple.java
  30. 5 2
      server/svr-authentication/src/main/java/com/yihu/jw/security/oauth2/config/WlyyAuthorizationServerConfigurerAdapter.java
  31. 19 5
      server/svr-authentication/src/main/java/com/yihu/jw/security/oauth2/core/redis/WlyyRedisVerifyCodeService.java
  32. 61 62
      server/svr-authentication/src/main/java/com/yihu/jw/security/oauth2/provider/WlyyTokenGranter.java
  33. 174 109
      server/svr-authentication/src/main/java/com/yihu/jw/security/oauth2/provider/endpoint/WlyyLoginEndpoint.java
  34. 5 8
      server/svr-authentication/src/main/java/com/yihu/jw/security/oauth2/provider/endpoint/WlyyTokenEndpoint.java
  35. 5 5
      server/svr-authentication/src/main/resources/application.yml
  36. 41 16
      svr/svr-base/src/main/java/com/yihu/jw/base/activemq/ConsumerRunner.java
  37. 0 57
      svr/svr-base/src/main/java/com/yihu/jw/base/config/BaseJpa.java
  38. 0 43
      svr/svr-base/src/main/java/com/yihu/jw/base/config/HibernateProperties.java
  39. 21 14
      svr/svr-base/src/main/java/com/yihu/jw/base/config/SwaggerDocs.java
  40. 6 14
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/patient/BasePatientDao.java
  41. 13 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/patient/BasePatientFamilyMemberDao.java
  42. 12 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/score/BaseEvaluateDao.java
  43. 11 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/score/BaseEvaluateScoreDao.java
  44. 29 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WechatDao.java
  45. 17 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxAccessTokenDao.java
  46. 15 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxGraphicMessageDao.java
  47. 15 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxGraphicSceneGroupDao.java
  48. 20 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxMenuDao.java
  49. 13 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxMenuJsonDao.java
  50. 18 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxReplySceneDao.java
  51. 15 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxTemplateConfigDao.java
  52. 21 0
      svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxTemplateDao.java
  53. 49 0
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/patient/PatientFamilyMemberEndpoint.java
  54. 44 0
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/score/ScoreEndPoint.java
  55. 138 0
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/wx/WechatConfigController.java
  56. 182 0
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/wx/WechatCoreController.java
  57. 47 0
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/wx/WxAccessTokenController.java
  58. 164 0
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/wx/WxGraphicMessageController.java
  59. 219 0
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/wx/WxMenuController.java
  60. 178 0
      svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/wx/WxTemplateController.java
  61. 121 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/patient/PatientFamilyMemberService.java
  62. 42 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/score/ScoreService.java
  63. 25 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/team/TeamService.java
  64. 353 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/wx/WechatCoreService.java
  65. 94 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/wx/WechatFansService.java
  66. 13 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/wx/WechatService.java
  67. 157 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/wx/WxAccessTokenService.java
  68. 177 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/wx/WxGraphicMessageService.java
  69. 50 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/wx/WxMenuService.java
  70. 156 0
      svr/svr-base/src/main/java/com/yihu/jw/base/service/wx/WxTemplateService.java
  71. 182 182
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/controller/WechatCoreController.java
  72. 210 210
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/controller/WxMenuController.java
  73. 171 171
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/controller/WxTemplateController.java
  74. 29 29
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WechatDao.java
  75. 17 17
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxAccessTokenDao.java
  76. 15 15
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxGraphicSceneGroupDao.java
  77. 20 20
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxMenuDao.java
  78. 13 13
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxMenuJsonDao.java
  79. 18 18
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxReplySceneDao.java
  80. 15 15
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxTemplateConfigDao.java
  81. 353 353
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WechatCoreService.java
  82. 94 94
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WechatFansService.java
  83. 13 13
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WechatService.java
  84. 157 157
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WxAccessTokenService.java
  85. 50 50
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WxMenuService.java
  86. 147 147
      svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WxTemplateService.java
  87. 170 0
      svr/svr-statistics/doc/es/QuartzJobConfig.java
  88. 127 0
      svr/svr-statistics/doc/es/QuartzJobConfig1.java
  89. 108 0
      svr/svr-statistics/doc/es/统计新增索引.txt
  90. 192 0
      svr/svr-statistics/doc/sql/统计相关表数据备份20171121.txt
  91. BIN
      svr/svr-statistics/doc/业务文档/统计指标流程.docx
  92. BIN
      svr/svr-statistics/doc/部署文档/正式库/后台/tomcat部署.docx
  93. 455 0
      svr/svr-statistics/pom.xml
  94. 120 0
      svr/svr-statistics/readme.MD
  95. 56 0
      svr/svr-statistics/src/main/java/com/yihu/wlyy/Application.java
  96. 50 0
      svr/svr-statistics/src/main/java/com/yihu/wlyy/statistics/config/AsyncConfig.java
  97. 240 0
      svr/svr-statistics/src/main/java/com/yihu/wlyy/statistics/config/DataSourceConfig.java
  98. 30 0
      svr/svr-statistics/src/main/java/com/yihu/wlyy/statistics/config/MVCConfig.java
  99. 64 0
      svr/svr-statistics/src/main/java/com/yihu/wlyy/statistics/config/SwaggerConfig.java
  100. 0 0
      svr/svr-statistics/src/main/java/com/yihu/wlyy/statistics/config/WebSecurityConfig.java

+ 2 - 2
common/common-entity/src/main/java/com/yihu/jw/entity/base/patient/BasePatientDO.java

@ -34,7 +34,7 @@ public class BasePatientDO extends UuidIdentityEntityWithOperator {
	private String password;
    /**
	 * 
	 *
	 */
	private String salt;
@ -146,7 +146,7 @@ public class BasePatientDO extends UuidIdentityEntityWithOperator {
	private String sickVillage;
    /**
	 * 
	 *
	 */
	private String sickVillageName;

+ 56 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/patient/BasePatientFamilyMemberDO.java

@ -0,0 +1,56 @@
package com.yihu.jw.entity.base.patient;
import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by Trick on 2018/8/31.
 */
@Entity
@Table(name = "base_patient_family_member")
public class BasePatientFamilyMemberDO extends UuidIdentityEntityWithOperator {
    private String patient;//居民code',
    private String familyMember;//家庭成员code',
    private Integer familyRelation;//家庭关系',
    private Integer isAuthorize;//是否授权0:未授权,1:已授权,默认为1',
    @Column(name = "patient")
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    @Column(name = "family_member")
    public String getFamilyMember() {
        return familyMember;
    }
    public void setFamilyMember(String familyMember) {
        this.familyMember = familyMember;
    }
    @Column(name = "family_relation")
    public Integer getFamilyRelation() {
        return familyRelation;
    }
    public void setFamilyRelation(Integer familyRelation) {
        this.familyRelation = familyRelation;
    }
    @Column(name = "is_authorize")
    public Integer getIsAuthorize() {
        return isAuthorize;
    }
    public void setIsAuthorize(Integer isAuthorize) {
        this.isAuthorize = isAuthorize;
    }
}

+ 46 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/score/BaseEvaluateDO.java

@ -0,0 +1,46 @@
package com.yihu.jw.entity.base.score;
import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by Trick on 2018/8/31.
 */
@Entity
@Table(name = "base_evaluate")
public class BaseEvaluateDO extends UuidIdentityEntityWithOperator {
    private String relationCode;//关联业务CODE(关联主表evlute_score)',
    private String scoreType;//评价类型:1、专业能力,2、服务态度,3、回复速度 (可拓展字段)',
    private Double score;//单项得分',
    @Column(name = "relation_code")
    public String getRelationCode() {
        return relationCode;
    }
    public void setRelationCode(String relationCode) {
        this.relationCode = relationCode;
    }
    @Column(name = "score_type")
    public String getScoreType() {
        return scoreType;
    }
    public void setScoreType(String scoreType) {
        this.scoreType = scoreType;
    }
    @Column(name = "score")
    public Double getScore() {
        return score;
    }
    public void setScore(Double score) {
        this.score = score;
    }
}

+ 136 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/score/BaseEvaluateScoreDO.java

@ -0,0 +1,136 @@
package com.yihu.jw.entity.base.score;
import com.yihu.jw.entity.UuidIdentityEntityWithOperator;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
 * Created by Trick on 2018/8/31.
 */
@Entity
@Table(name = "base_evaluate_score")
public class BaseEvaluateScoreDO extends UuidIdentityEntityWithOperator {
    private String city;//城市编码',
    private String town;//城镇编码',
    private String hospital;//医院编码',
    private String team;//团队编码',
    private String doctor;//被评价的医生编码',
    private String doctorName;//医生名字',
    private String patient;//评价人',
    private String patientName;//评价人姓名',
    private Integer evaluateType;//.咨询评价;',
    private String relationCode;//所属业务关系code,例如:1为咨询code',
    private Double score;//主表分数',
    private Integer type;//1、实名,2、匿名',
    @Column(name = "city")
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    @Column(name = "town")
    public String getTown() {
        return town;
    }
    public void setTown(String town) {
        this.town = town;
    }
    @Column(name = "hospital")
    public String getHospital() {
        return hospital;
    }
    public void setHospital(String hospital) {
        this.hospital = hospital;
    }
    @Column(name = "team")
    public String getTeam() {
        return team;
    }
    public void setTeam(String team) {
        this.team = team;
    }
    @Column(name = "doctor")
    public String getDoctor() {
        return doctor;
    }
    public void setDoctor(String doctor) {
        this.doctor = doctor;
    }
    @Column(name = "doctor_name")
    public String getDoctorName() {
        return doctorName;
    }
    public void setDoctorName(String doctorName) {
        this.doctorName = doctorName;
    }
    @Column(name = "patient")
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    @Column(name = "patient_name")
    public String getPatientName() {
        return patientName;
    }
    public void setPatientName(String patientName) {
        this.patientName = patientName;
    }
    @Column(name = "evaluate_type")
    public Integer getEvaluateType() {
        return evaluateType;
    }
    public void setEvaluateType(Integer evaluateType) {
        this.evaluateType = evaluateType;
    }
    @Column(name = "relation_code")
    public String getRelationCode() {
        return relationCode;
    }
    public void setRelationCode(String relationCode) {
        this.relationCode = relationCode;
    }
    @Column(name = "score")
    public Double getScore() {
        return score;
    }
    public void setScore(Double score) {
        this.score = score;
    }
    @Column(name = "type")
    public Integer getType() {
        return type;
    }
    public void setType(Integer type) {
        this.type = type;
    }
}

+ 2 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/sms/SmsDO.java

@ -1,5 +1,6 @@
package com.yihu.jw.entity.base.sms;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.*;
@ -85,6 +86,7 @@ public class SmsDO extends UuidIdentityEntity {
	}
	@Column(name = "deadline", nullable = false)
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
	public Date getDeadline() {
		return deadline;
	}

+ 32 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/statistics/JobConfigDO.java

@ -5,6 +5,7 @@ import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.io.Serializable;
/**
@ -16,6 +17,7 @@ import java.io.Serializable;
public class JobConfigDO extends UuidIdentityEntity implements Serializable {
    private String saasId;
    private String quotaId;//指标id
    private String jobName;//任务名称
    private String jobInfo;//任务描述
    private String jobType;//任务类型(0--单次执行  1--周期执行 2--监听任务)
@ -33,6 +35,9 @@ public class JobConfigDO extends UuidIdentityEntity implements Serializable {
    private String timeLevel;//1增量 2到达量 3生成到达量也生成增量
    private Integer incrementInterval;//增量时间间隔1天,2周,3月
    private String startTime;
    private String endTime;
    @Column(name = "saas_id")
    public String getSaasId() {
        return saasId;
@ -42,6 +47,15 @@ public class JobConfigDO extends UuidIdentityEntity implements Serializable {
        this.saasId = saasId;
    }
    @Column(name = "quota_id")
    public String getQuotaId() {
        return quotaId;
    }
    public void setQuotaId(String quotaId) {
        this.quotaId = quotaId;
    }
    @Column(name = "job_name")
    public String getJobName() {
        return jobName;
@ -182,4 +196,22 @@ public class JobConfigDO extends UuidIdentityEntity implements Serializable {
    public void setIncrementInterval(Integer incrementInterval) {
        this.incrementInterval = incrementInterval;
    }
    @Transient
    public String getStartTime() {
        return startTime;
    }
    public void setStartTime(String startTime) {
        this.startTime = startTime;
    }
    @Transient
    public String getEndTime() {
        return endTime;
    }
    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }
}

+ 90 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/base/statistics/JobLogDO.java

@ -0,0 +1,90 @@
package com.yihu.jw.entity.base.statistics;
import com.yihu.jw.entity.UuidIdentityEntity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;
/**
 * job执行日志表
 * @author yeshijie on 2018/9/3.
 */
@Entity
@Table(name = "base_quota")
public class JobLogDO extends UuidIdentityEntity implements Serializable {
    private String saasId;//
    private Date jobStartTime;//任务开始执行时间
    private Date jobEndTime;//任务结束时间
    private String jobId;//任务id
    private String jobContent;//任务执行情况
    private String jobType;// 1成功 0失败
    private String jobName;//任务名称
    @Column(name = "saas_id")
    public String getSaasId() {
        return saasId;
    }
    public void setSaasId(String saasId) {
        this.saasId = saasId;
    }
    @Column(name = "job_start_time")
    public Date getJobStartTime() {
        return jobStartTime;
    }
    public void setJobStartTime(Date jobStartTime) {
        this.jobStartTime = jobStartTime;
    }
    @Column(name = "job_end_time")
    public Date getJobEndTime() {
        return jobEndTime;
    }
    public void setJobEndTime(Date jobEndTime) {
        this.jobEndTime = jobEndTime;
    }
    @Column(name = "job_id")
    public String getJobId() {
        return jobId;
    }
    public void setJobId(String jobId) {
        this.jobId = jobId;
    }
    @Column(name = "job_content")
    public String getJobContent() {
        return jobContent;
    }
    public void setJobContent(String jobContent) {
        this.jobContent = jobContent;
    }
    @Column(name = "job_type")
    public String getJobType() {
        return jobType;
    }
    public void setJobType(String jobType) {
        this.jobType = jobType;
    }
    @Column(name = "job_name")
    public String getJobName() {
        return jobName;
    }
    public void setJobName(String jobName) {
        this.jobName = jobName;
    }
}

+ 1 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/base/team/BaseTeamDO.java

@ -10,7 +10,7 @@ import java.util.Date;
/**
* 团队信息实体
*
* @author Administrator on  2018年09月05日
* @author litaohong on  2018年08月31日
*
*/
@Entity

+ 36 - 0
common/common-entity/src/main/java/com/yihu/jw/entity/specialist/HospitalServiceItemDO.java

@ -32,12 +32,21 @@ public class HospitalServiceItemDO extends UuidIdentityEntityWithOperator implem
    @Column(name = "service_item_id")
    private String serviceItemId;//服务项目id
    @Column(name = "service_item_name")
    private String serviceItemName;//服务项目名称
    @Column(name = "status")
    private Integer status;//状态
    @Column(name = "expense")
    private Integer expense;//价格
    @Transient
    private Integer flag;//标识(1:社区,2、医院,3、社区、医院)
    @Column(name = "imediate")
    private Integer imediate;//(1:立即生效、0:未立即生效 )
    @Transient
    private SpecialistServiceItemDO specialistServiceItemDO;
@ -103,4 +112,31 @@ public class HospitalServiceItemDO extends UuidIdentityEntityWithOperator implem
    public void setExpense(Integer expense) {
        this.expense = expense;
    }
    @Column(name = "service_item_name")
    public String getServiceItemName() {
        return serviceItemName;
    }
    public void setServiceItemName(String serviceItemName) {
        this.serviceItemName = serviceItemName;
    }
    @Transient
    public Integer getFlag() {
        return flag;
    }
    public void setFlag(Integer flag) {
        this.flag = flag;
    }
    @Column(name = "imediate")
    public Integer getImediate() {
        return imediate;
    }
    public void setImediate(Integer imediate) {
        this.imediate = imediate;
    }
}

+ 1 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/specialist/SpecialistServiceItemDO.java

@ -74,7 +74,7 @@ public class SpecialistServiceItemDO extends UuidIdentityEntityWithOperator impl
    private Integer status; //删除状态
    @Transient
    public Integer flag;
    public Integer flag;//标识(1:社区,2、医院,3、社区、医院)
    @Column(name = "saas_id")

+ 2 - 1
common/common-entity/src/main/java/com/yihu/jw/entity/specialist/rehabilitation/RehabilitationOperateRecordsDO.java

@ -20,13 +20,13 @@ public class RehabilitationOperateRecordsDO extends UuidIdentityEntityWithOperat
    private String patientName;//居民名称
    private String doctorCode;//执行医生code
    private String doctorName;//执行医生名称
    private String node;//服务完成笔记
    private Integer relationRecordType;//关联记录类型(1、随访记录,2、健康指导,3、健康教育,4、服务码)
    private String relationRecordCode;//关联记录code
    private String relationRecordImg;//相关记录图片地址,json格式
    private Date reserveTime;//服务预定完成时间
    private Date completeTime;//服务完成时间
    private Integer status;//是否确认完成(0、未确认,1、已确认)
    private String node;//服务完成笔记
    @Column(name = "saas_id")
    public String getSaasId() {
@ -144,4 +144,5 @@ public class RehabilitationOperateRecordsDO extends UuidIdentityEntityWithOperat
    public void setStatus(Integer status) {
        this.status = status;
    }
}

+ 21 - 0
common/common-request-mapping/src/main/java/com/yihu/jw/rm/base/BaseRequestMapping.java

@ -180,6 +180,27 @@ public class BaseRequestMapping {
    public static class ImGetuiConfig extends Basic{
        public static final String PREFIX  = "/im_getui";
    }
    /**
     * 家庭成员管理
     */
    public static class PatientMember extends Basic{
        public static final String PREFIX = "/patient_member";
    }
    /**
     * 医生评价
     */
    public static class Score extends Basic{
        public static final String PREFIX = "/score";
    }
    /**
     * 团队
     */
    public static class team extends Basic{
        public static final String PREFIX = "/team";
    }
    /**
     * 城市字典

+ 8 - 0
common/common-request-mapping/src/main/java/com/yihu/jw/rm/specialist/SpecialistMapping.java

@ -80,6 +80,8 @@ public class SpecialistMapping {
        public static final String serviceDoctorList = "/serviceDoctorList";
        public static final String dailyJob = "/dailyJob";
        public static final String appCalendarPlanDetailList = "/appCalendarPlanDetailList";
        public static final String updatePlanDetailStatusById = "/updatePlanDetailStatusById";
        public static final String updatePlanStatusById = "/updatePlanStatusById";
    }
    public static class serviceItem{
@ -94,5 +96,11 @@ public class SpecialistMapping {
        public static final String selectByHospital = "/selectByHospital";
        public static final String selectById="/selectById";
        public static final String selectItemByHospital= "/selectItemByHospital";
        public static final String selectByOperate = "/selectByOperate";
        public static final String selectByCondition="/selectByCondition";
        public static final String deleteHospitalItem = "/deleteHospitalItem";
        public static final String selectByHospital1 = "/selectByHospital1";
        public static final String importData1 = "/importData1";
        public static final String importData2 = "/importData2";
    }
}

+ 61 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/patient/PatientFamilyMemberVO.java

@ -0,0 +1,61 @@
package com.yihu.jw.restmodel.base.patient;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
 * Created by Trick on 2018/8/31.
 */
@ApiModel(value = "PatientFamilyMemberVO", description = "家庭成员")
public class PatientFamilyMemberVO {
    @ApiModelProperty(value = "id")
    private String id;//主键id
    @ApiModelProperty(value = "居民code")
    private String patient;//居民code',
    @ApiModelProperty(value = "家庭成员code")
    private String familyMember;//家庭成员code',
    @ApiModelProperty(value = "家庭关系 1父亲 2母亲 3老公 4老婆 5儿子 6女儿 7其他")
    private String familyRelation;//家庭关系',
    @ApiModelProperty(value = "是否授权0")
    private Integer isAuthorize;//是否授权0:未授权,1:已授权,默认为1',
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getPatient() {
        return patient;
    }
    public void setPatient(String patient) {
        this.patient = patient;
    }
    public String getFamilyMember() {
        return familyMember;
    }
    public void setFamilyMember(String familyMember) {
        this.familyMember = familyMember;
    }
    public String getFamilyRelation() {
        return familyRelation;
    }
    public void setFamilyRelation(String familyRelation) {
        this.familyRelation = familyRelation;
    }
    public Integer getIsAuthorize() {
        return isAuthorize;
    }
    public void setIsAuthorize(Integer isAuthorize) {
        this.isAuthorize = isAuthorize;
    }
}

+ 17 - 15
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/servicePackage/ServicePackagePropvalueDO.java

@ -1,34 +1,41 @@
package com.yihu.jw.restmodel.base.servicePackage;
import com.yihu.jw.entity.UuidIdentityEntity;
import com.yihu.jw.restmodel.UuidIdentityVO;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;
/**
 * 服务包属性值表
 * @author yeshijie on 2018/8/29.
 */
@Entity
@Table(name = "base_service_package_propvalue")
public class ServicePackagePropvalueDO extends UuidIdentityEntity implements Serializable {
@ApiModel(value = "ServicePackagePropvalueDO", description = "服务包属性值表")
public class ServicePackagePropvalueVO extends UuidIdentityVO {
    @ApiModelProperty(value = "saasId")
    private String saasId;
    @ApiModelProperty(value = "类目ID")
    private Long cid;//类目ID',
    @ApiModelProperty(value = "属性 ID")
    private Long pid;//属性 ID',
    @ApiModelProperty(value = "属性名")
    private String propName;//属性名',
    @ApiModelProperty(value = "属性值ID")
    private Long vid;//属性值ID',
    @ApiModelProperty(value = "属性值")
    private String name;//属性值',
    @ApiModelProperty(value = "属性值别名")
    private String nameAlias;//属性值别名',
    @ApiModelProperty(value = "是否为父类目属性")
    private Integer isParent;//是否为父类目属性',
    @ApiModelProperty(value = "排列序号")
    private Long sortOrder;//排列序号。取值范围:大于零的整数',
    @ApiModelProperty(value = "创建时间")
    private Date createTime;
    private Integer del;//状态。可选值:1(正常),0(删除)',
    @ApiModelProperty(value = "状态。可选值:1(正常),0(删除)")
    private Integer del;//',
    @Column(name = "saas_id")
    public String getSaasId() {
        return saasId;
    }
@ -53,7 +60,6 @@ public class ServicePackagePropvalueDO extends UuidIdentityEntity implements Ser
        this.pid = pid;
    }
    @Column(name = "prop_name")
    public String getPropName() {
        return propName;
    }
@ -78,7 +84,6 @@ public class ServicePackagePropvalueDO extends UuidIdentityEntity implements Ser
        this.name = name;
    }
    @Column(name = "name_alias")
    public String getNameAlias() {
        return nameAlias;
    }
@ -87,7 +92,6 @@ public class ServicePackagePropvalueDO extends UuidIdentityEntity implements Ser
        this.nameAlias = nameAlias;
    }
    @Column(name = "is_parent")
    public Integer getIsParent() {
        return isParent;
    }
@ -96,7 +100,6 @@ public class ServicePackagePropvalueDO extends UuidIdentityEntity implements Ser
        this.isParent = isParent;
    }
    @Column(name = "sort_order")
    public Long getSortOrder() {
        return sortOrder;
    }
@ -105,7 +108,6 @@ public class ServicePackagePropvalueDO extends UuidIdentityEntity implements Ser
        this.sortOrder = sortOrder;
    }
    @Column(name = "create_time")
    public Date getCreateTime() {
        return createTime;
    }

+ 3 - 1
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/sms/SmsVO.java

@ -1,5 +1,6 @@
package com.yihu.jw.restmodel.base.sms;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.yihu.jw.entity.base.sms.SmsTemplateDO;
import com.yihu.jw.restmodel.UuidIdentityVO;
import io.swagger.annotations.ApiModel;
@ -31,7 +32,7 @@ public class SmsVO extends UuidIdentityVO {
    @ApiModelProperty(value = "短信内容", example = "【i健康综合管理平台】您使用的是i健康综合管理平台短信模板,您的验证码是826612,请于10分钟内正确输入!")
    private String content;
    //过期时间
    @ApiModelProperty(value = "应用ID", example = "EwC0iRSrcS")
    @ApiModelProperty(value = "过期时间", example = "2018-09-03 15:34:34")
    private Date deadline;
    //验证码
    private String captcha;
@ -78,6 +79,7 @@ public class SmsVO extends UuidIdentityVO {
        this.content = content;
    }
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+08:00")
    public Date getDeadline() {
        return deadline;
    }

+ 62 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/team/TeamMemberVO.java

@ -0,0 +1,62 @@
package com.yihu.jw.restmodel.base.team;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
 * Created by Trick on 2018/8/31.
 */
@ApiModel(value = "TeamMemberVO", description = "团队成员")
public class TeamMemberVO {
    @ApiModelProperty(value = "id")
    private String id;
    @ApiModelProperty(value = "团队ID")
    private String teamId;//团队ID',
    @ApiModelProperty(value = "机构标识")
    private String orgId;//机构标识',
    @ApiModelProperty(value = "医生标识,多个医生以逗号分开")
    private String doctorId;//医生标识,多个医生以逗号分开',
    @ApiModelProperty(value = "作废标识,1正常,0作废'")
    private String del;//作废标识,1正常,0作废',
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getTeamId() {
        return teamId;
    }
    public void setTeamId(String teamId) {
        this.teamId = teamId;
    }
    public String getOrgId() {
        return orgId;
    }
    public void setOrgId(String orgId) {
        this.orgId = orgId;
    }
    public String getDoctorId() {
        return doctorId;
    }
    public void setDoctorId(String doctorId) {
        this.doctorId = doctorId;
    }
    public String getDel() {
        return del;
    }
    public void setDel(String del) {
        this.del = del;
    }
}

+ 80 - 0
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/base/team/TeamVO.java

@ -0,0 +1,80 @@
package com.yihu.jw.restmodel.base.team;
import io.swagger.annotations.ApiModelProperty;
/**
 * Created by Trick on 2018/8/31.
 */
public class TeamVO {
    @ApiModelProperty(value = "id")
    private String id;
    @ApiModelProperty(value = "saas化")
    private String saasid;//saas化',
    @ApiModelProperty(value = "团队名称")
    private String name;//团队名称',
    @ApiModelProperty(value = "领导医生标识")
    private String leaderId;//领导医生标识',
    @ApiModelProperty(value = "团队人数")
    private String teamNum;//团队人数',
    @ApiModelProperty(value = "团队二维码")
    private String qrcode;//团队二维码',
    @ApiModelProperty(value = "作废标识,1正常,0作废',")
    private String del;//作废标识,1正常,0作废',
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getSaasid() {
        return saasid;
    }
    public void setSaasid(String saasid) {
        this.saasid = saasid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getLeaderId() {
        return leaderId;
    }
    public void setLeaderId(String leaderId) {
        this.leaderId = leaderId;
    }
    public String getTeamNum() {
        return teamNum;
    }
    public void setTeamNum(String teamNum) {
        this.teamNum = teamNum;
    }
    public String getQrcode() {
        return qrcode;
    }
    public void setQrcode(String qrcode) {
        this.qrcode = qrcode;
    }
    public String getDel() {
        return del;
    }
    public void setDel(String del) {
        this.del = del;
    }
}

+ 21 - 1
common/common-rest-model/src/main/java/com/yihu/jw/restmodel/specialist/PatientDisseaseInfoVO.java

@ -21,6 +21,8 @@ public class PatientDisseaseInfoVO {
    private String patient;
    @ApiModelProperty("居民姓名")
    private String patientName;
    @ApiModelProperty("专科医生签约团队")
    private String teamCode;
    @ApiModelProperty("年龄")
    private String age;
    @ApiModelProperty("性别")
@ -28,7 +30,9 @@ public class PatientDisseaseInfoVO {
    @ApiModelProperty("身份证")
    private String idcard;
    @ApiModelProperty("生日")
    private String  birthday;
    private String birthday;
    @ApiModelProperty("头像")
    private String photo;
    public String getDisease() {
        return disease;
@ -93,4 +97,20 @@ public class PatientDisseaseInfoVO {
    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }
    public String getTeamCode() {
        return teamCode;
    }
    public void setTeamCode(String teamCode) {
        this.teamCode = teamCode;
    }
    public String getPhoto() {
        return photo;
    }
    public void setPhoto(String photo) {
        this.photo = photo;
    }
}

+ 182 - 0
common/common-util/src/main/java/com/yihu/jw/util/idcard/IdCardUtil.java

@ -0,0 +1,182 @@
package com.yihu.jw.util.idcard;
import org.apache.commons.lang3.StringUtils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
 * Created by Trick on 2018/9/3.
 */
public class IdCardUtil {
    public static String level_sex_1="1";
    public static String level_sex_2="2";
    public static String level_sex_3="3";
//    public static String level_sex_1_name="男";
//    public static String level_sex_2_name="女";
//    public static String level_sex_3_name="未知";
    /**
     * 根据身份证的号码算出当前身份证持有者的年龄
     *
     * @param
     * @throws Exception
     */
    public static int getAgeForIdcard(String idcard) {
        try {
            int age = 0;
            if (StringUtils.isEmpty(idcard)) {
                return age;
            }
            String birth = "";
            if (idcard.length() == 18) {
                birth = idcard.substring(6, 14);
            } else if (idcard.length() == 15) {
                birth = "19" + idcard.substring(6, 12);
            }
            int year = Integer.valueOf(birth.substring(0, 4));
            int month = Integer.valueOf(birth.substring(4, 6));
            int day = Integer.valueOf(birth.substring(6));
            Calendar cal = Calendar.getInstance();
            age = cal.get(Calendar.YEAR) - year;
            //周岁计算
            if (cal.get(Calendar.MONTH) < (month - 1) || (cal.get(Calendar.MONTH) == (month - 1) && cal.get(Calendar.DATE) < day)) {
                age--;
            }
            return age;
        } catch (Exception e) {
        }
        return -1;
    }
    /**
     * 身份证提取出身日期
     *
     * @param card
     * @return
     * @throws Exception
     */
    public static Date getBirthdayForIdcard(String card)
            throws Exception {
        Date b = null;
        if (card.length() == 18) {
            String year = card.substring(6).substring(0, 4);// 得到年份
            String yue = card.substring(10).substring(0, 2);// 得到月份
            String ri = card.substring(12).substring(0, 2);// 得到日
            // String day=CardCode.substring(12).substring(0,2);//得到日
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            b = format.parse(year + "-" + yue + "-" + ri);
        } else if (card.length() == 15) {
            String uyear = "19" + card.substring(6, 8);// 年份
            String uyue = card.substring(8, 10);// 月份
            String uri = card.substring(10, 12);// 得到日
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            b = format.parse(uyear + "-" + uyue + "-" + uri);
        }
        return b;
    }
    /**
     * 身份证提取出身日期
     *
     * @param card
     * @return
     * @throws Exception
     */
    public static String getBirthdayForIdcardStr(String card)
            throws Exception {
        if (card.length() == 18) {
            String year = card.substring(6).substring(0, 4);// 得到年份
            String yue = card.substring(10).substring(0, 2);// 得到月份
            String ri = card.substring(12).substring(0, 2);// 得到日
            // String day=CardCode.substring(12).substring(0,2);//得到日
            return year + yue + ri;
        } else if (card.length() == 15) {
            String uyear = "19" + card.substring(6, 8);// 年份
            String uyue = card.substring(8, 10);// 月份
            String uri = card.substring(10, 12);// 得到日
            return uyear + uyue + uri;
        }
        return null;
    }
    /**
     * 根据身份证的号码算出当前身份证持有者的性别
     * 1 女 2 男 3未知
     *
     * @return
     * @throws Exception
     */
    public static String getSexForIdcard(String CardCode)
            throws Exception {
        String sex = level_sex_3;
        if (CardCode.length() == 18) {
            if (Integer.parseInt(CardCode.substring(16).substring(0, 1)) % 2 == 0) {// 判断性别
                // modifid by lyr 2016-09-29
                // sex =  Constant.level_sex_2;
                sex =level_sex_1;
                // modifid by lyr 2016-09-29
            } else {
                // modifid by lyr 2016-09-29
                // sex =  Constant.level_sex_1;
                sex = level_sex_2;
                // modifid by lyr 2016-09-29
            }
        } else if (CardCode.length() == 15) {
            String usex = CardCode.substring(14, 15);// 用户的性别
            if (Integer.parseInt(usex) % 2 == 0) {
                // sex =  Constant.level_sex_2;
                sex = level_sex_1;
            } else {
                // sex =  Constant.level_sex_1;
                sex = level_sex_2;
            }
        }
        return sex;
    }
    /**
     * 根据身份证的号码算出当前身份证持有者的性别
     * 1 男 2 女 3未知
     *
     * @return
     * @throws Exception
     */
    public static String getSexForIdcard_new(String CardCode)
            throws Exception {
        String sex = level_sex_3;
        try {
            if (CardCode.length() == 18) {
                if (Integer.parseInt(CardCode.substring(16).substring(0, 1)) % 2 == 0) {// 判断性别
                    // modifid by lyr 2016-09-29
                    sex = level_sex_2;
                    // modifid by lyr 2016-09-29
                } else {
                    // modifid by lyr 2016-09-29
                    sex = level_sex_1;
                    // modifid by lyr 2016-09-29
                }
            } else if (CardCode.length() == 15) {
                String usex = CardCode.substring(14, 15);// 用户的性别
                if (Integer.parseInt(usex) % 2 == 0) {
                    sex = level_sex_2;
                } else {
                    sex = level_sex_1;
                }
            }
            return sex;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sex;
    }
}

+ 1 - 1
gateway/ag-basic/src/main/resources/application.yml

@ -11,7 +11,7 @@ zuul:
      serviceId: svr-iot
    svr-base:
      path: /base/**
      serviceId: svr-base-sxy
      serviceId: svr-base
    demo:
      path: /baidu/**
      url: https://www.baidu.com

+ 10 - 0
server/svr-authentication/src/main/java/com/yihu/AuthServer.java

@ -4,6 +4,9 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
 * Created by progr1mmer on 2018/8/29.
@ -19,4 +22,11 @@ public class AuthServer extends SpringBootServletInitializer {
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(AuthServer.class);
    }
    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

+ 2 - 0
server/svr-authentication/src/main/java/com/yihu/jw/security/config/WlyyWebSecurityConfigurerAdapter.java

@ -31,6 +31,7 @@ public class WlyyWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapt
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/oauth/**");
        web.ignoring().antMatchers("/health");
    }
    @Override
@ -63,6 +64,7 @@ public class WlyyWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapt
        reflectionSaltSource.setUserPropertyToUse("salt");
        authenticationProvider.setSaltSource(reflectionSaltSource);
        authenticationProvider.setSaltSource(reflectionSaltSource);
        authenticationProvider.setHideUserNotFoundExceptions(false);
        return authenticationProvider;
    }

+ 4 - 0
server/svr-authentication/src/main/java/com/yihu/jw/security/core/userdetails/SaltUser.java

@ -31,6 +31,10 @@ public class SaltUser implements UserDetails, CredentialsContainer {
        this(username, password, salt, true, true, true, true, authorities);
    }
    public SaltUser(String username, String password, String salt, boolean enabled, boolean locked, Collection<? extends GrantedAuthority> authorities) {
        this(username, password, salt, enabled, true, true, !locked, authorities);
    }
    public SaltUser(String username, String password, String salt, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
        if(username != null && !"".equals(username) && password != null) {
            this.username = username;

+ 36 - 10
server/svr-authentication/src/main/java/com/yihu/jw/security/core/userdetails/jdbc/WlyyUserDetailsService.java

@ -3,6 +3,7 @@ package com.yihu.jw.security.core.userdetails.jdbc;
import com.yihu.jw.security.core.userdetails.SaltUser;
import com.yihu.jw.security.model.WlyyUserDetails;
import com.yihu.jw.security.model.WlyyUserSimple;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.security.core.GrantedAuthority;
@ -10,7 +11,10 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Collection;
@ -18,12 +22,12 @@ import java.util.Date;
import java.util.List;
/**
 * Service - 用户加载
 * Service - 用户信息
 * Created by progr1mmer on 2018/8/29.
 */
public class WlyyUserDetailsService extends JdbcDaoSupport implements UserDetailsService {
    private static final String DEFAULT_USER_DETAILS_STATEMENT = "SELECT * FROM base_user u WHERE u.username = ? OR u.mobile = ? OR u.idcard = ?";
    private static final String DEFAULT_USER_DETAILS_STATEMENT = "select * from base_user u where u.username = ? or u.mobile = ? or u.idcard = ?";
    public WlyyUserDetailsService(DataSource dataSource) {
        this.setDataSource(dataSource);
@ -42,18 +46,19 @@ public class WlyyUserDetailsService extends JdbcDaoSupport implements UserDetail
        if (users == null || users.size() == 0) {
            throw new UsernameNotFoundException(username);
        }
        return new SaltUser(username, users.get(0).getPassword(), users.get(0).getSalt(), getGrantedAuthorities(username));
    }
    private Collection<? extends GrantedAuthority> getGrantedAuthorities(String username) {
        Collection<GrantedAuthority> authorities = new ArrayList<>(1);
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        return authorities;
        if (users.get(0).isLocked()) {
            Date date = users.get(0).getLockedDate();
            if (new Date().after(DateUtils.addMinutes(date, 5))) {
                this.getJdbcTemplate().update("update base_user u set login_failure_count = 0, u.locked = 0 where u.username = ? or u.mobile = ? or u.idcard = ?", username, username, username);
                users.get(0).setLocked(false);
            }
        }
        return new SaltUser(username, users.get(0).getPassword(), users.get(0).getSalt(), users.get(0).isEnabled(), users.get(0).isLocked(), getGrantedAuthorities(username));
    }
    public WlyyUserSimple authSuccess (String username) throws UsernameNotFoundException {
        //更新登陆时间
        this.getJdbcTemplate().update("update base_user u set u.login_date = ? where u.username = ? or u.mobile = ? or u.idcard = ?", new Date(), username, username, username);
        this.getJdbcTemplate().update("update base_user u set login_failure_count = 0, u.login_date = ? where u.username = ? or u.mobile = ? or u.idcard = ?", new Date(), username, username, username);
        //加载用户简略信息
        List<WlyyUserSimple> users = this.getJdbcTemplate().query(DEFAULT_USER_DETAILS_STATEMENT, new BeanPropertyRowMapper(WlyyUserSimple.class), username, username, username);
        if (users == null || users.size() == 0) {
@ -62,4 +67,25 @@ public class WlyyUserDetailsService extends JdbcDaoSupport implements UserDetail
        return users.get(0);
    }
    public String authFailure () throws UsernameNotFoundException {
        //获取失败次数
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String username = request.getParameter("username");
        Integer loginFailureCount = this.getJdbcTemplate().queryForObject("select login_failure_count from base_user u where u.username = ? or u.mobile = ? or u.idcard = ?", Integer.class, username, username, username);
        loginFailureCount ++;
        if (loginFailureCount == 5) {
            this.getJdbcTemplate().update("update base_user u set u.login_failure_count = 5, locked = 1, u.locked_date = ? where u.username = ? or u.mobile = ? or u.idcard = ?", new Date(), username, username, username);
            return "账号已被锁定,请5分钟后重试!";
        } else {
            this.getJdbcTemplate().update("update base_user u set u.login_failure_count = ? where u.username = ? or u.mobile = ? or u.idcard = ?", loginFailureCount, username, username, username);
            return "密码错误,还可以再试" + (5 - loginFailureCount) + "次!";
        }
    }
    private Collection<? extends GrantedAuthority> getGrantedAuthorities(String username) {
        Collection<GrantedAuthority> authorities = new ArrayList<>(1);
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        return authorities;
    }
}

+ 42 - 0
server/svr-authentication/src/main/java/com/yihu/jw/security/model/Captcha.java

@ -0,0 +1,42 @@
package com.yihu.jw.security.model;
import java.io.Serializable;
import java.util.Date;
/**
 * Model - 验证码
 * Created by progr1mmer on 2018/9/3.
 */
public class Captcha implements Serializable {
    //验证码
    private String code;
    //过期时间(秒)
    private int expiresIn;
    //请求间隔(秒)
    private int interval;
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public int getExpiresIn() {
        return expiresIn;
    }
    public void setExpiresIn(int expiresIn) {
        this.expiresIn = expiresIn;
    }
    public int getInterval() {
        return interval;
    }
    public void setInterval(int interval) {
        this.interval = interval;
    }
}

+ 2 - 1
server/svr-authentication/src/main/java/com/yihu/jw/security/model/Oauth2Envelop.java

@ -2,13 +2,14 @@ package com.yihu.jw.security.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.io.Serializable;
import java.util.HashMap;
/**
 * Model - 认证失败信息
 * Created by progr1mmer on 2018/8/29.
 */
public class Oauth2Envelop<T> {
public class Oauth2Envelop<T> implements Serializable {
    protected String message;
    protected Integer status;

+ 31 - 0
server/svr-authentication/src/main/java/com/yihu/jw/security/model/PublicKey.java

@ -0,0 +1,31 @@
package com.yihu.jw.security.model;
import java.io.Serializable;
/**
 * Model 公钥
 * Created by progr1mmer on 2018/9/3.
 */
public class PublicKey implements Serializable {
    //模
    private String modulus;
    //指数
    private String exponent;
    public String getModulus() {
        return modulus;
    }
    public void setModulus(String modulus) {
        this.modulus = modulus;
    }
    public String getExponent() {
        return exponent;
    }
    public void setExponent(String exponent) {
        this.exponent = exponent;
    }
}

+ 2 - 1
server/svr-authentication/src/main/java/com/yihu/jw/security/model/WlyyUserSimple.java

@ -10,7 +10,8 @@ import java.util.Date;
 * Model - 认证用户简略信息
 * Created by progr1mmer on 2018/8/29.
 */
public class WlyyUserSimple implements Serializable {
public class
WlyyUserSimple implements Serializable {
    /**
     * 性别

+ 5 - 2
server/svr-authentication/src/main/java/com/yihu/jw/security/oauth2/config/WlyyAuthorizationServerConfigurerAdapter.java

@ -11,6 +11,7 @@ import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
@ -62,14 +63,16 @@ public class WlyyAuthorizationServerConfigurerAdapter extends AuthorizationServe
    @Primary
    WlyyTokenGranter wlyyTokenGranter (
            AuthenticationManager authenticationManager,
            AuthorizationServerTokenServices authorizationServerTokenServices) {
            AuthorizationServerTokenServices authorizationServerTokenServices,
            UserDetailsService userDetailsService) {
        WlyyTokenGranter tokenGranter = new WlyyTokenGranter(
                authenticationManager,
                authorizationServerTokenServices,
                authorizationCodeServices(),
                clientDetailsService(),
                new DefaultOAuth2RequestFactory(clientDetailsService()),
                wlyyRedisVerifyCodeService());
                wlyyRedisVerifyCodeService(),
                userDetailsService);
        return tokenGranter;
    }

+ 19 - 5
server/svr-authentication/src/main/java/com/yihu/jw/security/oauth2/core/redis/WlyyRedisVerifyCodeService.java

@ -6,6 +6,7 @@ import org.springframework.util.StringUtils;
import java.util.concurrent.TimeUnit;
/**
 * Service - 验证码缓存
 * Created by progr1mmer on 2018/4/18.
 */
public class WlyyRedisVerifyCodeService {
@ -17,21 +18,34 @@ public class WlyyRedisVerifyCodeService {
        this.redisTemplate = redisTemplate;
    }
    public void store (String client_id, String username, String code, long expire) {
    public void store (String client_id, String username, String code, int expire) {
        String key = client_id + ":" + username + KEY_SUFFIX;
        redisTemplate.opsForValue().set(key, code);
        redisTemplate.expire(key, expire, TimeUnit.MILLISECONDS);
        redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        String intervalKey = key + ":" + code + "_interval";
        redisTemplate.opsForValue().set(intervalKey, 60);
        redisTemplate.expire(intervalKey, 60, TimeUnit.SECONDS);
    }
    public Integer getExpireTime (String client_id, String username) {
        return new Long(redisTemplate.getExpire(client_id + ":" + username + KEY_SUFFIX)).intValue();
    public boolean isIntervalTimeout(String client_id, String username) {
        String key = client_id + ":" + username + KEY_SUFFIX;
        String code = (String) redisTemplate.opsForValue().get(key);
        if (null == code) {
            return true;
        }
        String intervalKey = key + ":" + code + "_interval";
        if (redisTemplate.opsForValue().get(intervalKey) != null) {
            return false;
        }
        return true;
    }
    public boolean verification (String client_id, String username, String code) {
        if (StringUtils.isEmpty(code)) {
            return false;
        }
        String _code = (String) redisTemplate.opsForValue().get(client_id + ":" + username + KEY_SUFFIX);
        String key = client_id + ":" + username + KEY_SUFFIX;
        String _code = (String) redisTemplate.opsForValue().get(key);
        if (null == _code) {
            return false;
        }

+ 61 - 62
server/svr-authentication/src/main/java/com/yihu/jw/security/oauth2/provider/WlyyTokenGranter.java

@ -1,11 +1,11 @@
package com.yihu.jw.security.oauth2.provider;
import com.yihu.jw.security.core.userdetails.SaltUser;
import com.yihu.jw.security.oauth2.core.redis.WlyyRedisVerifyCodeService;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
@ -35,45 +35,47 @@ public class WlyyTokenGranter implements TokenGranter {
                            AuthorizationCodeServices authorizationCodeServices,
                            ClientDetailsService clientDetailsService,
                            OAuth2RequestFactory requestFactory,
                            WlyyRedisVerifyCodeService wlyyRedisVerifyCodeService) {
                            WlyyRedisVerifyCodeService wlyyRedisVerifyCodeService,
                            UserDetailsService userDetailsService) {
        tokenGranters.put(EhrAuthorizationCodeGranter.GRANT_TYPE,
                new EhrAuthorizationCodeGranter(
        tokenGranters.put(WlyyAuthorizationCodeGranter.GRANT_TYPE,
                new WlyyAuthorizationCodeGranter(
                        tokenServices,
                        authorizationCodeServices,
                        clientDetailsService,
                        requestFactory
                ));
        tokenGranters.put(EhrResourceOwnerPasswordTokenGranter.GRANT_TYPE,
                new EhrResourceOwnerPasswordTokenGranter(
        tokenGranters.put(WlyyResourceOwnerPasswordTokenGranter.GRANT_TYPE,
                new WlyyResourceOwnerPasswordTokenGranter(
                        authenticationManager,
                        tokenServices,
                        clientDetailsService,
                        requestFactory
                ));
        tokenGranters.put(EhrRefreshTokenGranter.GRANT_TYPE,
                new EhrRefreshTokenGranter(
        tokenGranters.put(WlyyRefreshTokenGranter.GRANT_TYPE,
                new WlyyRefreshTokenGranter(
                        tokenServices,
                        clientDetailsService,
                        requestFactory
                ));
        tokenGranters.put(EhrImplicitTokenGranter.GRANT_TYPE,
                new EhrImplicitTokenGranter(
        tokenGranters.put(WlyyImplicitTokenGranter.GRANT_TYPE,
                new WlyyImplicitTokenGranter(
                        tokenServices,
                        clientDetailsService,
                        requestFactory
                ));
        tokenGranters.put(EhrVerifyCodeTokenGranter.GRANT_TYPE,
                new EhrVerifyCodeTokenGranter(
        tokenGranters.put(WlyyCaptchaTokenGranter.GRANT_TYPE,
                new WlyyCaptchaTokenGranter(
                        authenticationManager,
                        tokenServices,
                        clientDetailsService,
                        requestFactory,
                        wlyyRedisVerifyCodeService
                        wlyyRedisVerifyCodeService,
                        userDetailsService
                ));
    }
@ -88,19 +90,19 @@ public class WlyyTokenGranter implements TokenGranter {
    /**
     * authorization_code模式Token授权器。
     */
    public static class EhrAuthorizationCodeGranter extends AbstractTokenGranter {
    public static class WlyyAuthorizationCodeGranter extends AbstractTokenGranter {
        public static final String GRANT_TYPE = "authorization_code";
        private final AuthorizationCodeServices authorizationCodeServices;
        public EhrAuthorizationCodeGranter(AuthorizationServerTokenServices tokenServices,
        public WlyyAuthorizationCodeGranter(AuthorizationServerTokenServices tokenServices,
                                           AuthorizationCodeServices authorizationCodeServices,
                                           ClientDetailsService clientDetailsService,
                                           OAuth2RequestFactory requestFactory) {
            this(tokenServices, authorizationCodeServices, clientDetailsService, requestFactory, GRANT_TYPE);
        }
        protected EhrAuthorizationCodeGranter(AuthorizationServerTokenServices tokenServices,
        protected WlyyAuthorizationCodeGranter(AuthorizationServerTokenServices tokenServices,
                                              AuthorizationCodeServices authorizationCodeServices,
                                              ClientDetailsService clientDetailsService,
                                              OAuth2RequestFactory requestFactory,
@ -162,17 +164,6 @@ public class WlyyTokenGranter implements TokenGranter {
            Authentication userAuth = storedAuth.getUserAuthentication();
            //再次通过pk获取当前请求的用户信息
            /*String pk = combinedParameters.get("pk");
            String keyId = ehrJDBCUserSecurityService.getDefaultKeyIdSelectStatement(pk);
            String userId = ehrJDBCUserSecurityService.getDefaultUserIdByKeyIdSelectStatement(keyId);
            String userName = ehrJDBCUserSecurityService.getDefaultUserNameByUserId(userId);
            UserDetails userDetails = ehrUserDetailsService.loadUserByUsername(userName);
            if (StringUtils.isEmpty(keyId) || StringUtils.isEmpty(userId) || StringUtils.isEmpty(userName)) {
                throw new InsufficientAuthenticationException("Illegal pk");
            }
            UsernamePasswordAuthenticationToken userToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(), userDetails.getAuthorities());*/
            return new OAuth2Authentication(finalStoredOAuth2Request, userAuth);
        }
    }
@ -180,17 +171,17 @@ public class WlyyTokenGranter implements TokenGranter {
    /**
     * password模式Token授权器。
     */
    public static class EhrResourceOwnerPasswordTokenGranter extends AbstractTokenGranter {
    public static class WlyyResourceOwnerPasswordTokenGranter extends AbstractTokenGranter {
        private static final String GRANT_TYPE = "password";
        private final AuthenticationManager authenticationManager;
        public EhrResourceOwnerPasswordTokenGranter(AuthenticationManager authenticationManager,
        public WlyyResourceOwnerPasswordTokenGranter(AuthenticationManager authenticationManager,
                                                 AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
            this(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        }
        protected EhrResourceOwnerPasswordTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices,
        protected WlyyResourceOwnerPasswordTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices,
                                                    ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
            super(tokenServices, clientDetailsService, requestFactory, grantType);
            this.authenticationManager = authenticationManager;
@ -230,10 +221,10 @@ public class WlyyTokenGranter implements TokenGranter {
    /**
     * refresh模式Token授权器。
     */
    public static class EhrRefreshTokenGranter extends AbstractTokenGranter {
    public static class WlyyRefreshTokenGranter extends AbstractTokenGranter {
        static final String GRANT_TYPE = "refresh_token";
        public EhrRefreshTokenGranter(AuthorizationServerTokenServices tokenServices,
        public WlyyRefreshTokenGranter(AuthorizationServerTokenServices tokenServices,
                                      ClientDetailsService clientDetailsService,
                                      OAuth2RequestFactory requestFactory) {
            super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
@ -248,16 +239,16 @@ public class WlyyTokenGranter implements TokenGranter {
    }
    /**
     * Implicit模式Token授权器。
     * implicit模式Token授权器。
     */
    public static class EhrImplicitTokenGranter extends AbstractTokenGranter {
    public static class WlyyImplicitTokenGranter extends AbstractTokenGranter {
        private static final String GRANT_TYPE = "implicit";
        public EhrImplicitTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
        public WlyyImplicitTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
            this(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        }
        protected EhrImplicitTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService,
        protected WlyyImplicitTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService,
                                       OAuth2RequestFactory requestFactory, String grantType) {
            super(tokenServices, clientDetailsService, requestFactory, grantType);
        }
@ -283,32 +274,37 @@ public class WlyyTokenGranter implements TokenGranter {
    }
    /**
     * verify_code模式Token授权器。
     * captcha模式Token授权器。
     */
    public static class EhrVerifyCodeTokenGranter extends AbstractTokenGranter {
        private static final String GRANT_TYPE = "verify_code";
    public static class WlyyCaptchaTokenGranter extends AbstractTokenGranter {
        private static final String GRANT_TYPE = "captcha";
        private final AuthenticationManager authenticationManager;
        // Ehr Properties
        // Customize Properties
        private final WlyyRedisVerifyCodeService wlyyRedisVerifyCodeService;
        private final UserDetailsService userDetailsService;
        public EhrVerifyCodeTokenGranter(AuthenticationManager authenticationManager,
                                         AuthorizationServerTokenServices tokenServices,
                                         ClientDetailsService clientDetailsService,
                                         OAuth2RequestFactory requestFactory,
                                         WlyyRedisVerifyCodeService wlyyRedisVerifyCodeService) {
            this(authenticationManager, tokenServices, clientDetailsService, requestFactory, GRANT_TYPE, wlyyRedisVerifyCodeService);
        public WlyyCaptchaTokenGranter(AuthenticationManager authenticationManager,
                                       AuthorizationServerTokenServices tokenServices,
                                       ClientDetailsService clientDetailsService,
                                       OAuth2RequestFactory requestFactory,
                                       WlyyRedisVerifyCodeService wlyyRedisVerifyCodeService,
                                       UserDetailsService userDetailsService) {
            this(authenticationManager, tokenServices, clientDetailsService, requestFactory, wlyyRedisVerifyCodeService, userDetailsService, GRANT_TYPE);
        }
        protected EhrVerifyCodeTokenGranter(AuthenticationManager authenticationManager,
                                            AuthorizationServerTokenServices tokenServices,
                                            ClientDetailsService clientDetailsService,
                                            OAuth2RequestFactory requestFactory,
                                            String grantType,
                                            WlyyRedisVerifyCodeService wlyyRedisVerifyCodeService) {
        protected WlyyCaptchaTokenGranter(AuthenticationManager authenticationManager,
                                          AuthorizationServerTokenServices tokenServices,
                                          ClientDetailsService clientDetailsService,
                                          OAuth2RequestFactory requestFactory,
                                          WlyyRedisVerifyCodeService wlyyRedisVerifyCodeService,
                                          UserDetailsService userDetailsService,
                                          String grantType) {
            super(tokenServices, clientDetailsService, requestFactory, grantType);
            this.authenticationManager = authenticationManager;
            this.wlyyRedisVerifyCodeService = wlyyRedisVerifyCodeService;
            this.userDetailsService = userDetailsService;
        }
        @Override
@ -317,22 +313,25 @@ public class WlyyTokenGranter implements TokenGranter {
            Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
            String client_id = parameters.get("client_id");
            String username = parameters.get("username");
            String verify_code = parameters.get("verify_code");
            String captcha = parameters.get("captcha");
            if (!wlyyRedisVerifyCodeService.verification(client_id, username, verify_code)){
                throw new InvalidGrantException("Invalid verify_code");
            if (!wlyyRedisVerifyCodeService.verification(client_id, username, captcha)){
                throw new InvalidGrantException("Invalid captcha");
            }
            Authentication userAuth = new UsernamePasswordAuthenticationToken(username, verify_code, getGrantedAuthorities(username));
            SaltUser userDetails = (SaltUser)userDetailsService.loadUserByUsername(username);
            if (!userDetails.isEnabled()) {
                throw new InvalidGrantException("User is disabled");
            }
            if (!userDetails.isAccountNonLocked()) {
                throw new InvalidGrantException("User account is locked");
            }
            Authentication userAuth = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), captcha, userDetails.getAuthorities());
            ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
            OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
            return new OAuth2Authentication(storedOAuth2Request, userAuth);
        }
        private Collection<? extends GrantedAuthority> getGrantedAuthorities(String username) {
            Collection<GrantedAuthority> authorities = new ArrayList<>(1);
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
            return authorities;
        }
    }
}

+ 174 - 109
server/svr-authentication/src/main/java/com/yihu/jw/security/oauth2/provider/endpoint/WlyyLoginEndpoint.java

@ -1,18 +1,19 @@
package com.yihu.jw.security.oauth2.provider.endpoint;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.security.model.Captcha;
import com.yihu.jw.security.model.PublicKey;
import com.yihu.jw.security.oauth2.core.redis.WlyyRedisVerifyCodeService;
import com.yihu.jw.security.oauth2.provider.error.WlyyOAuth2ExceptionTranslator;
import com.yihu.jw.security.oauth2.provider.WlyyTokenGranter;
import com.yihu.jw.security.core.userdetails.jdbc.WlyyUserDetailsService;
import com.yihu.jw.security.model.Oauth2Envelop;
import com.yihu.jw.security.model.WlyyUserSimple;
import com.yihu.utils.security.RSAUtils;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.*;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
@ -24,15 +25,27 @@ import org.springframework.security.oauth2.provider.request.DefaultOAuth2Request
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestValidator;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.PostConstruct;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
 * <p>
@ -64,26 +77,40 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
    @Autowired
    private WlyyUserDetailsService userDetailsService;
    @Autowired
    private WlyyRedisVerifyCodeService wlyyRedisVerifyCodeService;
    private RestTemplate restTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    private WlyyRedisVerifyCodeService wlyyRedisVerifyCodeService;
    @PostConstruct
    private void init() {
        super.setTokenGranter(tokenGranter);
    }
    /**
     * 登陆
     * @param parameters
     * @param httpSession
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/oauth/login", method = RequestMethod.POST)
    public ResponseEntity<Oauth2Envelop<WlyyUserSimple>> login(@RequestParam Map<String, String> parameters) {
    public ResponseEntity<Oauth2Envelop<WlyyUserSimple>> login(@RequestParam Map<String, String> parameters, HttpSession httpSession) throws Exception {
        String username = parameters.get("username");
        if (StringUtils.isEmpty(username)) {
            throw new InvalidRequestException("username");
        }
        String client_id = parameters.get("client_id");
        if (StringUtils.isEmpty(client_id)) {
            throw new InvalidRequestException("client_id");
        }
        if (StringUtils.isEmpty(parameters.get("verify_code"))) {
        if (StringUtils.isEmpty(parameters.get("captcha"))) {
            parameters.put("grant_type", "password");
            if (parameters.get("password") != null) {
                RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)httpSession.getAttribute("privateKey");
                parameters.put("password", RSAUtils.decryptByPrivateKey(new String(Base64.decodeBase64(parameters.get("password"))), rsaPrivateKey));
            }
        } else {
            parameters.put("grant_type", "verify_code");
            parameters.put("grant_type", "captcha");
        }
        ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(client_id);
@ -118,6 +145,11 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        return getResponse(wlyyUserSimple);
    }
    /**
     * 单点登陆第二步 - token验证
     * @param parameters
     * @return
     */
    @RequestMapping(value = "/oauth/sso", method = RequestMethod.POST)
    public ResponseEntity<Oauth2Envelop<WlyyUserSimple>> sso(@RequestParam Map<String, String> parameters) {
        String clientId = parameters.get("client_id");
@ -154,6 +186,12 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        return getResponse(wlyyUserSimple);
    }
    /**
     * 登出
     * @param parameters
     * @param request
     * @return
     */
    @RequestMapping(value = "/oauth/logout", method = RequestMethod.POST)
    public ResponseEntity<Oauth2Envelop> logout(@RequestParam Map<String, String> parameters, HttpServletRequest request) {
        String token = request.getHeader("token");
@ -172,112 +210,125 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
        return new ResponseEntity<>(oauth2Envelop, headers, HttpStatus.OK);
    }
    /*@RequestMapping(value = ServiceApi.Authentication.VerifyCode, method = RequestMethod.POST)
    public ResponseEntity<Envelop> verifyCode(@RequestParam Map<String, String> parameters) throws  Exception{
        Envelop envelop = new Envelop();
    /**
     * 获取公钥
     * @param httpSession
     * @param httpServletResponse
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/oauth/public_key", method = RequestMethod.GET)
    public ResponseEntity<Oauth2Envelop<PublicKey>> publicKey (
            HttpSession httpSession,
            HttpServletResponse httpServletResponse) throws Exception {
        //生成公钥和私钥
        HashMap<String, Object> map = RSAUtils.generateKeys();
        RSAPublicKey rsaPublicKey = (RSAPublicKey) map.get("public");
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) map.get("private");
        PublicKey publicKey = new PublicKey();
        publicKey.setModulus(Base64.encodeBase64String(rsaPublicKey.getModulus().toByteArray()));
        publicKey.setExponent(Base64.encodeBase64String(rsaPublicKey.getPublicExponent().toByteArray()));
        httpSession.setAttribute("privateKey", rsaPrivateKey);
        //生成Cookie
        Cookie cookie = new Cookie("oauth2", UUID.randomUUID().toString());
        cookie.setMaxAge(60);
        cookie.setPath("/oauth");
        httpServletResponse.addCookie(cookie);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
        Oauth2Envelop<PublicKey> oauth2Envelop = new Oauth2Envelop<>("public_key", 200, publicKey);
        return new ResponseEntity<>(oauth2Envelop, headers, HttpStatus.OK);
    }
    /**
     * 获取验证码
     * @param parameters
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/oauth/captcha", method = RequestMethod.GET)
    public ResponseEntity<Oauth2Envelop<Captcha>> captcha(@RequestParam Map<String, String> parameters) throws  Exception{
        String client_id = parameters.get("client_id");
        String username = parameters.get("username");
        if (StringUtils.isEmpty(client_id)) {
            throw new InvalidRequestException("client_id");
        }
        if (StringUtils.isEmpty(username)){
            envelop.setSuccessFlg(false);
            envelop.setErrorMsg("手机号码【"+username+"】不能为空!");
            return new ResponseEntity<>(envelop, headers, HttpStatus.OK);
            throw new InvalidRequestException("username");
        }
        VerifyCode verifyCode = new VerifyCode();
        //手机短信验证码
        RandomUtil randomUtil = new RandomUtil();
        String random = randomUtil.getRandomString(6);
        //发送短信
        String api = "MsgGW.Sms.send";
        String content = "尊敬的用户:欢迎使用健康上饶,您的验证码为:【" + random + "】,有效期10分钟,请尽快完成注册。若非本人操作,请忽略。";
        Map<String, String> apiParamMap = new HashMap<>();
        //手机号码
        apiParamMap.put("mobile", username);
        //业务标签
        apiParamMap.put("handlerId", fzHandlerId);
        //短信内容
        apiParamMap.put("content", content);
        //渠道号
        apiParamMap.put("clientId", fzClientId);
        String result = null;
        Envelop resultEnvelop = fzApiClient.fzInnerApi(api, objectMapper.writeValueAsString(apiParamMap), 1);
        if (resultEnvelop.isSuccessFlg()) {
            result = resultEnvelop.getObj().toString();
        //验证请求间隔超时,防止频繁获取验证码
        if (!wlyyRedisVerifyCodeService.isIntervalTimeout(client_id, username)) {
            throw new IllegalAccessException("SMS request frequency is too fast");
        }
        if (!StringUtils.isEmpty(result)) {
            Map<String, Object> resultMap = objectMapper.readValue(result, Map.class);
            Integer resultCode = 0;
            if (null != resultMap.get("Code") && !"".equals(resultMap.get("Code"))) {
                resultCode = Integer.valueOf(resultMap.get("Code").toString());
            }
            if (resultCode == 10000) {
                verifyCode.setExpiresIn(600);
                verifyCode.setNextRequestTime(60);
                //验证码有效期
                ehrRedisVerifyCodeService.store(client_id, username, random, 600000);
                envelop.setSuccessFlg(true);
                envelop.setObj(verifyCode);
            } else if(resultCode == -201){
                envelop.setSuccessFlg(false);
                envelop.setErrorCode(resultCode);
                envelop.setErrorMsg("短信已达每天限制的次数(10次)!");
            } else if(resultCode == -200){
                envelop.setSuccessFlg(false);
                envelop.setErrorCode(resultCode);
                envelop.setErrorMsg("短信发送频率太快(不能低于60s)!");
            } else {
                envelop.setSuccessFlg(false);
                envelop.setErrorCode(resultCode);
                envelop.setErrorMsg("短信验证码发送失败!");
            }
        } else {
            envelop.setSuccessFlg(false);
            envelop.setErrorCode(ErrorCode.REQUEST_NOT_COMPLETED.value());
            envelop.setErrorMsg("短信验证码发送失败!");
        //发送短信获取验证码
        HttpHeaders reqHeaders = new HttpHeaders();
        reqHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("clientId", client_id);
        params.add("type", "login");
        params.add("to", username);
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, reqHeaders);
        HashMap<String, Object> result = restTemplate.postForObject("http://svr-base:10020/sms_gateway/send", httpEntity, HashMap.class);
        if (200 == (Integer) result.get("status")){
            Map<String, Object> sms =  (Map)result.get("obj");
            String captcha = (String) sms.get("captcha");
            Date deadline = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((String) sms.get("deadline"));
            Long expire = (deadline.getTime() - new Date().getTime()) / 1000;
            Captcha _captcha = new Captcha();
            _captcha.setCode(captcha);
            _captcha.setExpiresIn(expire.intValue());
            wlyyRedisVerifyCodeService.store(client_id, username, captcha, expire.intValue());
            Oauth2Envelop<Captcha> oauth2Envelop = new Oauth2Envelop<>("captcha", 200, _captcha);
            HttpHeaders headers = new HttpHeaders();
            headers.set("Cache-Control", "no-store");
            headers.set("Pragma", "no-cache");
            return new ResponseEntity<>(oauth2Envelop, headers, HttpStatus.OK);
        }
        return new ResponseEntity<>(envelop, headers, HttpStatus.OK);
    }
    @RequestMapping(value = ServiceApi.Authentication.VerifyCodeExpire, method = RequestMethod.POST)
    public ResponseEntity<VerifyCode> verifyCodeExpire(@RequestParam Map<String, String> parameters) {
        String client_id = parameters.get("client_id");
        String username = parameters.get("username");
        VerifyCode verifyCode = new VerifyCode();
        int expiresIn = ehrRedisVerifyCodeService.getExpireTime(client_id, username);
        int nextRequestTime = 60 + (expiresIn - 600 ) > 0 ? 60 + (expiresIn - 600 ) : 0;
        verifyCode.setNextRequestTime(nextRequestTime);
        verifyCode.setExpiresIn(expiresIn);
        throw new IllegalStateException((String) result.get("message"));
        /*Captcha _captcha = new Captcha();
        _captcha.setCode("12345");
        _captcha.setExpiresIn(10000);
        _captcha.setInterval(60);
        wlyyRedisVerifyCodeService.store(client_id, username, "12345", 100);
        Oauth2Envelop<Captcha> oauth2Envelop = new Oauth2Envelop("captcha", 200, _captcha);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
        return new ResponseEntity<>(verifyCode, headers, HttpStatus.OK);
        return new ResponseEntity<>(oauth2Envelop, headers, HttpStatus.OK);*/
    }
    @RequestMapping(value = ServiceApi.Authentication.VerifyCodeValidate, method = RequestMethod.POST)
    public ResponseEntity<Envelop> verifyCodeValidate(@RequestParam Map<String, String> parameters) throws  Exception{
        Envelop envelop = new Envelop();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
    /**
     * 验证验证码
     * @param parameters
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/oauth/captcha", method = RequestMethod.POST)
    public ResponseEntity<Oauth2Envelop> captchaCheck  (@RequestParam Map<String, String> parameters) throws  Exception{
        String client_id = parameters.get("client_id");
        String username = parameters.get("username");
        String verifyCode = parameters.get("verify_code");
        if (StringUtils.isEmpty(verifyCode)){
            envelop.setSuccessFlg(false);
            envelop.setErrorMsg("验证码不能为空!");
            return new ResponseEntity<>(envelop, headers, HttpStatus.OK);
        String captcha = parameters.get("captcha");
        if (StringUtils.isEmpty(client_id)) {
            throw new InvalidRequestException("client_id");
        }
        if (StringUtils.isEmpty(username)){
            throw new InvalidRequestException("username");
        }
        if (StringUtils.isEmpty(captcha)){
            throw new InvalidRequestException("captcha");
        }
        boolean _verify = ehrRedisVerifyCodeService.verification(client_id, username, verifyCode);
        if (_verify){
            envelop.setSuccessFlg(true);
        Oauth2Envelop<Boolean> oauth2Envelop;
        if (wlyyRedisVerifyCodeService.verification(client_id, username, captcha)) {
            oauth2Envelop = new Oauth2Envelop<>("验证码正确", 200, true);
        } else {
            envelop.setSuccessFlg(false);
            envelop.setErrorMsg("请输入正确的验证码!");
            oauth2Envelop = new Oauth2Envelop<>("验证码错误", 200, false);
        }
        return new ResponseEntity<>(envelop, headers, HttpStatus.OK);
    }*/
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
        return new ResponseEntity<>(oauth2Envelop, headers, HttpStatus.OK);
    }
    @Override
    protected TokenGranter getTokenGranter() {
@ -306,29 +357,43 @@ public class WlyyLoginEndpoint extends AbstractEndpoint {
   @ExceptionHandler(Exception.class)
    public ResponseEntity<Oauth2Envelop> handleException(Exception e) throws Exception {
        LOG.info(e.getMessage(), e);
        LOG.debug(e.getMessage(), e);
        if (e instanceof UsernameNotFoundException) {
            return handleOAuth2Exception(new Oauth2Envelop("用户未注册!", HttpStatus.UNAUTHORIZED.value()));
            return handleOAuth2Exception(new Oauth2Envelop("用户不存在!", HttpStatus.UNAUTHORIZED.value()), e);
        } else if (e instanceof NoSuchClientException) {
            return handleOAuth2Exception(new Oauth2Envelop("应用未注册!", HttpStatus.UNAUTHORIZED.value()));
            return handleOAuth2Exception(new Oauth2Envelop("应用未注册!", HttpStatus.UNAUTHORIZED.value()), e);
        } else if (e instanceof InvalidGrantException) {
            if (e.getMessage().equals("verify_code")) {
                return handleOAuth2Exception(new Oauth2Envelop("验证码有误!", HttpStatus.UNAUTHORIZED.value()));
            }
            return handleOAuth2Exception(new Oauth2Envelop("密码有误!", HttpStatus.UNAUTHORIZED.value()));
            return handleOAuth2Exception(new Oauth2Envelop(invalidGrantMessage((InvalidGrantException)e), HttpStatus.UNAUTHORIZED.value()), e);
        } else if (e instanceof InvalidTokenException) {
            return handleOAuth2Exception(new Oauth2Envelop("Token有误!", HttpStatus.UNAUTHORIZED.value()));
            return handleOAuth2Exception(new Oauth2Envelop("Token有误!", HttpStatus.UNAUTHORIZED.value()), e);
        } else if (e instanceof InvalidRequestException) {
            return handleOAuth2Exception(new Oauth2Envelop("参数" + e.getMessage() + "缺失!", HttpStatus.UNAUTHORIZED.value()));
            return handleOAuth2Exception(new Oauth2Envelop("参数" + e.getMessage() + "缺失!", HttpStatus.UNAUTHORIZED.value()), e);
        } else if (e instanceof IllegalAccessException) {
            return handleOAuth2Exception(new Oauth2Envelop("短信请求频率过快,请稍后再试!", -1), e);
        } else if (e instanceof IllegalStateException) {
            return handleOAuth2Exception(new Oauth2Envelop("短信网关请求失败!", -1), e);
        }
        return handleOAuth2Exception(new Oauth2Envelop(e.getMessage(), -1), e);
    }
    private String invalidGrantMessage(InvalidGrantException e) {
        if (e.getMessage().equals("User is disabled")) {
            return "账号不可用!";
        } else if (e.getMessage().equals("User account is locked")) {
            return "账号已被锁定,请稍后重试!";
        } else if (e.getMessage().equals("Bad credentials")) {
            return userDetailsService.authFailure();
        } else if (e.getMessage().equals("Invalid captcha")) {
            return "验证码错误!";
        }
        return handleOAuth2Exception(new Oauth2Envelop(e.getMessage(), -1));
        return e.getMessage();
    }
    private ResponseEntity<Oauth2Envelop> handleOAuth2Exception(Oauth2Envelop authenticationFailed) throws IOException {
    private ResponseEntity<Oauth2Envelop> handleOAuth2Exception(Oauth2Envelop authenticationFailed, Exception e) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
        headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, authenticationFailed.getMessage()));
        headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getMessage()));
        ResponseEntity<Oauth2Envelop> response = new ResponseEntity<>(authenticationFailed, headers, HttpStatus.OK);
        return response;
    }

+ 5 - 8
server/svr-authentication/src/main/java/com/yihu/jw/security/oauth2/provider/endpoint/WlyyTokenEndpoint.java

@ -97,7 +97,6 @@ public class WlyyTokenEndpoint extends AbstractEndpoint {
        TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(parameters, authenticatedClient);
        /*
         * customize
         * skip this step
         */
        /*if (clientId != null && !clientId.equals("")) {
@ -136,7 +135,7 @@ public class WlyyTokenEndpoint extends AbstractEndpoint {
        if (token == null) {
            throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());
        }
        // customize ---------------------------------
        // ----------------- Simple Result ----------------
        WlyyOAuth2AccessToken wlyyOAuth2AccessToken = new WlyyOAuth2AccessToken();
        wlyyOAuth2AccessToken.setAccessToken(token.getValue());
        wlyyOAuth2AccessToken.setTokenType(token.getTokenType());
@ -144,7 +143,7 @@ public class WlyyTokenEndpoint extends AbstractEndpoint {
        wlyyOAuth2AccessToken.setRefreshToken(token.getRefreshToken().getValue());
        wlyyOAuth2AccessToken.setScope(org.apache.commons.lang.StringUtils.join(token.getScope(), " "));
        wlyyOAuth2AccessToken.setState(parameters.get("state"));
        // customize ---------------------------------
        // ----------------- Simple Result ----------------
        return getResponse(wlyyOAuth2AccessToken);
@ -201,7 +200,6 @@ public class WlyyTokenEndpoint extends AbstractEndpoint {
    }*/
    /**
     * (customize)
     * @param e
     * @return
     * @throws Exception
@ -209,7 +207,7 @@ public class WlyyTokenEndpoint extends AbstractEndpoint {
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Oauth2Envelop> handleException(Exception e) throws Exception {
        LOG.info(e.getMessage(), e);
        return handleOAuth2Exception(new Oauth2Envelop(e.getMessage(), -1));
        return handleOAuth2Exception(new Oauth2Envelop(e.getMessage(), -1), e);
    }
    private ResponseEntity<WlyyOAuth2AccessToken> getResponse(WlyyOAuth2AccessToken accessToken) {
@ -220,17 +218,16 @@ public class WlyyTokenEndpoint extends AbstractEndpoint {
    }
    /**
     * customize
     * return results directly
     * @param authenticationFailed
     * @return
     * @throws IOException
     */
    private ResponseEntity<Oauth2Envelop> handleOAuth2Exception(Oauth2Envelop authenticationFailed) throws IOException {
    private ResponseEntity<Oauth2Envelop> handleOAuth2Exception(Oauth2Envelop authenticationFailed, Exception e) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
        headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, authenticationFailed.getMessage()));
        headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getMessage()));
        ResponseEntity<Oauth2Envelop> response = new ResponseEntity<>(authenticationFailed, headers, HttpStatus.OK);
        return response;
    }

+ 5 - 5
server/svr-authentication/src/main/resources/application.yml

@ -18,11 +18,11 @@ spring:
      max-wait: -1 # Maximum amount of time (in milliseconds) a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely.
      min-idle: 1 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive.
logging:
  level:
    org:
      springframework:
        security: DEBUG
#logging:
#  level:
#    org:
#      springframework:
#        security: DEBUG
---
spring:

+ 41 - 16
svr/svr-base/src/main/java/com/yihu/jw/base/activemq/ConsumerRunner.java

@ -9,6 +9,7 @@ import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;
import javax.jms.*;
import javax.jms.IllegalStateException;
import java.util.Set;
/**
@ -21,36 +22,59 @@ public class ConsumerRunner implements Runnable, ExceptionListener {
    private final String topic;
    private Set<String> pushUrl;
    private TopicConnection topicConnection;
    private QueueConnection connection;
    private Session session;
    private MessageConsumer consumer;
    private RestTemplate restTemplate;
    public ConsumerRunner(String topic, Set<String> pushUrl) throws Exception {
    public ConsumerRunner(String topic, Set<String> pushUrl) {
        Assert.notNull(topic, "Topic cannot be null");
        this.topic = topic;
        this.pushUrl = pushUrl;
        init();
    }
    private void init() throws Exception {
    private void init() {
        try {
            ActiveMQConnectionFactory connectionFactory = SpringContext.getService(ActiveMQConnectionFactory.class);
            // Create a Connection
            connection = connectionFactory.createQueueConnection();
            connection.start();
            connection.setExceptionListener(this);
            // Create a Session
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            // Create the destination (Topic or Queue)
            Destination destination = session.createQueue(topic);
            // Create a MessageConsumer from the Session to the Topic or Queue
            consumer = session.createConsumer(destination);
            restTemplate = new RestTemplate();
        } catch (JMSException e) {
            LOGGER.error("Failed to init ConsumerRunner", e);
        }
    }
    private void recover() throws JMSException {
        ActiveMQConnectionFactory connectionFactory = SpringContext.getService(ActiveMQConnectionFactory.class);
        // Create a Connection
        topicConnection = connectionFactory.createTopicConnection();
        topicConnection.start();
        topicConnection.setExceptionListener(this);
        connection = connectionFactory.createQueueConnection();
        connection.start();
        connection.setExceptionListener(this);
        // Create a Session
        Session session = topicConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        // Create the destination (Topic or Queue)
        Destination destination = session.createTopic(topic);
        Destination destination = session.createQueue(topic);
        // Create a MessageConsumer from the Session to the Topic or Queue
        consumer = session.createConsumer(destination);
        restTemplate = new RestTemplate();
        if (null == restTemplate) {
            restTemplate = new RestTemplate();
        }
    }
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
                // Wait for a message
                Message message = consumer.receive(1000);
                if (message != null) {
@ -70,18 +94,19 @@ public class ConsumerRunner implements Runnable, ExceptionListener {
                }
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
                if (e instanceof IllegalStateException) {
                    try {
                        recover();
                    } catch (JMSException jme) {
                        LOGGER.error("Failed to recover ConsumerRunner", jme);
                    }
                }
            }
        }
    }
    @Override
    public void onException(JMSException e) {
        LOGGER.error("Trying to recover from JMS Connection exception", e);
        try {
            topicConnection.close();
            topicConnection.start();
        } catch (Exception ex) {
            LOGGER.error("Failed to recover JMS Connection", ex);
        }
        LOGGER.error("ConsumerRunner onException", e);
    }
}

+ 0 - 57
svr/svr-base/src/main/java/com/yihu/jw/base/config/BaseJpa.java

@ -1,57 +0,0 @@
//package com.yihu.jw.base.config;
//
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
//import org.springframework.boot.context.properties.ConfigurationProperties;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.context.annotation.Primary;
//import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
//import org.springframework.orm.jpa.JpaTransactionManager;
//import org.springframework.orm.jpa.JpaVendorAdapter;
//import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
//import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
//import org.springframework.transaction.annotation.EnableTransactionManagement;
//
//import javax.persistence.EntityManagerFactory;
//import javax.sql.DataSource;
//
///**
// * Created by chenweida on 2017/4/6.
// */
//@Configuration
//@EnableTransactionManagement
//@EnableJpaRepositories(
//        entityManagerFactoryRef = "baseEntityManagerFactory",
//        transactionManagerRef = "baseTransactionManager",
//        basePackages = {"com.yihu.jw.business"})   //设置Repository所在位置
//public class BaseJpa {
//
//    @Autowired
//    private HibernateProperties hibernateProperties;
//
//    @Bean(name = "baseEntityManagerFactory")
//    @Primary
//    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(DataSource dataSource) {
//
//        LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
//        emfb.setDataSource(dataSource);
//        emfb.setPackagesToScan("com.yihu.jw.base");
//        emfb.setPersistenceUnitName("base");
//        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
//        emfb.setJpaVendorAdapter(vendorAdapter);
//        emfb.setJpaProperties(hibernateProperties.hibProperties());
//
//        return emfb;
//    }
//
//
//    @Bean(name = "baseTransactionManager")
//    @Primary
//    JpaTransactionManager transactionManagerSecondary(
//            @Qualifier("baseEntityManagerFactory") EntityManagerFactory builder) {
//        return new JpaTransactionManager(builder);
//    }
//}

+ 0 - 43
svr/svr-base/src/main/java/com/yihu/jw/base/config/HibernateProperties.java

@ -1,43 +0,0 @@
//package com.yihu.jw.base.config;
//
//import org.hibernate.EmptyInterceptor;
//import org.hibernate.Interceptor;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.cloud.context.config.annotation.RefreshScope;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.stereotype.Component;
//
//import java.util.List;
//import java.util.Properties;
//
///**
// * Created by chenweida on 2017/4/6.
// */
//@Configuration
//@Component
//public class HibernateProperties {
//    @Value("${hibernate.dialect}")
//    private String dialect;
//    @Value("${hibernate.show_sql}")
//    private String show_sql;
////    @Value("${hibernate.ejb.naming_strategy}")
////    private String naming_strategy;
//
//    @Value("${hibernate.physical_naming_strategy}")
//    private String physical_naming_strategy;
//    @Value("${hibernate.implicit_naming_strategy}")
//    private String implicit_naming_strategy;
////    @Autowired
////    private List<Interceptor> interceptors;
//
//    public Properties hibProperties() {
//        Properties properties = new Properties();
//        properties.put("hibernate.dialect", dialect);
//        properties.put("hibernate.show_sql", show_sql);
//        properties.put("hibernate.physical_naming_strategy", physical_naming_strategy);
//        properties.put("hibernate.implicit_naming_strategy", implicit_naming_strategy);
//        //properties.put("hibernate.ejb.interceptor", interceptors.get(0));
//        return properties;
//    }
//}

+ 21 - 14
svr/svr-base/src/main/java/com/yihu/jw/base/config/SwaggerDocs.java

@ -1,5 +1,12 @@
package com.yihu.jw.base.config;
import io.github.swagger2markup.GroupBy;
import io.github.swagger2markup.Language;
import io.github.swagger2markup.Swagger2MarkupConfig;
import io.github.swagger2markup.Swagger2MarkupConverter;
import io.github.swagger2markup.builder.Swagger2MarkupConfigBuilder;
import io.github.swagger2markup.markup.builder.MarkupLanguage;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
@ -17,19 +24,19 @@ public class SwaggerDocs {
        String prefix = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        Path outputFile = Paths.get(prefix.substring(prefix.lastIndexOf(":") + 1, prefix.indexOf("target") - 1) + "/build/" + group); //文档输出地址
//        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
//                .withMarkupLanguage(MarkupLanguage.ASCIIDOC)
//                .withOutputLanguage(Language.ZH)
//                .withPathsGroupedBy(GroupBy.TAGS)
//                .withGeneratedExamples()
//                .withoutInlineSchema()
//                //.withBasePathPrefix()
//                .build();
//
//        Swagger2MarkupConverter converter = Swagger2MarkupConverter.from(remoteSwaggerFile)
//                .withConfig(config)
//                .build();
//
//        converter.toFile(outputFile);
        Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder()
                .withMarkupLanguage(MarkupLanguage.ASCIIDOC)
                .withOutputLanguage(Language.ZH)
                .withPathsGroupedBy(GroupBy.TAGS)
                .withGeneratedExamples()
                .withoutInlineSchema()
                //.withBasePathPrefix()
                .build();
        Swagger2MarkupConverter converter = Swagger2MarkupConverter.from(remoteSwaggerFile)
                .withConfig(config)
                .build();
        converter.toFile(outputFile);
    }
}

+ 6 - 14
svr/svr-base/src/main/java/com/yihu/jw/base/dao/patient/BasePatientDao.java

@ -1,21 +1,13 @@
package com.yihu.jw.base.dao.patient;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.yihu.jw.entity.base.patient.BasePatientDO;
/**
 * 
 * 居民信息 数据库访问层
 * 
 * @version 
 * <pre>
 * Author	Version		Date		Changes
 * litaohong 	1.0  		2018年08月31日 	Created
 *
 * </pre>
 * @since 1.
 * Created by Trick on 2018/8/31.
 */
public interface BasePatientDao extends PagingAndSortingRepository<BasePatientDO, String>, JpaSpecificationExecutor<BasePatientDO>  {
}
public interface BasePatientDao extends PagingAndSortingRepository<BasePatientDO, String>, JpaSpecificationExecutor<BasePatientDO> {
    BasePatientDO findByIdAndDel(String id,String del);
}

+ 13 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/patient/BasePatientFamilyMemberDao.java

@ -0,0 +1,13 @@
package com.yihu.jw.base.dao.patient;
import com.yihu.jw.entity.base.patient.BasePatientFamilyMemberDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Trick on 2018/8/31.
 */
public interface BasePatientFamilyMemberDao extends PagingAndSortingRepository<BasePatientFamilyMemberDO, String>, JpaSpecificationExecutor<BasePatientFamilyMemberDO> {
    public BasePatientFamilyMemberDO findByPatientAndFamilyMember(String patient,String member);
}

+ 12 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/score/BaseEvaluateDao.java

@ -0,0 +1,12 @@
package com.yihu.jw.base.dao.score;
import com.yihu.jw.entity.base.score.BaseEvaluateDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Trick on 2018/8/31.
 */
public interface BaseEvaluateDao extends PagingAndSortingRepository<BaseEvaluateDO, String>, JpaSpecificationExecutor<BaseEvaluateDO> {
}

+ 11 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/score/BaseEvaluateScoreDao.java

@ -0,0 +1,11 @@
package com.yihu.jw.base.dao.score;
import com.yihu.jw.entity.base.score.BaseEvaluateScoreDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Trick on 2018/8/31.
 */
public interface BaseEvaluateScoreDao extends PagingAndSortingRepository<BaseEvaluateScoreDO, String>, JpaSpecificationExecutor<BaseEvaluateScoreDO> {
}

+ 29 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WechatDao.java

@ -0,0 +1,29 @@
package com.yihu.jw.base.dao.wx;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Administrator on 2017/5/20 0020.
 */
public interface WechatDao extends PagingAndSortingRepository<WxWechatDO, String>, JpaSpecificationExecutor<WxWechatDO> {
    @Query("from WxWechatDO w where w.appId = ?1 and w.status!=-1")
    WxWechatDO findByAppId(String appId);
    @Query("from WxWechatDO w where w.appId = ?1 and w.id!= ?2 and w.status!=-1")
    WxWechatDO findByAppIdExcludeId(String appId, String id);
    @Query("from WxWechatDO w where w.id = ?1 and w.status!=-1")
    WxWechatDO findById(String id);
    @Query("from WxWechatDO w where w.status!=-1")
    List<WxWechatDO> findAll();
    @Query("from WxWechatDO w where w.appOriginId = ?1 and w.status!=-1")
    WxWechatDO findByAppOriginId(String appOriginId);
}

+ 17 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxAccessTokenDao.java

@ -0,0 +1,17 @@
package com.yihu.jw.base.dao.wx;
import com.yihu.jw.entity.base.wx.WxAccessTokenDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Administrator on 2017/5/18 0018.
 */
public interface WxAccessTokenDao extends PagingAndSortingRepository<WxAccessTokenDO, String>, JpaSpecificationExecutor<WxAccessTokenDO> {
    @Query("from WxAccessTokenDO w where w.wechatId =?1 order by w.addTimestamp desc")
    List<WxAccessTokenDO> getWxAccessTokenById(String wechatId);
}

+ 15 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxGraphicMessageDao.java

@ -0,0 +1,15 @@
package com.yihu.jw.base.dao.wx;//package com.yihu.jw.business.wx.dao;
//
//import com.yihu.jw.base.wx.WxGraphicMessageDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.jpa.repository.Query;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
///**
// * Created by Administrator on 2017/5/20 0020.
// */
//public interface WxGraphicMessageDao extends PagingAndSortingRepository<WxGraphicMessageDO, String>, JpaSpecificationExecutor<WxGraphicMessageDO> {
//
//    @Query("from WxGraphicMessageDO w where w.id =?1 and w.status!=-1")
//    WxGraphicMessageDO findById(String id);
//}

+ 15 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxGraphicSceneGroupDao.java

@ -0,0 +1,15 @@
package com.yihu.jw.base.dao.wx;
import com.yihu.jw.entity.base.wx.WxGraphicSceneGroupDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Trick on 2018/8/16.
 */
public interface WxGraphicSceneGroupDao extends PagingAndSortingRepository<WxGraphicSceneGroupDO, String>, JpaSpecificationExecutor<WxGraphicSceneGroupDO> {
    List<WxGraphicSceneGroupDO> findByWechatIdAndScene(String wechatId, String scene);
}

+ 20 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxMenuDao.java

@ -0,0 +1,20 @@
package com.yihu.jw.base.dao.wx;
import com.yihu.jw.entity.base.wx.WxMenuDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Administrator on 2017/5/19 0019.
 */
public interface WxMenuDao  extends PagingAndSortingRepository<WxMenuDO, String>, JpaSpecificationExecutor<WxMenuDO> {
    @Query("FROM WxMenuDO w WHERE w.wechatId =?1 AND w.status ='1' AND w.supMenuid IS NULL ORDER BY w.sort ASC")
    List<WxMenuDO> findParentRootByWechatId(String wechatId);
    @Query("FROM WxMenuDO w WHERE w.wechatId =?1 AND w.status ='1' AND w.supMenuid IS NOT NULL ORDER BY w.sort ASC")
    List<WxMenuDO> findChilrenByWechatId(String wechatId);
}

+ 13 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxMenuJsonDao.java

@ -0,0 +1,13 @@
package com.yihu.jw.base.dao.wx;
import com.yihu.jw.entity.base.wx.WxMenuJsonDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Trick on 2018/8/13.
 */
public interface WxMenuJsonDao extends PagingAndSortingRepository<WxMenuJsonDO, String>, JpaSpecificationExecutor<WxMenuJsonDO> {
    WxMenuJsonDO findByWechatIdAndStatus(String wechatId, Integer status);
}

+ 18 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxReplySceneDao.java

@ -0,0 +1,18 @@
package com.yihu.jw.base.dao.wx;
import com.yihu.jw.entity.base.wx.WxReplySceneDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Trick on 2018/8/16.
 */
public interface WxReplySceneDao extends PagingAndSortingRepository<WxReplySceneDO, String>, JpaSpecificationExecutor<WxReplySceneDO> {
    List<WxReplySceneDO> findByAppOriginIdAndMsgTypeAndStatus(String appOriginId, String msgType, Integer status);
    List<WxReplySceneDO> findByAppOriginIdAndMsgTypeAndEventAndStatus(String appOriginId, String msgType, String event, Integer status);
}

+ 15 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxTemplateConfigDao.java

@ -0,0 +1,15 @@
package com.yihu.jw.base.dao.wx;
import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Trick on 2018/8/21.
 */
public interface WxTemplateConfigDao extends PagingAndSortingRepository<WxTemplateConfigDO, String>, JpaSpecificationExecutor<WxTemplateConfigDO> {
    WxTemplateConfigDO findByWechatIdAndTemplateNameAndScene(String wechatId, String templateName, String scene);
}

+ 21 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/dao/wx/WxTemplateDao.java

@ -0,0 +1,21 @@
package com.yihu.jw.base.dao.wx;//package com.yihu.jw.business.wx.dao;
//
//import com.yihu.jw.base.wx.WxTemplateDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.jpa.repository.Query;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
//import java.util.List;
//
///**
// * Created by Administrator on 2017/5/20 0020.
// */
//public interface WxTemplateDao extends PagingAndSortingRepository<WxTemplateDO, String>, JpaSpecificationExecutor<WxTemplateDO> {
//
//
//    @Query("from WxTemplateDO w where w.id = ?1 and w.status =1")
//    WxTemplateDO findById(String id);
//
//    @Query("from WxTemplateDO w where w.wechatId = ?1 and w.status =1")
//    List<WxTemplateDO> findByWxId(String wechatId);
//}

+ 49 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/patient/PatientFamilyMemberEndpoint.java

@ -0,0 +1,49 @@
package com.yihu.jw.base.endpoint.patient;
import com.yihu.jw.base.service.patient.PatientFamilyMemberService;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.BaseRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by Trick on 2018/9/3.
 */
@RestController
@RequestMapping(value = BaseRequestMapping.PatientMember.PREFIX)
@Api(value = "家庭成员", description = "家庭成员管理", tags = {"wlyy基础服务 - 家庭成员管理"})
public class PatientFamilyMemberEndpoint extends EnvelopRestEndpoint {
    @Autowired
    private PatientFamilyMemberService patientMemberService;
    @PostMapping(value = BaseRequestMapping.PatientMember.CREATE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建")
    public Envelop createFamilyMember(@ApiParam(name = "patient", value = "用户id", required = true)
                                      @RequestParam(value = "patient")String patient,
                                      @ApiParam(name = "member", value = "家庭成员id", required = true)
                                      @RequestParam(value = "member")String member,
                                      @ApiParam(name = "relation", value = "关系 1父亲 2母亲 3老公 4老婆 5儿子 6女儿 7其他", required = true)
                                      @RequestParam(value = "relation")Integer relation)throws Exception{
        patientMemberService.createFamilyMember(patient,member,relation);
        return success("success");
    }
    @PostMapping(value = BaseRequestMapping.PatientMember.DELETE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "删除")
    public Envelop delFamilyMember(@ApiParam(name = "patient", value = "用户id", required = true)
                                      @RequestParam(value = "patient")String patient,
                                      @ApiParam(name = "member", value = "家庭成员id", required = true)
                                      @RequestParam(value = "member")String member)throws Exception{
        patientMemberService.delFamilyMember(patient,member);
        return success("success");
    }
}

+ 44 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/score/ScoreEndPoint.java

@ -0,0 +1,44 @@
package com.yihu.jw.base.endpoint.score;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.base.service.score.ScoreService;
import com.yihu.jw.entity.base.score.BaseEvaluateDO;
import com.yihu.jw.entity.base.score.BaseEvaluateScoreDO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.BaseRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
 * Created by Trick on 2018/9/3.
 */
@RestController
@RequestMapping(value = BaseRequestMapping.Score.PREFIX)
@Api(value = "评价系统", description = "评价系统", tags = {"wlyy基础服务 - 评价系统"})
public class ScoreEndPoint extends EnvelopRestEndpoint {
    @Autowired
    private ScoreService scoreService;
    @PostMapping(value = BaseRequestMapping.Score.CREATE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "创建")
    public Envelop addEvaluateScore(@ApiParam(name = "baseEvaluateScoreJson", value = "分数主表json", required = true)
                                    @RequestParam(value = "baseEvaluateScoreJson") String baseEvaluateScoreJson,
                                    @ApiParam(name = "evaluates", value = "用户列表", required = true)
                                    @RequestParam(value = "evaluates") String evaluates) {
        BaseEvaluateScoreDO baseEvaluateScoreDO = JSONObject.parseObject(baseEvaluateScoreJson, BaseEvaluateScoreDO.class);
        List<BaseEvaluateDO> evaluateDOs = (List<BaseEvaluateDO>) JSONArray.parseArray(evaluates, BaseEvaluateDO.class);
        scoreService.addEvaluateScore(baseEvaluateScoreDO, evaluateDOs);
        return success("success");
    }
}

+ 138 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/wx/WechatConfigController.java

@ -0,0 +1,138 @@
package com.yihu.jw.base.endpoint.wx;//package com.yihu.jw.business.wx.controller;
//
//import com.yihu.jw.base.wx.WxWechatDO;
//import com.yihu.jw.business.wx.service.WechatService;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.restmodel.common.Envelop;
//import com.yihu.jw.restmodel.common.EnvelopRestController;
//import com.yihu.jw.restmodel.base.wx.WxWechatVO;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiParam;
//import org.apache.commons.lang.StringUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.MediaType;
//import org.springframework.web.bind.annotation.*;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.util.ArrayList;
//import java.util.List;
//
///**
// * Created by chenweida on 2017/5/11.
// */
//@RestController
//@RequestMapping(WechatRequestMapping.api_common)
//@Api(value = "微信相关操作", description = "微信相关操作")
//public class WechatConfigController extends EnvelopRestController {
//    @Autowired
//    private WechatService wechatService;
//
//    @PostMapping(value = WechatRequestMapping.WxConfig.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "创建微信配置", notes = "创建微信配置")
//    public Envelop createWechat(
//            @ApiParam(name = "json_data", value = "", defaultValue = "")
//            @RequestBody String jsonData) {
//        try {
//            WxWechatDO wechat = toEntity(jsonData, WxWechatDO.class);
//            return Envelop.getSuccess(WechatRequestMapping.WxConfig.message_success_create, wechatService.createWechat(wechat));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @PutMapping(value = WechatRequestMapping.WxConfig.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "修改微信配置", notes = "修改微信配置")
//    public Envelop updateWechat(
//            @ApiParam(name = "json_data", value = "", defaultValue = "")
//            @RequestBody String jsonData) {
//        try {
//            WxWechatDO wechat = toEntity(jsonData, WxWechatDO.class);
//            return Envelop.getSuccess(WechatRequestMapping.WxConfig.message_success_update, wechatService.updateWxchat(wechat));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//
//    @DeleteMapping(value = WechatRequestMapping.WxConfig.api_delete)
//    @ApiOperation(value = "删除微信配置", notes = "删除微信配置")
//    public Envelop deleteWechat(
//            @ApiParam(name = "ids", value = "ids")
//            @RequestParam(value = "ids", required = true) String ids,
//            @ApiParam(name = "userId", value = "userId")
//            @RequestParam(value = "userId", required = true) String userId,
//            @ApiParam(name = "userName", value = "userName")
//            @RequestParam(value = "userName", required = true) String userName
//            ) {
//        try {
//            wechatService.deleteWechat(ids,userId,userName);
//            return Envelop.getSuccess(WechatRequestMapping.WxConfig.message_success_delete );
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @GetMapping(value = WechatRequestMapping.WxConfig.api_getById)
//    @ApiOperation(value = "根据Id查找微信配置", notes = "根据code查找微信配置")
//    public Envelop findById(
//            @ApiParam(name = "id", value = "id")
//            @RequestParam(value = "id", required = true) String id
//    ) {
//        try {
//            return Envelop.getSuccess(WechatRequestMapping.WxConfig.message_success_find, wechatService.findById(id));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @RequestMapping(value = WechatRequestMapping.WxConfig.api_getWechats, method = RequestMethod.GET)
//    @ApiOperation(value = "获取微信配置列表(分页)")
//    public Envelop getWechats(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档")
//            @RequestParam(value = "sorts", required = false) String sorts,
//            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
//            @RequestParam(value = "size", required = false) int size,
//            @ApiParam(name = "page", value = "页码", defaultValue = "1")
//            @RequestParam(value = "page", required = false) int page,
//            HttpServletRequest request,
//            HttpServletResponse response) throws Exception {
//        if(StringUtils.isBlank(sorts)){
//            sorts = "-updateTime";
//        }
//        //得到list数据
//        List<WxWechatDO> list = wechatService.search(fields, filters, sorts, page, size);
//        //获取总数
//        long count=wechatService.getCount(filters);
//        //封装头信息
//        pagedResponse(request, response, count, page, size);
//        //封装返回格式
//        List<WxWechatVO> WxWechatVOs = convertToModels(list, new ArrayList<>(list.size()), WxWechatVO.class, fields);
//
//        return Envelop.getSuccessListWithPage(WechatRequestMapping.WxConfig.message_success_find_functions,WxWechatVOs, page, size,count);
//    }
//
//
//    @GetMapping(value = WechatRequestMapping.WxConfig.api_getWechatNoPage)
//    @ApiOperation(value = "获取微信列表配置,不分页")
//    public Envelop getWechatNoPage(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,name,saasId,appId,appSecret,baseUrl,remark")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
//        //得到list数据
//        List<WxWechatDO> list = wechatService.search(fields,filters,sorts);
//        //封装返回格式
//        List<WxWechatVO> WxWechatVOs = convertToModels(list, new ArrayList<>(list.size()), WxWechatVO.class, fields);
//        return Envelop.getSuccessList(WechatRequestMapping.WxConfig.message_success_find_functions,WxWechatVOs);
//    }
//
//}

+ 182 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/wx/WechatCoreController.java

@ -0,0 +1,182 @@
package com.yihu.jw.base.endpoint.wx;
import com.yihu.jw.base.service.wx.WechatCoreService;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.BaseRequestMapping;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
/**
 * Created by Trick on 2018/8/16.
 */
@RestController
@RequestMapping(BaseRequestMapping.WeChat.PREFIX)
@Api(value = "微信回调及事件处理", description = "微信回调及事件处理")
public class WechatCoreController extends EnvelopRestEndpoint {
    private Logger logger = LoggerFactory.getLogger(WechatCoreController.class);
    @Autowired
    private WechatCoreService wechatCoreService;
    /**
     * 微信接口验证
     *
     * @param request
     * @param response
     */
    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public void checkSignature(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String signature = request.getParameter("signature").toString();
        String timestamp = request.getParameter("timestamp").toString();
        String nonce = request.getParameter("nonce").toString();
        String echostr = request.getParameter("echostr").toString();
        if (validate(signature, timestamp, nonce)) {
            // 验证成功,返回验证码
            response.getWriter().print(echostr);
        } else {
            // 验证失败
            response.setStatus(401);
        }
    }
    /**
     * 接收居民微信回复的消息
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public void receiveMessages(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String signature = request.getParameter("signature").toString();
        String timestamp = request.getParameter("timestamp").toString();
        String nonce = request.getParameter("nonce").toString();
        if (validate(signature, timestamp, nonce)) {
            String xmlStr = wechatCoreService.messageProcess(request);
            // 判断返回值是xml、json格式(取关是空串)
            Boolean flag = wechatCoreService.isXML(xmlStr);
            if (xmlStr == "error") {
                // 服务器错误
                response.setStatus(500);
            } else if (!flag && StringUtils.isNotEmpty(xmlStr)) {
                JSONObject json = new JSONObject(xmlStr);
//                    if (json.has("openId")) {
//                        if (StringUtils.isNotEmpty(json.getString("openId")) && !("undefined".equals(json.getString("openId")))) {
//                            pushMsgTask.putWxMsg(getAccessToken(), json.getInt("type"), json.getString("openId"), null, json);
//                        }
//                    }
            } else {
                // 返回消息(图文消息)
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                //这句话的意思,是告诉servlet用UTF-8转码,而不是用默认的ISO8859
                response.setCharacterEncoding("UTF-8");
                logger.info(xmlStr);
                response.getWriter().print(xmlStr);
            }
        } else {
            // 验证失败
            response.setStatus(401);
        }
    }
    /**
     * 微信推送消息验证
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     * @throws NoSuchAlgorithmException
     */
    private boolean validate(String signature, String timestamp, String nonce) throws NoSuchAlgorithmException {
        //查询平台所有微信token
        List<WxWechatDO> wxs =  wechatCoreService.findAll();
        if(wxs!=null&&wxs.size()>0){
            for(WxWechatDO wx :wxs){
                String token = wx.getToken();
                // 字典序排序
                String[] array = new String[]{token, timestamp, nonce};
                Arrays.sort(array);
                //连接字典序排序后字符串
                String content = "";
                for (String str : array) {
                    content += str;
                }
                // 解析
                MessageDigest md = MessageDigest.getInstance("SHA-1");
                String decodeStr = "";
                byte[] bytes = md.digest(content.getBytes());
                decodeStr = byteToStr(bytes);
                //验证
                if (StringUtils.isNotEmpty(decodeStr) && decodeStr.equals(signature.toUpperCase())) {
                    return true;
                }
            }
        }
        return false;
    }
    /**
     * 将字节转换为字符
     *
     * @param mByte
     * @return
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }
    /**
     * 将字节数组转换为字符串
     *
     * @param byteArray
     * @return
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }
    @RequestMapping(value ="test", method = RequestMethod.POST)
    @ResponseBody
    public String  testProcess() throws Exception{
        return wechatCoreService.testProcess();
    }
}

+ 47 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/wx/WxAccessTokenController.java

@ -0,0 +1,47 @@
package com.yihu.jw.base.endpoint.wx;//package com.yihu.jw.business.wx.controller;
//
//import com.yihu.jw.base.wx.WxAccessTokenDO;
//import com.yihu.jw.business.wx.service.WxAccessTokenService;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.restmodel.common.Envelop;
//import com.yihu.jw.restmodel.common.EnvelopRestController;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiParam;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestParam;
//import org.springframework.web.bind.annotation.RestController;
//
///**
// * Created by cyx on 2017/5/11.
// */
//@RestController
//@RequestMapping(WechatRequestMapping.api_common)
//@Api(value = "微信token模块", description = "微信token模块接口管理")
//public class WxAccessTokenController extends EnvelopRestController {
//
//    @Autowired
//    private WxAccessTokenService wxAccessTokenService;
//
//    /**
//     * 根据wechatCode获取WxAccessToken
//     * @param wechatId
//     * @return MWxAccessToken
//     * @throws Exception
//     */
//    @GetMapping(value = WechatRequestMapping.WxAccessToken.api_get)
//    @ApiOperation(value = "根据wechatId获取最新的WxAccessToken")
//    public Envelop getWxAccessToken(
//            @ApiParam(name = "wechatId", value = "wechatId")
//            @RequestParam(value = "wechatId") String wechatId) {
//        try {
//            WxAccessTokenDO wxAccessToken = wxAccessTokenService.getWxAccessTokenById(wechatId);
//            return Envelop.getSuccess(WechatRequestMapping.WxAccessToken.message_success_get, wxAccessToken);
//        }catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//}

+ 164 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/wx/WxGraphicMessageController.java

@ -0,0 +1,164 @@
package com.yihu.jw.base.endpoint.wx;//package com.yihu.jw.business.wx.controller;
//
//import com.yihu.jw.base.wx.WxGraphicMessageDO;
//import com.yihu.jw.business.wx.service.WxGraphicMessageService;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.restmodel.common.Envelop;
//import com.yihu.jw.restmodel.common.EnvelopRestController;
//import com.yihu.jw.restmodel.base.wx.WxGraphicMessageVO;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiParam;
//import org.apache.commons.lang.StringUtils;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.MediaType;
//import org.springframework.web.bind.annotation.*;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.util.ArrayList;
//import java.util.List;
//
///**
// *   2017/5/11.
// */
//@RestController
//@RequestMapping(WechatRequestMapping.api_common)
//@Api(value = "微信图文相关操作", description = "微信图文相关操作")
//public class WxGraphicMessageController extends EnvelopRestController {
//    @Autowired
//    private WxGraphicMessageService wxGraphicMessageService;
//
//    @PostMapping(value = WechatRequestMapping.WxGraphicMessage.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "创建微信图文消息", notes = "创建微信图文消息")
//    public Envelop createWxGraphicMessage(
//            @ApiParam(name = "json_data", value = "", defaultValue = "")
//            @RequestBody String jsonData) {
//        try {
//            WxGraphicMessageDO WxGraphicMessage = toEntity(jsonData, WxGraphicMessageDO.class);
//            return Envelop.getSuccess(WechatRequestMapping.WxGraphicMessage.message_success_create, wxGraphicMessageService.createWxGraphicMessage(WxGraphicMessage));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//
//    @PutMapping(value = WechatRequestMapping.WxGraphicMessage.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "修改微信图文消息", notes = "修改微信图文消息")
//    public Envelop updateWxGraphicMessage(
//            @ApiParam(name = "json_data", value = "", defaultValue = "")
//            @RequestBody String jsonData) {
//        try {
//            WxGraphicMessageDO WxGraphicMessage = toEntity(jsonData, WxGraphicMessageDO.class);
//            return Envelop.getSuccess(WechatRequestMapping.WxGraphicMessage.message_success_update, wxGraphicMessageService.updateWxGraphicMessage(WxGraphicMessage));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//
//    @DeleteMapping(value = WechatRequestMapping.WxGraphicMessage.api_delete)
//    @ApiOperation(value = "删除微信图文消息", notes = "删除微信图文消息")
//    public Envelop deleteWxGraphicMessage(
//            @ApiParam(name = "codes", value = "codes")
//            @RequestParam(value = "codes", required = true) String codes,
//            @ApiParam(name = "userCode", value = "userCode")
//            @RequestParam(value = "userCode", required = true) String userCode,
//            @ApiParam(name = "userName", value = "userName")
//            @RequestParam(value = "userName", required = true) String userName
//    ) {
//        try {
//            wxGraphicMessageService.deleteWxGraphicMessage(codes, userCode, userName);
//            return Envelop.getSuccess(WechatRequestMapping.WxGraphicMessage.message_success_delete );
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @GetMapping(value = WechatRequestMapping.WxGraphicMessage.api_getById)
//    @ApiOperation(value = "根据code查找微信图文消息", notes = "根据code查找微信图文消息")
//    public Envelop findByCode(
//            @ApiParam(name = "id", value = "id")
//            @RequestParam(value = "id", required = true) String id
//    ) {
//        try {
//            return Envelop.getSuccess(WechatRequestMapping.WxGraphicMessage.message_success_find, wxGraphicMessageService.findById(id));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @RequestMapping(value = WechatRequestMapping.WxGraphicMessage.api_getWxGraphicMessages, method = RequestMethod.GET)
//    @ApiOperation(value = "获取微信图文消息列表(分页)")
//    public Envelop getWxGraphicMessages(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,title,description,url,pic_url,remark,status")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+title,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts,
//            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
//            @RequestParam(value = "size", required = false) int size,
//            @ApiParam(name = "page", value = "页码", defaultValue = "1")
//            @RequestParam(value = "page", required = false) int page,
//            HttpServletRequest request,
//            HttpServletResponse response) throws Exception {
//        if(StringUtils.isBlank(sorts)){
//            sorts = "-updateTime";
//        }
//        //得到list数据
//        List<WxGraphicMessageDO> list = wxGraphicMessageService.search(fields, filters, sorts, page, size);
//        //获取总数
//        long count=wxGraphicMessageService.getCount(filters);
//        //封装头信息
//        pagedResponse(request, response, count, page, size);
//        //封装返回格式
//        List<WxGraphicMessageVO> WxGraphicMessageVOs = convertToModels(list, new ArrayList<>(list.size()), WxGraphicMessageVO.class, fields);
//
//        return Envelop.getSuccessListWithPage(WechatRequestMapping.WxGraphicMessage.message_success_find_functions,WxGraphicMessageVOs, page, size,count);
//    }
//
//
//    @GetMapping(value = WechatRequestMapping.WxGraphicMessage.api_getWxGraphicMessageNoPage)
//    @ApiOperation(value = "获取图文消息列表,不分页")
//    public Envelop getWxGraphicMessageNoPage(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,title,description,url,pic_url,remark,status")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+title,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
//        //得到list数据
//        List<WxGraphicMessageDO> list = wxGraphicMessageService.search(fields,filters,sorts);
//        //封装返回格式
//        List<WxGraphicMessageVO> WxGraphicMessageVOs = convertToModels(list, new ArrayList<>(list.size()), WxGraphicMessageVO.class, fields);
//        return Envelop.getSuccessList(WechatRequestMapping.WxGraphicMessage.message_success_find_functions,WxGraphicMessageVOs);
//    }
//
//    //@GetMapping(value = WlyyContants.WxGraphicMessage.api_sendGraphicMessages)
//    //@ApiOperation(value = "发送图文消息")
//    //public Envelop sendGraphicMessages(
//    //        @ApiParam(name = "codes", value = "根据code发送微信图文消息,多个code用,分割")
//    //        @RequestParam(value = "codes", required = true) String codes,HttpServletRequest request) throws Exception {
//    //    String messages = wxGraphicMessageService.sendGraphicMessages(codes, request);
//    //    return Envelop.getSuccess("成功",messages);
//    //}
//
//    @GetMapping(value = WechatRequestMapping.WxGraphicMessage.api_sendGraphicMessages)
//    @ApiOperation(value = "发送图文消息")
//    @ResponseBody
//    public String sendGraphicMessages(
//            @ApiParam(name = "ids", value = "根据code发送微信图文消息,多个code用,分割")
//            @RequestParam(value = "ids", required = true) String ids,
//            @ApiParam(name = "fromUserName", value = "用户openid")
//            @RequestParam(value = "fromUserName", required = true) String fromUserName,
//            @ApiParam(name = "toUserName", value = "公众号")
//            @RequestParam(value = "toUserName", required = true) String toUserName
//            ) throws Exception {
//        String messages = wxGraphicMessageService.sendGraphicMessages(ids, fromUserName,toUserName);
//        return messages;
//    }
//
//
//}

+ 219 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/wx/WxMenuController.java

@ -0,0 +1,219 @@
package com.yihu.jw.base.endpoint.wx;
import com.yihu.jw.base.service.wx.WechatService;
import com.yihu.jw.base.service.wx.WxMenuService;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.WechatRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by Administrator on 2017/5/19 0019.
 */
@RestController
@RequestMapping(WechatRequestMapping.api_common)
@Api(value = "微信菜单相关操作", description = "微信菜单相关操作")
public class WxMenuController extends EnvelopRestEndpoint {
    @Autowired
    private WxMenuService wxMenuService;
    @Autowired
    private WechatService wechatService;
    @PostMapping(value = WechatRequestMapping.WxMenu.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "添加微信菜单", notes = "添加微信菜单")
    public MixEnvelop createWxMenu(@ApiParam(name = "wxId", value = "微信id")
                                    @RequestParam(value = "wxId", required = false)String wxId) throws Exception{
        return wxMenuService.createWxMenu(wxId);
    }
//    @PutMapping(value = WechatRequestMapping.WxMenu.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "修改微信菜单", notes = "修改微信菜单")
//    public Envelop updateWxMenu(
//            @ApiParam(name = "json_data", value = "", defaultValue = "")
//            @RequestBody String jsonData) {
//        try {
//            WxMenuDO wxMenu = toEntity(jsonData, WxMenuDO.class);
//            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_update, wxMenuService.updateWxMenu(wxMenu));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//    @DeleteMapping(value = WechatRequestMapping.WxMenu.api_delete)
//    @ApiOperation(value = "删除微信菜单", notes = "删除微信菜单")
//    public Envelop deleteWxMenu(
//            @ApiParam(name = "ids", value = "ids")
//            @RequestParam(value = "ids", required = true) String ids,
//            @ApiParam(name = "userId", value = "userId")
//            @RequestParam(value = "userId", required = true) String userId,
//            @ApiParam(name = "userName", value = "userName")
//            @RequestParam(value = "userName", required = true) String userName
//    ) {
//        try {
//            wxMenuService.deleteWxMenu(ids, userId, userName);
//            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_delete );
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @GetMapping(value = WechatRequestMapping.WxMenu.api_getById)
//    @ApiOperation(value = "根据code查找微信菜单", notes = "根据code查找微信菜单")
//    public Envelop findByCode(
//            @ApiParam(name = "id", value = "id")
//            @RequestParam(value = "id", required = true) String id
//    ) {
//        try {
//            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_find, wxMenuService.findById(id));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @RequestMapping(value = WechatRequestMapping.WxMenu.api_getWxMenus, method = RequestMethod.GET)
//    @ApiOperation(value = "获取微信菜单列表(分页)")
//    public Envelop getWxMenus(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,name,saasId,appId,appSecret,baseUrl,remark")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts,
//            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
//            @RequestParam(value = "size", required = false) int size,
//            @ApiParam(name = "page", value = "页码", defaultValue = "1")
//            @RequestParam(value = "page", required = false) int page,
//            HttpServletRequest request,
//            HttpServletResponse response) throws Exception {
//        if(StringUtils.isBlank(sorts)){
//            sorts = "-updateTime";
//        }
//
//        //得到微信列表数据
//        List<WxWechatDO> wechats = wechatService.search(fields, filters, sorts, page, size);
//        for(WxWechatDO wechat:wechats){
//            List<WxMenuDO> parentMenus = wxMenuService.findParentMenuByWechatCode(wechat.getId());
//            if (parentMenus.size()>0){
//                wechat.setState("closed");
//            }else{
//                wechat.setState("open");
//            }
//        }
//        //获取总数
//        long count=wechatService.getCount(filters);
//        //封装头信息
//        pagedResponse(request, response, count, page, size);
//        //封装返回格式
//        List<WxWechatVO> mwechats = convertToModels(wechats, new ArrayList<>(wechats.size()), WxWechatVO.class, fields);
//        return Envelop.getSuccessListWithPage(WechatRequestMapping.WxMenu.message_success_find_functions,mwechats, page, size,count);
//    }
//
//
//    @GetMapping(value = WechatRequestMapping.WxMenu.api_getWxMenuNoPage)
//    @ApiOperation(value = "获取微信菜单列表,不分页")
//    public Envelop getWxMenuNoPage(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,name,saasId,appId,appSecret,baseUrl,remark")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
//        if(filters!=null){
//            filters = "supMenucode=0;"+filters;
//        }else{
//            filters = "supMenucode=0;";
//        }
//        //得到list数据
//        List<WxMenuDO> list = wxMenuService.search(fields,filters,sorts);
//        for(WxMenuDO wxMenu:list){
//            List<WxMenuDO> childMenus = wxMenuService.findChildMenus(wxMenu.getId());
//            wxMenu.setChildren(childMenus);
//        }
//        //封装返回格式
//        List<WxMenuVO> WxMenuVOs = convertToModels(list, new ArrayList<>(list.size()), WxMenuVO.class, fields);
//        Map<String, String> map = wechatService.getAllWechatConfig();
//        for(WxMenuVO menu:WxMenuVOs){
//            menu.setWechatName(map.get(menu.getWechatCode()));
//        }
//        return Envelop.getSuccessList(WechatRequestMapping.WxMenu.message_success_find_functions,WxMenuVOs);
//    }
//
//    /**
//     * 创建微信公众号菜单
//     *
//     * @return
//     */
//    @ApiOperation(value = "创建微信公众号菜单", notes = "创建微信公众号菜单")
//    @RequestMapping(value = WechatRequestMapping.WxMenu.api_createMenu ,method = RequestMethod.GET)
//    public Envelop createWechatMenu(
//            @ApiParam(name = "wechatId", value = "", defaultValue = "")
//            @RequestParam(value = "wechatId", required = true)String wechatId){
//        try{
//            JSONObject result = wxMenuService.createWechatMenu(wechatId);
//            String errcode = result.get("errcode").toString();
//            WechatResponse wechatResponse = new WechatResponse(Integer.valueOf(errcode));
//            String msg = wechatResponse.getMsg();
//            return Envelop.getSuccess("成功",msg);
//        }catch (Exception e){
//            return Envelop.getSuccess("创建失败",e );
//        }
//    }
//
//    /**
//     * 根据微信code查找父菜单
//     * @param wechatId
//     * @return
//     */
//    @GetMapping(value = WechatRequestMapping.WxMenu.api_getParentMenu)
//    @ApiOperation(value = "根据微信code查找父菜单", notes = "根据微信code查找父菜单")
//    public Envelop getParentMenu(
//            @ApiParam(name = "wechatId", value = "wechatId")
//            @PathVariable(value = "wechatId", required = true) String wechatId
//    ) {
//        try {
//            List<WxMenuDO> parentMenus = wxMenuService.findParentMenuByWechatCode(wechatId);
//            for(WxMenuDO parentMenu:parentMenus){
//                List<WxMenuDO> childMenus = wxMenuService.findChildMenus(parentMenu.getId());
//                if (childMenus.size()>0){
//                    parentMenu.setState("closed");
//                }else{
//                    parentMenu.setState("open");
//                }
//            }
//            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_find, parentMenus);
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//
//    /**
//     * 根据父级菜单code查找子菜单
//     * @param parentCode
//     * @return
//     */
//    @GetMapping(value = WechatRequestMapping.WxMenu.api_getChildMenus)
//    @ApiOperation(value = "根据父级菜单code查找子菜单", notes = "根据父级菜单code查找子菜单")
//    public Envelop getChildMenus(
//            @ApiParam(name = "parentCode", value = "parentCode")
//            @PathVariable(value = "parentCode", required = true) String parentCode
//    ) {
//        try {
//            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_find, wxMenuService.findChildMenus(parentCode));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
}

+ 178 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/endpoint/wx/WxTemplateController.java

@ -0,0 +1,178 @@
package com.yihu.jw.base.endpoint.wx;
import com.yihu.jw.base.service.wx.WxTemplateService;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.WechatRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by Administrator on 2017/5/19 0019.
 */
@RestController
@RequestMapping(WechatRequestMapping.api_common)
@Api(value = "微信模版相关操作", description = "微信模版相关操作")
public class WxTemplateController extends EnvelopRestEndpoint {
    @Autowired
    private WxTemplateService wxTemplateService;
    @PostMapping(value = WechatRequestMapping.WxTemplate.api_test_template, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "测试发送微信模板", notes = "测试发送微信模板")
    public String sendWeTempMesTest(String wechatId,String openid)throws Exception{
        return wxTemplateService.sendWeTempMesTest(wechatId,openid);
    }
//    @PostMapping(value = WechatRequestMapping.WxTemplate.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "创建微信模版", notes = "创建微信模版")
//    public Envelop createWxTemplate(
//            @ApiParam(name = "json_data", value = "微信模版json字符串")
//            @RequestBody String jsonData) {
//        try {
//            WxTemplateDO WxTemplate = toEntity(jsonData, WxTemplateDO.class);
//            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_create, wxTemplateService.createWxTemplate(WxTemplate));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @PutMapping(value = WechatRequestMapping.WxTemplate.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "修改微信模版", notes = "修改微信模版")
//    public Envelop updateWxTemplate(
//            @ApiParam(name = "json_data", value = "", defaultValue = "")
//            @RequestBody String jsonData) {
//        try {
//            WxTemplateDO WxTemplate = toEntity(jsonData, WxTemplateDO.class);
//            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_update, wxTemplateService.updateWxTemplate(WxTemplate));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @DeleteMapping(value = WechatRequestMapping.WxTemplate.api_delete)
//    @ApiOperation(value = "删除微信模版", notes = "删除微信模版")
//    public Envelop deleteWxTemplate(
//            @ApiParam(name = "codes", value = "codes")
//            @RequestParam(value = "codes", required = true) String codes,
//            @ApiParam(name = "userCode", value = "userCode")
//            @RequestParam(value = "userCode", required = true) String userCode,
//            @ApiParam(name = "userName", value = "userName")
//            @RequestParam(value = "userName", required = true) String userName
//    ) {
//        try {
//            wxTemplateService.deleteWxTemplate(codes, userCode, userName);
//            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_delete );
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @GetMapping(value = WechatRequestMapping.WxTemplate.api_getById)
//    @ApiOperation(value = "根据code查找微信模版", notes = "根据code查找微信模版")
//    public Envelop findById(
//            @ApiParam(name = "id", value = "id")
//            @RequestParam(value = "id", required = true) String id
//    ) {
//        try {
//            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_find, wxTemplateService.findById(id));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @RequestMapping(value = WechatRequestMapping.WxTemplate.api_getWxTemplates, method = RequestMethod.GET)
//    @ApiOperation(value = "获取微信模版列表(分页)")
//    public Envelop getWechats(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,title,wechatCode,templateId,content,remark,status")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+title,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts,
//            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
//            @RequestParam(value = "size", required = false) int size,
//            @ApiParam(name = "page", value = "页码", defaultValue = "1")
//            @RequestParam(value = "page", required = false) int page,
//            HttpServletRequest request,
//            HttpServletResponse response) throws Exception {
//        if(StringUtils.isBlank(sorts)){
//            sorts = "-updateTime";
//        }
//
//        //得到微信列表数据
//        List<WxWechatDO> wechats = wechatService.search(fields, filters, sorts, page, size);
//        for(WxWechatDO wechat:wechats){
//            List<WxTemplateDO> wxTemplates = wxTemplateService.findByWxId(wechat.getId());
//            if (wxTemplates.size()>0){
//                wechat.setState("closed");
//            }else{
//                wechat.setState("open");
//            }
//        }
//        //获取总数
//        long count=wechatService.getCount(filters);
//        //封装头信息
//        pagedResponse(request, response, count, page, size);
//        //封装返回格式
//        List<WxWechatVO> mwechats = convertToModels(wechats, new ArrayList<>(wechats.size()), WxWechatVO.class, fields);
//        return Envelop.getSuccessListWithPage(WechatRequestMapping.WxMenu.message_success_find_functions,mwechats, page, size,count);
//
//    }
//
//
//    @GetMapping(value = WechatRequestMapping.WxTemplate.api_getWxTemplatesNoPage)
//    @ApiOperation(value = "获取微信模版列表(不分页)")
//    public Envelop getList(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,title,wechatCode,templateId,content,remark,status")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+title,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
//        //得到list数据
//        List<WxTemplateDO> list = wxTemplateService.search(fields,filters,sorts);
//        //封装返回格式
//        List<WxTemplateVO> mWxTemplateVOs = convertToModels(list, new ArrayList<>(list.size()), WxTemplateVO.class, fields);
//        return Envelop.getSuccessList(WechatRequestMapping.WxTemplate.message_success_find_functions,mWxTemplateVOs);
//    }
//
//    @GetMapping(value = WechatRequestMapping.WxTemplate.api_sendTemplateMessage)
//    @ApiOperation(value = "发送微信模板消息")
//    @ResponseBody
//    public Envelop sendTemplateMessage(
//            @ApiParam(name="openid",value="微信用户的openid")
//            @RequestParam String openid,
//            @ApiParam(name="templateCode",value = "模板code")
//            @RequestParam String templateCode,
//            @ApiParam(name="url",value="模板跳转链接")
//            @RequestParam(required = false) String url,
//            @ApiParam(name="appid",value="所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系)")
//            @RequestParam(required = false) String appid,
//            @ApiParam(name="pagepath",value="所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar)")
//            @RequestParam(required = false) String pagepath,
//            @ApiParam(name="data",value="json字符串")
//            @RequestParam String data
//    ){
//        try {
//            Miniprogram miniprogram = null;
//            if(StringUtils.isNotBlank(appid)&&StringUtils.isNotBlank(pagepath)){
//                miniprogram = new Miniprogram();
//                miniprogram.setAppid(appid);
//                miniprogram.setPagepath(pagepath);
//            }
//            JSONObject jsonObject = wxTemplateService.sendTemplateMessage(openid, templateCode, url, data, miniprogram);
//            String errcode = jsonObject.get("errcode").toString();
//            WechatResponse wechatResponse = new WechatResponse(Integer.valueOf(errcode));
//            String msg = wechatResponse.getMsg();
//            return Envelop.getSuccess("成功",msg);
//        }catch (Exception exception) {
//            return Envelop.getSuccess("error", exception);
//        }
//    }
}

+ 121 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/patient/PatientFamilyMemberService.java

@ -0,0 +1,121 @@
package com.yihu.jw.base.service.patient;
import com.yihu.jw.base.dao.patient.BasePatientDao;
import com.yihu.jw.base.dao.patient.BasePatientFamilyMemberDao;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.patient.BasePatientFamilyMemberDO;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.util.idcard.IdCardUtil;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * Created by Trick on 2018/8/31.
 */
@Service
@Transactional
public class PatientFamilyMemberService extends BaseJpaService<BasePatientFamilyMemberDO,BasePatientFamilyMemberDao> {
    @Autowired
    private BasePatientFamilyMemberDao familyMemberDao;
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public String createFamilyMember(String patient,String member,Integer relation)throws Exception{
        BasePatientDO pDo = basePatientDao.findByIdAndDel(patient,"1");
        BasePatientDO mDo = basePatientDao.findByIdAndDel(patient,"1");
        BasePatientFamilyMemberDO family1 = new BasePatientFamilyMemberDO();
        //添加正向关系
        family1.setPatient(patient);
        family1.setFamilyMember(member);
        family1.setFamilyRelation(relation);
        //默认添加已经授权记录,用户同意授权之后调用此接口
        family1.setIsAuthorize(1);
        //添加反向关系
        BasePatientFamilyMemberDO family2 = new BasePatientFamilyMemberDO();
        family1.setPatient(patient);
        family1.setFamilyMember(member);
        family1.setFamilyRelation(familyRelationTrans(mDo,relation));
        //默认添加已经授权记录,用户同意授权之后调用此接口
        family1.setIsAuthorize(1);
        return "1";
    }
    public String delFamilyMember(String patient,String member)throws Exception{
        BasePatientFamilyMemberDO family1 = familyMemberDao.findByPatientAndFamilyMember(patient,member);
        BasePatientFamilyMemberDO family2 = familyMemberDao.findByPatientAndFamilyMember(member,patient);
        familyMemberDao.delete(family1);
        familyMemberDao.delete(family2);
        return "1";
    }
    /**
     * 家庭关系转换
     *
     * @param patient  居民
     * @param relation 关系 1父亲 2母亲 3老公 4老婆 5儿子 6女儿 7其他
     * @return
     */
    public int familyRelationTrans(BasePatientDO patient, Integer relation) throws Exception {
        int relationTrans = 0;
        switch (relation) {
            case 1:
            case 2:
                if (patient.getSex() == 1) {
                    relationTrans = 5;
                } else if (patient.getSex() == 2) {
                    relationTrans = 6;
                } else {
                    relationTrans = 0;
                }
                if (relationTrans == 0) {
                    if (IdCardUtil.getSexForIdcard(StringUtils.isEmpty(patient.getIdcard()) ? "" : patient.getIdcard()).equals("1")) {
                        relationTrans = 6;
                    } else if (IdCardUtil.getSexForIdcard(StringUtils.isEmpty(patient.getIdcard()) ? "" : patient.getIdcard()).equals("2")) {
                        relationTrans = 5;
                    }
                }
                break;
            case 3:
                relationTrans = 4;
                break;
            case 4:
                relationTrans = 3;
                break;
            case 5:
            case 6:
                if (patient.getSex() == 1) {
                    relationTrans = 1;
                } else if (patient.getSex() == 2) {
                    relationTrans = 2;
                } else {
                    relationTrans = 0;
                }
                if (relationTrans == 0) {
                    if (IdCardUtil.getSexForIdcard(StringUtils.isEmpty(patient.getIdcard()) ? "" : patient.getIdcard()).equals("1")) {
                        relationTrans = 2;
                    } else if (IdCardUtil.getSexForIdcard(StringUtils.isEmpty(patient.getIdcard()) ? "" : patient.getIdcard()).equals("2")) {
                        relationTrans = 1;
                    }
                }
                break;
        }
        return relationTrans;
    }
}

+ 42 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/score/ScoreService.java

@ -0,0 +1,42 @@
package com.yihu.jw.base.service.score;
import com.yihu.jw.base.dao.score.BaseEvaluateDao;
import com.yihu.jw.base.dao.score.BaseEvaluateScoreDao;
import com.yihu.jw.entity.base.score.BaseEvaluateDO;
import com.yihu.jw.entity.base.score.BaseEvaluateScoreDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.List;
/**
 * Created by Trick on 2018/8/31.
 */
@Service
@Transactional
public class ScoreService {
    @Autowired
    private BaseEvaluateScoreDao baseEvaluateScoreDao;
    @Autowired
    private BaseEvaluateDao baseEvaluateDao;
    public String addEvaluateScore(BaseEvaluateScoreDO baseEvaluateScoreDO, List<BaseEvaluateDO> evaluateDOList){
        if(evaluateDOList!=null&& evaluateDOList.size()>0){
            Double total = 0.0;
            for(BaseEvaluateDO evaluate :evaluateDOList){
                total += evaluate.getScore();
            }
            Double avg = new BigDecimal(total/evaluateDOList.size()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            baseEvaluateScoreDO.setScore(avg);
            baseEvaluateDao.save(evaluateDOList);
            baseEvaluateScoreDao.save(baseEvaluateScoreDO);
        }
        return "success";
    }
}

+ 25 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/team/TeamService.java

@ -0,0 +1,25 @@
package com.yihu.jw.base.service.team;
import com.yihu.jw.base.dao.BaseTeamDao;
import com.yihu.jw.base.dao.BaseTeamMemberDao;
import com.yihu.jw.entity.base.team.BaseTeamDO;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * Created by Trick on 2018/8/31.
 */
@Service
@Transactional
public class TeamService extends BaseJpaService<BaseTeamDO, BaseTeamDao> {
    @Autowired
    private BaseTeamDao teamDao;
    @Autowired
    private BaseTeamMemberDao baseTeamMemberDao;
}

+ 353 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/wx/WechatCoreService.java

@ -0,0 +1,353 @@
package com.yihu.jw.base.service.wx;
import com.yihu.jw.base.dao.wx.WechatDao;
import com.yihu.jw.base.dao.wx.WxReplySceneDao;
import com.yihu.jw.entity.base.wx.WxReplySceneDO;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.util.wechat.WeiXinMessageReplyUtils;
import com.yihu.jw.util.wechat.WeiXinMessageUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by Trick on 2018/8/16.
 */
@Service
public class WechatCoreService {
    private Logger logger = LoggerFactory.getLogger(WechatCoreService.class);
    @Autowired
    private WechatDao wechatDao;
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    @Autowired
    private WxReplySceneDao wxReplySceneDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 微信推送消息处理
     *
     * @param request
     */
    public String messageProcess(HttpServletRequest request) {
        try {
            String returnStr = "";
            // 将解析结果存储在HashMap中
            Map<String, String> message = new HashMap();
            // 从request中取得输入流
            InputStream inputStream = request.getInputStream();
            // 读取输入流
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            // 得到xml根元素
            Element root = document.getRootElement();
            // 得到根元素的所有子节点
            List elementList = root.elements();
            // 遍历所有子节点
            for (Object e : elementList) {
                Element ele = (Element) e;
                message.put(ele.getName(), ele.getText());
            }
            logger.info("weixin  event:" + message.toString());
            // 释放资源
            inputStream.close();
            // 消息处理
            returnStr = messageProcess(message);
            return returnStr;
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }
    public String  testProcess() throws Exception{
        String returnStr = "";
        Map<String, String> message = new HashMap();
        message.put("Event","subscribe");
        message.put("CreateTime","1534495338");
        message.put("ToUserName","gh_73959f6e996b");
        message.put("FromUserName","oVH-2uJdhNrcAMt0Jhp3PMarDdaM");
        message.put("MsgType","event");
        returnStr = messageProcess(message);
        return returnStr;
    }
    /**
     * 对接收到的消息进行处理
     *
     * @param message
     * @return
     */
    private String messageProcess(Map<String, String> message) throws Exception {
        String msgType = message.get("MsgType");
        String result = "";
        switch (msgType) {
            case WeiXinMessageUtils.REQ_MESSAGE_TYPE_EVENT:  // 事件消息
                logger.info("MsgType:event");
                result = eventProcess(message);
                break;
            case WeiXinMessageUtils.RESP_MESSAGE_TYPE_TEXT:  // 回复文本消息
                //回复文本消息 处理
                logger.info("MsgType:text");
                result = textProcess(message);
                break;
            default:
                break;
        }
        return result;
    }
    /**
     * 事件细分处理:
     * 1.扫描二维码事件
     * 2.订阅事件
     * 3.取消订阅事件
     * 4.菜单点击
     * @param message
     * @return
     */
    public String eventProcess(Map<String, String> message) throws Exception{
        String result = "";
        String event = message.get("Event");
        switch (event) {
            case WeiXinMessageUtils.EVENT_TYPE_SCAN: // 扫描二维码事件
                result = scanEventProcess(message);
                break;
            case WeiXinMessageUtils.EVENT_TYPE_SUBSCRIBE: // 订阅事件
                if (message.containsKey("EventKey") && StringUtils.isNotEmpty(message.get("EventKey")) && message.containsKey("Ticket")
                        && StringUtils.isNotEmpty(message.get("Ticket"))) {
                    result = scanEventProcess(message);
                } else {
                    result = subscribeEventProcess(message);
                }
                break;
            case WeiXinMessageUtils.EVENT_TYPE_UNSUBSCRIBE: // 取消订阅事件
                result = unsubscribeEventProcess(message);
                break;
            case WeiXinMessageUtils.EVENT_TYPE_CLICK: //菜单点击
                result = this.clickProcess(message);
            default:
                break;
        }
        return result;
    }
    /**
     * 扫描二维码事件
     * 1. 用户未关注时,进行关注后的事件推送
     * <xml><ToUserName>< ![CDATA[toUser] ]></ToUserName><FromUserName>< ![CDATA[FromUser] ]></FromUserName><CreateTime>123456789</CreateTime><MsgType>< ![CDATA[event] ]></MsgType><Event>< ![CDATA[subscribe] ]></Event><EventKey>< ![CDATA[qrscene_123123] ]></EventKey><Ticket>< ![CDATA[TICKET] ]></Ticket></xml>
     * 2. 用户已关注时的事件推送
     * <xml> <ToUserName>< ![CDATA[toUser] ]></ToUserName> <FromUserName>< ![CDATA[FromUser] ]></FromUserName> <CreateTime>123456789</CreateTime> <MsgType>< ![CDATA[event] ]></MsgType> <Event>< ![CDATA[SCAN] ]></Event> <EventKey>< ![CDATA[SCENE_VALUE] ]></EventKey> <Ticket>< ![CDATA[TICKET] ]></Ticket> </xml>
     * @param message
     * @return
     */
    public String scanEventProcess(Map<String, String> message) throws Exception{
        //获取原始id
        String toUserName = message.get("ToUserName");
        //如果为已经关注,EventKey值为带参二维码值,如果是未关注 qrscene_为前缀,后面为二维码的参数值
        String eventKey = message.get("EventKey");
        //查询需要对应匹配的带参二维码事件值
        List<WxReplySceneDO> scenes = wxReplySceneDao.findByAppOriginIdAndMsgTypeAndEventAndStatus(toUserName,WeiXinMessageUtils.REQ_MESSAGE_TYPE_EVENT,WeiXinMessageUtils.EVENT_TYPE_SCAN,1);
        if(scenes!=null&&scenes.size()>0){
            for(WxReplySceneDO scene:scenes){
                //判断带参二维码中前缀是否包该场景值
                if(StringUtils.isNotBlank(scene.getScene())&&eventKey.indexOf(scene.getScene())!=-1){
                    return getGraphicXMl(scene.getScene(),scene.getWechatId(),message);
                }
            }
        }
        return "";
    }
    /**
     * 搜索关注事件
     * @param message
     * @return
     */
    public String subscribeEventProcess(Map<String, String> message) throws Exception{
        //获取原始id
        String toUserName = message.get("ToUserName");
        List<WxReplySceneDO> scenes = wxReplySceneDao.findByAppOriginIdAndMsgTypeAndEventAndStatus(toUserName,WeiXinMessageUtils.REQ_MESSAGE_TYPE_EVENT,WeiXinMessageUtils.EVENT_TYPE_SUBSCRIBE,1);
        if(scenes!=null&&scenes.size()>0){
            WxReplySceneDO scene = scenes.get(0);
            if(StringUtils.isNotBlank(scene.getScene())){
                return getGraphicXMl(scene.getScene(),scene.getWechatId(),message);
            }
        }
        return "";
    }
    /**
     * 取消关注事件,根据需求开发
     * @param message
     * @return
     */
    public String unsubscribeEventProcess(Map<String, String> message){
        return "";
    }
    /**
     * 点击事件,根据需求开发
     * @param message
     * @return
     */
    public String clickProcess(Map<String, String> message){
        return "";
    }
    /**
     * 文本消息动态生成图文消息
     * @param message
     * @return
     * @throws Exception
     */
    public String  textProcess(Map<String, String> message) throws Exception{
        String toUserName = message.get("ToUserName");
        String content = message.get("Content");
        List<WxReplySceneDO> scenes = wxReplySceneDao.findByAppOriginIdAndMsgTypeAndStatus(toUserName,WeiXinMessageUtils.RESP_MESSAGE_TYPE_TEXT,1);
        if(scenes!=null&&scenes.size()>0){
            for(WxReplySceneDO scene:scenes){
                if(StringUtils.isNotBlank(scene.getContent())
                        &&content.equals(scene.getContent())
                        &&StringUtils.isNotBlank(scene.getScene())){
                    //根据场景值,动态生成图文消息回复文斌
                    return getGraphicXMl(scene.getScene(),scene.getWechatId(),message);
                }
            }
        }
        return null;
    }
    /**
     * 构造图文消息XML
     * @param secene
     * @param wxId
     * @param message
     * @return
     * @throws Exception
     */
    public String getGraphicXMl(String secene,String wxId,Map<String, String> message)throws Exception{
        List<Map<String,Object>> group = getGraphicGroupByScene(secene,wxId);
        String result = "";
        String eventKey = message.get("EventKey");
        if(group!=null&&group.size()>0){
            List<Map<String, String>> articles = new ArrayList<>();
            for(Map<String,Object> graphic : group){
                // 图文信息
                Map<String, String> article = new HashMap<>();
                String url = (String)graphic.get("url");
                String baseUrl = (String)graphic.get("baseUrl");
                String appId = (String)graphic.get("appId");
                String title = (String)graphic.get("title");
                String description = (String)graphic.get("description");
                String picUrl = (String)graphic.get("picUrl");
                if(url.indexOf("{server}")!=-1){
                    url = url.replace("{server}",baseUrl);
                }
                if(url.indexOf("{appId}")!=-1){
                    url = url.replace("{appId}",appId);
                }
                //传递带参二维码给前端页面
                if(url.indexOf("{EventKey}")!=-1){
                    if(eventKey.indexOf("qrscene_")!=-1){
                        eventKey = eventKey.replace("qrscene_","");
                    }
                    url = url.replace("{EventKey}",eventKey);
                }
                article.put("Url", url);
                article.put("Title", title);
                article.put("Description", description);
                article.put("PicUrl", picUrl);
                articles.add(article);
            }
            result = WeiXinMessageReplyUtils.replyNewsMessage(message.get("FromUserName"), message.get("ToUserName"), articles);
        }
        return result;
    }
    /**
     * 获取指定场景下所有图文消息分组
     * @param secene
     * @param wxId
     * @return
     */
    public List<Map<String,Object>> getGraphicGroupByScene(String secene,String wxId) {
        String sql = "SELECT " +
                " m.title, " +
                " m.description, " +
                " m.url, " +
                " m.pic_url AS picUrl," +
                " w.app_id AS appId," +
                " w.base_url AS baseUrl" +
                " FROM " +
                " wx_graphic_scene_group g " +
                " JOIN wx_graphic_message m ON g.graphic_id = m.id " +
                " JOIN wx_wechat w ON w.id = g.wechat_id" +
                " WHERE " +
                " m.wechat_id = '"+wxId+"' " +
                " AND g.wechat_id = '"+wxId+"' " +
                " AND g.scene = '"+secene+"' " +
                " AND m.`status` = 1 " +
                " ORDER BY g.sort ASC";
        List<Map<String,Object>> group = jdbcTemplate.queryForList(sql);
        return group;
    }
    /**
     * 判断是否是xml结构
     */
    public boolean isXML(String value) {
        try {
            DocumentHelper.parseText(value);
        } catch (DocumentException e) {
            return false;
        }
        return true;
    }
    public List<WxWechatDO> findAll(){
        return wechatDao.findAll();
    }
}

+ 94 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/wx/WechatFansService.java

@ -0,0 +1,94 @@
package com.yihu.jw.base.service.wx;
import com.yihu.jw.util.wechat.wxhttp.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * 微信粉丝管理
 * Created by Trick on 2018/8/22.
 */
@Service
public class WechatFansService {
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    /**
     * 创建分组
     * @param wxId
     * @param param
     * @return
     */
    public String createWxTag(String wxId,String param){
        String url = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
        return HttpUtil.sendPost(url,param);
    }
    /**
     * 查询分组
     * @param wxId
     * @return
     */
    public String findWxTag(String wxId){
        String url = "https://api.weixin.qq.com/cgi-bin/tags/get?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
        return HttpUtil.sendGet(url);
    }
    /**
     * 更新分组
     * @param wxId
     * @param param
     * @return
     */
    public String updateWxTag(String wxId,String param){
        String url = "https://api.weixin.qq.com/cgi-bin/tags/update?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
        return HttpUtil.sendPost(url,param);
    }
    /**
     * 删除分组
     * @param wxId
     * @param param
     * @return
     */
    public String deleteWxTag(String wxId,String param){
        String url = "https://api.weixin.qq.com/cgi-bin/tags/delete?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
        return HttpUtil.sendPost(url,param);
    }
    /**
     *  批量为用户打标签
     * @param wxId
     * @param param
     * @return
     */
    public String createBatchtagging(String wxId,String param){
        String url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
        return HttpUtil.sendPost(url,param);
    }
    /**
     * 批量为用户取消标签
     * @param wxId
     * @param param
     * @return
     */
    public String cancelBatchuntagging(String wxId,String param){
        String url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
        return HttpUtil.sendPost(url,param);
    }
    /**
     * 获取用户身上的标签列表
     * @param wxId
     * @param param
     * @return
     */
    public String getidlist(String wxId,String param){
        String url = "https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
        return HttpUtil.sendPost(url,param);
    }
}

+ 13 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/wx/WechatService.java

@ -0,0 +1,13 @@
package com.yihu.jw.base.service.wx;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * Created by Administrator on 2017/5/20 0020.
 */
@Service
@Transactional
public class WechatService {
}

+ 157 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/wx/WxAccessTokenService.java

@ -0,0 +1,157 @@
package com.yihu.jw.base.service.wx;
import com.yihu.jw.base.dao.wx.WechatDao;
import com.yihu.jw.base.dao.wx.WxAccessTokenDao;
import com.yihu.jw.entity.base.wx.WxAccessTokenDO;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.rm.base.WechatRequestMapping;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.utils.network.HttpUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.*;
/**
 * Created by Administrator on 2017/5/18 0018.
 */
@Service
public class WxAccessTokenService extends BaseJpaService<WxAccessTokenDO, WxAccessTokenDao> {
    private Logger logger= LoggerFactory.getLogger(WxAccessTokenService.class);
    @Autowired
    private WxAccessTokenDao wxAccessTokenDao;
    @Autowired
    private WechatDao wechatDao;
    /**
     * 根据原始id查找
     * @param appOriginId
     * @return
     */
    public WxAccessTokenDO getWxAccessTokenByOriginId(String appOriginId) {
        try {
            //根据wechatCode查找出appid和appSecret
            WxWechatDO wxWechat = wechatDao.findByAppOriginId(appOriginId);
            if(wxWechat==null){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_wxWechat_is_no_exist, ExceptionCode.common_error_params_code);
            }
            List<WxAccessTokenDO> wxAccessTokens =  wxAccessTokenDao.getWxAccessTokenById(wxWechat.getId());
            if(wxAccessTokens!=null&&wxAccessTokens.size()>0){
                for (WxAccessTokenDO accessToken : wxAccessTokens) {
                    if ((System.currentTimeMillis() - accessToken.getAddTimestamp()) < (accessToken.getExpiresIn() * 500)) {
                        return accessToken;
                    } else {
                        wxAccessTokenDao.delete(accessToken);
                        break;
                    }
                }
            }
            String token_url = "https://api.weixin.qq.com/cgi-bin/token";
            String appId="";
            String appSecret="";
            appId = wxWechat.getAppId();
            appSecret = wxWechat.getAppSecret();
            if (StringUtils.isEmpty(appId)){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appId_is_null, ExceptionCode.common_error_params_code);
            }
            if (StringUtils.isEmpty(appSecret)){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appSecret_is_null, ExceptionCode.common_error_params_code);
            }
            /*String params = "grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
            String result = HttpUtil.sendGet(token_url, params);*/
            Map<String, Object> params = new HashMap<>();
            params.put("grant_type", "client_credential");
            params.put("appid", appId);
            params.put("secret", appSecret);
            String result = HttpUtils.doGet(token_url, params).getContent();
            logger.info("--------------wechat token return :"+result+"---------------");
            JSONObject json = new JSONObject(result);
            if (json.has("access_token")) {
                String token = json.get("access_token").toString();
                String expires_in = json.get("expires_in").toString();
                WxAccessTokenDO newaccessToken = new WxAccessTokenDO();
                newaccessToken.setAccessToken(token);
                newaccessToken.setExpiresIn(Long.parseLong(expires_in));
                newaccessToken.setAddTimestamp(System.currentTimeMillis());
                newaccessToken.setCzrq(new Date());
                newaccessToken.setCode(UUID.randomUUID().toString().replace("-",""));
                newaccessToken.setWechatId(wxWechat.getId());
                wxAccessTokenDao.save(newaccessToken);
                return newaccessToken;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public WxAccessTokenDO getWxAccessTokenById(String wechatId) {
        try {
            //根据wechatCode查找出appid和appSecret
            WxWechatDO wxWechat = wechatDao.findById(wechatId);
            if(wxWechat==null){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_wxWechat_is_no_exist, ExceptionCode.common_error_params_code);
            }
            List<WxAccessTokenDO> wxAccessTokens =  wxAccessTokenDao.getWxAccessTokenById(wechatId);
            if(wxAccessTokens!=null&&wxAccessTokens.size()>0){
                for (WxAccessTokenDO accessToken : wxAccessTokens) {
                    if ((System.currentTimeMillis() - accessToken.getAddTimestamp()) < (accessToken.getExpiresIn() * 500)) {
                        return accessToken;
                    } else {
                        wxAccessTokenDao.delete(accessToken);
                        break;
                    }
                }
            }
            String token_url = "https://api.weixin.qq.com/cgi-bin/token";
            String appId="";
            String appSecret="";
            appId = wxWechat.getAppId();
            appSecret = wxWechat.getAppSecret();
            if (StringUtils.isEmpty(appId)){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appId_is_null, ExceptionCode.common_error_params_code);
            }
            if (StringUtils.isEmpty(appSecret)){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appSecret_is_null, ExceptionCode.common_error_params_code);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("grant_type", "client_credential");
            params.put("appid", appId);
            params.put("secret", appSecret);
            String result = HttpUtils.doGet(token_url, params).getContent();
            logger.info("--------------wechat token return:"+result+"---------------");
            JSONObject json = new JSONObject(result);
            if (json.has("access_token")) {
                String token = json.get("access_token").toString();
                String expires_in = json.get("expires_in").toString();
                WxAccessTokenDO newaccessToken = new WxAccessTokenDO();
                newaccessToken.setAccessToken(token);
                newaccessToken.setExpiresIn(Long.parseLong(expires_in));
                newaccessToken.setAddTimestamp(System.currentTimeMillis());
                newaccessToken.setCzrq(new Date());
                newaccessToken.setCode(UUID.randomUUID().toString().replace("-",""));
                newaccessToken.setWechatId(wechatId);
                wxAccessTokenDao.save(newaccessToken);
                return newaccessToken;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

+ 177 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/wx/WxGraphicMessageService.java

@ -0,0 +1,177 @@
package com.yihu.jw.base.service.wx;//package com.yihu.jw.business.wx.service;
//
//import com.yihu.jw.base.wx.WxGraphicMessageDO;
//import com.yihu.jw.business.wx.dao.WxGraphicMessageDao;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.exception.code.ExceptionCode;
//import com.yihu.base.mysql.query.BaseJpaService;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//import com.yihu.jw.base.util.MessageUtil;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.util.StringUtils;
//
//import javax.persistence.Transient;
//import javax.servlet.http.HttpServletRequest;
//import java.util.*;
//
///**
// * Created by Administrator on 2017/5/20 0020.
// */
//@Service
//public class WxGraphicMessageService extends BaseJpaService<WxGraphicMessageDO, WxGraphicMessageDao> {
//
//    @Autowired
//    private WxGraphicMessageDao wxGraphicMessageDao;
//
//    @Transient
//    public WxGraphicMessageDO createWxGraphicMessage(WxGraphicMessageDO wxGraphicMessage) {
//        String code = UUID.randomUUID().toString().replaceAll("-", "");
//        wxGraphicMessage.setId(code);
//        if (StringUtils.isEmpty(wxGraphicMessage.getStatus())) {
//            throw new ApiException(WechatRequestMapping.WxGraphicMessage.message_fail_status_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(wxGraphicMessage.getTitle())) {
//            throw new ApiException(WechatRequestMapping.WxGraphicMessage.message_fail_title_is_null, ExceptionCode.common_error_params_code);
//        }
//        WxGraphicMessageDO wxGraphicMessageTem = wxGraphicMessageDao.findById(wxGraphicMessage.getId());
//        if (wxGraphicMessageTem != null) {
//            throw new ApiException(WechatRequestMapping.WxGraphicMessage.message_fail_id_exist, ExceptionCode.common_error_params_code);
//        }
//        return wxGraphicMessageDao.save(wxGraphicMessage);
//    }
//
//    @Transient
//    public WxGraphicMessageDO updateWxGraphicMessage(WxGraphicMessageDO wxGraphicMessage) {
//        if (StringUtils.isEmpty(wxGraphicMessage.getId())) {
//            throw new ApiException(WechatRequestMapping.WxGraphicMessage.message_fail_id_is_null, ExceptionCode.common_error_params_code);
//        }
//        if (StringUtils.isEmpty(wxGraphicMessage.getStatus())) {
//            throw new ApiException(WechatRequestMapping.WxGraphicMessage.message_fail_status_is_null, ExceptionCode.common_error_params_code);
//        }
//
//        //根据id查找
//        WxGraphicMessageDO wxGraphicMessage1 = findById(wxGraphicMessage.getId());
//        if(wxGraphicMessage1==null){
//            throw new ApiException(WechatRequestMapping.WxGraphicMessage.message_fail_wxGraphicMessage_is_no_exist, ExceptionCode.common_error_params_code);
//        }
//        return wxGraphicMessageDao.save(wxGraphicMessage);
//    }
//
//    public WxGraphicMessageDO findById(String id) {
//      return wxGraphicMessageDao.findById(id);
//    }
//
//    @Transient
//    public void deleteWxGraphicMessage(String codes, String userCode, String userName) {
//        if(!StringUtils.isEmpty(codes)){
//            String[] codeArray = codes.split(",");
//            for(String code:codeArray){
//                WxGraphicMessageDO wxGraphicMessage = findById(code);
//                wxGraphicMessage.setStatus(-1);
//                wxGraphicMessage.setUpdateUser(userCode);
//                wxGraphicMessage.setUpdateUserName(userName);
//                wxGraphicMessageDao.save(wxGraphicMessage);
//            }
//        }
//    }
//
//
//
//    private String replyNewsMessage(String toUser,String fromUser,List<Map<String,String>> articles) throws Exception {
//        if(articles == null || articles.size() < 1){
//            throw new Exception("图文信息不能为空!");
//        }
//
//        StringBuilder result = new StringBuilder();
//        result.append("<xml>");
//        result.append("<ToUserName>" + toUser + "</ToUserName>");
//        result.append("<FromUserName>" + fromUser + "</FromUserName>");
//        result.append("<CreateTime>" + new Date().getTime() + "</CreateTime>");
//        result.append("<MsgType>news</MsgType>");
//        result.append("<ArticleCount>" + articles.size() + "</ArticleCount>");
//        result.append("<Articles>");
//
//        for(Map<String,String>  article : articles){
//            result.append("<item>");
//            result.append("<Title>" +  article.get("Title") +"</Title>");
//            result.append("<Description>" + article.get("Description") + "</Description>");
//            result.append("<PicUrl>" + article.get("PicUrl") + "</PicUrl>");
//            result.append("<Url>" + article.get("Url") + "</Url>");
//            result.append("</item>");
//        }
//
//        result.append("</Articles>");
//        result.append("</xml>");
//
//        return result.toString();
//    }
//
//    /**
//     * 发送图文消息
//     * @param codes
//     * @param request
//     * @return
//     */
//    public String sendGraphicMessages(String codes, HttpServletRequest request) {
//        try {
//            // xml请求解析
//            Map<String, String> requestMap = MessageUtil.parseXml(request);
//            //用户openid
//            String fromUserName = requestMap.get("FromUserName");
//            //微信公众号
//            String toUserName = requestMap.get("ToUserName");
//            // 图文信息
//            List<Map<String,String>> articles =  new ArrayList<>();
//            if(codes!=null){
//                String[] codeArray = codes.split(",");
//                for(String code: codeArray){
//                    WxGraphicMessageDO graphicMessage = findById(code);
//                    Map<String,String> article = new HashMap<>();
//                    article.put("Url",graphicMessage.getUrl());
//                    article.put("Title", graphicMessage.getTitle());
//                    article.put("Description",graphicMessage.getDescription());
//                    article.put("PicUrl",graphicMessage.getPicUrl());
//                    articles.add(article);
//                }
//            }
//            // 构建回复消息XML
//            return replyNewsMessage(fromUserName, toUserName, articles);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return e.getMessage();
//        }
//    }
//
//    /**
//     * 发送图文消息
//     * @param ids
//     * @param fromUserName   用户的openId
//     * @param toUserName
//     * @return
//     */
//    public String sendGraphicMessages(String ids, String fromUserName,String toUserName) {
//        try {
//        // 图文信息
//            List<Map<String,String>> articles =  new ArrayList<>();
//            if(ids!=null){
//                String[] codeArray = ids.split(",");
//                for(String id: codeArray){
//                    WxGraphicMessageDO graphicMessage = findById(id);
//                    Map<String,String> article = new HashMap<>();
//                    article.put("Url",graphicMessage.getUrl());
//                    article.put("Title", graphicMessage.getTitle());
//                    article.put("Description",graphicMessage.getDescription());
//                    article.put("PicUrl",graphicMessage.getPicUrl());
//                    articles.add(article);
//                }
//            }
//            // 构建回复消息XML
//            return replyNewsMessage(fromUserName, toUserName, articles);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return e.getMessage();
//        }
//    }
//
//}

+ 50 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/wx/WxMenuService.java

@ -0,0 +1,50 @@
package com.yihu.jw.base.service.wx;
import com.yihu.jw.base.dao.wx.WechatDao;
import com.yihu.jw.base.dao.wx.WxMenuDao;
import com.yihu.jw.base.dao.wx.WxMenuJsonDao;
import com.yihu.jw.base.util.HttpUtil;
import com.yihu.jw.entity.base.wx.WxMenuDO;
import com.yihu.jw.entity.base.wx.WxMenuJsonDO;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.rm.base.WechatRequestMapping;
import com.yihu.mysql.query.BaseJpaService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * Created by Administrator on 2017/5/19 0019.
 */
@Service
public class WxMenuService extends BaseJpaService<WxMenuDO, WxMenuDao>{
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    @Autowired
    private WxMenuJsonDao wxMenuJsonDao;
    @Autowired
    private WechatDao wechatDao;
    public MixEnvelop createWxMenu(String wxId){
//        String url = "https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=" ;
        String url ="https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+ wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
        WxMenuJsonDO wxMenuJsonDO = wxMenuJsonDao.findByWechatIdAndStatus(wxId,1);
        String params = wxMenuJsonDO.getContent();
        WxWechatDO wechatDO =  wechatDao.findById(wxId);
        // 替换服务器地址、APPID
        params = params.replaceAll("server_url", wechatDO.getBaseUrl());
        params = params.replaceAll("appId", wechatDO.getAppId());
        String jsonStr = HttpUtil.sendPost(url, params);
        JSONObject result = new JSONObject(jsonStr);
        if (result != null && result.get("errcode").toString().equals("0") && result.getString("errmsg").equals("ok")) {
            MixEnvelop.getSuccess(WechatRequestMapping.WxMenu.message_success_update);
        }
        return MixEnvelop.getError(result.toString());
    }
}

+ 156 - 0
svr/svr-base/src/main/java/com/yihu/jw/base/service/wx/WxTemplateService.java

@ -0,0 +1,156 @@
package com.yihu.jw.base.service.wx;
import com.yihu.jw.base.dao.wx.WxTemplateConfigDao;
import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
import com.yihu.jw.util.wechat.WeixinMessagePushUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * Created by Administrator on 2017/5/19 0019.
 */
@Service
public class WxTemplateService {
    private Logger logger= LoggerFactory.getLogger(WxTemplateService.class);
    @Autowired
    private WxTemplateConfigDao wxTemplateConfigDao;
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    @Autowired
    private WeixinMessagePushUtils weixinMessagePushUtils;
    public String sendWeTempMesTest(String wechatId,String openid)throws Exception{
        WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndScene(wechatId,"template_survey","test");
        config.setFirst(config.getFirst().replace("key1","小明"));
        config.setKeyword2("2018-08-21");
        weixinMessagePushUtils.putWxMsg(wxAccessTokenService.getWxAccessTokenById(wechatId).getAccessToken(),openid,config);
        return "success";
    }
//    public WxTemplateDO createWxTemplate(WxTemplateDO wxTemplate) {
//        if (StringUtils.isEmpty(wxTemplate.getTemplateId())) {
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_templateid_is_null, ExceptionCode.common_error_params_code);
//        }
//        String content = wxTemplate.getContent().replace(" ","");
//        if (StringUtils.isEmpty(content)) {
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_is_null, ExceptionCode.common_error_params_code);
//        }
//        if(!content.matches("\\{\\{.+\\.DATA\\}\\}")){//content必须还有 "{{.DATA}}"
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_format_is_not_right, ExceptionCode.common_error_params_code);
//        }
//        return wxTemplateDao.save(wxTemplate);
//    }
//
//    public WxTemplateDO updateWxTemplate(WxTemplateDO wxTemplate) {
//        if (StringUtils.isEmpty(wxTemplate.getTemplateId())) {
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_templateid_is_null, ExceptionCode.common_error_params_code);
//        }
//        String content = wxTemplate.getContent().replace(" ","");
//        if (StringUtils.isEmpty(content)) {
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_is_null, ExceptionCode.common_error_params_code);
//        }
//        String id = wxTemplate.getId();
//        if (StringUtils.isEmpty(id)) {
//            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_id_is_null, ExceptionCode.common_error_params_code);
//        }
//        WxTemplateDO wxTemplate1 = findById(id);
//        if(wxTemplate1==null){
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_template_is_no_exist, ExceptionCode.common_error_params_code);
//        }
//        wxTemplate.setCreateTime(wxTemplate1.getCreateTime());
//        wxTemplate.setUpdateTime(new Date());
//        if(!content.matches("\\{\\{.+\\.DATA\\}\\}")){//content必须还有 "{{.DATA}}"
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_format_is_not_right, ExceptionCode.common_error_params_code);
//        }
//        return wxTemplateDao.save(wxTemplate);
//    }
//
//    public void deleteWxTemplate(String codes, String userCode, String userName) {
//        if(!StringUtils.isEmpty(codes)) {
//            String[] codeArray = codes.split(",");
//            for (String code : codeArray) {
//                WxTemplateDO wxTemplate = wxTemplateDao.findById(code);
//                if (wxTemplate == null) {
//                    throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_id_no_exist, ExceptionCode.common_error_params_code);
//                }
//                wxTemplate.setStatus(-1);
//                wxTemplate.setUpdateUser(userCode);
//                wxTemplate.setUpdateUserName(userName);
//                wxTemplateDao.save(wxTemplate);
//            }
//        }
//    }
//
//
//    public WxTemplateDO findById(String id) {
//        WxTemplateDO wxTemplate = wxTemplateDao.findById(id);
//        return wxTemplate;
//    }
//
//    public JSONObject sendTemplateMessage(String openid, String templateId, String url, String data,Miniprogram miniprogram) {
//        try {
//            //首先根据wechatTemplate获取微信模版
//            WxTemplateDO wxTemplate = findById(templateId);
//            if(wxTemplate==null){
//                throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_template_is_no_exist, ExceptionCode.common_error_params_code);
//            }
//            String wechatCode =  wxTemplate.getWechatId();
//            String content = wxTemplate.getContent().replaceAll(" ", "");//{{result.DATA}}领奖金额:{{withdrawMoney.DATA}   }领奖  时间:{ {withdrawTime.DATA} }银行信息:{ {cardInfo.DATA} }到账时间:{{arrivedTime.DATA}}{{remark.DATA}}
//            String[] contentArray = content.split("\\{\\{");
//
//            //将result,withdrawMoney,withdrawTime,cardInfo,arrivedTime等字符串放入contentList中
//            List<String> contentList = new ArrayList<>();
//            for(int i=1;i<contentArray.length;i++){
//                contentList.add(contentArray[i].substring(0,contentArray[i].indexOf(".")));
//            }
//
//            ObjectMapper mapper = new ObjectMapper();
//            ////将data转为对象
//            Map<String, WechatTemplateDataDO> dataMap = mapper.readValue(data, new TypeReference<LinkedHashMap<String, WechatTemplateDataDO>>() {});
//            Map<String, WechatTemplateDataDO> newDataMap = new LinkedHashMap<String, WechatTemplateDataDO>();
//            int j = 0;
//            for (Map.Entry<String, WechatTemplateDataDO> entry : dataMap.entrySet()) {//(keyword1,WechatTemplateData)
//                String key = entry.getKey();//keyword1   转为result
//                newDataMap.put(contentList.get(j),entry.getValue());
//                j++;
//            }
//
//            //将数据封装在WechatTemplate对象中
//            WechatTemplateDO wechatTemplate = new WechatTemplateDO();
//            wechatTemplate.setTouser(openid);
//            wechatTemplate.setUrl(url);
//            wechatTemplate.setTemplate_id(wxTemplate.getTemplateId());
//            if(miniprogram!=null){
//                wechatTemplate.setMiniprogram(miniprogram);
//            }
//            wechatTemplate.setData(newDataMap);
//
//            String params = mapper.writeValueAsString(wechatTemplate);
//            logger.info("----------------------模版消息json字符串:"+params+"------------------");
//
//            WxAccessTokenDO wxAccessTokenByCode = wxAccessTokenService.getWxAccessTokenById(wechatCode);
//            String token = wxAccessTokenByCode.getAccessToken();
//            String token_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
//            String result = HttpUtil.sendPost(token_url, params);
//            logger.info("------------------------发送模板消息,微信返回结果:"+result+"-----------------------");
//
//            JSONObject jsonResult = new JSONObject(result);
//            return jsonResult;
//        } catch (Exception e) {
//            e.printStackTrace();
//            JSONObject jsonResult = new JSONObject();
//            return jsonResult;
//        }
//    }
//
//    public List<WxTemplateDO> findByWxId(String code) {
//        return wxTemplateDao.findByWxId(code);
//    }
}

+ 182 - 182
svr/svr-base/src/main/java/com/yihu/jw/business/wx/controller/WechatCoreController.java

@ -1,182 +1,182 @@
package com.yihu.jw.business.wx.controller;
import com.yihu.jw.business.wx.service.WechatCoreService;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.rm.base.WechatRequestMapping;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;
/**
 * Created by Trick on 2018/8/16.
 */
@RestController
@RequestMapping(BaseRequestMapping.WeChat.PREFIX)
@Api(value = "微信回调及事件处理", description = "微信回调及事件处理")
public class WechatCoreController extends EnvelopRestEndpoint {
    private Logger logger = LoggerFactory.getLogger(WechatCoreController.class);
    @Autowired
    private WechatCoreService wechatCoreService;
    /**
     * 微信接口验证
     *
     * @param request
     * @param response
     */
    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public void checkSignature(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String signature = request.getParameter("signature").toString();
        String timestamp = request.getParameter("timestamp").toString();
        String nonce = request.getParameter("nonce").toString();
        String echostr = request.getParameter("echostr").toString();
        if (validate(signature, timestamp, nonce)) {
            // 验证成功,返回验证码
            response.getWriter().print(echostr);
        } else {
            // 验证失败
            response.setStatus(401);
        }
    }
    /**
     * 接收居民微信回复的消息
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public void receiveMessages(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String signature = request.getParameter("signature").toString();
        String timestamp = request.getParameter("timestamp").toString();
        String nonce = request.getParameter("nonce").toString();
        if (validate(signature, timestamp, nonce)) {
            String xmlStr = wechatCoreService.messageProcess(request);
            // 判断返回值是xml、json格式(取关是空串)
            Boolean flag = wechatCoreService.isXML(xmlStr);
            if (xmlStr == "error") {
                // 服务器错误
                response.setStatus(500);
            } else if (!flag && StringUtils.isNotEmpty(xmlStr)) {
                JSONObject json = new JSONObject(xmlStr);
//                    if (json.has("openId")) {
//                        if (StringUtils.isNotEmpty(json.getString("openId")) && !("undefined".equals(json.getString("openId")))) {
//                            pushMsgTask.putWxMsg(getAccessToken(), json.getInt("type"), json.getString("openId"), null, json);
//                        }
//                    }
            } else {
                // 返回消息(图文消息)
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                //这句话的意思,是告诉servlet用UTF-8转码,而不是用默认的ISO8859
                response.setCharacterEncoding("UTF-8");
                logger.info(xmlStr);
                response.getWriter().print(xmlStr);
            }
        } else {
            // 验证失败
            response.setStatus(401);
        }
    }
    /**
     * 微信推送消息验证
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     * @throws NoSuchAlgorithmException
     */
    private boolean validate(String signature, String timestamp, String nonce) throws NoSuchAlgorithmException {
        //查询平台所有微信token
        List<WxWechatDO> wxs =  wechatCoreService.findAll();
        if(wxs!=null&&wxs.size()>0){
            for(WxWechatDO wx :wxs){
                String token = wx.getToken();
                // 字典序排序
                String[] array = new String[]{token, timestamp, nonce};
                Arrays.sort(array);
                //连接字典序排序后字符串
                String content = "";
                for (String str : array) {
                    content += str;
                }
                // 解析
                MessageDigest md = MessageDigest.getInstance("SHA-1");
                String decodeStr = "";
                byte[] bytes = md.digest(content.getBytes());
                decodeStr = byteToStr(bytes);
                //验证
                if (StringUtils.isNotEmpty(decodeStr) && decodeStr.equals(signature.toUpperCase())) {
                    return true;
                }
            }
        }
        return false;
    }
    /**
     * 将字节转换为字符
     *
     * @param mByte
     * @return
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }
    /**
     * 将字节数组转换为字符串
     *
     * @param byteArray
     * @return
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }
    @RequestMapping(value ="test", method = RequestMethod.POST)
    @ResponseBody
    public String  testProcess() throws Exception{
        return wechatCoreService.testProcess();
    }
}
//package com.yihu.jw.business.wx.controller;
//
//import com.yihu.jw.business.wx.service.WechatCoreService;
//import com.yihu.jw.entity.base.wx.WxWechatDO;
//import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
//import com.yihu.jw.rm.base.BaseRequestMapping;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//import io.swagger.annotations.Api;
//import org.apache.commons.lang3.StringUtils;
//import org.json.JSONObject;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestMethod;
//import org.springframework.web.bind.annotation.ResponseBody;
//import org.springframework.web.bind.annotation.RestController;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.security.MessageDigest;
//import java.security.NoSuchAlgorithmException;
//import java.util.Arrays;
//import java.util.List;
//
///**
// * Created by Trick on 2018/8/16.
// */
//@RestController
//@RequestMapping(BaseRequestMapping.WeChat.PREFIX)
//@Api(value = "微信回调及事件处理", description = "微信回调及事件处理")
//public class WechatCoreController extends EnvelopRestEndpoint {
//
//    private Logger logger = LoggerFactory.getLogger(WechatCoreController.class);
//
//    @Autowired
//    private WechatCoreService wechatCoreService;
//
//    /**
//     * 微信接口验证
//     *
//     * @param request
//     * @param response
//     */
//    @RequestMapping(method = RequestMethod.GET)
//    @ResponseBody
//    public void checkSignature(HttpServletRequest request, HttpServletResponse response) throws Exception {
//        String signature = request.getParameter("signature").toString();
//        String timestamp = request.getParameter("timestamp").toString();
//        String nonce = request.getParameter("nonce").toString();
//        String echostr = request.getParameter("echostr").toString();
//
//        if (validate(signature, timestamp, nonce)) {
//            // 验证成功,返回验证码
//            response.getWriter().print(echostr);
//        } else {
//            // 验证失败
//            response.setStatus(401);
//        }
//
//    }
//
//    /**
//     * 接收居民微信回复的消息
//     *
//     * @return
//     */
//    @RequestMapping(method = RequestMethod.POST)
//    @ResponseBody
//    public void receiveMessages(HttpServletRequest request, HttpServletResponse response) throws Exception{
//
//        String signature = request.getParameter("signature").toString();
//        String timestamp = request.getParameter("timestamp").toString();
//        String nonce = request.getParameter("nonce").toString();
//
//        if (validate(signature, timestamp, nonce)) {
//            String xmlStr = wechatCoreService.messageProcess(request);
//            // 判断返回值是xml、json格式(取关是空串)
//            Boolean flag = wechatCoreService.isXML(xmlStr);
//            if (xmlStr == "error") {
//                // 服务器错误
//                response.setStatus(500);
//            } else if (!flag && StringUtils.isNotEmpty(xmlStr)) {
//                JSONObject json = new JSONObject(xmlStr);
////                    if (json.has("openId")) {
////                        if (StringUtils.isNotEmpty(json.getString("openId")) && !("undefined".equals(json.getString("openId")))) {
////                            pushMsgTask.putWxMsg(getAccessToken(), json.getInt("type"), json.getString("openId"), null, json);
////                        }
////                    }
//            } else {
//                // 返回消息(图文消息)
//                response.setHeader("Content-type", "text/html;charset=UTF-8");
//                //这句话的意思,是告诉servlet用UTF-8转码,而不是用默认的ISO8859
//                response.setCharacterEncoding("UTF-8");
//
//                logger.info(xmlStr);
//
//                response.getWriter().print(xmlStr);
//            }
//        } else {
//            // 验证失败
//            response.setStatus(401);
//        }
//
//    }
//
//
//    /**
//     * 微信推送消息验证
//     *
//     * @param signature
//     * @param timestamp
//     * @param nonce
//     * @return
//     * @throws NoSuchAlgorithmException
//     */
//    private boolean validate(String signature, String timestamp, String nonce) throws NoSuchAlgorithmException {
//
//        //查询平台所有微信token
//        List<WxWechatDO> wxs =  wechatCoreService.findAll();
//
//        if(wxs!=null&&wxs.size()>0){
//
//            for(WxWechatDO wx :wxs){
//
//                String token = wx.getToken();
//                // 字典序排序
//                String[] array = new String[]{token, timestamp, nonce};
//                Arrays.sort(array);
//                //连接字典序排序后字符串
//                String content = "";
//                for (String str : array) {
//                    content += str;
//                }
//                // 解析
//                MessageDigest md = MessageDigest.getInstance("SHA-1");
//                String decodeStr = "";
//                byte[] bytes = md.digest(content.getBytes());
//                decodeStr = byteToStr(bytes);
//                //验证
//                if (StringUtils.isNotEmpty(decodeStr) && decodeStr.equals(signature.toUpperCase())) {
//                    return true;
//                }
//            }
//        }
//        return false;
//    }
//    /**
//     * 将字节转换为字符
//     *
//     * @param mByte
//     * @return
//     */
//    private static String byteToHexStr(byte mByte) {
//        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
//        char[] tempArr = new char[2];
//        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
//        tempArr[1] = Digit[mByte & 0X0F];
//        String s = new String(tempArr);
//        return s;
//    }
//
//    /**
//     * 将字节数组转换为字符串
//     *
//     * @param byteArray
//     * @return
//     */
//    private static String byteToStr(byte[] byteArray) {
//        String strDigest = "";
//        for (int i = 0; i < byteArray.length; i++) {
//            strDigest += byteToHexStr(byteArray[i]);
//        }
//        return strDigest;
//    }
//
//    @RequestMapping(value ="test", method = RequestMethod.POST)
//    @ResponseBody
//    public String  testProcess() throws Exception{
//        return wechatCoreService.testProcess();
//    }
//}

+ 210 - 210
svr/svr-base/src/main/java/com/yihu/jw/business/wx/controller/WxMenuController.java

@ -1,220 +1,220 @@
package com.yihu.jw.business.wx.controller;
import com.yihu.jw.business.wx.service.WechatService;
import com.yihu.jw.business.wx.service.WxMenuService;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.WechatRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by Administrator on 2017/5/19 0019.
 */
@RestController
@RequestMapping(WechatRequestMapping.api_common)
@Api(value = "微信菜单相关操作", description = "微信菜单相关操作")
public class WxMenuController extends EnvelopRestEndpoint {
    @Autowired
    private WxMenuService wxMenuService;
    @Autowired
    private WechatService wechatService;
    @PostMapping(value = WechatRequestMapping.WxMenu.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "添加微信菜单", notes = "添加微信菜单")
    public MixEnvelop createWxMenu(@ApiParam(name = "wxId", value = "微信id")
                                    @RequestParam(value = "wxId", required = false)String wxId) throws Exception{
        return wxMenuService.createWxMenu(wxId);
    }
//    @PutMapping(value = WechatRequestMapping.WxMenu.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "修改微信菜单", notes = "修改微信菜单")
//    public Envelop updateWxMenu(
//            @ApiParam(name = "json_data", value = "", defaultValue = "")
//            @RequestBody String jsonData) {
//        try {
//            WxMenuDO wxMenu = toEntity(jsonData, WxMenuDO.class);
//            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_update, wxMenuService.updateWxMenu(wxMenu));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//    @DeleteMapping(value = WechatRequestMapping.WxMenu.api_delete)
//    @ApiOperation(value = "删除微信菜单", notes = "删除微信菜单")
//    public Envelop deleteWxMenu(
//            @ApiParam(name = "ids", value = "ids")
//            @RequestParam(value = "ids", required = true) String ids,
//            @ApiParam(name = "userId", value = "userId")
//            @RequestParam(value = "userId", required = true) String userId,
//            @ApiParam(name = "userName", value = "userName")
//            @RequestParam(value = "userName", required = true) String userName
//    ) {
//        try {
//            wxMenuService.deleteWxMenu(ids, userId, userName);
//            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_delete );
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//package com.yihu.jw.business.wx.controller;
//
//    @GetMapping(value = WechatRequestMapping.WxMenu.api_getById)
//    @ApiOperation(value = "根据code查找微信菜单", notes = "根据code查找微信菜单")
//    public Envelop findByCode(
//            @ApiParam(name = "id", value = "id")
//            @RequestParam(value = "id", required = true) String id
//    ) {
//        try {
//            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_find, wxMenuService.findById(id));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//import com.yihu.jw.business.wx.service.WechatService;
//import com.yihu.jw.business.wx.service.WxMenuService;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.restmodel.web.MixEnvelop;
//import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiParam;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.MediaType;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RequestParam;
//import org.springframework.web.bind.annotation.RestController;
//
//    @RequestMapping(value = WechatRequestMapping.WxMenu.api_getWxMenus, method = RequestMethod.GET)
//    @ApiOperation(value = "获取微信菜单列表(分页)")
//    public Envelop getWxMenus(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,name,saasId,appId,appSecret,baseUrl,remark")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts,
//            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
//            @RequestParam(value = "size", required = false) int size,
//            @ApiParam(name = "page", value = "页码", defaultValue = "1")
//            @RequestParam(value = "page", required = false) int page,
//            HttpServletRequest request,
//            HttpServletResponse response) throws Exception {
//        if(StringUtils.isBlank(sorts)){
//            sorts = "-updateTime";
//        }
///**
// * Created by Administrator on 2017/5/19 0019.
// */
//@RestController
//@RequestMapping(WechatRequestMapping.api_common)
//@Api(value = "微信菜单相关操作", description = "微信菜单相关操作")
//public class WxMenuController extends EnvelopRestEndpoint {
//
//        //得到微信列表数据
//        List<WxWechatDO> wechats = wechatService.search(fields, filters, sorts, page, size);
//        for(WxWechatDO wechat:wechats){
//            List<WxMenuDO> parentMenus = wxMenuService.findParentMenuByWechatCode(wechat.getId());
//            if (parentMenus.size()>0){
//                wechat.setState("closed");
//            }else{
//                wechat.setState("open");
//            }
//        }
//        //获取总数
//        long count=wechatService.getCount(filters);
//        //封装头信息
//        pagedResponse(request, response, count, page, size);
//        //封装返回格式
//        List<WxWechatVO> mwechats = convertToModels(wechats, new ArrayList<>(wechats.size()), WxWechatVO.class, fields);
//        return Envelop.getSuccessListWithPage(WechatRequestMapping.WxMenu.message_success_find_functions,mwechats, page, size,count);
//    }
//    @Autowired
//    private WxMenuService wxMenuService;
//
//    @Autowired
//    private WechatService wechatService;
//
//    @GetMapping(value = WechatRequestMapping.WxMenu.api_getWxMenuNoPage)
//    @ApiOperation(value = "获取微信菜单列表,不分页")
//    public Envelop getWxMenuNoPage(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,name,saasId,appId,appSecret,baseUrl,remark")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
//        if(filters!=null){
//            filters = "supMenucode=0;"+filters;
//        }else{
//            filters = "supMenucode=0;";
//        }
//        //得到list数据
//        List<WxMenuDO> list = wxMenuService.search(fields,filters,sorts);
//        for(WxMenuDO wxMenu:list){
//            List<WxMenuDO> childMenus = wxMenuService.findChildMenus(wxMenu.getId());
//            wxMenu.setChildren(childMenus);
//        }
//        //封装返回格式
//        List<WxMenuVO> WxMenuVOs = convertToModels(list, new ArrayList<>(list.size()), WxMenuVO.class, fields);
//        Map<String, String> map = wechatService.getAllWechatConfig();
//        for(WxMenuVO menu:WxMenuVOs){
//            menu.setWechatName(map.get(menu.getWechatCode()));
//        }
//        return Envelop.getSuccessList(WechatRequestMapping.WxMenu.message_success_find_functions,WxMenuVOs);
//    @PostMapping(value = WechatRequestMapping.WxMenu.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "添加微信菜单", notes = "添加微信菜单")
//    public MixEnvelop createWxMenu(@ApiParam(name = "wxId", value = "微信id")
//                                    @RequestParam(value = "wxId", required = false)String wxId) throws Exception{
//        return wxMenuService.createWxMenu(wxId);
//    }
//
//    /**
//     * 创建微信公众号菜单
//     *
//     * @return
//     */
//    @ApiOperation(value = "创建微信公众号菜单", notes = "创建微信公众号菜单")
//    @RequestMapping(value = WechatRequestMapping.WxMenu.api_createMenu ,method = RequestMethod.GET)
//    public Envelop createWechatMenu(
//            @ApiParam(name = "wechatId", value = "", defaultValue = "")
//            @RequestParam(value = "wechatId", required = true)String wechatId){
//        try{
//            JSONObject result = wxMenuService.createWechatMenu(wechatId);
//            String errcode = result.get("errcode").toString();
//            WechatResponse wechatResponse = new WechatResponse(Integer.valueOf(errcode));
//            String msg = wechatResponse.getMsg();
//            return Envelop.getSuccess("成功",msg);
//        }catch (Exception e){
//            return Envelop.getSuccess("创建失败",e );
//        }
//    }
////    @PutMapping(value = WechatRequestMapping.WxMenu.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
////    @ApiOperation(value = "修改微信菜单", notes = "修改微信菜单")
////    public Envelop updateWxMenu(
////            @ApiParam(name = "json_data", value = "", defaultValue = "")
////            @RequestBody String jsonData) {
////        try {
////            WxMenuDO wxMenu = toEntity(jsonData, WxMenuDO.class);
////            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_update, wxMenuService.updateWxMenu(wxMenu));
////        } catch (ApiException e) {
////            return Envelop.getError(e.getMessage(), e.getErrorCode());
////        }
////    }
//
//    /**
//     * 根据微信code查找父菜单
//     * @param wechatId
//     * @return
//     */
//    @GetMapping(value = WechatRequestMapping.WxMenu.api_getParentMenu)
//    @ApiOperation(value = "根据微信code查找父菜单", notes = "根据微信code查找父菜单")
//    public Envelop getParentMenu(
//            @ApiParam(name = "wechatId", value = "wechatId")
//            @PathVariable(value = "wechatId", required = true) String wechatId
//    ) {
//        try {
//            List<WxMenuDO> parentMenus = wxMenuService.findParentMenuByWechatCode(wechatId);
//            for(WxMenuDO parentMenu:parentMenus){
//                List<WxMenuDO> childMenus = wxMenuService.findChildMenus(parentMenu.getId());
//                if (childMenus.size()>0){
//                    parentMenu.setState("closed");
//                }else{
//                    parentMenu.setState("open");
//                }
//            }
//            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_find, parentMenus);
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
////    @DeleteMapping(value = WechatRequestMapping.WxMenu.api_delete)
////    @ApiOperation(value = "删除微信菜单", notes = "删除微信菜单")
////    public Envelop deleteWxMenu(
////            @ApiParam(name = "ids", value = "ids")
////            @RequestParam(value = "ids", required = true) String ids,
////            @ApiParam(name = "userId", value = "userId")
////            @RequestParam(value = "userId", required = true) String userId,
////            @ApiParam(name = "userName", value = "userName")
////            @RequestParam(value = "userName", required = true) String userName
////    ) {
////        try {
////            wxMenuService.deleteWxMenu(ids, userId, userName);
////            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_delete );
////        } catch (ApiException e) {
////            return Envelop.getError(e.getMessage(), e.getErrorCode());
////        }
////    }
////
////    @GetMapping(value = WechatRequestMapping.WxMenu.api_getById)
////    @ApiOperation(value = "根据code查找微信菜单", notes = "根据code查找微信菜单")
////    public Envelop findByCode(
////            @ApiParam(name = "id", value = "id")
////            @RequestParam(value = "id", required = true) String id
////    ) {
////        try {
////            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_find, wxMenuService.findById(id));
////        } catch (ApiException e) {
////            return Envelop.getError(e.getMessage(), e.getErrorCode());
////        }
////    }
////
////    @RequestMapping(value = WechatRequestMapping.WxMenu.api_getWxMenus, method = RequestMethod.GET)
////    @ApiOperation(value = "获取微信菜单列表(分页)")
////    public Envelop getWxMenus(
////            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,name,saasId,appId,appSecret,baseUrl,remark")
////            @RequestParam(value = "fields", required = false) String fields,
////            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
////            @RequestParam(value = "filters", required = false) String filters,
////            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
////            @RequestParam(value = "sorts", required = false) String sorts,
////            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
////            @RequestParam(value = "size", required = false) int size,
////            @ApiParam(name = "page", value = "页码", defaultValue = "1")
////            @RequestParam(value = "page", required = false) int page,
////            HttpServletRequest request,
////            HttpServletResponse response) throws Exception {
////        if(StringUtils.isBlank(sorts)){
////            sorts = "-updateTime";
////        }
////
////        //得到微信列表数据
////        List<WxWechatDO> wechats = wechatService.search(fields, filters, sorts, page, size);
////        for(WxWechatDO wechat:wechats){
////            List<WxMenuDO> parentMenus = wxMenuService.findParentMenuByWechatCode(wechat.getId());
////            if (parentMenus.size()>0){
////                wechat.setState("closed");
////            }else{
////                wechat.setState("open");
////            }
////        }
////        //获取总数
////        long count=wechatService.getCount(filters);
////        //封装头信息
////        pagedResponse(request, response, count, page, size);
////        //封装返回格式
////        List<WxWechatVO> mwechats = convertToModels(wechats, new ArrayList<>(wechats.size()), WxWechatVO.class, fields);
////        return Envelop.getSuccessListWithPage(WechatRequestMapping.WxMenu.message_success_find_functions,mwechats, page, size,count);
////    }
////
////
////    @GetMapping(value = WechatRequestMapping.WxMenu.api_getWxMenuNoPage)
////    @ApiOperation(value = "获取微信菜单列表,不分页")
////    public Envelop getWxMenuNoPage(
////            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,name,saasId,appId,appSecret,baseUrl,remark")
////            @RequestParam(value = "fields", required = false) String fields,
////            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
////            @RequestParam(value = "filters", required = false) String filters,
////            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+name,+createTime")
////            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
////        if(filters!=null){
////            filters = "supMenucode=0;"+filters;
////        }else{
////            filters = "supMenucode=0;";
////        }
////        //得到list数据
////        List<WxMenuDO> list = wxMenuService.search(fields,filters,sorts);
////        for(WxMenuDO wxMenu:list){
////            List<WxMenuDO> childMenus = wxMenuService.findChildMenus(wxMenu.getId());
////            wxMenu.setChildren(childMenus);
////        }
////        //封装返回格式
////        List<WxMenuVO> WxMenuVOs = convertToModels(list, new ArrayList<>(list.size()), WxMenuVO.class, fields);
////        Map<String, String> map = wechatService.getAllWechatConfig();
////        for(WxMenuVO menu:WxMenuVOs){
////            menu.setWechatName(map.get(menu.getWechatCode()));
////        }
////        return Envelop.getSuccessList(WechatRequestMapping.WxMenu.message_success_find_functions,WxMenuVOs);
////    }
////
////    /**
////     * 创建微信公众号菜单
////     *
////     * @return
////     */
////    @ApiOperation(value = "创建微信公众号菜单", notes = "创建微信公众号菜单")
////    @RequestMapping(value = WechatRequestMapping.WxMenu.api_createMenu ,method = RequestMethod.GET)
////    public Envelop createWechatMenu(
////            @ApiParam(name = "wechatId", value = "", defaultValue = "")
////            @RequestParam(value = "wechatId", required = true)String wechatId){
////        try{
////            JSONObject result = wxMenuService.createWechatMenu(wechatId);
////            String errcode = result.get("errcode").toString();
////            WechatResponse wechatResponse = new WechatResponse(Integer.valueOf(errcode));
////            String msg = wechatResponse.getMsg();
////            return Envelop.getSuccess("成功",msg);
////        }catch (Exception e){
////            return Envelop.getSuccess("创建失败",e );
////        }
////    }
////
////    /**
////     * 根据微信code查找父菜单
////     * @param wechatId
////     * @return
////     */
////    @GetMapping(value = WechatRequestMapping.WxMenu.api_getParentMenu)
////    @ApiOperation(value = "根据微信code查找父菜单", notes = "根据微信code查找父菜单")
////    public Envelop getParentMenu(
////            @ApiParam(name = "wechatId", value = "wechatId")
////            @PathVariable(value = "wechatId", required = true) String wechatId
////    ) {
////        try {
////            List<WxMenuDO> parentMenus = wxMenuService.findParentMenuByWechatCode(wechatId);
////            for(WxMenuDO parentMenu:parentMenus){
////                List<WxMenuDO> childMenus = wxMenuService.findChildMenus(parentMenu.getId());
////                if (childMenus.size()>0){
////                    parentMenu.setState("closed");
////                }else{
////                    parentMenu.setState("open");
////                }
////            }
////            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_find, parentMenus);
////        } catch (ApiException e) {
////            return Envelop.getError(e.getMessage(), e.getErrorCode());
////        }
////    }
////
////
////    /**
////     * 根据父级菜单code查找子菜单
////     * @param parentCode
////     * @return
////     */
////    @GetMapping(value = WechatRequestMapping.WxMenu.api_getChildMenus)
////    @ApiOperation(value = "根据父级菜单code查找子菜单", notes = "根据父级菜单code查找子菜单")
////    public Envelop getChildMenus(
////            @ApiParam(name = "parentCode", value = "parentCode")
////            @PathVariable(value = "parentCode", required = true) String parentCode
////    ) {
////        try {
////            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_find, wxMenuService.findChildMenus(parentCode));
////        } catch (ApiException e) {
////            return Envelop.getError(e.getMessage(), e.getErrorCode());
////        }
////    }
//
//    /**
//     * 根据父级菜单code查找子菜单
//     * @param parentCode
//     * @return
//     */
//    @GetMapping(value = WechatRequestMapping.WxMenu.api_getChildMenus)
//    @ApiOperation(value = "根据父级菜单code查找子菜单", notes = "根据父级菜单code查找子菜单")
//    public Envelop getChildMenus(
//            @ApiParam(name = "parentCode", value = "parentCode")
//            @PathVariable(value = "parentCode", required = true) String parentCode
//    ) {
//        try {
//            return Envelop.getSuccess(WechatRequestMapping.WxMenu.message_success_find, wxMenuService.findChildMenus(parentCode));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
}
//}

+ 171 - 171
svr/svr-base/src/main/java/com/yihu/jw/business/wx/controller/WxTemplateController.java

@ -1,178 +1,178 @@
package com.yihu.jw.business.wx.controller;
import com.yihu.jw.business.wx.service.WxTemplateService;
import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
import com.yihu.jw.rm.base.WechatRequestMapping;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by Administrator on 2017/5/19 0019.
 */
@RestController
@RequestMapping(WechatRequestMapping.api_common)
@Api(value = "微信模版相关操作", description = "微信模版相关操作")
public class WxTemplateController extends EnvelopRestEndpoint {
    @Autowired
    private WxTemplateService wxTemplateService;
    @PostMapping(value = WechatRequestMapping.WxTemplate.api_test_template, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiOperation(value = "测试发送微信模板", notes = "测试发送微信模板")
    public String sendWeTempMesTest(String wechatId,String openid)throws Exception{
        return wxTemplateService.sendWeTempMesTest(wechatId,openid);
    }
//    @PostMapping(value = WechatRequestMapping.WxTemplate.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "创建微信模版", notes = "创建微信模版")
//    public Envelop createWxTemplate(
//            @ApiParam(name = "json_data", value = "微信模版json字符串")
//            @RequestBody String jsonData) {
//        try {
//            WxTemplateDO WxTemplate = toEntity(jsonData, WxTemplateDO.class);
//            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_create, wxTemplateService.createWxTemplate(WxTemplate));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//package com.yihu.jw.business.wx.controller;
//
//    @PutMapping(value = WechatRequestMapping.WxTemplate.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "修改微信模版", notes = "修改微信模版")
//    public Envelop updateWxTemplate(
//            @ApiParam(name = "json_data", value = "", defaultValue = "")
//            @RequestBody String jsonData) {
//        try {
//            WxTemplateDO WxTemplate = toEntity(jsonData, WxTemplateDO.class);
//            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_update, wxTemplateService.updateWxTemplate(WxTemplate));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//import com.yihu.jw.business.wx.service.WxTemplateService;
//import com.yihu.jw.restmodel.web.endpoint.EnvelopRestEndpoint;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//import io.swagger.annotations.Api;
//import io.swagger.annotations.ApiOperation;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.MediaType;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//
//    @DeleteMapping(value = WechatRequestMapping.WxTemplate.api_delete)
//    @ApiOperation(value = "删除微信模版", notes = "删除微信模版")
//    public Envelop deleteWxTemplate(
//            @ApiParam(name = "codes", value = "codes")
//            @RequestParam(value = "codes", required = true) String codes,
//            @ApiParam(name = "userCode", value = "userCode")
//            @RequestParam(value = "userCode", required = true) String userCode,
//            @ApiParam(name = "userName", value = "userName")
//            @RequestParam(value = "userName", required = true) String userName
//    ) {
//        try {
//            wxTemplateService.deleteWxTemplate(codes, userCode, userName);
//            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_delete );
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
//
//    @GetMapping(value = WechatRequestMapping.WxTemplate.api_getById)
//    @ApiOperation(value = "根据code查找微信模版", notes = "根据code查找微信模版")
//    public Envelop findById(
//            @ApiParam(name = "id", value = "id")
//            @RequestParam(value = "id", required = true) String id
//    ) {
//        try {
//            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_find, wxTemplateService.findById(id));
//        } catch (ApiException e) {
//            return Envelop.getError(e.getMessage(), e.getErrorCode());
//        }
//    }
///**
// * Created by Administrator on 2017/5/19 0019.
// */
//@RestController
//@RequestMapping(WechatRequestMapping.api_common)
//@Api(value = "微信模版相关操作", description = "微信模版相关操作")
//public class WxTemplateController extends EnvelopRestEndpoint {
//
//    @RequestMapping(value = WechatRequestMapping.WxTemplate.api_getWxTemplates, method = RequestMethod.GET)
//    @ApiOperation(value = "获取微信模版列表(分页)")
//    public Envelop getWechats(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,title,wechatCode,templateId,content,remark,status")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+title,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts,
//            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
//            @RequestParam(value = "size", required = false) int size,
//            @ApiParam(name = "page", value = "页码", defaultValue = "1")
//            @RequestParam(value = "page", required = false) int page,
//            HttpServletRequest request,
//            HttpServletResponse response) throws Exception {
//        if(StringUtils.isBlank(sorts)){
//            sorts = "-updateTime";
//        }
//
//        //得到微信列表数据
//        List<WxWechatDO> wechats = wechatService.search(fields, filters, sorts, page, size);
//        for(WxWechatDO wechat:wechats){
//            List<WxTemplateDO> wxTemplates = wxTemplateService.findByWxId(wechat.getId());
//            if (wxTemplates.size()>0){
//                wechat.setState("closed");
//            }else{
//                wechat.setState("open");
//            }
//        }
//        //获取总数
//        long count=wechatService.getCount(filters);
//        //封装头信息
//        pagedResponse(request, response, count, page, size);
//        //封装返回格式
//        List<WxWechatVO> mwechats = convertToModels(wechats, new ArrayList<>(wechats.size()), WxWechatVO.class, fields);
//        return Envelop.getSuccessListWithPage(WechatRequestMapping.WxMenu.message_success_find_functions,mwechats, page, size,count);
//    @Autowired
//    private WxTemplateService wxTemplateService;
//
//    @PostMapping(value = WechatRequestMapping.WxTemplate.api_test_template, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
//    @ApiOperation(value = "测试发送微信模板", notes = "测试发送微信模板")
//    public String sendWeTempMesTest(String wechatId,String openid)throws Exception{
//        return wxTemplateService.sendWeTempMesTest(wechatId,openid);
//    }
//
//
//    @GetMapping(value = WechatRequestMapping.WxTemplate.api_getWxTemplatesNoPage)
//    @ApiOperation(value = "获取微信模版列表(不分页)")
//    public Envelop getList(
//            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,title,wechatCode,templateId,content,remark,status")
//            @RequestParam(value = "fields", required = false) String fields,
//            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
//            @RequestParam(value = "filters", required = false) String filters,
//            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+title,+createTime")
//            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
//        //得到list数据
//        List<WxTemplateDO> list = wxTemplateService.search(fields,filters,sorts);
//        //封装返回格式
//        List<WxTemplateVO> mWxTemplateVOs = convertToModels(list, new ArrayList<>(list.size()), WxTemplateVO.class, fields);
//        return Envelop.getSuccessList(WechatRequestMapping.WxTemplate.message_success_find_functions,mWxTemplateVOs);
//    }
//
//    @GetMapping(value = WechatRequestMapping.WxTemplate.api_sendTemplateMessage)
//    @ApiOperation(value = "发送微信模板消息")
//    @ResponseBody
//    public Envelop sendTemplateMessage(
//            @ApiParam(name="openid",value="微信用户的openid")
//            @RequestParam String openid,
//            @ApiParam(name="templateCode",value = "模板code")
//            @RequestParam String templateCode,
//            @ApiParam(name="url",value="模板跳转链接")
//            @RequestParam(required = false) String url,
//            @ApiParam(name="appid",value="所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系)")
//            @RequestParam(required = false) String appid,
//            @ApiParam(name="pagepath",value="所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar)")
//            @RequestParam(required = false) String pagepath,
//            @ApiParam(name="data",value="json字符串")
//            @RequestParam String data
//    ){
//        try {
//            Miniprogram miniprogram = null;
//            if(StringUtils.isNotBlank(appid)&&StringUtils.isNotBlank(pagepath)){
//                miniprogram = new Miniprogram();
//                miniprogram.setAppid(appid);
//                miniprogram.setPagepath(pagepath);
//            }
//            JSONObject jsonObject = wxTemplateService.sendTemplateMessage(openid, templateCode, url, data, miniprogram);
//            String errcode = jsonObject.get("errcode").toString();
//            WechatResponse wechatResponse = new WechatResponse(Integer.valueOf(errcode));
//            String msg = wechatResponse.getMsg();
//            return Envelop.getSuccess("成功",msg);
//        }catch (Exception exception) {
//            return Envelop.getSuccess("error", exception);
//        }
//    }
}
////    @PostMapping(value = WechatRequestMapping.WxTemplate.api_create, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
////    @ApiOperation(value = "创建微信模版", notes = "创建微信模版")
////    public Envelop createWxTemplate(
////            @ApiParam(name = "json_data", value = "微信模版json字符串")
////            @RequestBody String jsonData) {
////        try {
////            WxTemplateDO WxTemplate = toEntity(jsonData, WxTemplateDO.class);
////            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_create, wxTemplateService.createWxTemplate(WxTemplate));
////        } catch (ApiException e) {
////            return Envelop.getError(e.getMessage(), e.getErrorCode());
////        }
////    }
////
////    @PutMapping(value = WechatRequestMapping.WxTemplate.api_update, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
////    @ApiOperation(value = "修改微信模版", notes = "修改微信模版")
////    public Envelop updateWxTemplate(
////            @ApiParam(name = "json_data", value = "", defaultValue = "")
////            @RequestBody String jsonData) {
////        try {
////            WxTemplateDO WxTemplate = toEntity(jsonData, WxTemplateDO.class);
////            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_update, wxTemplateService.updateWxTemplate(WxTemplate));
////        } catch (ApiException e) {
////            return Envelop.getError(e.getMessage(), e.getErrorCode());
////        }
////    }
////
////    @DeleteMapping(value = WechatRequestMapping.WxTemplate.api_delete)
////    @ApiOperation(value = "删除微信模版", notes = "删除微信模版")
////    public Envelop deleteWxTemplate(
////            @ApiParam(name = "codes", value = "codes")
////            @RequestParam(value = "codes", required = true) String codes,
////            @ApiParam(name = "userCode", value = "userCode")
////            @RequestParam(value = "userCode", required = true) String userCode,
////            @ApiParam(name = "userName", value = "userName")
////            @RequestParam(value = "userName", required = true) String userName
////    ) {
////        try {
////            wxTemplateService.deleteWxTemplate(codes, userCode, userName);
////            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_delete );
////        } catch (ApiException e) {
////            return Envelop.getError(e.getMessage(), e.getErrorCode());
////        }
////    }
////
////    @GetMapping(value = WechatRequestMapping.WxTemplate.api_getById)
////    @ApiOperation(value = "根据code查找微信模版", notes = "根据code查找微信模版")
////    public Envelop findById(
////            @ApiParam(name = "id", value = "id")
////            @RequestParam(value = "id", required = true) String id
////    ) {
////        try {
////            return Envelop.getSuccess(WechatRequestMapping.WxTemplate.message_success_find, wxTemplateService.findById(id));
////        } catch (ApiException e) {
////            return Envelop.getError(e.getMessage(), e.getErrorCode());
////        }
////    }
////
////    @RequestMapping(value = WechatRequestMapping.WxTemplate.api_getWxTemplates, method = RequestMethod.GET)
////    @ApiOperation(value = "获取微信模版列表(分页)")
////    public Envelop getWechats(
////            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,title,wechatCode,templateId,content,remark,status")
////            @RequestParam(value = "fields", required = false) String fields,
////            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
////            @RequestParam(value = "filters", required = false) String filters,
////            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+title,+createTime")
////            @RequestParam(value = "sorts", required = false) String sorts,
////            @ApiParam(name = "size", value = "分页大小", defaultValue = "15")
////            @RequestParam(value = "size", required = false) int size,
////            @ApiParam(name = "page", value = "页码", defaultValue = "1")
////            @RequestParam(value = "page", required = false) int page,
////            HttpServletRequest request,
////            HttpServletResponse response) throws Exception {
////        if(StringUtils.isBlank(sorts)){
////            sorts = "-updateTime";
////        }
////
////        //得到微信列表数据
////        List<WxWechatDO> wechats = wechatService.search(fields, filters, sorts, page, size);
////        for(WxWechatDO wechat:wechats){
////            List<WxTemplateDO> wxTemplates = wxTemplateService.findByWxId(wechat.getId());
////            if (wxTemplates.size()>0){
////                wechat.setState("closed");
////            }else{
////                wechat.setState("open");
////            }
////        }
////        //获取总数
////        long count=wechatService.getCount(filters);
////        //封装头信息
////        pagedResponse(request, response, count, page, size);
////        //封装返回格式
////        List<WxWechatVO> mwechats = convertToModels(wechats, new ArrayList<>(wechats.size()), WxWechatVO.class, fields);
////        return Envelop.getSuccessListWithPage(WechatRequestMapping.WxMenu.message_success_find_functions,mwechats, page, size,count);
////
////    }
////
////
////    @GetMapping(value = WechatRequestMapping.WxTemplate.api_getWxTemplatesNoPage)
////    @ApiOperation(value = "获取微信模版列表(不分页)")
////    public Envelop getList(
////            @ApiParam(name = "fields", value = "返回的字段,为空返回全部字段", defaultValue = "id,code,title,wechatCode,templateId,content,remark,status")
////            @RequestParam(value = "fields", required = false) String fields,
////            @ApiParam(name = "filters", value = "过滤器,为空检索所有条件")
////            @RequestParam(value = "filters", required = false) String filters,
////            @ApiParam(name = "sorts", value = "排序,规则参见说明文档", defaultValue = "+title,+createTime")
////            @RequestParam(value = "sorts", required = false) String sorts) throws Exception {
////        //得到list数据
////        List<WxTemplateDO> list = wxTemplateService.search(fields,filters,sorts);
////        //封装返回格式
////        List<WxTemplateVO> mWxTemplateVOs = convertToModels(list, new ArrayList<>(list.size()), WxTemplateVO.class, fields);
////        return Envelop.getSuccessList(WechatRequestMapping.WxTemplate.message_success_find_functions,mWxTemplateVOs);
////    }
////
////    @GetMapping(value = WechatRequestMapping.WxTemplate.api_sendTemplateMessage)
////    @ApiOperation(value = "发送微信模板消息")
////    @ResponseBody
////    public Envelop sendTemplateMessage(
////            @ApiParam(name="openid",value="微信用户的openid")
////            @RequestParam String openid,
////            @ApiParam(name="templateCode",value = "模板code")
////            @RequestParam String templateCode,
////            @ApiParam(name="url",value="模板跳转链接")
////            @RequestParam(required = false) String url,
////            @ApiParam(name="appid",value="所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系)")
////            @RequestParam(required = false) String appid,
////            @ApiParam(name="pagepath",value="所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar)")
////            @RequestParam(required = false) String pagepath,
////            @ApiParam(name="data",value="json字符串")
////            @RequestParam String data
////    ){
////        try {
////            Miniprogram miniprogram = null;
////            if(StringUtils.isNotBlank(appid)&&StringUtils.isNotBlank(pagepath)){
////                miniprogram = new Miniprogram();
////                miniprogram.setAppid(appid);
////                miniprogram.setPagepath(pagepath);
////            }
////            JSONObject jsonObject = wxTemplateService.sendTemplateMessage(openid, templateCode, url, data, miniprogram);
////            String errcode = jsonObject.get("errcode").toString();
////            WechatResponse wechatResponse = new WechatResponse(Integer.valueOf(errcode));
////            String msg = wechatResponse.getMsg();
////            return Envelop.getSuccess("成功",msg);
////        }catch (Exception exception) {
////            return Envelop.getSuccess("error", exception);
////        }
////    }
//}

+ 29 - 29
svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WechatDao.java

@ -1,29 +1,29 @@
package com.yihu.jw.business.wx.dao;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Administrator on 2017/5/20 0020.
 */
public interface WechatDao extends PagingAndSortingRepository<WxWechatDO, String>, JpaSpecificationExecutor<WxWechatDO> {
    @Query("from WxWechatDO w where w.appId = ?1 and w.status!=-1")
    WxWechatDO findByAppId(String appId);
    @Query("from WxWechatDO w where w.appId = ?1 and w.id!= ?2 and w.status!=-1")
    WxWechatDO findByAppIdExcludeId(String appId, String id);
    @Query("from WxWechatDO w where w.id = ?1 and w.status!=-1")
    WxWechatDO findById(String id);
    @Query("from WxWechatDO w where w.status!=-1")
    List<WxWechatDO> findAll();
    @Query("from WxWechatDO w where w.appOriginId = ?1 and w.status!=-1")
    WxWechatDO findByAppOriginId(String appOriginId);
}
//package com.yihu.jw.business.wx.dao;
//
//import com.yihu.jw.entity.base.wx.WxWechatDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.jpa.repository.Query;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
//import java.util.List;
//
///**
// * Created by Administrator on 2017/5/20 0020.
// */
//public interface WechatDao extends PagingAndSortingRepository<WxWechatDO, String>, JpaSpecificationExecutor<WxWechatDO> {
//
//    @Query("from WxWechatDO w where w.appId = ?1 and w.status!=-1")
//    WxWechatDO findByAppId(String appId);
//
//    @Query("from WxWechatDO w where w.appId = ?1 and w.id!= ?2 and w.status!=-1")
//    WxWechatDO findByAppIdExcludeId(String appId, String id);
//
//    @Query("from WxWechatDO w where w.id = ?1 and w.status!=-1")
//    WxWechatDO findById(String id);
//
//    @Query("from WxWechatDO w where w.status!=-1")
//    List<WxWechatDO> findAll();
//
//    @Query("from WxWechatDO w where w.appOriginId = ?1 and w.status!=-1")
//    WxWechatDO findByAppOriginId(String appOriginId);
//}

+ 17 - 17
svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxAccessTokenDao.java

@ -1,17 +1,17 @@
package com.yihu.jw.business.wx.dao;
import com.yihu.jw.entity.base.wx.WxAccessTokenDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Administrator on 2017/5/18 0018.
 */
public interface WxAccessTokenDao extends PagingAndSortingRepository<WxAccessTokenDO, String>, JpaSpecificationExecutor<WxAccessTokenDO> {
    @Query("from WxAccessTokenDO w where w.wechatId =?1 order by w.addTimestamp desc")
    List<WxAccessTokenDO> getWxAccessTokenById(String wechatId);
}
//package com.yihu.jw.business.wx.dao;
//
//import com.yihu.jw.entity.base.wx.WxAccessTokenDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.jpa.repository.Query;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
//import java.util.List;
//
///**
// * Created by Administrator on 2017/5/18 0018.
// */
//public interface WxAccessTokenDao extends PagingAndSortingRepository<WxAccessTokenDO, String>, JpaSpecificationExecutor<WxAccessTokenDO> {
//
//    @Query("from WxAccessTokenDO w where w.wechatId =?1 order by w.addTimestamp desc")
//    List<WxAccessTokenDO> getWxAccessTokenById(String wechatId);
//}

+ 15 - 15
svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxGraphicSceneGroupDao.java

@ -1,15 +1,15 @@
package com.yihu.jw.business.wx.dao;
import com.yihu.jw.entity.base.wx.WxGraphicSceneGroupDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Trick on 2018/8/16.
 */
public interface WxGraphicSceneGroupDao extends PagingAndSortingRepository<WxGraphicSceneGroupDO, String>, JpaSpecificationExecutor<WxGraphicSceneGroupDO> {
    List<WxGraphicSceneGroupDO> findByWechatIdAndScene(String wechatId,String scene);
}
//package com.yihu.jw.business.wx.dao;
//
//import com.yihu.jw.entity.base.wx.WxGraphicSceneGroupDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
//import java.util.List;
//
///**
// * Created by Trick on 2018/8/16.
// */
//public interface WxGraphicSceneGroupDao extends PagingAndSortingRepository<WxGraphicSceneGroupDO, String>, JpaSpecificationExecutor<WxGraphicSceneGroupDO> {
//
//    List<WxGraphicSceneGroupDO> findByWechatIdAndScene(String wechatId,String scene);
//}

+ 20 - 20
svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxMenuDao.java

@ -1,20 +1,20 @@
package com.yihu.jw.business.wx.dao;
import com.yihu.jw.entity.base.wx.WxMenuDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Administrator on 2017/5/19 0019.
 */
public interface WxMenuDao  extends PagingAndSortingRepository<WxMenuDO, String>, JpaSpecificationExecutor<WxMenuDO> {
    @Query("FROM WxMenuDO w WHERE w.wechatId =?1 AND w.status ='1' AND w.supMenuid IS NULL ORDER BY w.sort ASC")
    List<WxMenuDO> findParentRootByWechatId(String wechatId);
    @Query("FROM WxMenuDO w WHERE w.wechatId =?1 AND w.status ='1' AND w.supMenuid IS NOT NULL ORDER BY w.sort ASC")
    List<WxMenuDO> findChilrenByWechatId(String wechatId);
}
//package com.yihu.jw.business.wx.dao;
//
//import com.yihu.jw.entity.base.wx.WxMenuDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.jpa.repository.Query;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
//import java.util.List;
//
///**
// * Created by Administrator on 2017/5/19 0019.
// */
//public interface WxMenuDao  extends PagingAndSortingRepository<WxMenuDO, String>, JpaSpecificationExecutor<WxMenuDO> {
//
//    @Query("FROM WxMenuDO w WHERE w.wechatId =?1 AND w.status ='1' AND w.supMenuid IS NULL ORDER BY w.sort ASC")
//    List<WxMenuDO> findParentRootByWechatId(String wechatId);
//
//    @Query("FROM WxMenuDO w WHERE w.wechatId =?1 AND w.status ='1' AND w.supMenuid IS NOT NULL ORDER BY w.sort ASC")
//    List<WxMenuDO> findChilrenByWechatId(String wechatId);
//}

+ 13 - 13
svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxMenuJsonDao.java

@ -1,13 +1,13 @@
package com.yihu.jw.business.wx.dao;
import com.yihu.jw.entity.base.wx.WxMenuJsonDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Trick on 2018/8/13.
 */
public interface WxMenuJsonDao extends PagingAndSortingRepository<WxMenuJsonDO, String>, JpaSpecificationExecutor<WxMenuJsonDO> {
    WxMenuJsonDO findByWechatIdAndStatus(String wechatId,Integer status);
}
//package com.yihu.jw.business.wx.dao;
//
//import com.yihu.jw.entity.base.wx.WxMenuJsonDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
///**
// * Created by Trick on 2018/8/13.
// */
//public interface WxMenuJsonDao extends PagingAndSortingRepository<WxMenuJsonDO, String>, JpaSpecificationExecutor<WxMenuJsonDO> {
//
//    WxMenuJsonDO findByWechatIdAndStatus(String wechatId,Integer status);
//}

+ 18 - 18
svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxReplySceneDao.java

@ -1,18 +1,18 @@
package com.yihu.jw.business.wx.dao;
import com.yihu.jw.entity.base.wx.WxReplySceneDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
/**
 * Created by Trick on 2018/8/16.
 */
public interface WxReplySceneDao extends PagingAndSortingRepository<WxReplySceneDO, String>, JpaSpecificationExecutor<WxReplySceneDO> {
    List<WxReplySceneDO> findByAppOriginIdAndMsgTypeAndStatus(String appOriginId,String msgType,Integer status);
    List<WxReplySceneDO> findByAppOriginIdAndMsgTypeAndEventAndStatus(String appOriginId,String msgType,String event,Integer status);
}
//package com.yihu.jw.business.wx.dao;
//
//import com.yihu.jw.entity.base.wx.WxReplySceneDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
//import java.util.List;
//
///**
// * Created by Trick on 2018/8/16.
// */
//public interface WxReplySceneDao extends PagingAndSortingRepository<WxReplySceneDO, String>, JpaSpecificationExecutor<WxReplySceneDO> {
//
//
//    List<WxReplySceneDO> findByAppOriginIdAndMsgTypeAndStatus(String appOriginId,String msgType,Integer status);
//
//    List<WxReplySceneDO> findByAppOriginIdAndMsgTypeAndEventAndStatus(String appOriginId,String msgType,String event,Integer status);
//}

+ 15 - 15
svr/svr-base/src/main/java/com/yihu/jw/business/wx/dao/WxTemplateConfigDao.java

@ -1,15 +1,15 @@
package com.yihu.jw.business.wx.dao;
import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
 * Created by Trick on 2018/8/21.
 */
public interface WxTemplateConfigDao extends PagingAndSortingRepository<WxTemplateConfigDO, String>, JpaSpecificationExecutor<WxTemplateConfigDO> {
    WxTemplateConfigDO findByWechatIdAndTemplateNameAndScene(String wechatId,String templateName,String scene);
}
//package com.yihu.jw.business.wx.dao;
//
//
//import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
//import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
//import org.springframework.data.repository.PagingAndSortingRepository;
//
///**
// * Created by Trick on 2018/8/21.
// */
//public interface WxTemplateConfigDao extends PagingAndSortingRepository<WxTemplateConfigDO, String>, JpaSpecificationExecutor<WxTemplateConfigDO> {
//
//    WxTemplateConfigDO findByWechatIdAndTemplateNameAndScene(String wechatId,String templateName,String scene);
//
//}

+ 353 - 353
svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WechatCoreService.java

@ -1,353 +1,353 @@
package com.yihu.jw.business.wx.service;
import com.yihu.jw.entity.base.wx.WxReplySceneDO;
import com.yihu.jw.business.wx.dao.WechatDao;
import com.yihu.jw.business.wx.dao.WxReplySceneDao;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.util.wechat.WeiXinMessageReplyUtils;
import com.yihu.jw.util.wechat.WeiXinMessageUtils;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by Trick on 2018/8/16.
 */
@Service
public class WechatCoreService {
    private Logger logger = LoggerFactory.getLogger(WechatCoreService.class);
    @Autowired
    private WechatDao wechatDao;
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    @Autowired
    private WxReplySceneDao wxReplySceneDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 微信推送消息处理
     *
     * @param request
     */
    public String messageProcess(HttpServletRequest request) {
        try {
            String returnStr = "";
            // 将解析结果存储在HashMap中
            Map<String, String> message = new HashMap();
            // 从request中取得输入流
            InputStream inputStream = request.getInputStream();
            // 读取输入流
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            // 得到xml根元素
            Element root = document.getRootElement();
            // 得到根元素的所有子节点
            List elementList = root.elements();
            // 遍历所有子节点
            for (Object e : elementList) {
                Element ele = (Element) e;
                message.put(ele.getName(), ele.getText());
            }
            logger.info("weixin  event:" + message.toString());
            // 释放资源
            inputStream.close();
            // 消息处理
            returnStr = messageProcess(message);
            return returnStr;
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }
    public String  testProcess() throws Exception{
        String returnStr = "";
        Map<String, String> message = new HashMap();
        message.put("Event","subscribe");
        message.put("CreateTime","1534495338");
        message.put("ToUserName","gh_73959f6e996b");
        message.put("FromUserName","oVH-2uJdhNrcAMt0Jhp3PMarDdaM");
        message.put("MsgType","event");
        returnStr = messageProcess(message);
        return returnStr;
    }
    /**
     * 对接收到的消息进行处理
     *
     * @param message
     * @return
     */
    private String messageProcess(Map<String, String> message) throws Exception {
        String msgType = message.get("MsgType");
        String result = "";
        switch (msgType) {
            case WeiXinMessageUtils.REQ_MESSAGE_TYPE_EVENT:  // 事件消息
                logger.info("MsgType:event");
                result = eventProcess(message);
                break;
            case WeiXinMessageUtils.RESP_MESSAGE_TYPE_TEXT:  // 回复文本消息
                //回复文本消息 处理
                logger.info("MsgType:text");
                result = textProcess(message);
                break;
            default:
                break;
        }
        return result;
    }
    /**
     * 事件细分处理:
     * 1.扫描二维码事件
     * 2.订阅事件
     * 3.取消订阅事件
     * 4.菜单点击
     * @param message
     * @return
     */
    public String eventProcess(Map<String, String> message) throws Exception{
        String result = "";
        String event = message.get("Event");
        switch (event) {
            case WeiXinMessageUtils.EVENT_TYPE_SCAN: // 扫描二维码事件
                result = scanEventProcess(message);
                break;
            case WeiXinMessageUtils.EVENT_TYPE_SUBSCRIBE: // 订阅事件
                if (message.containsKey("EventKey") && StringUtils.isNotEmpty(message.get("EventKey")) && message.containsKey("Ticket")
                        && StringUtils.isNotEmpty(message.get("Ticket"))) {
                    result = scanEventProcess(message);
                } else {
                    result = subscribeEventProcess(message);
                }
                break;
            case WeiXinMessageUtils.EVENT_TYPE_UNSUBSCRIBE: // 取消订阅事件
                result = unsubscribeEventProcess(message);
                break;
            case WeiXinMessageUtils.EVENT_TYPE_CLICK: //菜单点击
                result = this.clickProcess(message);
            default:
                break;
        }
        return result;
    }
    /**
     * 扫描二维码事件
     * 1. 用户未关注时,进行关注后的事件推送
     * <xml><ToUserName>< ![CDATA[toUser] ]></ToUserName><FromUserName>< ![CDATA[FromUser] ]></FromUserName><CreateTime>123456789</CreateTime><MsgType>< ![CDATA[event] ]></MsgType><Event>< ![CDATA[subscribe] ]></Event><EventKey>< ![CDATA[qrscene_123123] ]></EventKey><Ticket>< ![CDATA[TICKET] ]></Ticket></xml>
     * 2. 用户已关注时的事件推送
     * <xml> <ToUserName>< ![CDATA[toUser] ]></ToUserName> <FromUserName>< ![CDATA[FromUser] ]></FromUserName> <CreateTime>123456789</CreateTime> <MsgType>< ![CDATA[event] ]></MsgType> <Event>< ![CDATA[SCAN] ]></Event> <EventKey>< ![CDATA[SCENE_VALUE] ]></EventKey> <Ticket>< ![CDATA[TICKET] ]></Ticket> </xml>
     * @param message
     * @return
     */
    public String scanEventProcess(Map<String, String> message) throws Exception{
        //获取原始id
        String toUserName = message.get("ToUserName");
        //如果为已经关注,EventKey值为带参二维码值,如果是未关注 qrscene_为前缀,后面为二维码的参数值
        String eventKey = message.get("EventKey");
        //查询需要对应匹配的带参二维码事件值
        List<WxReplySceneDO> scenes = wxReplySceneDao.findByAppOriginIdAndMsgTypeAndEventAndStatus(toUserName,WeiXinMessageUtils.REQ_MESSAGE_TYPE_EVENT,WeiXinMessageUtils.EVENT_TYPE_SCAN,1);
        if(scenes!=null&&scenes.size()>0){
            for(WxReplySceneDO scene:scenes){
                //判断带参二维码中前缀是否包该场景值
                if(StringUtils.isNotBlank(scene.getScene())&&eventKey.indexOf(scene.getScene())!=-1){
                    return getGraphicXMl(scene.getScene(),scene.getWechatId(),message);
                }
            }
        }
        return "";
    }
    /**
     * 搜索关注事件
     * @param message
     * @return
     */
    public String subscribeEventProcess(Map<String, String> message) throws Exception{
        //获取原始id
        String toUserName = message.get("ToUserName");
        List<WxReplySceneDO> scenes = wxReplySceneDao.findByAppOriginIdAndMsgTypeAndEventAndStatus(toUserName,WeiXinMessageUtils.REQ_MESSAGE_TYPE_EVENT,WeiXinMessageUtils.EVENT_TYPE_SUBSCRIBE,1);
        if(scenes!=null&&scenes.size()>0){
            WxReplySceneDO scene = scenes.get(0);
            if(StringUtils.isNotBlank(scene.getScene())){
                return getGraphicXMl(scene.getScene(),scene.getWechatId(),message);
            }
        }
        return "";
    }
    /**
     * 取消关注事件,根据需求开发
     * @param message
     * @return
     */
    public String unsubscribeEventProcess(Map<String, String> message){
        return "";
    }
    /**
     * 点击事件,根据需求开发
     * @param message
     * @return
     */
    public String clickProcess(Map<String, String> message){
        return "";
    }
    /**
     * 文本消息动态生成图文消息
     * @param message
     * @return
     * @throws Exception
     */
    public String  textProcess(Map<String, String> message) throws Exception{
        String toUserName = message.get("ToUserName");
        String content = message.get("Content");
        List<WxReplySceneDO> scenes = wxReplySceneDao.findByAppOriginIdAndMsgTypeAndStatus(toUserName,WeiXinMessageUtils.RESP_MESSAGE_TYPE_TEXT,1);
        if(scenes!=null&&scenes.size()>0){
            for(WxReplySceneDO scene:scenes){
                if(StringUtils.isNotBlank(scene.getContent())
                        &&content.equals(scene.getContent())
                        &&StringUtils.isNotBlank(scene.getScene())){
                    //根据场景值,动态生成图文消息回复文斌
                    return getGraphicXMl(scene.getScene(),scene.getWechatId(),message);
                }
            }
        }
        return null;
    }
    /**
     * 构造图文消息XML
     * @param secene
     * @param wxId
     * @param message
     * @return
     * @throws Exception
     */
    public String getGraphicXMl(String secene,String wxId,Map<String, String> message)throws Exception{
        List<Map<String,Object>> group = getGraphicGroupByScene(secene,wxId);
        String result = "";
        String eventKey = message.get("EventKey");
        if(group!=null&&group.size()>0){
            List<Map<String, String>> articles = new ArrayList<>();
            for(Map<String,Object> graphic : group){
                // 图文信息
                Map<String, String> article = new HashMap<>();
                String url = (String)graphic.get("url");
                String baseUrl = (String)graphic.get("baseUrl");
                String appId = (String)graphic.get("appId");
                String title = (String)graphic.get("title");
                String description = (String)graphic.get("description");
                String picUrl = (String)graphic.get("picUrl");
                if(url.indexOf("{server}")!=-1){
                    url = url.replace("{server}",baseUrl);
                }
                if(url.indexOf("{appId}")!=-1){
                    url = url.replace("{appId}",appId);
                }
                //传递带参二维码给前端页面
                if(url.indexOf("{EventKey}")!=-1){
                    if(eventKey.indexOf("qrscene_")!=-1){
                        eventKey = eventKey.replace("qrscene_","");
                    }
                    url = url.replace("{EventKey}",eventKey);
                }
                article.put("Url", url);
                article.put("Title", title);
                article.put("Description", description);
                article.put("PicUrl", picUrl);
                articles.add(article);
            }
            result = WeiXinMessageReplyUtils.replyNewsMessage(message.get("FromUserName"), message.get("ToUserName"), articles);
        }
        return result;
    }
    /**
     * 获取指定场景下所有图文消息分组
     * @param secene
     * @param wxId
     * @return
     */
    public List<Map<String,Object>> getGraphicGroupByScene(String secene,String wxId) {
        String sql = "SELECT " +
                " m.title, " +
                " m.description, " +
                " m.url, " +
                " m.pic_url AS picUrl," +
                " w.app_id AS appId," +
                " w.base_url AS baseUrl" +
                " FROM " +
                " wx_graphic_scene_group g " +
                " JOIN wx_graphic_message m ON g.graphic_id = m.id " +
                " JOIN wx_wechat w ON w.id = g.wechat_id" +
                " WHERE " +
                " m.wechat_id = '"+wxId+"' " +
                " AND g.wechat_id = '"+wxId+"' " +
                " AND g.scene = '"+secene+"' " +
                " AND m.`status` = 1 " +
                " ORDER BY g.sort ASC";
        List<Map<String,Object>> group = jdbcTemplate.queryForList(sql);
        return group;
    }
    /**
     * 判断是否是xml结构
     */
    public boolean isXML(String value) {
        try {
            DocumentHelper.parseText(value);
        } catch (DocumentException e) {
            return false;
        }
        return true;
    }
    public List<WxWechatDO> findAll(){
        return wechatDao.findAll();
    }
}
//package com.yihu.jw.business.wx.service;
//
//import com.yihu.jw.base.dao.wx.WechatDao;
//import com.yihu.jw.base.dao.wx.WxReplySceneDao;
//import com.yihu.jw.entity.base.wx.WxReplySceneDO;
//import com.yihu.jw.entity.base.wx.WxWechatDO;
//import com.yihu.jw.util.wechat.WeiXinMessageReplyUtils;
//import com.yihu.jw.util.wechat.WeiXinMessageUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.dom4j.Document;
//import org.dom4j.DocumentException;
//import org.dom4j.DocumentHelper;
//import org.dom4j.Element;
//import org.dom4j.io.SAXReader;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.jdbc.core.JdbcTemplate;
//import org.springframework.stereotype.Service;
//
//import javax.servlet.http.HttpServletRequest;
//import java.io.InputStream;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
///**
// * Created by Trick on 2018/8/16.
// */
//@Service
//public class WechatCoreService {
//
//    private Logger logger = LoggerFactory.getLogger(WechatCoreService.class);
//
//    @Autowired
//    private WechatDao wechatDao;
//
//    @Autowired
//    private WxAccessTokenService wxAccessTokenService;
//
//    @Autowired
//    private WxReplySceneDao wxReplySceneDao;
//
//    @Autowired
//    private JdbcTemplate jdbcTemplate;
//
//    /**
//     * 微信推送消息处理
//     *
//     * @param request
//     */
//    public String messageProcess(HttpServletRequest request) {
//        try {
//            String returnStr = "";
//            // 将解析结果存储在HashMap中
//            Map<String, String> message = new HashMap();
//
//            // 从request中取得输入流
//            InputStream inputStream = request.getInputStream();
//            // 读取输入流
//            SAXReader reader = new SAXReader();
//            Document document = reader.read(inputStream);
//            // 得到xml根元素
//            Element root = document.getRootElement();
//            // 得到根元素的所有子节点
//            List elementList = root.elements();
//
//            // 遍历所有子节点
//            for (Object e : elementList) {
//                Element ele = (Element) e;
//                message.put(ele.getName(), ele.getText());
//            }
//            logger.info("weixin  event:" + message.toString());
//            // 释放资源
//            inputStream.close();
//            // 消息处理
//            returnStr = messageProcess(message);
//
//            return returnStr;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "error";
//        }
//    }
//
//    public String  testProcess() throws Exception{
//        String returnStr = "";
//
//        Map<String, String> message = new HashMap();
//        message.put("Event","subscribe");
//        message.put("CreateTime","1534495338");
//        message.put("ToUserName","gh_73959f6e996b");
//        message.put("FromUserName","oVH-2uJdhNrcAMt0Jhp3PMarDdaM");
//        message.put("MsgType","event");
//
//        returnStr = messageProcess(message);
//
//        return returnStr;
//    }
//
//
//    /**
//     * 对接收到的消息进行处理
//     *
//     * @param message
//     * @return
//     */
//    private String messageProcess(Map<String, String> message) throws Exception {
//        String msgType = message.get("MsgType");
//        String result = "";
//
//        switch (msgType) {
//            case WeiXinMessageUtils.REQ_MESSAGE_TYPE_EVENT:  // 事件消息
//                logger.info("MsgType:event");
//                result = eventProcess(message);
//                break;
//            case WeiXinMessageUtils.RESP_MESSAGE_TYPE_TEXT:  // 回复文本消息
//                //回复文本消息 处理
//                logger.info("MsgType:text");
//                result = textProcess(message);
//                break;
//            default:
//                break;
//        }
//
//        return result;
//    }
//
//    /**
//     * 事件细分处理:
//     * 1.扫描二维码事件
//     * 2.订阅事件
//     * 3.取消订阅事件
//     * 4.菜单点击
//     * @param message
//     * @return
//     */
//    public String eventProcess(Map<String, String> message) throws Exception{
//        String result = "";
//        String event = message.get("Event");
//
//        switch (event) {
//            case WeiXinMessageUtils.EVENT_TYPE_SCAN: // 扫描二维码事件
//                result = scanEventProcess(message);
//                break;
//            case WeiXinMessageUtils.EVENT_TYPE_SUBSCRIBE: // 订阅事件
//                if (message.containsKey("EventKey") && StringUtils.isNotEmpty(message.get("EventKey")) && message.containsKey("Ticket")
//                        && StringUtils.isNotEmpty(message.get("Ticket"))) {
//                    result = scanEventProcess(message);
//                } else {
//                    result = subscribeEventProcess(message);
//                }
//                break;
//            case WeiXinMessageUtils.EVENT_TYPE_UNSUBSCRIBE: // 取消订阅事件
//                result = unsubscribeEventProcess(message);
//                break;
//            case WeiXinMessageUtils.EVENT_TYPE_CLICK: //菜单点击
//                result = this.clickProcess(message);
//            default:
//                break;
//        }
//
//        return result;
//    }
//
//    /**
//     * 扫描二维码事件
//     * 1. 用户未关注时,进行关注后的事件推送
//     * <xml><ToUserName>< ![CDATA[toUser] ]></ToUserName><FromUserName>< ![CDATA[FromUser] ]></FromUserName><CreateTime>123456789</CreateTime><MsgType>< ![CDATA[event] ]></MsgType><Event>< ![CDATA[subscribe] ]></Event><EventKey>< ![CDATA[qrscene_123123] ]></EventKey><Ticket>< ![CDATA[TICKET] ]></Ticket></xml>
//     * 2. 用户已关注时的事件推送
//     * <xml> <ToUserName>< ![CDATA[toUser] ]></ToUserName> <FromUserName>< ![CDATA[FromUser] ]></FromUserName> <CreateTime>123456789</CreateTime> <MsgType>< ![CDATA[event] ]></MsgType> <Event>< ![CDATA[SCAN] ]></Event> <EventKey>< ![CDATA[SCENE_VALUE] ]></EventKey> <Ticket>< ![CDATA[TICKET] ]></Ticket> </xml>
//     * @param message
//     * @return
//     */
//    public String scanEventProcess(Map<String, String> message) throws Exception{
//        //获取原始id
//        String toUserName = message.get("ToUserName");
//        //如果为已经关注,EventKey值为带参二维码值,如果是未关注 qrscene_为前缀,后面为二维码的参数值
//        String eventKey = message.get("EventKey");
//        //查询需要对应匹配的带参二维码事件值
//        List<WxReplySceneDO> scenes = wxReplySceneDao.findByAppOriginIdAndMsgTypeAndEventAndStatus(toUserName,WeiXinMessageUtils.REQ_MESSAGE_TYPE_EVENT,WeiXinMessageUtils.EVENT_TYPE_SCAN,1);
//        if(scenes!=null&&scenes.size()>0){
//            for(WxReplySceneDO scene:scenes){
//                //判断带参二维码中前缀是否包该场景值
//                if(StringUtils.isNotBlank(scene.getScene())&&eventKey.indexOf(scene.getScene())!=-1){
//                    return getGraphicXMl(scene.getScene(),scene.getWechatId(),message);
//                }
//            }
//        }
//
//        return "";
//    }
//
//    /**
//     * 搜索关注事件
//     * @param message
//     * @return
//     */
//    public String subscribeEventProcess(Map<String, String> message) throws Exception{
//        //获取原始id
//        String toUserName = message.get("ToUserName");
//        List<WxReplySceneDO> scenes = wxReplySceneDao.findByAppOriginIdAndMsgTypeAndEventAndStatus(toUserName,WeiXinMessageUtils.REQ_MESSAGE_TYPE_EVENT,WeiXinMessageUtils.EVENT_TYPE_SUBSCRIBE,1);
//        if(scenes!=null&&scenes.size()>0){
//            WxReplySceneDO scene = scenes.get(0);
//            if(StringUtils.isNotBlank(scene.getScene())){
//                return getGraphicXMl(scene.getScene(),scene.getWechatId(),message);
//            }
//        }
//        return "";
//    }
//
//    /**
//     * 取消关注事件,根据需求开发
//     * @param message
//     * @return
//     */
//    public String unsubscribeEventProcess(Map<String, String> message){
//        return "";
//    }
//
//    /**
//     * 点击事件,根据需求开发
//     * @param message
//     * @return
//     */
//    public String clickProcess(Map<String, String> message){
//        return "";
//    }
//
//
//    /**
//     * 文本消息动态生成图文消息
//     * @param message
//     * @return
//     * @throws Exception
//     */
//    public String  textProcess(Map<String, String> message) throws Exception{
//        String toUserName = message.get("ToUserName");
//        String content = message.get("Content");
//        List<WxReplySceneDO> scenes = wxReplySceneDao.findByAppOriginIdAndMsgTypeAndStatus(toUserName,WeiXinMessageUtils.RESP_MESSAGE_TYPE_TEXT,1);
//
//        if(scenes!=null&&scenes.size()>0){
//            for(WxReplySceneDO scene:scenes){
//                if(StringUtils.isNotBlank(scene.getContent())
//                        &&content.equals(scene.getContent())
//                        &&StringUtils.isNotBlank(scene.getScene())){
//                    //根据场景值,动态生成图文消息回复文斌
//                    return getGraphicXMl(scene.getScene(),scene.getWechatId(),message);
//                }
//            }
//        }
//
//        return null;
//    }
//
//    /**
//     * 构造图文消息XML
//     * @param secene
//     * @param wxId
//     * @param message
//     * @return
//     * @throws Exception
//     */
//    public String getGraphicXMl(String secene,String wxId,Map<String, String> message)throws Exception{
//        List<Map<String,Object>> group = getGraphicGroupByScene(secene,wxId);
//        String result = "";
//        String eventKey = message.get("EventKey");
//        if(group!=null&&group.size()>0){
//            List<Map<String, String>> articles = new ArrayList<>();
//
//            for(Map<String,Object> graphic : group){
//                // 图文信息
//                Map<String, String> article = new HashMap<>();
//                String url = (String)graphic.get("url");
//                String baseUrl = (String)graphic.get("baseUrl");
//                String appId = (String)graphic.get("appId");
//                String title = (String)graphic.get("title");
//                String description = (String)graphic.get("description");
//                String picUrl = (String)graphic.get("picUrl");
//
//                if(url.indexOf("{server}")!=-1){
//                    url = url.replace("{server}",baseUrl);
//                }
//                if(url.indexOf("{appId}")!=-1){
//                    url = url.replace("{appId}",appId);
//                }
//                //传递带参二维码给前端页面
//                if(url.indexOf("{EventKey}")!=-1){
//                    if(eventKey.indexOf("qrscene_")!=-1){
//                        eventKey = eventKey.replace("qrscene_","");
//                    }
//                    url = url.replace("{EventKey}",eventKey);
//                }
//
//                article.put("Url", url);
//                article.put("Title", title);
//                article.put("Description", description);
//                article.put("PicUrl", picUrl);
//
//                articles.add(article);
//            }
//            result = WeiXinMessageReplyUtils.replyNewsMessage(message.get("FromUserName"), message.get("ToUserName"), articles);
//        }
//        return result;
//    }
//
//    /**
//     * 获取指定场景下所有图文消息分组
//     * @param secene
//     * @param wxId
//     * @return
//     */
//    public List<Map<String,Object>> getGraphicGroupByScene(String secene,String wxId) {
//        String sql = "SELECT " +
//                " m.title, " +
//                " m.description, " +
//                " m.url, " +
//                " m.pic_url AS picUrl," +
//                " w.app_id AS appId," +
//                " w.base_url AS baseUrl" +
//                " FROM " +
//                " wx_graphic_scene_group g " +
//                " JOIN wx_graphic_message m ON g.graphic_id = m.id " +
//                " JOIN wx_wechat w ON w.id = g.wechat_id" +
//                " WHERE " +
//                " m.wechat_id = '"+wxId+"' " +
//                " AND g.wechat_id = '"+wxId+"' " +
//                " AND g.scene = '"+secene+"' " +
//                " AND m.`status` = 1 " +
//                " ORDER BY g.sort ASC";
//        List<Map<String,Object>> group = jdbcTemplate.queryForList(sql);
//        return group;
//    }
//
//    /**
//     * 判断是否是xml结构
//     */
//    public boolean isXML(String value) {
//        try {
//            DocumentHelper.parseText(value);
//        } catch (DocumentException e) {
//            return false;
//        }
//        return true;
//    }
//
//    public List<WxWechatDO> findAll(){
//        return wechatDao.findAll();
//    }
//
//
//}

+ 94 - 94
svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WechatFansService.java

@ -1,94 +1,94 @@
package com.yihu.jw.business.wx.service;
import com.yihu.jw.util.wechat.wxhttp.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * 微信粉丝管理
 * Created by Trick on 2018/8/22.
 */
@Service
public class WechatFansService {
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    /**
     * 创建分组
     * @param wxId
     * @param param
     * @return
     */
    public String createWxTag(String wxId,String param){
        String url = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
        return HttpUtil.sendPost(url,param);
    }
    /**
     * 查询分组
     * @param wxId
     * @return
     */
    public String findWxTag(String wxId){
        String url = "https://api.weixin.qq.com/cgi-bin/tags/get?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
        return HttpUtil.sendGet(url);
    }
    /**
     * 更新分组
     * @param wxId
     * @param param
     * @return
     */
    public String updateWxTag(String wxId,String param){
        String url = "https://api.weixin.qq.com/cgi-bin/tags/update?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
        return HttpUtil.sendPost(url,param);
    }
    /**
     * 删除分组
     * @param wxId
     * @param param
     * @return
     */
    public String deleteWxTag(String wxId,String param){
        String url = "https://api.weixin.qq.com/cgi-bin/tags/delete?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
        return HttpUtil.sendPost(url,param);
    }
    /**
     *  批量为用户打标签
     * @param wxId
     * @param param
     * @return
     */
    public String createBatchtagging(String wxId,String param){
        String url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
        return HttpUtil.sendPost(url,param);
    }
    /**
     * 批量为用户取消标签
     * @param wxId
     * @param param
     * @return
     */
    public String cancelBatchuntagging(String wxId,String param){
        String url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
        return HttpUtil.sendPost(url,param);
    }
    /**
     * 获取用户身上的标签列表
     * @param wxId
     * @param param
     * @return
     */
    public String getidlist(String wxId,String param){
        String url = "https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
        return HttpUtil.sendPost(url,param);
    }
}
//package com.yihu.jw.business.wx.service;
//
//import com.yihu.jw.util.wechat.wxhttp.HttpUtil;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
///**
// * 微信粉丝管理
// * Created by Trick on 2018/8/22.
// */
//@Service
//public class WechatFansService {
//
//    @Autowired
//    private WxAccessTokenService wxAccessTokenService;
//
//    /**
//     * 创建分组
//     * @param wxId
//     * @param param
//     * @return
//     */
//    public String createWxTag(String wxId,String param){
//        String url = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
//        return HttpUtil.sendPost(url,param);
//    }
//
//    /**
//     * 查询分组
//     * @param wxId
//     * @return
//     */
//    public String findWxTag(String wxId){
//        String url = "https://api.weixin.qq.com/cgi-bin/tags/get?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
//        return HttpUtil.sendGet(url);
//    }
//
//    /**
//     * 更新分组
//     * @param wxId
//     * @param param
//     * @return
//     */
//    public String updateWxTag(String wxId,String param){
//        String url = "https://api.weixin.qq.com/cgi-bin/tags/update?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
//        return HttpUtil.sendPost(url,param);
//    }
//
//    /**
//     * 删除分组
//     * @param wxId
//     * @param param
//     * @return
//     */
//    public String deleteWxTag(String wxId,String param){
//        String url = "https://api.weixin.qq.com/cgi-bin/tags/delete?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
//        return HttpUtil.sendPost(url,param);
//    }
//
//    /**
//     *  批量为用户打标签
//     * @param wxId
//     * @param param
//     * @return
//     */
//    public String createBatchtagging(String wxId,String param){
//        String url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
//        return HttpUtil.sendPost(url,param);
//    }
//
//    /**
//     * 批量为用户取消标签
//     * @param wxId
//     * @param param
//     * @return
//     */
//    public String cancelBatchuntagging(String wxId,String param){
//        String url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
//        return HttpUtil.sendPost(url,param);
//    }
//
//    /**
//     * 获取用户身上的标签列表
//     * @param wxId
//     * @param param
//     * @return
//     */
//    public String getidlist(String wxId,String param){
//        String url = "https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token="+wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
//        return HttpUtil.sendPost(url,param);
//    }
//
//
//}

+ 13 - 13
svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WechatService.java

@ -1,13 +1,13 @@
package com.yihu.jw.business.wx.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * Created by Administrator on 2017/5/20 0020.
 */
@Service
@Transactional
public class WechatService {
}
//package com.yihu.jw.business.wx.service;
//
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
///**
// * Created by Administrator on 2017/5/20 0020.
// */
//@Service
//@Transactional
//public class WechatService {
//
//}

+ 157 - 157
svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WxAccessTokenService.java

@ -1,157 +1,157 @@
package com.yihu.jw.business.wx.service;
import com.yihu.jw.business.wx.dao.WechatDao;
import com.yihu.jw.business.wx.dao.WxAccessTokenDao;
import com.yihu.jw.entity.base.wx.WxAccessTokenDO;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.exception.ApiException;
import com.yihu.jw.exception.code.ExceptionCode;
import com.yihu.jw.rm.base.WechatRequestMapping;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.utils.network.HttpUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.*;
/**
 * Created by Administrator on 2017/5/18 0018.
 */
@Service
public class WxAccessTokenService extends BaseJpaService<WxAccessTokenDO, WxAccessTokenDao> {
    private Logger logger= LoggerFactory.getLogger(WxAccessTokenService.class);
    @Autowired
    private WxAccessTokenDao wxAccessTokenDao;
    @Autowired
    private WechatDao wechatDao;
    /**
     * 根据原始id查找
     * @param appOriginId
     * @return
     */
    public WxAccessTokenDO getWxAccessTokenByOriginId(String appOriginId) {
        try {
            //根据wechatCode查找出appid和appSecret
            WxWechatDO wxWechat = wechatDao.findByAppOriginId(appOriginId);
            if(wxWechat==null){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_wxWechat_is_no_exist, ExceptionCode.common_error_params_code);
            }
            List<WxAccessTokenDO> wxAccessTokens =  wxAccessTokenDao.getWxAccessTokenById(wxWechat.getId());
            if(wxAccessTokens!=null&&wxAccessTokens.size()>0){
                for (WxAccessTokenDO accessToken : wxAccessTokens) {
                    if ((System.currentTimeMillis() - accessToken.getAddTimestamp()) < (accessToken.getExpiresIn() * 500)) {
                        return accessToken;
                    } else {
                        wxAccessTokenDao.delete(accessToken);
                        break;
                    }
                }
            }
            String token_url = "https://api.weixin.qq.com/cgi-bin/token";
            String appId="";
            String appSecret="";
            appId = wxWechat.getAppId();
            appSecret = wxWechat.getAppSecret();
            if (StringUtils.isEmpty(appId)){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appId_is_null, ExceptionCode.common_error_params_code);
            }
            if (StringUtils.isEmpty(appSecret)){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appSecret_is_null, ExceptionCode.common_error_params_code);
            }
            /*String params = "grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
            String result = HttpUtil.sendGet(token_url, params);*/
            Map<String, Object> params = new HashMap<>();
            params.put("grant_type", "client_credential");
            params.put("appid", appId);
            params.put("secret", appSecret);
            String result = HttpUtils.doGet(token_url, params).getContent();
            logger.info("--------------wechat token return :"+result+"---------------");
            JSONObject json = new JSONObject(result);
            if (json.has("access_token")) {
                String token = json.get("access_token").toString();
                String expires_in = json.get("expires_in").toString();
                WxAccessTokenDO newaccessToken = new WxAccessTokenDO();
                newaccessToken.setAccessToken(token);
                newaccessToken.setExpiresIn(Long.parseLong(expires_in));
                newaccessToken.setAddTimestamp(System.currentTimeMillis());
                newaccessToken.setCzrq(new Date());
                newaccessToken.setCode(UUID.randomUUID().toString().replace("-",""));
                newaccessToken.setWechatId(wxWechat.getId());
                wxAccessTokenDao.save(newaccessToken);
                return newaccessToken;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public WxAccessTokenDO getWxAccessTokenById(String wechatId) {
        try {
            //根据wechatCode查找出appid和appSecret
            WxWechatDO wxWechat = wechatDao.findById(wechatId);
            if(wxWechat==null){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_wxWechat_is_no_exist, ExceptionCode.common_error_params_code);
            }
            List<WxAccessTokenDO> wxAccessTokens =  wxAccessTokenDao.getWxAccessTokenById(wechatId);
            if(wxAccessTokens!=null&&wxAccessTokens.size()>0){
                for (WxAccessTokenDO accessToken : wxAccessTokens) {
                    if ((System.currentTimeMillis() - accessToken.getAddTimestamp()) < (accessToken.getExpiresIn() * 500)) {
                        return accessToken;
                    } else {
                        wxAccessTokenDao.delete(accessToken);
                        break;
                    }
                }
            }
            String token_url = "https://api.weixin.qq.com/cgi-bin/token";
            String appId="";
            String appSecret="";
            appId = wxWechat.getAppId();
            appSecret = wxWechat.getAppSecret();
            if (StringUtils.isEmpty(appId)){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appId_is_null, ExceptionCode.common_error_params_code);
            }
            if (StringUtils.isEmpty(appSecret)){
                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appSecret_is_null, ExceptionCode.common_error_params_code);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("grant_type", "client_credential");
            params.put("appid", appId);
            params.put("secret", appSecret);
            String result = HttpUtils.doGet(token_url, params).getContent();
            logger.info("--------------wechat token return:"+result+"---------------");
            JSONObject json = new JSONObject(result);
            if (json.has("access_token")) {
                String token = json.get("access_token").toString();
                String expires_in = json.get("expires_in").toString();
                WxAccessTokenDO newaccessToken = new WxAccessTokenDO();
                newaccessToken.setAccessToken(token);
                newaccessToken.setExpiresIn(Long.parseLong(expires_in));
                newaccessToken.setAddTimestamp(System.currentTimeMillis());
                newaccessToken.setCzrq(new Date());
                newaccessToken.setCode(UUID.randomUUID().toString().replace("-",""));
                newaccessToken.setWechatId(wechatId);
                wxAccessTokenDao.save(newaccessToken);
                return newaccessToken;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
//package com.yihu.jw.business.wx.service;
//
//import com.yihu.jw.business.wx.dao.WechatDao;
//import com.yihu.jw.business.wx.dao.WxAccessTokenDao;
//import com.yihu.jw.entity.base.wx.WxAccessTokenDO;
//import com.yihu.jw.entity.base.wx.WxWechatDO;
//import com.yihu.jw.exception.ApiException;
//import com.yihu.jw.exception.code.ExceptionCode;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//import com.yihu.mysql.query.BaseJpaService;
//import com.yihu.utils.network.HttpUtils;
//import org.json.JSONObject;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.util.StringUtils;
//
//import java.util.*;
//
///**
// * Created by Administrator on 2017/5/18 0018.
// */
//@Service
//public class WxAccessTokenService extends BaseJpaService<WxAccessTokenDO, WxAccessTokenDao> {
//
//
//    private Logger logger= LoggerFactory.getLogger(WxAccessTokenService.class);
//
//    @Autowired
//    private WxAccessTokenDao wxAccessTokenDao;
//
//    @Autowired
//    private WechatDao wechatDao;
//
//    /**
//     * 根据原始id查找
//     * @param appOriginId
//     * @return
//     */
//    public WxAccessTokenDO getWxAccessTokenByOriginId(String appOriginId) {
//        try {
//            //根据wechatCode查找出appid和appSecret
//            WxWechatDO wxWechat = wechatDao.findByAppOriginId(appOriginId);
//            if(wxWechat==null){
//                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_wxWechat_is_no_exist, ExceptionCode.common_error_params_code);
//            }
//            List<WxAccessTokenDO> wxAccessTokens =  wxAccessTokenDao.getWxAccessTokenById(wxWechat.getId());
//            if(wxAccessTokens!=null&&wxAccessTokens.size()>0){
//                for (WxAccessTokenDO accessToken : wxAccessTokens) {
//                    if ((System.currentTimeMillis() - accessToken.getAddTimestamp()) < (accessToken.getExpiresIn() * 500)) {
//                        return accessToken;
//                    } else {
//                        wxAccessTokenDao.delete(accessToken);
//                        break;
//                    }
//                }
//            }
//            String token_url = "https://api.weixin.qq.com/cgi-bin/token";
//            String appId="";
//            String appSecret="";
//            appId = wxWechat.getAppId();
//            appSecret = wxWechat.getAppSecret();
//            if (StringUtils.isEmpty(appId)){
//                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appId_is_null, ExceptionCode.common_error_params_code);
//            }
//            if (StringUtils.isEmpty(appSecret)){
//                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appSecret_is_null, ExceptionCode.common_error_params_code);
//            }
//            /*String params = "grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
//            String result = HttpUtil.sendGet(token_url, params);*/
//            Map<String, Object> params = new HashMap<>();
//            params.put("grant_type", "client_credential");
//            params.put("appid", appId);
//            params.put("secret", appSecret);
//            String result = HttpUtils.doGet(token_url, params).getContent();
//            logger.info("--------------wechat token return :"+result+"---------------");
//            JSONObject json = new JSONObject(result);
//            if (json.has("access_token")) {
//                String token = json.get("access_token").toString();
//                String expires_in = json.get("expires_in").toString();
//                WxAccessTokenDO newaccessToken = new WxAccessTokenDO();
//                newaccessToken.setAccessToken(token);
//                newaccessToken.setExpiresIn(Long.parseLong(expires_in));
//                newaccessToken.setAddTimestamp(System.currentTimeMillis());
//                newaccessToken.setCzrq(new Date());
//                newaccessToken.setCode(UUID.randomUUID().toString().replace("-",""));
//                newaccessToken.setWechatId(wxWechat.getId());
//                wxAccessTokenDao.save(newaccessToken);
//                return newaccessToken;
//            } else {
//                return null;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//    }
//
//
//    public WxAccessTokenDO getWxAccessTokenById(String wechatId) {
//        try {
//            //根据wechatCode查找出appid和appSecret
//            WxWechatDO wxWechat = wechatDao.findById(wechatId);
//            if(wxWechat==null){
//                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_wxWechat_is_no_exist, ExceptionCode.common_error_params_code);
//            }
//            List<WxAccessTokenDO> wxAccessTokens =  wxAccessTokenDao.getWxAccessTokenById(wechatId);
//            if(wxAccessTokens!=null&&wxAccessTokens.size()>0){
//                for (WxAccessTokenDO accessToken : wxAccessTokens) {
//                    if ((System.currentTimeMillis() - accessToken.getAddTimestamp()) < (accessToken.getExpiresIn() * 500)) {
//                        return accessToken;
//                    } else {
//                        wxAccessTokenDao.delete(accessToken);
//                        break;
//                    }
//                }
//            }
//            String token_url = "https://api.weixin.qq.com/cgi-bin/token";
//            String appId="";
//            String appSecret="";
//            appId = wxWechat.getAppId();
//            appSecret = wxWechat.getAppSecret();
//            if (StringUtils.isEmpty(appId)){
//                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appId_is_null, ExceptionCode.common_error_params_code);
//            }
//            if (StringUtils.isEmpty(appSecret)){
//                throw new ApiException(WechatRequestMapping.WxConfig.message_fail_appSecret_is_null, ExceptionCode.common_error_params_code);
//            }
//            Map<String, Object> params = new HashMap<>();
//            params.put("grant_type", "client_credential");
//            params.put("appid", appId);
//            params.put("secret", appSecret);
//            String result = HttpUtils.doGet(token_url, params).getContent();
//            logger.info("--------------wechat token return:"+result+"---------------");
//            JSONObject json = new JSONObject(result);
//            if (json.has("access_token")) {
//                String token = json.get("access_token").toString();
//                String expires_in = json.get("expires_in").toString();
//                WxAccessTokenDO newaccessToken = new WxAccessTokenDO();
//                newaccessToken.setAccessToken(token);
//                newaccessToken.setExpiresIn(Long.parseLong(expires_in));
//                newaccessToken.setAddTimestamp(System.currentTimeMillis());
//                newaccessToken.setCzrq(new Date());
//                newaccessToken.setCode(UUID.randomUUID().toString().replace("-",""));
//                newaccessToken.setWechatId(wechatId);
//                wxAccessTokenDao.save(newaccessToken);
//                return newaccessToken;
//            } else {
//                return null;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//    }
//}

+ 50 - 50
svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WxMenuService.java

@ -1,50 +1,50 @@
package com.yihu.jw.business.wx.service;
import com.yihu.jw.base.util.HttpUtil;
import com.yihu.jw.entity.base.wx.WxMenuDO;
import com.yihu.jw.entity.base.wx.WxMenuJsonDO;
import com.yihu.jw.business.wx.dao.WechatDao;
import com.yihu.jw.business.wx.dao.WxMenuDao;
import com.yihu.jw.business.wx.dao.WxMenuJsonDao;
import com.yihu.jw.entity.base.wx.WxWechatDO;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.rm.base.WechatRequestMapping;
import com.yihu.mysql.query.BaseJpaService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * Created by Administrator on 2017/5/19 0019.
 */
@Service
public class WxMenuService extends BaseJpaService<WxMenuDO, WxMenuDao>{
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    @Autowired
    private WxMenuJsonDao wxMenuJsonDao;
    @Autowired
    private WechatDao wechatDao;
    public MixEnvelop createWxMenu(String wxId){
//        String url = "https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=" ;
        String url ="https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+ wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
        WxMenuJsonDO wxMenuJsonDO = wxMenuJsonDao.findByWechatIdAndStatus(wxId,1);
        String params = wxMenuJsonDO.getContent();
        WxWechatDO wechatDO =  wechatDao.findById(wxId);
        // 替换服务器地址、APPID
        params = params.replaceAll("server_url", wechatDO.getBaseUrl());
        params = params.replaceAll("appId", wechatDO.getAppId());
        String jsonStr = HttpUtil.sendPost(url, params);
        JSONObject result = new JSONObject(jsonStr);
        if (result != null && result.get("errcode").toString().equals("0") && result.getString("errmsg").equals("ok")) {
            MixEnvelop.getSuccess(WechatRequestMapping.WxMenu.message_success_update);
        }
        return MixEnvelop.getError(result.toString());
    }
}
//package com.yihu.jw.business.wx.service;
//
//import com.yihu.jw.base.util.HttpUtil;
//import com.yihu.jw.entity.base.wx.WxMenuDO;
//import com.yihu.jw.entity.base.wx.WxMenuJsonDO;
//import com.yihu.jw.business.wx.dao.WechatDao;
//import com.yihu.jw.business.wx.dao.WxMenuDao;
//import com.yihu.jw.business.wx.dao.WxMenuJsonDao;
//import com.yihu.jw.entity.base.wx.WxWechatDO;
//import com.yihu.jw.restmodel.web.MixEnvelop;
//import com.yihu.jw.rm.base.WechatRequestMapping;
//import com.yihu.mysql.query.BaseJpaService;
//import org.json.JSONObject;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
///**
// * Created by Administrator on 2017/5/19 0019.
// */
//@Service
//public class WxMenuService extends BaseJpaService<WxMenuDO, WxMenuDao>{
//
//    @Autowired
//    private WxAccessTokenService wxAccessTokenService;
//    @Autowired
//    private WxMenuJsonDao wxMenuJsonDao;
//    @Autowired
//    private WechatDao wechatDao;
//
//    public MixEnvelop createWxMenu(String wxId){
//
////        String url = "https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token=" ;
//        String url ="https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+ wxAccessTokenService.getWxAccessTokenById(wxId).getAccessToken();
//        WxMenuJsonDO wxMenuJsonDO = wxMenuJsonDao.findByWechatIdAndStatus(wxId,1);
//        String params = wxMenuJsonDO.getContent();
//        WxWechatDO wechatDO =  wechatDao.findById(wxId);
//        // 替换服务器地址、APPID
//        params = params.replaceAll("server_url", wechatDO.getBaseUrl());
//        params = params.replaceAll("appId", wechatDO.getAppId());
//
//        String jsonStr = HttpUtil.sendPost(url, params);
//        JSONObject result = new JSONObject(jsonStr);
//        if (result != null && result.get("errcode").toString().equals("0") && result.getString("errmsg").equals("ok")) {
//            MixEnvelop.getSuccess(WechatRequestMapping.WxMenu.message_success_update);
//        }
//        return MixEnvelop.getError(result.toString());
//
//    }
//
//}

+ 147 - 147
svr/svr-base/src/main/java/com/yihu/jw/business/wx/service/WxTemplateService.java

@ -1,156 +1,156 @@
package com.yihu.jw.business.wx.service;
import com.yihu.jw.business.wx.dao.WxTemplateConfigDao;
import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
import com.yihu.jw.util.wechat.WeixinMessagePushUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * Created by Administrator on 2017/5/19 0019.
 */
@Service
public class WxTemplateService {
    private Logger logger= LoggerFactory.getLogger(WxTemplateService.class);
    @Autowired
    private WxTemplateConfigDao wxTemplateConfigDao;
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    @Autowired
    private WeixinMessagePushUtils weixinMessagePushUtils;
    public String sendWeTempMesTest(String wechatId,String openid)throws Exception{
        WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndScene(wechatId,"template_survey","test");
        config.setFirst(config.getFirst().replace("key1","小明"));
        config.setKeyword2("2018-08-21");
        weixinMessagePushUtils.putWxMsg(wxAccessTokenService.getWxAccessTokenById(wechatId).getAccessToken(),openid,config);
        return "success";
    }
//    public WxTemplateDO createWxTemplate(WxTemplateDO wxTemplate) {
//        if (StringUtils.isEmpty(wxTemplate.getTemplateId())) {
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_templateid_is_null, ExceptionCode.common_error_params_code);
//        }
//        String content = wxTemplate.getContent().replace(" ","");
//        if (StringUtils.isEmpty(content)) {
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_is_null, ExceptionCode.common_error_params_code);
//        }
//        if(!content.matches("\\{\\{.+\\.DATA\\}\\}")){//content必须还有 "{{.DATA}}"
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_format_is_not_right, ExceptionCode.common_error_params_code);
//        }
//        return wxTemplateDao.save(wxTemplate);
//    }
//
//    public WxTemplateDO updateWxTemplate(WxTemplateDO wxTemplate) {
//        if (StringUtils.isEmpty(wxTemplate.getTemplateId())) {
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_templateid_is_null, ExceptionCode.common_error_params_code);
//        }
//        String content = wxTemplate.getContent().replace(" ","");
//        if (StringUtils.isEmpty(content)) {
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_is_null, ExceptionCode.common_error_params_code);
//        }
//        String id = wxTemplate.getId();
//        if (StringUtils.isEmpty(id)) {
//            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_id_is_null, ExceptionCode.common_error_params_code);
//        }
//        WxTemplateDO wxTemplate1 = findById(id);
//        if(wxTemplate1==null){
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_template_is_no_exist, ExceptionCode.common_error_params_code);
//        }
//        wxTemplate.setCreateTime(wxTemplate1.getCreateTime());
//        wxTemplate.setUpdateTime(new Date());
//        if(!content.matches("\\{\\{.+\\.DATA\\}\\}")){//content必须还有 "{{.DATA}}"
//            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_format_is_not_right, ExceptionCode.common_error_params_code);
//        }
//        return wxTemplateDao.save(wxTemplate);
//    }
//
//    public void deleteWxTemplate(String codes, String userCode, String userName) {
//        if(!StringUtils.isEmpty(codes)) {
//            String[] codeArray = codes.split(",");
//            for (String code : codeArray) {
//                WxTemplateDO wxTemplate = wxTemplateDao.findById(code);
//                if (wxTemplate == null) {
//                    throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_id_no_exist, ExceptionCode.common_error_params_code);
//                }
//                wxTemplate.setStatus(-1);
//                wxTemplate.setUpdateUser(userCode);
//                wxTemplate.setUpdateUserName(userName);
//                wxTemplateDao.save(wxTemplate);
//            }
//        }
//    }
//package com.yihu.jw.business.wx.service;
//
//import com.yihu.jw.business.wx.dao.WxTemplateConfigDao;
//import com.yihu.jw.entity.base.wx.WxTemplateConfigDO;
//import com.yihu.jw.util.wechat.WeixinMessagePushUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//    public WxTemplateDO findById(String id) {
//        WxTemplateDO wxTemplate = wxTemplateDao.findById(id);
//        return wxTemplate;
//    }
//
//    public JSONObject sendTemplateMessage(String openid, String templateId, String url, String data,Miniprogram miniprogram) {
//        try {
//            //首先根据wechatTemplate获取微信模版
//            WxTemplateDO wxTemplate = findById(templateId);
//            if(wxTemplate==null){
//                throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_template_is_no_exist, ExceptionCode.common_error_params_code);
//            }
//            String wechatCode =  wxTemplate.getWechatId();
//            String content = wxTemplate.getContent().replaceAll(" ", "");//{{result.DATA}}领奖金额:{{withdrawMoney.DATA}   }领奖  时间:{ {withdrawTime.DATA} }银行信息:{ {cardInfo.DATA} }到账时间:{{arrivedTime.DATA}}{{remark.DATA}}
//            String[] contentArray = content.split("\\{\\{");
//
//            //将result,withdrawMoney,withdrawTime,cardInfo,arrivedTime等字符串放入contentList中
//            List<String> contentList = new ArrayList<>();
//            for(int i=1;i<contentArray.length;i++){
//                contentList.add(contentArray[i].substring(0,contentArray[i].indexOf(".")));
//            }
///**
// * Created by Administrator on 2017/5/19 0019.
// */
//@Service
//public class WxTemplateService {
//
//            ObjectMapper mapper = new ObjectMapper();
//            ////将data转为对象
//            Map<String, WechatTemplateDataDO> dataMap = mapper.readValue(data, new TypeReference<LinkedHashMap<String, WechatTemplateDataDO>>() {});
//            Map<String, WechatTemplateDataDO> newDataMap = new LinkedHashMap<String, WechatTemplateDataDO>();
//            int j = 0;
//            for (Map.Entry<String, WechatTemplateDataDO> entry : dataMap.entrySet()) {//(keyword1,WechatTemplateData)
//                String key = entry.getKey();//keyword1   转为result
//                newDataMap.put(contentList.get(j),entry.getValue());
//                j++;
//            }
//    private Logger logger= LoggerFactory.getLogger(WxTemplateService.class);
//
//            //将数据封装在WechatTemplate对象中
//            WechatTemplateDO wechatTemplate = new WechatTemplateDO();
//            wechatTemplate.setTouser(openid);
//            wechatTemplate.setUrl(url);
//            wechatTemplate.setTemplate_id(wxTemplate.getTemplateId());
//            if(miniprogram!=null){
//                wechatTemplate.setMiniprogram(miniprogram);
//            }
//            wechatTemplate.setData(newDataMap);
//    @Autowired
//    private WxTemplateConfigDao wxTemplateConfigDao;
//
//            String params = mapper.writeValueAsString(wechatTemplate);
//            logger.info("----------------------模版消息json字符串:"+params+"------------------");
//    @Autowired
//    private WxAccessTokenService wxAccessTokenService;
//
//            WxAccessTokenDO wxAccessTokenByCode = wxAccessTokenService.getWxAccessTokenById(wechatCode);
//            String token = wxAccessTokenByCode.getAccessToken();
//            String token_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
//            String result = HttpUtil.sendPost(token_url, params);
//            logger.info("------------------------发送模板消息,微信返回结果:"+result+"-----------------------");
//    @Autowired
//    private WeixinMessagePushUtils weixinMessagePushUtils;
//
//            JSONObject jsonResult = new JSONObject(result);
//            return jsonResult;
//        } catch (Exception e) {
//            e.printStackTrace();
//            JSONObject jsonResult = new JSONObject();
//            return jsonResult;
//        }
//    public String sendWeTempMesTest(String wechatId,String openid)throws Exception{
//        WxTemplateConfigDO config = wxTemplateConfigDao.findByWechatIdAndTemplateNameAndScene(wechatId,"template_survey","test");
//        config.setFirst(config.getFirst().replace("key1","小明"));
//        config.setKeyword2("2018-08-21");
//        weixinMessagePushUtils.putWxMsg(wxAccessTokenService.getWxAccessTokenById(wechatId).getAccessToken(),openid,config);
//        return "success";
//    }
//
//    public List<WxTemplateDO> findByWxId(String code) {
//        return wxTemplateDao.findByWxId(code);
//    }
}
//
////    public WxTemplateDO createWxTemplate(WxTemplateDO wxTemplate) {
////        if (StringUtils.isEmpty(wxTemplate.getTemplateId())) {
////            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_templateid_is_null, ExceptionCode.common_error_params_code);
////        }
////        String content = wxTemplate.getContent().replace(" ","");
////        if (StringUtils.isEmpty(content)) {
////            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_is_null, ExceptionCode.common_error_params_code);
////        }
////        if(!content.matches("\\{\\{.+\\.DATA\\}\\}")){//content必须还有 "{{.DATA}}"
////            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_format_is_not_right, ExceptionCode.common_error_params_code);
////        }
////        return wxTemplateDao.save(wxTemplate);
////    }
////
////    public WxTemplateDO updateWxTemplate(WxTemplateDO wxTemplate) {
////        if (StringUtils.isEmpty(wxTemplate.getTemplateId())) {
////            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_templateid_is_null, ExceptionCode.common_error_params_code);
////        }
////        String content = wxTemplate.getContent().replace(" ","");
////        if (StringUtils.isEmpty(content)) {
////            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_is_null, ExceptionCode.common_error_params_code);
////        }
////        String id = wxTemplate.getId();
////        if (StringUtils.isEmpty(id)) {
////            throw new ApiException(WechatRequestMapping.WxConfig.message_fail_id_is_null, ExceptionCode.common_error_params_code);
////        }
////        WxTemplateDO wxTemplate1 = findById(id);
////        if(wxTemplate1==null){
////            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_template_is_no_exist, ExceptionCode.common_error_params_code);
////        }
////        wxTemplate.setCreateTime(wxTemplate1.getCreateTime());
////        wxTemplate.setUpdateTime(new Date());
////        if(!content.matches("\\{\\{.+\\.DATA\\}\\}")){//content必须还有 "{{.DATA}}"
////            throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_content_format_is_not_right, ExceptionCode.common_error_params_code);
////        }
////        return wxTemplateDao.save(wxTemplate);
////    }
////
////    public void deleteWxTemplate(String codes, String userCode, String userName) {
////        if(!StringUtils.isEmpty(codes)) {
////            String[] codeArray = codes.split(",");
////            for (String code : codeArray) {
////                WxTemplateDO wxTemplate = wxTemplateDao.findById(code);
////                if (wxTemplate == null) {
////                    throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_id_no_exist, ExceptionCode.common_error_params_code);
////                }
////                wxTemplate.setStatus(-1);
////                wxTemplate.setUpdateUser(userCode);
////                wxTemplate.setUpdateUserName(userName);
////                wxTemplateDao.save(wxTemplate);
////            }
////        }
////    }
////
////
////    public WxTemplateDO findById(String id) {
////        WxTemplateDO wxTemplate = wxTemplateDao.findById(id);
////        return wxTemplate;
////    }
////
////    public JSONObject sendTemplateMessage(String openid, String templateId, String url, String data,Miniprogram miniprogram) {
////        try {
////            //首先根据wechatTemplate获取微信模版
////            WxTemplateDO wxTemplate = findById(templateId);
////            if(wxTemplate==null){
////                throw new ApiException(WechatRequestMapping.WxTemplate.message_fail_template_is_no_exist, ExceptionCode.common_error_params_code);
////            }
////            String wechatCode =  wxTemplate.getWechatId();
////            String content = wxTemplate.getContent().replaceAll(" ", "");//{{result.DATA}}领奖金额:{{withdrawMoney.DATA}   }领奖  时间:{ {withdrawTime.DATA} }银行信息:{ {cardInfo.DATA} }到账时间:{{arrivedTime.DATA}}{{remark.DATA}}
////            String[] contentArray = content.split("\\{\\{");
////
////            //将result,withdrawMoney,withdrawTime,cardInfo,arrivedTime等字符串放入contentList中
////            List<String> contentList = new ArrayList<>();
////            for(int i=1;i<contentArray.length;i++){
////                contentList.add(contentArray[i].substring(0,contentArray[i].indexOf(".")));
////            }
////
////            ObjectMapper mapper = new ObjectMapper();
////            ////将data转为对象
////            Map<String, WechatTemplateDataDO> dataMap = mapper.readValue(data, new TypeReference<LinkedHashMap<String, WechatTemplateDataDO>>() {});
////            Map<String, WechatTemplateDataDO> newDataMap = new LinkedHashMap<String, WechatTemplateDataDO>();
////            int j = 0;
////            for (Map.Entry<String, WechatTemplateDataDO> entry : dataMap.entrySet()) {//(keyword1,WechatTemplateData)
////                String key = entry.getKey();//keyword1   转为result
////                newDataMap.put(contentList.get(j),entry.getValue());
////                j++;
////            }
////
////            //将数据封装在WechatTemplate对象中
////            WechatTemplateDO wechatTemplate = new WechatTemplateDO();
////            wechatTemplate.setTouser(openid);
////            wechatTemplate.setUrl(url);
////            wechatTemplate.setTemplate_id(wxTemplate.getTemplateId());
////            if(miniprogram!=null){
////                wechatTemplate.setMiniprogram(miniprogram);
////            }
////            wechatTemplate.setData(newDataMap);
////
////            String params = mapper.writeValueAsString(wechatTemplate);
////            logger.info("----------------------模版消息json字符串:"+params+"------------------");
////
////            WxAccessTokenDO wxAccessTokenByCode = wxAccessTokenService.getWxAccessTokenById(wechatCode);
////            String token = wxAccessTokenByCode.getAccessToken();
////            String token_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;
////            String result = HttpUtil.sendPost(token_url, params);
////            logger.info("------------------------发送模板消息,微信返回结果:"+result+"-----------------------");
////
////            JSONObject jsonResult = new JSONObject(result);
////            return jsonResult;
////        } catch (Exception e) {
////            e.printStackTrace();
////            JSONObject jsonResult = new JSONObject();
////            return jsonResult;
////        }
////    }
////
////    public List<WxTemplateDO> findByWxId(String code) {
////        return wxTemplateDao.findByWxId(code);
////    }
//}

+ 170 - 0
svr/svr-statistics/doc/es/QuartzJobConfig.java

@ -0,0 +1,170 @@
package com.yihu.wlyy.entity.job;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
/**
 * 计划任务
 */
@Entity
@Table(name = "wlyy_job_config")
public class QuartzJobConfig implements java.io.Serializable {
	private String id;
	private String quotaId;//指标id
	private String jobName;//任务名称
	private String jobInfo;//任务描述
	private String jobType;//任务类型(0--单次执行  1--周期执行 2--监听任务)
	private String jobClass;//任务执行的class
	private String quartzCron;//quartz表达式
	private String status;//1 启动 0停止
	private String del;//是否删除 1正常 0删除
	private String sql;
	private String sqlCount;
	private String sqlDay;
	private String sqlYear;
	private String cacheKey;//缓存的key
	/** minimal constructor */
	public QuartzJobConfig() {
	}
	/** full constructor */
	public QuartzJobConfig(String jobName, String jobInfo, String jobType,
                           String jobClass, String quartzCron, String status) {
		this.jobName = jobName;
		this.jobInfo = jobInfo;
		this.jobType = jobType;
		this.jobClass = jobClass;
		this.quartzCron = quartzCron;
		this.status = status;
	}
	// Property accessors
	@GenericGenerator(name = "generator", strategy = "uuid")
	@Id
	@GeneratedValue(generator = "generator")
	@Column(name = "id", unique = true, nullable = false, length = 50)
	public String getId() {
		return this.id;
	}
	public void setId(String id) {
		this.id = id;
	}
	@Column(name = "job_name", length = 50)
	public String getJobName() {
		return this.jobName;
	}
	public void setJobName(String jobName) {
		this.jobName = jobName;
	}
	@Column(name = "job_info", length = 200)
	public String getJobInfo() {
		return this.jobInfo;
	}
	public void setJobInfo(String jobInfo) {
		this.jobInfo = jobInfo;
	}
	@Column(name = "job_type", length = 10)
	public String getJobType() {
		return this.jobType;
	}
	public void setJobType(String jobType) {
		this.jobType = jobType;
	}
	@Column(name = "job_class", length = 200)
	public String getJobClass() {
		return jobClass;
	}
	public void setJobClass(String jobClass) {
		this.jobClass = jobClass;
	}
	@Column(name = "quartz_cron", length = 200)
	public String getQuartzCron() {
		return this.quartzCron;
	}
	public void setQuartzCron(String quartzCron) {
		this.quartzCron = quartzCron;
	}
	@Column(name = "status", length = 1)
	public String getStatus() {
		return this.status;
	}
	public void setStatus(String status) {
		this.status = status;
	}
	@Column(name = "quota_id", length = 50)
	public String getQuotaId() {
		return quotaId;
	}
	public void setQuotaId(String quotaId) {
		this.quotaId = quotaId;
	}
	@Column(name = "del", length = 1)
	public String getDel() {
		return del;
	}
	public void setDel(String del) {
		this.del = del;
	}
	public String getSql() {
		return sql;
	}
	public void setSql(String sql) {
		this.sql = sql;
	}
	public String getSqlCount() {
		return sqlCount;
	}
	public void setSqlCount(String sqlCount) {
		this.sqlCount = sqlCount;
	}
	public String getSqlDay() {
		return sqlDay;
	}
	public void setSqlDay(String sqlDay) {
		this.sqlDay = sqlDay;
	}
	public String getSqlYear() {
		return sqlYear;
	}
	public void setSqlYear(String sqlYear) {
		this.sqlYear = sqlYear;
	}
	public String getCacheKey() {
		return cacheKey;
	}
	public void setCacheKey(String cacheKey) {
		this.cacheKey = cacheKey;
	}
}

+ 127 - 0
svr/svr-statistics/doc/es/QuartzJobConfig1.java

@ -0,0 +1,127 @@
//package com.yihu.wlyy.entity.job;
//
//import javax.persistence.Column;
//import javax.persistence.Entity;
//import javax.persistence.GeneratedValue;
//import javax.persistence.Id;
//import javax.persistence.Table;
//import org.hibernate.annotations.GenericGenerator;
//
///**
// * 计划任务
// */
//@Entity
//@Table(name = "wlyy_job_config")
//public class QuartzJobConfig implements java.io.Serializable {
//
//	private String id;
//	private String quotaId;//指标id
//	private String jobName;//任务名称
//	private String jobInfo;//任务描述
//	private String jobType;//任务类型(0--单次执行  1--周期执行 2--监听任务)
//	private String jobClass;//任务执行的class
//	private String quartzCron;//quartz表达式
//	private String status;//1 启动 0停止
//	private String del;//是否删除 1正常 0删除
//
//	/** minimal constructor */
//	public QuartzJobConfig() {
//
//	}
//
//	/** full constructor */
//	public QuartzJobConfig(String jobName, String jobInfo, String jobType,
//                           String jobClass, String quartzCron, String status) {
//		this.jobName = jobName;
//		this.jobInfo = jobInfo;
//		this.jobType = jobType;
//		this.jobClass = jobClass;
//		this.quartzCron = quartzCron;
//		this.status = status;
//	}
//
//	// Property accessors
//	@GenericGenerator(name = "generator", strategy = "uuid")
//	@Id
//	@GeneratedValue(generator = "generator")
//	@Column(name = "id", unique = true, nullable = false, length = 50)
//	public String getId() {
//		return this.id;
//	}
//
//	public void setId(String id) {
//		this.id = id;
//	}
//
//	@Column(name = "job_name", length = 50)
//	public String getJobName() {
//		return this.jobName;
//	}
//
//	public void setJobName(String jobName) {
//		this.jobName = jobName;
//	}
//
//	@Column(name = "job_info", length = 200)
//	public String getJobInfo() {
//		return this.jobInfo;
//	}
//
//	public void setJobInfo(String jobInfo) {
//		this.jobInfo = jobInfo;
//	}
//
//	@Column(name = "job_type", length = 10)
//	public String getJobType() {
//		return this.jobType;
//	}
//
//	public void setJobType(String jobType) {
//		this.jobType = jobType;
//	}
//
//	@Column(name = "job_class", length = 200)
//	public String getJobClass() {
//		return jobClass;
//	}
//
//	public void setJobClass(String jobClass) {
//		this.jobClass = jobClass;
//	}
//
//	@Column(name = "quartz_cron", length = 200)
//	public String getQuartzCron() {
//		return this.quartzCron;
//	}
//
//	public void setQuartzCron(String quartzCron) {
//		this.quartzCron = quartzCron;
//	}
//
//	@Column(name = "status", length = 1)
//	public String getStatus() {
//		return this.status;
//	}
//
//	public void setStatus(String status) {
//		this.status = status;
//	}
//
//	@Column(name = "quota_id", length = 50)
//	public String getQuotaId() {
//		return quotaId;
//	}
//
//	public void setQuotaId(String quotaId) {
//		this.quotaId = quotaId;
//	}
//
//	@Column(name = "del", length = 1)
//	public String getDel() {
//		return del;
//	}
//
//	public void setDel(String del) {
//		this.del = del;
//	}
//}

+ 108 - 0
svr/svr-statistics/doc/es/统计新增索引.txt

@ -0,0 +1,108 @@
创建索引
POST  http://172.19.103.68:9200/wlyy_quota_test
查询索引
GET http://172.19.103.68:9200/wlyy_quota_test/
给索引加mapping
POST http://172.19.103.68:9200/wlyy_quota_test/wlyy_quota_test/_mapping
{
    "wlyy_quota_test": {
            "properties": {
                "quotaCode": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "city": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "cityName": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "town": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "townName": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "hospital": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "hospitalName": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "team": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "teamName": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "slaveKey1": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "slaveKey1Name": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "slaveKey2": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "slaveKey2Name": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "slaveKey3": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "slaveKey3Name": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "slaveKey4": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "slaveKey4Name": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "areaLevel": {
                    "type": "string",
                    "index": "not_analyzed"
                }, 
               "timeLevel": {
                    "type": "string",
                    "index": "not_analyzed"
                },
                "result1": {
                    "type": "double"
                },
                "result2": {
                    "type": "double"
                },
                "quotaDate": {
                    "type": "date"
                },
                "createTime": {
                    "type": "date"
                }
            }
        }
  }
增加索引搜索大小
PUT  http://172.19.103.68:9200/wlyy_quota_test/_settings
{
  "index": {
    "max_result_window": 500000
  }
}

Datei-Diff unterdrückt, da er zu groß ist
+ 192 - 0
svr/svr-statistics/doc/sql/统计相关表数据备份20171121.txt


BIN
svr/svr-statistics/doc/业务文档/统计指标流程.docx


BIN
svr/svr-statistics/doc/部署文档/正式库/后台/tomcat部署.docx


+ 455 - 0
svr/svr-statistics/pom.xml

@ -0,0 +1,455 @@
<?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/maven-v4_0_0.xsd">
    <parent>
        <groupId>com.yihu.jw</groupId>
        <artifactId>wlyy-parent-pom</artifactId>
        <version>2.0.0</version>
        <relativePath>../../wlyy-parent-pom/pom.xml</relativePath>
    </parent>
    <groupId>com.yihu.jw</groupId>
    <artifactId>svr-statistics</artifactId>
    <packaging>war</packaging>
    <version>${parent.version}</version>
    <modelVersion>4.0.0</modelVersion>
    <!--<packaging>jar</packaging>-->
    <name>svr-statistics</name>
    <properties>
        <version.commons-bean-utils>1.9.2</version.commons-bean-utils>
        <version.commons-codec>1.9</version.commons-codec>
        <version.commons-collections>3.2.1</version.commons-collections>
        <version.commons-compress>1.9</version.commons-compress>
        <version.commons-dbcp2>2.1.1</version.commons-dbcp2>
        <version.commons-dbutils>1.6</version.commons-dbutils>
        <version.commons-io>2.4</version.commons-io>
        <version.commons-lang3>3.2.1</version.commons-lang3>
        <version.commons-pool2>2.4.2</version.commons-pool2>
        <version.hibernate>4.3.11.Final</version.hibernate>
        <version.hibernate-annotations>4.0.5.Final</version.hibernate-annotations>
        <version.hibernate-jpa-api>1.0.0.Final</version.hibernate-jpa-api>
        <version.http-client>4.5.1</version.http-client>
        <version.http-core>4.4.3</version.http-core>
        <version.java>1.8</version.java>
        <version.jackson>2.6.6</version.jackson>
        <version.jedis>2.9.0</version.jedis>
        <version.jcl-over-slf4j>1.7.19</version.jcl-over-slf4j>
        <version.jul-over-slf4j>1.7.21</version.jul-over-slf4j>
        <version.joda-time>2.8.2</version.joda-time>
        <version.junit>4.12</version.junit>
        <version.log4j2>2.4.1</version.log4j2>
        <version.logback>1.1.7</version.logback>
        <version.mysql>5.1.38</version.mysql>
        <version.quartz>2.2.3</version.quartz>
        <version.servlet-api>3.1.0</version.servlet-api>
        <version.slf4j>1.7.21</version.slf4j>
        <version.swagger>2.4.0</version.swagger>
        <version.swagger-ui>2.4.0</version.swagger-ui>
        <version.tomcat-embed>8.0.28</version.tomcat-embed>
        <version.elasticsearch>2.4.4</version.elasticsearch>
        <version.jest>2.4.0</version.jest>
        <version.httpmime>4.4.1</version.httpmime>
    </properties>
    <dependencies>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-entity</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yihu.jw</groupId>
            <artifactId>common-rest-model</artifactId>
        </dependency>
        <!--Jackson library-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${version.jackson}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${version.jackson}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${version.jackson}</version>
        </dependency>
        <!--elasticsearch start-->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>${version.elasticsearch}</version>
        </dependency>
        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
            <version>${version.jest}</version>
        </dependency>
        <!--elasticsearch end-->
        <!--Apache commons library-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>${version.httpmime}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${version.commons-lang3}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>${version.http-core}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>${version.http-client}</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>${version.commons-bean-utils}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>${version.commons-pool2}</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>${version.commons-dbutils}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>${version.commons-dbcp2}</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${version.commons-io}</version>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>${version.commons-collections}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>${version.commons-compress}</version>
        </dependency>
        <!--Hibernate framework-->
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>${version.hibernate-jpa-api}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${version.hibernate}</version>
        </dependency>
        <!--Miscellaneous-->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>${version.quartz}</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz-jobs</artifactId>
            <version>${version.quartz}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${version.servlet-api}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${version.slf4j}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${version.junit}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${version.swagger}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${version.swagger-ui}</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${version.mysql}</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>${version.joda-time}</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>${version.commons-codec}</version>
        </dependency>
        <!--Log framework-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${version.log4j2}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${version.log4j2}</version>
        </dependency>
        <!--Log framework to SLF4J bridge: x-over-slf4j-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${version.jcl-over-slf4j}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-jdk14</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jul-to-slf4j</artifactId>
            <version>${version.jul-over-slf4j}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--SLF4J api-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${version.slf4j}</version>
        </dependency>
        <!--The single log BACKEND-->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${version.logback}</version>
        </dependency>
        <!--Spring framework family-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <!--Spring integration family-->
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-jmx</artifactId>
        </dependency>
        <!--Spring batch family-->
        <!--Spring boot family-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-actuator-docs</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.3.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20151123</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.15</version>
        </dependency>
        <dependency>
            <groupId>org.nlpcn</groupId>
            <artifactId>elasticsearch-sql</artifactId>
            <version>2.4.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.plugin</groupId>
            <artifactId>delete-by-query</artifactId>
            <version>2.4.1</version>
        </dependency>
        <!-- Alibaba -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${verion.fastjson}</version>
        </dependency>
        <!-- Jzkl Starter -->
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>swagger-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>mysql-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.yihu</groupId>
            <artifactId>elasticsearch-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>patient-co-statistics-es</finalName>
        <plugins>
            <!--打成war包需要的配置-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
                <version>3.1</version>
            </plugin>
        </plugins>
    </build>
</project>

+ 120 - 0
svr/svr-statistics/readme.MD

@ -0,0 +1,120 @@
[es-sql](http://172.19.103.68:9200/_plugin/sql/) 例子
[elasticsearch-sql文档](https://github.com/NLPchina/elasticsearch-sql/wiki/Functions-support)
**重命名配置支持**
{elasticsearch_home}/config/elasticsearch.yml
```
script.inline: on
script.indexed: on
script.engine.groovy.inline.aggs: on
```
**目前2.4.2 es-sql不支持update delete**
6.x 系列的es支持delete
**查询表**
```SELECT * FROM wlyy_quota_test```
**条件查询表**
```SELECT * FROM wlyy_quota_test where townName='湖里区'```
**模糊查询**
SELECT * FROM wlyy_quota_test where townName like '%湖里%'
**查询返回单个字段**
```SELECT city FROM wlyy_quota_test```
**查询返回单个字段并且重命名**
```SELECT city as slavename FROM wlyy_quota_test```
**查询根据某个字段聚合**
```SELECT city  FROM wlyy_quota_test group by city```
**查询根据某个字段聚合并且重命名**
```SELECT city as slavename  FROM wlyy_quota_test group by slavename```
**条件查询并且排序表**
```SELECT * FROM wlyy_quota_test where townName='湖里区' order by createTime desc ```
**分页查询(分页查询不能与group by 同时使用)**
```SELECT city as slavename  FROM wlyy_quota_test limit 0,10```
**分页查询带条件(分页查询不能与group by 同时使用)**
```SELECT townName as slavename  FROM wlyy_quota_test where townName='湖里区' limit 0,10```
**count使用**
```SELECT count(*) num FROM wlyy_quota_test where townName='湖里区'```
**count distinct使用**
```select count( distinct town) from wlyy_quota_test```
**max使用**
```SELECT max(result1) FROM wlyy_quota_test where townName='湖里区'```
**min使用**
```SELECT min(result1) FROM wlyy_quota_test where townName='湖里区'```
**sum使用**
```select sum(result1) from wlyy_quota_test```
**按照年龄分组使用**
```SELECT count(age) FROM account GROUP BY range(age, 20,25,30,35,40)```
**时间聚合使用**
```select town,townName,sum(result1) result1 from wlyy_quota_test group by town,townName,date_histogram(field='quotaDate','interval'='month')```
interval例子
```
1天    date_histogram(field='quotaDate','interval'='1d')
每周   date_histogram(field='quotaDate','interval'='week')
每月   date_histogram(field='quotaDate','interval'='month')
每季度 date_histogram(field='quotaDate','interval'='quarter')
每年   date_histogram(field='quotaDate','interval'='year')
```
**子字段(nested)查询**
```SELECT townName.name FROM wlyy_quota_test where townName.name like '%湖里%'```
**join(只支持2个表,简单的查询 不支持分组)**
```select  table1.town town1 ,table2.townName townName2 from wlyy_quota_test table1 join wlyy_quota_test table2 on table1.town=table2.town```

+ 56 - 0
svr/svr-statistics/src/main/java/com/yihu/wlyy/Application.java

@ -0,0 +1,56 @@
package com.yihu.wlyy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration;
import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration;
import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.support.ErrorPageFilter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
/**
 * Created by Administrator on 2016.10.12.
 */
@SpringBootApplication
@EnableJpaRepositories(
        entityManagerFactoryRef = "wlyyEntityManagerFactory",
        transactionManagerRef = "wlyyTransactionManager")
@EnableAutoConfiguration(exclude = {
        ElasticsearchAutoConfiguration.class,
        ElasticsearchRepositoriesAutoConfiguration.class,
        ElasticsearchDataAutoConfiguration.class,
        RedisRepositoriesAutoConfiguration.class
})
public class Application {
    public static ApplicationContext ctx = null;
    public static void main(String[] args) {
        ctx = SpringApplication.run(Application.class, args);
    }
    /**
     * start 解决如下问题
     * Cannot forward to error page for
     * request [/strategy/list/] as the response has already been committed. As a
     * result, the response may have the wrong status code. If your application is
     * running on WebSphere Application Server you may be able to resolve this
     * problem by setting com.ibm.ws.webcontainer.invokeFlushAfterService to false
     */
    @Bean
    public ErrorPageFilter errorPageFilter() {
        return new ErrorPageFilter();
    }
    @Bean
    public FilterRegistrationBean disableSpringBootErrorFilter(ErrorPageFilter filter) {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(filter);
        filterRegistrationBean.setEnabled(false);
        return filterRegistrationBean;
    }
    //end
}

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

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

+ 240 - 0
svr/svr-statistics/src/main/java/com/yihu/wlyy/statistics/config/DataSourceConfig.java

@ -0,0 +1,240 @@
package com.yihu.wlyy.statistics.config;
import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
 * Created by Administrator on 2016.10.20.
 * 多数据源配置
 */
@Configuration
public class DataSourceConfig {
    @Value("${spring.datasource.driverClassName}")
    private String driverClassName;
    @Value("${spring.datasource.initialSize}")
    private Integer initialSize;
    @Value("${spring.datasource.minIdle}")
    private Integer minIdle;
    @Value("${spring.datasource.maxActive}")
    private Integer maxActive;
    @Value("${spring.datasource.maxWait}")
    private Integer maxWait;
    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
    private Integer timeBetweenEvictionRunsMillis;
    @Value("${spring.datasource.minEvictableIdleTimeMillis}")
    private Integer minEvictableIdleTimeMillis;
    @Value("${spring.datasource.validationQuery}")
    private String validationQuery;
    @Value("${spring.datasource.testWhileIdle}")
    private Boolean testWhileIdle;
    @Value("${spring.datasource.testOnBorrow}")
    private Boolean testOnBorrow;
    @Value("${spring.datasource.testOnReturn}")
    private Boolean testOnReturn;
    @Value("${spring.datasource.poolPreparedStatements}")
    private Boolean poolPreparedStatements;
    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
    private Integer maxPoolPreparedStatementPerConnectionSize;
    @Value("${spring.datasource.removeAbandoned}")
    private Boolean removeAbandoned;
    @Value("${spring.datasource.removeAbandonedTimeout}")
    private Integer removeAbandonedTimeout;
    @Value("${spring.datasource.logAbandoned}")
    private Boolean logAbandoned;
    @Value("${spring.datasource.filters")
    private String filters;
    @Value("${spring.datasource.primaryReadWrite.url}")
    private String primaryReadWriteUrl;
    @Value("${spring.datasource.primaryReadWrite.username}")
    private String primaryReadWriteUsername;
    @Value("${spring.datasource.primaryReadWrite.password}")
    private String primaryReadWritePassword;
    /**
     * 主数据源
     *
     * @return
     */
    @Bean(name = "primaryReadWrite")
    @Primary//主库 默认不写名字用这个
    public DataSource primaryReadWriteDataSource(StatFilter statFilter) throws SQLException {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(primaryReadWriteUrl);
        datasource.setUsername(primaryReadWriteUsername);
        datasource.setPassword(primaryReadWritePassword);
        datasource.setDriverClassName(driverClassName);
        //configuration
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        datasource.setRemoveAbandoned(removeAbandoned);
        datasource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
        datasource.setLogAbandoned(logAbandoned);
        datasource.setFilters(filters);
        datasource.setConnectProperties(properties());//;# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
        datasource.setUseGlobalDataSourceStat(true);// 合并多个DruidDataSource的监控数据
        List proxyFilters = new ArrayList<>();
        proxyFilters.add(statFilter);
        datasource.setProxyFilters(proxyFilters);
        return datasource;
    }
    @Value("${spring.datasource.primaryRead.url}")
    private String primaryReadUrl;
    @Value("${spring.datasource.primaryRead.username}")
    private String pprimaryReadUsername;
    @Value("${spring.datasource.primaryRead.password}")
    private String primaryReadPassword;
    @Bean(name = "primaryRead")
    public DataSource primaryReadDataSource(StatFilter statFilter) throws SQLException {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(primaryReadUrl);
        datasource.setUsername(pprimaryReadUsername);
        datasource.setPassword(primaryReadPassword);
        datasource.setDriverClassName(driverClassName);
        //configuration
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        datasource.setRemoveAbandoned(removeAbandoned);
        datasource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
        datasource.setLogAbandoned(logAbandoned);
        datasource.setFilters(filters);
        datasource.setConnectProperties(properties());//;# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
        datasource.setUseGlobalDataSourceStat(true);// 合并多个DruidDataSource的监控数据
        List proxyFilters = new ArrayList<>();
        proxyFilters.add(statFilter);
        datasource.setProxyFilters(proxyFilters);
        return datasource;
    }
    @Value("${spring.datasource.im.url}")
    private String imUrl;
    @Value("${spring.datasource.im.username}")
    private String imUsername;
    @Value("${spring.datasource.im.password}")
    private String imPassword;
    @Bean(name = "imData")
    public DataSource imDataSource(StatFilter statFilter) throws SQLException {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(imUrl);
        datasource.setUsername(imUsername);
        datasource.setPassword(imPassword);
        datasource.setDriverClassName(driverClassName);
        //configuration
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        datasource.setRemoveAbandoned(removeAbandoned);
        datasource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
        datasource.setLogAbandoned(logAbandoned);
        datasource.setFilters(filters);
        datasource.setConnectProperties(properties());//;# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
        datasource.setUseGlobalDataSourceStat(true);// 合并多个DruidDataSource的监控数据
        List proxyFilters = new ArrayList<>();
        proxyFilters.add(statFilter);
        datasource.setProxyFilters(proxyFilters);
        return datasource;
    }
    private Properties properties() {
        Properties properties = new Properties();
        properties.put("druid.stat.mergeSql", "true");
        properties.put("slowSqlMillis", "1000");
        return properties;
    }
    //------------------------------------druid 监控----------------------------------------------
    @Bean
    public ServletRegistrationBean statViewServlet() {
        //创建servlet注册实体
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        //设置ip白名单
        //servletRegistrationBean.addInitParameter("allow","127.0.0.1");
        //设置ip黑名单,如果allow与deny共同存在时,deny优先于allow
        // servletRegistrationBean.addInitParameter("deny","192.168.0.19");
        //设置控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername", "jkzl");
        servletRegistrationBean.addInitParameter("loginPassword", "jkzlehr");
        //是否可以重置数据
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }
    @Bean
    public FilterRegistrationBean filterRegistrationBean(WebStatFilter webStatFilter) {
        //创建过滤器
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(webStatFilter);
        //设置过滤器过滤路径
        filterRegistrationBean.addUrlPatterns("/*");
        //忽略过滤的形式
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
    @Bean
    public StatFilter statFilter() {
        return new StatFilter();
    }
    @Bean
    public WebStatFilter webStatFilter() {
        return new WebStatFilter();
    }
    //------------------------------------druid 监控----------------------------------------------
}

+ 30 - 0
svr/svr-statistics/src/main/java/com/yihu/wlyy/statistics/config/MVCConfig.java

@ -0,0 +1,30 @@
package com.yihu.wlyy.statistics.config;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;
/**
 * Created by chenweida on 2017/7/17.
 */
@Configuration
public class MVCConfig extends WebMvcConfigurerAdapter {
    /**
     * 为null的数据不返回
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper=new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(mappingJackson2HttpMessageConverter);
    }
}

+ 64 - 0
svr/svr-statistics/src/main/java/com/yihu/wlyy/statistics/config/SwaggerConfig.java

@ -0,0 +1,64 @@
package com.yihu.wlyy.statistics.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static com.google.common.base.Predicates.or;
import static springfox.documentation.builders.PathSelectors.regex;
/**
 * Created by chenweida on 2016/2/3.
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter {
    private static final String PUBLIC_API = "Default";
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
    @Bean
    public Docket publicAPI() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName(PUBLIC_API)
                .genericModelSubstitutes(DeferredResult.class)
                .useDefaultResponseMessages(false)
                .forCodeGeneration(true)
                .pathMapping("/")
                .select()
                .paths(or(
                        regex("/job/.*"),
                        regex("/quotaQuery/.*"),
                        regex("/extractDataToEs/.*")
                ))
                .build()
                .apiInfo(publicApiInfo());
    }
    private ApiInfo publicApiInfo() {
        ApiInfo apiInfo = new ApiInfo("三师平台统计分析API",
                "统计分析接口。",
                "1.0",
                "No terms of service",
                "admin@jkzl.com",
                "The Apache License, Version 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0.html"
        );
        return apiInfo;
    }
}

+ 0 - 0
svr/svr-statistics/src/main/java/com/yihu/wlyy/statistics/config/WebSecurityConfig.java


Einige Dateien werden nicht angezeigt, da zu viele Dateien in diesem Diff geändert wurden.