├── .DS_Store ├── .classpath ├── .gitignore ├── .project ├── .settings ├── .jsdtscope ├── org.eclipse.core.resources.prefs ├── org.eclipse.jdt.core.prefs ├── org.eclipse.m2e.core.prefs ├── org.eclipse.wst.common.component ├── org.eclipse.wst.common.project.facet.core.xml ├── org.eclipse.wst.jsdt.ui.superType.container ├── org.eclipse.wst.jsdt.ui.superType.name └── org.eclipse.wst.validation.prefs ├── README.md ├── doc ├── index.sql ├── init.sql └── perms.properties ├── pom.xml └── src ├── .DS_Store ├── main ├── .DS_Store ├── java │ └── com │ │ └── onecoderspace │ │ └── base │ │ ├── BaseApplication.java │ │ ├── aop │ │ └── WebLogAspect.java │ │ ├── component │ │ ├── common │ │ │ ├── QueryTypeEnum.java │ │ │ ├── dao │ │ │ │ └── BaseDao.java │ │ │ ├── domain │ │ │ │ ├── AbstractBaseModel.java │ │ │ │ ├── BaseModel.java │ │ │ │ └── MarkDeleteableModel.java │ │ │ └── service │ │ │ │ ├── BaseService.java │ │ │ │ ├── BaseServiceImpl.java │ │ │ │ └── QueryTypeEnum.java │ │ └── web │ │ │ └── GlobalDefaultExceptionHandler.java │ │ ├── config │ │ ├── MyShiroRealm.java │ │ ├── RedisSessionConfig.java │ │ ├── ShiroConfigration.java │ │ ├── Swagger2.java │ │ └── WebConfig.java │ │ ├── controller │ │ ├── LoginController.java │ │ ├── UploadController.java │ │ ├── UserController.java │ │ └── admin │ │ │ ├── AdminUserController.java │ │ │ ├── PermissionController.java │ │ │ └── RoleController.java │ │ ├── dao │ │ ├── PermissionDao.java │ │ ├── RoleDao.java │ │ ├── RolePermissionDao.java │ │ ├── UserDao.java │ │ └── UserRoleDao.java │ │ ├── domain │ │ ├── Permission.java │ │ ├── Role.java │ │ ├── RolePermission.java │ │ ├── User.java │ │ └── UserRole.java │ │ ├── filter │ │ ├── CsrfFilter.java │ │ ├── LoginFilter.java │ │ ├── ShiroSessionFilter.java │ │ ├── XssFilter.java │ │ └── XssHttpServletRequestWrapper.java │ │ ├── service │ │ ├── PermissionService.java │ │ ├── RolePermissionService.java │ │ ├── RoleService.java │ │ ├── UserRoleService.java │ │ ├── UserService.java │ │ └── impl │ │ │ ├── PermissionServiceImpl.java │ │ │ ├── RolePermissionServiceImpl.java │ │ │ ├── RoleServiceImpl.java │ │ │ ├── UserRoleServiceImpl.java │ │ │ └── UserServiceImpl.java │ │ └── util │ │ ├── AjaxResponseWriter.java │ │ ├── Constants.java │ │ ├── DateUtils.java │ │ ├── FileUtil.java │ │ ├── HttpServletHelper.java │ │ ├── JacksonHelper.java │ │ ├── JsUtils.java │ │ ├── ListOptionHelper.java │ │ ├── LoginSessionHelper.java │ │ ├── MD5.java │ │ ├── OperationCheck.java │ │ ├── RandomUtils.java │ │ ├── RegixUtils.java │ │ ├── Return.java │ │ ├── SaltMD5Util.java │ │ ├── ServiceStatusEnum.java │ │ ├── SpringContextUtil.java │ │ ├── ThreadLocalUtils.java │ │ ├── TokenUtils.java │ │ ├── http │ │ ├── AbstractHttpHelper.java │ │ ├── DefaultConnectionKeepAliveStrategy.java │ │ ├── HttpHelper.java │ │ ├── HttpRuntimeException.java │ │ ├── RequestByBodyCreator.java │ │ ├── RequestByParametersCreator.java │ │ ├── RequestByURLCreator.java │ │ ├── RequestCreator.java │ │ └── UnexpectedHttpStatusException.java │ │ ├── lock │ │ ├── DistributedLock.java │ │ ├── DistributedLockUtil.java │ │ └── impl │ │ │ └── JedisLock.java │ │ ├── ognl │ │ └── OgnlWrapper.java │ │ ├── redis │ │ └── RedisBlockingQueue.java │ │ └── security │ │ └── xss │ │ └── JsoupUtil.java └── resources │ ├── application-dev.properties │ ├── application-local.properties │ ├── application-prod.properties │ ├── application.properties │ ├── ehcache-shiro.xml │ └── logback-spring.xml └── test ├── .DS_Store └── java ├── .DS_Store └── com ├── .DS_Store └── onecoderspace ├── .DS_Store └── base ├── OrderService2Test.java ├── OrderServiceTest.java ├── OrderServiceTestSuit.java ├── StringRedisTemplateServiceTest.java ├── UnifiedOrderTaskTests.java └── UserServiceTest.java /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/q7322068/rest-base/43c2f4469008360c531b53d9d121ff2d5a1cef0e/.DS_Store -------------------------------------------------------------------------------- /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | rest-base 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.wst.jsdt.core.javascriptValidator 10 | 11 | 12 | 13 | 14 | org.eclipse.wst.common.project.facet.core.builder 15 | 16 | 17 | 18 | 19 | org.eclipse.jdt.core.javabuilder 20 | 21 | 22 | 23 | 24 | org.eclipse.wst.validation.validationbuilder 25 | 26 | 27 | 28 | 29 | org.eclipse.m2e.core.maven2Builder 30 | 31 | 32 | 33 | 34 | 35 | org.eclipse.jem.workbench.JavaEMFNature 36 | org.eclipse.wst.common.modulecore.ModuleCoreNature 37 | org.eclipse.jdt.core.javanature 38 | org.eclipse.m2e.core.maven2Nature 39 | org.eclipse.wst.common.project.facet.core.nature 40 | org.eclipse.wst.jsdt.core.jsNature 41 | 42 | 43 | -------------------------------------------------------------------------------- /.settings/.jsdtscope: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /.settings/org.eclipse.core.resources.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | encoding//src/main/java=UTF-8 3 | encoding//src/main/resources=UTF-8 4 | encoding//src/test/java=UTF-8 5 | encoding/=UTF-8 6 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 4 | org.eclipse.jdt.core.compiler.compliance=1.7 5 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 6 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 7 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 8 | org.eclipse.jdt.core.compiler.source=1.7 9 | -------------------------------------------------------------------------------- /.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /.settings/org.eclipse.wst.common.component: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /.settings/org.eclipse.wst.common.project.facet.core.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.settings/org.eclipse.wst.jsdt.ui.superType.container: -------------------------------------------------------------------------------- 1 | org.eclipse.wst.jsdt.launching.baseBrowserLibrary -------------------------------------------------------------------------------- /.settings/org.eclipse.wst.jsdt.ui.superType.name: -------------------------------------------------------------------------------- 1 | Window -------------------------------------------------------------------------------- /.settings/org.eclipse.wst.validation.prefs: -------------------------------------------------------------------------------- 1 | disabled=06target 2 | eclipse.preferences.version=1 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rest-base 2 | 基于spring boot搭建的web基础框架,包含了web开发中常用的功能,如:缓存(redis)、日志、事务、JPA、shiro、安全、常用工具类、swagger2在线接口文档、跨域支持等,可以基于该项目快速进行公司内部的项目开发。 3 | 4 | # 运行方式 5 | 1. 本地创建数据库base,调整application-local.properties内的mysql和redis配置; 6 | 2. 创建数据库后,直接运行BaseApplication,待项目启动后,在数据库内执行doc目录下的init.sql和index.sql; 7 | 3. 访问http://localhost:8070/login/submit?username=admin&pwd=admin2017进行登录 8 | 4. 访问http://localhost:8070/swagger-ui.html查看接口文档; 9 | 5. 访问http://localhost:8070/admin/user/list测试接口; 10 | 11 | # redis安装方式 12 | $ wget http://download.redis.io/releases/redis-4.0.2.tar.gz 13 | $ tar xzf redis-4.0.2.tar.gz 14 | $ cd redis-4.0.2 15 | $ make 16 | 17 | 修改Redis配置文件redis.conf,改变配置: 18 | daemonize yes 19 | requirepass test!@#$% 20 | 21 | $ src/redis-server 22 | src/redis-cli 23 | 24 | 25 | # 简书博客 26 | http://www.jianshu.com/u/1182bf416662 27 | 28 | # csdn博客 29 | http://blog.csdn.net/u014411966 30 | -------------------------------------------------------------------------------- /doc/index.sql: -------------------------------------------------------------------------------- 1 | create index idx_username on user(username); 2 | 3 | create index idx_userId on user_role(user_id); 4 | create index idx_roleId on user_role(role_id); 5 | 6 | create index idx_roleId on role_permission(role_id); 7 | create index idx_permissionId on role_permission(permission_id); 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /doc/init.sql: -------------------------------------------------------------------------------- 1 | -- 初始化管理员用户 admin admin2017 2 | insert into user(id,username,name,salt,pwd,enable,del,type,register_time,update_time) VALUES(1,'admin','admin','Jm1tRIWU2o42!OVb','6f4dd2230a5d6a68e5c13ca7b5a681eb',1,0,1,NOW(),NOW()); 3 | 4 | -- 初始化角色 5 | insert into role(id,name,code,remark) VALUES(1,'普通用户','user','系统角色,请勿删除'); 6 | insert into role(id,name,code,remark) VALUES(2,'操作员','operator','系统角色,请勿删除'); 7 | insert into role(id,name,code,remark) VALUES(3,'管理员','admin','系统角色,请勿删除'); 8 | 9 | -- 添加用户角色关系 10 | insert into user_role(user_id,role_id) VALUES(1,3); 11 | 12 | -- 初始权限 13 | insert into permission(id,type,name,code,url,weight,pid) VALUES(1,2,'用户-查询','user:get','/user/get',4,3); 14 | insert into permission(id,type,name,code,url,weight,pid) VALUES(2,2,'用户-当前用户','user:current','/user/current',5,3); 15 | insert into permission(id,type,name,code,url,weight,pid) VALUES(3,2,'用户-修改密码','user:reset-pwd','/user/reset-pwd',7,3); 16 | insert into permission(id,type,name,code,url,weight,pid) VALUES(4,2,'用户审核-列表','admin:user:list','/admin/user/list',46,3); 17 | insert into permission(id,type,name,code,url,weight,pid) VALUES(5,2,'用户审核-保存','admin:user:save','/admin/user/save',47,3); 18 | insert into permission(id,type,name,code,url,weight,pid) VALUES(6,2,'用户审核-删除','admin:user:delete','/admin/user/delete',48,3); 19 | insert into permission(id,type,name,code,url,weight,pid) VALUES(7,2,'用户审核-列表','admin:user:role:list','/admin/user/role/list',51,3); 20 | insert into permission(id,type,name,code,url,weight,pid) VALUES(8,2,'用户审核-设置角色','admin:user:role:set','/admin/user/role/set',52,3); 21 | 22 | -- 添加角色[admin]的权限 23 | insert into role_permission(role_id,permission_id) VALUES(3,1); 24 | insert into role_permission(role_id,permission_id) VALUES(3,2); 25 | insert into role_permission(role_id,permission_id) VALUES(3,3); 26 | insert into role_permission(role_id,permission_id) VALUES(3,4); 27 | insert into role_permission(role_id,permission_id) VALUES(3,5); 28 | insert into role_permission(role_id,permission_id) VALUES(3,6); 29 | insert into role_permission(role_id,permission_id) VALUES(3,7); 30 | insert into role_permission(role_id,permission_id) VALUES(3,8); 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /doc/perms.properties: -------------------------------------------------------------------------------- 1 | ##用户账号 2 | 用户-查询|/user/get|user:get 3 | 用户-当前用户|/user/current|user:current 4 | 用户-修改密码|/user/reset-pwd|user:reset-pwd 5 | 6 | ##用户审核 7 | 用户审核-列表|/admin/user/list|admin:user:list 8 | 用户审核-保存|/admin/user/save|admin:user:save 9 | 用户审核-删除|/admin/user/delete|admin:user:delete 10 | 用户审核-提交审核|/admin/user/audit|admin:user:audit 11 | 用户审核-列表|/admin/user/role/list|admin:user:role:list 12 | 用户审核-设置角色|/admin/user/role/set|admin:user:role:set 13 | 14 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.hexun.bdc 6 | rest-base 7 | 1.0-SNAPSHOT 8 | war 9 | 10 | rest-base 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 1.7 16 | 3.1 17 | 18.0 18 | 2.4 19 | 4.3.2 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-parent 25 | 1.5.4.RELEASE 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-web 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-tomcat 36 | 37 | 38 | 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-starter-aop 43 | 44 | 45 | 46 | org.springframework.boot 47 | spring-boot-starter-tomcat 48 | provided 49 | 50 | 51 | 52 | 53 | mysql 54 | mysql-connector-java 55 | 56 | 57 | 58 | org.springframework.boot 59 | spring-boot-starter-data-jpa 60 | 61 | 62 | 63 | 64 | net.sf.ehcache 65 | ehcache 66 | 67 | 68 | 69 | 70 | org.springframework.boot 71 | spring-boot-starter-data-redis 72 | 73 | 74 | org.springframework.session 75 | spring-session-data-redis 76 | 77 | 78 | 79 | org.springframework.boot 80 | spring-boot-starter-actuator 81 | 82 | 83 | 84 | 85 | org.apache.commons 86 | commons-lang3 87 | ${commons-lang3.version} 88 | 89 | 90 | 91 | com.google.guava 92 | guava 93 | ${guava.version} 94 | 95 | 96 | 97 | commons-io 98 | commons-io 99 | ${commons-io.version} 100 | 101 | 102 | 103 | com.fasterxml.jackson.core 104 | jackson-databind 105 | 106 | 107 | 108 | org.codehaus.jackson 109 | jackson-mapper-asl 110 | 1.9.13 111 | 112 | 113 | 114 | joda-time 115 | joda-time 116 | 117 | 118 | 119 | 120 | ognl 121 | ognl 122 | 3.2.1 123 | 124 | 125 | 126 | 127 | org.jsoup 128 | jsoup 129 | 1.9.2 130 | 131 | 132 | 133 | 134 | org.apache.httpcomponents 135 | httpclient 136 | 137 | 138 | org.apache.httpcomponents 139 | httpcore 140 | 141 | 142 | 143 | commons-httpclient 144 | commons-httpclient 145 | 3.1 146 | 147 | 148 | 149 | 150 | org.springframework.boot 151 | spring-boot-starter-test 152 | test 153 | 154 | 155 | 156 | 157 | org.apache.shiro 158 | shiro-core 159 | 1.3.2 160 | 161 | 162 | org.apache.shiro 163 | shiro-spring 164 | 1.3.2 165 | 166 | 167 | org.apache.shiro 168 | shiro-web 169 | 1.3.2 170 | 171 | 172 | 173 | org.apache.shiro 174 | shiro-ehcache 175 | 1.3.2 176 | 177 | 178 | 179 | 180 | io.springfox 181 | springfox-swagger2 182 | 2.7.0 183 | 184 | 185 | io.springfox 186 | springfox-swagger-ui 187 | 2.7.0 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | org.apache.maven.plugins 196 | maven-war-plugin 197 | 198 | rest-base 199 | 200 | 201 | 202 | 203 | 204 | -------------------------------------------------------------------------------- /src/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/q7322068/rest-base/43c2f4469008360c531b53d9d121ff2d5a1cef0e/src/.DS_Store -------------------------------------------------------------------------------- /src/main/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/q7322068/rest-base/43c2f4469008360c531b53d9d121ff2d5a1cef0e/src/main/.DS_Store -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/BaseApplication.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base; 2 | 3 | import org.springframework.boot.Banner; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.builder.SpringApplicationBuilder; 6 | import org.springframework.boot.web.support.SpringBootServletInitializer; 7 | 8 | @SpringBootApplication 9 | public class BaseApplication extends SpringBootServletInitializer { 10 | 11 | @Override 12 | protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { 13 | return builder.sources(BaseApplication.class); 14 | } 15 | 16 | public static void main(String[] args) { 17 | configureApplication(new SpringApplicationBuilder()).run(args); 18 | } 19 | 20 | private static SpringApplicationBuilder configureApplication(SpringApplicationBuilder builder) { 21 | return builder.sources(BaseApplication.class).bannerMode(Banner.Mode.OFF); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/aop/WebLogAspect.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.aop; 2 | 3 | import java.util.List; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | import javax.servlet.http.HttpServletResponse; 7 | 8 | import org.aspectj.lang.JoinPoint; 9 | import org.aspectj.lang.annotation.AfterReturning; 10 | import org.aspectj.lang.annotation.Aspect; 11 | import org.aspectj.lang.annotation.Before; 12 | import org.aspectj.lang.annotation.Pointcut; 13 | import org.slf4j.Logger; 14 | import org.slf4j.LoggerFactory; 15 | import org.springframework.stereotype.Component; 16 | 17 | import com.google.common.base.Joiner; 18 | import com.google.common.collect.Lists; 19 | 20 | @Component 21 | @Aspect 22 | public class WebLogAspect { 23 | 24 | private static final Logger logger = LoggerFactory 25 | .getLogger(WebLogAspect.class); 26 | 27 | ThreadLocal startTimeThreadLocal = new ThreadLocal(); 28 | 29 | @Pointcut("execution(public * com.onecoderspace.base.controller..*.*(..))") 30 | public void webLog() { 31 | } 32 | 33 | @Before("webLog()") 34 | public void doBefore(JoinPoint joinPoint) throws Throwable { 35 | startTimeThreadLocal.set(System.currentTimeMillis()); 36 | } 37 | 38 | @AfterReturning(pointcut = "webLog()") 39 | public void doAfterReturning(JoinPoint joinPoint) throws Throwable { 40 | long usedTime = System.currentTimeMillis() - startTimeThreadLocal.get(); 41 | Object[] arr = joinPoint.getArgs(); 42 | List list = Lists.newArrayList(); 43 | for(Object obj : arr){ 44 | if(obj == null){ 45 | continue; 46 | } 47 | if(obj instanceof HttpServletRequest || obj instanceof HttpServletResponse){ 48 | continue; 49 | } 50 | list.add(obj.toString()); 51 | } 52 | String args = Joiner.on(",").join(list); 53 | String key = String.format("method=[%s.%s]", 54 | joinPoint.getSignature().getDeclaringType().getSimpleName(), 55 | joinPoint.getSignature().getName()); 56 | if(usedTime > 100){ 57 | logger.info(String.format("method=[%s],args=[%s] use time=%d ms",key, args, usedTime)); 58 | } else if(logger.isDebugEnabled()){ 59 | logger.debug(String.format("method=[%s],args=[%s] use time=%d ms",key, args, usedTime)); 60 | } 61 | 62 | } 63 | 64 | } -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/component/common/QueryTypeEnum.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.component.common; 2 | 3 | import io.swagger.annotations.ApiModel; 4 | 5 | @ApiModel(value="查询条件支持的过滤方式") 6 | public enum QueryTypeEnum { 7 | like, 8 | equal, 9 | ne, 10 | lt, 11 | lte, 12 | gt, 13 | gte 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/component/common/dao/BaseDao.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.component.common.dao; 2 | 3 | import java.io.Serializable; 4 | 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.data.jpa.repository.JpaSpecificationExecutor; 7 | import org.springframework.data.repository.NoRepositoryBean; 8 | 9 | @NoRepositoryBean 10 | public interface BaseDao extends JpaSpecificationExecutor,JpaRepository{ 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/component/common/domain/AbstractBaseModel.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.component.common.domain; 2 | 3 | import io.swagger.annotations.ApiModelProperty; 4 | 5 | import java.io.Serializable; 6 | import java.sql.Timestamp; 7 | 8 | import javax.persistence.Column; 9 | import javax.persistence.MappedSuperclass; 10 | 11 | /** 12 | * 提取了部分公共字段,可以避免多个实体重复设置这些属性 13 | * @author yangwk 14 | * @version v1.0 15 | * @time 2017年8月9日 下午1:50:22 16 | */ 17 | @MappedSuperclass 18 | public abstract class AbstractBaseModel implements BaseModel{ 19 | 20 | private static final long serialVersionUID = 1195969732659409799L; 21 | 22 | @ApiModelProperty(value="创建者ID") 23 | @Column(columnDefinition="int default 0") 24 | private int creator = 0; 25 | 26 | @ApiModelProperty(value="创建时间") 27 | @Column(name="create_time") 28 | private Timestamp createTime; 29 | 30 | @ApiModelProperty(value="最后修改人") 31 | @Column(columnDefinition="int default 0") 32 | private int updator = 0; 33 | 34 | @ApiModelProperty(value="最后修改时间") 35 | @Column(name="update_time") 36 | private Timestamp updateTime; 37 | 38 | public int getCreator() { 39 | return creator; 40 | } 41 | 42 | public void setCreator(int creator) { 43 | this.creator = creator; 44 | } 45 | 46 | public Timestamp getCreateTime() { 47 | return createTime; 48 | } 49 | 50 | public void setCreateTime(Timestamp createTime) { 51 | this.createTime = createTime; 52 | } 53 | 54 | public int getUpdator() { 55 | return updator; 56 | } 57 | 58 | public void setUpdator(int updator) { 59 | this.updator = updator; 60 | } 61 | 62 | public Timestamp getUpdateTime() { 63 | return updateTime; 64 | } 65 | 66 | public void setUpdateTime(Timestamp updateTime) { 67 | this.updateTime = updateTime; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/component/common/domain/BaseModel.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.component.common.domain; 2 | 3 | import java.io.Serializable; 4 | 5 | public interface BaseModel extends Serializable{ 6 | 7 | ID getId(); 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/component/common/domain/MarkDeleteableModel.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.component.common.domain; 2 | 3 | import io.swagger.annotations.ApiModelProperty; 4 | 5 | import java.io.Serializable; 6 | 7 | import javax.persistence.Column; 8 | import javax.persistence.MappedSuperclass; 9 | 10 | import com.onecoderspace.base.util.Constants; 11 | 12 | /** 13 | * 需要标记删除的实体继承该类 14 | * @author yangwk 15 | */ 16 | @MappedSuperclass 17 | public abstract class MarkDeleteableModel extends AbstractBaseModel{ 18 | 19 | private static final long serialVersionUID = -1880548221110317053L; 20 | 21 | @ApiModelProperty(value="标记删除字段 0未删除 1已删除 ") 22 | @Column(name = "del", columnDefinition = "tinyint default 0") 23 | private int del = Constants.DEL_NO; 24 | 25 | public int getDel() { 26 | return del; 27 | } 28 | 29 | public void setDel(int del) { 30 | this.del = del; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/component/common/service/BaseService.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.component.common.service; 2 | 3 | import java.io.Serializable; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | import org.springframework.data.domain.Page; 8 | import org.springframework.data.domain.Pageable; 9 | 10 | import com.onecoderspace.base.component.common.domain.BaseModel; 11 | 12 | public interface BaseService, ID extends Serializable> { 13 | 14 | /** 15 | * 新增或更新 16 | */ 17 | T save(T t); 18 | 19 | /** 20 | * 新增或更新 21 | * 注意数量不要太大,特别是数据迁移时不要使用该方法 22 | */ 23 | Iterable save(Iterable entities); 24 | 25 | /** 26 | * 根据ID删除 27 | */ 28 | void del(ID id); 29 | 30 | /** 31 | * 根据实体删除 32 | */ 33 | void del(T t); 34 | 35 | /** 36 | * 根据ID查找对象 37 | */ 38 | T findById(ID id); 39 | 40 | List findAll(); 41 | 42 | /** 43 | * 分页排序获取数据 44 | * 禁止使用该接口进行count操作 45 | * Pageable pageable = new PageRequest(0, 10, new Sort(Sort.Direction.DESC,"id")); 46 | * @param pageable 47 | * @return 48 | */ 49 | Page findAll(Pageable pageable); 50 | 51 | /** 52 | * 多条件查询 53 | * 注:多个条件间是and关系 & 参数是属性对应的类型 使用时注意避免结果集过大 54 | * @author yangwk 55 | * @time 2017年8月1日 下午3:50:46 56 | * @param params {"username:like":"test"} 键的格式为字段名:过滤方式,过滤方式见{@code QueryTypeEnum} 57 | * @return 58 | */ 59 | List list(Map params); 60 | 61 | /** 62 | * 分页多条件查询 63 | * 注:多个条件间是and关系 & 参数是属性对应的类型 64 | * @author yangwk 65 | * @time 2017年8月1日 下午3:50:46 66 | * @param params {"username:like":"test"} 键的格式为字段名:过滤方式,过滤方式见{@code QueryTypeEnum} 67 | * @param pageable 分页信息 new PageRequest(page, size,new Sort(Direction.DESC, "updateTime")) 68 | * @return 69 | */ 70 | Page list(Map params,Pageable pageable); 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/component/common/service/QueryTypeEnum.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.component.common.service; 2 | 3 | import io.swagger.annotations.ApiModel; 4 | 5 | @ApiModel(value="查询条件支持的过滤方式") 6 | public enum QueryTypeEnum { 7 | like, 8 | equal, 9 | ne, 10 | lt, 11 | lte, 12 | gt, 13 | gte 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/component/web/GlobalDefaultExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.component.web; 2 | 3 | import java.util.Map; 4 | 5 | import javax.servlet.http.HttpServletRequest; 6 | import javax.servlet.http.HttpServletResponse; 7 | 8 | import org.apache.shiro.authz.UnauthorizedException; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | import org.springframework.web.bind.annotation.ControllerAdvice; 12 | import org.springframework.web.bind.annotation.ExceptionHandler; 13 | import org.springframework.web.bind.annotation.ResponseBody; 14 | 15 | import com.google.common.collect.Maps; 16 | 17 | /** 18 | * 全局异常捕获 19 | * @author yangwenkui 20 | */ 21 | @ControllerAdvice 22 | public class GlobalDefaultExceptionHandler { 23 | private static Logger logger = LoggerFactory.getLogger(GlobalDefaultExceptionHandler.class); 24 | 25 | /** 26 | * 未授权异常处理 27 | * @author yangwk 28 | * @return 29 | */ 30 | @ExceptionHandler(value = UnauthorizedException.class) 31 | @ResponseBody 32 | public Map unauthorizedHandler(HttpServletRequest req,HttpServletResponse response, Exception e) { 33 | // 打印异常信息: 34 | response.setStatus(403); 35 | 36 | Map map = Maps.newHashMap(); 37 | map.put("code", "-10000"); 38 | map.put("msg", "您没有访问权限"); 39 | return map; 40 | } 41 | 42 | @ExceptionHandler(value = Exception.class) 43 | @ResponseBody 44 | public Map defaultErrorHandler(HttpServletRequest req,HttpServletResponse response, Exception e) { 45 | // 打印异常信息: 46 | logger.error("defaultErrorHandler:", e); 47 | response.setStatus(500); 48 | 49 | Map map = Maps.newHashMap(); 50 | map.put("code", "-10000"); 51 | map.put("msg", "系统繁忙"); 52 | return map; 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/config/MyShiroRealm.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.config; 2 | 3 | import java.util.HashSet; 4 | import java.util.List; 5 | import java.util.Set; 6 | 7 | import org.apache.commons.lang3.StringUtils; 8 | import org.apache.commons.lang3.math.NumberUtils; 9 | import org.apache.shiro.authc.AuthenticationException; 10 | import org.apache.shiro.authc.AuthenticationInfo; 11 | import org.apache.shiro.authc.AuthenticationToken; 12 | import org.apache.shiro.authc.SimpleAuthenticationInfo; 13 | import org.apache.shiro.authz.AuthorizationInfo; 14 | import org.apache.shiro.authz.SimpleAuthorizationInfo; 15 | import org.apache.shiro.realm.AuthorizingRealm; 16 | import org.apache.shiro.subject.PrincipalCollection; 17 | import org.slf4j.Logger; 18 | import org.slf4j.LoggerFactory; 19 | import org.springframework.beans.factory.annotation.Autowired; 20 | 21 | import com.onecoderspace.base.domain.Permission; 22 | import com.onecoderspace.base.domain.Role; 23 | import com.onecoderspace.base.domain.User; 24 | import com.onecoderspace.base.service.RolePermissionService; 25 | import com.onecoderspace.base.service.RoleService; 26 | import com.onecoderspace.base.service.UserRoleService; 27 | import com.onecoderspace.base.service.UserService; 28 | 29 | 30 | public class MyShiroRealm extends AuthorizingRealm { 31 | private static final Logger logger = LoggerFactory.getLogger(MyShiroRealm.class); 32 | 33 | @Autowired 34 | private UserService userService; 35 | 36 | @Autowired 37 | private UserRoleService userRoleService; 38 | 39 | @Autowired 40 | private RoleService roleService; 41 | 42 | @Autowired 43 | private RolePermissionService rolePermissionService; 44 | 45 | @Override 46 | protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { 47 | 48 | 49 | //获取用户的输入的账号. 50 | String idObj = (String) token.getPrincipal(); 51 | Integer id = NumberUtils.toInt(idObj); 52 | User user = userService.findById(id); 53 | 54 | if (user == null) { 55 | // 返回null的话,就会导致任何用户访问被拦截的请求时,都会自动跳转到unauthorizedUrl指定的地址 56 | return null; 57 | } 58 | 59 | SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getId(), 60 | user.getPwd(), getName()); 61 | 62 | return authenticationInfo; 63 | 64 | } 65 | 66 | @Override 67 | protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { 68 | /* 69 | * 当没有使用缓存的时候,不断刷新页面的话,这个代码会不断执行, 70 | * 当其实没有必要每次都重新设置权限信息,所以我们需要放到缓存中进行管理; 71 | * 当放到缓存中时,这样的话,doGetAuthorizationInfo就只会执行一次了, 72 | * 缓存过期之后会再次执行。 73 | */ 74 | logger.debug("权限配置-->MyShiroRealm.doGetAuthorizationInfo()"); 75 | 76 | SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); 77 | authorizationInfo.addRole("ACTUATOR"); 78 | 79 | Integer userId = Integer.parseInt(principals.getPrimaryPrincipal().toString()); 80 | //实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法 81 | 82 | Set roleIds = userRoleService.findRoleIds(userId); 83 | Set roles = roleService.findByIds(roleIds); 84 | for(Role role : roles){ 85 | authorizationInfo.addRole(role.getCode()); 86 | } 87 | 88 | //设置权限信息. 89 | List permissions = rolePermissionService.getPermissions(roleIds); 90 | Set set = new HashSet(permissions.size()*2); 91 | for(Permission permission : permissions){ 92 | if(StringUtils.isNotBlank(permission.getCode())){ 93 | set.add(permission.getCode()); 94 | } 95 | } 96 | authorizationInfo.setStringPermissions(set); 97 | return authorizationInfo; 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/config/RedisSessionConfig.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; 5 | 6 | /** 7 | * spring session配置 8 | * @author yangwk 9 | * @version v1.0 10 | * @time 2017年9月30日 下午3:32:40 11 | */ 12 | @Configuration 13 | @EnableRedisHttpSession(maxInactiveIntervalInSeconds=7200,redisNamespace="base") 14 | public class RedisSessionConfig { 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/config/ShiroConfigration.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.config; 2 | 3 | import java.util.HashMap; 4 | import java.util.LinkedHashMap; 5 | import java.util.Map; 6 | 7 | import org.apache.shiro.cache.ehcache.EhCacheManager; 8 | import org.apache.shiro.codec.Base64; 9 | import org.apache.shiro.spring.LifecycleBeanPostProcessor; 10 | import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; 11 | import org.apache.shiro.spring.web.ShiroFilterFactoryBean; 12 | import org.apache.shiro.web.mgt.CookieRememberMeManager; 13 | import org.apache.shiro.web.mgt.DefaultWebSecurityManager; 14 | import org.apache.shiro.web.servlet.SimpleCookie; 15 | import org.slf4j.Logger; 16 | import org.slf4j.LoggerFactory; 17 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 18 | import org.springframework.context.annotation.Bean; 19 | import org.springframework.context.annotation.Configuration; 20 | import org.springframework.web.filter.DelegatingFilterProxy; 21 | 22 | import com.onecoderspace.base.filter.LoginFilter; 23 | 24 | @Configuration 25 | public class ShiroConfigration { 26 | private static final Logger logger = LoggerFactory.getLogger(ShiroConfigration.class); 27 | 28 | private static Map filterChainDefinitionMap = new LinkedHashMap(); 29 | 30 | 31 | @Bean 32 | public SimpleCookie rememberMeCookie() { 33 | SimpleCookie simpleCookie = new SimpleCookie("rememberMe"); 34 | simpleCookie.setMaxAge(7 * 24 * 60 * 60);//保存10天 35 | return simpleCookie; 36 | } 37 | 38 | /** 39 | * cookie管理对象; 40 | */ 41 | @Bean 42 | public CookieRememberMeManager rememberMeManager() { 43 | logger.debug("ShiroConfiguration.rememberMeManager()"); 44 | CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager(); 45 | cookieRememberMeManager.setCookie(rememberMeCookie()); 46 | cookieRememberMeManager.setCipherKey(Base64.decode("kPv59vyqzj00x11LXJZTjJ2UHW48jzHN")); 47 | return cookieRememberMeManager; 48 | } 49 | 50 | 51 | @Bean(name = "lifecycleBeanPostProcessor") 52 | public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() { 53 | return new LifecycleBeanPostProcessor(); 54 | } 55 | 56 | 57 | @Bean 58 | public FilterRegistrationBean filterRegistrationBean() { 59 | FilterRegistrationBean filterRegistration = new FilterRegistrationBean(); 60 | DelegatingFilterProxy proxy = new DelegatingFilterProxy("shiroFilter"); 61 | // 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 62 | proxy.setTargetFilterLifecycle(true); 63 | filterRegistration.setFilter(proxy); 64 | 65 | filterRegistration.setEnabled(true); 66 | //filterRegistration.addUrlPatterns("/*");// 可以自己灵活的定义很多,避免一些根本不需要被Shiro处理的请求被包含进来 67 | return filterRegistration; 68 | } 69 | 70 | @Bean 71 | public MyShiroRealm myShiroRealm() { 72 | MyShiroRealm myShiroRealm = new MyShiroRealm(); 73 | return myShiroRealm; 74 | } 75 | 76 | @Bean(name="securityManager") 77 | public DefaultWebSecurityManager securityManager() { 78 | DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); 79 | manager.setRealm(myShiroRealm()); 80 | manager.setRememberMeManager(rememberMeManager()); 81 | manager.setCacheManager(ehCacheManager()); 82 | return manager; 83 | } 84 | 85 | 86 | /** 87 | * ShiroFilterFactoryBean 处理拦截资源文件问题。 88 | * 注意:单独一个ShiroFilterFactoryBean配置是或报错的,以为在 89 | * 初始化ShiroFilterFactoryBean的时候需要注入:SecurityManager 90 | *

