commit 79549977df597e5913d12c2cfdd4faa879779027 Author: xiangwb Date: Fri Nov 3 15:41:52 2017 +0800 merge diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a23968a --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +### IntelliJ IDEA ### +.idea +.mvn +*.iml +logs + +boot-service/target +boot-service/*.iml +boot-web/target +boot-web/*.iml + +mvnw +mvnw.cmd +### eclipse ### +sbdemo/.project +sbdemo/.classpath +sbdemo/.settings diff --git a/boot-service/pom.xml b/boot-service/pom.xml new file mode 100644 index 0000000..52a95b3 --- /dev/null +++ b/boot-service/pom.xml @@ -0,0 +1,66 @@ + + + + boot-module-demo + com.xwbing + 1.0 + + 4.0.0 + boot-service + + + nexus + drore Team nexus + http://192.168.11.110:8081/nexus/content/groups/public + + + + + nexus + drore Team nexus + http://192.168.11.110:8081/nexus/content/groups/public + + + + + + org.springframework.boot + spring-boot-starter-mail + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + mysql + mysql-connector-java + + + + org.projectlombok + lombok + ${lombok.version} + + + + org.hibernate + hibernate-validator + + + + redis.clients + jedis + 2.7.3 + + + + javax.servlet + servlet-api + 2.5 + provided + + + \ No newline at end of file diff --git a/boot-service/src/main/java/com/xwbing/constant/CommonConstant.java b/boot-service/src/main/java/com/xwbing/constant/CommonConstant.java new file mode 100644 index 0000000..bbb7445 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/constant/CommonConstant.java @@ -0,0 +1,77 @@ +package com.xwbing.constant; + +/** + * 说明: 公共常量 + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +public class CommonConstant { + /** + * 顶级 + */ + public static String ROOT = "root"; + /** + * 密码加密 + */ + public static final int SALT_SIZE = 8; + /** + * 密码加密 + */ + public static int HASH_INTERATIONS = 1024; + + /** + * 启用 + */ + public static String ISENABLE = "Y"; + /** + * 禁用 + */ + public static String ISNOTENABLE = "N"; + + /** + * 邮件服务器配置项 + */ + public static final String SYSCONFIG_EMAILCONFIGKEY = "email_config"; + + /** + * 服务器配置项 + */ + public static final String SYSCONFIG_SERVER_TOPO = "server_topo"; + + /** + * 邮箱找回密码有效时间 + */ + public static final String SYSCONFIG_LOOK_PASSWORD_TIME = "look_password_time"; + + /** + * 资源文件xml 名称 + */ + public static final String RESOURCE_XML="resource.xml"; + /** + * 资源文件 sql + */ + public static final String RESOURCE_SQL="resource.sql"; + /** + * 资源详情xml文件 + */ + public static final String RESOURCE_DETAIL_XML="resource_detail.xml"; + /** + * 导出报表文件名称 + */ + public static String USERREPORTFILENAME = "人员统计报表.xls"; + /** + * 导出报表列名称 + */ + public static String[] USERREPORTCOLUMNS = new String[]{"线路名称","发团人数","成人","儿童","幼儿"}; + /*** + * 当前登录用户 + */ + public static final String SESSION_CURRENT_USER="CURRENT_USER"; + + /*** + * 当前登录管理员用户 + */ + public static final String SESSION_ADMIN_USER="ADMIN_USER"; + +} diff --git a/boot-service/src/main/java/com/xwbing/constant/CommonEnum.java b/boot-service/src/main/java/com/xwbing/constant/CommonEnum.java new file mode 100644 index 0000000..30b8047 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/constant/CommonEnum.java @@ -0,0 +1,84 @@ +package com.xwbing.constant; + +import java.util.Arrays; +import java.util.stream.Collectors; + +/** + * 说明: 公共枚举 + * 项目名称: zdemo + * 创建日期: 2016年12月9日 上午9:50:30 + * 作者: xiangwb + */ +public class CommonEnum { + public enum YesOrNo { + YES("是", "Y"), NO("否", "N"); + private String name; + private String code; + + YesOrNo(String name, String code) { + this.name = name; + this.code = code; + } + + public String getCode() { + return code; + } + + public String getName() { + return name; + } + } + + /** + * 登录登出标记 + */ + public enum LoginInOut { + IN("登录", 1), OUT("登出", 2); + private String name; + private int value; + + LoginInOut(String name, int value) { + this.name = name; + this.value = value; + } + + public int getValue() { + return value; + } + + public String getName() { + return name; + } + } + + public enum ValidateResultEnum { + SUCCESS("校验通过", 1), FAILED("校验失败", 0); + private String msg; + private int errorCode; + + ValidateResultEnum(String msg, int errorCode) { + this.msg = msg; + this.errorCode = errorCode; + } + + public String getMsg() { + return this.msg; + } + + public int getErrorCode() { + return this.errorCode; + } + } + + public static void main(String[] args) { + String code = "Y"; + for (YesOrNo yesOrNo : YesOrNo.values()) { + if (yesOrNo.getCode().equals(code)) { + System.out.println(yesOrNo.getName()); + break; + } + } + YesOrNo yesOrNo = Arrays.stream(YesOrNo.values()).filter(obj -> obj.getCode().equals(code)).collect(Collectors.toList()).get(0); + System.out.println(yesOrNo.getName()); + } +} diff --git a/boot-service/src/main/java/com/xwbing/domain/BaseEntity.java b/boot-service/src/main/java/com/xwbing/domain/BaseEntity.java new file mode 100644 index 0000000..9449e38 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/domain/BaseEntity.java @@ -0,0 +1,33 @@ +package com.xwbing.domain; + +import lombok.Data; + +import javax.persistence.Column; +import javax.persistence.Id; +import javax.persistence.MappedSuperclass; +import java.io.Serializable; +import java.util.Date; + +/** + * 说明: 基础类 + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +@Data +@MappedSuperclass +public class BaseEntity implements Serializable { + private static final long serialVersionUID = 8901948362657956187L; + @Id + @Column(length = 50) + private String id; + private String creator; + private String modifier; + @Column(name = "create_time") + private Date createTime; + @Column(name = "modified_time") + private Date modifiedTime; + @Column(name = "is_deleted") + private String isDeleted; + private Integer sort; +} diff --git a/boot-service/src/main/java/com/xwbing/domain/SysAuthority.java b/boot-service/src/main/java/com/xwbing/domain/SysAuthority.java new file mode 100644 index 0000000..476d7f7 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/domain/SysAuthority.java @@ -0,0 +1,58 @@ +package com.xwbing.domain; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.hibernate.validator.constraints.Length; +import org.hibernate.validator.constraints.NotBlank; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.validation.constraints.Pattern; + +/** + * 说明: 权限 + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Entity(name = "sys_authority") +public class SysAuthority extends BaseEntity { + private static final long serialVersionUID = -6469518352117371987L; + public static String table = "sys_authority"; + /** + * 名称 + */ + @NotBlank(message = "name不能为空") + @Length(min = 1, max = 10, message = "name长度为1-10") + private String name; + /** + * 编号 + */ + @NotBlank(message = "编号不能为空") + @Length(min = 6, max = 50, message = "编号长度为6-50") + private String code; + /** + * 是否启用 + */ + @NotBlank(message = "是否启用不能为空") + @Pattern(regexp = "Y|N",message = "是否启用格式应为Y|N") + @Column(name = "is_enable") + private String isEnable; + /** + * url地址 + */ + private String url; + /** + * 父ID + */ + @NotBlank(message = "父ID不能为空") + @Length(min = 6, max = 50, message = "父ID长度为6-50") + @Column(name = "parent_id") + private String parentId; + /** + * 类型 2按钮 1菜单 + */ + private Integer type; +} diff --git a/boot-service/src/main/java/com/xwbing/domain/SysConfig.java b/boot-service/src/main/java/com/xwbing/domain/SysConfig.java new file mode 100644 index 0000000..7fb5d38 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/domain/SysConfig.java @@ -0,0 +1,49 @@ +package com.xwbing.domain; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.hibernate.validator.constraints.Length; +import org.hibernate.validator.constraints.NotBlank; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.validation.constraints.Pattern; + +/** + * 说明: 系统配置 + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Entity(name = "system_config") +public class SysConfig extends BaseEntity { + private static final long serialVersionUID = -7587016038432881980L; + public static String table = "system_config"; + /** + * 配置项的key + */ + @NotBlank(message = "配置项的code不能为空") + @Length(min = 1, max = 50, message = "code长度为1-50") + private String code; + /** + * 配置项的值 + */ + @NotBlank(message = "配置项的value不能为空") + private String value; + /** + * 是否启用 + */ + @NotBlank(message = "是否启用不能为空") + @Pattern(regexp = "Y|N",message = "是否启用格式为Y|N") + @Column(name = "is_enable") + private String isEnable; + /** + * 配置项的描述(名称) + */ + @NotBlank(message = "配置项的name不能为空") + @Length(min = 1, max = 10, message = "value长度为1-10") + private String name; + +} diff --git a/boot-service/src/main/java/com/xwbing/domain/SysRole.java b/boot-service/src/main/java/com/xwbing/domain/SysRole.java new file mode 100644 index 0000000..824588e --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/domain/SysRole.java @@ -0,0 +1,46 @@ +package com.xwbing.domain; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.hibernate.validator.constraints.Length; +import org.hibernate.validator.constraints.NotBlank; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.validation.constraints.Pattern; + +/** + * 说明: 角色 + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Entity(name = "sys_role") +public class SysRole extends BaseEntity { + private static final long serialVersionUID = -3048021197170624143L; + public static String table = "sys_role"; + /** + * 角色名称 + */ + @NotBlank(message = "角色名称不能为空") + private String name; + /** + * 角色编码 + */ + @NotBlank(message = "角色编码不能为空") + @Length(min = 6, max = 50, message = "长度为6-20") + private String code; + /** + * 是否启用 + */ + @NotBlank(message = "是否启用不能为空") + @Pattern(regexp = "Y|N",message = "是否启用格式应为Y|N") + @Column(name = "is_enable") + private String isEnable; + /** + * 描述 + */ + private String remark; +} diff --git a/boot-service/src/main/java/com/xwbing/domain/SysRoleAuthority.java b/boot-service/src/main/java/com/xwbing/domain/SysRoleAuthority.java new file mode 100644 index 0000000..25cf406 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/domain/SysRoleAuthority.java @@ -0,0 +1,34 @@ +package com.xwbing.domain; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.hibernate.validator.constraints.NotBlank; + +import javax.persistence.Column; +import javax.persistence.Entity; + +/** + * 说明: 角色权限关系 + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Entity(name = "sys_role_authority") +public class SysRoleAuthority extends BaseEntity { + private static final long serialVersionUID = 1241064470335852429L; + public static String table = "sys_role_authority"; + /** + * 角色主键 + */ + @NotBlank(message = "角色主键不能为空") + @Column(name = "role_id") + private String roleId; + /** + * 权限主键 + */ + @NotBlank(message = "权限主键不能为空") + @Column(name = "authority_id") + private String authorityId; +} diff --git a/boot-service/src/main/java/com/xwbing/domain/SysUser.java b/boot-service/src/main/java/com/xwbing/domain/SysUser.java new file mode 100644 index 0000000..4a38564 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/domain/SysUser.java @@ -0,0 +1,83 @@ +package com.xwbing.domain; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.hibernate.validator.constraints.Email; +import org.hibernate.validator.constraints.Length; +import org.hibernate.validator.constraints.NotBlank; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.validation.constraints.Pattern; +import java.util.Date; + +/** + * 说明: 用户 + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Entity(name = "sys_user_info") +public class SysUser extends BaseEntity { + private static final long serialVersionUID = -2447528751353457021L; + public static String table = "sys_user_info"; + /** + * 密码盐长度 + */ + public static final int SALT_SIZE = 10; + /** + * 初始默认密码长度 + */ + public static final int PWD_LENGTH = 8; + /** + * hash + */ + public static int HASH_INTERATIONS = 1024; + /** + * 用户名 + */ + @NotBlank(message = "用户名不能为空") + @Length(min = 1, max = 20, message = "长度为1-20") + @Column(name = "user_name") + private String userName; + /** + * 姓名 + */ + private String name; + /** + * 盐值 + */ + private String salt; + /** + * 密码 + */ + private String password; + /** + * 最后登录IP + */ + @Column(name = "last_login_ip") + private String lastLoginIp; + /** + * 最后登录时间 + */ + @Column(name = "last_login_time") + private Date lastLoginTime; + /** + * 邮箱 + */ + @Email + private String mail; + /** + * 性别 + */ + @NotBlank + @Pattern(regexp = "[01]", message = "性别格式为0|1,0代表女,1代表男") + private String sex; + /** + * 是否管理员 + */ + @Column(name = "is_admin") + private String isAdmin; +} diff --git a/boot-service/src/main/java/com/xwbing/domain/SysUserRole.java b/boot-service/src/main/java/com/xwbing/domain/SysUserRole.java new file mode 100644 index 0000000..d2ff42c --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/domain/SysUserRole.java @@ -0,0 +1,34 @@ +package com.xwbing.domain; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import org.hibernate.validator.constraints.NotBlank; + +import javax.persistence.Column; +import javax.persistence.Entity; + +/** + * 说明: 用户角色关系 + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Entity(name = "sys_user_role") +public class SysUserRole extends BaseEntity { + private static final long serialVersionUID = 7340808603856635810L; + public static String table="sys_user_role"; + /** + * 用户主键 + */ + @NotBlank(message = "用户主键不能为空") + @Column(name = "user_id") + private String userId; + /** + * 角色主键 + */ + @NotBlank(message = "角色主键不能为空") + @Column(name = "role_id") + private String roleId; +} diff --git a/boot-service/src/main/java/com/xwbing/domain/model/EmailModel.java b/boot-service/src/main/java/com/xwbing/domain/model/EmailModel.java new file mode 100644 index 0000000..38427e7 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/domain/model/EmailModel.java @@ -0,0 +1,153 @@ +package com.xwbing.domain.model; + +import java.util.Date; + +/** + * 说明: 邮箱属性 + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +public class EmailModel { + public EmailModel(){ + //默认值 + } + /** + * 发送邮件协议名称,默认smtp + */ + private String protocol; + /** + * 发送邮箱地址 + */ + private String fromEmail; + /** + * 邮箱密码 + */ + private String password; + /** + * 接收邮箱 + */ + private String toEmail; + /** + * 设置发送时间,默认是即时发送 + */ + private Date sendTime; + /** + * 发送邮件服务器主机 + */ + private String serverHost; + /** + * 发送邮件服务器端口 + */ + private Integer serverPort; + /** + * 是否需要身份验证 + */ + private boolean auth; + + /** + * 邮件主题 + */ + private String subject; + /** + * 邮件内容 + */ + private String centent; + /** + * 邮件附件的文件名 + */ + private String[] attachFileNames; + + public String getFromEmail() { + return fromEmail; + } + + public void setFromEmail(String fromEmail) { + this.fromEmail = fromEmail; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getToEmail() { + return toEmail; + } + + public void setToEmail(String toEmail) { + this.toEmail = toEmail; + } + + public Date getSendTime() { + if (sendTime == null) + sendTime = new Date(); + return sendTime; + } + + public void setSendTime(Date sendTime) { + this.sendTime = sendTime; + } + + public String getServerHost() { + return serverHost; + } + + public void setServerHost(String serverHost) { + this.serverHost = serverHost; + } + + public Integer getServerPort() { + return serverPort; + } + + public void setServerPort(Integer serverPort) { + this.serverPort = serverPort; + } + + public boolean isAuth() { + return auth; + } + + public void setAuth(boolean auth) { + this.auth = auth; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public String getCentent() { + return centent; + } + + public void setCentent(String centent) { + this.centent = centent; + } + + public String[] getAttachFileNames() { + return attachFileNames; + } + + public void setAttachFileNames(String[] attachFileNames) { + this.attachFileNames = attachFileNames; + } + + public String getProtocol() { + if(protocol==null || "".equals(protocol.trim())) + this.protocol="smtp"; + return protocol; + } + + public void setProtocol(String protocol) { + this.protocol = protocol; + } + +} diff --git a/boot-service/src/main/java/com/xwbing/domain/model/ValidateModel.java b/boot-service/src/main/java/com/xwbing/domain/model/ValidateModel.java new file mode 100644 index 0000000..adc46cf --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/domain/model/ValidateModel.java @@ -0,0 +1,104 @@ +package com.xwbing.domain.model; + +import org.hibernate.validator.constraints.Email; +import org.hibernate.validator.constraints.Length; +import org.hibernate.validator.constraints.NotBlank; +import org.hibernate.validator.constraints.NotEmpty; +import org.springframework.format.annotation.DateTimeFormat; + +import javax.validation.constraints.DecimalMin; +import javax.validation.constraints.Min; +import javax.validation.constraints.Pattern; +import java.util.Date; + +/** + * 说明: hibernate validate JSR303校验框架 + * controller层新增或更新的实体前加@Valid注解 + * 项目名称: sbdemo + * 创建时间: 2017/5/17 16:13 + * 作者: xiangwb + */ + +public class ValidateModel { + @NotBlank(message = "name不能为空") + @Length(max = 50, message = "name长度为1-50") + private String name; + + @NotEmpty(message = "age不能为空") + @Min(value = 0, message = "age不能为负") + private int age; + + @NotEmpty(message = "money不能为空") + @DecimalMin(value = "0", message = "money不能为负") + private double money; + + @DateTimeFormat(pattern = "yyyy-MM-dd") + private Date birthDay; + + @NotBlank(message = "happyTime不能为空") + @Pattern(regexp = "\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}", message = "happyTime格式为yyyy-MM-dd HH:mm:ss") + private String happyTime; + + @Email(message = "邮箱格式不正确") + private String email; + + @NotBlank(message = "sex不能为空") + @Pattern(regexp = "[01]", message = "sex格式为0|1,0代表女,1代表男") + private String sex; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public double getMoney() { + return money; + } + + public void setMoney(double money) { + this.money = money; + } + + public Date getBirthDay() { + return birthDay; + } + + public void setBirthDay(Date birthDay) { + this.birthDay = birthDay; + } + + public String getHappyTime() { + return happyTime; + } + + public void setHappyTime(String happyTime) { + this.happyTime = happyTime; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getSex() { + return sex; + } + + public void setSex(String sex) { + this.sex = sex; + } +} diff --git a/boot-service/src/main/java/com/xwbing/exception/BusinessException.java b/boot-service/src/main/java/com/xwbing/exception/BusinessException.java new file mode 100644 index 0000000..3705069 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/exception/BusinessException.java @@ -0,0 +1,24 @@ +package com.xwbing.exception; + +/** + * 说明: 自定义业务异常 + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +public class BusinessException extends RuntimeException { + private static final long serialVersionUID = 7493711492820795133L; + + public BusinessException(Throwable cause) { + super(cause); + } + + public BusinessException(String message) { + super(message); + } + + public BusinessException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/boot-service/src/main/java/com/xwbing/exception/UserNotLoginException.java b/boot-service/src/main/java/com/xwbing/exception/UserNotLoginException.java new file mode 100644 index 0000000..31d95df --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/exception/UserNotLoginException.java @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2016 Zhejiang DRORE Technology CO.,LTD. + * All rights reserved. + * Official Web Site: http://www.drore.com. + * Developer Web Site: http://open.drore.com. + */ +package com.xwbing.exception; + +/** + * 说明: 用户系统中未登陆异常 + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +public class UserNotLoginException extends RuntimeException { + private static final long serialVersionUID = -3173607918780955199L; + + + public UserNotLoginException() { + // TODO Auto-generated constructor stub + } + + public UserNotLoginException(String msg) { + super(msg); + } + + +} diff --git a/boot-service/src/main/java/com/xwbing/redis/RedisConfig.java b/boot-service/src/main/java/com/xwbing/redis/RedisConfig.java new file mode 100644 index 0000000..0c9c295 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/redis/RedisConfig.java @@ -0,0 +1,49 @@ +package com.xwbing.redis; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; + +/** + * 说明: redisConfig + * 项目名称: sbdemo + * 创建时间: 2017/5/5 16:44 + * 作者: xiangwb + */ +@Configuration +public class RedisConfig { + private final Logger logger = LoggerFactory.getLogger(RedisConfig.class); + @Value("${redis.maxTotal}") + private Integer maxTotal; + @Value("${redis.maxIdle}") + private Integer maxIdle; + @Value("${redis.minIdle}") + private Integer minIdle; + @Value("${redis.host}") + private String host; + @Value("${redis.port}") + private Integer port; + @Value("${redis.timeout}") + private Integer timeOut; + + @Bean + public JedisPoolConfig jedisPoolConfig() { + JedisPoolConfig config = new JedisPoolConfig(); + config.setMaxTotal(maxTotal); + config.setMaxIdle(maxIdle); + config.setMinIdle(minIdle); + return config; + } + + @Bean + public JedisPool jedisPool() { + JedisPoolConfig config = jedisPoolConfig(); + JedisPool pool = new JedisPool(config, host, port, timeOut); + logger.info("init JedisPool ..............."); + return pool; + } +} diff --git a/boot-service/src/main/java/com/xwbing/redis/RedisService.java b/boot-service/src/main/java/com/xwbing/redis/RedisService.java new file mode 100644 index 0000000..aebe11a --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/redis/RedisService.java @@ -0,0 +1,384 @@ +package com.xwbing.redis; + +/** + * 说明: 封装redis 缓存服务器服务接口 + * 项目名称: sbdemo + * 创建时间: 2017/5/5 16:44 + * 作者: xiangwb + */ + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +@Component +@PropertySource("classpath:redis.properties") +public class RedisService { + @Autowired + private JedisPool jedisPool; + @Value("${redisCode}") + private String redisCode; + + private RedisService() { + + } + + /** + * 获取一个jedis 客户端 + * + * @return + */ + private Jedis getJedis() { + return jedisPool.getResource(); + } + + /** + * 释放Jedis资源 + * + * @param jedis + */ + private void returnJedies(Jedis jedis) { + if (null != jedis) { + jedis.close(); + } + } + ////////////////////////////////////////string//////////////////////////////////////// + + /** + * 添加key value + * + * @param key + * @param value + */ + public void set(String key, String value) { + Jedis jedis = null; + try { + jedis = getJedis(); + key = redisCode + key; + jedis.set(key, value); + } finally { + returnJedies(jedis); + } + } + + /** + * 添加key value 并且设置存活时间 + * + * @param key + * @param value + * @param liveTime + */ + public void set(String key, String value, int liveTime) { + Jedis jedis = null; + try { + jedis = getJedis(); + key = redisCode + key; + jedis.setex(key, liveTime, value); + } finally { + returnJedies(jedis); + } + } + + /** + * 获取redis value (String) + * + * @param key + * @return + */ + public String get(String key) { + Jedis jedis = null; + try { + jedis = getJedis(); + key = redisCode + key; + String value = jedis.get(key); + return value; + } finally { + returnJedies(jedis); + } + } + + /** + * 通过正则匹配keys + * + * @param pattern + * @return + */ + public Set keys(String pattern) { + Jedis jedis = null; + try { + jedis = getJedis(); + return jedis.keys(pattern); + } finally { + returnJedies(jedis); + } + } + ////////////////////////////////////////list//////////////////////////////////////// + + /** + * 添加数据到list + * + * @param list + * @param values + */ + public void lpush(String list, String... values) { + Jedis jedis = null; + try { + jedis = getJedis(); + list = redisCode + list; + jedis.lpush(list, values); + } finally { + returnJedies(jedis); + } + } + + /** + * 获取list + * + * @param key + * @return + */ + public List lrange(String key) { + Jedis jedis = null; + try { + jedis = getJedis(); + key = redisCode + key; + return jedis.lrange(key, 0, -1); + } finally { + returnJedies(jedis); + } + } + ////////////////////////////////////////map//////////////////////////////////////// + + /** + * 存map + * + * @param key + * @param hash + * @return + */ + public String hmset(String key, Map hash) { + Jedis jedis = null; + try { + jedis = getJedis(); + key = redisCode + key; + return jedis.hmset(key, hash); + } finally { + returnJedies(jedis); + } + } + + /** + * 获取map + * + * @param map + * @return + */ + public Map hgetAll(String map) { + Jedis jedis = null; + try { + jedis = getJedis(); + map = redisCode + map; + return jedis.hgetAll(map); + } finally { + returnJedies(jedis); + } + } + + /** + * 添加数据到指定map + * + * @param map + * @param key + * @param value + */ + + public void hset(String map, String key, String value) { + Jedis jedis = null; + try { + jedis = getJedis(); + map = redisCode + map; + jedis.hset(key, map, value); + } finally { + returnJedies(jedis); + } + } + + /** + * 获取指定map的值 + * + * @param map + * @param key + * @return + */ + public String hget(String map, String key) { + Jedis jedis = null; + try { + jedis = getJedis(); + map = redisCode + map; + return jedis.hget(key, map); + } finally { + returnJedies(jedis); + } + } + + /** + * 删除指定map的值 + * + * @param map + * @param key + */ + public void hdel(String map, String key) { + Jedis jedis = null; + try { + jedis = getJedis(); + map = redisCode + map; + jedis.hdel(key, map); + } finally { + returnJedies(jedis); + } + } + + /** + * 获取指定map中所有的keys + * + * @param map + */ + public Set hkeys(String map) { + Jedis jedis = null; + try { + jedis = getJedis(); + map = redisCode + map; + return jedis.hkeys(map); + } finally { + returnJedies(jedis); + } + } + + /** + * 获取指定map中所有的values + * + * @param map + */ + public List hvals(String map) { + Jedis jedis = null; + try { + jedis = getJedis(); + map = redisCode + map; + return jedis.hvals(map); + } finally { + returnJedies(jedis); + } + } + ///////////////////////////////////public///////////////////////////////////////////////// + + /** + * 通过key删除 + * + * @param key + */ + public void del(String key) { + Jedis jedis = null; + try { + jedis = getJedis(); + key = redisCode + key; + jedis.del(key); + } finally { + returnJedies(jedis); + } + } + + /** + * 初始化的时候删除 + * + * @param key + */ + public void delInit(String key) { + Jedis jedis = null; + try { + jedis = getJedis(); + jedis.del(key); + } finally { + returnJedies(jedis); + } + } + + /** + * 检查key是否已经存在 + * + * @param key + * @return + */ + public boolean exists(String key) { + Jedis jedis = null; + try { + jedis = getJedis(); + key = redisCode + key; + return jedis.exists(key); + } finally { + returnJedies(jedis); + } + } + + /** + * 刷新缓存 + */ + public void flushAll() { + Jedis jedis = null; + try { + jedis = getJedis(); + jedis.flushAll(); + } finally { + returnJedies(jedis); + } + } + + /** + * 清空redis 所有数据 + * + * @return + */ + public String flushDB() { + Jedis jedis = null; + try { + jedis = getJedis(); + return jedis.flushDB(); + } finally { + returnJedies(jedis); + } + } + + /** + * 查看redis里有多少数据 + */ + public long dbSize() { + Jedis jedis = null; + try { + jedis = getJedis(); + return jedis.dbSize(); + } finally { + returnJedies(jedis); + } + } + + /** + * 检查是否连接成功 + * + * @return + */ + public String ping() { + Jedis jedis = null; + try { + jedis = getJedis(); + return jedis.ping(); + } finally { + returnJedies(jedis); + } + } +} diff --git a/boot-service/src/main/java/com/xwbing/redis/RedisStartupInit.java b/boot-service/src/main/java/com/xwbing/redis/RedisStartupInit.java new file mode 100644 index 0000000..c664a00 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/redis/RedisStartupInit.java @@ -0,0 +1,44 @@ +package com.xwbing.redis; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.PropertySource; +import org.springframework.stereotype.Component; + +import java.util.Iterator; +import java.util.Set; + +/** + * 说明: 启动时刷新redis缓存 + * 项目名称: sbdemo + * 创建时间: 2017/5/5 16:44 + * 作者: xiangwb + */ +@Component +@PropertySource("classpath:redis.properties")//只能读取properties文件 +public class RedisStartupInit implements InitializingBean { + private final Logger logger = LoggerFactory.getLogger(RedisStartupInit.class); + @Autowired + private RedisService redisService; + @Value("${redisCode}") + private String redisCode; + + public void afterPropertiesSet() throws Exception { + logger.info("redis has been start"); + System.out.println("---------启动执行方法---刷新缓存----------------"); + redisService.set("xwb", "测试数据"); + System.out.printf(redisService.get("xwb")); + redisService.del("xwb"); + System.out.printf(String.valueOf(redisService.exists("xwb"))); + Set set = redisService.keys(redisCode + "*"); + Iterator it = set.iterator(); + while (it.hasNext()) { + String keyStr = it.next(); + System.out.println("启动删除缓存名称==" + keyStr); + redisService.delInit(keyStr); + } + } +} diff --git a/boot-service/src/main/java/com/xwbing/repository/AuthorityRepository.java b/boot-service/src/main/java/com/xwbing/repository/AuthorityRepository.java new file mode 100644 index 0000000..dfce6b2 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/repository/AuthorityRepository.java @@ -0,0 +1,10 @@ +package com.xwbing.repository; + +import com.xwbing.domain.SysAuthority; +import org.springframework.data.jpa.repository.JpaRepository; + +/** + * + */ +public interface AuthorityRepository extends JpaRepository { +} diff --git a/boot-service/src/main/java/com/xwbing/repository/RoleRepository.java b/boot-service/src/main/java/com/xwbing/repository/RoleRepository.java new file mode 100644 index 0000000..6fdbece --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/repository/RoleRepository.java @@ -0,0 +1,10 @@ +package com.xwbing.repository; + +import com.xwbing.domain.SysRole; +import org.springframework.data.jpa.repository.JpaRepository; + +/** + * Created by admin on 2017/4/11. + */ +public interface RoleRepository extends JpaRepository { +} diff --git a/boot-service/src/main/java/com/xwbing/repository/SysConfigRepository.java b/boot-service/src/main/java/com/xwbing/repository/SysConfigRepository.java new file mode 100644 index 0000000..3a1671a --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/repository/SysConfigRepository.java @@ -0,0 +1,15 @@ +package com.xwbing.repository; + +import com.xwbing.domain.SysConfig; +import org.springframework.data.jpa.repository.JpaRepository; + +/** + * 浙江卓锐科技股份有限公司 版权所有 ? Copyright 2016
+ * 说明:
+ * 项目名称: ${project_name}
+ * 创建日期: ${date} ${time}
+ * 作者: wdz + */ +public interface SysConfigRepository extends JpaRepository { + SysConfig findByCode(String code); +} diff --git a/boot-service/src/main/java/com/xwbing/repository/UserRepository.java b/boot-service/src/main/java/com/xwbing/repository/UserRepository.java new file mode 100644 index 0000000..473bb58 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/repository/UserRepository.java @@ -0,0 +1,11 @@ +package com.xwbing.repository; + +import com.xwbing.domain.SysUser; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface UserRepository extends JpaRepository { + List findByUserName(String userName); + +} diff --git a/boot-service/src/main/java/com/xwbing/service/BaseService.java b/boot-service/src/main/java/com/xwbing/service/BaseService.java new file mode 100644 index 0000000..d142fa6 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/service/BaseService.java @@ -0,0 +1,68 @@ +package com.xwbing.service; + +import com.xwbing.util.RestMessage; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Objects; + +/** + * 说明: + * 项目名称: sbdemo + * 创建时间: 2017/5/5 16:44 + * 作者: xiangwb + */ +@Service +public class BaseService { + private JpaRepository jpaRepository; + + /** + * 增 + * @param t + * @return + */ + public RestMessage saveOrUpdate(T t){ + RestMessage result=new RestMessage(); + t=jpaRepository.save(t); + if(Objects.isNull(t)){ + result.setMsg("保存数据失败"); + }else { + result.setSuccess(true); + result.setMsg("保存数据成功"); + } + return result; + } + + /** + * 删 + * @param id + * @return + */ + public RestMessage removeById(String id){ + RestMessage result=new RestMessage(); + jpaRepository.delete(id); + result.setSuccess(true); + result.setMsg("删除数据成功"); + return result; + } + + /** + * 单个查找 + * @param id + * @return + */ + public T findById(String id){ + T t=jpaRepository.findOne(id); + return t; + } + + /** + * 列表超找 + * @return + */ + public List findList(){ + List list=jpaRepository.findAll(); + return list; + } +} diff --git a/boot-service/src/main/java/com/xwbing/service/MailService.java b/boot-service/src/main/java/com/xwbing/service/MailService.java new file mode 100644 index 0000000..80b939d --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/service/MailService.java @@ -0,0 +1,138 @@ +package com.xwbing.service; + +import com.xwbing.exception.BusinessException; +import com.xwbing.util.RestMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.FileSystemResource; +import org.springframework.mail.SimpleMailMessage; +import org.springframework.mail.javamail.JavaMailSender; +import org.springframework.mail.javamail.MimeMessageHelper; +import org.springframework.stereotype.Service; + +import javax.mail.MessagingException; +import javax.mail.internet.MimeMessage; +import java.io.File; + +/** + * 项目名称: sb-demo + * 创建时间: 2017/9/18 11:31 + * 作者: xiangwb + * 说明: mail服务层 + */ +@Service +public class MailService { + @Autowired + private JavaMailSender mailSender; + @Value("${spring.mail.username}") + private String from; + + /** + * 发送纯文本的简单邮件 + * + * @param to 收件人 + * @param subject 主题 + * @param content 文本内容 + */ + public RestMessage sendSimpleMail(String to, String subject, String content) { + RestMessage restMessage = new RestMessage(); + SimpleMailMessage message = new SimpleMailMessage(); + message.setFrom(from); + message.setTo(to); + message.setSubject(subject); + message.setText(content); + mailSender.send(message); + restMessage.setSuccess(true); + restMessage.setMsg("纯文本邮件已经发送"); + return restMessage; + } + + /** + * 发送html格式的邮件 + * + * @param to 收件人 + * @param subject 主题 + * @param content 文本内容 + */ + public RestMessage sendHtmlMail(String to, String subject, String content) { + RestMessage restMessage = new RestMessage(); + MimeMessage message = mailSender.createMimeMessage(); + try { + //true表示需要创建一个multipart message + MimeMessageHelper helper = new MimeMessageHelper(message, true); + helper.setFrom(from); + helper.setTo(to); + helper.setSubject(subject); + helper.setText(content, true);//启用html + mailSender.send(message); + restMessage.setSuccess(true); + restMessage.setMsg("html邮件已经发送!"); + return restMessage; + } catch (MessagingException e) { + throw new BusinessException("发送html邮件时发生异常"); + } + } + + /** + * 发送带附件的邮件 + * + * @param to 收件人 + * @param subject 主题 + * @param content 文本内容 + * @param rscPath 附件文件路径 + */ + public RestMessage sendAttachmentsMail(String to, String subject, String content, String rscPath) { + RestMessage restMessage = new RestMessage(); + MimeMessage message = mailSender.createMimeMessage(); + try { + //true表示需要创建一个multipart message + MimeMessageHelper helper = new MimeMessageHelper(message, true); + helper.setFrom(from); + helper.setTo(to); + helper.setSubject(subject); + helper.setText(content, true); + //添加附件1 + FileSystemResource file = new FileSystemResource(new File(rscPath)); + String fileName = rscPath.substring(rscPath.lastIndexOf(File.separator) + 1); + helper.addAttachment(fileName, file); + // 可以继续添加附件。。。。。 + mailSender.send(message);//发送邮件 + restMessage.setSuccess(true); + restMessage.setMsg("带附件的邮件已经发送!"); + return restMessage; + } catch (MessagingException e) { + throw new BusinessException("发送带附件的邮件时发生异常"); + } + } + + /** + * 发送嵌入静态资源(一般是图片)的邮件 + * + * @param to 收件人 + * @param subject 主题 + * @param content 邮件内容,需要包括一个静态资源的id,比如: + * @param rscPath 静态资源路径和文件名 + * @param rscId 静态资源id + */ + public RestMessage sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) { + RestMessage restMessage = new RestMessage(); + MimeMessage message = mailSender.createMimeMessage(); + try { + //true表示需要创建一个multipart message + MimeMessageHelper helper = new MimeMessageHelper(message, true); + helper.setFrom(from); + helper.setTo(to); + helper.setSubject(subject); + helper.setText(content, true); + //添加多个图片可以使用多条 和 helper.addInline(rscId, res) 来实现 + FileSystemResource res = new FileSystemResource(new File(rscPath)); + helper.addInline(rscId, res); + mailSender.send(message); + restMessage.setSuccess(true); + restMessage.setMsg("嵌入静态资源的邮件已经发送!"); + return restMessage; + } catch (MessagingException e) { + throw new BusinessException("发送嵌入静态资源的邮件时发生异常!"); + } + } +} diff --git a/boot-service/src/main/java/com/xwbing/service/SysConfigService.java b/boot-service/src/main/java/com/xwbing/service/SysConfigService.java new file mode 100644 index 0000000..ad19109 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/service/SysConfigService.java @@ -0,0 +1,65 @@ +package com.xwbing.service; + +import com.xwbing.domain.SysConfig; +import com.xwbing.exception.BusinessException; +import com.xwbing.repository.SysConfigRepository; +import com.xwbing.util.PassWordUtil; +import com.xwbing.util.RestMessage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Date; +import java.util.Objects; + +/** + * 说明: + * 项目名称: sbdemo + * 创建时间: 2017/5/5 16:44 + * 作者: xiangwb + */ +@Service +public class SysConfigService { + @Autowired + private SysConfigRepository sysConfigRepository; + private static Logger logger= LoggerFactory.getLogger(SysConfigService.class); + public RestMessage save(SysConfig sysConfig) { + logger.info("保存配置信息"); + RestMessage result = new RestMessage(); + sysConfig.setId(PassWordUtil.createId()); + sysConfig.setCreateTime(new Date()); + if (Objects.isNull(sysConfig)) { + throw new BusinessException("配置数据不能为空"); + } + SysConfig old = findByCode(sysConfig.getCode()); + if (Objects.nonNull(old)) { + throw new BusinessException(sysConfig.getCode() + "已存在"); + } + SysConfig one = sysConfigRepository.save(sysConfig); + if (Objects.nonNull(one)) { + result.setSuccess(true); + result.setMsg("保存配置成功"); + } else { + result.setMsg("保存配置失败"); + } + return result; + } + + public RestMessage removeByCode(String code) { + logger.info("删除配置信息"); + RestMessage result = new RestMessage(); + SysConfig old = findByCode(code); + if (Objects.isNull(old)) { + throw new BusinessException("该配置项不存在"); + } + sysConfigRepository.delete(old.getId()); + result.setSuccess(true); + result.setMsg("删除配置成功"); + return result; + } + + public SysConfig findByCode(String code) { + return sysConfigRepository.findByCode(code); + } +} diff --git a/boot-service/src/main/java/com/xwbing/service/UserService.java b/boot-service/src/main/java/com/xwbing/service/UserService.java new file mode 100644 index 0000000..d8526a0 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/service/UserService.java @@ -0,0 +1,183 @@ +package com.xwbing.service; + +import com.alibaba.fastjson.JSONObject; +import com.xwbing.constant.CommonConstant; +import com.xwbing.constant.CommonEnum; +import com.xwbing.domain.SysConfig; +import com.xwbing.domain.SysUser; +import com.xwbing.domain.model.EmailModel; +import com.xwbing.exception.BusinessException; +import com.xwbing.repository.UserRepository; +import com.xwbing.util.*; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Date; +import java.util.List; +import java.util.Objects; + +/** + * 说明: + * 项目名称: sbdemo + * 创建时间: 2017/5/5 16:44 + * 作者: xiangwb + */ +@Service +public class UserService { + @Autowired + private UserRepository userRepository; + @Autowired + private SysConfigService sysConfigService; + + /** + * 增 + * @param sysUser + * @return + */ + public RestMessage save(SysUser sysUser) { + RestMessage result = new RestMessage(); + SysUser old = findByUserName(sysUser.getUserName()); + if (Objects.nonNull(old)) { + throw new BusinessException("已经存在此用户名"); + } + sysUser.setId(PassWordUtil.createId()); + sysUser.setCreateTime(new Date()); + // 设置否管理员 + sysUser.setIsAdmin(CommonEnum.YesOrNo.NO.getCode()); + // 获取初始密码 + String[] res = PassWordUtil.getUserSecret(null, null); + sysUser.setSalt(res[1]); + sysUser.setPassword(res[2]); + SysUser one = userRepository.save(sysUser); + if (Objects.isNull(one)) { + throw new BusinessException("新增用户失败"); + } + SysConfig sysConfig = sysConfigService.findByCode(CommonConstant.SYSCONFIG_EMAILCONFIGKEY); + if (Objects.isNull(sysConfig)) { + throw new BusinessException("没有查找到邮件配置项"); + } + EmailModel emailModel = null; + if (StringUtils.isNotEmpty(sysConfig.getCode())) { + JSONObject jsonObject = JSONObject.parseObject(sysConfig.getValue()); + emailModel = JSONObject.toJavaObject(jsonObject, EmailModel.class); + } + emailModel.setToEmail(sysUser.getMail()); + emailModel.setSubject(emailModel.getSubject()); + emailModel.setCentent(emailModel.getCentent() + " 你的用户名是:" + sysUser.getUserName() + "密码是:" + res[0]); + // 发送邮件结束 + boolean sucess = EmailUtil.sendTextEmail(emailModel); + if (!sucess) { + throw new BusinessException("发送密码邮件错误"); + } + result.setSuccess(true); + return result; + } + + /** + * 删 + * @param id + * @return + */ + public RestMessage removeById(String id) { + RestMessage result = new RestMessage(); + SysUser old=findOne(id); + if(Objects.isNull(old)){ + throw new BusinessException("该对象不存在"); + } + if (CommonEnum.YesOrNo.YES.getCode().equalsIgnoreCase(old.getIsAdmin())) { + throw new BusinessException("不能对管理员进行删除操作"); + } + userRepository.delete(id); + result.setSuccess(true); + return result; + + } + + /** + * 更新 + * @param sysUser + * @return + */ + public RestMessage update(SysUser sysUser){ + RestMessage result=new RestMessage(); + SysUser old=findOne(sysUser.getId()); + if(Objects.isNull(old)){ + throw new BusinessException("该对象不存在"); + } + // 根据实际情况补充 + old.setName(sysUser.getName()); + old.setMail(sysUser.getMail()); + old.setSex(sysUser.getSex()); + old.setUserName(sysUser.getUserName()); + SysUser one=userRepository.save(old); + if(Objects.nonNull(one)){ + result.setMsg("更新用户成功"); + result.setSuccess(true); + }else { + result.setMsg("更新用户失败"); + } + return result; + } + /** + * 单个查询 + * @param id + * @return + */ + public SysUser findOne(String id) { + return userRepository.findOne(id); + } + + /** + * 列表查询 + * @return + */ + public List findList() { + List list = null; + list = userRepository.findAll(); + return list; + } + + /** + * 根据用户名查找用户 + * + * @param userName + * @return + */ + public SysUser findByUserName(String userName) { + SysUser sysUser = null; + List list = userRepository.findByUserName(userName); + if (CollectionUtils.isNotEmpty(list)) { + sysUser = list.get(0); + } + return sysUser; + } + public RestMessage updatePassWord(String newPassWord, String oldPassWord, + String loginUserId){ + RestMessage result=new RestMessage(); + SysUser sysUser=findOne(loginUserId); + // 根据密码盐值, 解码 + byte[] salt = EncodeUtils.hexDecode(sysUser.getSalt()); + byte[] hashPassword = Digests.sha1(oldPassWord.getBytes(), salt, + SysUser.HASH_INTERATIONS); + // 密码 数据库中密码 + String validatePassWord = EncodeUtils.hexEncode(hashPassword); + if (!Objects.equals(validatePassWord,sysUser.getPassword())) {// 如果不相等 + throw new BusinessException("原密码错误,请重新输入"); + } + String[] str = PassWordUtil.getUserSecret(newPassWord, null); + sysUser.setSalt(str[1]); + sysUser.setPassword(str[2]); + SysUser one=userRepository.save(sysUser); + if(Objects.nonNull(one)){ + result.setMsg("更新密码成功"); + result.setSuccess(true); + }else { + result.setMsg("更新密码失败"); + } + return result; + + } + +} diff --git a/boot-service/src/main/java/com/xwbing/util/DateUtil2.java b/boot-service/src/main/java/com/xwbing/util/DateUtil2.java new file mode 100644 index 0000000..9817a16 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/util/DateUtil2.java @@ -0,0 +1,483 @@ +package com.xwbing.util; + + +import com.xwbing.exception.BusinessException; + +import java.text.DecimalFormat; +import java.text.ParseException; +import java.time.*; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.time.temporal.TemporalAdjusters; +import java.util.*; + +/** + * 创建时间: 2017/1/9 17:11 + * 作者: xiangwb + * 说明: 日期处理类 + */ +public class DateUtil2 { + public static DecimalFormat df = new DecimalFormat("######0.00"); + public static final long SECOND = 1000; + public static final long MINUTE = SECOND * 60; + public static final long HOUR = MINUTE * 60; + public static final long DAY = HOUR * 24; + public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; + public static final String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm"; + public static final String YYYY_MM_DD = "yyyy-MM-dd"; + public static final String YYYY_MM = "yyyy-MM"; + public static final String YYYY = "yyyy"; + public static final String HH_MM_SS = "HH:mm:ss"; + public static final String HH_MM = "HH:mm"; + /* + * ChronoUnit:各种时间单位 | TemporalAdjusters:时态对象 可以获取第一天,最后一天等 + * 获取时间分量:Duration要求是localDateTime/localTime类型 | Period要求是localDate类型 + * Instant类似于date,可以互转 + */ + + /** + * 格式化 + * + * @param pattern + * @return + */ + private static DateTimeFormatter getDateFormat(String pattern) { + return DateTimeFormatter.ofPattern(pattern); + } + + ////////////////////////基本转换///////////////////////////////基本转换///////////////////////////////////////// + + /** + * data转string + * + * @param date + * @param pattern + * @return + */ + public static String dateToStr(Date date, String pattern) { + Instant instant = date.toInstant(); + LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); + return dateTime.format(getDateFormat(pattern)); + } + + /** + * string转date + * + * @param dateStr + * @param pattern + * @return + */ + public static Date strToDate(String dateStr, String pattern) { + LocalDateTime localDateTime; + Instant instant; + if (dateStr.length() < 10) { + throw new BusinessException("时间格式错误:" + dateStr); + } + if (dateStr.length() == 10) { + dateStr += " 00:00:00"; + localDateTime = LocalDateTime.parse(dateStr, getDateFormat(YYYY_MM_DD_HH_MM_SS)); + instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant(); + } else { + localDateTime = LocalDateTime.parse(dateStr, getDateFormat(pattern)); + instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant(); + } + return Date.from(instant); + } + + /** + * 将毫秒转换为时间字符串 + * + * @param ms + * @param pattern + * @return + */ + public static String msToDateStr(String ms, String pattern) { + Instant instant = Instant.ofEpochMilli(Long.valueOf(ms)); + LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); + return dateTime.format(getDateFormat(pattern)); + } + + /** + * 将时间戳转换为时间字符串 + * + * @param s + * @param pattern + * @return + */ + public static String stampToDateStr(String s, String pattern) { + Instant instant = Instant.ofEpochSecond(Long.valueOf(s)); + LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); + return dateTime.format(getDateFormat(pattern)); + } + + /** + * 将时间字符串转为毫秒字符串 + * + * @param dateStr + * @return + */ + public static String dateStrToMs(String dateStr) { + LocalDateTime localDateTime = LocalDateTime.parse(dateStr, getDateFormat(YYYY_MM_DD_HH_MM_SS)); + long epochMilli = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); + return String.valueOf(epochMilli); + } + + /** + * 将时间字符串转为时间戳 + * + * @param dateStr + * @return + */ + public static String dateStrToStamp(String dateStr) { + LocalDateTime localDateTime = LocalDateTime.parse(dateStr, getDateFormat(YYYY_MM_DD_HH_MM_SS)); + long epochSecond = localDateTime.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond(); + return String.valueOf(epochSecond); + } + + /////////////////////////////获取数据////////////获取数据///////////////////////////////////////////////////////////// + + /** + *获取周几 + * @param day 0代表当天 负数代表前几天 正数代表后几天 + * @return + */ + public static int getWeek(int day) { + LocalDate localDate = LocalDate.now(); + LocalDate date = day >= 0 ? localDate.plusDays(day) : localDate.minusDays(Math.abs(day)); + return date.getDayOfWeek().getValue(); + } + + /** + * 获取周几 + * + * @param day 0代表当天 负数代表前几天 正数代表后几天 + * @return + */ + public static String getWeek2(int day) { + LocalDate localDate = LocalDate.now(); + LocalDate date = day >= 0 ? localDate.plusDays(day) : localDate.minusDays(Math.abs(day)); + int week = date.getDayOfWeek().getValue(); + String[] data = {"一", "二", "三", "四", "五", "六", "日"}; + return "周" + data[week - 1]; + } + + /** + * 获取n分钟前/后时间字符串 + * 返回格式:HH_MM_SS/HH_MM + * + * @param time 格式:hh:mm/hh:mm:ss + * @param minute 分钟 + * @return + */ + public static String timeAddMinusMinutes(String time, int minute) { + LocalTime localTime = LocalTime.parse(time); + LocalTime nowLocalTime = minute >= 0 ? localTime.plusMinutes(minute) : localTime.minusMinutes(Math.abs(minute)); + return nowLocalTime.toString(); + } + + /** + * 获取n小时前/后的时间字符串 + * 返回格式:hh:mm + * + * @param time 格式 hh:mm + * @param h + * @return + */ + public static String timeAddMinusHours(String time, int h) { + LocalTime localTime = LocalTime.parse(time); + LocalTime newTime = h >= 0 ? localTime.plusHours(h) : localTime.minusHours(Math.abs(h)); + return newTime.toString(); + } + + /** + * 获取n天前/后日期 + * 返回格式:YYYY_MM_DD + * + * @param date + * @param day + * @return + */ + public static String dateAddMinusDays(String date, int day) { + LocalDate localDate = LocalDate.parse(date, getDateFormat(YYYY_MM_DD)); + LocalDate newDate = day >= 0 ? localDate.plusDays(day) : localDate.minusDays(Math.abs(day)); + return newDate.toString(); + } + + + /** + * 获取当月的第一天 + * + * @return + */ + public static String firstDayOfMonth() { + LocalDate localDate = LocalDate.now(); + LocalDate date = localDate.with(TemporalAdjusters.firstDayOfMonth()); + return date.format(getDateFormat(YYYY_MM_DD)); + } + + /** + * 获取上个月第一天 + * + * @return + */ + public static String firstDayOfLastMonth() { + LocalDate localDate = LocalDate.now(); + LocalDate date = localDate.minusMonths(1).with(TemporalAdjusters.firstDayOfMonth()); + return date.format(getDateFormat(YYYY_MM_DD)); + } + + /** + * 获取下个月第一天 + * + * @return + */ + public static String firstDayOfNextMonth() { + LocalDate localDate = LocalDate.now(); + LocalDate date = localDate.plusMonths(1).with(TemporalAdjusters.firstDayOfMonth()); + return date.format(getDateFormat(YYYY_MM_DD)); + } + + /** + * 获取指定月份第一天 + * + * @param month YYYY-MM + * @return + */ + public static String getMonthFirstDay(int month) { + LocalDate localDate = LocalDate.now().withMonth(month).with(TemporalAdjusters.firstDayOfMonth()); + return localDate.format(getDateFormat(YYYY_MM_DD)); + } + + /** + * 获取当年的第一天 + * + * @return + */ + public static String firstDayOfYear() { + LocalDate localDate = LocalDate.now(); + LocalDate date = localDate.with(TemporalAdjusters.firstDayOfYear()); + return date.format(getDateFormat(YYYY_MM_DD)); + } + + /** + * 获取某年第一天日期 + * + * @param year 年份 + * @return Date + */ + public static String getYearFirstDay(int year) { + LocalDate localDate = LocalDate.now(); + LocalDate date = localDate.withYear(year).with(TemporalAdjusters.firstDayOfYear()); + return date.format(getDateFormat(YYYY_MM_DD)); + } + + /** + * 遍历获取月份集合 + * + * @param startMoth YYYY-MM + * @param endMonth YYYY-MM + * @return + * @throws ParseException + */ + public static List listYearMonth(String startMoth, String endMonth) { + LocalDate start = LocalDate.parse(startMoth + "-01"); + LocalDate end = LocalDate.parse(endMonth + "-01"); + List list = new ArrayList<>(); + if (startMoth.equals(endMonth)) { + list.add(startMoth); + return list; + } + long m = ChronoUnit.MONTHS.between(start, end); + list.add(start.toString()); + for (long i = 1; i <= m; i++) { + list.add(start.plusMonths(i).format(getDateFormat(YYYY_MM))); + } + return list; + } + + /** + * 遍历获取两个日期之间天数集合 + * + * @param startDate + * @param endDate + * @return + * @throws Exception + */ + public static List listDate(String startDate, String endDate) { + List dateList = new ArrayList<>(); + LocalDate start = LocalDate.parse(startDate); + LocalDate end = LocalDate.parse(endDate); + long d = ChronoUnit.DAYS.between(start, end); + dateList.add(start.toString()); + for (long i = 1; i <= d; i++) { + dateList.add(start.plusDays(i).toString()); + } + return dateList; + } + + /////////////////////////////比较////////////相差////////////排序///////////////////////////////////////////////////////////// + + /** + * 比较时间字符串大小 + * + * @param str1 + * @param str2 + * @return + */ + public static boolean compareDate(String str1, String str2) { + long longstr1 = Long.valueOf(str1.replaceAll("[-\\s:]", "")); + long longstr2 = Long.valueOf(str2.replaceAll("[-\\s:]", "")); + return longstr1 >= longstr2; + } + + /** + * 比较两个时间相差几小时(不隔天) + * + * @param startTime 09:00 + * @param endTime 13:00 + */ + public static String hoursBetween1(String startTime, String endTime) { + LocalTime sTime = LocalTime.parse(startTime); + LocalTime eTime = LocalTime.parse(endTime); + Duration duration = Duration.between(sTime, eTime); + long m = duration.toMinutes(); + return df.format(m / 60.0); + } + + /** + * 比较两个时间相差几小时(隔天) + * + * @param startDateTime 2016-11-11 10:00 + * @param endDateTime 2016-11-12 10:00 + * @return + */ + public static String hoursBetween2(String startDateTime, String endDateTime) { + LocalDateTime sDateTime = LocalDateTime.parse(startDateTime); + LocalDateTime eDateTime = LocalDateTime.parse(endDateTime); + Duration duration = Duration.between(sDateTime, eDateTime); + long m = duration.toMinutes(); + return df.format(m / 60.0); + } + + /** + * 比较两个日期相差的天数 + * + * @param startDate + * @param endDate + * @return + */ + public static long daysBetween(String startDate, String endDate) { + LocalDate start = LocalDate.parse(startDate); + LocalDate end = LocalDate.parse(endDate); + return ChronoUnit.DAYS.between(start, end); + } + + /** + * 比较两个日期相差的月数 + * + * @param startDate + * @param endDate + * @return + */ + public static long monthBetween(String startDate, String endDate) { + LocalDate start = LocalDate.parse(startDate); + LocalDate end = LocalDate.parse(endDate); + return ChronoUnit.MONTHS.between(start, end); + } + + /** + * 比较两个日期相差的年数 + * + * @param startDate + * @param endDate + * @return + */ + public static long yearsBetween(String startDate, String endDate) { + LocalDate start = LocalDate.parse(startDate); + LocalDate end = LocalDate.parse(endDate); + return ChronoUnit.YEARS.between(start, end); + } + + /** + * 获取两个时间差(时间分量:日时分秒) + * + * @param startDateTime + * @param endDateTime + * @return + */ + public static Map getDateTimePool(String startDateTime, + String endDateTime) { + LocalDateTime sDateTime = LocalDateTime.parse(startDateTime, + getDateFormat(YYYY_MM_DD_HH_MM_SS)); + LocalDateTime eDateTime = LocalDateTime.parse(endDateTime, + getDateFormat(YYYY_MM_DD_HH_MM_SS)); + Duration duration = Duration.between(sDateTime, eDateTime); + long diff = duration.toMillis(); + long diffSeconds = diff / SECOND % 60; + long diffMinutes = diff / MINUTE % 60; + long diffHours = diff / HOUR % 24; + long diffDays = diff / DAY; + Map map = new HashMap<>(); + map.put("days", (int) diffDays); + map.put("hours", (int) diffHours); + map.put("minutes", (int) diffMinutes); + map.put("seconds", (int) diffSeconds); + return map; + } + + /** + * 获取两个时间差(时间分量:年月日) + * + * @param startDate + * @param endDate + * @return + */ + public static Map getDatePool(String startDate, String endDate) { + LocalDate sDate = LocalDate.parse(startDate); + LocalDate eDate = LocalDate.parse(endDate); + Period period = Period.between(sDate, eDate); + Map map = new HashMap<>(); + map.put("years", period.getYears()); + map.put("months", period.getMonths()); + map.put("days", period.getDays()); + return map; + } + + /** + * 字符串类型日期集合排序 + * + * @param list + * @return + */ + public static List shortListDate(List list) { + Collections.sort(list); + return list; + } + + /** + * 判断两者时间是否重合 重合返回true + * + * @param compareSTime 比较的时间段 09:00 + * @param compareETime 比较的时间段 13:00 + * @param needSTime 需要的时间段 09:00 + * @param needETime 需要的时间段 13:00 + * @return + */ + public static boolean compare(String compareSTime, String compareETime, + String needSTime, String needETime) { + if (needSTime.compareTo(compareETime) == 0 + || needETime.compareTo(compareSTime) == 0)// 表示开始时间等于结束时间,或者结束时间等于开始时间 + return false; + if (needSTime.compareTo(compareSTime) >= 0 + && needSTime.compareTo(compareETime) < 0)// 需要时间开始时间在比较时间之间,表示已经重复了 + return true; + if (needETime.compareTo(compareSTime) > 0 + && needETime.compareTo(compareETime) <= 0) {// 需要时间结束时间在比较时间之间,表示已经重复了 + return true; + } + if (needSTime.compareTo(compareSTime) < 0 + && needETime.compareTo(compareETime) > 0)// 需要时间在比较时间前后,表示已经重复了 + return true; + return false; + } +} diff --git a/boot-service/src/main/java/com/xwbing/util/Digests.java b/boot-service/src/main/java/com/xwbing/util/Digests.java new file mode 100644 index 0000000..885f23a --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/util/Digests.java @@ -0,0 +1,100 @@ + +package com.xwbing.util; + +import java.io.IOException; +import java.io.InputStream; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.SecureRandom; + +/** + * 说明:散列算法(哈希算法) + * 创建日期: 2016年11月29日 上午10:31:20 + * 作者: xiangwb + */ +public class Digests { + + private static final String SHA1 = "SHA-1"; + private static final String MD5 = "MD5"; + + private static SecureRandom random = new SecureRandom(); + + /** + * 对输入字符串进行sha1散列. + */ + public static byte[] sha1(byte[] input) { + return digest(input, SHA1, null, 1); + } + + public static byte[] sha1(byte[] input, byte[] salt) { + return digest(input, SHA1, salt, 1); + } + + public static byte[] sha1(byte[] input, byte[] salt, int iterations) { + return digest(input, SHA1, salt, iterations); + } + + /** + * 对字符串进行散列, 支持md5与sha1算法. + */ + private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) { + try { + MessageDigest digest = MessageDigest.getInstance(algorithm); + if (salt != null) { + digest.update(salt); + } + byte[] result = digest.digest(input); + for (int i = 1; i < iterations; i++) { + digest.reset(); + result = digest.digest(result); + } + return result; + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + /** + * 生成随机的Byte[]作为salt. + * + * @param numBytes byte数组的大小 + */ + public static byte[] generateSalt(int numBytes) { + if (numBytes <= 0) { + throw new RuntimeException("numBytes argument must be a positive integer (1 or larger)"); + } + byte[] bytes = new byte[numBytes]; + random.nextBytes(bytes); + return bytes; + } + + /** + * 对文件进行md5散列. + */ + public static byte[] md5(InputStream input) throws IOException { + return digest(input, MD5); + } + + /** + * 对文件进行sha1散列. + */ + public static byte[] sha1(InputStream input) throws IOException { + return digest(input, SHA1); + } + + private static byte[] digest(InputStream input, String algorithm) throws IOException { + try { + MessageDigest messageDigest = MessageDigest.getInstance(algorithm); + int bufferLength = 8 * 1024; + byte[] buffer = new byte[bufferLength]; + int read = input.read(buffer, 0, bufferLength); + while (read > -1) { + messageDigest.update(buffer, 0, read); + read = input.read(buffer, 0, bufferLength); + } + return messageDigest.digest(); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } +} diff --git a/boot-service/src/main/java/com/xwbing/util/EmailUtil.java b/boot-service/src/main/java/com/xwbing/util/EmailUtil.java new file mode 100644 index 0000000..9838759 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/util/EmailUtil.java @@ -0,0 +1,145 @@ +package com.xwbing.util; + + +import com.xwbing.domain.model.EmailModel; +import com.xwbing.exception.BusinessException; +import org.apache.commons.lang3.StringUtils; + +import javax.mail.*; +import javax.mail.internet.*; +import java.util.Properties; + +/** + * 创建时间: 2016/11/7 10:11 + * 作者: xiangwb + * 说明: 邮箱工具类 + */ +public class EmailUtil { + /** + * 发送邮件 + * + * @param emailModel + * @return + */ + public static boolean sendTextEmail(EmailModel emailModel) { + try { + boolean result = true; + // 1. 创建参数配置, 用于连接邮件服务器的参数配置 + Properties props = new Properties();// 用于连接邮件服务器的参数配置(发送邮件时才需要用到) + String serverHost = emailModel.getServerHost();// 设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器) + if (StringUtils.isEmpty(serverHost)) { + result = false; + throw new BusinessException("发送邮件主机不能为空"); + } + props.setProperty("mail.transport.protocol", + emailModel.getProtocol());// 使用的协议(JavaMail规范要求) + props.setProperty("mail.smtp.host", serverHost); // 发件人的邮箱的 + // SMTP服务器地址 + if (emailModel.getServerPort() != null) { + props.setProperty("mail.smtp.port", emailModel.getServerPort() + "");// 发送邮件服务器端口 + } + props.setProperty("mail.smtp.auth", emailModel.isAuth() + "");// 需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条) + // 2. 根据配置创建会话对象, 用于和邮件服务器交互 + Session session = Session.getDefaultInstance(props);// 用刚刚设置好的props对象构建一个session + session.setDebug(true);// 有了这句便可以在发送邮件的过程中在console处显示过程信息,供调试使 + // 3. 创建一封邮件,真正要发送时, 邮箱必须是真实有效的邮箱。 + MimeMessage message = new MimeMessage(session);// 用session为参数 创建邮件对象 + // From: 发件人 + String fromEmail = emailModel.getFromEmail(); + if (StringUtils.isEmpty(fromEmail)) { + result = false; + throw new BusinessException("发送邮箱不能为空"); + } + message.setFrom(new InternetAddress(emailModel.getFromEmail())); + // To: 收件人 + if (StringUtils.isEmpty(emailModel.getToEmail())) { + result = false; + throw new BusinessException("接收邮箱不能为空"); + } + InternetAddress[] toEmailList = InternetAddress.parse(emailModel + .getToEmail());// toEmail格式为"aaa,bbb,..."或"aaa" + message.setRecipients(Message.RecipientType.TO, toEmailList); + /* + * message.addRecipient(MimeMessage.RecipientType.TO,new + * InternetAddress("xx@xx.com")); // To: 增加收件人(单个)(可选) + * message.setRecipient(MimeMessage.RecipientType.CC,new + * InternetAddress("xx@xx.com")); // Cc: 抄送(可选) + * message.setRecipient(MimeMessage.RecipientType.BCC,new + * InternetAddress("xx@xx.com"));// Bcc: 密送(可选) + */ + // Subject: 邮件主题 + if (StringUtils.isEmpty(emailModel.getSubject())) { + result = false; + throw new BusinessException("邮件主题不能为空"); + } + message.setSubject(emailModel.getSubject()); + // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件 + Multipart multipart = new MimeMultipart(); + // 创建一个包含HTML内容的MimeBodyPart + BodyPart html = new MimeBodyPart(); + // 设置HTML内容 + html.setContent(emailModel.getCentent(), "text/html; charset=utf-8"); + multipart.addBodyPart(html); + message.setContent(multipart); + message.setSentDate(emailModel.getSendTime());// 设置显示的发件时间 + message.saveChanges();// 保存邮件 + // 4.根据 Session 获取邮件传输对象 + Transport transport = session.getTransport("smtp"); + // 5. 使用 邮箱账号 和 密码 连接邮件服务器 + if (StringUtils.isEmpty(emailModel.getPassword())) { + result = false; + throw new BusinessException("发送邮箱密码不能为空"); + } + transport.connect(serverHost, fromEmail, emailModel.getPassword());// 这里认证的邮箱必须与 + // message中的发件人邮箱一致,否则报错 + // 6.发送邮件, 发到所有的收件地址, message.getAllRecipients() + // 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人 + transport.sendMessage(message, message.getAllRecipients()); + // 7. 关闭连接 + transport.close(); + return result; + } catch (AddressException e) { + e.printStackTrace(); + return false; + } catch (MessagingException e) { + e.printStackTrace(); + return false; + } + } + + /** + * 将toemail数组转为"aaa,bbb"格式字符串 + * + * @param toEmailArray + * @return + */ + public static String getMailList(String[] toEmailArray) { + StringBuffer toList = new StringBuffer(); + if (toEmailArray != null && toEmailArray.length > 0) { + for (int i = 0; i < toEmailArray.length; i++) { + if (toList.length() > 0) + toList.append(","); + toList.append(toEmailArray[i]); + } + return toList.toString(); + } + return ""; + } + + public static void main(String[] args) { + EmailModel emailModel = new EmailModel(); + emailModel.setServerHost("smtp.163.com"); + emailModel.setServerPort(25); + emailModel.setProtocol("smtp"); + emailModel.setAuth(true); +// emailModel.setSendTime();默认当前时间 + emailModel.setFromEmail("xwbing2009@163.com"); + emailModel.setToEmail("786461501@qq.com,xiangwb@drore.com"); + emailModel.setAttachFileNames(null); + emailModel.setPassword("xwbing900417"); + emailModel.setSubject("测试邮件"); + emailModel.setCentent("邮件功能测试,请勿回复"); + boolean b = sendTextEmail(emailModel); + System.out.println(b); + } +} diff --git a/boot-service/src/main/java/com/xwbing/util/EncodeUtils.java b/boot-service/src/main/java/com/xwbing/util/EncodeUtils.java new file mode 100644 index 0000000..b4aeb85 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/util/EncodeUtils.java @@ -0,0 +1,107 @@ +package com.xwbing.util; + +import org.apache.commons.codec.DecoderException; +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.codec.binary.Hex; +import org.apache.commons.lang3.StringEscapeUtils; + +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; + +/** + * 说明:编码解码工具类 + * 创建日期: 2016年11月29日 上午10:30:34 + * 作者: xiangwb + */ +public class EncodeUtils { + private static final String DEFAULT_URL_ENCODING = "UTF-8"; + + /** + * Hex编码. + */ + public static String hexEncode(byte[] input) { + return Hex.encodeHexString(input); + } + + /** + * Hex解码. + */ + public static byte[] hexDecode(String input) { + try { + return Hex.decodeHex(input.toCharArray()); + } catch (DecoderException e) { + throw new IllegalStateException("Hex Decoder exception", e); + } + } + + /** + * Base64编码. + */ + public static String base64Encode(byte[] input) { + return new String(Base64.encodeBase64(input)); + /* + * java8新特性 + */ +// return java.util.Base64.getEncoder().encodeToString(input);// + } + + + /** + * Base64编码, URL安全(将Base64中的URL非法字符如+,/=转为其他字符, 见RFC3548). + */ + public static String base64UrlSafeEncode(byte[] input) { + return Base64.encodeBase64URLSafeString(input); + /** + * java8新特性 + */ +// return java.util.Base64.getUrlEncoder().encodeToString(input); + } + + /** + * Base64解码. + */ + public static byte[] base64Decode(String input) { + return Base64.decodeBase64(input); + /* + * java8新特性 + */ +// return java.util.Base64.getDecoder().decode(input); + } + + /** + * URL 编码, Encode默认为UTF-8. + */ + public static String urlEncode(String input) { + try { + return URLEncoder.encode(input, DEFAULT_URL_ENCODING); + } catch (UnsupportedEncodingException e) { + throw new IllegalArgumentException("Unsupported Encoding Exception", e); + } + } + + /** + * URL 解码, Encode默认为UTF-8. + */ + public static String urlDecode(String input) { + try { + return URLDecoder.decode(input, DEFAULT_URL_ENCODING); + } catch (UnsupportedEncodingException e) { + throw new IllegalArgumentException("Unsupported Encoding Exception", e); + } + } + + /** + * Xml 转码. + */ + public static String xmlEscape(String xml) { + return StringEscapeUtils.escapeXml(xml); + } + + /** + * Xml 解码. + */ + public static String xmlUnescape(String xmlEscaped) { + return StringEscapeUtils.unescapeXml(xmlEscaped); + } +} diff --git a/boot-service/src/main/java/com/xwbing/util/JSONObjResult.java b/boot-service/src/main/java/com/xwbing/util/JSONObjResult.java new file mode 100644 index 0000000..a39c45e --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/util/JSONObjResult.java @@ -0,0 +1,56 @@ +package com.xwbing.util; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.serializer.SerializerFeature; +import lombok.Data; + +/** + * 说明: 封装对象结果的json结果 + * 创建日期: 2016年12月14日 下午3:20:05 + * 作者: xiangwb + */ +@Data +public class JSONObjResult { + /** + * 是否成功 + */ + private boolean success; + /*** + * 新增、修改主鍵返回id + */ + private String id; + + /** + * 消息体 + */ + private String message = "未知异常"; + /** + * 返回数据 + */ + private Object data; + + public static JSONObject toJSONObj(Object o, boolean success, String message) { + JSONObjResult jsonObjResult = new JSONObjResult(); + jsonObjResult.setSuccess(success); + jsonObjResult.setMessage(message); + jsonObjResult.setData(JSONUtil.beanToMap(o)); + return JSON.parseObject(JSON.toJSONString(jsonObjResult, SerializerFeature.WriteMapNullValue)); + } + + public static JSONObject toJSONObj(RestMessage rest) { + JSONObjResult jsonObjResult = new JSONObjResult(); + jsonObjResult.setSuccess(rest.isSuccess()); + jsonObjResult.setMessage(rest.getMsg()); + jsonObjResult.setData(JSONUtil.beanToMap(rest.getData())); + jsonObjResult.setId(rest.getId()); + return JSON.parseObject(JSON.toJSONString(jsonObjResult, SerializerFeature.WriteMapNullValue)); + } + + public static JSONObject toJSONObj(String error) { + JSONObjResult jsonObjResult = new JSONObjResult(); + jsonObjResult.setSuccess(false); + jsonObjResult.setMessage(error); + return JSON.parseObject(JSONObject.toJSONString(jsonObjResult, SerializerFeature.WriteMapNullValue)); + } +} diff --git a/boot-service/src/main/java/com/xwbing/util/JSONUtil.java b/boot-service/src/main/java/com/xwbing/util/JSONUtil.java new file mode 100644 index 0000000..dfa2917 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/util/JSONUtil.java @@ -0,0 +1,56 @@ +package com.xwbing.util; + +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.beanutils.PropertyUtilsBean; + +import java.beans.PropertyDescriptor; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 说明: json格式转换 + * 创建日期: 2016年8月16日 下午8:06:01 + * 作者: xiangwb + */ +public class JSONUtil { + /** + * 实体对象不序列化转换成jsonobject + * + * @param obj + * @return + */ + public static Object beanToMap(Object obj) { + if (obj == null) + return null; + if (obj instanceof List) { + List list = (List) obj; + ArrayList result = new ArrayList<>(); + for (Object o : list) { + JSONObject javaObject = (JSONObject) beanToMap(o); + result.add(javaObject); + } + return result; + } else if (obj instanceof JSONObject) { + return obj; + } else if (obj instanceof Map) { + return obj; + } else { + Map params = new HashMap<>(0); + try { + PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean(); + PropertyDescriptor[] descriptors = propertyUtilsBean.getPropertyDescriptors(obj); + for (int i = 0; i < descriptors.length; i++) { + String name = descriptors[i].getName(); + if (!"class".equals(name)) { + params.put(name, propertyUtilsBean.getNestedProperty(obj, name)); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return new JSONObject(params); + } + } +} diff --git a/boot-service/src/main/java/com/xwbing/util/PassWordUtil.java b/boot-service/src/main/java/com/xwbing/util/PassWordUtil.java new file mode 100644 index 0000000..cc2cad6 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/util/PassWordUtil.java @@ -0,0 +1,62 @@ +package com.xwbing.util; +import org.apache.commons.lang3.StringUtils; + +import java.util.UUID; + +/** + * + * 说明:密码工具类 + * 创建日期: 2016年11月29日 上午10:28:36 + * 作者: xiangwb + */ +public class PassWordUtil { + /** + * 初始默认密码长度 + */ + public static final int PWD_LENGTH = 8; + /** + * 密码盐长度 + */ + public static final int SALT_SIZE = 10; + /** + * hash + */ + public static int HASH_INTERATIONS = 1024; + public static void main(String[] args) { + getUserSecret("123456", "123456"); + } + /** + * 传入未加密密码,如果为空,随机生成, 传入盐值, 如果为空,随机生成。 返回密码,盐值,和加密后的密码 + * + * @param password + * @return + */ + public static String[] getUserSecret(String password, String pwdSalt) { + String[] str = new String[3]; + if (StringUtils.isEmpty(password)) + password = RadomUtil.buildRandom(PWD_LENGTH); + // 密码盐值 + byte[] salt; + // 密码盐值 如果是为空,那么随机获取;不为空,解析pwdSalt + if (StringUtils.isEmpty(pwdSalt)) { + salt = Digests.generateSalt(SALT_SIZE); + } else + salt = EncodeUtils.hexDecode(pwdSalt); + // 密码加密 + byte[] hashPassword = Digests.sha1(password.getBytes(), salt, + HASH_INTERATIONS); + str[0] = password; + str[1] = EncodeUtils.hexEncode(salt); + str[2] = EncodeUtils.hexEncode(hashPassword); + return str; + } + + /** + * 生成uuid + * @return + */ + public static String createId(){ + UUID uuid=UUID.randomUUID(); + return uuid.toString().replace("-",""); + } +} diff --git a/boot-service/src/main/java/com/xwbing/util/RadomUtil.java b/boot-service/src/main/java/com/xwbing/util/RadomUtil.java new file mode 100644 index 0000000..73c5282 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/util/RadomUtil.java @@ -0,0 +1,32 @@ +package com.xwbing.util; + +import java.util.Random; + +/** + * 说明:生成随机码 + * 创建日期: 2016年11月29日 上午10:28:21 + * 作者: xiangwb + */ +public class RadomUtil { + + public static String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + + public static String buildRandom(int length) { + if (length < 1) + throw new RuntimeException("参数异常!!!"); + Random random = new Random(); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < length; i++) { + int number = random.nextInt(str.length()); + sb.append(str.charAt(number)); + } + return sb.toString(); + } + + public static void main(String[] args) { + while (true) + System.out.println(buildRandom(8)); + } + + +} diff --git a/boot-service/src/main/java/com/xwbing/util/RestMessage.java b/boot-service/src/main/java/com/xwbing/util/RestMessage.java new file mode 100644 index 0000000..484315c --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/util/RestMessage.java @@ -0,0 +1,73 @@ +package com.xwbing.util; + +import java.io.Serializable; + +/** + * 说明:返回消息封装类 + * 创建日期: 2017年3月3日 上午11:43:13 + * 作者: xiangwb + */ +public class RestMessage implements Serializable { + private static final long serialVersionUID = -4167591341943919542L; + private boolean isSuccess = false;// 默认false + private String msg;// 成功、错误返回提示信息 + private Object data;// 返回的数据 + private String id;// 新增、修改主鍵返回id + private Integer code;//错误码 + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public Object getData() { + return data; + } + + public void setData(Object data) { + this.data = data; + } + + public boolean isSuccess() { + return isSuccess; + } + + public void setSuccess(boolean isSuccess) { + this.isSuccess = isSuccess; + } + + public RestMessage() { + super(); + } + + public RestMessage(Object data) { + super(); + this.data = data; + } + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public RestMessage(boolean isSuccess, Object data) { + super(); + this.isSuccess = isSuccess; + this.data = data; + } + +} diff --git a/boot-service/src/main/java/com/xwbing/util/captcah/CaptchaException.java b/boot-service/src/main/java/com/xwbing/util/captcah/CaptchaException.java new file mode 100644 index 0000000..0b91313 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/util/captcah/CaptchaException.java @@ -0,0 +1,36 @@ +package com.xwbing.util.captcah; + +/** + * 说明:创建验证码异常类 + * 创建日期: 2016年8月29日 上午11:02:42 + * 作者: xiangwb + */ +public class CaptchaException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public CaptchaException() { + + super(); + + } + + public CaptchaException(String message, Throwable cause) { + + super(message, cause); + + } + + public CaptchaException(String message) { + + super(message); + + } + + public CaptchaException(Throwable cause) { + + super(cause); + + } + +} \ No newline at end of file diff --git a/boot-service/src/main/java/com/xwbing/util/captcah/CaptchaServlet.java b/boot-service/src/main/java/com/xwbing/util/captcah/CaptchaServlet.java new file mode 100644 index 0000000..0fc37eb --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/util/captcah/CaptchaServlet.java @@ -0,0 +1,46 @@ +package com.xwbing.util.captcah; + +import javax.imageio.ImageIO; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.io.OutputStream; + +/** + * 说明: 创建验证码的servlet + * 创建日期: 2016年8月29日 上午10:59:27 + * 作者: xiangwb + */ +public class CaptchaServlet extends HttpServlet { + private static final long serialVersionUID = -124247581620199710L; + /* + * 存放session中的值 + */ + public static final String KEY_CAPTCHA = "SE_KEY_MM_CODE"; + + @Override + protected void service(HttpServletRequest req, HttpServletResponse res) { + // 设置相应类型,告诉浏览器输出的内容为图片 + res.setContentType("image/jpeg"); + // 禁止图像缓存。 + res.setHeader("Pragma", "No-cache"); + res.setHeader("Cache-Control", "no-cache"); + res.setDateHeader("Expire", 0); + try { + HttpSession session = req.getSession(); + CaptchaUtil tool = new CaptchaUtil(); + StringBuffer code = new StringBuffer(); + BufferedImage image = tool.genRandomCodeImage(code); + session.removeAttribute(KEY_CAPTCHA); + session.setAttribute(KEY_CAPTCHA, code.toString()); + // 将内存中的图片通过流形式输出到客户端 + OutputStream out = res.getOutputStream(); + ImageIO.write(image, "JPEG", out); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/boot-service/src/main/java/com/xwbing/util/captcah/CaptchaUtil.java b/boot-service/src/main/java/com/xwbing/util/captcah/CaptchaUtil.java new file mode 100644 index 0000000..eef8934 --- /dev/null +++ b/boot-service/src/main/java/com/xwbing/util/captcah/CaptchaUtil.java @@ -0,0 +1,114 @@ +package com.xwbing.util.captcah; + +import javax.imageio.ImageIO; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.FileOutputStream; +import java.util.Random; + +/** + * 说明:验证码工具类 + * 创建日期: 2016年8月29日 上午10:57:41 + * 作者: xiangwb + */ +public class CaptchaUtil { + + // 随机产生的字符串 + private static final String RANDOM_STRS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + private static final String FONT_NAME = "Fixedsys"; + private Random random = new Random(); + private static final int FONT_SIZE = 18;// 字体大小 + private static final int width = 80;// 图片宽 + private static final int height = 25;// 图片高 + private static final int lineNum = 50;// 干扰线数量 + private static final int strNum = 4;// 随机产生字符数量 + + + /** + * 生成随机图片 + */ + public BufferedImage genRandomCodeImage(StringBuffer randomCode) { + // BufferedImage类是具有缓冲区的Image类 + BufferedImage image = new BufferedImage(width, height, + BufferedImage.TYPE_INT_BGR); + // 获取Graphics对象,便于对图像进行各种绘制操作 + Graphics g = image.getGraphics(); + // 设置背景色 + g.setColor(getRandColor(200, 250)); + // 填充矩形面积 + g.fillRect(0, 0, width, height); + // 设置干扰线的颜色 + g.setColor(getRandColor(110, 120)); + // 绘制干扰线 + for (int i = 0; i <= lineNum; i++) { + drowLine(g); + } + // 绘制随机字符 + g.setFont(new Font(FONT_NAME, Font.ROMAN_BASELINE, FONT_SIZE)); + for (int i = 1; i <= strNum; i++) { + randomCode.append(drowString(g, i)); + } + g.dispose(); + return image; + } + + /** + * 给定范围获得随机颜色 + */ + private Color getRandColor(int fc, int bc) { + if (fc > 255) + fc = 255; + if (bc > 255) + bc = 255; + int r = fc + random.nextInt(bc - fc); + int g = fc + random.nextInt(bc - fc); + int b = fc + random.nextInt(bc - fc); + return new Color(r, g, b); + } + + /** + * 绘制字符串 + */ + private String drowString(Graphics g, int i) { + g.setColor(new Color(random.nextInt(101), random.nextInt(111), random + .nextInt(121))); + String rand = String.valueOf(getRandomString(random.nextInt(RANDOM_STRS + .length()))); + g.translate(random.nextInt(3), random.nextInt(3)); + g.drawString(rand, 13 * i, 16); + return rand; + } + + /** + * 绘制干扰线 + */ + private void drowLine(Graphics g) { + int x = random.nextInt(width); + int y = random.nextInt(height); + int x0 = random.nextInt(16); + int y0 = random.nextInt(16); + g.drawLine(x, y, x + x0, y + y0); + } + + /** + * 获取随机的字符 + */ + private String getRandomString(int num) { + return String.valueOf(RANDOM_STRS.charAt(num)); + } + + public static void main(String[] args) { + CaptchaUtil tool = new CaptchaUtil(); + StringBuffer code = new StringBuffer(); + BufferedImage image = tool.genRandomCodeImage(code); + System.out.println(">>> random code =: " + code); + try { + // 将内存中的图片通过流动形式输出到客户端 + ImageIO.write(image, "JPEG", new FileOutputStream(new File( + "random-code.jpg"))); + } catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/boot-service/src/main/resources/redis.properties b/boot-service/src/main/resources/redis.properties new file mode 100644 index 0000000..a529b32 --- /dev/null +++ b/boot-service/src/main/resources/redis.properties @@ -0,0 +1,2 @@ +redisCode=springboot- +systemCode=dataCenter_single \ No newline at end of file diff --git a/boot-web/pom.xml b/boot-web/pom.xml new file mode 100644 index 0000000..d3e5ce7 --- /dev/null +++ b/boot-web/pom.xml @@ -0,0 +1,116 @@ + + + + boot-module-demo + com.xwbing + 1.0 + + 4.0.0 + boot-web + war + + + nexus + drore Team nexus + http://192.168.11.110:8081/nexus/content/groups/public + + + + + nexus + drore Team nexus + http://192.168.11.110:8081/nexus/content/groups/public + + + + + + nexus-drore-team-3rd + http://192.168.11.110:8081/nexus/content/repositories/thirdparty/ + + + + + + com.xwbing + boot-service + 1.0-SNAPSHOT + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-logging + + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.boot + spring-boot-devtools + + + + org.springframework.boot + spring-boot-starter-tomcat + + + + + org.springframework.boot + spring-boot-starter-aop + + + + boot-web + + + org.springframework.boot + spring-boot-maven-plugin + + com.xwbing.Application + true + + + + + org.apache.maven.plugins + maven-war-plugin + 2.4 + + ROOT + false + + + + + org.apache.maven.plugins + maven-source-plugin + 2.4 + + true + + + + compile + + jar + + + + + + + \ No newline at end of file diff --git a/boot-web/src/main/java/com/xwbing/Application.java b/boot-web/src/main/java/com/xwbing/Application.java new file mode 100644 index 0000000..1bbe1b0 --- /dev/null +++ b/boot-web/src/main/java/com/xwbing/Application.java @@ -0,0 +1,24 @@ +package com.xwbing; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.support.SpringBootServletInitializer; + +/** + * 项目名称: boot-module-demo + * 创建时间: 2017/11/2 18:19 + * 作者: xiangwb + * 说明: 启动类 + */ +@SpringBootApplication +public class Application extends SpringBootServletInitializer { + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(Application.class); + } + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/boot-web/src/main/java/com/xwbing/annotation/LogInfo.java b/boot-web/src/main/java/com/xwbing/annotation/LogInfo.java new file mode 100644 index 0000000..e326f97 --- /dev/null +++ b/boot-web/src/main/java/com/xwbing/annotation/LogInfo.java @@ -0,0 +1,16 @@ +package com.xwbing.annotation; + +import java.lang.annotation.*; + +/** + * 说明: 自定义日志信息注解 + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) +@Documented +public @interface LogInfo { + String value() default ""; +} diff --git a/boot-web/src/main/java/com/xwbing/configuration/ApplicationContextConfig.java b/boot-web/src/main/java/com/xwbing/configuration/ApplicationContextConfig.java new file mode 100644 index 0000000..7fe478f --- /dev/null +++ b/boot-web/src/main/java/com/xwbing/configuration/ApplicationContextConfig.java @@ -0,0 +1,33 @@ +package com.xwbing.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +/** + * 说明: 程序上下文配置 + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +@Configuration//相当于.xml文件中的 +//@ComponentScan(value = {"com.xwbing"}, excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class)}) +//@Import(xxx.class)//用来导入其他配置类 +//@ImportResource("classpath:applicationContext.xml")//用来加载其他xml配置文件 +public class ApplicationContextConfig { + /** + * 线程池 + * + * @return + */ + @Bean(name = "taskExecutor")//相当于XML中的 + public static ThreadPoolTaskExecutor getPoolTaskExecutor() { + ThreadPoolTaskExecutor poolTaskExecutor = new ThreadPoolTaskExecutor(); + poolTaskExecutor.setCorePoolSize(5);//核心线程数 + poolTaskExecutor.setMaxPoolSize(1000);//最大线程数 + poolTaskExecutor.setKeepAliveSeconds(30000);//空闲线程的存活时间 + poolTaskExecutor.setQueueCapacity(200);//队列最大长度 + return poolTaskExecutor; + } + +} diff --git a/boot-web/src/main/java/com/xwbing/configuration/DispatcherServletConfig.java b/boot-web/src/main/java/com/xwbing/configuration/DispatcherServletConfig.java new file mode 100644 index 0000000..a528116 --- /dev/null +++ b/boot-web/src/main/java/com/xwbing/configuration/DispatcherServletConfig.java @@ -0,0 +1,100 @@ +package com.xwbing.configuration; + +import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.MediaType; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.web.filter.CharacterEncodingFilter; +import org.springframework.web.multipart.commons.CommonsMultipartResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +import javax.servlet.Filter; +import java.util.ArrayList; +import java.util.List; + +/** + * 说明: 程序配置 + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +@Configuration +@EnableWebMvc +//@ComponentScan(basePackages = {"com.xwbing.controller"}, includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = RestController.class)}) +public class DispatcherServletConfig extends WebMvcConfigurerAdapter { + private static final Logger logger = LoggerFactory.getLogger(DispatcherServletConfig.class); + + /*** + * 添加拦截器 + * @param registry + */ + @Override + public void addInterceptors(InterceptorRegistry registry) { + logger.info("addInterceptors......"); + //拦截器1:登录判断 +// registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**"); +// registry.addInterceptor(new LoginInterceptor()) +// .addPathPatterns("/**").excludePathPatterns("/user/login", "/servlet/captchaCode", "/doc.html", "/swagger-ui.html"); + //拦截器2... + super.addInterceptors(registry); + } + + /** + * 扩展消息转换器,增加fastjson + * + * @param converters + */ + @Override + public void extendMessageConverters(List> converters) { + converters.add(getFastJsonHttpMessageConverter()); + super.configureMessageConverters(converters); + } + + /** + * 请求处理程序映射适配器,使用fastJson + * + * @return + */ + @Bean + public HttpMessageConverter getFastJsonHttpMessageConverter() { + FastJsonHttpMessageConverter httpMessageConverter = new FastJsonHttpMessageConverter(); + List mediaTypes = new ArrayList<>(); + mediaTypes.add(MediaType.TEXT_HTML);//避免IE出现下载JSON文件的情况 + mediaTypes.add(MediaType.APPLICATION_JSON); + mediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED); + mediaTypes.add(MediaType.APPLICATION_OCTET_STREAM); + httpMessageConverter.setSupportedMediaTypes(mediaTypes); + return httpMessageConverter; + } + + /** + * 文件上传解析器 + * + * @return + */ + @Bean + public CommonsMultipartResolver getCommonsMultipartResolver() { + CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); + multipartResolver.setMaxUploadSize(104857600); + multipartResolver.setDefaultEncoding("UTF-8"); + return multipartResolver; + } + + /** + * encoding编码问题 + * + * @return + */ + @Bean + public Filter characterEncodingFilter() { + CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); + characterEncodingFilter.setEncoding("UTF-8"); + characterEncodingFilter.setForceEncoding(true); + return characterEncodingFilter; + } +} diff --git a/boot-web/src/main/java/com/xwbing/configuration/SchedulingConfig.java b/boot-web/src/main/java/com/xwbing/configuration/SchedulingConfig.java new file mode 100644 index 0000000..a80890e --- /dev/null +++ b/boot-web/src/main/java/com/xwbing/configuration/SchedulingConfig.java @@ -0,0 +1,26 @@ +package com.xwbing.configuration; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; + +/** + * 说明: 定时任务定时类 + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +@Configuration +@EnableScheduling // 启用定时任务 +public class SchedulingConfig { + private static final Logger logger = LoggerFactory.getLogger(SchedulingConfig.class); + + @Scheduled(cron = "0 */30 * * * ?") // 每半小时执行一次 + public void scheduler() { + logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> scheduled ... "); + //TODO + } + +} diff --git a/boot-web/src/main/java/com/xwbing/configuration/ServletConfig.java b/boot-web/src/main/java/com/xwbing/configuration/ServletConfig.java new file mode 100644 index 0000000..bd61307 --- /dev/null +++ b/boot-web/src/main/java/com/xwbing/configuration/ServletConfig.java @@ -0,0 +1,30 @@ +package com.xwbing.configuration; + +import com.xwbing.util.captcah.CaptchaServlet; +import org.springframework.boot.web.servlet.ServletRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * 说明: 统一的servlet配置 + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +@Configuration +public class ServletConfig { + @Bean + public CaptchaServlet captchaServlet() { + return new CaptchaServlet(); + } + + @Bean + public ServletRegistrationBean captchaServletRegistrationBean(CaptchaServlet captchaServlet) { + ServletRegistrationBean registration = new ServletRegistrationBean(captchaServlet); + registration.setEnabled(true); + registration.addUrlMappings("/servlet/captchaCode"); + return registration; + } + /********************************************/ + +} diff --git a/boot-web/src/main/java/com/xwbing/configuration/SwaggerConfig.java b/boot-web/src/main/java/com/xwbing/configuration/SwaggerConfig.java new file mode 100644 index 0000000..f1518ad --- /dev/null +++ b/boot-web/src/main/java/com/xwbing/configuration/SwaggerConfig.java @@ -0,0 +1,43 @@ +package com.xwbing.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +/** + * 说明: swagger config + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ + +@Configuration +@EnableSwagger2 +public class SwaggerConfig { + @Bean + public Docket createRestApi() { + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.basePackage("com.xwbing.controller")) + .paths(PathSelectors.any()) + .build(); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("管理系统RESTful APIs") + .description("管理系统api接口,包含登录、注册.......") + .termsOfServiceUrl("http://localhost:8080/swagger-ui.html") + .contact("xiangwb") + .version("1.0") + .build(); + } + +} diff --git a/boot-web/src/main/java/com/xwbing/controller/MailTestControl.java b/boot-web/src/main/java/com/xwbing/controller/MailTestControl.java new file mode 100644 index 0000000..be4f48c --- /dev/null +++ b/boot-web/src/main/java/com/xwbing/controller/MailTestControl.java @@ -0,0 +1,76 @@ +package com.xwbing.controller; + +import com.alibaba.fastjson.JSONObject; +import com.xwbing.service.MailService; +import com.xwbing.util.JSONObjResult; +import com.xwbing.util.RestMessage; +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.RestController; + +/** + * 项目名称: sb-demo + * 创建时间: 2017/9/18 13:42 + * 作者: xiangwb + * 说明:邮件测试控制层 + */ +@RestController +@RequestMapping("/mail/") +public class MailTestControl { + @Autowired + private MailService mailService; + + /** + * 发送纯文本邮件 + * + * @return + */ + @GetMapping("sendSimpleMail") + public JSONObject sendSimpleMail() { + RestMessage restMessage = mailService.sendSimpleMail("786461501@qq.com", "测试邮件", "收到一个纯文本邮件"); + return JSONObjResult.toJSONObj(restMessage); + } + + /** + * 发送html格式邮件 + * + * @return + */ + @GetMapping("sendHtmlMail") + public JSONObject sendHtmlMail() { + String content = "" + + "" + + "

hello world ! 这是一封Html邮件!

" + + "" + + ""; + RestMessage restMessage = mailService.sendHtmlMail("786461501@qq.com", "html测试邮件", content); + return JSONObjResult.toJSONObj(restMessage); + } + + /** + * 发送带附件邮件 + * + * @return + */ + @GetMapping("sendAttachmentsMail") + public JSONObject sendAttachmentsMail() { + String path = "C:\\Users\\admin\\Desktop\\qq.txt"; + RestMessage restMessage = mailService.sendAttachmentsMail("786461501@qq.com", "附件测试邮件", "收到一个带附件邮件", path); + return JSONObjResult.toJSONObj(restMessage); + } + + /** + * 发送文本内嵌图片邮件 + * + * @return + */ + @GetMapping("sendInlineResourceMail") + public JSONObject sendInlineResourceMail() { + String rscId = "pic"; + String content = "这是有图片的邮件:"; + String imgPath = "C:\\Users\\admin\\Desktop\\0000001.png"; + RestMessage restMessage = mailService.sendInlineResourceMail("786461501@qq.com", "内嵌图片测试邮件", content, imgPath, rscId); + return JSONObjResult.toJSONObj(restMessage); + } +} diff --git a/boot-web/src/main/java/com/xwbing/controller/SysConfigControl.java b/boot-web/src/main/java/com/xwbing/controller/SysConfigControl.java new file mode 100644 index 0000000..9947d7a --- /dev/null +++ b/boot-web/src/main/java/com/xwbing/controller/SysConfigControl.java @@ -0,0 +1,78 @@ +package com.xwbing.controller; + +import com.alibaba.fastjson.JSONObject; +import com.xwbing.domain.SysConfig; +import com.xwbing.service.SysConfigService; +import com.xwbing.util.JSONObjResult; +import com.xwbing.util.RestMessage; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; +import java.util.Objects; + +/** + * 说明: 系统配置控制层 + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +@Api("系统配置") +@RestController +@RequestMapping("/config/") +public class SysConfigControl { + private static Logger log = LoggerFactory.getLogger(SysConfigControl.class); + @Autowired + private SysConfigService sysConfigService; + + @ApiOperation(value = "新增", notes = "新增系统配置信息") + @ApiImplicitParams({ + @ApiImplicitParam(name = "code", value = "配置项的key,长度为1-50", paramType = "query", required = true, dataType = "string"), + @ApiImplicitParam(name = "value", value = "配置项的值", paramType = "query", required = true, dataType = "string"), + @ApiImplicitParam(name = "isEnable", value = "是否启用,格式为Y|N", paramType = "query", required = true, dataType = "string"), + @ApiImplicitParam(name = "name", value = "配置名称,长度为1-10", paramType = "query", required = true, dataType = "string") + }) + @PostMapping("save") + public JSONObject save(@Valid SysConfig sysConfig) { + String logMsg = "新增系统配置信息"; + log.info(logMsg); + RestMessage result = sysConfigService.save(sysConfig); + return JSONObjResult.toJSONObj(result); + } + + @ApiOperation(value = "删除", notes = "根据code删除系统配置信息") + @ApiImplicitParam(name = "code", value = "配置项的code", paramType = "query", required = true, dataType = "string") + @PostMapping("removeByCode/{code}") + public JSONObject removeByCode(@PathVariable String code) { + String logMsg = "删除系统配置信息"; + log.info(logMsg + " code:{}", code); + if (StringUtils.isEmpty(code)) { + return JSONObjResult.toJSONObj("code不能为空"); + } + RestMessage result = sysConfigService.removeByCode(code); + return JSONObjResult.toJSONObj(result); + } + + @ApiOperation(value = "查找", notes = "根据key查找系统配置信息") + @ApiImplicitParam(name = "code", value = "配置项的code", paramType = "query", required = true, dataType = "string") + @PostMapping("findByCode") + public JSONObject findByCode(@RequestParam String code) { + String logMsg = "根据code查找系统配置信息"; + log.info(logMsg + " code:{}", code); + if (StringUtils.isEmpty(code)) { + return JSONObjResult.toJSONObj("code不能为空"); + } + SysConfig one = sysConfigService.findByCode(code); + if (Objects.isNull(one)) { + return JSONObjResult.toJSONObj("该对象不存在"); + } + return JSONObjResult.toJSONObj(one, true, ""); + } +} diff --git a/boot-web/src/main/java/com/xwbing/controller/TestControl.java b/boot-web/src/main/java/com/xwbing/controller/TestControl.java new file mode 100644 index 0000000..e076bb1 --- /dev/null +++ b/boot-web/src/main/java/com/xwbing/controller/TestControl.java @@ -0,0 +1,40 @@ +package com.xwbing.controller; + +import com.xwbing.annotation.LogInfo; +import com.xwbing.redis.RedisService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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.RestController; + +/** + * 说明: + * 项目名称: sbdemo + * 创建时间: 2017/5/5 9:21 + * 作者: xiangwb + */ +@RestController +@RequestMapping("/test/") +public class TestControl { + @Autowired + private RedisService redisService; + private final Logger logger = LoggerFactory.getLogger(TestControl.class); + + @LogInfo("redisLog") + @GetMapping("redis") + public void redis() { + redisService.set("redis", "xwbing"); + String s = redisService.get("redis"); + System.out.println(s); + logger.info("获取的数据为:" + s); + } + + @LogInfo("log") + @GetMapping("log") + public void log() { + logger.info("info"); + logger.error("error"); + } +} diff --git a/boot-web/src/main/java/com/xwbing/controller/UserControl.java b/boot-web/src/main/java/com/xwbing/controller/UserControl.java new file mode 100644 index 0000000..de5dcb2 --- /dev/null +++ b/boot-web/src/main/java/com/xwbing/controller/UserControl.java @@ -0,0 +1,73 @@ +package com.xwbing.controller; + +import com.alibaba.fastjson.JSONObject; +import com.xwbing.domain.SysUser; +import com.xwbing.service.UserService; +import com.xwbing.util.JSONObjResult; +import com.xwbing.util.RestMessage; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; +import java.util.List; +import java.util.Objects; + +/** + * 说明: user + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +@RestController +@RequestMapping("/user/") +public class UserControl { + private final static Logger log = LoggerFactory.getLogger(UserControl.class); + @Autowired + private UserService userService; + + @PostMapping("save") + public JSONObject save(@Valid SysUser sysUser) { + RestMessage result = userService.save(sysUser); + return JSONObjResult.toJSONObj(result); + } + + @PostMapping("removeById") + public JSONObject removeById(@RequestParam String id) { + if (StringUtils.isEmpty(id)) { + return JSONObjResult.toJSONObj("主键不能为空"); + } + RestMessage result = userService.removeById(id); + return JSONObjResult.toJSONObj(result); + } + + @PostMapping("update") + public JSONObject update(SysUser sysUser) { + if (StringUtils.isEmpty(sysUser.getId())) { + return JSONObjResult.toJSONObj("主键不能为空"); + } + RestMessage result = userService.update(sysUser); + return JSONObjResult.toJSONObj(result); + } + + @GetMapping("findById") + public JSONObject findById(String id) { + if (StringUtils.isEmpty(id)) { + return JSONObjResult.toJSONObj("主键不能为空"); + } + SysUser sysUser = userService.findOne(id); + if (Objects.isNull(sysUser)) { + return JSONObjResult.toJSONObj("未查到该对象"); + } + return JSONObjResult.toJSONObj(sysUser, true, ""); + } + + @GetMapping("findList") + public JSONObject findList() { + List list = userService.findList(); + return JSONObjResult.toJSONObj(list, true, ""); + } + +} diff --git a/boot-web/src/main/java/com/xwbing/handler/GlobalExceptionHandler.java b/boot-web/src/main/java/com/xwbing/handler/GlobalExceptionHandler.java new file mode 100644 index 0000000..f9a9885 --- /dev/null +++ b/boot-web/src/main/java/com/xwbing/handler/GlobalExceptionHandler.java @@ -0,0 +1,87 @@ +package com.xwbing.handler; + +import com.alibaba.fastjson.JSONObject; +import com.xwbing.exception.BusinessException; +import com.xwbing.util.JSONObjResult; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.validation.BindException; +import org.springframework.validation.ObjectError; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.List; + +/** + * 说明: GlobalExceptionHandler + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +// 作用在所有注解了@RequestMapping的控制器的方法上 +@ControllerAdvice +public class GlobalExceptionHandler { + private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); + + /** + * 自定义业务异常 + * + * @param request + * @param ex + * @return + */ + // 拦截处理控制器里对应的异常。 + @ExceptionHandler(value = BusinessException.class) + // 返回给页面200状态码 + @ResponseStatus(value = HttpStatus.OK) + @ResponseBody + public JSONObject handlerGuideException(HttpServletRequest request, + Exception ex) { + logger.error(ex.getMessage()); + return JSONObjResult.toJSONObj(ex.getMessage()); + } + + /** + * 表单检验(validator) 异常 + * + * @param request + * @param response + * @param ex + * @return + */ + @ExceptionHandler(value = BindException.class) + @ResponseBody + public JSONObject handlerBindException(HttpServletRequest request, + HttpServletResponse response, BindException ex) { + + List list = ex.getAllErrors(); + StringBuffer stringBuffer = new StringBuffer(); + for (ObjectError objectError : list) { + if (stringBuffer.length() > 0) + stringBuffer.append(" && "); + stringBuffer.append(objectError.getDefaultMessage()); + } + logger.error(stringBuffer.toString()); + response.setStatus(HttpStatus.OK.value()); + return JSONObjResult.toJSONObj(stringBuffer.toString()); + } + + /** + * @param request + * @param ex + * @return + */ + @ExceptionHandler(value = Exception.class) + @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) + @ResponseBody + public JSONObject handlerException(HttpServletRequest request, + Exception ex) { + logger.error(ex.getMessage()); + return JSONObjResult.toJSONObj("系统异常,请联系管理员"); + } +} diff --git a/boot-web/src/main/java/com/xwbing/handler/LoginInterceptor.java b/boot-web/src/main/java/com/xwbing/handler/LoginInterceptor.java new file mode 100644 index 0000000..87bde82 --- /dev/null +++ b/boot-web/src/main/java/com/xwbing/handler/LoginInterceptor.java @@ -0,0 +1,44 @@ +package com.xwbing.handler; + +import com.xwbing.configuration.DispatcherServletConfig; +import com.xwbing.constant.CommonConstant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.util.HashSet; +import java.util.Set; + +/** + * 说明: 登录拦截器 + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:36 + * 作者: xiangwb + */ +public class LoginInterceptor extends HandlerInterceptorAdapter { + private final Logger logger = LoggerFactory.getLogger(DispatcherServletConfig.class); + private static final Set set = new HashSet<>();//拦截器白名单 + static { + set.add("/v2/api-docs"); + set.add("/servlet/captchaCode"); + set.add("/swagger-ui.html"); + } + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + String servletPath = request.getServletPath(); + if(!set.contains(servletPath) && !servletPath.contains("login")){ + HttpSession session = request.getSession(); + if (session.getAttribute(CommonConstant.SESSION_CURRENT_USER)!=null) { + // TODO: 2017/5/15 + return true; + }else { + // TODO: 2017/10/3 + return false; + } + } + return true; + } +} diff --git a/boot-web/src/main/java/com/xwbing/handler/WebLogAspect.java b/boot-web/src/main/java/com/xwbing/handler/WebLogAspect.java new file mode 100644 index 0000000..f9eb5f5 --- /dev/null +++ b/boot-web/src/main/java/com/xwbing/handler/WebLogAspect.java @@ -0,0 +1,122 @@ +package com.xwbing.handler; + +import com.xwbing.annotation.LogInfo; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Method; + +/** + * 说明: web层日志记录切面 + * 项目名称: sbdemo + * 创建时间: 2017/5/10 16:34 + * 作者: xiangwb + */ +@Aspect +@Component +public class WebLogAspect { + private final Logger logger = LoggerFactory.getLogger(WebLogAspect.class); + ThreadLocal startTime = new ThreadLocal<>(); + + @Pointcut("within(com.xwbing.controller..*) && @annotation(logInfo)") + public void pointCutWithMsg(LogInfo logInfo) { + } + + @Pointcut("within(com.xwbing.controller..*)") + public void pointCut() { + } + + /** + * 前置通知 + * + * @param logInfo + */ + @Before("pointCutWithMsg(logInfo)") + public void before(JoinPoint joinPoint, LogInfo logInfo) { + startTime.set(System.currentTimeMillis()); + String info = logInfo.value(); + String targetName = joinPoint.getTarget().getClass().getName(); + String methodName = joinPoint.getSignature().getName(); + logger.info("{} {} : {} started", targetName, methodName, info); + } + + /** + * 后置通知 + * + * @param logInfo + */ + @AfterReturning(pointcut = "pointCutWithMsg(logInfo)") + public void afterReturning(JoinPoint joinPoint, LogInfo logInfo) { + long end = System.currentTimeMillis(); + long ms = end - startTime.get(); + String info = logInfo.value(); + String targetName = joinPoint.getTarget().getClass().getName(); + String methodName = joinPoint.getSignature().getName(); + logger.info("{} {} : {} completed in {} ms", targetName, methodName, info, ms); + } + + /** + * 异常通知 + * + * @param e + */ + // @AfterThrowing(pointcut = "pointCut()", throwing = "e") + public void afterThroing(Exception e) { + logger.error("异常信息:{}", e.getMessage()); + } + + /** + * 环绕通知=前置+后置 + * + * @param pjp + * @param logInfo + * @return + */ + // @Around("pointCutWithMsg(logInfo)") + public Object around(ProceedingJoinPoint pjp, LogInfo logInfo) { + String info = logInfo.value();// 获取注解信息 + Object result = null;// 被代理对象方法返回的结果 + try { + logger.info("{} start", info); + result = pjp.proceed(); + logger.info("{} end", info); + } catch (Throwable e) { + logger.error(e.getMessage()); + } + return result; + } + + /** + * 获取日志注解信息 + * + * @param joinPoint + * @return + * @throws ClassNotFoundException + */ + @Deprecated + public String getMsg(JoinPoint joinPoint) throws ClassNotFoundException { + String targetName = joinPoint.getTarget().getClass().getName();// 类名 + String methodName = joinPoint.getSignature().getName();// 方法名 + Object[] arguments = joinPoint.getArgs();// 方法参数 + Class targetClass = Class.forName(targetName); + Method[] methods = targetClass.getMethods(); + String description = ""; + for (Method method : methods) { + if (method.getName().equals(methodName)) { + Class[] clazzs = method.getParameterTypes(); + if (clazzs.length == arguments.length) { + description = method.getAnnotation(LogInfo.class).value(); + break; + } + } + } + return description; + } +} diff --git a/boot-web/src/main/resources/application.yml b/boot-web/src/main/resources/application.yml new file mode 100644 index 0000000..6a6ec8d --- /dev/null +++ b/boot-web/src/main/resources/application.yml @@ -0,0 +1,56 @@ +#server +server: + port: 8088 + session: + timeout: 30 + context-path: / + +#spring +spring: + #datasource + datasource: + driver-class-name: com.mysql.jdbc.Driver + url: jdbc:mysql://127.0.0.1:3306/springboot2?useUnicode=true&characterEncoding=utf8 + username: root + password: xwbing + #jpa + jpa: + database: mysql + show-sql: true + hibernate: + ddl-auto: update + properties: + hibernate : + naming-strategy : org.hibernate.cfg.ImprovedNamingStrategy + dialect : org.hibernate.dialect.MySQL5Dialect + #aop + aop: + auto: true # Add @EnableAspectJAutoProxy + proxy-target-class: false + #mail + mail: + host: smtp.163.com + username: xiangwbs@163.com + password: xwbing900511 #邮箱设置里获取的授权码 + default-encoding: utf-8 + properties: + mail: + smtp: + auth: true #授权 + starttls: + enable: true + required: true +#redis +redis: + host: 192.168.11.202 + port: 6379 + password: + timeout: 10000 + maxTotal: 8 #最大连接数 + maxIdle: 8 #最大空闲数 + minIdle: 0 #最小空闲数 + +#log +logging: + config: classpath:log4j2.xml + diff --git a/boot-web/src/main/resources/config.properties b/boot-web/src/main/resources/config.properties new file mode 100644 index 0000000..e69de29 diff --git a/boot-web/src/main/resources/log4j2.xml b/boot-web/src/main/resources/log4j2.xml new file mode 100644 index 0000000..65bf60c --- /dev/null +++ b/boot-web/src/main/resources/log4j2.xml @@ -0,0 +1,84 @@ + + + + + + + + + logs + + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %L %-5p %class{36} %M : %msg%xEx%n + + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %L %-5p %class{36} %M : %msg%xEx%n + + + + + + + + + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %L %-5p %class{36} %M : %msg%xEx%n + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..a0b282e --- /dev/null +++ b/pom.xml @@ -0,0 +1,115 @@ + + + 4.0.0 + com.xwbing + boot-module-demo + pom + 1.0 + + boot-service + boot-web + + + org.springframework.boot + spring-boot-starter-parent + 1.5.7.RELEASE + + + + + nexus + drore Team nexus + http://192.168.11.110:8081/nexus/content/groups/public + + + + + nexus + drore Team nexus + http://192.168.11.110:8081/nexus/content/groups/public + + + + UTF-8 + UTF-8 + 1.8 + 1.3.1 + 1.16.16 + + true + 2.2.2 + + + + org.springframework + spring-web + + + + org.springframework.boot + spring-boot-starter-log4j2 + + + + io.springfox + springfox-swagger2 + ${swagger2.version} + + + io.springfox + springfox-swagger-ui + ${swagger2.version} + + + + com.alibaba + fastjson + 1.1.41 + + + com.google.code.gson + gson + + + + org.apache.commons + commons-lang3 + 3.1 + + + commons-codec + commons-codec + + + commons-collections + commons-collections + + + commons-beanutils + commons-beanutils + + + commons-fileupload + commons-fileupload + ${fileUpLoad.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${java.version} + ${java.version} + + ${skipTests} + ${project.build.sourceEncoding} + + + + + \ No newline at end of file