91 | * Filter Chain定义说明 92 | * 1、一个URL可以配置多个Filter,使用逗号分隔 93 | * 2、当设置多个过滤器时,全部验证通过,才视为通过 94 | * 3、部分过滤器可指定参数,如perms,roles 95 | */ 96 | @Bean(name = "shiroFilter") 97 | public ShiroFilterFactoryBean getShiroFilterFactoryBean() { 98 | logger.debug("ShiroConfigration.getShiroFilterFactoryBean()"); 99 | ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); 100 | // 必须设置 SecurityManager 101 | shiroFilterFactoryBean.setSecurityManager(securityManager()); 102 | 103 | HashMap loginFilter = new HashMap<>(); 104 | loginFilter.put("loginFilter", new LoginFilter()); 105 | shiroFilterFactoryBean.setFilters(loginFilter); 106 | 107 | 108 | filterChainDefinitionMap.put("/login/submit", "anon"); 109 | filterChainDefinitionMap.put("/logout", "anon"); 110 | filterChainDefinitionMap.put("/img/**", "anon"); 111 | filterChainDefinitionMap.put("/js/**", "anon"); 112 | filterChainDefinitionMap.put("/css/**", "anon"); 113 | 114 | // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面 115 | shiroFilterFactoryBean.setLoginUrl("/login"); 116 | 117 | //配置记住我或认证通过可以访问的地址 118 | filterChainDefinitionMap.put("/", "user"); 119 | //未授权界面; 120 | shiroFilterFactoryBean.setUnauthorizedUrl("/unauth"); 121 | filterChainDefinitionMap.put("/**", "loginFilter"); 122 | shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); 123 | return shiroFilterFactoryBean; 124 | } 125 | 126 | /** 127 | * shiro缓存管理器; 128 | * 需要注入对应的其它的实体类中: 129 | * 1、安全管理器:securityManager 130 | * 可见securityManager是整个shiro的核心; 131 | * 132 | * @return 133 | */ 134 | @Bean 135 | public EhCacheManager ehCacheManager() { 136 | EhCacheManager cacheManager = new EhCacheManager(); 137 | cacheManager.setCacheManagerConfigFile("classpath:ehcache-shiro.xml"); 138 | return cacheManager; 139 | } 140 | 141 | 142 | @Bean 143 | public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) { 144 | AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); 145 | authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); 146 | return authorizationAttributeSourceAdvisor; 147 | } 148 | 149 | } 150 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/config/Swagger2.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | 6 | import springfox.documentation.builders.ApiInfoBuilder; 7 | import springfox.documentation.builders.PathSelectors; 8 | import springfox.documentation.builders.RequestHandlerSelectors; 9 | import springfox.documentation.service.ApiInfo; 10 | import springfox.documentation.spi.DocumentationType; 11 | import springfox.documentation.spring.web.plugins.Docket; 12 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 13 | 14 | @Configuration 15 | @EnableSwagger2 16 | public class Swagger2 { 17 | 18 | @Bean 19 | public Docket createRestApi() { 20 | return new Docket(DocumentationType.SWAGGER_2) 21 | .apiInfo(apiInfo()) 22 | .select() 23 | .apis(RequestHandlerSelectors 24 | .basePackage("com.onecoderspace.base.controller")) 25 | .paths(PathSelectors.any()).build(); 26 | } 27 | 28 | private ApiInfo apiInfo() { 29 | return new ApiInfoBuilder() 30 | .title("基础项目接口API") 31 | .description("基础项目接口API") 32 | .version("1.0").build(); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/config/WebConfig.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.config; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Date; 5 | import java.util.Map; 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.beans.factory.annotation.Value; 9 | import org.springframework.boot.actuate.autoconfigure.ExportMetricWriter; 10 | import org.springframework.boot.actuate.endpoint.MetricReaderPublicMetrics; 11 | import org.springframework.boot.actuate.endpoint.PublicMetrics; 12 | import org.springframework.boot.actuate.metrics.aggregate.AggregateMetricReader; 13 | import org.springframework.boot.actuate.metrics.export.MetricExportProperties; 14 | import org.springframework.boot.actuate.metrics.reader.MetricReader; 15 | import org.springframework.boot.actuate.metrics.repository.redis.RedisMetricRepository; 16 | import org.springframework.boot.actuate.metrics.writer.MetricWriter; 17 | import org.springframework.boot.web.servlet.FilterRegistrationBean; 18 | import org.springframework.context.annotation.Bean; 19 | import org.springframework.context.annotation.Configuration; 20 | import org.springframework.core.convert.converter.Converter; 21 | import org.springframework.data.redis.connection.RedisConnectionFactory; 22 | import org.springframework.http.HttpHeaders; 23 | import org.springframework.web.servlet.config.annotation.CorsRegistry; 24 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 25 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 26 | 27 | import com.google.common.collect.Maps; 28 | import com.onecoderspace.base.filter.CsrfFilter; 29 | import com.onecoderspace.base.filter.ShiroSessionFilter; 30 | import com.onecoderspace.base.filter.XssFilter; 31 | 32 | @Configuration 33 | public class WebConfig { 34 | 35 | @Autowired 36 | private RedisConnectionFactory redisConnectionFactory; 37 | 38 | @Value("${server.session.timeout}") 39 | private String serverSessionTimeout; 40 | 41 | @Value("${csrf.filter.open}") 42 | private String isCsrfFilterOpen; 43 | 44 | @Bean 45 | @ExportMetricWriter 46 | MetricWriter metricWriter(MetricExportProperties export) { 47 | return new RedisMetricRepository(redisConnectionFactory, export 48 | .getRedis().getPrefix(), export.getRedis().getKey()); 49 | } 50 | 51 | @Autowired 52 | private MetricExportProperties export; 53 | 54 | @Bean 55 | public PublicMetrics metricsAggregate() { 56 | return new MetricReaderPublicMetrics(aggregatesMetricReader()); 57 | } 58 | 59 | private MetricReader globalMetricsForAggregation() { 60 | return new RedisMetricRepository(this.redisConnectionFactory, 61 | this.export.getRedis().getAggregatePrefix(), this.export 62 | .getRedis().getKey()); 63 | } 64 | 65 | private MetricReader aggregatesMetricReader() { 66 | AggregateMetricReader repository = new AggregateMetricReader( 67 | globalMetricsForAggregation()); 68 | return repository; 69 | } 70 | 71 | /** 72 | * 参数绑定时将String时间转换为Date 73 | * @author yangwk 74 | * @time 2017年7月26日 下午4:53:19 75 | * @return 76 | */ 77 | @Bean 78 | public Converter stringDateConvert() { 79 | return new Converter() { 80 | @Override 81 | public Date convert(String source) { 82 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 83 | Date date = null; 84 | try { 85 | date = sdf.parse((String) source); 86 | } catch (Exception e) { 87 | e.printStackTrace(); 88 | } 89 | return date; 90 | } 91 | }; 92 | } 93 | 94 | /** 95 | * 解决跨域调用问题 96 | */ 97 | @Bean 98 | public WebMvcConfigurer corsConfigurer() { 99 | return new WebMvcConfigurerAdapter() { 100 | @Override 101 | public void addCorsMappings(CorsRegistry registry) { 102 | registry.addMapping("/**").allowedOrigins("*") 103 | .allowedMethods("*").allowedHeaders("*") 104 | .allowCredentials(true) 105 | .exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L); 106 | } 107 | }; 108 | } 109 | 110 | /** 111 | * xss过滤拦截器 112 | */ 113 | @Bean 114 | public FilterRegistrationBean xssFilterRegistrationBean() { 115 | FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); 116 | filterRegistrationBean.setFilter(new XssFilter()); 117 | filterRegistrationBean.setOrder(1); 118 | filterRegistrationBean.setEnabled(true); 119 | filterRegistrationBean.addUrlPatterns("/*"); 120 | Map initParameters = Maps.newHashMap(); 121 | initParameters.put("excludes", "/favicon.ico,/img/*,/js/*,/css/*"); 122 | initParameters.put("isIncludeRichText", "true"); 123 | filterRegistrationBean.setInitParameters(initParameters); 124 | return filterRegistrationBean; 125 | } 126 | 127 | /** 128 | * csrf过滤拦截器 只处理post请求 129 | */ 130 | @Bean 131 | public FilterRegistrationBean csrfFilterRegistrationBean() { 132 | FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); 133 | filterRegistrationBean.setFilter(new CsrfFilter()); 134 | filterRegistrationBean.setOrder(2); 135 | filterRegistrationBean.setEnabled(true); 136 | filterRegistrationBean.addUrlPatterns("/*"); 137 | Map initParameters = Maps.newHashMap(); 138 | initParameters.put("excludes", "/login/*"); 139 | initParameters.put("isOpen", isCsrfFilterOpen); 140 | filterRegistrationBean.setInitParameters(initParameters); 141 | return filterRegistrationBean; 142 | } 143 | 144 | @Bean 145 | public FilterRegistrationBean shiroSessionFilterRegistrationBean() { 146 | FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); 147 | filterRegistrationBean.setFilter(new ShiroSessionFilter()); 148 | filterRegistrationBean.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE); 149 | filterRegistrationBean.setEnabled(true); 150 | filterRegistrationBean.addUrlPatterns("/*"); 151 | Map initParameters = Maps.newHashMap(); 152 | initParameters.put("serverSessionTimeout", serverSessionTimeout); 153 | initParameters.put("excludes", "/favicon.ico,/img/*,/js/*,/css/*"); 154 | filterRegistrationBean.setInitParameters(initParameters); 155 | return filterRegistrationBean; 156 | } 157 | 158 | } 159 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/controller/LoginController.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.controller; 2 | 3 | import io.swagger.annotations.Api; 4 | import io.swagger.annotations.ApiImplicitParam; 5 | import io.swagger.annotations.ApiImplicitParams; 6 | import io.swagger.annotations.ApiOperation; 7 | 8 | import java.util.Map; 9 | import java.util.UUID; 10 | 11 | import javax.servlet.http.HttpServletRequest; 12 | import javax.servlet.http.HttpServletResponse; 13 | 14 | import org.apache.commons.lang3.math.NumberUtils; 15 | import org.apache.shiro.SecurityUtils; 16 | import org.apache.shiro.authc.AuthenticationException; 17 | import org.apache.shiro.authc.ExcessiveAttemptsException; 18 | import org.apache.shiro.authc.IncorrectCredentialsException; 19 | import org.apache.shiro.authc.LockedAccountException; 20 | import org.apache.shiro.authc.UnknownAccountException; 21 | import org.apache.shiro.authc.UsernamePasswordToken; 22 | import org.apache.shiro.subject.Subject; 23 | import org.slf4j.Logger; 24 | import org.slf4j.LoggerFactory; 25 | import org.springframework.beans.factory.annotation.Autowired; 26 | import org.springframework.beans.factory.annotation.Value; 27 | import org.springframework.web.bind.annotation.RequestMapping; 28 | import org.springframework.web.bind.annotation.RequestMethod; 29 | import org.springframework.web.bind.annotation.RequestParam; 30 | import org.springframework.web.bind.annotation.RestController; 31 | 32 | import com.google.common.collect.Maps; 33 | import com.onecoderspace.base.domain.User; 34 | import com.onecoderspace.base.service.UserService; 35 | import com.onecoderspace.base.util.SaltMD5Util; 36 | 37 | @Api(value="用户登录",tags={"用户登录"}) 38 | @RestController 39 | public class LoginController { 40 | private static Logger logger = LoggerFactory.getLogger(LoginController.class); 41 | 42 | @Value("${server.session.timeout}") 43 | private String serverSessionTimeout; 44 | 45 | /** 46 | * 用户登录接口 通过用户名和密码进行登录 47 | */ 48 | @ApiOperation(value = "用户登录接口 通过用户名和密码进行登录", notes = "用户登录接口 通过用户名和密码进行登录") 49 | @ApiImplicitParams({ 50 | @ApiImplicitParam(paramType = "query", name = "username", value = "用户名", required = true, dataType = "String"), 51 | @ApiImplicitParam(paramType = "query", name = "pwd", value = "密码", required = true, dataType = "String"), 52 | @ApiImplicitParam(paramType = "query", name = "autoLogin", value = "自动登录", required = true, dataType = "boolean")}) 53 | @RequestMapping(value = "/login/submit",method={RequestMethod.GET,RequestMethod.POST}) 54 | public Map subm(HttpServletRequest request,HttpServletResponse response, 55 | String username,String pwd,@RequestParam(value = "autoLogin", defaultValue = "false") boolean autoLogin) { 56 | Map map = Maps.newLinkedHashMap(); 57 | Subject currentUser = SecurityUtils.getSubject(); 58 | User user = userService.findByUsername(username); 59 | if (user == null) { 60 | map.put("code", "-1"); 61 | map.put("description", "账号不存在"); 62 | return map; 63 | } 64 | if (user.getEnable() == 0) { //账号被禁用 65 | map.put("code", "-1"); 66 | map.put("description", "账号已被禁用"); 67 | return map; 68 | } 69 | 70 | String salt = user.getSalt(); 71 | UsernamePasswordToken token = null; 72 | Integer userId = user.getId(); 73 | token = new UsernamePasswordToken(userId.toString(),SaltMD5Util.encode(pwd, salt)); 74 | token.setRememberMe(autoLogin); 75 | 76 | loginValid(map, currentUser, token); 77 | 78 | // 验证是否登录成功 79 | if (currentUser.isAuthenticated()) { 80 | map.put("code","1"); 81 | map.put("description", "ok"); 82 | map.put("id", String.valueOf(userId)); 83 | map.put("username", user.getUsername()); 84 | map.put("name", user.getName()); 85 | String uuidToken = UUID.randomUUID().toString(); 86 | map.put("token", uuidToken); 87 | 88 | currentUser.getSession().setTimeout(NumberUtils.toLong(serverSessionTimeout, 1800)*1000); 89 | request.getSession().setAttribute("token",uuidToken ); 90 | } else { 91 | map.put("code", "-1"); 92 | token.clear(); 93 | } 94 | return map; 95 | } 96 | 97 | @RequestMapping(value="test/set",method=RequestMethod.GET) 98 | public String testSet(HttpServletRequest request) { 99 | request.getSession().setAttribute("test", "test"); 100 | return "success"; 101 | } 102 | 103 | @RequestMapping(value="test/get",method=RequestMethod.GET) 104 | public String testGet(HttpServletRequest request) { 105 | String value = (String) request.getSession().getAttribute("test"); 106 | return value == null ? "null" : value; 107 | } 108 | 109 | @RequestMapping(value="logout",method=RequestMethod.GET) 110 | public Map logout() { 111 | Map map = Maps.newLinkedHashMap(); 112 | Subject currentUser = SecurityUtils.getSubject(); 113 | currentUser.logout(); 114 | map.put("code", "logout"); 115 | return map; 116 | } 117 | 118 | @RequestMapping(value="unauth",method=RequestMethod.GET) 119 | public Map unauth() { 120 | Map map = Maps.newLinkedHashMap(); 121 | map.put("code", "403"); 122 | map.put("msg", "你没有访问权限"); 123 | return map; 124 | } 125 | 126 | private boolean loginValid(Map map,Subject currentUser, UsernamePasswordToken token) { 127 | String username = null; 128 | if (token != null) { 129 | username = (String) token.getPrincipal(); 130 | } 131 | 132 | try { 133 | // 在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查 134 | // 每个Realm都能在必要时对提交的AuthenticationTokens作出反应 135 | // 所以这一步在调用login(token)方法时,它会走到MyRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法 136 | currentUser.login(token); 137 | return true; 138 | } catch (UnknownAccountException | IncorrectCredentialsException ex) { 139 | map.put("description", "账号或密码错误"); 140 | } catch (LockedAccountException lae) { 141 | map.put("description","账户已锁定"); 142 | } catch (ExcessiveAttemptsException eae) { 143 | map.put("description", "错误次数过多"); 144 | } catch (AuthenticationException ae) { 145 | // 通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景 146 | map.put("description", "登录失败"); 147 | logger.warn(String.format("对用户[%s]进行登录验证..验证未通过", username),ae); 148 | } 149 | return false; 150 | } 151 | 152 | @Autowired 153 | private UserService userService; 154 | } 155 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/controller/UploadController.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.controller; 2 | 3 | import io.swagger.annotations.Api; 4 | import io.swagger.annotations.ApiImplicitParam; 5 | import io.swagger.annotations.ApiOperation; 6 | 7 | import java.io.File; 8 | import java.io.IOException; 9 | import java.util.HashSet; 10 | import java.util.List; 11 | import java.util.Set; 12 | import java.util.UUID; 13 | 14 | import org.jsoup.helper.StringUtil; 15 | import org.slf4j.Logger; 16 | import org.slf4j.LoggerFactory; 17 | import org.springframework.beans.factory.annotation.Value; 18 | import org.springframework.web.bind.annotation.RequestMapping; 19 | import org.springframework.web.bind.annotation.RequestMethod; 20 | import org.springframework.web.bind.annotation.RequestParam; 21 | import org.springframework.web.bind.annotation.RestController; 22 | import org.springframework.web.multipart.MultipartFile; 23 | 24 | import com.google.common.collect.Lists; 25 | import com.onecoderspace.base.util.DateUtils; 26 | import com.onecoderspace.base.util.RandomUtils; 27 | 28 | @Api(value = "上传图片", tags = { "上传图片" }) 29 | @RestController 30 | @RequestMapping("/upload") 31 | public class UploadController { 32 | 33 | private static Logger logger = LoggerFactory.getLogger(UploadController.class); 34 | 35 | @Value("${upload.file.path}") 36 | private String uploadFilePath;//值类似于/var/www/html/upload 37 | 38 | @Value("${upload.file.path.project.name}") 39 | private String projectName; //值类似于dmp 40 | 41 | /** 42 | * 上传图片 43 | * @author yangwk 44 | * @time 2017年7月28日 下午3:42:41 45 | * @param files 46 | * @return 47 | */ 48 | @ApiOperation(value = "上传图片", notes = "上传图片") 49 | @ApiImplicitParam(paramType = "query", name = "files", value = "图片上传", required = true, dataType = "MultipartFile") 50 | @RequestMapping(value = "/img", method = RequestMethod.POST) 51 | public List img(@RequestParam("file") MultipartFile[] files) { 52 | String savePath = String.format("/%s/img/%s/%s",projectName, RandomUtils.randomNum(2),RandomUtils.randomNum(2)); 53 | List paths = Lists.newArrayList(); 54 | for (MultipartFile file : files) { 55 | String name = file.getOriginalFilename(); 56 | String suffix = ""; 57 | if(suffix.lastIndexOf(".") != -1){ 58 | suffix = name.substring(name.lastIndexOf(".")); 59 | } 60 | if (StringUtil.isBlank(suffix)) { 61 | suffix = ".jpg"; 62 | } 63 | name = String.format("%s-%s%s",DateUtils.getCurrentTime("yyyyMMdd"), getRandomUniqName(), suffix); 64 | boolean success = saveFile(savePath, name, file); 65 | if (success) { 66 | paths.add(String.format("%s/%s", savePath, name)); 67 | } else { 68 | paths.add(""); 69 | } 70 | } 71 | return paths; 72 | } 73 | 74 | /** 75 | * 上传图片 76 | * @author yangwk 77 | * @time 2017年7月28日 下午3:42:41 78 | * @param files 79 | * @return 80 | */ 81 | @ApiOperation(value = "上传文件", notes = "上传图片") 82 | @ApiImplicitParam(paramType = "query", name = "files", value = "图片上传", required = true, dataType = "MultipartFile") 83 | @RequestMapping(value = "/file", method = RequestMethod.POST) 84 | public List file(@RequestParam("file") MultipartFile[] files) { 85 | String savePath = String.format("/%s/file/%s/%s",projectName, RandomUtils.randomNum(2),RandomUtils.randomNum(2)); 86 | List paths = Lists.newArrayList(); 87 | for (MultipartFile file : files) { 88 | String name = file.getOriginalFilename(); 89 | String suffix = ""; 90 | if(suffix.lastIndexOf(".") != -1){ 91 | suffix = name.substring(name.lastIndexOf(".")); 92 | } 93 | name = String.format("%s-%s%s",DateUtils.getCurrentTime("yyyyMMdd"),getRandomUniqName(), suffix); 94 | boolean success = saveFile(savePath, name, file); 95 | if (success) { 96 | paths.add(String.format("%s/%s", savePath, name)); 97 | } else { 98 | paths.add(""); 99 | } 100 | } 101 | return paths; 102 | } 103 | 104 | /** 105 | * 获取随机值:10w以内基本可保证唯一,但非绝对不唯一 106 | * @author yangwk 107 | * @time 2017年8月16日 下午3:18:18 108 | * @return 109 | */ 110 | private static String getRandomUniqName(){ 111 | String prefix = RandomUtils.randomNum(1);//最大支持1-9个集群机器部署 112 | int hashCodeV = UUID.randomUUID().toString().hashCode(); 113 | if(hashCodeV < 0) {//有可能是负数 114 | hashCodeV = - hashCodeV; 115 | } 116 | // 0 代表前面补充0 117 | // 4 代表长度为4 118 | // d 代表参数为正数型 119 | return String.format("%s%015d",prefix, hashCodeV); 120 | } 121 | 122 | public static void main(String[] args) { 123 | Set set = new HashSet(100000); 124 | for(int i=0;i<100;i++){ 125 | String value = getRandomUniqName(); 126 | if(set.contains(value)){ 127 | System.err.println(value); 128 | } 129 | set.add(value); 130 | } 131 | } 132 | 133 | private boolean saveFile(String savePath, String name, MultipartFile file) { 134 | String path = String.format("%s%s", uploadFilePath, savePath); 135 | File dir = new File(path); 136 | if (!dir.exists()) { 137 | dir.mkdirs(); 138 | } 139 | // 保存文件 140 | try { 141 | file.transferTo(new File(String.format("%s/%s", path, name))); 142 | } catch (IOException e) { 143 | logger.error("save file due to error", e); 144 | return false; 145 | } 146 | return true; 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/controller/UserController.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.controller; 2 | 3 | import io.swagger.annotations.Api; 4 | import io.swagger.annotations.ApiImplicitParam; 5 | import io.swagger.annotations.ApiImplicitParams; 6 | import io.swagger.annotations.ApiOperation; 7 | 8 | import org.apache.commons.lang3.StringUtils; 9 | import org.apache.shiro.SecurityUtils; 10 | import org.apache.shiro.authz.annotation.RequiresPermissions; 11 | import org.apache.shiro.subject.Subject; 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.web.bind.annotation.RequestMapping; 14 | import org.springframework.web.bind.annotation.RequestMethod; 15 | import org.springframework.web.bind.annotation.RestController; 16 | 17 | import com.onecoderspace.base.domain.User; 18 | import com.onecoderspace.base.service.UserService; 19 | import com.onecoderspace.base.util.Return; 20 | import com.onecoderspace.base.util.SaltMD5Util; 21 | 22 | @Api(value="用户管理",tags={"用户管理"}) 23 | @RestController 24 | @RequestMapping("/user") 25 | public class UserController { 26 | 27 | @ApiOperation(value="获取用户详细信息", notes="根据ID查找用户") 28 | @ApiImplicitParam(paramType="query",name = "id", value = "用户ID", required = true,dataType="int") 29 | @RequiresPermissions(value={"user:get"}) 30 | @RequestMapping(value="/get",method=RequestMethod.GET) 31 | public User get(int id){ 32 | User entity = userService.findById(id); 33 | entity.setPwd(null); 34 | entity.setSalt(null); 35 | return entity; 36 | } 37 | 38 | @ApiOperation(value="修改密码", notes="修改密码") 39 | @ApiImplicitParams({ 40 | @ApiImplicitParam(paramType = "query", name = "oldPwd", value = "旧密码", required = true, dataType = "String"), 41 | @ApiImplicitParam(paramType = "query", name = "pwd", value = "新密码", required = true, dataType = "String"), 42 | @ApiImplicitParam(paramType = "query", name = "confirmPwd", value = "新密码(确认)", required = true, dataType = "String")}) 43 | @RequiresPermissions(value={"user:reset-pwd"}) 44 | @RequestMapping(value="/reset-pwd",method=RequestMethod.POST) 45 | public Return resetPwd(String oldPwd,String pwd,String confirmPwd){ 46 | if(StringUtils.isBlank(oldPwd) || StringUtils.isBlank(pwd) 47 | || StringUtils.isBlank(confirmPwd) || !pwd.equals(confirmPwd)) { 48 | return Return.fail("非法参数"); 49 | } 50 | 51 | Subject currentUser = SecurityUtils.getSubject(); 52 | Integer userId=(Integer) currentUser.getPrincipal(); 53 | User entity = userService.findById(userId); 54 | if(!entity.getPwd().equals(SaltMD5Util.encode(oldPwd, entity.getSalt()))){ 55 | return Return.fail("原始密码错误"); 56 | } 57 | return userService.changePwd(entity,pwd); 58 | } 59 | 60 | @ApiOperation(value="返回当前用户", notes="返回当前用户") 61 | @RequiresPermissions(value={"user:current"}) 62 | @RequestMapping(value="/current",method=RequestMethod.GET) 63 | public User current(){ 64 | //得到当前用户 65 | Subject currentUser = SecurityUtils.getSubject(); 66 | Integer userId=(Integer) currentUser.getPrincipal(); 67 | User entity = userService.findById(userId); 68 | entity.setPwd(null); 69 | entity.setSalt(null); 70 | return entity; 71 | } 72 | 73 | @Autowired 74 | private UserService userService; 75 | 76 | } -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/controller/admin/AdminUserController.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.controller.admin; 2 | 3 | import io.swagger.annotations.Api; 4 | import io.swagger.annotations.ApiImplicitParam; 5 | import io.swagger.annotations.ApiImplicitParams; 6 | import io.swagger.annotations.ApiOperation; 7 | 8 | import java.sql.Timestamp; 9 | import java.util.List; 10 | import java.util.Map; 11 | 12 | import org.apache.shiro.authz.annotation.RequiresPermissions; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.data.domain.Page; 15 | import org.springframework.data.domain.PageRequest; 16 | import org.springframework.data.domain.Sort; 17 | import org.springframework.data.domain.Sort.Direction; 18 | import org.springframework.web.bind.annotation.RequestMapping; 19 | import org.springframework.web.bind.annotation.RequestMethod; 20 | import org.springframework.web.bind.annotation.RequestParam; 21 | import org.springframework.web.bind.annotation.RestController; 22 | 23 | import com.google.common.collect.Maps; 24 | import com.onecoderspace.base.domain.User; 25 | import com.onecoderspace.base.domain.UserRole; 26 | import com.onecoderspace.base.service.UserRoleService; 27 | import com.onecoderspace.base.service.UserService; 28 | import com.onecoderspace.base.util.Constants; 29 | import com.onecoderspace.base.util.LoginSessionHelper; 30 | import com.onecoderspace.base.util.Return; 31 | import com.onecoderspace.base.util.SaltMD5Util; 32 | 33 | @Api(value = "运营接口 用户", tags = { "运营接口 用户" }) 34 | @RestController("adminUserController") 35 | @RequestMapping(value="/admin/user") 36 | public class AdminUserController { 37 | 38 | @ApiOperation(value = "分页获取用户数据", notes = "根据用户名获取用户姓名获取用户数据") 39 | @ApiImplicitParams({ 40 | @ApiImplicitParam(paramType = "query", name = "type", value = "用户类别 0普通用户 1运营人员", required = true, dataType = "String"), 41 | @ApiImplicitParam(paramType = "query", name = "status", value = "账号状态 0已注册未审核 1待审核 2审核通过 -1审核未通过", required = true, dataType = "String"), 42 | @ApiImplicitParam(paramType = "query", name = "username", value = "用户名", required = true, dataType = "String"), 43 | @ApiImplicitParam(paramType = "query", name = "name", value = "用户姓名", required = true, dataType = "String"), 44 | @ApiImplicitParam(paramType = "query", name = "page", value = "分页,页码从0开始", required = true, dataType = "int"), 45 | @ApiImplicitParam(paramType = "query", name = "size", value = "每一页大小", required = true, dataType = "int") }) 46 | @RequiresPermissions(value = { "admin:user:list" }) 47 | @RequestMapping(value = "/list", method = RequestMethod.GET) 48 | public Page list(String type, String status, String username, String name, 49 | @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "10") int size) { 50 | Map params = Maps.newHashMap(); 51 | params.put("type", type); 52 | params.put("status", status); 53 | params.put("username", username); 54 | params.put("name", name); 55 | Page rs = this.userService.listByPage(params,new PageRequest(page, size, new Sort(Direction.DESC, "updateTime"))); 56 | 57 | /*//或者使用service内的公共方法也可以 58 | Map params2 = Maps.newHashMap(); 59 | params.put("type", type); 60 | params.put("status", status); 61 | params.put("username:like", username); 62 | params.put("name:like", name); 63 | Page rs2 = this.userService.list(params2, new PageRequest(page, size, new Sort(Direction.DESC, "updateTime"))); 64 | */ 65 | for (User user : rs.getContent()) { 66 | user.setPwd(null); 67 | user.setSalt(null); 68 | } 69 | return rs; 70 | } 71 | 72 | @ApiOperation(value = "用户审核时的全部信息", notes = "用户审核时的全部信息:用户信息、公司信息、公司资质信息,根据id查询用户") 73 | @ApiImplicitParam(paramType = "query", name = "id", value = "用户id", required = true, dataType = "int") 74 | @RequiresPermissions(value = { "admin:user:audit-info" }) 75 | @RequestMapping(value = "/audit-info", method = RequestMethod.GET) 76 | public Map auditInfo(int id) { 77 | Map map = Maps.newHashMap(); 78 | User entity = userService.findById(id); 79 | entity.setPwd(null); 80 | entity.setSalt(null); 81 | map.put("user", entity); 82 | return map; 83 | } 84 | 85 | @ApiOperation(value = "审核用户账号", notes = "审核用户账号") 86 | @ApiImplicitParams({ 87 | @ApiImplicitParam(paramType = "query", name = "id", value = "用户id", required = true, dataType = "int"), 88 | @ApiImplicitParam(paramType = "query", name = "value", value = "value 0未通过 1通过", required = true, dataType = "int"), 89 | @ApiImplicitParam(paramType = "query", name = "msg", value = "不通过原因", required = true, dataType = "String") }) 90 | @RequiresPermissions(value = { "admin:user:audit" }) 91 | @RequestMapping(value = "/audit", method = RequestMethod.GET) 92 | public Return audit(int id, int value, String msg) { 93 | User entity = userService.findById(id); 94 | if (entity == null) { 95 | return Return.fail("用户已不存在"); 96 | } 97 | if (entity.getStatus() != User.STATUS_WAIT_AUDIT) { 98 | return Return.fail("用户不是待审核状态"); 99 | } 100 | return userService.doAudit(entity, value, msg); 101 | } 102 | 103 | @ApiOperation(value = "保存用户信息", notes = "保存用户信息") 104 | @ApiImplicitParam(paramType = "query", name = "user", value = "用户实体", required = true, dataType = "user") 105 | @RequiresPermissions(value = { "admin:user:save" }) 106 | @RequestMapping(value = "/save", method = RequestMethod.GET) 107 | public Return save(User user) { 108 | int currentUid = LoginSessionHelper.getCurrentUserId(); 109 | if (user.getId() != null && user.getId() != 0) { 110 | User old = userService.findById(user.getId()); 111 | if (old == null) { 112 | return Return.fail("信息已不存在"); 113 | } 114 | user.setUsername(old.getUsername()); 115 | user.setPwd(old.getPwd()); 116 | user.setSalt(old.getSalt()); 117 | user.setStatus(old.getStatus()); 118 | user.setType(old.getType()); 119 | user.setDel(old.getDel()); 120 | user.setRegisterTime(old.getRegisterTime()); 121 | user.setEnable(old.getEnable()); 122 | 123 | } else { 124 | user.setDel(Constants.DEL_NO); 125 | user.setStatus(User.STATUS_UNAUDIT); 126 | user.setEnable(1); 127 | String salt = SaltMD5Util.getSalt(); 128 | String pwd = SaltMD5Util.encode(user.getPwd(), salt); 129 | user.setPwd(pwd); 130 | user.setSalt(salt); 131 | user.setRegisterTime(new Timestamp(System.currentTimeMillis())); 132 | 133 | } 134 | user.setUpdator(currentUid); 135 | user.setUpdateTime(new Timestamp(System.currentTimeMillis())); 136 | 137 | Return re = this.userService.saveUser(user); 138 | return re; 139 | } 140 | 141 | @ApiOperation(value = "标记删除", notes = "标记删除") 142 | @ApiImplicitParam(paramType = "query", name = "id", value = "用户id",dataType = "int") 143 | @RequiresPermissions(value = { "admin:user:delete" }) 144 | @RequestMapping(value="/delete",method=RequestMethod.GET) 145 | public Return delete(int id) { 146 | User user = this.userService.findById(id); 147 | user.setDel(Constants.DEL_YES); 148 | userService.save(user); 149 | return Return.success(); 150 | } 151 | 152 | @ApiOperation(value = "用户拥有的角色", notes = " 用户拥有的角色") 153 | @ApiImplicitParam(paramType = "query", name = "uid", value = "用户uid", required = true, dataType = "int") 154 | @RequiresPermissions(value = { "admin:user:role:list" }) 155 | @RequestMapping(value="/role/list",method=RequestMethod.GET) 156 | public List roleList(int uid) { 157 | List userRoles = userRoleService.findByUserId(uid); 158 | return userRoles; 159 | } 160 | 161 | @ApiOperation(value = "设置用户角色", notes = "设置用户角色") 162 | @ApiImplicitParams({ 163 | @ApiImplicitParam(paramType = "query", name = "uid", value = "用户uid", required = true, dataType = "int"), 164 | @ApiImplicitParam(paramType = "query", name = "roleids", value = "角色id", required = true, dataType = "String") 165 | }) 166 | @RequiresPermissions(value = { "admin:user:role:set" }) 167 | @RequestMapping(value="/role/set",method=RequestMethod.POST) 168 | public Return roleSet(int uid, String roleIds) { 169 | return userService.doSetRoles(uid, roleIds); 170 | } 171 | 172 | @Autowired 173 | private UserService userService; 174 | 175 | @Autowired 176 | private UserRoleService userRoleService; 177 | } -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/controller/admin/PermissionController.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.controller.admin; 2 | 3 | import io.swagger.annotations.Api; 4 | import io.swagger.annotations.ApiImplicitParam; 5 | import io.swagger.annotations.ApiOperation; 6 | 7 | import org.apache.shiro.authz.annotation.RequiresPermissions; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.data.domain.Sort; 10 | import org.springframework.data.domain.Sort.Direction; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RequestMethod; 13 | import org.springframework.web.bind.annotation.RestController; 14 | 15 | import com.onecoderspace.base.domain.Permission; 16 | import com.onecoderspace.base.service.PermissionService; 17 | import com.onecoderspace.base.util.Return; 18 | 19 | 20 | @Api(value = "运营接口 权限", tags = { "运营接口 权限" }) 21 | @RestController 22 | @RequestMapping("/admin/permission") 23 | public class PermissionController { 24 | 25 | @ApiOperation(value = "获取所有权限", notes = "获取所有权限") 26 | @RequiresPermissions(value={"admin:permission:list"}) 27 | @RequestMapping(value="/list",method=RequestMethod.GET) 28 | public Iterable list(){ 29 | Iterable list = this.permissionService.findAll(new Sort(Direction.ASC, "weight","id")); 30 | return list; 31 | } 32 | 33 | @ApiOperation(value = "新增/修改 权限", notes = "保存 新增/修改的 权限") 34 | @ApiImplicitParam(paramType = "query", name = "permission", value = "菜单操作权限实体", required = true, dataType = "Permission") 35 | @RequiresPermissions(value={"admin:permission:save"}) 36 | @RequestMapping(value="/save",method=RequestMethod.GET) 37 | public Return save(Permission permission){ 38 | this.permissionService.save(permission); 39 | return Return.success(); 40 | } 41 | 42 | 43 | @ApiOperation(value = "删除 权限", notes = "根据id删除权限") 44 | @ApiImplicitParam(paramType = "query", name = "id", value = "权限id", required = true, dataType = "int") 45 | @RequiresPermissions(value={"admin:permission:delete"}) 46 | @RequestMapping(value="/delete",method=RequestMethod.GET) 47 | public Return delete(int id){ 48 | this.permissionService.del(id); 49 | return Return.success(); 50 | } 51 | 52 | @ApiOperation(value = "获取权限", notes = "根据id查询权限") 53 | @ApiImplicitParam(paramType = "query", name = "id", value = "权限id", required = true, dataType = "int") 54 | @RequiresPermissions(value={"admin:permission:get"}) 55 | @RequestMapping(value="/get",method=RequestMethod.GET) 56 | public Permission get(int id){ 57 | Permission entity = permissionService.findById(id); 58 | return entity; 59 | } 60 | 61 | @Autowired 62 | private PermissionService permissionService; 63 | 64 | } -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/controller/admin/RoleController.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.controller.admin; 2 | 3 | import io.swagger.annotations.Api; 4 | import io.swagger.annotations.ApiImplicitParam; 5 | import io.swagger.annotations.ApiImplicitParams; 6 | import io.swagger.annotations.ApiOperation; 7 | 8 | import java.util.List; 9 | 10 | import org.apache.shiro.authz.annotation.RequiresPermissions; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.data.domain.Page; 13 | import org.springframework.data.domain.PageRequest; 14 | import org.springframework.data.domain.Sort; 15 | import org.springframework.data.domain.Sort.Direction; 16 | import org.springframework.web.bind.annotation.RequestMapping; 17 | import org.springframework.web.bind.annotation.RequestMethod; 18 | import org.springframework.web.bind.annotation.RequestParam; 19 | import org.springframework.web.bind.annotation.RestController; 20 | 21 | import com.onecoderspace.base.domain.Role; 22 | import com.onecoderspace.base.domain.RolePermission; 23 | import com.onecoderspace.base.service.RolePermissionService; 24 | import com.onecoderspace.base.service.RoleService; 25 | import com.onecoderspace.base.util.Return; 26 | 27 | @Api(value="角色管理",tags={"运营接口 角色"}) 28 | @RestController 29 | @RequestMapping("/admin/role") 30 | public class RoleController { 31 | 32 | @ApiOperation(value="分页查询",notes="分页查询") 33 | @ApiImplicitParams({ 34 | @ApiImplicitParam(paramType="query",name="page",value="分页,页码从0开始",required=true,dataType="int"), 35 | @ApiImplicitParam(paramType="query",name="size",value="每一页大小",required=true,dataType="int")} 36 | ) 37 | @RequiresPermissions(value={"admin:permission:list"}) 38 | @RequestMapping(value="/list",method=RequestMethod.GET) 39 | public Page list(String name, @RequestParam(defaultValue = "0") int page, 40 | @RequestParam(defaultValue = "10") int size) { 41 | Page rs = this.roleService.listByPage(name, new PageRequest(page, size, new Sort(Direction.DESC, "id"))); 42 | return rs; 43 | } 44 | 45 | @ApiOperation(value="新增&修改",notes="新增&修改") 46 | @ApiImplicitParam(paramType="query",name="role",value="角色",dataType="Role") 47 | @RequiresPermissions(value={"admin:permission:save"}) 48 | @RequestMapping(value="/save",method=RequestMethod.GET) 49 | public Return save(Role role) { 50 | this.roleService.save(role); 51 | return Return.success(); 52 | } 53 | 54 | @ApiOperation(value="查询",notes="根据id查询") 55 | @ApiImplicitParam(paramType="query",name="id",value="角色id",required=true,dataType="int") 56 | @RequiresPermissions(value={"admin:permission:get"}) 57 | @RequestMapping(value="/get",method=RequestMethod.GET) 58 | public Role get(int id) { 59 | Role entity = roleService.findById(id); 60 | return entity; 61 | } 62 | 63 | @ApiOperation(value="删除",notes="根据id删除") 64 | @ApiImplicitParam(paramType="query",name="id",value="角色id",required=true,dataType="int") 65 | @RequiresPermissions(value={"admin:permission:delete"}) 66 | @RequestMapping("/delete") 67 | public Return delete(int id){ 68 | this.roleService.del(id); 69 | return Return.success(); 70 | } 71 | 72 | @ApiOperation(value = "角色拥有权限", notes = "根据id查询用户拥有的权限") 73 | @ApiImplicitParam(paramType="query",name="roleId",value="角色id",required=true,dataType="int") 74 | @RequiresPermissions(value={"admin:permission:permission:list"}) 75 | @RequestMapping(value="/permission/list",method=RequestMethod.GET) 76 | public List permissionList(int roleId) { 77 | List rolePermissions = rolePermissionService.findByRoleId(roleId); 78 | return rolePermissions; 79 | } 80 | 81 | @ApiOperation(value = "设置角色拥有的权限", notes = "根据角色id设置权限") 82 | @ApiImplicitParams({ 83 | @ApiImplicitParam(paramType = "query", name = "roleId", value = "角色id", required = true, dataType = "int"), 84 | @ApiImplicitParam(paramType = "query", name = "permissionIds", value = "权限ID,多个权限ID用英文逗号隔开", required = true, dataType = "int") }) 85 | @RequiresPermissions(value = { "admin:permission:permission:set" }) 86 | @RequestMapping(value = "/permission/set", method = RequestMethod.POST) 87 | public Return permissionSet(int roleId, String permissionIds) { 88 | return roleService.doSetPermissions(roleId, permissionIds); 89 | } 90 | 91 | @Autowired 92 | private RoleService roleService; 93 | 94 | @Autowired 95 | private RolePermissionService rolePermissionService; 96 | } -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/dao/PermissionDao.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.dao; 2 | 3 | import java.util.List; 4 | import java.util.Set; 5 | 6 | import org.springframework.data.jpa.repository.Query; 7 | 8 | import com.onecoderspace.base.component.common.dao.BaseDao; 9 | import com.onecoderspace.base.domain.Permission; 10 | 11 | public interface PermissionDao extends BaseDao{ 12 | 13 | @Query(value="select perm.* from role_permission rp left join permission perm on rp.permission_id=perm.id where rp.role_id in(?1);",nativeQuery=true) 14 | List listByRoleIds(Set roles); 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/dao/RoleDao.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.dao; 2 | 3 | import java.util.Set; 4 | 5 | import com.onecoderspace.base.component.common.dao.BaseDao; 6 | import com.onecoderspace.base.domain.Role; 7 | 8 | public interface RoleDao extends BaseDao{ 9 | 10 | Role findByCode(String code); 11 | 12 | Set findByIdIn(Set roleIds); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/dao/RolePermissionDao.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.dao; 2 | 3 | import java.util.List; 4 | import java.util.Set; 5 | 6 | import org.springframework.data.jpa.repository.Modifying; 7 | import org.springframework.data.jpa.repository.Query; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | import com.onecoderspace.base.component.common.dao.BaseDao; 11 | import com.onecoderspace.base.domain.Permission; 12 | import com.onecoderspace.base.domain.RolePermission; 13 | 14 | public interface RolePermissionDao extends BaseDao{ 15 | 16 | List findByRoleId(int roleId); 17 | 18 | @Transactional 19 | @Query(value = "delete from role_permission where role_id=?1 ", nativeQuery = true) 20 | @Modifying 21 | void deleleByRoleId(int roleId); 22 | 23 | List findByRoleIdIn(Set roles); 24 | 25 | @Query(value="select perm.* from role_permission rp left join permission perm on rp.permission_id=perm.id where rp.role_id in(?1);",nativeQuery=true) 26 | List listByRoleIds(Set roles); 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/dao/UserDao.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.dao; 2 | 3 | import com.onecoderspace.base.component.common.dao.BaseDao; 4 | import com.onecoderspace.base.domain.User; 5 | 6 | public interface UserDao extends BaseDao{ 7 | User findByUsernameAndDel(String username, int del); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/dao/UserRoleDao.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.dao; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.data.jpa.repository.Modifying; 6 | import org.springframework.data.jpa.repository.Query; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | import com.onecoderspace.base.component.common.dao.BaseDao; 10 | import com.onecoderspace.base.domain.UserRole; 11 | 12 | public interface UserRoleDao extends BaseDao{ 13 | 14 | List findByUserId(int uid); 15 | 16 | @Transactional 17 | @Query(value = "delete from user_role where user_id=?1 ", nativeQuery = true) 18 | @Modifying 19 | void deleleByUserId(int uid); 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/domain/Permission.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.domain; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.GeneratedValue; 6 | import javax.persistence.GenerationType; 7 | import javax.persistence.Id; 8 | import javax.persistence.Table; 9 | 10 | import com.onecoderspace.base.component.common.domain.BaseModel; 11 | 12 | /** 13 | * 菜单及操作权限,树形结构 14 | */ 15 | @Entity 16 | @Table(name = "permission") 17 | public class Permission implements BaseModel{ 18 | 19 | private static final long serialVersionUID = 6581772362165179231L; 20 | 21 | @Id 22 | @GeneratedValue(strategy=GenerationType.AUTO) 23 | private Integer id;//主键 24 | 25 | @Column(name="type",columnDefinition="tinyint default 0") 26 | private int type; //权限类型 0菜单 1按钮 2 操作权限 27 | 28 | @Column(name="name",length=50) 29 | private String name; //权限名称,用来展示 30 | 31 | @Column(name="code",length=50) 32 | private String code; //权限的值,校验权限时使用 33 | 34 | private String url;//操作权限的url 35 | 36 | @Column(name="weight",columnDefinition="int default 10000") 37 | private int weight = 10000; //排序值,升序 38 | 39 | @Column(name="pid",columnDefinition="int default 0") 40 | private int pid; //父节点ID 41 | 42 | @Override 43 | public Integer getId() { 44 | return id; 45 | } 46 | 47 | public void setId(Integer id) { 48 | this.id = id; 49 | } 50 | 51 | public int getType() { 52 | return type; 53 | } 54 | 55 | public void setType(int type) { 56 | this.type = type; 57 | } 58 | 59 | public String getName() { 60 | return name; 61 | } 62 | 63 | public void setName(String name) { 64 | this.name = name; 65 | } 66 | 67 | public String getCode() { 68 | return code; 69 | } 70 | 71 | public void setCode(String code) { 72 | this.code = code; 73 | } 74 | 75 | public String getUrl() { 76 | return url; 77 | } 78 | 79 | public void setUrl(String url) { 80 | this.url = url; 81 | } 82 | 83 | public int getWeight() { 84 | return weight; 85 | } 86 | 87 | public void setWeight(int weight) { 88 | this.weight = weight; 89 | } 90 | 91 | public int getPid() { 92 | return pid; 93 | } 94 | 95 | public void setPid(int pid) { 96 | this.pid = pid; 97 | } 98 | 99 | @Override 100 | public String toString() { 101 | return "Permission [id=" + id + ", type=" + type + ", name=" + name 102 | + ", code=" + code + ", weight=" + weight + ", pid=" + pid 103 | + "]"; 104 | } 105 | 106 | } 107 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/domain/Role.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.domain; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.GeneratedValue; 6 | import javax.persistence.GenerationType; 7 | import javax.persistence.Id; 8 | import javax.persistence.Table; 9 | 10 | import com.onecoderspace.base.component.common.domain.BaseModel; 11 | 12 | /** 13 | * 角色 14 | */ 15 | @Entity 16 | @Table(name = "role") 17 | public class Role implements BaseModel{ 18 | 19 | private static final long serialVersionUID = 254681740752863107L; 20 | 21 | @Id 22 | @GeneratedValue(strategy=GenerationType.AUTO) 23 | private Integer id;//主键 24 | 25 | @Column(name="name",length=50) 26 | private String name; //角色名称,通常为中文,用于展示 27 | 28 | @Column(name="code",length=45) 29 | private String code; //角色的值,用来校验权限,通常为英文 30 | 31 | @Column(name="remark",length=255) 32 | private String remark; //备注 33 | 34 | @Override 35 | public Integer getId() { 36 | return id; 37 | } 38 | 39 | public void setId(Integer id) { 40 | this.id = id; 41 | } 42 | 43 | public String getName() { 44 | return name; 45 | } 46 | 47 | public void setName(String name) { 48 | this.name = name; 49 | } 50 | 51 | public String getCode() { 52 | return code; 53 | } 54 | 55 | public void setCode(String code) { 56 | this.code = code; 57 | } 58 | 59 | public String getRemark() { 60 | return remark; 61 | } 62 | 63 | public void setRemark(String remark) { 64 | this.remark = remark; 65 | } 66 | 67 | 68 | @Override 69 | public String toString() { 70 | return "Role [id=" + id + ", name=" + name + ", code=" + code 71 | + ", remark=" + remark + "]"; 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/domain/RolePermission.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.domain; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.GeneratedValue; 6 | import javax.persistence.GenerationType; 7 | import javax.persistence.Id; 8 | import javax.persistence.Table; 9 | 10 | import com.onecoderspace.base.component.common.domain.BaseModel; 11 | 12 | /** 13 | * 角色权限关联表 14 | */ 15 | @Entity 16 | @Table(name = "role_permission") 17 | public class RolePermission implements BaseModel{ 18 | 19 | private static final long serialVersionUID = 2562960339678855205L; 20 | 21 | @Id 22 | @GeneratedValue(strategy=GenerationType.AUTO) 23 | private Integer id;//主键 24 | 25 | @Column(name="role_id",columnDefinition="int default 0") 26 | private int roleId; //角色ID 27 | 28 | @Column(name="permission_id",columnDefinition="int default 0") 29 | private int permissionId; //权限ID 30 | 31 | @Override 32 | public Integer getId() { 33 | return id; 34 | } 35 | 36 | public void setId(Integer id) { 37 | this.id = id; 38 | } 39 | 40 | public int getRoleId() { 41 | return roleId; 42 | } 43 | 44 | public void setRoleId(int roleId) { 45 | this.roleId = roleId; 46 | } 47 | 48 | public int getPermissionId() { 49 | return permissionId; 50 | } 51 | 52 | public void setPermissionId(int permissionId) { 53 | this.permissionId = permissionId; 54 | } 55 | 56 | @Override 57 | public String toString() { 58 | return "RolePermission [id=" + id + ", roleId=" + roleId 59 | + ", permissionId=" + permissionId + "]"; 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/domain/User.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.domain; 2 | 3 | import io.swagger.annotations.ApiModelProperty; 4 | 5 | import javax.persistence.Column; 6 | import javax.persistence.Entity; 7 | import javax.persistence.GeneratedValue; 8 | import javax.persistence.GenerationType; 9 | import javax.persistence.Id; 10 | import javax.persistence.Table; 11 | 12 | import com.onecoderspace.base.component.common.domain.BaseModel; 13 | 14 | import java.sql.Timestamp; 15 | 16 | /** 17 | * 用户 18 | */ 19 | @Entity 20 | @Table(name = "user") 21 | public class User implements BaseModel{ 22 | 23 | private static final long serialVersionUID = -91221104520172449L; 24 | 25 | @Id 26 | @GeneratedValue(strategy=GenerationType.AUTO) 27 | private Integer id;//主键 28 | 29 | @ApiModelProperty(value="用户类别 0普通用户 1运营人员") 30 | @Column(columnDefinition="tinyint default 0") 31 | private int type = 0; 32 | 33 | @ApiModelProperty(value="账号") 34 | @Column(name="username",length=50) 35 | private String username; 36 | 37 | @ApiModelProperty(value="姓名") 38 | @Column(name="name",length=50) 39 | private String name; 40 | 41 | @ApiModelProperty(value="密码(md5(mix(password,salt)))") 42 | @Column(name="pwd",length=50) 43 | private String pwd; 44 | 45 | @ApiModelProperty(value="密码加密的“盐”") 46 | @Column(name="salt",length=16) 47 | private String salt; 48 | 49 | @ApiModelProperty(value="手机号") 50 | @Column(name="mobile",length=15) 51 | private String mobile; 52 | 53 | @ApiModelProperty(value="邮箱") 54 | @Column(name="email",length=50) 55 | private String email; 56 | 57 | @ApiModelProperty(value="昵称") 58 | @Column(name="nick_name",length=50) 59 | private String nickName; 60 | 61 | @ApiModelProperty(value="性别 0未设置 1男 2女") 62 | @Column(name="gender",columnDefinition="tinyint default 0") 63 | private int gender = 0; 64 | 65 | @ApiModelProperty(value="账号状态 0已注册未审核 1待审核 2审核通过 -1审核未通过") 66 | @Column(name="status",columnDefinition="tinyint default 0") 67 | private int status = 0; 68 | 69 | @ApiModelProperty(value="账号是否有效 1有效 0无效") 70 | @Column(name="enable",columnDefinition="tinyint default 1") 71 | private int enable = 0; 72 | 73 | @ApiModelProperty(value="用户头像 相对路径,不要带域名") 74 | @Column(name="avatar",length=255) 75 | private String avatar; 76 | 77 | @ApiModelProperty(value="注册时间") 78 | @Column(name="register_time") 79 | private Timestamp registerTime; 80 | 81 | @ApiModelProperty(value="最后更新人") 82 | @Column(name="updator",columnDefinition="int default 0") 83 | private int updator = 0; 84 | 85 | @ApiModelProperty(value="最后更新时间") 86 | @Column(name="update_time") 87 | private Timestamp updateTime; 88 | 89 | @ApiModelProperty(value="标记删除字段 1已删除 0未删除") 90 | @Column(name="del",columnDefinition="tinyint default 0") 91 | private int del = 0; 92 | 93 | 94 | //账号状态 0已注册未审核 1待审核 2审核通过 -1审核未通过 95 | public static final int STATUS_UNAUDIT = 0; 96 | public static final int STATUS_WAIT_AUDIT = 1; 97 | public static final int STATUS_AUDIT_PASS = 2; 98 | public static final int STATUS_AUDIT_UNPASS = -1; 99 | 100 | //用户类别 0普通用户 1运营人员 101 | public static final int TYPE_USER = 0; 102 | public static final int TYPE_OPERATOR = 1; 103 | 104 | @Override 105 | public Integer getId() { 106 | return id; 107 | } 108 | 109 | public void setId(Integer id) { 110 | this.id = id; 111 | } 112 | 113 | public int getType() { 114 | return type; 115 | } 116 | 117 | public void setType(int type) { 118 | this.type = type; 119 | } 120 | 121 | public String getUsername() { 122 | return username; 123 | } 124 | 125 | public void setUsername(String username) { 126 | this.username = username; 127 | } 128 | 129 | public String getName() { 130 | return name; 131 | } 132 | 133 | public void setName(String name) { 134 | this.name = name; 135 | } 136 | 137 | public String getPwd() { 138 | return pwd; 139 | } 140 | 141 | public void setPwd(String pwd) { 142 | this.pwd = pwd; 143 | } 144 | 145 | public String getSalt() { 146 | return salt; 147 | } 148 | 149 | public void setSalt(String salt) { 150 | this.salt = salt; 151 | } 152 | 153 | public String getMobile() { 154 | return mobile; 155 | } 156 | 157 | public void setMobile(String mobile) { 158 | this.mobile = mobile; 159 | } 160 | 161 | public String getEmail() { 162 | return email; 163 | } 164 | 165 | public void setEmail(String email) { 166 | this.email = email; 167 | } 168 | 169 | public String getNickName() { 170 | return nickName; 171 | } 172 | 173 | public void setNickName(String nickName) { 174 | this.nickName = nickName; 175 | } 176 | 177 | public int getGender() { 178 | return gender; 179 | } 180 | 181 | public void setGender(int gender) { 182 | this.gender = gender; 183 | } 184 | 185 | public int getStatus() { 186 | return status; 187 | } 188 | 189 | public void setStatus(int status) { 190 | this.status = status; 191 | } 192 | 193 | public int getEnable() { 194 | return enable; 195 | } 196 | 197 | public void setEnable(int enable) { 198 | this.enable = enable; 199 | } 200 | 201 | public String getAvatar() { 202 | return avatar; 203 | } 204 | 205 | public void setAvatar(String avatar) { 206 | this.avatar = avatar; 207 | } 208 | 209 | public Timestamp getRegisterTime() { 210 | return registerTime; 211 | } 212 | 213 | public void setRegisterTime(Timestamp registerTime) { 214 | this.registerTime = registerTime; 215 | } 216 | 217 | public int getUpdator() { 218 | return updator; 219 | } 220 | 221 | public void setUpdator(int updator) { 222 | this.updator = updator; 223 | } 224 | 225 | public Timestamp getUpdateTime() { 226 | return updateTime; 227 | } 228 | 229 | public void setUpdateTime(Timestamp updateTime) { 230 | this.updateTime = updateTime; 231 | } 232 | 233 | public int getDel() { 234 | return del; 235 | } 236 | 237 | public void setDel(int del) { 238 | this.del = del; 239 | } 240 | 241 | @Override 242 | public String toString() { 243 | return String 244 | .format("User [id=%s, type=%s, username=%s, name=%s, pwd=%s, salt=%s, mobile=%s, email=%s, nickName=%s, gender=%s, status=%s, enable=%s, avatar=%s, registerTime=%s, updator=%s, updateTime=%s, del=%s]", 245 | id, type, username, name, pwd, salt, mobile, email, 246 | nickName, gender, status, enable, avatar, registerTime, 247 | updator, updateTime, del); 248 | } 249 | 250 | } 251 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/domain/UserRole.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.domain; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.GeneratedValue; 6 | import javax.persistence.GenerationType; 7 | import javax.persistence.Id; 8 | import javax.persistence.Table; 9 | 10 | import com.onecoderspace.base.component.common.domain.BaseModel; 11 | 12 | /** 13 | * 用户角色 14 | */ 15 | @Entity 16 | @Table(name = "user_role") 17 | public class UserRole implements BaseModel{ 18 | 19 | private static final long serialVersionUID = 5806516492008208503L; 20 | 21 | @Id 22 | @GeneratedValue(strategy=GenerationType.AUTO) 23 | private Integer id;//主键 24 | 25 | @Column(name="user_id",columnDefinition="int default 0") 26 | private int userId; //用户ID 27 | 28 | @Column(name="role_id",columnDefinition="int default 0") 29 | private int roleId; //角色ID 30 | 31 | @Override 32 | public Integer getId() { 33 | return id; 34 | } 35 | 36 | public void setId(Integer id) { 37 | this.id = id; 38 | } 39 | 40 | public int getUserId() { 41 | return userId; 42 | } 43 | 44 | public void setUserId(int userId) { 45 | this.userId = userId; 46 | } 47 | 48 | public int getRoleId() { 49 | return roleId; 50 | } 51 | 52 | public void setRoleId(int roleId) { 53 | this.roleId = roleId; 54 | } 55 | 56 | @Override 57 | public String toString() { 58 | return "UserRole [id=" + id + ", userId=" + userId + ", roleId=" 59 | + roleId + "]"; 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/filter/CsrfFilter.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.filter; 2 | 3 | import java.io.IOException; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.regex.Matcher; 7 | import java.util.regex.Pattern; 8 | 9 | import javax.servlet.Filter; 10 | import javax.servlet.FilterChain; 11 | import javax.servlet.FilterConfig; 12 | import javax.servlet.ServletException; 13 | import javax.servlet.ServletRequest; 14 | import javax.servlet.ServletResponse; 15 | import javax.servlet.http.HttpServletRequest; 16 | import javax.servlet.http.HttpServletResponse; 17 | import javax.servlet.http.HttpSession; 18 | 19 | import org.apache.commons.lang3.StringUtils; 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | 23 | import com.onecoderspace.base.util.AjaxResponseWriter; 24 | import com.onecoderspace.base.util.ServiceStatusEnum; 25 | 26 | /** 27 | * CSRF跨域请求伪造拦截 28 | * 除登录以外的post方法,都需要携带token,如果token为空或token错误,则返回异常提示 29 | * 注意在filter初始化参数内配置排除的url 30 | * @author yangwk 31 | */ 32 | public class CsrfFilter implements Filter { 33 | private static Logger logger = LoggerFactory.getLogger(CsrfFilter.class); 34 | 35 | public List excludes = new ArrayList(); 36 | 37 | private boolean isOpen = false;//是否开启该filter 38 | 39 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,ServletException { 40 | if(!isOpen){ 41 | filterChain.doFilter(request, response); 42 | return ; 43 | } 44 | if(logger.isDebugEnabled()){ 45 | logger.debug("csrf filter is running"); 46 | } 47 | 48 | HttpServletRequest req = (HttpServletRequest) request; 49 | HttpServletResponse resp = (HttpServletResponse) response; 50 | HttpSession session = req.getSession(); 51 | Object token = session.getAttribute("token"); 52 | if(!"post".equalsIgnoreCase(req.getMethod()) || handleExcludeURL(req, resp) || token == null){ 53 | filterChain.doFilter(request, response); 54 | return; 55 | } 56 | 57 | String requestToken = req.getParameter("token"); 58 | if(StringUtils.isBlank(requestToken) || !requestToken.equals(token)){ 59 | AjaxResponseWriter.write(req, resp, ServiceStatusEnum.ILLEGAL_TOKEN, "非法的token"); 60 | return; 61 | } 62 | filterChain.doFilter(request, response); 63 | } 64 | 65 | private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) { 66 | if (excludes == null || excludes.isEmpty()) { 67 | return false; 68 | } 69 | String url = request.getServletPath(); 70 | for (String pattern : excludes) { 71 | Pattern p = Pattern.compile("^" + pattern); 72 | Matcher m = p.matcher(url); 73 | if (m.find()) { 74 | return true; 75 | } 76 | } 77 | return false; 78 | } 79 | 80 | @Override 81 | public void init(FilterConfig filterConfig) throws ServletException { 82 | if(logger.isDebugEnabled()){ 83 | logger.debug("csrf filter init~~~~~~~~~~~~"); 84 | } 85 | 86 | String temp = filterConfig.getInitParameter("excludes"); 87 | if (temp != null) { 88 | String[] url = temp.split(","); 89 | for (int i = 0; url != null && i < url.length; i++) { 90 | excludes.add(url[i]); 91 | } 92 | } 93 | 94 | temp = filterConfig.getInitParameter("isOpen"); 95 | if(StringUtils.isNotBlank(temp) && "true".equals(isOpen)){ 96 | isOpen = true; 97 | } 98 | } 99 | 100 | @Override 101 | public void destroy() {} 102 | 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/filter/LoginFilter.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.filter; 2 | 3 | import java.io.IOException; 4 | 5 | import javax.servlet.Filter; 6 | import javax.servlet.FilterChain; 7 | import javax.servlet.FilterConfig; 8 | import javax.servlet.ServletException; 9 | import javax.servlet.ServletRequest; 10 | import javax.servlet.ServletResponse; 11 | import javax.servlet.http.HttpServletRequest; 12 | import javax.servlet.http.HttpServletResponse; 13 | 14 | import org.apache.shiro.SecurityUtils; 15 | import org.apache.shiro.subject.Subject; 16 | 17 | import com.onecoderspace.base.util.AjaxResponseWriter; 18 | import com.onecoderspace.base.util.ServiceStatusEnum; 19 | 20 | public class LoginFilter implements Filter { 21 | 22 | @Override 23 | public void destroy() {} 24 | 25 | @Override 26 | public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException { 27 | Subject currentUser = SecurityUtils.getSubject(); 28 | if (!currentUser.isAuthenticated()) { 29 | HttpServletRequest req = (HttpServletRequest) request; 30 | HttpServletResponse res = (HttpServletResponse) response; 31 | AjaxResponseWriter.write(req, res, ServiceStatusEnum.UNLOGIN, "请登录"); 32 | return; 33 | } 34 | chain.doFilter(request, response); 35 | } 36 | 37 | @Override 38 | public void init(FilterConfig filterConfig) throws ServletException {} 39 | 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/filter/ShiroSessionFilter.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.filter; 2 | 3 | import java.io.IOException; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.regex.Matcher; 7 | import java.util.regex.Pattern; 8 | 9 | import javax.servlet.Filter; 10 | import javax.servlet.FilterChain; 11 | import javax.servlet.FilterConfig; 12 | import javax.servlet.ServletException; 13 | import javax.servlet.ServletRequest; 14 | import javax.servlet.ServletResponse; 15 | import javax.servlet.http.HttpServletRequest; 16 | import javax.servlet.http.HttpServletResponse; 17 | 18 | import org.apache.commons.lang3.StringUtils; 19 | import org.apache.commons.lang3.math.NumberUtils; 20 | import org.apache.shiro.SecurityUtils; 21 | import org.apache.shiro.subject.Subject; 22 | import org.slf4j.Logger; 23 | import org.slf4j.LoggerFactory; 24 | 25 | /** 26 | * 通过拦截器设置shiroSession过期时间 27 | * @author yangwk 28 | */ 29 | public class ShiroSessionFilter implements Filter { 30 | private static Logger logger = LoggerFactory.getLogger(ShiroSessionFilter.class); 31 | 32 | public List excludes = new ArrayList(); 33 | 34 | private long serverSessionTimeout = 180000L;//ms 35 | 36 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,ServletException { 37 | if(logger.isDebugEnabled()){ 38 | logger.debug("shiro session filter is open"); 39 | } 40 | 41 | HttpServletRequest req = (HttpServletRequest) request; 42 | HttpServletResponse resp = (HttpServletResponse) response; 43 | if(handleExcludeURL(req, resp)){ 44 | filterChain.doFilter(request, response); 45 | return; 46 | } 47 | 48 | Subject currentUser = SecurityUtils.getSubject(); 49 | if(currentUser.isAuthenticated()){ 50 | currentUser.getSession().setTimeout(serverSessionTimeout); 51 | } 52 | filterChain.doFilter(request, response); 53 | } 54 | 55 | private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) { 56 | 57 | if (excludes == null || excludes.isEmpty()) { 58 | return false; 59 | } 60 | 61 | String url = request.getServletPath(); 62 | for (String pattern : excludes) { 63 | Pattern p = Pattern.compile("^" + pattern); 64 | Matcher m = p.matcher(url); 65 | if (m.find()) { 66 | return true; 67 | } 68 | } 69 | 70 | return false; 71 | } 72 | 73 | @Override 74 | public void init(FilterConfig filterConfig) throws ServletException { 75 | if(logger.isDebugEnabled()){ 76 | logger.debug("shiro session filter init~~~~~~~~~~~~"); 77 | } 78 | String temp = filterConfig.getInitParameter("excludes"); 79 | if (temp != null) { 80 | String[] url = temp.split(","); 81 | for (int i = 0; url != null && i < url.length; i++) { 82 | excludes.add(url[i]); 83 | } 84 | } 85 | String timeout = filterConfig.getInitParameter("serverSessionTimeout"); 86 | if(StringUtils.isNotBlank(timeout)){ 87 | this.serverSessionTimeout = NumberUtils.toLong(timeout,1800L)*1000L; 88 | } 89 | } 90 | 91 | @Override 92 | public void destroy() {} 93 | 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/filter/XssFilter.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.filter; 2 | 3 | import java.io.IOException; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.regex.Matcher; 7 | import java.util.regex.Pattern; 8 | 9 | import javax.servlet.Filter; 10 | import javax.servlet.FilterChain; 11 | import javax.servlet.FilterConfig; 12 | import javax.servlet.ServletException; 13 | import javax.servlet.ServletRequest; 14 | import javax.servlet.ServletResponse; 15 | import javax.servlet.http.HttpServletRequest; 16 | import javax.servlet.http.HttpServletResponse; 17 | 18 | import org.apache.commons.lang3.BooleanUtils; 19 | import org.apache.commons.lang3.StringUtils; 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | 23 | /** 24 | * 拦截防止xss注入 25 | * 通过Jsoup过滤请求参数内的特定字符 26 | * @author yangwk 27 | */ 28 | public class XssFilter implements Filter { 29 | private static Logger logger = LoggerFactory.getLogger(XssFilter.class); 30 | 31 | private static boolean IS_INCLUDE_RICH_TEXT = false;//是否过滤富文本内容 32 | 33 | public List excludes = new ArrayList(); 34 | 35 | public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException,ServletException { 36 | if(logger.isDebugEnabled()){ 37 | logger.debug("xss filter is open"); 38 | } 39 | 40 | HttpServletRequest req = (HttpServletRequest) request; 41 | HttpServletResponse resp = (HttpServletResponse) response; 42 | if(handleExcludeURL(req, resp)){ 43 | filterChain.doFilter(request, response); 44 | return; 45 | } 46 | 47 | XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request,IS_INCLUDE_RICH_TEXT); 48 | filterChain.doFilter(xssRequest, response); 49 | } 50 | 51 | private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) { 52 | 53 | if (excludes == null || excludes.isEmpty()) { 54 | return false; 55 | } 56 | 57 | String url = request.getServletPath(); 58 | for (String pattern : excludes) { 59 | Pattern p = Pattern.compile("^" + pattern); 60 | Matcher m = p.matcher(url); 61 | if (m.find()) { 62 | return true; 63 | } 64 | } 65 | 66 | return false; 67 | } 68 | 69 | @Override 70 | public void init(FilterConfig filterConfig) throws ServletException { 71 | if(logger.isDebugEnabled()){ 72 | logger.debug("xss filter init~~~~~~~~~~~~"); 73 | } 74 | String isIncludeRichText = filterConfig.getInitParameter("isIncludeRichText"); 75 | if(StringUtils.isNotBlank(isIncludeRichText)){ 76 | IS_INCLUDE_RICH_TEXT = BooleanUtils.toBoolean(isIncludeRichText); 77 | } 78 | 79 | String temp = filterConfig.getInitParameter("excludes"); 80 | if (temp != null) { 81 | String[] url = temp.split(","); 82 | for (int i = 0; url != null && i < url.length; i++) { 83 | excludes.add(url[i]); 84 | } 85 | } 86 | } 87 | 88 | @Override 89 | public void destroy() {} 90 | 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/filter/XssHttpServletRequestWrapper.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.filter; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | import javax.servlet.http.HttpServletRequestWrapper; 5 | 6 | import org.apache.commons.lang3.StringUtils; 7 | 8 | import com.onecoderspace.base.util.security.xss.JsoupUtil; 9 | 10 | /** 11 | * {@link XssHttpServletRequestWrapper} 12 | */ 13 | public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { 14 | HttpServletRequest orgRequest = null; 15 | private boolean isIncludeRichText = false; 16 | 17 | public XssHttpServletRequestWrapper(HttpServletRequest request, boolean isIncludeRichText) { 18 | super(request); 19 | orgRequest = request; 20 | this.isIncludeRichText = isIncludeRichText; 21 | } 22 | 23 | /** 24 | * 覆盖getParameter方法,将参数名和参数值都做xss过滤。
25 | * 如果需要获得原始的值,则通过super.getParameterValues(name)来获取
26 | * getParameterNames,getParameterValues和getParameterMap也可能需要覆盖 27 | */ 28 | @Override 29 | public String getParameter(String name) { 30 | if(("content".equals(name) || name.endsWith("WithHtml")) && !isIncludeRichText){ 31 | return super.getParameter(name); 32 | } 33 | name = JsoupUtil.clean(name); 34 | String value = super.getParameter(name); 35 | if (StringUtils.isNotBlank(value)) { 36 | value = JsoupUtil.clean(value); 37 | } 38 | return value; 39 | } 40 | 41 | @Override 42 | public String[] getParameterValues(String name) { 43 | String[] arr = super.getParameterValues(name); 44 | if(arr != null){ 45 | for (int i=0;i 55 | * 如果需要获得原始的值,则通过super.getHeaders(name)来获取
56 | * getHeaderNames 也可能需要覆盖 57 | */ 58 | @Override 59 | public String getHeader(String name) { 60 | name = JsoupUtil.clean(name); 61 | String value = super.getHeader(name); 62 | if (StringUtils.isNotBlank(value)) { 63 | value = JsoupUtil.clean(value); 64 | } 65 | return value; 66 | } 67 | 68 | /** 69 | * 获取最原始的request 70 | * 71 | * @return 72 | */ 73 | public HttpServletRequest getOrgRequest() { 74 | return orgRequest; 75 | } 76 | 77 | /** 78 | * 获取最原始的request的静态方法 79 | * 80 | * @return 81 | */ 82 | public static HttpServletRequest getOrgRequest(HttpServletRequest req) { 83 | if (req instanceof XssHttpServletRequestWrapper) { 84 | return ((XssHttpServletRequestWrapper) req).getOrgRequest(); 85 | } 86 | 87 | return req; 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/service/PermissionService.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.service; 2 | 3 | import org.springframework.data.domain.Sort; 4 | 5 | import com.onecoderspace.base.component.common.service.BaseService; 6 | import com.onecoderspace.base.domain.Permission; 7 | 8 | /** 9 | *菜单及操作权限,树形结构 10 | */ 11 | public interface PermissionService extends BaseService{ 12 | 13 | Iterable findAll(Sort sort); 14 | 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/service/RolePermissionService.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.service; 2 | 3 | import java.util.List; 4 | import java.util.Set; 5 | 6 | import com.onecoderspace.base.component.common.service.BaseService; 7 | import com.onecoderspace.base.domain.Permission; 8 | import com.onecoderspace.base.domain.RolePermission; 9 | 10 | /** 11 | *角色权限关联表 12 | */ 13 | public interface RolePermissionService extends BaseService{ 14 | 15 | List findByRoleId(int roleId); 16 | 17 | void deleleByRoleId(int roleId); 18 | 19 | List getPermissions(Set roles); 20 | 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/service/RoleService.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.service; 2 | 3 | import java.util.Set; 4 | 5 | import org.springframework.data.domain.Page; 6 | import org.springframework.data.domain.Pageable; 7 | 8 | import com.onecoderspace.base.component.common.service.BaseService; 9 | import com.onecoderspace.base.domain.Role; 10 | import com.onecoderspace.base.util.Return; 11 | 12 | /** 13 | *角色 14 | */ 15 | public interface RoleService extends BaseService{ 16 | 17 | Page listByPage(String name, Pageable pageable); 18 | 19 | Return doSetPermissions(int roleId, String permissionIds); 20 | 21 | Role findByCode(String code); 22 | 23 | Set findByIds(Set roleIds); 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/service/UserRoleService.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.service; 2 | 3 | import java.util.List; 4 | import java.util.Set; 5 | 6 | import com.onecoderspace.base.component.common.service.BaseService; 7 | import com.onecoderspace.base.domain.UserRole; 8 | 9 | /** 10 | *用户角色 11 | */ 12 | public interface UserRoleService extends BaseService{ 13 | 14 | List findByUserId(int uid); 15 | 16 | void deleleByUserId(int uid); 17 | 18 | /** 19 | * 添加角色 20 | * @author yangwk 21 | * @time 2017年7月28日 下午2:12:35 22 | * @param userId 用户ID 23 | * @param code 角色编码 24 | */ 25 | void add(int id, String code); 26 | 27 | 28 | Set findRoleIds(int userId); 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.service; 2 | 3 | import java.util.Map; 4 | 5 | import org.springframework.data.domain.Page; 6 | import org.springframework.data.domain.Pageable; 7 | 8 | import com.onecoderspace.base.component.common.service.BaseService; 9 | import com.onecoderspace.base.domain.User; 10 | import com.onecoderspace.base.util.Return; 11 | 12 | /** 13 | *用户 14 | */ 15 | public interface UserService extends BaseService{ 16 | 17 | User findByUsername(String username); 18 | 19 | /** 20 | * 设置密码 21 | * @author yangwk 22 | * @time 2017年7月27日 上午10:15:12 23 | * @param entity 24 | * @param pwd 25 | * @return 26 | */ 27 | Return changePwd(User entity, String pwd); 28 | 29 | /** 30 | * 带条件分页查询 31 | * @author yangwk 32 | * @time 2017年7月27日 上午10:15:26 33 | * @param params 34 | * @param pageable 35 | * @return 36 | */ 37 | Page listByPage(Map params,Pageable pageable); 38 | 39 | /** 40 | * 保存审核结果 41 | * @author yangwk 42 | * @time 2017年7月27日 上午10:14:11 43 | * @param entity 素材新 44 | * @param value 审核结果 1通过 0未通过 45 | * @param msg 备注新 46 | * @return 47 | */ 48 | Return doAudit(User entity, int value, String msg); 49 | 50 | /** 51 | * 设置用户的角色 52 | * @author yangwk 53 | * @time 2017年7月27日 上午10:15:01 54 | * @param uid 55 | * @param roleIds 56 | * @return 57 | */ 58 | Return doSetRoles(int uid, String roleIds); 59 | 60 | /** 61 | * 保存用户 62 | * @author yangwk 63 | * @time 2017年7月28日 下午1:37:24 64 | * @param user 用户信息 65 | * @param company 公司信息 66 | * @return 67 | */ 68 | Return saveUser(User user); 69 | 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/service/impl/PermissionServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.service.impl; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.data.domain.Sort; 5 | import org.springframework.stereotype.Service; 6 | import org.springframework.transaction.annotation.Transactional; 7 | 8 | import com.onecoderspace.base.component.common.dao.BaseDao; 9 | import com.onecoderspace.base.component.common.service.BaseServiceImpl; 10 | import com.onecoderspace.base.dao.PermissionDao; 11 | import com.onecoderspace.base.domain.Permission; 12 | import com.onecoderspace.base.service.PermissionService; 13 | 14 | @Transactional 15 | @Service("permissionService") 16 | public class PermissionServiceImpl extends BaseServiceImpl implements PermissionService{ 17 | 18 | @Autowired 19 | private PermissionDao permissionDao; 20 | 21 | @Override 22 | public BaseDao getDAO() { 23 | return permissionDao; 24 | } 25 | 26 | @Override 27 | public Iterable findAll(Sort sort) { 28 | return this.permissionDao.findAll(sort); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/service/impl/RolePermissionServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.service.impl; 2 | 3 | import java.util.List; 4 | import java.util.Set; 5 | 6 | import org.apache.commons.collections.CollectionUtils; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Service; 9 | import org.springframework.transaction.annotation.Transactional; 10 | 11 | import com.google.common.collect.Lists; 12 | import com.onecoderspace.base.component.common.dao.BaseDao; 13 | import com.onecoderspace.base.component.common.service.BaseServiceImpl; 14 | import com.onecoderspace.base.dao.PermissionDao; 15 | import com.onecoderspace.base.dao.RolePermissionDao; 16 | import com.onecoderspace.base.domain.Permission; 17 | import com.onecoderspace.base.domain.RolePermission; 18 | import com.onecoderspace.base.service.RolePermissionService; 19 | 20 | @Transactional 21 | @Service("rolePermissionService") 22 | public class RolePermissionServiceImpl extends BaseServiceImpl implements RolePermissionService{ 23 | 24 | @Autowired 25 | private RolePermissionDao rolePermissionDao; 26 | 27 | @Override 28 | public BaseDao getDAO() { 29 | return rolePermissionDao; 30 | } 31 | 32 | @Override 33 | public List findByRoleId(int roleId) { 34 | return this.rolePermissionDao.findByRoleId(roleId); 35 | } 36 | 37 | @Override 38 | public void deleleByRoleId(int roleId) { 39 | this.rolePermissionDao.deleleByRoleId(roleId); 40 | } 41 | 42 | @Override 43 | public List getPermissions(Set roles) { 44 | if(CollectionUtils.isEmpty(roles)){ 45 | return Lists.newArrayList(); 46 | } 47 | List list = this.permissionDao.listByRoleIds(roles); 48 | return list; 49 | } 50 | 51 | @Autowired 52 | private PermissionDao permissionDao; 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/service/impl/RoleServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.service.impl; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Set; 6 | 7 | import javax.persistence.criteria.CriteriaBuilder; 8 | import javax.persistence.criteria.CriteriaQuery; 9 | import javax.persistence.criteria.Predicate; 10 | import javax.persistence.criteria.Root; 11 | 12 | import org.apache.commons.collections.CollectionUtils; 13 | import org.apache.commons.lang3.StringUtils; 14 | import org.apache.commons.lang3.math.NumberUtils; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.data.domain.Page; 17 | import org.springframework.data.domain.Pageable; 18 | import org.springframework.data.jpa.domain.Specification; 19 | import org.springframework.stereotype.Service; 20 | import org.springframework.transaction.annotation.Transactional; 21 | 22 | import com.google.common.collect.Sets; 23 | import com.onecoderspace.base.component.common.dao.BaseDao; 24 | import com.onecoderspace.base.component.common.service.BaseServiceImpl; 25 | import com.onecoderspace.base.dao.RoleDao; 26 | import com.onecoderspace.base.domain.Role; 27 | import com.onecoderspace.base.domain.RolePermission; 28 | import com.onecoderspace.base.service.RolePermissionService; 29 | import com.onecoderspace.base.service.RoleService; 30 | import com.onecoderspace.base.util.Return; 31 | 32 | @Transactional 33 | @Service("roleService") 34 | public class RoleServiceImpl extends BaseServiceImpl implements RoleService{ 35 | 36 | @Autowired 37 | private RoleDao roleDao; 38 | 39 | @Override 40 | public BaseDao getDAO() { 41 | return roleDao; 42 | } 43 | 44 | @Override 45 | public Page listByPage(final String name, Pageable pageable) { 46 | Specification spec = new Specification() { 47 | @Override 48 | public Predicate toPredicate(Root root,CriteriaQuery query,CriteriaBuilder cb) { 49 | List list = new ArrayList(); 50 | if(StringUtils.isNotBlank(name)){ 51 | list.add(cb.like(root.get("name").as(String.class), String.format("%%%s%%", name))); 52 | } 53 | Predicate[] p = new Predicate[list.size()]; 54 | return cb.and(list.toArray(p)); 55 | } 56 | }; 57 | Page page = roleDao.findAll(spec, pageable); 58 | return page; 59 | } 60 | 61 | @Override 62 | public Return doSetPermissions(int roleId, String permissionIds) { 63 | rolePermissionService.deleleByRoleId(roleId); 64 | String[] arr = permissionIds.split(","); 65 | for (String permissionId : arr) { 66 | RolePermission entity = new RolePermission(); 67 | entity.setRoleId(roleId); 68 | entity.setPermissionId(NumberUtils.toInt(permissionId)); 69 | rolePermissionService.save(entity); 70 | } 71 | return Return.success(); 72 | } 73 | 74 | @Override 75 | public Role findByCode(String code) { 76 | return this.roleDao.findByCode(code); 77 | } 78 | 79 | @Override 80 | public Set findByIds(Set roleIds) { 81 | if(CollectionUtils.isEmpty(roleIds)){ 82 | return Sets.newHashSet(); 83 | } 84 | return this.roleDao.findByIdIn(roleIds); 85 | } 86 | 87 | @Autowired 88 | private RolePermissionService rolePermissionService; 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/service/impl/UserRoleServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.service.impl; 2 | 3 | import java.util.List; 4 | import java.util.Set; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | import com.google.common.collect.Sets; 11 | import com.onecoderspace.base.component.common.dao.BaseDao; 12 | import com.onecoderspace.base.component.common.service.BaseServiceImpl; 13 | import com.onecoderspace.base.dao.UserRoleDao; 14 | import com.onecoderspace.base.domain.Role; 15 | import com.onecoderspace.base.domain.UserRole; 16 | import com.onecoderspace.base.service.RoleService; 17 | import com.onecoderspace.base.service.UserRoleService; 18 | 19 | @Transactional 20 | @Service("userRoleService") 21 | public class UserRoleServiceImpl extends BaseServiceImpl implements UserRoleService{ 22 | 23 | @Autowired 24 | private UserRoleDao userRoleDao; 25 | 26 | @Override 27 | public BaseDao getDAO() { 28 | return userRoleDao; 29 | } 30 | 31 | @Override 32 | public List findByUserId(int uid) { 33 | return userRoleDao.findByUserId(uid); 34 | } 35 | 36 | @Override 37 | public void deleleByUserId(int uid) { 38 | userRoleDao.deleleByUserId(uid); 39 | } 40 | 41 | @Override 42 | public void add(int userId, String code) { 43 | Role role = this.roleService.findByCode(code); 44 | if(role == null){ 45 | return ; 46 | } 47 | UserRole userRole = new UserRole(); 48 | userRole.setUserId(userId); 49 | userRole.setRoleId(role.getId()); 50 | this.userRoleDao.save(userRole); 51 | } 52 | 53 | @Override 54 | public Set findRoleIds(int userId) { 55 | List list = this.userRoleDao.findByUserId(userId); 56 | Set ids = Sets.newHashSet(); 57 | for(UserRole entity : list){ 58 | ids.add(entity.getRoleId()); 59 | } 60 | return ids; 61 | } 62 | 63 | @Autowired 64 | private RoleService roleService; 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.service.impl; 2 | 3 | import java.sql.Timestamp; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import javax.persistence.criteria.CriteriaBuilder; 9 | import javax.persistence.criteria.CriteriaQuery; 10 | import javax.persistence.criteria.Predicate; 11 | import javax.persistence.criteria.Root; 12 | 13 | import org.apache.commons.lang3.StringUtils; 14 | import org.apache.commons.lang3.math.NumberUtils; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.data.domain.Page; 17 | import org.springframework.data.domain.PageRequest; 18 | import org.springframework.data.domain.Pageable; 19 | import org.springframework.data.domain.Sort; 20 | import org.springframework.data.domain.Sort.Direction; 21 | import org.springframework.data.jpa.domain.Specification; 22 | import org.springframework.stereotype.Service; 23 | import org.springframework.transaction.annotation.Transactional; 24 | 25 | import com.onecoderspace.base.component.common.dao.BaseDao; 26 | import com.onecoderspace.base.component.common.service.BaseServiceImpl; 27 | import com.onecoderspace.base.dao.UserDao; 28 | import com.onecoderspace.base.domain.User; 29 | import com.onecoderspace.base.domain.UserRole; 30 | import com.onecoderspace.base.service.UserRoleService; 31 | import com.onecoderspace.base.service.UserService; 32 | import com.onecoderspace.base.util.Constants; 33 | import com.onecoderspace.base.util.LoginSessionHelper; 34 | import com.onecoderspace.base.util.Return; 35 | import com.onecoderspace.base.util.SaltMD5Util; 36 | 37 | @Transactional 38 | @Service("userService") 39 | public class UserServiceImpl extends BaseServiceImpl implements UserService{ 40 | 41 | @Autowired 42 | private UserDao userDao; 43 | 44 | @Override 45 | public BaseDao getDAO() { 46 | return userDao; 47 | } 48 | 49 | @Override 50 | public User findByUsername(String username) { 51 | return userDao.findByUsernameAndDel(username,Constants.DEL_NO); 52 | } 53 | 54 | @Override 55 | public Return changePwd(User entity, String pwd) { 56 | String salt = SaltMD5Util.getSalt(); 57 | entity.setPwd(SaltMD5Util.encode(pwd, salt)); 58 | entity.setSalt(salt); 59 | userDao.save(entity); 60 | return Return.success(); 61 | } 62 | 63 | @Override 64 | public Page listByPage(final Map params,Pageable pageable){ 65 | Specification spec = new Specification() { 66 | @Override 67 | public Predicate toPredicate(Root root,CriteriaQuery query,CriteriaBuilder cb) { 68 | List list = new ArrayList(); 69 | String type = params.get("type"); 70 | String status= params.get("status"); 71 | String username = params.get("username"); 72 | String name = params.get("name"); 73 | 74 | if(StringUtils.isNotBlank(type)){ 75 | list.add(cb.equal(root.get("type").as(Integer.class), NumberUtils.toInt(type))); 76 | } 77 | if(StringUtils.isNotBlank(status)){ 78 | list.add(cb.equal(root.get("status").as(Integer.class), NumberUtils.toInt(status))); 79 | } 80 | if(StringUtils.isNotBlank(username)){ 81 | list.add(cb.like(root.get("username").as(String.class), String.format("%%%s%%", username))); 82 | } 83 | if(StringUtils.isNotBlank(name)){ 84 | list.add(cb.like(root.get("name").as(String.class), String.format("%%%s%%", name))); 85 | } 86 | list.add(cb.equal(root.get("del"), Constants.DEL_NO)); 87 | Predicate[] p = new Predicate[list.size()]; 88 | return cb.and(list.toArray(p)); 89 | 90 | //in条件查询 91 | /*List ids = Lists.newArrayList(); 92 | ids.add(1); 93 | ids.add(2); 94 | In in = cb.in(root.get("id").as(Integer.class)); 95 | in.value(1); 96 | in.value(2); 97 | return cb.or(in);*/ 98 | } 99 | }; 100 | Page page = userDao.findAll(spec, pageable); 101 | return page; 102 | } 103 | 104 | @Override 105 | public Return doAudit(User entity, int value, String msg) { 106 | if(value == 1){ 107 | entity.setStatus(User.STATUS_AUDIT_PASS); 108 | } else { 109 | entity.setStatus(User.STATUS_AUDIT_UNPASS); 110 | } 111 | int currentUid = LoginSessionHelper.getCurrentUserId(); 112 | entity.setUpdator(currentUid); 113 | entity.setUpdateTime(new Timestamp(System.currentTimeMillis())); 114 | userDao.save(entity); 115 | Pageable pageable = new PageRequest(0, 10, new Sort(Direction.DESC, "updateTime")); 116 | Page page = userDao.findAll(pageable); 117 | 118 | return Return.success(); 119 | } 120 | 121 | @Override 122 | public Return doSetRoles(int uid, String roleIds) { 123 | userRoleService.deleleByUserId(uid); 124 | String[] arr = roleIds.split(","); 125 | for (String roleId : arr) { 126 | UserRole entity = new UserRole(); 127 | entity.setUserId(uid); 128 | entity.setRoleId(NumberUtils.toInt(roleId)); 129 | userRoleService.save(entity); 130 | } 131 | return Return.success(); 132 | } 133 | 134 | @Override 135 | public Return saveUser(User user) { 136 | this.userDao.save(user); 137 | 138 | String code = user.getType() == User.TYPE_OPERATOR ? Constants.ROLE_CODE_OPERATOR : Constants.ROLE_CODE_USER; 139 | this.userRoleService.add(user.getId(),code); 140 | 141 | return Return.success(); 142 | } 143 | 144 | @Autowired 145 | private UserRoleService userRoleService; 146 | 147 | } 148 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/AjaxResponseWriter.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util; 2 | 3 | import java.io.IOException; 4 | import java.io.PrintWriter; 5 | import java.util.Map; 6 | 7 | import javax.servlet.http.HttpServletRequest; 8 | import javax.servlet.http.HttpServletResponse; 9 | 10 | import com.google.common.collect.Maps; 11 | 12 | /** 13 | * 当前端通过ajax请求时,直接将返回结果写回前端 14 | * @author yangwk 15 | */ 16 | public class AjaxResponseWriter { 17 | 18 | /** 19 | * 写回数据到前端 20 | * @param request 21 | * @param response 22 | * @param status {@link ServiceStatusEnum} 23 | * @param message 返回的描述信息 24 | * @throws IOException 25 | */ 26 | public static void write(HttpServletRequest request,HttpServletResponse response,ServiceStatusEnum status,String message) throws IOException{ 27 | String contentType = "application/json"; 28 | response.setContentType(contentType); 29 | response.setCharacterEncoding("UTF-8"); 30 | response.setHeader("Access-Control-Allow-Credentials", "true"); 31 | response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin")); 32 | 33 | Map map = Maps.newLinkedHashMap(); 34 | map.put("service_status", status.code); 35 | map.put("description", message); 36 | String result = JacksonHelper.toJson(map); 37 | PrintWriter out = response.getWriter(); 38 | try{ 39 | out.print(result); 40 | out.flush(); 41 | } finally { 42 | out.close(); 43 | } 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/Constants.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util; 2 | 3 | public class Constants { 4 | 5 | /**已删除*/ 6 | public static final int DEL_YES = 1; 7 | 8 | /**未删除*/ 9 | public static final int DEL_NO = 0; 10 | 11 | 12 | /**普通用户*/ 13 | public static final String ROLE_CODE_USER = "user"; 14 | /**操作员*/ 15 | public static final String ROLE_CODE_OPERATOR = "operator"; 16 | /**管理员*/ 17 | public static final String ROLE_CODE_ADMIN = "admin"; 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/DateUtils.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util; 2 | 3 | import java.sql.Timestamp; 4 | import java.util.Calendar; 5 | 6 | import org.apache.commons.lang3.StringUtils; 7 | import org.joda.time.DateTime; 8 | 9 | public class DateUtils { 10 | 11 | public final static String DATE_FORMAT_DEFAULT = "yyyy-MM-dd"; 12 | public final static String DATE_FORMAT_TIME = "yyyy-MM-dd HH:mm"; 13 | public final static String DATE_FORMAT_ALL = "yyyy-MM-dd HH:mm:ss"; 14 | public final static String DATE_CHINA_DEFAULT = "yyyy年MM月dd日"; 15 | 16 | /** 17 | * 获取指定日期前后num天的日期 18 | * @author yangwk 19 | * @time 2017年9月14日 上午11:13:18 20 | * @param date 21 | * @param num 正数 多少天之后的日期 负数 多少天之后的日期 22 | * @return 23 | */ 24 | public static String getDay(String date,int num){ 25 | return getDay(date, num,DATE_FORMAT_DEFAULT); 26 | } 27 | 28 | /** 29 | * 获取指定日期前后num天的日期 30 | * @author yangwk 31 | * @time 2017年9月14日 上午11:13:18 32 | * @param date 33 | * @param num 正数 多少天之后的日期 负数 多少天之后的日期 34 | * @param format 日期格式 35 | * @return 36 | */ 37 | public static String getDay(String date,int num,String format){ 38 | long t = parseStringToLong(date); 39 | return getDay(t, num, DATE_FORMAT_DEFAULT); 40 | } 41 | 42 | /** 43 | * 获取指定日期前后num天的日期 44 | * @author yangwk 45 | * @time 2017年9月14日 上午11:13:18 46 | * @param date 47 | * @param num 正数 多少天之后的日期 负数 多少天之后的日期 48 | * @return 49 | */ 50 | public static String getDay(long date,int num){ 51 | return getDay(date, num, DATE_FORMAT_DEFAULT); 52 | } 53 | 54 | /** 55 | * 获取指定日期前后num天的日期 56 | * @author yangwk 57 | * @time 2017年9月14日 上午11:13:18 58 | * @param date 59 | * @param num 正数 多少天之后的日期 负数 多少天之后的日期 60 | * @param format 日期格式 61 | * @return 62 | */ 63 | public static String getDay(long date,int num,String format){ 64 | Calendar calendar = Calendar.getInstance(); 65 | calendar.setTimeInMillis(date); 66 | calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH)+num); 67 | return longToString(calendar.getTimeInMillis(),format); 68 | } 69 | 70 | /** 71 | * 将毫秒时间转换为yyyy-MM-dd格式的时间 72 | * @author yangwenkui 73 | * @time 2017年10月6日 下午5:56:40 74 | * @param time 毫秒数 75 | * @return 76 | */ 77 | public static String longToString(long time) { 78 | return longToString(time, DATE_FORMAT_DEFAULT); 79 | } 80 | 81 | /** 82 | * 将毫秒时间转换为指定格式的时间 83 | * @author yangwenkui 84 | * @time 2017年10月6日 下午5:56:40 85 | * @param time 毫秒数 86 | * @param format 日期格式 87 | * @return 88 | */ 89 | public static String longToString(long time, String format) { 90 | if (StringUtils.isBlank(format)) { 91 | format = DATE_FORMAT_DEFAULT; 92 | } 93 | DateTime dTime = new DateTime(time); 94 | return dTime.toString(format); 95 | } 96 | 97 | /** 98 | * 获取今天开始的时间 99 | * @author yangwenkui 100 | * @time 2017年10月6日 下午5:58:18 101 | * @return 102 | */ 103 | public static Timestamp getTodayStartTime() { 104 | Calendar cal = Calendar.getInstance(); 105 | cal.set(Calendar.HOUR_OF_DAY, 0); 106 | cal.set(Calendar.SECOND, 0); 107 | cal.set(Calendar.MINUTE, 0); 108 | cal.set(Calendar.MILLISECOND, 001); 109 | return new Timestamp(cal.getTimeInMillis()); 110 | } 111 | 112 | /** 113 | * 获取指定日期开始的当日开始时间 114 | * @author yangwenkui 115 | * @time 2017年10月6日 下午5:58:33 116 | * @param date 117 | * @return 118 | */ 119 | public static long getDayStartTime(String date) { 120 | Calendar cal = Calendar.getInstance(); 121 | cal.setTimeInMillis(parseStringToLong(date)); 122 | cal.set(Calendar.HOUR_OF_DAY, 0); 123 | cal.set(Calendar.SECOND, 0); 124 | cal.set(Calendar.MINUTE, 0); 125 | cal.set(Calendar.MILLISECOND, 001); 126 | return cal.getTimeInMillis(); 127 | } 128 | 129 | /** 130 | * 获取指定日期结束时间 131 | * @author yangwenkui 132 | * @time 2017年10月6日 下午5:58:58 133 | * @param date 134 | * @return 135 | */ 136 | public static long getDayEndTime(String date) { 137 | Calendar cal = Calendar.getInstance(); 138 | cal.setTimeInMillis(parseStringToLong(date)); 139 | cal.set(Calendar.HOUR_OF_DAY, 23); 140 | cal.set(Calendar.SECOND, 59); 141 | cal.set(Calendar.MINUTE, 59); 142 | cal.set(Calendar.MILLISECOND, 999); 143 | return cal.getTimeInMillis(); 144 | } 145 | 146 | /** 147 | * 获得当前日期 148 | */ 149 | public static String getCurrentTime() { 150 | return getCurrentTime("yyyy-MM-dd"); 151 | } 152 | 153 | /** 154 | * 获得当前时间 155 | * @param format 日期格式 156 | * @return 157 | */ 158 | public static String getCurrentTime(String format) { 159 | DateTime dTime = new DateTime(); 160 | return dTime.toString(format); 161 | } 162 | 163 | /** 164 | * 将字符串类型的日期转换为毫秒数 165 | * @author yangwenkui 166 | * @time 2017年10月6日 下午6:00:27 167 | * @param dateStr 168 | * @return 169 | */ 170 | public static long parseStringToLong(String dateStr) { 171 | dateStr = dateStr.trim(); 172 | if (dateStr.length() == 19 || dateStr.length() == 23) { 173 | try { 174 | java.util.Calendar cal = java.util.Calendar.getInstance(); 175 | cal.set(Integer.parseInt(dateStr.substring(0, 4)), 176 | Integer.parseInt(dateStr.substring(5, 7)) - 1, 177 | Integer.parseInt(dateStr.substring(8, 10)), 178 | Integer.parseInt(dateStr.substring(11, 13)), 179 | Integer.parseInt(dateStr.substring(14, 16)), 180 | Integer.parseInt(dateStr.substring(17, 19))); 181 | cal.set(java.util.Calendar.MILLISECOND, 0); 182 | return (cal.getTime().getTime()); 183 | } catch (Exception e) { 184 | return 0; 185 | } 186 | 187 | } else if (dateStr.length() == 16) { 188 | try { 189 | java.util.Calendar cal = java.util.Calendar.getInstance(); 190 | cal.set(Integer.parseInt(dateStr.substring(0, 4)), 191 | Integer.parseInt(dateStr.substring(5, 7)) - 1, 192 | Integer.parseInt(dateStr.substring(8, 10)), 193 | Integer.parseInt(dateStr.substring(11, 13)), 194 | Integer.parseInt(dateStr.substring(14, 16))); 195 | cal.set(java.util.Calendar.MILLISECOND, 0); 196 | return (cal.getTime().getTime()); 197 | } catch (Exception e) { 198 | return 0; 199 | } 200 | 201 | } else if (dateStr.length() == 14) { 202 | try { 203 | java.util.Calendar cal = java.util.Calendar.getInstance(); 204 | cal.set(Integer.parseInt(dateStr.substring(0, 4)), 205 | Integer.parseInt(dateStr.substring(4, 6)) - 1, 206 | Integer.parseInt(dateStr.substring(6, 8)), 207 | Integer.parseInt(dateStr.substring(8, 10)), 208 | Integer.parseInt(dateStr.substring(10, 12)), 209 | Integer.parseInt(dateStr.substring(12, 14))); 210 | cal.set(java.util.Calendar.MILLISECOND, 0); 211 | return (cal.getTime().getTime()); 212 | } catch (Exception e) { 213 | return 0; 214 | } 215 | } else if (dateStr.length() == 10 || dateStr.length() == 11) { 216 | try { 217 | java.util.Calendar cal = java.util.Calendar.getInstance(); 218 | cal.set(Integer.parseInt(dateStr.substring(0, 4)), 219 | Integer.parseInt(dateStr.substring(5, 7)) - 1, 220 | Integer.parseInt(dateStr.substring(8, 10)), 0, 0, 0); 221 | cal.set(java.util.Calendar.MILLISECOND, 0); 222 | return (cal.getTime().getTime()); 223 | } catch (Exception e) { 224 | return 0; 225 | } 226 | } else if (dateStr.length() == 8 ) { 227 | try { 228 | java.util.Calendar cal = java.util.Calendar.getInstance(); 229 | cal.set(Integer.parseInt(dateStr.substring(0, 4)), 230 | Integer.parseInt(dateStr.substring(4, 6)) - 1, 231 | Integer.parseInt(dateStr.substring(6, 8)), 0, 0, 0); 232 | cal.set(java.util.Calendar.MILLISECOND, 0); 233 | return (cal.getTime().getTime()); 234 | } catch (Exception e) { 235 | return 0; 236 | } 237 | } else { 238 | try { 239 | return Long.parseLong(dateStr); 240 | } catch (Exception e) { 241 | return 0; 242 | } 243 | 244 | } 245 | } 246 | 247 | public static void main(String[] args) { 248 | System.out.println(getDay(System.currentTimeMillis(), -30)); 249 | } 250 | } -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/FileUtil.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.IOException; 6 | import java.util.List; 7 | 8 | import org.apache.commons.io.IOUtils; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | 12 | import com.google.common.collect.Lists; 13 | 14 | public class FileUtil { 15 | private static Logger logger = LoggerFactory.getLogger(FileUtil.class); 16 | 17 | /** 18 | * 读取文件内的所有行 19 | * @author yangwk 20 | * @time 2017年9月12日 上午9:46:33 21 | * @param filePath 文件完整路径 22 | * @return 23 | */ 24 | public static List getLines(String filePath){ 25 | FileInputStream inputStream = null; 26 | List lines = Lists.newArrayList(); 27 | try { 28 | inputStream = new FileInputStream(new File(filePath)); 29 | lines = IOUtils.readLines(inputStream); 30 | } catch (Exception e) { 31 | logger.error("read file due to error",e); 32 | }finally { 33 | try { 34 | if(inputStream != null){ 35 | inputStream.close(); 36 | } 37 | } catch (IOException e) { 38 | logger.error("close inputStream due to error",e); 39 | } 40 | } 41 | return lines; 42 | } 43 | 44 | /** 45 | * 写入文件 46 | * @author yangwk 47 | * @time 2017年9月14日 下午1:44:23 48 | * @param file 49 | * @param lines 50 | */ 51 | public static void writeLines(File file, List lines) { 52 | try { 53 | org.apache.commons.io.FileUtils.writeLines(file, lines, "\n"); 54 | } catch (IOException e) { 55 | logger.error("write lines due to error",e); 56 | } 57 | 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/HttpServletHelper.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util; 2 | 3 | import java.util.Map; 4 | 5 | import javax.servlet.http.Cookie; 6 | import javax.servlet.http.HttpServletRequest; 7 | import javax.servlet.http.HttpServletResponse; 8 | 9 | import org.apache.commons.lang3.ArrayUtils; 10 | import org.apache.commons.lang3.StringUtils; 11 | import org.springframework.web.context.request.RequestContextHolder; 12 | import org.springframework.web.context.request.ServletRequestAttributes; 13 | 14 | import com.google.common.base.Joiner; 15 | import com.google.common.base.Joiner.MapJoiner; 16 | import com.google.common.base.Splitter; 17 | import com.google.common.collect.Maps; 18 | 19 | public class HttpServletHelper { 20 | 21 | public static String getCookie(HttpServletRequest request, String key) { 22 | Cookie[] cookies = request.getCookies(); 23 | 24 | if(ArrayUtils.isEmpty(cookies)){ 25 | return StringUtils.EMPTY; 26 | } 27 | 28 | for (Cookie cookie : cookies) { 29 | if(StringUtils.equals(cookie.getName(), key) ){ 30 | return cookie.getValue(); 31 | } 32 | } 33 | return StringUtils.EMPTY; 34 | } 35 | 36 | 37 | public static void delCookie(HttpServletResponse response,String key){ 38 | Cookie del= new Cookie(key,null); 39 | del.setMaxAge(0); 40 | response.addCookie(del); 41 | } 42 | 43 | public static void delCookie(HttpServletResponse response,String key,String path,String domain){ 44 | Cookie del= new Cookie(key,null); 45 | del.setMaxAge(0); 46 | if(StringUtils.isNotBlank(path)){ 47 | del.setPath(path); 48 | } 49 | if(StringUtils.isNotBlank(domain)){ 50 | del.setDomain(domain); 51 | } 52 | response.addCookie(del); 53 | } 54 | 55 | public static void addCookie(HttpServletResponse response, Cookie cookie){ 56 | response.addCookie(cookie); 57 | } 58 | 59 | 60 | //Set-Cookie: =[; =][; expires=][; domain=]=[; path=][; secure][; HttpOnly] 61 | public static void addCookieHttpOnly(HttpServletResponse response, Cookie cookie){ 62 | 63 | int maxAge = cookie.getMaxAge(); 64 | if(maxAge==0){ 65 | return; 66 | } 67 | StringBuilder sb = new StringBuilder(cookie.getName()); 68 | sb.append("="); 69 | sb.append(cookie.getValue()); 70 | 71 | if(maxAge>0){ 72 | sb.append(";").append("Max-Age=").append(cookie.getMaxAge()); 73 | } 74 | 75 | if(StringUtils.isNotBlank(cookie.getDomain())){ 76 | sb.append(";").append("Domain=").append(cookie.getDomain()); 77 | } 78 | if(StringUtils.isNotBlank(cookie.getPath())){ 79 | sb.append(";").append("Path=").append(cookie.getPath()); 80 | } 81 | sb.append("; HttpOnly"); 82 | 83 | String cookieStr = sb.toString(); 84 | response.addHeader("Set-Cookie", cookieStr); 85 | //response.setHeader("Set-Cookie", cookieStr); //错误用法,其他cookie会被覆盖 86 | } 87 | 88 | 89 | private static final String SESSION_KEY_CALLBACK = "cb_url"; 90 | public static void setCallBackUrl(HttpServletRequest request){ 91 | 92 | String callback = getCurrentUrl(request);// eg. /iapp/study/me.do?a=b 93 | request.getSession().setAttribute(SESSION_KEY_CALLBACK, callback); 94 | } 95 | 96 | 97 | public static String getCallBackUrlAndClean(HttpServletRequest request){ 98 | String callback =(String) request.getSession().getAttribute(SESSION_KEY_CALLBACK); 99 | 100 | if(StringUtils.isNotBlank(callback)){ 101 | request.getSession().removeAttribute(SESSION_KEY_CALLBACK); 102 | } 103 | return callback; 104 | } 105 | 106 | public static String getCurrentUrl(HttpServletRequest request){ 107 | return Joiner.on("?").skipNulls().join(request.getRequestURL().toString(), request.getQueryString()); // eg. http://xxx:xx/iapp/study/me.do?a=b 108 | 109 | } 110 | 111 | 112 | /** 113 | * 获取跟路径 114 | * @param request 115 | * @return 116 | */ 117 | public static String getRootPath(HttpServletRequest request){ 118 | String rootPath = String.format("%s:%s%s", request.getServerName(),request.getServerPort(),request.getContextPath()); 119 | return rootPath; 120 | } 121 | 122 | /** 123 | * 获取绝对路径 124 | * @param request 125 | * @param relativePath 126 | * @return 127 | */ 128 | public static String getAbsolutePath(HttpServletRequest request, 129 | String relativePath) { 130 | return String.format("http://%s/%s", getRootPath(request),relativePath); 131 | } 132 | 133 | 134 | private static MapJoiner queryStringMapJoiner = Joiner.on("&").withKeyValueSeparator("="); 135 | 136 | public static String replaceQueryString(String queryString, String key, String value) { 137 | Map myMap = Splitter.on("&").trimResults().withKeyValueSeparator("=").split(queryString); 138 | myMap = Maps.newHashMap(myMap); 139 | myMap.put(key, value); 140 | return queryStringMapJoiner.join(myMap); 141 | } 142 | 143 | public static String removeParamQueryString(String queryString, String key) { 144 | Map myMap = Splitter.on("&").trimResults().withKeyValueSeparator("=").split(queryString); 145 | myMap = Maps.newHashMap(myMap); 146 | myMap.remove(key); 147 | return queryStringMapJoiner.join(myMap); 148 | } 149 | 150 | public static String getRequestUri(){ 151 | HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); 152 | //获取请求的URL 153 | String requestUri = request.getRequestURI(); 154 | return requestUri; 155 | } 156 | 157 | } 158 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/JacksonHelper.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util; 2 | 3 | import java.io.IOException; 4 | import java.util.Collection; 5 | import java.util.Map; 6 | import java.util.Map.Entry; 7 | 8 | import org.codehaus.jackson.map.ObjectMapper; 9 | import org.codehaus.jackson.type.JavaType; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | 13 | public class JacksonHelper { 14 | 15 | private static final ObjectMapper mapper = new ObjectMapper(); 16 | 17 | private static Logger logger = LoggerFactory.getLogger(JacksonHelper.class); 18 | 19 | 20 | /** 21 | * 将对象转化为json 22 | * @author yangwenkui 23 | * @time 2017年3月16日 下午2:55:10 24 | * @param obj 待转化的对象 25 | * @return 当转化发生异常时返回null 26 | */ 27 | public static String toJson(Object obj){ 28 | if(obj == null){ 29 | return null; 30 | } 31 | try { 32 | return mapper.writeValueAsString(obj); 33 | } catch (IOException e) { 34 | logger.error(String.format("obj=[%s]", obj.toString()), e); 35 | } 36 | return null; 37 | } 38 | 39 | /** 40 | * 将json转化为对象 41 | * @author yangwenkui 42 | * @time 2017年3月16日 下午2:56:26 43 | * @param json json对象 44 | * @param clazz 待转化的对象类型 45 | * @return 当转化发生异常时返回null 46 | */ 47 | public static T fromJson(String json,Class clazz){ 48 | if(json == null){ 49 | return null; 50 | } 51 | try { 52 | return mapper.readValue(json, clazz); 53 | } catch (IOException e) { 54 | logger.error(String.format("json=[%s]", json), e); 55 | } 56 | return null; 57 | } 58 | 59 | /** 60 | * 将json对象转化为集合类型 61 | * @author yangwenkui 62 | * @time 2017年3月16日 下午2:57:15 63 | * @param json json对象 64 | * @param collectionClazz 具体的集合类的class,如:ArrayList.class 65 | * @param clazz 集合内存放的对象的class 66 | * @return 67 | */ 68 | @SuppressWarnings("rawtypes") 69 | public static Collection fromJson(String json,Class collectionClazz,Class clazz){ 70 | if(json == null){ 71 | return null; 72 | } 73 | try { 74 | Collection collection = mapper.readValue(json, getCollectionType(collectionClazz,clazz)); 75 | return collection; 76 | } catch (IOException e) { 77 | logger.error(String.format("json=[%s]", json), e); 78 | } 79 | return null; 80 | } 81 | 82 | private static JavaType getCollectionType(Class collectionClass, Class... elementClasses) { 83 | return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); 84 | } 85 | 86 | public static void main(String[] args) { 87 | String s = "{\"ss\":\"12\",\"dd\":\"33\",\"tt\":23}"; 88 | @SuppressWarnings("unchecked") 89 | Map map = fromJson(s, Map.class); 90 | for (Entry entry : map.entrySet()) { 91 | System.out.println(entry); 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/JsUtils.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.util.List; 6 | 7 | import javax.script.ScriptEngine; 8 | import javax.script.ScriptEngineManager; 9 | import javax.script.ScriptException; 10 | 11 | import org.apache.commons.io.IOUtils; 12 | import org.slf4j.Logger; 13 | import org.slf4j.LoggerFactory; 14 | 15 | public class JsUtils { 16 | private static Logger logger = LoggerFactory.getLogger(JsUtils.class); 17 | 18 | /** 19 | * 获取js代码内的某个变量值 20 | * @author yangwk 21 | * @time 2017年9月7日 下午1:57:46 22 | * @param jsCode 23 | * @param property 24 | * @return 25 | */ 26 | public static String getProperty(String jsCode,String property){ 27 | try { 28 | ScriptEngineManager manager = new ScriptEngineManager(); 29 | ScriptEngine engine = manager.getEngineByName("javascript"); 30 | engine.eval(jsCode); 31 | String value = (String) engine.get(property); 32 | return value; 33 | } catch (ScriptException e) { 34 | logger.error(String.format("jsCode=%s,property=%s", jsCode,property),e); 35 | } 36 | return ""; 37 | } 38 | 39 | public static void main(String[] args) throws Exception { 40 | List list = IOUtils.readLines(new FileInputStream(new File("D:/workspace/crawler-task/doc/test.js"))); 41 | System.out.println(getProperty(list.get(0), "code")); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/ListOptionHelper.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util; 2 | 3 | 4 | import java.util.ArrayList; 5 | import java.util.Collection; 6 | import java.util.HashSet; 7 | import java.util.List; 8 | import java.util.Set; 9 | 10 | import org.apache.commons.lang3.StringUtils; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | 14 | import com.google.common.base.Joiner; 15 | import com.google.common.collect.Lists; 16 | 17 | public class ListOptionHelper { 18 | 19 | private static Logger logger = LoggerFactory.getLogger(JacksonHelper.class); 20 | 21 | /** 22 | * 获取在first集合内而不在second集合内的元素 23 | * @param first 24 | * @param second 25 | * @return 26 | */ 27 | public static List getDiffList(Collection first, Collection second) { 28 | long t = System.currentTimeMillis(); 29 | Set sameString = new HashSet(second); 30 | List result = new ArrayList(first.size()); 31 | for (String s : first) { 32 | if (!sameString.contains(s)) { 33 | result.add(s); 34 | } 35 | } 36 | if(System.currentTimeMillis() - t > 1){ 37 | logger.debug("getDiffList with list first.size={},sencond.size={},use time={}ms",first.size(),second.size(),System.currentTimeMillis()-t); 38 | } 39 | 40 | return result; 41 | } 42 | 43 | /** 44 | * 获得在list内同时在list2内的元素 45 | * 注意:在结果集内并不去重,如果list内本身有重复,返回的结果内可能包含相同元素 46 | * @param list 47 | * @param list2 48 | * @return 49 | */ 50 | public static List getSameElements(Collection list, Collection list2) { 51 | long t = System.nanoTime(); 52 | Set set = new HashSet(list2); 53 | List sameElements = new ArrayList(list.size()); 54 | for(String item : list){ 55 | if(set.contains(item)){ 56 | sameElements.add(item); 57 | } 58 | } 59 | if(logger.isDebugEnabled()){ 60 | logger.debug("getSameElements list.size={},list2.size={},use time={}ns",list.size(),list2.size(),System.nanoTime()-t); 61 | } 62 | return sameElements; 63 | } 64 | 65 | 66 | /** 67 | * 判断集合list和list2内是否有相同元素 68 | * @param list 69 | * @param list2 70 | * @return 71 | */ 72 | public static boolean hasSameItem(List list,List list2){ 73 | for (String item : list) { 74 | if(list2.contains(item)){ 75 | return true; 76 | } 77 | } 78 | return false; 79 | } 80 | 81 | /** 82 | * 辅助方法,将字符串分割转换为list 83 | * @author yangwenkui 84 | * @time 2017年1月10日 下午4:22:20 85 | * @param provinceIds 86 | * @return 87 | */ 88 | public static List stringToList(String str,String split) { 89 | if(StringUtils.isBlank(str)){ 90 | return Lists.newArrayList(); 91 | } 92 | String[] arr = str.split(split); 93 | List list = new ArrayList(arr.length); 94 | for(String item : arr){ 95 | if(StringUtils.isNotBlank(item)){ 96 | list.add(item); 97 | } 98 | } 99 | return list; 100 | } 101 | 102 | public static void main(String[] args) { 103 | 104 | for(int j=0;j<20;j++){ 105 | List all = Lists.newArrayList(); 106 | for(int i=1000000;i<1001500;i++){ 107 | all.add(String.valueOf(i)); 108 | } 109 | 110 | List hasSend = Lists.newArrayList(); 111 | for(int i=1000000;i<1000500;i++){ 112 | hasSend.add(String.valueOf(i)); 113 | } 114 | long t = System.nanoTime(); 115 | // List list = getDiffList1(all, hasSend);//12ms 116 | // all.removeAll(hasSend);//9ms 117 | List list = getDiffList(all, hasSend);//2ms 当前选用 20次调用时平均耗时0.2ms 118 | // List list = getSameElements1(all, hasSend);//8ms 119 | // List list = getSameElements2(all, hasSend);//6ms 120 | // List list = getSameElements(all, hasSend);//1ms 当前选用 121 | System.out.println(System.nanoTime()-t); 122 | System.out.println("size="+list.size()+JacksonHelper.toJson(list)); 123 | } 124 | } 125 | 126 | 127 | 128 | 129 | 130 | /**以下方法因低效,放弃使用*/ 131 | // public static List getDiffList1(List firstList, List secondList) { 132 | // if(CollectionUtils.isEmpty(firstList)){ 133 | // return Lists.newArrayList(); 134 | // } 135 | // if(CollectionUtils.isEmpty(secondList)){ 136 | // return firstList; 137 | // } 138 | // 139 | // List results = Lists.newArrayList(); 140 | // for(String item : firstList){ 141 | // if(!secondList.contains(item)){ 142 | // results.add(item); 143 | // } 144 | // } 145 | // return results; 146 | // } 147 | 148 | // @SuppressWarnings("unchecked") 149 | // public static List getSameElements1(List list, List list2) { 150 | // return new ArrayList(CollectionUtils.intersection(list, list2)); 151 | // } 152 | 153 | // public static List getSameElements2(List list, List list2) { 154 | // List sameElements = Lists.newArrayList(); 155 | // for(String item : list){ 156 | // if(list2.contains(item)){ 157 | // sameElements.add(item); 158 | // } 159 | // } 160 | // return sameElements; 161 | // } 162 | 163 | } 164 | 165 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/LoginSessionHelper.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util; 2 | 3 | import org.apache.shiro.SecurityUtils; 4 | import org.apache.shiro.subject.Subject; 5 | import org.springframework.web.context.request.RequestContextHolder; 6 | 7 | public class LoginSessionHelper { 8 | 9 | /** 10 | * 返回当前用户ID 11 | * @return 12 | */ 13 | public static int getCurrentUserId(){ 14 | Subject currentUser = SecurityUtils.getSubject(); 15 | if(currentUser == null || currentUser.getPrincipal() == null){ 16 | return 0; 17 | } 18 | Integer userId = (Integer) currentUser.getPrincipal(); 19 | return userId; 20 | } 21 | 22 | /** 23 | * 返回当前用户唯一标记,当用户已登录,返回用户ID,当用户未登录,返回sessionId 24 | * @return 25 | */ 26 | public static String getCurrentUserKey(){ 27 | Subject currentUser = SecurityUtils.getSubject(); 28 | Integer userId = (Integer) currentUser.getPrincipal(); 29 | if(userId == null){ 30 | String sessionId = RequestContextHolder.getRequestAttributes().getSessionId(); 31 | return sessionId; 32 | } 33 | return String.valueOf(userId); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/MD5.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util; 2 | 3 | import java.security.MessageDigest; 4 | 5 | 6 | 7 | /**MD5加密算法 8 | * @author songsp 2010-1-13 9 | * 10 | */ 11 | public class MD5 { 12 | public final static String encodeMd5(String s) { 13 | char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 14 | 'a', 'b', 'c', 'd', 'e', 'f' }; 15 | try { 16 | byte[] strTemp = s.getBytes(); 17 | MessageDigest mdTemp = MessageDigest.getInstance("MD5");//返回实现MD5摘要算法的 MessageDigest 对象 18 | mdTemp.update(strTemp);//使用指定的字节更新摘要 19 | byte[] md = mdTemp.digest();// 得到md5算法结果 //通过执行诸如填充之类的最终操作完成哈希计算 20 | int j = md.length; 21 | char str[] = new char[j * 2]; 22 | int k = 0; 23 | for (int i = 0; i < j; i++) { 24 | byte byte0 = md[i]; 25 | str[k++] = hexDigits[byte0 >>> 4 & 0xf];// 分成高低4位处理 26 | str[k++] = hexDigits[byte0 & 0xf]; 27 | } 28 | return new String(str); 29 | } catch (Exception e) { 30 | return null; 31 | } 32 | } 33 | 34 | 35 | 36 | public static void main(String[] args) { 37 | String key = System.currentTimeMillis()+""; 38 | System.out.println(key); 39 | System.out.println(MD5.encodeMd5("md5cenwavepublickey"+key+"cenwave1000001")); 40 | System.out.println(MD5.encodeMd5("bosskey2010-05-30 16:00:002010-06-08 15:59:59")); 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/OperationCheck.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util; 2 | 3 | public class OperationCheck { 4 | 5 | /** 6 | * 校验数据拥有者是否是当前用户 7 | * @author yangwk 8 | * @time 2017年7月27日 上午9:52:05 9 | * @param uid 数据拥有者ID 10 | * @return 11 | */ 12 | public static boolean isOwnerCurrentUser(int uid){ 13 | if(uid == LoginSessionHelper.getCurrentUserId()){ 14 | return true; 15 | } 16 | return false; 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/RandomUtils.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util; 2 | 3 | import java.util.Random; 4 | 5 | public class RandomUtils { 6 | 7 | private static final int[] numArr = {0,1,2,3,4,5,6,7,8,9}; 8 | 9 | /** 10 | * 随机获取两位数字 11 | * @author yangwk 12 | * @time 2017年7月28日 下午3:26:44 13 | * @param length 数字长度 14 | * @return 15 | */ 16 | public static String randomNum(int length){ 17 | StringBuilder builder = new StringBuilder(); 18 | Random random = new Random(); 19 | for(int i=0;i i){ 57 | builder.append(saltLast.charAt(i)); 58 | } 59 | builder.append(pwd.charAt(i)); 60 | } 61 | if(saltLast.length() > pwd.length()){ 62 | builder.append(saltLast.substring(pwd.length())); 63 | } 64 | return builder.toString(); 65 | } 66 | 67 | public static void main(String[] args) { 68 | String salt = "HpsuQ2d4FkqjGU01";//getSalt(); 69 | System.err.println(salt); 70 | System.err.println(encode("eva2017admin", salt)); 71 | } 72 | 73 | } 74 | 75 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/ServiceStatusEnum.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util; 2 | 3 | /** 4 | * 全局性状态码 5 | * @author yangwk 6 | */ 7 | public enum ServiceStatusEnum { 8 | UNLOGIN("0001"), //未登录 9 | ILLEGAL_TOKEN("0002"),//非法的token 10 | ; 11 | public String code; 12 | 13 | private ServiceStatusEnum(String code){ 14 | this.code = code; 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/SpringContextUtil.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util; 2 | 3 | import java.util.Locale; 4 | 5 | import org.springframework.beans.BeansException; 6 | import org.springframework.context.ApplicationContext; 7 | import org.springframework.context.ApplicationContextAware; 8 | import org.springframework.stereotype.Component; 9 | 10 | @Component 11 | public class SpringContextUtil implements ApplicationContextAware { 12 | 13 | private static ApplicationContext context; 14 | 15 | @SuppressWarnings("static-access") 16 | @Override 17 | public void setApplicationContext(ApplicationContext contex) 18 | throws BeansException { 19 | this.context=contex; 20 | } 21 | public static Object getBean(String beanName){ 22 | return context.getBean(beanName); 23 | } 24 | 25 | public static T getBean(Class requiredType){ 26 | return context.getBean(requiredType); 27 | } 28 | 29 | public T getBean(String name, Class requiredType) { 30 | return context.getBean(name, requiredType); 31 | } 32 | 33 | public static String getMessage(String key){ 34 | return context.getMessage(key, null, Locale.getDefault()); 35 | } 36 | 37 | public static ApplicationContext getApplicationContext(){ 38 | return context; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/ThreadLocalUtils.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * 注意在线程内部使用完后手动调用remove方法,避免某些使用线程池的地方出现内存泄漏|数据错误等诡异问题 8 | * @author Administrator 9 | * 10 | */ 11 | public final class ThreadLocalUtils { 12 | private static final ThreadLocal> threadLocal = new ThreadLocal>() { 13 | protected Map initialValue() { 14 | return new HashMap(4); 15 | } 16 | }; 17 | 18 | public static Map getThreadLocal(){ 19 | return threadLocal.get(); 20 | } 21 | 22 | @SuppressWarnings("unchecked") 23 | public static T get(String key) { 24 | Map map = threadLocal.get(); 25 | return (T)map.get(key); 26 | } 27 | 28 | @SuppressWarnings("unchecked") 29 | public static T get(String key,T defaultValue) { 30 | Map map = threadLocal.get(); 31 | return map.get(key) == null ? defaultValue : (T)map.get(key); 32 | } 33 | 34 | public static void set(String key, Object value) { 35 | Map map = threadLocal.get(); 36 | map.put(key, value); 37 | } 38 | 39 | public static void set(Map keyValueMap) { 40 | Map map = threadLocal.get(); 41 | map.putAll(keyValueMap); 42 | } 43 | 44 | public static void remove() { 45 | threadLocal.remove(); 46 | } 47 | 48 | @SuppressWarnings("unchecked") 49 | public static T remove(String key) { 50 | Map map = threadLocal.get(); 51 | return (T)map.remove(key); 52 | } 53 | } -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/TokenUtils.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util; 2 | 3 | import java.io.IOException; 4 | import java.util.Random; 5 | import java.util.UUID; 6 | 7 | /** 8 | * Token生成器 9 | */ 10 | public class TokenUtils { 11 | 12 | public static String defaultStr="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%"; 13 | 14 | public static String defaultNum="123456789"; 15 | 16 | /** 17 | * 使用UUID生成指定长度的Token 18 | * 19 | * @param length 20 | * 长度:8位字符串 21 | * @return 22 | */ 23 | public static String generateToken() { 24 | return UUID.randomUUID().toString().substring(0, 8); 25 | } 26 | 27 | /** 28 | * 默认:随机一个指定长度的字符串符串 29 | * @return 30 | */ 31 | public static String generateToken(int length){ 32 | String str = defaultStr; 33 | Random rd = new Random(); 34 | StringBuffer sb = new StringBuffer(); 35 | for (int i = 0; i < length; i++) { 36 | int number = rd.nextInt(str.length()); 37 | sb.append(str.charAt(number)); 38 | } 39 | return sb.toString(); 40 | } 41 | 42 | /** 43 | * 默认:随机一个指定长度的字符串符串 44 | * @return 45 | */ 46 | public static String generateToken(String str,int length){ 47 | Random rd = new Random(); 48 | StringBuffer sb = new StringBuffer(); 49 | for (int i = 0; i < length; i++) { 50 | int number = rd.nextInt(str.length()); 51 | sb.append(str.charAt(number)); 52 | } 53 | return sb.toString(); 54 | } 55 | 56 | 57 | public static void main(String[] args) throws IOException { 58 | System.out.println(generateToken(32)); 59 | System.out.println(generateToken()); 60 | System.out.println(generateToken(defaultNum,3)); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/http/AbstractHttpHelper.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util.http; 2 | 3 | import org.apache.commons.io.IOUtils; 4 | import org.apache.commons.lang3.CharEncoding; 5 | import org.apache.commons.lang3.exception.ExceptionUtils; 6 | import org.apache.http.Header; 7 | import org.apache.http.HeaderElement; 8 | import org.apache.http.HttpEntity; 9 | import org.apache.http.HttpException; 10 | import org.apache.http.HttpRequest; 11 | import org.apache.http.HttpRequestInterceptor; 12 | import org.apache.http.HttpResponse; 13 | import org.apache.http.HttpResponseInterceptor; 14 | import org.apache.http.client.HttpClient; 15 | import org.apache.http.client.ResponseHandler; 16 | import org.apache.http.client.entity.GzipDecompressingEntity; 17 | import org.apache.http.client.methods.HttpRequestBase; 18 | import org.apache.http.protocol.HttpContext; 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | 22 | import java.io.IOException; 23 | import java.util.Arrays; 24 | import java.util.Map; 25 | 26 | public abstract class AbstractHttpHelper { 27 | 28 | private static Logger logger = LoggerFactory.getLogger(HttpHelper.class); 29 | 30 | public static class GZIPRequestInterceptor implements HttpRequestInterceptor { 31 | 32 | public static final GZIPRequestInterceptor DEFAULT = new GZIPRequestInterceptor(); 33 | 34 | public static final String GZIP = "gzip"; 35 | 36 | public static final String ACCEPT_ENCODING = "Accept-Encoding"; 37 | 38 | @Override 39 | public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { 40 | if (!request.containsHeader(ACCEPT_ENCODING)) { 41 | request.addHeader(ACCEPT_ENCODING, GZIP); 42 | } 43 | } 44 | 45 | } 46 | 47 | public static class GZIPResponseInterceptor implements HttpResponseInterceptor { 48 | 49 | public static final GZIPResponseInterceptor DEFAULT = new GZIPResponseInterceptor(); 50 | 51 | @Override 52 | public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { 53 | HttpEntity entity = response.getEntity(); 54 | if (entity == null) { 55 | return; 56 | } 57 | 58 | Header header = entity.getContentEncoding(); 59 | if (header == null) { 60 | return; 61 | } 62 | 63 | HeaderElement[] codecs = header.getElements(); 64 | 65 | for (int i = 0; i < codecs.length; i++) { 66 | if (codecs[i].getName().equalsIgnoreCase(GZIPRequestInterceptor.GZIP)) { 67 | logger.debug("the content encoding is:{}, use gzip decompressing", Arrays.toString(codecs)); 68 | response.setEntity(new GzipDecompressingEntity(entity)); 69 | return; 70 | } 71 | } 72 | } 73 | 74 | } 75 | 76 | public static class ResponseToString implements ResponseHandler { 77 | 78 | public static final ResponseToString DEFAULT = new ResponseToString(CharEncoding.UTF_8); 79 | 80 | public ResponseToString(String charset) { 81 | this.charset = charset; 82 | } 83 | 84 | private String charset; 85 | 86 | @Override 87 | public String handleResponse(HttpResponse response) throws IOException { 88 | return IOUtils.toString(response.getEntity().getContent(), charset); 89 | } 90 | } 91 | 92 | public T doPost(final String url, final byte[] body, ResponseHandler handler) { 93 | return executeRequest(new RequestByBodyCreator(url, body), handler); 94 | } 95 | 96 | public T doPost(final String url, final Map parameters, ResponseHandler handler) { 97 | return executeRequest(new RequestByParametersCreator(url, parameters), handler); 98 | } 99 | 100 | public T doGet(final String url, ResponseHandler handler) { 101 | return executeRequest(new RequestByURLCreator(url), handler); 102 | } 103 | 104 | protected abstract HttpClient getHttpClient(); 105 | 106 | public T executeRequest(RequestCreator creator, final ResponseHandler handler) { 107 | 108 | HttpRequestBase request = null; 109 | try { 110 | request = creator.create(); 111 | T response = (T) getHttpClient().execute(request, new DelegateResponseHandler(handler)); 112 | return response; 113 | } catch (UnexpectedHttpStatusException e) { 114 | throw e; 115 | } catch (Exception e) { 116 | logger.error("execute request:[{}] due to error:[{}]", request.getURI(), ExceptionUtils.getStackTrace(e)); 117 | throw new HttpRuntimeException(e); 118 | } finally { 119 | request.releaseConnection(); 120 | } 121 | } 122 | 123 | protected void validateResponseStatus(HttpResponse response) throws UnexpectedHttpStatusException, IOException { 124 | int status = response.getStatusLine().getStatusCode(); 125 | if (status == 200) { 126 | return; 127 | } 128 | 129 | throw new UnexpectedHttpStatusException(status, 130 | String.format("the request failed, the status is:[%s], the response is:[%s]", 131 | response.getStatusLine(), 132 | IOUtils.toString(response.getEntity().getContent())) 133 | ); 134 | } 135 | 136 | protected class DelegateResponseHandler implements ResponseHandler { 137 | 138 | public DelegateResponseHandler(ResponseHandler delegate) { 139 | this.delegate = delegate; 140 | } 141 | 142 | private ResponseHandler delegate; 143 | 144 | @Override 145 | public T handleResponse(HttpResponse response) throws IOException { 146 | validateResponseStatus(response); 147 | return delegate.handleResponse(response); 148 | } 149 | } 150 | 151 | } -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/http/DefaultConnectionKeepAliveStrategy.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util.http; 2 | 3 | import org.apache.http.HeaderElement; 4 | import org.apache.http.HeaderElementIterator; 5 | import org.apache.http.HttpResponse; 6 | import org.apache.http.conn.ConnectionKeepAliveStrategy; 7 | import org.apache.http.message.BasicHeaderElementIterator; 8 | import org.apache.http.protocol.HTTP; 9 | import org.apache.http.protocol.HttpContext; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | 13 | public class DefaultConnectionKeepAliveStrategy implements ConnectionKeepAliveStrategy { 14 | 15 | public static final Logger LOGGER = LoggerFactory.getLogger(DefaultConnectionKeepAliveStrategy.class); 16 | 17 | public static final DefaultConnectionKeepAliveStrategy DEFAULT = new DefaultConnectionKeepAliveStrategy(); 18 | 19 | public static final String KEY_NAME = "timeout"; 20 | 21 | public static final long DEFAULT_TIMEOUT = 120 * 1000; 22 | 23 | @Override 24 | public long getKeepAliveDuration(HttpResponse response, HttpContext context) { 25 | if (response == null) { 26 | return DEFAULT_TIMEOUT; 27 | } 28 | 29 | final HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); 30 | while (it.hasNext()) { 31 | final HeaderElement he = it.nextElement(); 32 | final String param = he.getName(); 33 | final String value = he.getValue(); 34 | if (value != null && param.equalsIgnoreCase(KEY_NAME)) { 35 | try { 36 | return Long.parseLong(value) * 1000; 37 | } catch (final NumberFormatException ignore) { 38 | LOGGER.warn("invalid timeout value:[{}]", value); 39 | } 40 | } 41 | } 42 | 43 | return DEFAULT_TIMEOUT; 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/http/HttpHelper.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util.http; 2 | 3 | import java.io.IOException; 4 | import java.util.Map; 5 | import java.util.concurrent.TimeUnit; 6 | 7 | import org.apache.http.Consts; 8 | import org.apache.http.client.ClientProtocolException; 9 | import org.apache.http.client.HttpClient; 10 | import org.apache.http.client.ResponseHandler; 11 | import org.apache.http.config.ConnectionConfig; 12 | import org.apache.http.config.SocketConfig; 13 | import org.apache.http.conn.HttpClientConnectionManager; 14 | import org.apache.http.impl.client.HttpClientBuilder; 15 | import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; 16 | 17 | public final class HttpHelper extends AbstractHttpHelper { 18 | 19 | protected static HttpHelper instance = new HttpHelper(); 20 | 21 | public static HttpHelper get() { 22 | return instance; 23 | } 24 | 25 | private HttpHelper() { 26 | httpClient = HttpClientBuilder.create().setConnectionManager(getClientConnectionManager()) 27 | .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.DEFAULT) 28 | .addInterceptorFirst(GZIPRequestInterceptor.DEFAULT).addInterceptorLast(GZIPResponseInterceptor.DEFAULT) 29 | .build(); 30 | } 31 | 32 | protected HttpClient httpClient; 33 | 34 | protected HttpClient getHttpClient() { 35 | return this.httpClient; 36 | } 37 | 38 | protected HttpClientConnectionManager getClientConnectionManager() { 39 | PoolingHttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(5, 40 | TimeUnit.MINUTES); 41 | clientConnectionManager.setDefaultConnectionConfig( 42 | ConnectionConfig.custom().setBufferSize(4096).setCharset(Consts.UTF_8).build()); 43 | clientConnectionManager.setDefaultSocketConfig(SocketConfig.custom().build()); 44 | clientConnectionManager.setDefaultMaxPerRoute(Runtime.getRuntime().availableProcessors() * 1024); 45 | clientConnectionManager.setMaxTotal(Runtime.getRuntime().availableProcessors() * 1024); 46 | return clientConnectionManager; 47 | } 48 | 49 | /** 50 | * ********** post by parameters and handler ********** 51 | */ 52 | 53 | public T doPost(String url, Map parameters, ResponseHandler handler) { 54 | return super.doPost(url, parameters, handler); 55 | } 56 | 57 | public String doPost(String uri, Map parameters, String charset) { 58 | return super.doPost(uri, parameters, new ResponseToString(charset)); 59 | } 60 | 61 | public String doPost(String uri, Map parameters) { 62 | return super.doPost(uri, parameters, ResponseToString.DEFAULT); 63 | } 64 | 65 | /** 66 | * *********** post by body and handler ****************** 67 | */ 68 | 69 | public T doPost(String uri, String body, ResponseHandler handler) { 70 | return super.doPost(uri, body.getBytes(), handler); 71 | } 72 | 73 | public String doPost(String uri, String body, String charset) { 74 | return super.doPost(uri, body.getBytes(), new ResponseToString(charset)); 75 | } 76 | 77 | public String doPost(String uri, String body) { 78 | return super.doPost(uri, body.getBytes(), ResponseToString.DEFAULT); 79 | } 80 | 81 | /** 82 | * ****** get by url ******************* 83 | */ 84 | 85 | public T doGet(String url, ResponseHandler handler) { 86 | return super.doGet(url, handler); 87 | } 88 | 89 | public String doGet(String uri, String charset) { 90 | return super.doGet(uri, new ResponseToString(charset)); 91 | } 92 | 93 | public String doGet(String uri) { 94 | return super.doGet(uri, ResponseToString.DEFAULT); 95 | } 96 | 97 | public static void main(String[] args) throws ClientProtocolException, IOException { 98 | HttpHelper helper = HttpHelper.get(); 99 | String text = helper.doGet("http://www.baidu123.com"); 100 | System.out.println(text); 101 | // CloseableHttpClient httpClient = HttpClients.createDefault(); 102 | // HttpGet httpGet = new HttpGet("http://www.baidu.com"); 103 | // HttpResponse response = httpClient.execute(httpGet); 104 | // System.err.println(response.getStatusLine()); 105 | // HttpEntity entity = response.getEntity(); 106 | // if (entity != null) { 107 | // String text = EntityUtils.toString(entity); 108 | // EntityUtils.consume(entity); 109 | // System.out.println(text); 110 | // } 111 | 112 | } 113 | 114 | } 115 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/http/HttpRuntimeException.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util.http; 2 | 3 | public class HttpRuntimeException extends RuntimeException { 4 | 5 | /** 6 | * serialVersionUID 7 | */ 8 | private static final long serialVersionUID = 3058392373225533751L; 9 | 10 | /** 11 | * 12 | */ 13 | public HttpRuntimeException() { 14 | // TODO Auto-generated constructor stub 15 | } 16 | 17 | /** 18 | * @param message 19 | */ 20 | public HttpRuntimeException(String message) { 21 | super(message); 22 | // TODO Auto-generated constructor stub 23 | } 24 | 25 | /** 26 | * @param cause 27 | */ 28 | public HttpRuntimeException(Throwable cause) { 29 | super(cause); 30 | // TODO Auto-generated constructor stub 31 | } 32 | 33 | /** 34 | * @param message 35 | * @param cause 36 | */ 37 | public HttpRuntimeException(String message, Throwable cause) { 38 | super(message, cause); 39 | // TODO Auto-generated constructor stub 40 | } 41 | 42 | /** 43 | * @param message 44 | * @param cause 45 | * @param enableSuppression 46 | * @param writableStackTrace 47 | */ 48 | public HttpRuntimeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { 49 | super(message, cause, enableSuppression, writableStackTrace); 50 | // TODO Auto-generated constructor stub 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/http/RequestByBodyCreator.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util.http; 2 | 3 | import org.apache.http.client.config.RequestConfig; 4 | import org.apache.http.client.methods.HttpPost; 5 | import org.apache.http.client.methods.HttpRequestBase; 6 | import org.apache.http.entity.ByteArrayEntity; 7 | 8 | public class RequestByBodyCreator implements RequestCreator { 9 | 10 | public RequestByBodyCreator(String url, byte[] body) { 11 | this.url = url; 12 | this.body = body; 13 | } 14 | 15 | final String url; 16 | final byte[] body; 17 | 18 | @Override 19 | public HttpRequestBase create() throws Exception { 20 | HttpPost post = new HttpPost(url); 21 | post.setConfig(CONFIG); 22 | post.setEntity(new ByteArrayEntity(body)); 23 | return post; 24 | } 25 | 26 | public static void main(String[] args) { 27 | System.out.println(RequestConfig.DEFAULT); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/http/RequestByParametersCreator.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util.http; 2 | 3 | import org.apache.commons.lang3.StringUtils; 4 | import org.apache.http.Consts; 5 | import org.apache.http.NameValuePair; 6 | import org.apache.http.client.entity.UrlEncodedFormEntity; 7 | import org.apache.http.client.methods.HttpPost; 8 | import org.apache.http.client.methods.HttpRequestBase; 9 | import org.apache.http.message.BasicNameValuePair; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | import java.util.Map; 14 | 15 | public class RequestByParametersCreator implements RequestCreator { 16 | 17 | private static final String parameterValuesDelimiter = ","; 18 | 19 | public RequestByParametersCreator(String url, Map parameters) { 20 | this.url = url; 21 | this.parameters = parameters; 22 | } 23 | 24 | final String url; 25 | final Map parameters; 26 | 27 | @Override 28 | public HttpRequestBase create() throws Exception { 29 | HttpPost post = new HttpPost(url); 30 | post.setConfig(CONFIG); 31 | if (parameters != null) { 32 | List pairs = new ArrayList(); 33 | for (String name : parameters.keySet()) { 34 | Object value = parameters.get(name); 35 | 36 | if (value == null) { 37 | value = StringUtils.EMPTY; 38 | } 39 | 40 | if (value instanceof String[]) { 41 | String[] _values = (String[]) value; 42 | value = _values.length > 1 43 | ? StringUtils.join(value, parameterValuesDelimiter) 44 | : _values[0]; 45 | } 46 | 47 | pairs.add(new BasicNameValuePair(name, (String) value)); 48 | } 49 | post.setEntity(new UrlEncodedFormEntity(pairs, Consts.UTF_8)); 50 | } 51 | 52 | return post; 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/http/RequestByURLCreator.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util.http; 2 | 3 | import org.apache.http.client.methods.HttpGet; 4 | import org.apache.http.client.methods.HttpRequestBase; 5 | 6 | public class RequestByURLCreator implements RequestCreator { 7 | 8 | public RequestByURLCreator(String url) { 9 | this.url = url; 10 | } 11 | 12 | final String url; 13 | 14 | @Override 15 | public HttpRequestBase create() throws Exception { 16 | HttpGet get = new HttpGet(url); 17 | get.setConfig(CONFIG); 18 | return get; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/http/RequestCreator.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util.http; 2 | 3 | import org.apache.http.client.config.RequestConfig; 4 | import org.apache.http.client.methods.HttpRequestBase; 5 | 6 | public interface RequestCreator { 7 | 8 | static RequestConfig CONFIG = RequestConfig.custom() 9 | .setConnectionRequestTimeout(1000) 10 | .setConnectTimeout(1000 * 5) 11 | .setSocketTimeout(1000 * 30) 12 | .build(); 13 | 14 | HttpRequestBase create() throws Exception; 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/http/UnexpectedHttpStatusException.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util.http; 2 | 3 | public class UnexpectedHttpStatusException extends RuntimeException { 4 | 5 | private static final long serialVersionUID = -4664410630156843862L; 6 | 7 | public UnexpectedHttpStatusException() { 8 | super(); 9 | // TODO Auto-generated constructor stub 10 | } 11 | 12 | /** 13 | * @param message 14 | * @param cause 15 | * @param enableSuppression 16 | * @param writableStackTrace 17 | */ 18 | public UnexpectedHttpStatusException(String message, Throwable cause, boolean enableSuppression, 19 | boolean writableStackTrace) { 20 | super(message, cause, enableSuppression, writableStackTrace); 21 | // TODO Auto-generated constructor stub 22 | } 23 | 24 | /** 25 | * @param message 26 | * @param cause 27 | */ 28 | public UnexpectedHttpStatusException(String message, Throwable cause) { 29 | super(message, cause); 30 | // TODO Auto-generated constructor stub 31 | } 32 | 33 | /** 34 | * @param message 35 | */ 36 | public UnexpectedHttpStatusException(String message) { 37 | super(message); 38 | // TODO Auto-generated constructor stub 39 | } 40 | 41 | /** 42 | * @param cause 43 | */ 44 | public UnexpectedHttpStatusException(Throwable cause) { 45 | super(cause); 46 | // TODO Auto-generated constructor stub 47 | } 48 | 49 | public UnexpectedHttpStatusException(int status) { 50 | super(); 51 | this.status = status; 52 | } 53 | 54 | public UnexpectedHttpStatusException(int status, String message) { 55 | super(message); 56 | this.status = status; 57 | } 58 | 59 | private int status; 60 | 61 | public int getStatus() { 62 | return status; 63 | } 64 | 65 | public void setStatus(int status) { 66 | this.status = status; 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/lock/DistributedLock.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Title: 3 | * Description: 4 | * @author yangwenkui 5 | * @version v1.0 6 | * @time 2016年5月6日 上午10:52:58 7 | */ 8 | package com.onecoderspace.base.util.lock; 9 | 10 | /** 11 | * Title: 分布式锁接口 12 | * @author yangwenkui 13 | * @version v1.0 14 | * @time 2016年5月6日 上午10:52:58 15 | */ 16 | public interface DistributedLock { 17 | 18 | /** 19 | * 获取锁 20 | * @author yangwenkui 21 | * @time 2016年5月6日 上午11:02:54 22 | * @return 23 | * @throws InterruptedException 24 | */ 25 | public boolean acquire(); 26 | 27 | /** 28 | * 释放锁 29 | * @author yangwenkui 30 | * @time 2016年5月6日 上午11:02:59 31 | */ 32 | public void release(); 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/lock/DistributedLockUtil.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util.lock; 2 | 3 | import com.onecoderspace.base.util.lock.impl.JedisLock; 4 | 5 | /** 6 | * Title:分布式锁获取帮助类 7 | * @author yangwenkui 8 | * @version v1.0 9 | */ 10 | public class DistributedLockUtil{ 11 | 12 | /** 13 | * 获取分布式锁 14 | * 默认获取锁10s超时,锁过期时间60s 15 | * @author yangwenkui 16 | * @time 2016年5月6日 下午1:30:46 17 | * @return 18 | */ 19 | public static DistributedLock getDistributedLock(String lockKey){ 20 | lockKey = assembleKey(lockKey); 21 | JedisLock lock = new JedisLock(lockKey); 22 | return lock; 23 | } 24 | 25 | /** 26 | * 正式环境、测试环境共用一个redis时,避免key相同造成影响 27 | * @author yangwenkui 28 | * @param lockKey 29 | * @return 30 | */ 31 | private static String assembleKey(String lockKey) { 32 | return String.format("lock_%s",lockKey ); 33 | } 34 | 35 | /** 36 | * 获取分布式锁 37 | * 默认获取锁10s超时,锁过期时间60s 38 | * @author yangwenkui 39 | * @time 2016年5月6日 下午1:38:32 40 | * @param lockKey 41 | * @param timeoutMsecs 指定获取锁超时时间 42 | * @return 43 | */ 44 | public static DistributedLock getDistributedLock(String lockKey,int timeoutMsecs){ 45 | lockKey = assembleKey(lockKey); 46 | JedisLock lock = new JedisLock(lockKey,timeoutMsecs); 47 | return lock; 48 | } 49 | 50 | /** 51 | * 获取分布式锁 52 | * 默认获取锁10s超时,锁过期时间60s 53 | * @author yangwenkui 54 | * @time 2016年5月6日 下午1:40:04 55 | * @param lockKey 锁的key 56 | * @param timeoutMsecs 指定获取锁超时时间 57 | * @param expireMsecs 指定锁过期时间 58 | * @return 59 | */ 60 | public static DistributedLock getDistributedLock(String lockKey,int timeoutMsecs,int expireMsecs){ 61 | lockKey = assembleKey(lockKey); 62 | JedisLock lock = new JedisLock(lockKey,expireMsecs,timeoutMsecs); 63 | return lock; 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/lock/impl/JedisLock.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util.lock.impl; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.data.redis.core.StringRedisTemplate; 6 | 7 | import com.onecoderspace.base.util.SpringContextUtil; 8 | import com.onecoderspace.base.util.lock.DistributedLock; 9 | 10 | /** 11 | * Title:基于redis的分布式锁实现--互斥锁 12 | * @author yangwenkui 13 | * @version v1.0 14 | * @time 2016年5月6日 下午2:19:28 15 | */ 16 | public class JedisLock implements DistributedLock{ 17 | 18 | private static Logger logger = LoggerFactory.getLogger(JedisLock.class); 19 | 20 | private static StringRedisTemplate redisTemplate; 21 | 22 | /** 23 | * 分布式锁的键值 24 | */ 25 | String lockKey; //锁的键值 26 | int expireMsecs = 10 * 1000; //锁超时,防止线程在入锁以后,无限的执行等待 27 | int timeoutMsecs = 10 * 1000; //锁等待,防止线程饥饿 28 | boolean locked = false; //是否已经获取锁 29 | 30 | /** 31 | * 获取指定键值的锁 32 | * @param lockKey 锁的键值 33 | */ 34 | public JedisLock(String lockKey) { 35 | this.lockKey = lockKey; 36 | } 37 | 38 | /** 39 | * 获取指定键值的锁,同时设置获取锁超时时间 40 | * @param lockKey 锁的键值 41 | * @param timeoutMsecs 获取锁超时时间 42 | */ 43 | public JedisLock(String lockKey, int timeoutMsecs) { 44 | this.lockKey = lockKey; 45 | this.timeoutMsecs = timeoutMsecs; 46 | } 47 | 48 | /** 49 | * 获取指定键值的锁,同时设置获取锁超时时间和锁过期时间 50 | * @param lockKey 锁的键值 51 | * @param timeoutMsecs 获取锁超时时间 52 | * @param expireMsecs 锁失效时间 53 | */ 54 | public JedisLock(String lockKey, int timeoutMsecs, int expireMsecs) { 55 | this.lockKey = lockKey; 56 | this.timeoutMsecs = timeoutMsecs; 57 | this.expireMsecs = expireMsecs; 58 | } 59 | 60 | public String getLockKey() { 61 | return lockKey; 62 | } 63 | 64 | /** 65 | * 66 | * @return true if lock is acquired, false acquire timeouted 67 | * @throws InterruptedException 68 | * in case of thread interruption 69 | */ 70 | public synchronized boolean acquire() { 71 | int timeout = timeoutMsecs; 72 | if(redisTemplate == null){ 73 | redisTemplate = SpringContextUtil.getBean(StringRedisTemplate.class); 74 | } 75 | try { 76 | while (timeout >= 0) { 77 | long expires = System.currentTimeMillis() + expireMsecs + 1; 78 | String expiresStr = String.valueOf(expires); //锁到期时间 79 | 80 | if (redisTemplate.opsForValue().setIfAbsent(lockKey, expiresStr)) { 81 | // lock acquired 82 | locked = true; 83 | return true; 84 | } 85 | 86 | String currentValueStr = redisTemplate.opsForValue().get(lockKey); //redis里的时间 87 | if (currentValueStr != null && Long.parseLong(currentValueStr) < System.currentTimeMillis()) { 88 | //判断是否为空,不为空的情况下,如果被其他线程设置了值,则第二个条件判断是过不去的 89 | // lock is expired 90 | 91 | String oldValueStr = redisTemplate.opsForValue().getAndSet(lockKey, expiresStr); 92 | //获取上一个锁到期时间,并设置现在的锁到期时间, 93 | //只有一个线程才能获取上一个线上的设置时间,因为jedis.getSet是同步的 94 | if (oldValueStr != null && oldValueStr.equals(currentValueStr)) { 95 | //如过这个时候,多个线程恰好都到了这里,但是只有一个线程的设置值和当前值相同,他才有权利获取锁 96 | // lock acquired 97 | locked = true; 98 | return true; 99 | } 100 | } 101 | timeout -= 100; 102 | Thread.sleep(100); 103 | } 104 | } catch (Exception e) { 105 | logger.error("release lock due to error",e); 106 | } 107 | return false; 108 | } 109 | 110 | /** 111 | * 释放锁 112 | */ 113 | public synchronized void release() { 114 | if(redisTemplate == null){ 115 | redisTemplate = SpringContextUtil.getBean(StringRedisTemplate.class); 116 | } 117 | try { 118 | if (locked) { 119 | String currentValueStr = redisTemplate.opsForValue().get(lockKey); //redis里的时间 120 | //校验是否超过有效期,如果不在有效期内,那说明当前锁已经失效,不能进行删除锁操作 121 | if (currentValueStr != null && Long.parseLong(currentValueStr) > System.currentTimeMillis()) { 122 | redisTemplate.delete(lockKey); 123 | locked = false; 124 | } 125 | } 126 | } catch (Exception e) { 127 | logger.error("release lock due to error",e); 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/ognl/OgnlWrapper.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util.ognl; 2 | 3 | import java.util.Map; 4 | 5 | import org.apache.commons.lang3.Validate; 6 | import org.codehaus.jackson.map.ObjectMapper; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | 10 | import com.onecoderspace.base.util.JacksonHelper; 11 | 12 | import ognl.Ognl; 13 | import ognl.OgnlException; 14 | 15 | @SuppressWarnings("unchecked") 16 | public class OgnlWrapper { 17 | 18 | private static Logger logger = LoggerFactory.getLogger(OgnlWrapper.class); 19 | 20 | private static ObjectMapper om = new ObjectMapper(); 21 | private Map payload; 22 | 23 | public OgnlWrapper(Map playload) { 24 | Validate.notEmpty(playload, "can not construct with none playload!"); 25 | this.payload = playload; 26 | } 27 | 28 | 29 | public OgnlWrapper(Object playload) { 30 | this.payload = om.convertValue(playload, Map.class); 31 | } 32 | 33 | public T get(String expression) { 34 | try { 35 | return (T) Ognl.getValue(expression, this.payload); 36 | } catch (OgnlException e) { 37 | logger.trace(String.format("get value with expression:[%s] due to error, return null instead of", 38 | expression), e); 39 | return null; 40 | } 41 | } 42 | 43 | public Long getLong(String expression) { 44 | try { 45 | Object obj = Ognl.getValue(expression, this.payload); 46 | if (null == obj) 47 | return null; 48 | try { 49 | return Long.parseLong(obj.toString()); 50 | } catch (NumberFormatException nfe) { 51 | logger.warn(String.format("get value with expression:[%s] due to error, return null. value[%s] cannot be cast to java.lang.Long", 52 | expression, 53 | obj.toString())); 54 | return null; 55 | } 56 | } catch (OgnlException e) { 57 | logger.trace(String.format("get value with expression:[%s] due to error, return null instead of", 58 | expression), e); 59 | return null; 60 | } 61 | } 62 | 63 | public Integer getInt(String expression) { 64 | try { 65 | Object obj = Ognl.getValue(expression, this.payload); 66 | if (null == obj) 67 | return null; 68 | try { 69 | return Integer.parseInt(obj.toString()); 70 | } catch (NumberFormatException nfe) { 71 | logger.warn(String.format("get value with expression:[%s] due to error, return null. value[%s] cannot be cast to java.lang.Integer", 72 | expression, 73 | obj.toString())); 74 | return null; 75 | } 76 | } catch (OgnlException e) { 77 | logger.trace(String.format("get value with expression:[%s] due to error, return null instead of", 78 | expression), e); 79 | return null; 80 | } 81 | } 82 | 83 | @Override 84 | public String toString() { 85 | return String.format("OgnlWrapper[%s]", this.payload.toString()); 86 | } 87 | 88 | public static void main(String[] args) { 89 | String json = "{\"user\":{\"name\":\"123\"}}"; 90 | Map map = JacksonHelper.fromJson(json, Map.class); 91 | OgnlWrapper ognlWrapper = new OgnlWrapper(map); 92 | System.err.println(ognlWrapper.get("user.name")); 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/redis/RedisBlockingQueue.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util.redis; 2 | 3 | import java.util.Collection; 4 | import java.util.Iterator; 5 | import java.util.concurrent.BlockingQueue; 6 | import java.util.concurrent.TimeUnit; 7 | 8 | import org.apache.commons.lang3.Validate; 9 | import org.springframework.data.redis.core.StringRedisTemplate; 10 | 11 | import com.onecoderspace.base.util.SpringContextUtil; 12 | 13 | /** 14 | * redis的list为双向链表,使用左出右进的策略构建一个queue 15 | * 16 | */ 17 | public class RedisBlockingQueue implements BlockingQueue { 18 | 19 | public static RedisBlockingQueue get(String queueName){ 20 | return new RedisBlockingQueue(queueName); 21 | } 22 | 23 | public RedisBlockingQueue(String queueName) { 24 | this.queueName = queueName; 25 | synchronized (RedisBlockingQueue.class) { 26 | if(redisTemplate == null){ 27 | redisTemplate = SpringContextUtil.getBean(StringRedisTemplate.class); 28 | } 29 | } 30 | } 31 | 32 | private String queueName; 33 | 34 | private static StringRedisTemplate redisTemplate; 35 | 36 | @Override 37 | public String remove() { 38 | String r = this.poll(); 39 | Validate.notNull(r); 40 | return r; 41 | } 42 | 43 | @Override 44 | public String poll() { 45 | return redisTemplate.opsForList().leftPop(queueName); 46 | } 47 | 48 | @Override 49 | public String element() { 50 | String r = this.peek(); 51 | Validate.notNull(r); 52 | return r; 53 | } 54 | 55 | @Override 56 | public String peek() { 57 | return redisTemplate.opsForList().index(queueName, 0); 58 | } 59 | 60 | @Override 61 | public int size() { 62 | long size = redisTemplate.opsForList().size(queueName); 63 | return (int)size; 64 | } 65 | 66 | @Override 67 | public boolean isEmpty() { 68 | return this.size() == 0; 69 | } 70 | 71 | @Override 72 | public Iterator iterator() { 73 | throw new RuntimeException("Redis queue not support iterator method"); 74 | } 75 | 76 | @Override 77 | public Object[] toArray() { 78 | return redisTemplate.opsForList().range(queueName, 0, -1).toArray(); 79 | } 80 | 81 | @Override 82 | public T[] toArray(T[] a) { 83 | throw new RuntimeException("Redis queue not support toArray method"); 84 | } 85 | 86 | @Override 87 | public boolean containsAll(Collection c) { 88 | throw new RuntimeException("Redis queue not support containsAll method"); 89 | } 90 | 91 | @Override 92 | public boolean addAll(Collection c) { 93 | throw new RuntimeException("Redis queue not support addAll method"); 94 | } 95 | 96 | @Override 97 | public boolean removeAll(Collection c) { 98 | throw new RuntimeException("Redis queue not support removeAll method"); 99 | } 100 | 101 | @Override 102 | public boolean retainAll(Collection c) { 103 | throw new RuntimeException("Redis queue not support retainAll method"); 104 | } 105 | 106 | @Override 107 | public void clear() { 108 | redisTemplate.expire(queueName, 1L, TimeUnit.SECONDS); 109 | } 110 | 111 | @Override 112 | public boolean add(final String e) { 113 | long length = redisTemplate.opsForList().rightPush(queueName, e); 114 | return length > 0; 115 | } 116 | 117 | @Override 118 | public boolean offer(String e) { 119 | return this.add(e); 120 | } 121 | 122 | @Override 123 | public void put(String e) throws InterruptedException { 124 | this.add(e); 125 | } 126 | 127 | @Override 128 | public boolean offer(String e, long timeout, TimeUnit unit) throws InterruptedException { 129 | return this.add(e); 130 | } 131 | 132 | @Override 133 | public String take() throws InterruptedException { 134 | return redisTemplate.opsForList().leftPop(queueName, Integer.MAX_VALUE, TimeUnit.SECONDS); 135 | } 136 | 137 | @Override 138 | public String poll(final long timeout, final TimeUnit unit) throws InterruptedException { 139 | return redisTemplate.opsForList().leftPop(queueName, timeout, unit); 140 | } 141 | 142 | @Override 143 | public int remainingCapacity() { 144 | throw new RuntimeException("Redis queue not support remainingCapacity method"); 145 | } 146 | 147 | @Override 148 | public boolean remove(final Object value) { 149 | long count = redisTemplate.opsForList().remove(queueName, 0, value); 150 | return count > 0; 151 | } 152 | 153 | @Override 154 | public boolean contains(Object o) { 155 | throw new RuntimeException("Redis queue not support contains method"); 156 | } 157 | 158 | @Override 159 | public int drainTo(Collection c) { 160 | throw new RuntimeException("Redis queue not support drainTo method"); 161 | } 162 | 163 | @Override 164 | public int drainTo(Collection c, int maxElements) { 165 | throw new RuntimeException("Redis queue not support drainTo method"); 166 | } 167 | 168 | } 169 | -------------------------------------------------------------------------------- /src/main/java/com/onecoderspace/base/util/security/xss/JsoupUtil.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base.util.security.xss; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.io.IOException; 5 | 6 | import org.jsoup.Jsoup; 7 | import org.jsoup.nodes.Document; 8 | import org.jsoup.safety.Whitelist; 9 | 10 | /** 11 | * xss非法标签过滤 12 | * {@link http://www.jianshu.com/p/32abc12a175a?nomobile=yes} 13 | * @author yangwenkui 14 | * @version v2.0 15 | * @time 2017年4月27日 下午5:47:09 16 | */ 17 | public class JsoupUtil { 18 | 19 | /** 20 | * 使用自带的basicWithImages 白名单 21 | * 允许的便签有a,b,blockquote,br,cite,code,dd,dl,dt,em,i,li,ol,p,pre,q,small,span, 22 | * strike,strong,sub,sup,u,ul,img 23 | * 以及a标签的href,img标签的src,align,alt,height,width,title属性 24 | */ 25 | private static final Whitelist whitelist = Whitelist.basicWithImages(); 26 | /** 配置过滤化参数,不对代码进行格式化 */ 27 | private static final Document.OutputSettings outputSettings = new Document.OutputSettings().prettyPrint(false); 28 | static { 29 | // 富文本编辑时一些样式是使用style来进行实现的 30 | // 比如红色字体 style="color:red;" 31 | // 所以需要给所有标签添加style属性 32 | whitelist.addAttributes(":all", "style"); 33 | } 34 | 35 | public static String clean(String content) { 36 | return Jsoup.clean(content, "", whitelist, outputSettings); 37 | } 38 | 39 | public static void main(String[] args) throws FileNotFoundException, IOException { 40 | String text = "ssssss"; 41 | System.out.println(clean(text)); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/resources/application-dev.properties: -------------------------------------------------------------------------------- 1 | 2 | #上传文件存储目录 3 | upload.file.path=/var/www/html/upload 4 | 5 | #是否开启csrf过滤 6 | csrf.filter.open=false 7 | 8 | # Show or not log for each sql query 9 | spring.jpa.show-sql = true 10 | 11 | ######################################################## 12 | ###datasource 13 | ######################################################## 14 | spring.datasource.url=jdbc:mysql://xxx:3306/base?characterEncoding=utf8 15 | spring.datasource.username=base 16 | spring.datasource.password=base 17 | spring.datasource.driverClassName=com.mysql.jdbc.Driver 18 | spring.datasource.max-active=5 19 | spring.datasource.max-idle=1 20 | spring.datasource.min-idle=1 21 | spring.datasource.initial-size=1 22 | 23 | ###redis配置### 24 | spring.redis.database=0 25 | spring.redis.password=pwd 26 | 27 | # pool settings ...池配置 28 | spring.redis.pool.max-idle=4 29 | spring.redis.pool.min-idle=1 30 | spring.redis.pool.max-active=4 31 | spring.redis.pool.max-wait=2000 32 | 33 | #哨兵监听redis server名称 34 | spring.redis.sentinel.master=mymaster 35 | #哨兵的配置列表 36 | spring.redis.sentinel.nodes=host:port,host2:port2 37 | -------------------------------------------------------------------------------- /src/main/resources/application-local.properties: -------------------------------------------------------------------------------- 1 | #debug=false 2 | #logging.level.org.springframework.transaction=trace 3 | 4 | #上传文件存储目录 5 | upload.file.path=D:/workspace/rest-base 6 | 7 | #是否开启csrf过滤 8 | csrf.filter.open=false 9 | 10 | # Show or not log for each sql query 11 | spring.jpa.show-sql = true 12 | 13 | ######################################################## 14 | ###datasource 15 | ######################################################## 16 | spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8 17 | spring.datasource.username=root 18 | spring.datasource.password=root 19 | spring.datasource.driverClassName=com.mysql.jdbc.Driver 20 | spring.datasource.max-active=3 21 | spring.datasource.max-idle=1 22 | spring.datasource.min-idle=1 23 | spring.datasource.initial-size=1 24 | 25 | ###redis配置### 26 | spring.redis.host=127.0.0.1 27 | spring.redis.port=6379 28 | spring.redis.database=0 29 | spring.redis.password=test!@#$% 30 | 31 | # pool settings ...池配置 32 | spring.redis.pool.max-idle=4 33 | spring.redis.pool.min-idle=1 34 | spring.redis.pool.max-active=4 35 | spring.redis.pool.max-wait=2000 36 | -------------------------------------------------------------------------------- /src/main/resources/application-prod.properties: -------------------------------------------------------------------------------- 1 | 2 | #上传文件存储目录 3 | upload.file.path=/var/www/html/upload 4 | 5 | #是否开启csrf过滤 6 | csrf.filter.open=true 7 | 8 | # Show or not log for each sql query 9 | spring.jpa.show-sql = false 10 | 11 | ######################################################## 12 | ###datasource 13 | ######################################################## 14 | spring.datasource.url=jdbc:mysql://xxx:3306/base?characterEncoding=utf8 15 | spring.datasource.username=base 16 | spring.datasource.password=base 17 | spring.datasource.driverClassName=com.mysql.jdbc.Driver 18 | spring.datasource.max-active=40 19 | spring.datasource.max-idle=5 20 | spring.datasource.min-idle=5 21 | spring.datasource.initial-size=5 22 | 23 | ###redis配置### 24 | spring.redis.database=0 25 | spring.redis.password=pwd 26 | 27 | # pool settings ...池配置 28 | spring.redis.pool.max-idle=5 29 | spring.redis.pool.min-idle=5 30 | spring.redis.pool.max-active=20 31 | spring.redis.pool.max-wait=2000 32 | 33 | #哨兵监听redis server名称 34 | spring.redis.sentinel.master=mymaster 35 | #哨兵的配置列表 36 | spring.redis.sentinel.nodes=host:port,host2:port2 -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.profiles.active=local 2 | 3 | #文件上传的项目名称 4 | upload.file.path.project.name=base 5 | 6 | server.port=8070 7 | server.context-path=/ 8 | ##Session timeout in seconds 9 | server.session.timeout=7200 10 | 11 | spring.mvc.favicon.enabled = false 12 | 13 | ######################################################## 14 | ### Java Persistence Api 15 | ######################################################## 16 | # Specify the DBMS 17 | spring.jpa.database = MYSQL 18 | # Hibernate ddl auto (create, create-drop, update) 19 | spring.jpa.hibernate.ddl-auto = update 20 | # Naming strategy 21 | spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy 22 | # stripped before adding them to the entity manager) 23 | spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect 24 | 25 | spring.metrics.export.redis.prefix: metrics.evaluation 26 | spring.metrics.export.redis.key: keys.metrics.evaluation 27 | -------------------------------------------------------------------------------- /src/main/resources/ehcache-shiro.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 26 | 35 | 36 | 37 | 38 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /src/main/resources/logback-spring.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | %d{yyyy-MM-dd HH:mm:ssS} %5p [%c]:%L-%m%n 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | ${LOG_PATH}/rest-base/rest-base_dev.log 20 | true 21 | 22 | %d{yyyy-MM-dd HH:mm:ssS} %5p [%c{5}#%M]:%L-%m%n%caller{0} 23 | 24 | false 25 | 26 | 27 | ${LOG_PATH}/rest-base/rest-base_dev.%d{yyyy-MM-dd}.log.gz 28 | 29 | 30 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | ${LOG_PATH}/rest-base/rest-base.log 38 | true 39 | 40 | %d{yyyy-MM-dd HH:mm:ssS} %5p [%c{5}#%M]:%L-%m%n%caller{0} 41 | 42 | false 43 | 44 | 45 | ${LOG_PATH}/rest-base/rest-base.%d{yyyy-MM-dd}.log.gz 46 | 47 | 30 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /src/test/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/q7322068/rest-base/43c2f4469008360c531b53d9d121ff2d5a1cef0e/src/test/.DS_Store -------------------------------------------------------------------------------- /src/test/java/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/q7322068/rest-base/43c2f4469008360c531b53d9d121ff2d5a1cef0e/src/test/java/.DS_Store -------------------------------------------------------------------------------- /src/test/java/com/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/q7322068/rest-base/43c2f4469008360c531b53d9d121ff2d5a1cef0e/src/test/java/com/.DS_Store -------------------------------------------------------------------------------- /src/test/java/com/onecoderspace/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/q7322068/rest-base/43c2f4469008360c531b53d9d121ff2d5a1cef0e/src/test/java/com/onecoderspace/.DS_Store -------------------------------------------------------------------------------- /src/test/java/com/onecoderspace/base/OrderService2Test.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base; 2 | 3 | import org.junit.FixMethodOrder; 4 | import org.junit.Test; 5 | import org.junit.experimental.categories.Category; 6 | import org.junit.runner.RunWith; 7 | import org.junit.runners.MethodSorters; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 10 | 11 | @RunWith(SpringJUnit4ClassRunner.class) 12 | @SpringBootTest(classes=BaseApplication.class) 13 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 14 | public class OrderService2Test { 15 | 16 | @Category(UnifiedOrderTaskTests.class) 17 | @Test 18 | public void testInsert(){ 19 | System.err.println("OrderService2 test insert"); 20 | } 21 | 22 | @Test 23 | public void testQuery(){ 24 | System.err.println("OrderService2 test query"); 25 | } 26 | 27 | @Category(UnifiedOrderTaskTests.class) 28 | @Test 29 | public void testQuery2(){ 30 | System.err.println("OrderService2 test query 2"); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/onecoderspace/base/OrderServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base; 2 | 3 | import org.junit.FixMethodOrder; 4 | import org.junit.Test; 5 | import org.junit.experimental.categories.Category; 6 | import org.junit.runner.RunWith; 7 | import org.junit.runners.MethodSorters; 8 | import org.springframework.boot.test.context.SpringBootTest; 9 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 10 | 11 | @RunWith(SpringJUnit4ClassRunner.class) 12 | @SpringBootTest(classes=BaseApplication.class) 13 | @FixMethodOrder(MethodSorters.NAME_ASCENDING) 14 | public class OrderServiceTest { 15 | 16 | @Category(UnifiedOrderTaskTests.class) 17 | @Test 18 | public void testInsert(){ 19 | System.err.println("test insert"); 20 | } 21 | 22 | @Category(UnifiedOrderTaskTests.class) 23 | @Test 24 | public void testQuery(){ 25 | System.err.println("test query"); 26 | } 27 | 28 | @Test 29 | public void testQuery2(){ 30 | System.err.println("test query 2"); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/onecoderspace/base/OrderServiceTestSuit.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base; 2 | 3 | import org.junit.experimental.categories.Categories; 4 | import org.junit.experimental.categories.Categories.ExcludeCategory; 5 | import org.junit.experimental.categories.Category; 6 | import org.junit.runner.RunWith; 7 | import org.junit.runners.Suite; 8 | 9 | /** 10 | * Created by wenkuiyang on 2017/11/17. 11 | */ 12 | @RunWith(Categories.class) 13 | @Suite.SuiteClasses({OrderServiceTest.class,OrderService2Test.class}) 14 | //@Categories.IncludeCategory(UnifiedOrderTaskTests.class) 15 | @ExcludeCategory(UnifiedOrderTaskTests.class) 16 | public class OrderServiceTestSuit { 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/com/onecoderspace/base/StringRedisTemplateServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base; 2 | 3 | import java.util.List; 4 | import java.util.Set; 5 | import java.util.concurrent.TimeUnit; 6 | 7 | import org.junit.Assert; 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.data.redis.core.RedisTemplate; 13 | import org.springframework.data.redis.core.StringRedisTemplate; 14 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 15 | 16 | import com.onecoderspace.base.domain.Role; 17 | import com.onecoderspace.base.domain.User; 18 | import com.onecoderspace.base.util.JacksonHelper; 19 | 20 | @RunWith(SpringJUnit4ClassRunner.class) 21 | @SpringBootTest(classes=BaseApplication.class) 22 | public class StringRedisTemplateServiceTest { 23 | 24 | @Test 25 | public void test(){ 26 | //设置缓存,建议每个键都设置过期时间 27 | redisTemplate.opsForValue().set("test", "test", 10, TimeUnit.SECONDS); 28 | Assert.assertEquals(redisTemplate.opsForValue().get("test"), "test"); 29 | 30 | redisTemplate.delete("test");//删除某个键 31 | 32 | //操作set 33 | redisTemplate.opsForSet().add("testSet", "1"); 34 | redisTemplate.opsForSet().add("testSet", "2"); 35 | redisTemplate.opsForSet().add("testSet", "3"); 36 | Set members = redisTemplate.opsForSet().members("testSet");//获取set内的所有值 37 | for (String string : members) { 38 | System.err.println(string); 39 | } 40 | redisTemplate.opsForSet().remove("testSet", "1","2");//移除set内的多个对象 41 | 42 | System.err.println("-----------"); 43 | 44 | //操作list 45 | redisTemplate.opsForList().rightPush("testList", "1"); 46 | redisTemplate.opsForList().rightPush("testList", "2"); 47 | redisTemplate.opsForList().rightPush("testList", "3"); 48 | List list = redisTemplate.opsForList().range("testList", 0, -1); 49 | for (String string : list) { 50 | System.err.println(string); 51 | } 52 | 53 | User user = new User(); 54 | user.setId(1); 55 | user.setName("test"); 56 | objRedisTemplate.opsForValue().set("user", user,10,TimeUnit.SECONDS); 57 | user = (User) objRedisTemplate.opsForValue().get("user"); 58 | System.err.println(JacksonHelper.toJson(user)); 59 | 60 | Role role = new Role(); 61 | role.setId(1); 62 | role.setName("role"); 63 | objRedisTemplate.opsForValue().set("role", role,10,TimeUnit.SECONDS); 64 | role = (Role) objRedisTemplate.opsForValue().get("role"); 65 | System.err.println(JacksonHelper.toJson(role)); 66 | } 67 | 68 | @Autowired 69 | private StringRedisTemplate redisTemplate; 70 | 71 | @Autowired 72 | private RedisTemplate objRedisTemplate; 73 | 74 | } 75 | 76 | -------------------------------------------------------------------------------- /src/test/java/com/onecoderspace/base/UnifiedOrderTaskTests.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base; 2 | 3 | /** 4 | * 单元测试分类标记,用于标记统一订单改造相关方法 5 | * 6 | * Created by wenkuiyang on 2017/11/17. 7 | */ 8 | public interface UnifiedOrderTaskTests { 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/test/java/com/onecoderspace/base/UserServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.onecoderspace.base; 2 | 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.data.domain.Page; 11 | import org.springframework.data.domain.PageRequest; 12 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 13 | 14 | import com.google.common.collect.Maps; 15 | import com.onecoderspace.base.BaseApplication; 16 | import com.onecoderspace.base.domain.User; 17 | import com.onecoderspace.base.service.UserService; 18 | import com.onecoderspace.base.util.JacksonHelper; 19 | 20 | @RunWith(SpringJUnit4ClassRunner.class) 21 | @SpringBootTest(classes=BaseApplication.class) 22 | public class UserServiceTest { 23 | 24 | @Test 25 | public void listByPage(){ 26 | Map params = Maps.newHashMap(); 27 | params.put("type", "0"); 28 | params.put("status", "1"); 29 | params.put("username", "te"); 30 | params.put("name", ""); 31 | Page page = userService.listByPage(params, new PageRequest(0, 10)); 32 | System.err.println(JacksonHelper.toJson(page)); 33 | 34 | List list = userService.findAll(); 35 | System.err.println(JacksonHelper.toJson(list)); 36 | 37 | Map params2 = Maps.newHashMap(); 38 | params2.put("type", "0"); 39 | params2.put("status", ""); 40 | params2.put("username:like", "te"); 41 | params2.put("name:like", ""); 42 | 43 | list = userService.list(params2); 44 | System.err.println(JacksonHelper.toJson(list)); 45 | 46 | page = userService.list(params2, new PageRequest(0, 10)); 47 | System.err.println(JacksonHelper.toJson(page)); 48 | 49 | } 50 | 51 | @Autowired 52 | private UserService userService; 53 | 54 | } 55 | --------------------------------------------------------------------------------