diff --git a/README.md b/README.md index bee171d..6796675 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ forest([ˈfôrəst],n.森林)是一款现代化的知识社区项目,使 ## ⚡ 动机 -在 2019 年的某一天,受到 [Hugh](https://rymcu.com/user/Hugh) 的邀请, 构建一个开源嵌入式知识学习交流平台。因此就有了 forest 这个项目。 forest +在 2019 年的某一天,受到 [Hugh](https://rymcu.com/user/RYMCU-J) 的邀请, 构建一个开源嵌入式知识学习交流平台。因此就有了 forest 这个项目。 forest 在很多方面受到了 [Symphony](https://github.com/88250/symphony) 的启发,并尝试着在 [Symphony](https://github.com/88250/symphony) 和 [B3log 思想](https://ld246.com/article/1546941897596) 的基础上进一步探索。 @@ -96,4 +96,10 @@ forest([ˈfôrəst],n.森林)是一款现代化的知识社区项目,使 ## 鸣谢 - 感谢 `JetBrains` 对本项目的帮助,为作者提供了开源许可版 `JetBrains` 全家桶 -![JetBrains](src/main/resources/static/jetbrains.png) + +![JetBrains](src/main/resources/static/jb_beam.svg) + + +## ⭐ Star 历史 + +[![Stargazers over time](https://starchart.cc/rymcu/forest.svg)](https://starchart.cc/rymcu/forest) diff --git a/pom.xml b/pom.xml index 336080b..78ce411 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.springframework.boot spring-boot-starter-parent - 2.3.5.RELEASE + 2.7.2 com.rymcu @@ -17,7 +17,7 @@ 1.8 - 8.11.1 + 8.11.2 @@ -40,6 +40,7 @@ org.springframework.boot spring-boot-starter-web + org.mybatis.spring.boot mybatis-spring-boot-starter @@ -49,6 +50,7 @@ mysql mysql-connector-java + 8.0.30 runtime @@ -74,8 +76,19 @@ com.vaadin.external.google android-json + + net.minidev + json-smart + + + + net.minidev + json-smart + 2.4.8 + + org.springframework.boot spring-boot-starter-aop @@ -84,43 +97,37 @@ tk.mybatis mapper - 4.1.5 - - - net.sourceforge.jtds - jtds - 1.3.1 + 4.2.1 com.github.pagehelper pagehelper - 5.3.0 + 5.3.1 com.alibaba fastjson - 1.2.83 + 2.0.12 org.apache.shiro shiro-spring - 1.7.1 - - - - org.crazycake - shiro-redis - 3.2.3 + 1.9.1 - org.apache.shiro - shiro-core + commons-collections + commons-collections + + org.apache.commons + commons-collections4 + 4.4 + commons-lang @@ -151,7 +158,7 @@ com.alibaba druid-spring-boot-starter - 1.2.8 + 1.2.11 org.apache.logging.log4j @@ -163,7 +170,7 @@ org.apache.logging.log4j log4j-to-slf4j - 2.17.1 + 2.18.0 org.apache.logging.log4j @@ -174,7 +181,7 @@ org.apache.logging.log4j log4j-api - 2.17.1 + 2.18.0 org.springframework.boot @@ -185,11 +192,6 @@ org.springframework.boot spring-boot-starter-thymeleaf - - net.sourceforge.nekohtml - nekohtml - 1.9.22 - org.springframework.boot spring-boot-starter-websocket @@ -197,26 +199,7 @@ org.jodd jodd-http - 6.2.1 - - - com.github.binarywang - weixin-java-open - 4.2.5.B - - - commons-codec - commons-codec - - - commons-io - commons-io - - - com.thoughtworks.xstream - xstream - - + 6.3.0 com.thoughtworks.xstream @@ -228,21 +211,6 @@ jedis-lock 1.0.0 - - com.baidu.aip - java-sdk - 4.16.5 - - - org.slf4j - slf4j-simple - - - com.google.guava - guava - - - @@ -273,12 +241,12 @@ cn.hutool hutool-core - 5.7.20 + 5.8.5 cn.hutool hutool-http - 5.7.20 + 5.8.5 @@ -292,8 +260,6 @@ - - diff --git a/src/main/java/com/rymcu/forest/ForestApplication.java b/src/main/java/com/rymcu/forest/ForestApplication.java index 6279091..2ec75e9 100644 --- a/src/main/java/com/rymcu/forest/ForestApplication.java +++ b/src/main/java/com/rymcu/forest/ForestApplication.java @@ -2,10 +2,12 @@ package com.rymcu.forest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.scheduling.annotation.EnableAsync; /** * @author ronger */ +@EnableAsync @SpringBootApplication public class ForestApplication { diff --git a/src/main/java/com/rymcu/forest/config/BaseExceptionHandler.java b/src/main/java/com/rymcu/forest/config/BaseExceptionHandler.java index 632a1ad..73b0279 100644 --- a/src/main/java/com/rymcu/forest/config/BaseExceptionHandler.java +++ b/src/main/java/com/rymcu/forest/config/BaseExceptionHandler.java @@ -1,6 +1,7 @@ package com.rymcu.forest.config; import com.alibaba.fastjson.support.spring.FastJsonJsonView; +import com.rymcu.forest.core.exception.BusinessException; import com.rymcu.forest.core.exception.ServiceException; import com.rymcu.forest.core.exception.TransactionException; import com.rymcu.forest.core.result.GlobalResult; @@ -62,6 +63,9 @@ public class BaseExceptionHandler { } else if (ex instanceof ServletException) { result.setCode(ResultCode.FAIL.getCode()); result.setMessage(ex.getMessage()); + } else if (ex instanceof BusinessException) { + result.setCode(ResultCode.FAIL.getCode()); + result.setMessage(ex.getMessage()); } else if (ex instanceof TransactionException) { result.setCode(TransactionCode.InsufficientBalance.getCode()); result.setMessage(ex.getMessage()); @@ -108,6 +112,9 @@ public class BaseExceptionHandler { } else if (ex instanceof ServletException) { attributes.put("code", ResultCode.FAIL.getCode()); attributes.put("message", ex.getMessage()); + } else if (ex instanceof BusinessException) { + attributes.put("code", ResultCode.FAIL.getCode()); + attributes.put("message", ex.getMessage()); } else if (ex instanceof TransactionException) { attributes.put("code", TransactionCode.InsufficientBalance.getCode()); attributes.put("message", ex.getMessage()); diff --git a/src/main/java/com/rymcu/forest/config/BaseShiroRealm.java b/src/main/java/com/rymcu/forest/config/BaseShiroRealm.java index bdd6323..2ddf682 100644 --- a/src/main/java/com/rymcu/forest/config/BaseShiroRealm.java +++ b/src/main/java/com/rymcu/forest/config/BaseShiroRealm.java @@ -1,5 +1,6 @@ package com.rymcu.forest.config; +import com.fasterxml.jackson.annotation.JsonFormat; import com.rymcu.forest.core.constant.ShiroConstants; import com.rymcu.forest.core.exception.CaptchaException; import com.rymcu.forest.entity.Permission; @@ -106,7 +107,8 @@ public class BaseShiroRealm extends AuthorizingRealm { private static final long serialVersionUID = 1L; - private Integer id; // 编号 + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long id; // 编号 private String account; // 登录名 private String name; // 姓名 private boolean mobileLogin; // 是否手机登录 @@ -120,7 +122,7 @@ public class BaseShiroRealm extends AuthorizingRealm { this.mobileLogin = mobileLogin; } - public Integer getId() { + public Long getId() { return id; } diff --git a/src/main/java/com/rymcu/forest/config/MybatisConfigurer.java b/src/main/java/com/rymcu/forest/config/MybatisConfigurer.java index 9aa708d..73aede7 100644 --- a/src/main/java/com/rymcu/forest/config/MybatisConfigurer.java +++ b/src/main/java/com/rymcu/forest/config/MybatisConfigurer.java @@ -40,12 +40,11 @@ public class MybatisConfigurer { pageHelper.setProperties(properties); //添加插件 - factory.setPlugins(new Interceptor[]{pageHelper}); + factory.setPlugins(pageHelper); //添加XML目录 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); factory.setMapperLocations(resolver.getResources("classpath:mapper/**/*.xml")); -// factory.setTypeHandlersPackage("com.rymcu.forest.util.handlers"); return factory.getObject(); } diff --git a/src/main/java/com/rymcu/forest/config/ShiroConfig.java b/src/main/java/com/rymcu/forest/config/ShiroConfig.java index 4b02b82..47463c3 100644 --- a/src/main/java/com/rymcu/forest/config/ShiroConfig.java +++ b/src/main/java/com/rymcu/forest/config/ShiroConfig.java @@ -3,14 +3,12 @@ package com.rymcu.forest.config; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.session.mgt.SessionManager; +import org.apache.shiro.session.mgt.eis.MemorySessionDAO; import org.apache.shiro.spring.LifecycleBeanPostProcessor; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.filter.authc.FormAuthenticationFilter; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; -import org.crazycake.shiro.RedisCacheManager; -import org.crazycake.shiro.RedisManager; -import org.crazycake.shiro.RedisSessionDAO; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.EnvironmentAware; @@ -116,62 +114,12 @@ public class ShiroConfig implements EnvironmentAware { @Bean public SessionManager sessionManager() { BaseSessionManager sessionManager = new BaseSessionManager(); - sessionManager.setSessionDAO(redisSessionDAO()); + sessionManager.setSessionDAO(new MemorySessionDAO()); sessionManager.setSessionIdUrlRewritingEnabled(false); sessionManager.setGlobalSessionTimeout(21600000L); return sessionManager; } - /** - * 配置shiro redisManager - *

- * 使用的是shiro-redis开源插件 - * - * @return - */ - - - public RedisManager redisManager() { - StringBuffer host = new StringBuffer(env.getProperty("spring.redis.host")); - host.append(":").append(env.getProperty("spring.redis.port")); - // 设置redis配置信息 - RedisManager redisManager = new RedisManager(); - redisManager.setHost(host.toString()); - redisManager.setPassword(env.getProperty("spring.redis.password")); - return redisManager; - } - - /** - * cacheManager 缓存 redis实现 - *

- * 使用的是shiro-redis开源插件 - * - * @return - */ - - - @Bean - public RedisCacheManager cacheManager() { - RedisCacheManager redisCacheManager = new RedisCacheManager(); - redisCacheManager.setRedisManager(redisManager()); - return redisCacheManager; - } - - /** - * RedisSessionDAO shiro sessionDao层的实现 通过redis - *

- * 使用的是shiro-redis开源插件 - */ - - - @Bean - public RedisSessionDAO redisSessionDAO() { - RedisSessionDAO redisSessionDAO = new RedisSessionDAO(); - redisSessionDAO.setRedisManager(redisManager()); - redisSessionDAO.setExpire(21600); - return redisSessionDAO; - } - /** * 开启shiro aop注解支持. * 使用代理方式;所以需要开启代码支持; diff --git a/src/main/java/com/rymcu/forest/config/WebMvcConfigurer.java b/src/main/java/com/rymcu/forest/config/WebMvcConfigurer.java index 7ce6c50..b14d7d2 100644 --- a/src/main/java/com/rymcu/forest/config/WebMvcConfigurer.java +++ b/src/main/java/com/rymcu/forest/config/WebMvcConfigurer.java @@ -12,6 +12,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.util.ResourceUtils; +import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; @@ -54,7 +55,7 @@ public class WebMvcConfigurer extends WebMvcConfigurationSupport { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") - .allowedOrigins("*") + .allowedOriginPatterns(CorsConfiguration.ALL) .allowCredentials(true) .allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH"); } diff --git a/src/main/java/com/rymcu/forest/core/exception/AccountExistsException.java b/src/main/java/com/rymcu/forest/core/exception/AccountExistsException.java new file mode 100644 index 0000000..fe97f41 --- /dev/null +++ b/src/main/java/com/rymcu/forest/core/exception/AccountExistsException.java @@ -0,0 +1,28 @@ +package com.rymcu.forest.core.exception; + +import org.apache.shiro.authc.AccountException; + +/** + * Created on 2022/8/25 19:27. + * + * @author ronger + * @email ronger-x@outlook.com + */ +public class AccountExistsException extends AccountException { + private static final long serialVersionUID = 3206734387536223284L; + + public AccountExistsException() { + } + + public AccountExistsException(String message) { + super(message); + } + + public AccountExistsException(String message, Throwable cause) { + super(message, cause); + } + + public AccountExistsException(Throwable cause) { + super(cause); + } +} diff --git a/src/main/java/com/rymcu/forest/core/exception/BusinessException.java b/src/main/java/com/rymcu/forest/core/exception/BusinessException.java new file mode 100644 index 0000000..88908dc --- /dev/null +++ b/src/main/java/com/rymcu/forest/core/exception/BusinessException.java @@ -0,0 +1,28 @@ +package com.rymcu.forest.core.exception; + +/** + * @author KKould + */ +public class BusinessException extends RuntimeException { + + private static final long serialVersionUID = 3206744387536223284L; + + public BusinessException() { + } + + public BusinessException(String message) { + super(message); + } + + public BusinessException(String message, Throwable cause) { + super(message, cause); + } + + public BusinessException(Throwable cause) { + super(cause); + } + + public BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/src/main/java/com/rymcu/forest/core/exception/ContentNotExistException.java b/src/main/java/com/rymcu/forest/core/exception/ContentNotExistException.java new file mode 100644 index 0000000..7a31d9b --- /dev/null +++ b/src/main/java/com/rymcu/forest/core/exception/ContentNotExistException.java @@ -0,0 +1,27 @@ +package com.rymcu.forest.core.exception; + +/** + * @author KKould + */ +public class ContentNotExistException extends BusinessException { + private static final long serialVersionUID = 3206734387536223284L; + + public ContentNotExistException() { + } + + public ContentNotExistException(String message) { + super(message); + } + + public ContentNotExistException(String message, Throwable cause) { + super(message, cause); + } + + public ContentNotExistException(Throwable cause) { + super(cause); + } + + public ContentNotExistException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/src/main/java/com/rymcu/forest/core/exception/NicknameOccupyException.java b/src/main/java/com/rymcu/forest/core/exception/NicknameOccupyException.java new file mode 100644 index 0000000..90b281f --- /dev/null +++ b/src/main/java/com/rymcu/forest/core/exception/NicknameOccupyException.java @@ -0,0 +1,32 @@ +package com.rymcu.forest.core.exception; + +/** + * Created on 2022/8/25 19:11. + * + * @author ronger + * @email ronger-x@outlook.com + */ +public class NicknameOccupyException extends BusinessException { + + private static final long serialVersionUID = 3206744387536223284L; + + public NicknameOccupyException() { + } + + public NicknameOccupyException(String message) { + super(message); + } + + public NicknameOccupyException(String message, Throwable cause) { + super(message, cause); + } + + public NicknameOccupyException(Throwable cause) { + super(cause); + } + + public NicknameOccupyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + +} diff --git a/src/main/java/com/rymcu/forest/core/exception/TransactionException.java b/src/main/java/com/rymcu/forest/core/exception/TransactionException.java index 5ecb5dd..ddbb8ee 100644 --- a/src/main/java/com/rymcu/forest/core/exception/TransactionException.java +++ b/src/main/java/com/rymcu/forest/core/exception/TransactionException.java @@ -5,7 +5,7 @@ import com.rymcu.forest.enumerate.TransactionCode; /** * @author ronger */ -public class TransactionException extends Exception { +public class TransactionException extends BusinessException { private int code; diff --git a/src/main/java/com/rymcu/forest/core/exception/UltraViresException.java b/src/main/java/com/rymcu/forest/core/exception/UltraViresException.java new file mode 100644 index 0000000..8ade8f1 --- /dev/null +++ b/src/main/java/com/rymcu/forest/core/exception/UltraViresException.java @@ -0,0 +1,29 @@ +package com.rymcu.forest.core.exception; + +/** + * @author KKould + */ +public class UltraViresException extends BusinessException { + + private static final long serialVersionUID = 3206744387536228284L; + + public UltraViresException() { + super(); + } + + public UltraViresException(String message) { + super(message); + } + + public UltraViresException(String message, Throwable cause) { + super(message, cause); + } + + public UltraViresException(Throwable cause) { + super(cause); + } + + protected UltraViresException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/src/main/java/com/rymcu/forest/core/service/log/VisitAspect.java b/src/main/java/com/rymcu/forest/core/service/log/VisitAspect.java index ce0ed4f..e1c9c26 100644 --- a/src/main/java/com/rymcu/forest/core/service/log/VisitAspect.java +++ b/src/main/java/com/rymcu/forest/core/service/log/VisitAspect.java @@ -90,7 +90,7 @@ public class VisitAspect { if (StringUtils.isBlank(param) || "undefined".equals(param) || "null".equals(param)) { break; } - Integer id = Integer.parseInt(param); + Long id = Long.parseLong(param); articleService.incrementArticleViewCount(id); break; default: diff --git a/src/main/java/com/rymcu/forest/core/service/security/AuthorshipAspect.java b/src/main/java/com/rymcu/forest/core/service/security/AuthorshipAspect.java index 92fd989..a344aea 100644 --- a/src/main/java/com/rymcu/forest/core/service/security/AuthorshipAspect.java +++ b/src/main/java/com/rymcu/forest/core/service/security/AuthorshipAspect.java @@ -76,7 +76,7 @@ public class AuthorshipAspect { } HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); String idArticle; - Integer idAuthor = 0; + Long idAuthor = 0l; if (isAjax(request)) { Object[] objects = joinPoint.getArgs(); JSONObject jsonObject; diff --git a/src/main/java/com/rymcu/forest/dto/ArticleDTO.java b/src/main/java/com/rymcu/forest/dto/ArticleDTO.java index 530998c..4b7e370 100644 --- a/src/main/java/com/rymcu/forest/dto/ArticleDTO.java +++ b/src/main/java/com/rymcu/forest/dto/ArticleDTO.java @@ -1,7 +1,11 @@ package com.rymcu.forest.dto; import com.alibaba.fastjson.annotation.JSONField; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Data; +import lombok.NoArgsConstructor; import java.util.Date; import java.util.List; @@ -10,14 +14,19 @@ import java.util.List; * @author ronger */ @Data +@Builder +@NoArgsConstructor +@AllArgsConstructor public class ArticleDTO { - private Integer idArticle; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idArticle; /** 文章标题 */ private String articleTitle; /** 文章缩略图 */ private String articleThumbnailUrl; /** 文章作者id */ - private Integer articleAuthorId; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long articleAuthorId; /** 文章作者 */ private String articleAuthorName; /** 文章作者头像 */ diff --git a/src/main/java/com/rymcu/forest/dto/ArticleTagDTO.java b/src/main/java/com/rymcu/forest/dto/ArticleTagDTO.java index c825537..44585b2 100644 --- a/src/main/java/com/rymcu/forest/dto/ArticleTagDTO.java +++ b/src/main/java/com/rymcu/forest/dto/ArticleTagDTO.java @@ -1,18 +1,26 @@ package com.rymcu.forest.dto; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Data; +import lombok.NoArgsConstructor; /** * @author ronger */ @Data +@Builder +@NoArgsConstructor +@AllArgsConstructor public class ArticleTagDTO { - - private Integer idArticleTag; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idArticleTag; private Integer idTag; - private Integer idArticle; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idArticle; private String tagTitle; @@ -22,5 +30,6 @@ public class ArticleTagDTO { private String tagIconPath; - private Integer tagAuthorId; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long tagAuthorId; } diff --git a/src/main/java/com/rymcu/forest/dto/Author.java b/src/main/java/com/rymcu/forest/dto/Author.java index 3782f01..a15cc53 100644 --- a/src/main/java/com/rymcu/forest/dto/Author.java +++ b/src/main/java/com/rymcu/forest/dto/Author.java @@ -1,14 +1,22 @@ package com.rymcu.forest.dto; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Data; +import lombok.NoArgsConstructor; /** * @author ronger */ @Data +@Builder +@NoArgsConstructor +@AllArgsConstructor public class Author { - private Integer idUser; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idUser; private String userNickname; diff --git a/src/main/java/com/rymcu/forest/dto/ChangeEmailDTO.java b/src/main/java/com/rymcu/forest/dto/ChangeEmailDTO.java index e3a9e06..0e2bf71 100644 --- a/src/main/java/com/rymcu/forest/dto/ChangeEmailDTO.java +++ b/src/main/java/com/rymcu/forest/dto/ChangeEmailDTO.java @@ -1,5 +1,6 @@ package com.rymcu.forest.dto; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; /** @@ -8,7 +9,8 @@ import lombok.Data; @Data public class ChangeEmailDTO { - private Integer idUser; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idUser; private String email; diff --git a/src/main/java/com/rymcu/forest/dto/NotificationDTO.java b/src/main/java/com/rymcu/forest/dto/NotificationDTO.java index d661521..47bd524 100644 --- a/src/main/java/com/rymcu/forest/dto/NotificationDTO.java +++ b/src/main/java/com/rymcu/forest/dto/NotificationDTO.java @@ -1,5 +1,6 @@ package com.rymcu.forest.dto; +import com.fasterxml.jackson.annotation.JsonFormat; import com.rymcu.forest.entity.Notification; import lombok.Data; import lombok.EqualsAndHashCode; @@ -11,7 +12,8 @@ import lombok.EqualsAndHashCode; @EqualsAndHashCode(callSuper = false) public class NotificationDTO extends Notification { - private Integer idNotification; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idNotification; private String dataTitle; diff --git a/src/main/java/com/rymcu/forest/dto/PortfolioArticleDTO.java b/src/main/java/com/rymcu/forest/dto/PortfolioArticleDTO.java index 6a37646..776e685 100644 --- a/src/main/java/com/rymcu/forest/dto/PortfolioArticleDTO.java +++ b/src/main/java/com/rymcu/forest/dto/PortfolioArticleDTO.java @@ -1,5 +1,6 @@ package com.rymcu.forest.dto; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.util.List; @@ -10,11 +11,14 @@ import java.util.List; @Data public class PortfolioArticleDTO { - private Integer id; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long id; - private Integer idPortfolio; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idPortfolio; - private Integer idArticle; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idArticle; private String headImgUrl; diff --git a/src/main/java/com/rymcu/forest/dto/PortfolioDTO.java b/src/main/java/com/rymcu/forest/dto/PortfolioDTO.java index bf8cbd1..13363b2 100644 --- a/src/main/java/com/rymcu/forest/dto/PortfolioDTO.java +++ b/src/main/java/com/rymcu/forest/dto/PortfolioDTO.java @@ -1,5 +1,6 @@ package com.rymcu.forest.dto; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.util.Date; @@ -10,11 +11,13 @@ import java.util.Date; @Data public class PortfolioDTO { - private Integer idPortfolio; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idPortfolio; /** 作品集头像 */ private String headImgUrl; /** 作品集作者 */ - private Integer portfolioAuthorId; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long portfolioAuthorId; /** 作品集作者 */ private String portfolioAuthorName; /** 作品集作者头像 */ diff --git a/src/main/java/com/rymcu/forest/dto/ProductDTO.java b/src/main/java/com/rymcu/forest/dto/ProductDTO.java new file mode 100644 index 0000000..dd8c3cc --- /dev/null +++ b/src/main/java/com/rymcu/forest/dto/ProductDTO.java @@ -0,0 +1,23 @@ +package com.rymcu.forest.dto; + +import com.rymcu.forest.entity.Product; +import lombok.Data; + +/** + * Created on 2022/6/21 9:38. + * + * @author ronger + * @email ronger-x@outlook.com + * @packageName com.rymcu.forest.dto + */ +@Data +public class ProductDTO extends Product { + /** + * 文章内容 + */ + private String productContent; + /** + * 文章内容html + */ + private String productContentHtml; +} diff --git a/src/main/java/com/rymcu/forest/dto/TokenUser.java b/src/main/java/com/rymcu/forest/dto/TokenUser.java index 387f770..339e7bd 100644 --- a/src/main/java/com/rymcu/forest/dto/TokenUser.java +++ b/src/main/java/com/rymcu/forest/dto/TokenUser.java @@ -1,5 +1,6 @@ package com.rymcu.forest.dto; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; /** @@ -8,7 +9,8 @@ import lombok.Data; @Data public class TokenUser { - private Integer idUser; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idUser; private String account; diff --git a/src/main/java/com/rymcu/forest/dto/UpdatePasswordDTO.java b/src/main/java/com/rymcu/forest/dto/UpdatePasswordDTO.java index 8e8ab47..296caac 100644 --- a/src/main/java/com/rymcu/forest/dto/UpdatePasswordDTO.java +++ b/src/main/java/com/rymcu/forest/dto/UpdatePasswordDTO.java @@ -1,5 +1,6 @@ package com.rymcu.forest.dto; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; /** @@ -8,7 +9,8 @@ import lombok.Data; @Data public class UpdatePasswordDTO { - private Integer idUser; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idUser; private String password; diff --git a/src/main/java/com/rymcu/forest/dto/UserDTO.java b/src/main/java/com/rymcu/forest/dto/UserDTO.java index a4d755e..c67affe 100644 --- a/src/main/java/com/rymcu/forest/dto/UserDTO.java +++ b/src/main/java/com/rymcu/forest/dto/UserDTO.java @@ -1,5 +1,6 @@ package com.rymcu.forest.dto; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; /** @@ -8,7 +9,8 @@ import lombok.Data; @Data public class UserDTO { - private Integer idUser; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idUser; private String account; @@ -19,4 +21,6 @@ public class UserDTO { private String nickname; private String signature; + + private String bgImgUrl; } diff --git a/src/main/java/com/rymcu/forest/dto/UserInfoDTO.java b/src/main/java/com/rymcu/forest/dto/UserInfoDTO.java index 60ff5e3..e41efee 100644 --- a/src/main/java/com/rymcu/forest/dto/UserInfoDTO.java +++ b/src/main/java/com/rymcu/forest/dto/UserInfoDTO.java @@ -1,6 +1,7 @@ package com.rymcu.forest.dto; import com.alibaba.fastjson.annotation.JSONField; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; @@ -13,7 +14,8 @@ import java.util.Date; @Data public class UserInfoDTO implements Serializable { - private Integer idUser; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idUser; private String account; @@ -46,4 +48,6 @@ public class UserInfoDTO implements Serializable { private Integer onlineStatus; + private String bgImgUrl; + } diff --git a/src/main/java/com/rymcu/forest/dto/admin/TopicTagDTO.java b/src/main/java/com/rymcu/forest/dto/admin/TopicTagDTO.java index 3bad3b5..1ceba63 100644 --- a/src/main/java/com/rymcu/forest/dto/admin/TopicTagDTO.java +++ b/src/main/java/com/rymcu/forest/dto/admin/TopicTagDTO.java @@ -1,5 +1,6 @@ package com.rymcu.forest.dto.admin; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; /** @@ -8,7 +9,9 @@ import lombok.Data; @Data public class TopicTagDTO { - private Integer idTopic; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idTopic; - private Integer idTag; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idTag; } diff --git a/src/main/java/com/rymcu/forest/dto/admin/UserRoleDTO.java b/src/main/java/com/rymcu/forest/dto/admin/UserRoleDTO.java index a33f8c5..af78c3b 100644 --- a/src/main/java/com/rymcu/forest/dto/admin/UserRoleDTO.java +++ b/src/main/java/com/rymcu/forest/dto/admin/UserRoleDTO.java @@ -1,5 +1,6 @@ package com.rymcu.forest.dto.admin; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; /** @@ -7,7 +8,10 @@ import lombok.Data; */ @Data public class UserRoleDTO { - private Integer idUser; - private Integer idRole; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idUser; + + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idRole; } diff --git a/src/main/java/com/rymcu/forest/entity/Article.java b/src/main/java/com/rymcu/forest/entity/Article.java index a929ee3..88fd893 100644 --- a/src/main/java/com/rymcu/forest/entity/Article.java +++ b/src/main/java/com/rymcu/forest/entity/Article.java @@ -1,5 +1,6 @@ package com.rymcu.forest.entity; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; @@ -19,13 +20,15 @@ public class Article implements Serializable,Cloneable { @Id @GeneratedValue(generator = "JDBC") @Column(name = "id") - private Integer idArticle; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idArticle; /** 文章标题 */ private String articleTitle; /** 文章缩略图 */ private String articleThumbnailUrl; /** 文章作者id */ - private Integer articleAuthorId; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long articleAuthorId; /** 文章类型 */ private String articleType; /** 文章标签 */ diff --git a/src/main/java/com/rymcu/forest/entity/ArticleContent.java b/src/main/java/com/rymcu/forest/entity/ArticleContent.java index 846b477..75cdd91 100644 --- a/src/main/java/com/rymcu/forest/entity/ArticleContent.java +++ b/src/main/java/com/rymcu/forest/entity/ArticleContent.java @@ -1,5 +1,6 @@ package com.rymcu.forest.entity; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; @@ -18,7 +19,8 @@ public class ArticleContent { @Id @Column(name = "id") @GeneratedValue(generator = "JDBC") - private Integer idArticle; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idArticle; private String articleContent; diff --git a/src/main/java/com/rymcu/forest/entity/ArticleThumbsUp.java b/src/main/java/com/rymcu/forest/entity/ArticleThumbsUp.java index b7729dd..3ff6332 100644 --- a/src/main/java/com/rymcu/forest/entity/ArticleThumbsUp.java +++ b/src/main/java/com/rymcu/forest/entity/ArticleThumbsUp.java @@ -1,5 +1,6 @@ package com.rymcu.forest.entity; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; @@ -21,15 +22,18 @@ public class ArticleThumbsUp implements Serializable, Cloneable { @Id @Column(name = "id") @GeneratedValue(generator = "JDBC") - private Integer idArticleThumbsUp; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idArticleThumbsUp; /** * 文章表主键 */ - private Integer idArticle; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idArticle; /** * 用户表主键 */ - private Integer idUser; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idUser; /** * 点赞时间 */ diff --git a/src/main/java/com/rymcu/forest/entity/Bank.java b/src/main/java/com/rymcu/forest/entity/Bank.java index 97405fb..d1ecd9c 100644 --- a/src/main/java/com/rymcu/forest/entity/Bank.java +++ b/src/main/java/com/rymcu/forest/entity/Bank.java @@ -1,6 +1,7 @@ package com.rymcu.forest.entity; import com.alibaba.fastjson.annotation.JSONField; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; @@ -21,15 +22,17 @@ public class Bank { @Id @Column(name = "id") @GeneratedValue(generator = "JDBC") - private Integer idBank; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idBank; /** 银行名称 */ private String bankName; /** 银行负责人 */ - private Integer bankOwner; + private Long bankOwner; /** 银行描述 */ private String bankDescription; /** 创建人 */ - private Integer createdBy; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long createdBy; /** 创建时间 */ @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date createdTime; diff --git a/src/main/java/com/rymcu/forest/entity/BankAccount.java b/src/main/java/com/rymcu/forest/entity/BankAccount.java index 3c3374a..c6a3a85 100644 --- a/src/main/java/com/rymcu/forest/entity/BankAccount.java +++ b/src/main/java/com/rymcu/forest/entity/BankAccount.java @@ -1,6 +1,7 @@ package com.rymcu.forest.entity; import com.alibaba.fastjson.annotation.JSONField; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; @@ -21,15 +22,18 @@ public class BankAccount { @Id @Column(name = "id") @GeneratedValue(generator = "JDBC") - private Integer idBankAccount; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idBankAccount; /** 所属银行 */ - private Integer idBank; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idBank; /** 银行账户 */ private String bankAccount; /** 账户余额 */ private BigDecimal accountBalance; /** 账户所有者 */ - private Integer accountOwner; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long accountOwner; /** 创建时间 */ @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date createdTime; diff --git a/src/main/java/com/rymcu/forest/entity/Comment.java b/src/main/java/com/rymcu/forest/entity/Comment.java index 3431f74..d1f4bbb 100644 --- a/src/main/java/com/rymcu/forest/entity/Comment.java +++ b/src/main/java/com/rymcu/forest/entity/Comment.java @@ -1,5 +1,6 @@ package com.rymcu.forest.entity; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; @@ -19,22 +20,26 @@ public class Comment implements Serializable,Cloneable { @Id @GeneratedValue(generator = "JDBC") @Column(name = "id") - private Integer idComment; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idComment; /** 评论内容 */ @Column(name = "comment_content") private String commentContent; /** 作者 id */ @Column(name = "comment_author_id") - private Integer commentAuthorId; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long commentAuthorId; /** 文章 id */ @Column(name = "comment_article_id") - private Integer commentArticleId; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long commentArticleId; /** 锚点 url */ @Column(name = "comment_sharp_url") private String commentSharpUrl; /** 父评论 id */ @Column(name = "comment_original_comment_id") - private Integer commentOriginalCommentId; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long commentOriginalCommentId; /** 状态 */ @Column(name = "comment_status") private String commentStatus; diff --git a/src/main/java/com/rymcu/forest/entity/CurrencyIssue.java b/src/main/java/com/rymcu/forest/entity/CurrencyIssue.java index 4ab315c..0ed9caf 100644 --- a/src/main/java/com/rymcu/forest/entity/CurrencyIssue.java +++ b/src/main/java/com/rymcu/forest/entity/CurrencyIssue.java @@ -1,5 +1,6 @@ package com.rymcu.forest.entity; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.GeneratedValue; @@ -18,11 +19,13 @@ public class CurrencyIssue { /** 主键 */ @Id @GeneratedValue(generator = "JDBC") - private Integer id; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long id; /** 发行数额 */ private BigDecimal issueValue; /** 发行人 */ - private Integer createdBy; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long createdBy; /** 发行时间 */ private Date createdTime; diff --git a/src/main/java/com/rymcu/forest/entity/CurrencyRule.java b/src/main/java/com/rymcu/forest/entity/CurrencyRule.java index 243a5cc..934b02e 100644 --- a/src/main/java/com/rymcu/forest/entity/CurrencyRule.java +++ b/src/main/java/com/rymcu/forest/entity/CurrencyRule.java @@ -1,5 +1,6 @@ package com.rymcu.forest.entity; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; @@ -21,7 +22,8 @@ public class CurrencyRule implements Serializable, Cloneable { @Id @GeneratedValue(generator = "JDBC") @Column(name = "id") - private Integer idCurrencyRule; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idCurrencyRule; /** * 规则名称 */ diff --git a/src/main/java/com/rymcu/forest/entity/Follow.java b/src/main/java/com/rymcu/forest/entity/Follow.java index 471fe44..6e9d081 100644 --- a/src/main/java/com/rymcu/forest/entity/Follow.java +++ b/src/main/java/com/rymcu/forest/entity/Follow.java @@ -1,5 +1,6 @@ package com.rymcu.forest.entity; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; @@ -18,13 +19,16 @@ public class Follow implements Serializable,Cloneable { @Id @GeneratedValue(generator = "JDBC") @Column(name = "id") - private Integer idFollow; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idFollow; /** 关注者 id */ @Column(name = "follower_id") - private Integer followerId; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long followerId; /** 关注数据 id */ @Column(name = "following_id") - private Integer followingId; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long followingId; /** 0:用户,1:标签,2:帖子收藏,3:帖子关注 */ @Column(name = "following_type") private String followingType; diff --git a/src/main/java/com/rymcu/forest/entity/ForestFile.java b/src/main/java/com/rymcu/forest/entity/ForestFile.java index 58a8dfa..bcb7aee 100644 --- a/src/main/java/com/rymcu/forest/entity/ForestFile.java +++ b/src/main/java/com/rymcu/forest/entity/ForestFile.java @@ -1,5 +1,6 @@ package com.rymcu.forest.entity; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; @@ -21,13 +22,15 @@ public class ForestFile { @Id @GeneratedValue(generator = "JDBC") @Column(name = "id") + @JsonFormat(shape = JsonFormat.Shape.STRING) private Long id; /** * 文件大小 */ @Column(name = "file_size") - private long fileSize; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long fileSize; /** * 文件类型-文件后缀 @@ -68,7 +71,8 @@ public class ForestFile { * 创建人 */ @Column(name = "created_by") - private long createdBy; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long createdBy; } diff --git a/src/main/java/com/rymcu/forest/entity/LoginRecord.java b/src/main/java/com/rymcu/forest/entity/LoginRecord.java index 36825cd..776f57c 100644 --- a/src/main/java/com/rymcu/forest/entity/LoginRecord.java +++ b/src/main/java/com/rymcu/forest/entity/LoginRecord.java @@ -1,6 +1,7 @@ package com.rymcu.forest.entity; import com.alibaba.fastjson.annotation.JSONField; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; @@ -22,7 +23,8 @@ public class LoginRecord implements Serializable,Cloneable { @Id @GeneratedValue(generator = "JDBC") @Column(name = "id") - private Integer id; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long id; /** IP */ @Column(name = "login_ip") private String loginIp; @@ -43,7 +45,8 @@ public class LoginRecord implements Serializable,Cloneable { private String loginBrowser; /** 用户 id */ @Column(name = "id_user") - private Integer idUser; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idUser; /** 创建时间 */ @Column(name = "created_time") @JSONField(format = "yyyy-MM-dd HH:mm:ss") diff --git a/src/main/java/com/rymcu/forest/entity/Notification.java b/src/main/java/com/rymcu/forest/entity/Notification.java index 809f070..a54927e 100644 --- a/src/main/java/com/rymcu/forest/entity/Notification.java +++ b/src/main/java/com/rymcu/forest/entity/Notification.java @@ -1,6 +1,7 @@ package com.rymcu.forest.entity; import com.alibaba.fastjson.annotation.JSONField; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; @@ -23,12 +24,14 @@ public class Notification implements Serializable,Cloneable { @Id @GeneratedValue(generator = "JDBC") @Column(name = "id") - private Integer idNotification; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idNotification; /** * 用户id */ @Column(name = "id_user") - private Integer idUser; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idUser; /** * 数据类型 */ @@ -38,7 +41,8 @@ public class Notification implements Serializable,Cloneable { * 数据id */ @Column(name = "data_id") - private Integer dataId; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long dataId; /** * 数据摘要 */ diff --git a/src/main/java/com/rymcu/forest/entity/Permission.java b/src/main/java/com/rymcu/forest/entity/Permission.java index d5b0bb8..f5c27d7 100644 --- a/src/main/java/com/rymcu/forest/entity/Permission.java +++ b/src/main/java/com/rymcu/forest/entity/Permission.java @@ -1,5 +1,6 @@ package com.rymcu.forest.entity; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import tk.mybatis.mapper.annotation.ColumnType; @@ -19,7 +20,8 @@ public class Permission implements Serializable,Cloneable { @Id @Column(name = "id") @GeneratedValue(generator = "JDBC") - private Integer idPermission; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idPermission; /** * 权限标识 diff --git a/src/main/java/com/rymcu/forest/entity/Portfolio.java b/src/main/java/com/rymcu/forest/entity/Portfolio.java index 8165a4f..c628b6f 100644 --- a/src/main/java/com/rymcu/forest/entity/Portfolio.java +++ b/src/main/java/com/rymcu/forest/entity/Portfolio.java @@ -1,5 +1,6 @@ package com.rymcu.forest.entity; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.*; @@ -15,14 +16,16 @@ public class Portfolio { @Id @GeneratedValue(generator = "JDBC") @Column(name = "id") - private Integer idPortfolio; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idPortfolio; /** 作品集头像 */ @Column(name = "portfolio_head_img_url") private String headImgUrl; /** 作品集名称 */ private String portfolioTitle; /** 作品集作者 */ - private Integer portfolioAuthorId; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long portfolioAuthorId; /** 作品集介绍 */ private String portfolioDescription; /** 作品集介绍 Html */ diff --git a/src/main/java/com/rymcu/forest/entity/Product.java b/src/main/java/com/rymcu/forest/entity/Product.java new file mode 100644 index 0000000..88c670d --- /dev/null +++ b/src/main/java/com/rymcu/forest/entity/Product.java @@ -0,0 +1,62 @@ +package com.rymcu.forest.entity; + +import com.alibaba.fastjson.annotation.JSONField; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; + +import javax.persistence.Column; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; +import java.io.Serializable; +import java.util.Date; + +/** + * Created on 2022/6/13 21:42. + * + * @author ronger + * @email ronger-x@outlook.com + * @desc : 产品表 + */ +@Data +@Table(name = "forest_product") +public class Product implements Serializable, Cloneable { + /** + * 主键 + */ + @Id + @GeneratedValue(generator = "JDBC") + @Column(name = "id") + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idProduct; + /** + * 产品名 + */ + private String productTitle; + /** + * 单价(单位:分) + */ + private Integer productPrice; + /** + * 产品主图 + */ + private String productImgUrl; + /** + * 产品描述 + */ + private String productDescription; + /** + * 权重;数值越小权限越大;0:无权限 + */ + private Integer weights; + /** + * 创建时间 + */ + @JSONField(format = "yyyy-MM-dd HH:mm:ss") + private Date createdTime; + /** + * 更新时间 + */ + @JSONField(format = "yyyy-MM-dd HH:mm:ss") + private Date updatedTime; +} diff --git a/src/main/java/com/rymcu/forest/entity/ProductContent.java b/src/main/java/com/rymcu/forest/entity/ProductContent.java new file mode 100644 index 0000000..70d2066 --- /dev/null +++ b/src/main/java/com/rymcu/forest/entity/ProductContent.java @@ -0,0 +1,44 @@ +package com.rymcu.forest.entity; + +import com.alibaba.fastjson.annotation.JSONField; +import com.fasterxml.jackson.annotation.JsonFormat; +import lombok.Data; + +import javax.persistence.Table; +import java.io.Serializable; +import java.util.Date; + +/** + * Created on 2022/6/13 21:51. + * + * @author ronger + * @email ronger-x@outlook.com + * @desc : 产品详情表 + */ +@Data +@Table(name = "forest_product_content") +public class ProductContent implements Serializable, Cloneable { + /** + * 产品表主键 + */ + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idProduct; + /** + * 产品详情原文 + */ + private String productContent; + /** + * 产品详情;Html + */ + private String productContentHtml; + /** + * 创建时间 + */ + @JSONField(format = "yyyy-MM-dd HH:mm:ss") + private Date createdTime; + /** + * 更新时间 + */ + @JSONField(format = "yyyy-MM-dd HH:mm:ss") + private Date updatedTime; +} diff --git a/src/main/java/com/rymcu/forest/entity/Role.java b/src/main/java/com/rymcu/forest/entity/Role.java index 99c2511..92af0a9 100644 --- a/src/main/java/com/rymcu/forest/entity/Role.java +++ b/src/main/java/com/rymcu/forest/entity/Role.java @@ -1,6 +1,7 @@ package com.rymcu.forest.entity; import com.alibaba.fastjson.annotation.JSONField; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; @@ -19,7 +20,8 @@ public class Role implements Serializable,Cloneable { @Id @Column(name = "id") @GeneratedValue(generator = "JDBC") - private Integer idRole; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idRole; /** * 角色名称 diff --git a/src/main/java/com/rymcu/forest/entity/SpecialDay.java b/src/main/java/com/rymcu/forest/entity/SpecialDay.java index 5455d6a..744c98a 100644 --- a/src/main/java/com/rymcu/forest/entity/SpecialDay.java +++ b/src/main/java/com/rymcu/forest/entity/SpecialDay.java @@ -1,5 +1,6 @@ package com.rymcu.forest.entity; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; @@ -19,7 +20,8 @@ public class SpecialDay implements Serializable,Cloneable{ @Id @Column(name = "id") @GeneratedValue(generator = "JDBC") - private Integer idSpecialDay; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idSpecialDay; /** 名称 */ private String specialDayName; /** 权重/优先级,小数优秀 */ diff --git a/src/main/java/com/rymcu/forest/entity/Sponsor.java b/src/main/java/com/rymcu/forest/entity/Sponsor.java index a9eeaef..1dbb03f 100644 --- a/src/main/java/com/rymcu/forest/entity/Sponsor.java +++ b/src/main/java/com/rymcu/forest/entity/Sponsor.java @@ -1,5 +1,6 @@ package com.rymcu.forest.entity; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.GeneratedValue; @@ -20,7 +21,8 @@ public class Sponsor implements Serializable, Cloneable { */ @Id @GeneratedValue(generator = "JDBC") - private Integer id; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long id; /** * 数据类型 */ @@ -28,11 +30,13 @@ public class Sponsor implements Serializable, Cloneable { /** * 数据主键 */ - private Integer dataId; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long dataId; /** * 赞赏人 */ - private Integer sponsor; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long sponsor; /** * 赞赏日期 */ diff --git a/src/main/java/com/rymcu/forest/entity/Tag.java b/src/main/java/com/rymcu/forest/entity/Tag.java index 8a2e5f2..6419807 100644 --- a/src/main/java/com/rymcu/forest/entity/Tag.java +++ b/src/main/java/com/rymcu/forest/entity/Tag.java @@ -1,5 +1,6 @@ package com.rymcu.forest.entity; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; @@ -19,7 +20,8 @@ public class Tag implements Serializable,Cloneable { @Id @Column(name = "id") @GeneratedValue(generator = "JDBC") - private Integer idTag; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idTag; /** 标签名 */ private String tagTitle; /** 标签图标 */ diff --git a/src/main/java/com/rymcu/forest/entity/Topic.java b/src/main/java/com/rymcu/forest/entity/Topic.java index cab07de..920de24 100644 --- a/src/main/java/com/rymcu/forest/entity/Topic.java +++ b/src/main/java/com/rymcu/forest/entity/Topic.java @@ -1,5 +1,6 @@ package com.rymcu.forest.entity; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; @@ -19,7 +20,8 @@ public class Topic { @Id @Column(name = "id") @GeneratedValue(generator = "JDBC") - private Integer idTopic; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idTopic; /** 专题标题 */ private String topicTitle; /** 专题路径 */ diff --git a/src/main/java/com/rymcu/forest/entity/TransactionRecord.java b/src/main/java/com/rymcu/forest/entity/TransactionRecord.java index c7e34c8..b310c5a 100644 --- a/src/main/java/com/rymcu/forest/entity/TransactionRecord.java +++ b/src/main/java/com/rymcu/forest/entity/TransactionRecord.java @@ -1,5 +1,6 @@ package com.rymcu.forest.entity; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; @@ -20,7 +21,8 @@ public class TransactionRecord { @Id @Column(name = "id") @GeneratedValue(generator = "JDBC") - private Integer idTransactionRecord; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idTransactionRecord; /** 交易流水号 */ private String transactionNo; /** 款项 */ diff --git a/src/main/java/com/rymcu/forest/entity/User.java b/src/main/java/com/rymcu/forest/entity/User.java index 8654f99..7429770 100644 --- a/src/main/java/com/rymcu/forest/entity/User.java +++ b/src/main/java/com/rymcu/forest/entity/User.java @@ -1,6 +1,7 @@ package com.rymcu.forest.entity; import com.alibaba.fastjson.annotation.JSONField; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import org.apache.ibatis.type.JdbcType; import tk.mybatis.mapper.annotation.ColumnType; @@ -21,7 +22,8 @@ public class User implements Serializable,Cloneable { @Id @Column(name = "id") @GeneratedValue(generator = "JDBC") - private Integer idUser; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idUser; /** * 登录账号 @@ -120,4 +122,10 @@ public class User implements Serializable,Cloneable { @Column(name = "last_online_time") @JSONField(format = "yyyy-MM-dd HH:mm:ss") private Date lastOnlineTime; + + /** + * 个人中心背景图片 + * */ + @Column(name = "bg_img_url") + private String bgImgUrl; } \ No newline at end of file diff --git a/src/main/java/com/rymcu/forest/entity/UserExtend.java b/src/main/java/com/rymcu/forest/entity/UserExtend.java index b4e339a..59a3d4d 100644 --- a/src/main/java/com/rymcu/forest/entity/UserExtend.java +++ b/src/main/java/com/rymcu/forest/entity/UserExtend.java @@ -1,5 +1,6 @@ package com.rymcu.forest.entity; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Id; @@ -13,7 +14,8 @@ import javax.persistence.Table; public class UserExtend { @Id - private Integer idUser; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idUser; private String github; diff --git a/src/main/java/com/rymcu/forest/entity/Visit.java b/src/main/java/com/rymcu/forest/entity/Visit.java index f1f2aa1..f8beb08 100644 --- a/src/main/java/com/rymcu/forest/entity/Visit.java +++ b/src/main/java/com/rymcu/forest/entity/Visit.java @@ -1,6 +1,7 @@ package com.rymcu.forest.entity; import com.alibaba.fastjson.annotation.JSONField; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; @@ -22,7 +23,8 @@ public class Visit implements Serializable,Cloneable { @Id @GeneratedValue(generator = "JDBC") @Column(name = "id") - private Integer id; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long id; /** 浏览链接 */ @Column(name = "visit_url") private String visitUrl; @@ -40,7 +42,8 @@ public class Visit implements Serializable,Cloneable { private String visitDeviceId; /** 浏览者 id */ @Column(name = "visit_user_id") - private Integer visitUserId; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long visitUserId; /** 上游链接 */ @Column(name = "visit_referer_url") private String visitRefererUrl; diff --git a/src/main/java/com/rymcu/forest/entity/WxUser.java b/src/main/java/com/rymcu/forest/entity/WxUser.java index 81fdce4..34f8d77 100644 --- a/src/main/java/com/rymcu/forest/entity/WxUser.java +++ b/src/main/java/com/rymcu/forest/entity/WxUser.java @@ -1,5 +1,6 @@ package com.rymcu.forest.entity; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import javax.persistence.Column; @@ -17,7 +18,8 @@ public class WxUser { @Id @Column(name = "id") @GeneratedValue(generator = "JDBC") - private Integer idWxUser; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idWxUser; private Boolean subscribe; diff --git a/src/main/java/com/rymcu/forest/handler/AccountHandler.java b/src/main/java/com/rymcu/forest/handler/AccountHandler.java new file mode 100644 index 0000000..96315a5 --- /dev/null +++ b/src/main/java/com/rymcu/forest/handler/AccountHandler.java @@ -0,0 +1,26 @@ +package com.rymcu.forest.handler; + +import com.rymcu.forest.handler.event.AccountEvent; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.event.EventListener; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +/** + * Created on 2022/8/24 14:44. + * + * @author ronger + * @email ronger-x@outlook.com + * @packageName com.rymcu.forest.handler + */ +@Slf4j +@Component +public class AccountHandler { + + @Async + @EventListener + public void processAccountLastLoginEvent(AccountEvent accountEvent) { + + } + +} diff --git a/src/main/java/com/rymcu/forest/handler/ArticleHandler.java b/src/main/java/com/rymcu/forest/handler/ArticleHandler.java new file mode 100644 index 0000000..b3d372d --- /dev/null +++ b/src/main/java/com/rymcu/forest/handler/ArticleHandler.java @@ -0,0 +1,66 @@ +package com.rymcu.forest.handler; + +import com.alibaba.fastjson.JSON; +import com.rymcu.forest.core.constant.NotificationConstant; +import com.rymcu.forest.handler.event.ArticleDeleteEvent; +import com.rymcu.forest.handler.event.ArticleEvent; +import com.rymcu.forest.lucene.service.LuceneService; +import com.rymcu.forest.util.NotificationUtils; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.event.EventListener; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; + +/** + * Created on 2022/8/16 20:42. + * + * @author ronger + * @email ronger-x@outlook.com + */ +@Slf4j +@Component +public class ArticleHandler { + @Resource + private LuceneService luceneService; + + @EventListener + @Async + public void processArticlePostEvent(ArticleEvent articleEvent) throws InterruptedException { + Thread.sleep(1000); + log.info(String.format("执行文章发布相关事件:[%s]", JSON.toJSONString(articleEvent))); + // 发送系统通知 + if (articleEvent.getNotification()) { + NotificationUtils.sendAnnouncement(articleEvent.getIdArticle(), NotificationConstant.Article, articleEvent.getArticleTitle()); + } else { + // 发送关注通知 + StringBuilder dataSummary = new StringBuilder(); + if (articleEvent.getIsUpdate()) { + dataSummary.append(articleEvent.getNickname()).append("更新了文章: ").append(articleEvent.getArticleTitle()); + NotificationUtils.sendArticlePush(articleEvent.getIdArticle(), NotificationConstant.UpdateArticle, dataSummary.toString(), articleEvent.getArticleAuthorId()); + } else { + dataSummary.append(articleEvent.getNickname()).append("发布了文章: ").append(articleEvent.getArticleTitle()); + NotificationUtils.sendArticlePush(articleEvent.getIdArticle(), NotificationConstant.PostArticle, dataSummary.toString(), articleEvent.getArticleAuthorId()); + } + } + // 草稿不更新索引 + if (articleEvent.getIsUpdate()) { + log.info("更新文章索引,id={}", articleEvent.getIdArticle()); + luceneService.updateArticle(articleEvent.getIdArticle()); + } else { + log.info("写入文章索引,id={}", articleEvent.getIdArticle()); + luceneService.writeArticle(articleEvent.getIdArticle()); + } + log.info("执行完成文章发布相关事件...id={}", articleEvent.getIdArticle()); + } + + @EventListener + @Async + public void processArticleDeleteEvent(ArticleDeleteEvent articleDeleteEvent) throws InterruptedException { + Thread.sleep(1000); + log.info(String.format("执行文章删除相关事件:[%s]", JSON.toJSONString(articleDeleteEvent))); + luceneService.deleteArticle(articleDeleteEvent.getIdArticle()); + log.info("执行完成文章删除相关事件...id={}", articleDeleteEvent.getIdArticle()); + } +} diff --git a/src/main/java/com/rymcu/forest/handler/CommentHandler.java b/src/main/java/com/rymcu/forest/handler/CommentHandler.java new file mode 100644 index 0000000..b8cab12 --- /dev/null +++ b/src/main/java/com/rymcu/forest/handler/CommentHandler.java @@ -0,0 +1,57 @@ +package com.rymcu.forest.handler; + +import com.alibaba.fastjson.JSON; +import com.rymcu.forest.core.constant.NotificationConstant; +import com.rymcu.forest.entity.Comment; +import com.rymcu.forest.handler.event.CommentEvent; +import com.rymcu.forest.mapper.CommentMapper; +import com.rymcu.forest.util.Html2TextUtil; +import com.rymcu.forest.util.NotificationUtils; +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.event.EventListener; +import org.springframework.scheduling.annotation.Async; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; + +/** + * Created on 2022/8/17 7:38. + * + * @author ronger + * @email ronger-x@outlook.com + * @packageName com.rymcu.forest.handler + */ +@Slf4j +@Component +public class CommentHandler { + + private static final int MAX_PREVIEW = 200; + @Resource + private CommentMapper commentMapper; + + @Async + @EventListener + public void processCommentCreatedEvent(CommentEvent commentEvent) throws InterruptedException { + log.info(String.format("开始执行评论发布事件:[%s]", JSON.toJSONString(commentEvent))); + String commentContent = commentEvent.getContent(); + Integer length = commentContent.length(); + if (length > MAX_PREVIEW) { + length = 200; + } + String commentPreviewContent = commentContent.substring(0, length); + commentContent = Html2TextUtil.getContent(commentPreviewContent); + // 判断是否是回复消息 + if (commentEvent.getCommentOriginalCommentId() != null && commentEvent.getCommentOriginalCommentId() != 0) { + Comment originalComment = commentMapper.selectByPrimaryKey(commentEvent.getCommentOriginalCommentId()); + // 回复消息时,评论者不是上级评论作者则进行消息通知 + if (!commentEvent.getCommentAuthorId().equals(originalComment.getCommentAuthorId())) { + NotificationUtils.saveNotification(originalComment.getCommentAuthorId(), commentEvent.getIdComment(), NotificationConstant.Comment, commentContent); + } + } else { + // 评论者不是作者本人则进行消息通知 + if (!commentEvent.getCommentAuthorId().equals(commentEvent.getArticleAuthorId())) { + NotificationUtils.saveNotification(commentEvent.getArticleAuthorId(), commentEvent.getIdComment(), NotificationConstant.Comment, commentContent); + } + } + } +} diff --git a/src/main/java/com/rymcu/forest/handler/event/AccountEvent.java b/src/main/java/com/rymcu/forest/handler/event/AccountEvent.java new file mode 100644 index 0000000..dfdc955 --- /dev/null +++ b/src/main/java/com/rymcu/forest/handler/event/AccountEvent.java @@ -0,0 +1,19 @@ +package com.rymcu.forest.handler.event; + +import lombok.AllArgsConstructor; +import lombok.Data; + +/** + * Created on 2022/8/24 14:45. + * + * @author ronger + * @email ronger-x@outlook.com + * @packageName com.rymcu.forest.handler.event + */ +@Data +@AllArgsConstructor +public class AccountEvent { + + private String account; + +} diff --git a/src/main/java/com/rymcu/forest/handler/event/ArticleDeleteEvent.java b/src/main/java/com/rymcu/forest/handler/event/ArticleDeleteEvent.java new file mode 100644 index 0000000..c44b34c --- /dev/null +++ b/src/main/java/com/rymcu/forest/handler/event/ArticleDeleteEvent.java @@ -0,0 +1,18 @@ +package com.rymcu.forest.handler.event; + +import lombok.AllArgsConstructor; +import lombok.Data; + +/** + * Created on 2022/8/20 18:51. + * + * @author ronger + * @email ronger-x@outlook.com + */ +@Data +@AllArgsConstructor +public class ArticleDeleteEvent { + + private Long idArticle; + +} diff --git a/src/main/java/com/rymcu/forest/handler/event/ArticleEvent.java b/src/main/java/com/rymcu/forest/handler/event/ArticleEvent.java new file mode 100644 index 0000000..57940d2 --- /dev/null +++ b/src/main/java/com/rymcu/forest/handler/event/ArticleEvent.java @@ -0,0 +1,27 @@ +package com.rymcu.forest.handler.event; + +import lombok.AllArgsConstructor; +import lombok.Data; + +/** + * Created on 2022/8/16 20:56. + * + * @author ronger + * @email ronger-x@outlook.com + */ +@Data +@AllArgsConstructor +public class ArticleEvent { + + private Long idArticle; + + private String articleTitle; + + private Boolean isUpdate; + + private Boolean notification; + + private String nickname; + + private Long articleAuthorId; +} diff --git a/src/main/java/com/rymcu/forest/handler/event/CommentEvent.java b/src/main/java/com/rymcu/forest/handler/event/CommentEvent.java new file mode 100644 index 0000000..2599006 --- /dev/null +++ b/src/main/java/com/rymcu/forest/handler/event/CommentEvent.java @@ -0,0 +1,26 @@ +package com.rymcu.forest.handler.event; + +import lombok.AllArgsConstructor; +import lombok.Data; + +/** + * Created on 2022/8/17 7:43. + * + * @author ronger + * @email ronger-x@outlook.com + * @packageName com.rymcu.forest.handler.event + */ +@Data +@AllArgsConstructor +public class CommentEvent { + + private Long idComment; + + private Long articleAuthorId; + + private Long commentAuthorId; + + private String content; + + private Long commentOriginalCommentId; +} diff --git a/src/main/java/com/rymcu/forest/jwt/service/RedisTokenManager.java b/src/main/java/com/rymcu/forest/jwt/service/RedisTokenManager.java index 4387a84..a409a01 100644 --- a/src/main/java/com/rymcu/forest/jwt/service/RedisTokenManager.java +++ b/src/main/java/com/rymcu/forest/jwt/service/RedisTokenManager.java @@ -1,13 +1,14 @@ package com.rymcu.forest.jwt.service; +import com.rymcu.forest.handler.event.AccountEvent; import com.rymcu.forest.jwt.def.JwtConstants; import com.rymcu.forest.jwt.model.TokenModel; -import com.rymcu.forest.service.UserService; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationEventPublisher; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; @@ -27,7 +28,7 @@ public class RedisTokenManager implements TokenManager { @Autowired private StringRedisTemplate redisTemplate; @Resource - private UserService userService; + private ApplicationEventPublisher applicationEventPublisher; /** * 生成TOKEN @@ -62,7 +63,7 @@ public class RedisTokenManager implements TokenManager { String result = redisTemplate.boundValueOps(key.toString()).get(); if (StringUtils.isBlank(result)) { // 更新最后在线时间 - userService.updateLastOnlineTimeByEmail(model.getUsername()); + applicationEventPublisher.publishEvent(new AccountEvent(model.getUsername())); redisTemplate.boundValueOps(key.toString()).set(LocalDateTime.now().toString(), JwtConstants.LAST_ONLINE_EXPIRES_MINUTE, TimeUnit.MINUTES); } return true; diff --git a/src/main/java/com/rymcu/forest/lucene/api/LuceneSearchController.java b/src/main/java/com/rymcu/forest/lucene/api/LuceneSearchController.java index 80350c1..baebd86 100755 --- a/src/main/java/com/rymcu/forest/lucene/api/LuceneSearchController.java +++ b/src/main/java/com/rymcu/forest/lucene/api/LuceneSearchController.java @@ -99,7 +99,7 @@ public class LuceneSearchController { int endIndex = Math.min(startIndex + rows, total); // 分割子列表 List subList = resList.subList(startIndex, endIndex); - String[] ids = subList.stream().map(ArticleLucene::getIdArticle).toArray(String[]::new); + Long[] ids = subList.stream().map(ArticleLucene::getIdArticle).toArray(Long[]::new); List articleDTOList = luceneService.getArticlesByIds(ids); ArticleDTO temp; // 写入文章关键词信息 @@ -114,7 +114,7 @@ public class LuceneSearchController { } articles.addAll(articleDTOList); PageInfo pageInfo = new PageInfo<>(articles); - return GlobalResultGenerator.genSuccessResult(Utils.getArticlesGlobalResult(pageInfo)); + return GlobalResultGenerator.genSuccessResult(pageInfo); } /** @@ -141,7 +141,7 @@ public class LuceneSearchController { int endIndex = Math.min(startIndex + rows, total); // 分割子列表 List subList = resList.subList(startIndex, endIndex); - Integer[] ids = subList.stream().map(UserLucene::getIdUser).toArray(Integer[]::new); + Long[] ids = subList.stream().map(UserLucene::getIdUser).toArray(Long[]::new); List userDTOList = userLuceneService.getUsersByIds(ids); UserDTO temp; // 写入文章关键词信息 @@ -156,7 +156,7 @@ public class LuceneSearchController { } users.addAll(userDTOList); PageInfo pageInfo = new PageInfo<>(users); - return GlobalResultGenerator.genSuccessResult(Utils.getUserGlobalResult(pageInfo)); + return GlobalResultGenerator.genSuccessResult(pageInfo); } /** @@ -183,7 +183,7 @@ public class LuceneSearchController { int endIndex = Math.min(startIndex + rows, total); // 分割子列表 List subList = resList.subList(startIndex, endIndex); - String[] ids = subList.stream().map(PortfolioLucene::getIdPortfolio).toArray(String[]::new); + Long[] ids = subList.stream().map(PortfolioLucene::getIdPortfolio).toArray(Long[]::new); List portfolioDTOList = portfolioLuceneService.getPortfoliosByIds(ids); PortfolioDTO temp; // 写入文章关键词信息 @@ -198,6 +198,6 @@ public class LuceneSearchController { } portfolios.addAll(portfolioDTOList); PageInfo pageInfo = new PageInfo<>(portfolios); - return GlobalResultGenerator.genSuccessResult(Utils.getPortfolioGlobalResult(pageInfo)); + return GlobalResultGenerator.genSuccessResult(pageInfo); } } diff --git a/src/main/java/com/rymcu/forest/lucene/mapper/ArticleLuceneMapper.java b/src/main/java/com/rymcu/forest/lucene/mapper/ArticleLuceneMapper.java index 88f3f5c..6ecb2a3 100755 --- a/src/main/java/com/rymcu/forest/lucene/mapper/ArticleLuceneMapper.java +++ b/src/main/java/com/rymcu/forest/lucene/mapper/ArticleLuceneMapper.java @@ -29,7 +29,7 @@ public interface ArticleLuceneMapper { * @param ids 文章id(半角逗号分隔) * @return */ - List getArticlesByIds(@Param("ids") String[] ids); + List getArticlesByIds(@Param("ids") Long[] ids); /** @@ -38,6 +38,6 @@ public interface ArticleLuceneMapper { * @param id 文章id * @return */ - ArticleLucene getById(@Param("id") String id); + ArticleLucene getById(@Param("id") Long id); } diff --git a/src/main/java/com/rymcu/forest/lucene/mapper/PortfolioLuceneMapper.java b/src/main/java/com/rymcu/forest/lucene/mapper/PortfolioLuceneMapper.java index cf9ac13..b75a7a4 100644 --- a/src/main/java/com/rymcu/forest/lucene/mapper/PortfolioLuceneMapper.java +++ b/src/main/java/com/rymcu/forest/lucene/mapper/PortfolioLuceneMapper.java @@ -32,7 +32,7 @@ public interface PortfolioLuceneMapper { * @param ids 作品集id(半角逗号分隔) * @return */ - List getPortfoliosByIds(@Param("ids") String[] ids); + List getPortfoliosByIds(@Param("ids") Long[] ids); /** * 加载作品集 @@ -40,5 +40,5 @@ public interface PortfolioLuceneMapper { * @param id 用户id * @return */ - PortfolioLucene getById(@Param("id") String id); + PortfolioLucene getById(@Param("id") Long id); } diff --git a/src/main/java/com/rymcu/forest/lucene/mapper/UserLuceneMapper.java b/src/main/java/com/rymcu/forest/lucene/mapper/UserLuceneMapper.java index 9e0bbf4..ad84019 100644 --- a/src/main/java/com/rymcu/forest/lucene/mapper/UserLuceneMapper.java +++ b/src/main/java/com/rymcu/forest/lucene/mapper/UserLuceneMapper.java @@ -29,7 +29,7 @@ public interface UserLuceneMapper { * @param ids 用户id(半角逗号分隔) * @return */ - List getUsersByIds(@Param("ids") Integer[] ids); + List getUsersByIds(@Param("ids") Long[] ids); /** * 加载 UserLucene diff --git a/src/main/java/com/rymcu/forest/lucene/model/ArticleLucene.java b/src/main/java/com/rymcu/forest/lucene/model/ArticleLucene.java index c8b8015..125cb11 100644 --- a/src/main/java/com/rymcu/forest/lucene/model/ArticleLucene.java +++ b/src/main/java/com/rymcu/forest/lucene/model/ArticleLucene.java @@ -1,5 +1,6 @@ package com.rymcu.forest.lucene.model; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -20,7 +21,8 @@ import javax.persistence.Id; public class ArticleLucene { /** 文章编号 */ - private String idArticle; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idArticle; /** 文章标题 */ private String articleTitle; diff --git a/src/main/java/com/rymcu/forest/lucene/model/PortfolioLucene.java b/src/main/java/com/rymcu/forest/lucene/model/PortfolioLucene.java index 8eabbc5..81d6b58 100644 --- a/src/main/java/com/rymcu/forest/lucene/model/PortfolioLucene.java +++ b/src/main/java/com/rymcu/forest/lucene/model/PortfolioLucene.java @@ -1,5 +1,6 @@ package com.rymcu.forest.lucene.model; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -18,7 +19,8 @@ import lombok.NoArgsConstructor; public class PortfolioLucene { /** 作品集编号 */ - private String idPortfolio; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idPortfolio; /** 作品集名称 */ private String portfolioTitle; diff --git a/src/main/java/com/rymcu/forest/lucene/model/UserLucene.java b/src/main/java/com/rymcu/forest/lucene/model/UserLucene.java index 6946e33..708494a 100644 --- a/src/main/java/com/rymcu/forest/lucene/model/UserLucene.java +++ b/src/main/java/com/rymcu/forest/lucene/model/UserLucene.java @@ -1,5 +1,6 @@ package com.rymcu.forest.lucene.model; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -22,7 +23,8 @@ import javax.persistence.Column; public class UserLucene { /** 用户编号 */ - private Integer idUser; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idUser; /** 昵称 */ private String nickname; diff --git a/src/main/java/com/rymcu/forest/lucene/service/LuceneService.java b/src/main/java/com/rymcu/forest/lucene/service/LuceneService.java index f83e659..6e9c6d7 100644 --- a/src/main/java/com/rymcu/forest/lucene/service/LuceneService.java +++ b/src/main/java/com/rymcu/forest/lucene/service/LuceneService.java @@ -25,7 +25,7 @@ public interface LuceneService { * * @param id */ - void writeArticle(String id); + void writeArticle(Long id); /** @@ -40,14 +40,14 @@ public interface LuceneService { * * @param id */ - void updateArticle(String id); + void updateArticle(Long id); /** * 删除单个文章索引 * * @param id */ - void deleteArticle(String id); + void deleteArticle(Long id); /** * 关键词搜索 @@ -71,5 +71,5 @@ public interface LuceneService { * @param ids 文章id(半角逗号分隔) * @return */ - List getArticlesByIds(String[] ids); + List getArticlesByIds(Long[] ids); } diff --git a/src/main/java/com/rymcu/forest/lucene/service/PortfolioLuceneService.java b/src/main/java/com/rymcu/forest/lucene/service/PortfolioLuceneService.java index cb54e09..e532548 100644 --- a/src/main/java/com/rymcu/forest/lucene/service/PortfolioLuceneService.java +++ b/src/main/java/com/rymcu/forest/lucene/service/PortfolioLuceneService.java @@ -25,7 +25,7 @@ public interface PortfolioLuceneService { * * @param id */ - void writePortfolio(String id); + void writePortfolio(Long id); /** * 写入单个作品集索引 @@ -39,14 +39,14 @@ public interface PortfolioLuceneService { * * @param id */ - void updatePortfolio(String id); + void updatePortfolio(Long id); /** * 删除单个作品集索引 * * @param id */ - void deletePortfolio(String id); + void deletePortfolio(Long id); /** * 关键词搜索 @@ -70,5 +70,5 @@ public interface PortfolioLuceneService { * @param ids 作品集id(半角逗号分隔) * @return */ - List getPortfoliosByIds(String[] ids); + List getPortfoliosByIds(Long[] ids); } diff --git a/src/main/java/com/rymcu/forest/lucene/service/UserLuceneService.java b/src/main/java/com/rymcu/forest/lucene/service/UserLuceneService.java index a04670e..fd2c6bd 100644 --- a/src/main/java/com/rymcu/forest/lucene/service/UserLuceneService.java +++ b/src/main/java/com/rymcu/forest/lucene/service/UserLuceneService.java @@ -70,5 +70,5 @@ public interface UserLuceneService { * @param ids 用户id(半角逗号分隔) * @return */ - List getUsersByIds(Integer[] ids); + List getUsersByIds(Long[] ids); } diff --git a/src/main/java/com/rymcu/forest/lucene/service/impl/LuceneServiceImpl.java b/src/main/java/com/rymcu/forest/lucene/service/impl/LuceneServiceImpl.java index ed6cbc2..72f4a79 100644 --- a/src/main/java/com/rymcu/forest/lucene/service/impl/LuceneServiceImpl.java +++ b/src/main/java/com/rymcu/forest/lucene/service/impl/LuceneServiceImpl.java @@ -3,8 +3,6 @@ package com.rymcu.forest.lucene.service.impl; import com.rymcu.forest.dto.ArticleDTO; import com.rymcu.forest.dto.ArticleTagDTO; import com.rymcu.forest.dto.Author; -import com.rymcu.forest.dto.PortfolioArticleDTO; -import com.rymcu.forest.entity.ArticleContent; import com.rymcu.forest.entity.User; import com.rymcu.forest.lucene.lucene.ArticleBeanIndex; import com.rymcu.forest.lucene.lucene.IKAnalyzer; @@ -67,6 +65,7 @@ public class LuceneServiceImpl implements LuceneService { try { int totalCount = list.size(); int perThreadCount = 3000; + // 加1避免线程池的参数为0 int threadCount = totalCount / perThreadCount + (totalCount % perThreadCount == 0 ? 0 : 1); ExecutorService pool = Executors.newFixedThreadPool(threadCount); CountDownLatch countDownLatch1 = new CountDownLatch(1); @@ -96,7 +95,7 @@ public class LuceneServiceImpl implements LuceneService { } @Override - public void writeArticle(String id) { + public void writeArticle(Long id) { writeArticle(luceneMapper.getById(id)); } @@ -106,12 +105,12 @@ public class LuceneServiceImpl implements LuceneService { } @Override - public void updateArticle(String id) { + public void updateArticle(Long id) { ArticleIndexUtil.updateIndex(luceneMapper.getById(id)); } @Override - public void deleteArticle(String id) { + public void deleteArticle(Long id) { ArticleIndexUtil.deleteIndex(id); } @@ -156,12 +155,11 @@ public class LuceneServiceImpl implements LuceneService { float score = hit.score; Document hitDoc = searcher.doc(hit.doc); // 获取到summary - String name = hitDoc.get("summary"); + String summary = hitDoc.get("summary"); // 将查询的词和搜索词匹配,匹配到添加前缀和后缀 - TokenStream tokenStream = - TokenSources.getAnyTokenStream(searcher.getIndexReader(), id, "summary", analyzer); + TokenStream tokenStream = TokenSources.getTokenStream("summary", searcher.getIndexReader().getTermVectors(id), summary, analyzer, -1); // 传入的第二个参数是查询的值 - TextFragment[] frag = highlighter.getBestTextFragments(tokenStream, name, false, 10); + TextFragment[] frag = highlighter.getBestTextFragments(tokenStream, summary, false, 10); StringBuilder baikeValue = new StringBuilder(); for (TextFragment textFragment : frag) { if ((textFragment != null) && (textFragment.getScore() > 0)) { @@ -173,8 +171,7 @@ public class LuceneServiceImpl implements LuceneService { // 获取到title String title = hitDoc.get("title"); - TokenStream titleTokenStream = - TokenSources.getAnyTokenStream(searcher.getIndexReader(), id, "title", analyzer); + TokenStream titleTokenStream = TokenSources.getTokenStream("title", searcher.getIndexReader().getTermVectors(id), title, analyzer, -1); TextFragment[] titleFrag = highlighter.getBestTextFragments(titleTokenStream, title, false, 10); StringBuilder titleValue = new StringBuilder(); @@ -185,7 +182,7 @@ public class LuceneServiceImpl implements LuceneService { } resList.add( ArticleLucene.builder() - .idArticle(hitDoc.get("id")) + .idArticle(Long.valueOf(hitDoc.get("id"))) .articleTitle(titleValue.toString()) .articleContent(baikeValue.toString()) .score(String.valueOf(score)) @@ -209,9 +206,9 @@ public class LuceneServiceImpl implements LuceneService { } @Override - public List getArticlesByIds(String[] ids) { + public List getArticlesByIds(Long[] ids) { List list = luceneMapper.getArticlesByIds(ids); - list.forEach(articleDTO -> genArticle(articleDTO)); + list.forEach(this::genArticle); return list; } diff --git a/src/main/java/com/rymcu/forest/lucene/service/impl/PortfolioLuceneServiceImpl.java b/src/main/java/com/rymcu/forest/lucene/service/impl/PortfolioLuceneServiceImpl.java index 430969a..07bc0ee 100644 --- a/src/main/java/com/rymcu/forest/lucene/service/impl/PortfolioLuceneServiceImpl.java +++ b/src/main/java/com/rymcu/forest/lucene/service/impl/PortfolioLuceneServiceImpl.java @@ -41,150 +41,150 @@ import java.util.concurrent.Executors; @Service public class PortfolioLuceneServiceImpl implements PortfolioLuceneService { - @Resource private PortfolioLuceneMapper portfolioLuceneMapper; + @Resource + private PortfolioLuceneMapper portfolioLuceneMapper; - /** - * 将文章的数据解析为一个个关键字词存储到索引文件中 - * - * @param list - */ - @Override - public void writePortfolio(List list) { - try { - int totalCount = list.size(); - int perThreadCount = 3000; - int threadCount = totalCount / perThreadCount + (totalCount % perThreadCount == 0 ? 0 : 1); - ExecutorService pool = Executors.newFixedThreadPool(threadCount); - CountDownLatch countDownLatch1 = new CountDownLatch(1); - CountDownLatch countDownLatch2 = new CountDownLatch(threadCount); + /** + * 将文章的数据解析为一个个关键字词存储到索引文件中 + * + * @param list + */ + @Override + public void writePortfolio(List list) { + try { + int totalCount = list.size(); + int perThreadCount = 3000; + // 加1避免线程池的参数为0 + int threadCount = totalCount / perThreadCount + (totalCount % perThreadCount == 0 ? 0 : 1); + ExecutorService pool = Executors.newFixedThreadPool(threadCount); + CountDownLatch countDownLatch1 = new CountDownLatch(1); + CountDownLatch countDownLatch2 = new CountDownLatch(threadCount); - for (int i = 0; i < threadCount; i++) { - int start = i * perThreadCount; - int end = Math.min((i + 1) * perThreadCount, totalCount); - List subList = list.subList(start, end); - Runnable runnable = - new PortfolioBeanIndex(LucenePath.PORTFOLIO_PATH, i, countDownLatch1, countDownLatch2, subList); - // 子线程交给线程池管理 - pool.execute(runnable); - } - countDownLatch1.countDown(); - System.out.println("开始创建索引"); - // 等待所有线程都完成 - countDownLatch2.await(); - // 线程全部完成工作 - System.out.println("所有线程都创建索引完毕"); - // 释放线程池资源 - pool.shutdown(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Override - public void writePortfolio(String id) { - writePortfolio(portfolioLuceneMapper.getById(id)); - } - - @Override - public void writePortfolio(PortfolioLucene portfolioLucene) { - PortfolioIndexUtil.addIndex(portfolioLucene); - } - - - @Override - public void updatePortfolio(String id) { - PortfolioIndexUtil.updateIndex(portfolioLuceneMapper.getById(id)); - } - - @Override - public void deletePortfolio(String id) { - PortfolioIndexUtil.deleteIndex(id); - } - - @Override - public List getAllPortfolioLucene() { - return portfolioLuceneMapper.getAllPortfolioLucene(); - } - - @Override - public List getPortfoliosByIds(String[] ids) { - return portfolioLuceneMapper.getPortfoliosByIds(ids); - } - - @Override - public List searchPortfolio(String value) { - List resList = new ArrayList<>(); - ExecutorService service = Executors.newCachedThreadPool(); - // 定义分词器 - Analyzer analyzer = new IKAnalyzer(); - try { - IndexSearcher searcher = SearchUtil.getIndexSearcherByParentPath(LucenePath.PORTFOLIO_PATH, service); - String[] fields = {"title", "summary"}; - // 构造Query对象 - MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer); - - BufferedReader in = - new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); - String line = value != null ? value : in.readLine(); - Query query = parser.parse(line); - // 最终被分词后添加的前缀和后缀处理器,默认是粗体 - SimpleHTMLFormatter htmlFormatter = - new SimpleHTMLFormatter("", ""); - // 高亮搜索的词添加到高亮处理器中 - Highlighter highlighter = new Highlighter(htmlFormatter, new QueryScorer(query)); - - // 获取搜索的结果,指定返回document返回的个数 - // TODO 默认搜索结果为显示第一页,1000 条,可以优化 - TopDocs results = SearchUtil.getScoreDocsByPerPage(1, 100, searcher, query); - ScoreDoc[] hits = results.scoreDocs; - - // 遍历,输出 - for (ScoreDoc hit : hits) { - int id = hit.doc; - float score = hit.score; - Document hitDoc = searcher.doc(hit.doc); - // 获取到summary - String summary = hitDoc.get("summary"); - // 将查询的词和搜索词匹配,匹配到添加前缀和后缀 - TokenStream tokenStream = - TokenSources.getAnyTokenStream(searcher.getIndexReader(), id, "summary", analyzer); - // 传入的第二个参数是查询的值 - TextFragment[] frag = highlighter.getBestTextFragments(tokenStream, summary, false, 10); - StringBuilder sb = new StringBuilder(); - for (TextFragment textFragment : frag) { - if ((textFragment != null) && (textFragment.getScore() > 0)) { - // if ((frag[j] != null)) { - // 获取 summary 的值 - sb.append(textFragment.toString()); - } + for (int i = 0; i < threadCount; i++) { + int start = i * perThreadCount; + int end = Math.min((i + 1) * perThreadCount, totalCount); + List subList = list.subList(start, end); + Runnable runnable = + new PortfolioBeanIndex(LucenePath.PORTFOLIO_PATH, i, countDownLatch1, countDownLatch2, subList); + // 子线程交给线程池管理 + pool.execute(runnable); + } + countDownLatch1.countDown(); + System.out.println("开始创建索引"); + // 等待所有线程都完成 + countDownLatch2.await(); + // 线程全部完成工作 + System.out.println("所有线程都创建索引完毕"); + // 释放线程池资源 + pool.shutdown(); + } catch (Exception e) { + e.printStackTrace(); } - // 获取到title - String title = hitDoc.get("title"); - TokenStream titleTokenStream = - TokenSources.getAnyTokenStream(searcher.getIndexReader(), id, "title", analyzer); - TextFragment[] titleFrag = - highlighter.getBestTextFragments(titleTokenStream, title, false, 10); - StringBuilder titleValue = new StringBuilder(); - for (int j = 0; j < titleFrag.length; j++) { - if ((frag[j] != null)) { - titleValue.append(titleFrag[j].toString()); - } - } - resList.add( - PortfolioLucene.builder() - .idPortfolio(hitDoc.get("id")) - .portfolioTitle(titleValue.toString()) - .portfolioDescription(sb.toString()) - .score(String.valueOf(score)) - .build()); - } - } catch (IOException | ParseException | InvalidTokenOffsetsException e) { - System.out.println(e.getMessage()); - e.printStackTrace(); - } finally { - service.shutdownNow(); } - return resList; - } + + @Override + public void writePortfolio(Long id) { + writePortfolio(portfolioLuceneMapper.getById(id)); + } + + @Override + public void writePortfolio(PortfolioLucene portfolioLucene) { + PortfolioIndexUtil.addIndex(portfolioLucene); + } + + + @Override + public void updatePortfolio(Long id) { + PortfolioIndexUtil.updateIndex(portfolioLuceneMapper.getById(id)); + } + + @Override + public void deletePortfolio(Long id) { + PortfolioIndexUtil.deleteIndex(id); + } + + @Override + public List getAllPortfolioLucene() { + return portfolioLuceneMapper.getAllPortfolioLucene(); + } + + @Override + public List getPortfoliosByIds(Long[] ids) { + return portfolioLuceneMapper.getPortfoliosByIds(ids); + } + + @Override + public List searchPortfolio(String value) { + List resList = new ArrayList<>(); + ExecutorService service = Executors.newCachedThreadPool(); + // 定义分词器 + Analyzer analyzer = new IKAnalyzer(); + try { + IndexSearcher searcher = SearchUtil.getIndexSearcherByParentPath(LucenePath.PORTFOLIO_PATH, service); + String[] fields = {"title", "summary"}; + // 构造Query对象 + MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer); + + BufferedReader in = + new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); + String line = value != null ? value : in.readLine(); + Query query = parser.parse(line); + // 最终被分词后添加的前缀和后缀处理器,默认是粗体 + SimpleHTMLFormatter htmlFormatter = + new SimpleHTMLFormatter("", ""); + // 高亮搜索的词添加到高亮处理器中 + Highlighter highlighter = new Highlighter(htmlFormatter, new QueryScorer(query)); + + // 获取搜索的结果,指定返回document返回的个数 + // TODO 默认搜索结果为显示第一页,1000 条,可以优化 + TopDocs results = SearchUtil.getScoreDocsByPerPage(1, 100, searcher, query); + ScoreDoc[] hits = results.scoreDocs; + + // 遍历,输出 + for (ScoreDoc hit : hits) { + int id = hit.doc; + float score = hit.score; + Document hitDoc = searcher.doc(hit.doc); + // 获取到summary + String summary = hitDoc.get("summary"); + // 将查询的词和搜索词匹配,匹配到添加前缀和后缀 + TokenStream tokenStream = TokenSources.getTokenStream("summary", searcher.getIndexReader().getTermVectors(id), summary, analyzer, -1); + // 传入的第二个参数是查询的值 + TextFragment[] frag = highlighter.getBestTextFragments(tokenStream, summary, false, 10); + StringBuilder sb = new StringBuilder(); + for (TextFragment textFragment : frag) { + if ((textFragment != null) && (textFragment.getScore() > 0)) { + // if ((frag[j] != null)) { + // 获取 summary 的值 + sb.append(textFragment); + } + } + // 获取到title + String title = hitDoc.get("title"); + TokenStream titleTokenStream = TokenSources.getTokenStream("title", searcher.getIndexReader().getTermVectors(id), title, analyzer, -1); + TextFragment[] titleFrag = + highlighter.getBestTextFragments(titleTokenStream, title, false, 10); + StringBuilder titleValue = new StringBuilder(); + for (int j = 0; j < titleFrag.length; j++) { + if ((frag[j] != null)) { + titleValue.append(titleFrag[j].toString()); + } + } + resList.add( + PortfolioLucene.builder() + .idPortfolio(Long.valueOf(hitDoc.get("id"))) + .portfolioTitle(titleValue.toString()) + .portfolioDescription(sb.toString()) + .score(String.valueOf(score)) + .build()); + } + } catch (IOException | ParseException | InvalidTokenOffsetsException e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } finally { + service.shutdownNow(); + } + return resList; + } } diff --git a/src/main/java/com/rymcu/forest/lucene/service/impl/UserLuceneServiceImpl.java b/src/main/java/com/rymcu/forest/lucene/service/impl/UserLuceneServiceImpl.java index a251cd5..78c8a9f 100644 --- a/src/main/java/com/rymcu/forest/lucene/service/impl/UserLuceneServiceImpl.java +++ b/src/main/java/com/rymcu/forest/lucene/service/impl/UserLuceneServiceImpl.java @@ -133,13 +133,13 @@ public class UserLuceneServiceImpl implements UserLuceneService { int id = hit.doc; float score = hit.score; Document hitDoc = searcher.doc(hit.doc); - // 获取到summary - String name = hitDoc.get("signature"); + // 获取到 signature + String signature = hitDoc.get("signature"); // 将查询的词和搜索词匹配,匹配到添加前缀和后缀 - TokenStream tokenStream = - TokenSources.getAnyTokenStream(searcher.getIndexReader(), id, "signature", analyzer); + TokenStream tokenStream = TokenSources.getTokenStream("signature", searcher.getIndexReader().getTermVectors(id), signature, analyzer, -1); + // 传入的第二个参数是查询的值 - TextFragment[] frag = highlighter.getBestTextFragments(tokenStream, name, false, 10); + TextFragment[] frag = highlighter.getBestTextFragments(tokenStream, signature, false, 10); StringBuilder baikeValue = new StringBuilder(); for (TextFragment textFragment : frag) { if ((textFragment != null) && (textFragment.getScore() > 0)) { @@ -148,12 +148,11 @@ public class UserLuceneServiceImpl implements UserLuceneService { baikeValue.append(textFragment.toString()); } } - // 获取到title - String title = hitDoc.get("nickname"); - TokenStream titleTokenStream = - TokenSources.getAnyTokenStream(searcher.getIndexReader(), id, "nickname", analyzer); + // 获取到 nickname + String nickname = hitDoc.get("nickname"); + TokenStream titleTokenStream = TokenSources.getTokenStream("nickname", searcher.getIndexReader().getTermVectors(id), nickname, analyzer, -1); TextFragment[] titleFrag = - highlighter.getBestTextFragments(titleTokenStream, title, false, 10); + highlighter.getBestTextFragments(titleTokenStream, nickname, false, 10); StringBuilder titleValue = new StringBuilder(); for (int j = 0; j < titleFrag.length; j++) { if ((frag[j] != null)) { @@ -162,7 +161,7 @@ public class UserLuceneServiceImpl implements UserLuceneService { } resList.add( UserLucene.builder() - .idUser(Integer.valueOf(hitDoc.get("id"))) + .idUser(Long.valueOf(hitDoc.get("id"))) .nickname(titleValue.toString()) .signature(baikeValue.toString()) .score(String.valueOf(score)) @@ -183,7 +182,7 @@ public class UserLuceneServiceImpl implements UserLuceneService { } @Override - public List getUsersByIds(Integer[] ids) { + public List getUsersByIds(Long[] ids) { return userLuceneMapper.getUsersByIds(ids); } } diff --git a/src/main/java/com/rymcu/forest/lucene/util/ArticleIndexUtil.java b/src/main/java/com/rymcu/forest/lucene/util/ArticleIndexUtil.java index 0e6b12c..eaeb772 100644 --- a/src/main/java/com/rymcu/forest/lucene/util/ArticleIndexUtil.java +++ b/src/main/java/com/rymcu/forest/lucene/util/ArticleIndexUtil.java @@ -1,7 +1,6 @@ package com.rymcu.forest.lucene.util; import cn.hutool.core.io.FileUtil; -import cn.hutool.core.util.StrUtil; import com.rymcu.forest.lucene.model.ArticleLucene; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; @@ -12,6 +11,7 @@ import org.apache.lucene.index.Term; import java.io.IOException; import java.util.Arrays; +import java.util.concurrent.locks.ReentrantLock; /** * 文章索引更新工具类 @@ -20,65 +20,85 @@ import java.util.Arrays; */ public class ArticleIndexUtil { - /** lucene索引保存目录 */ - private static final String PATH = - System.getProperty("user.dir") + StrUtil.SLASH + LucenePath.ARTICLE_INDEX_PATH; + /** + * lucene索引保存目录 + */ + private static final String PATH = + System.getProperty("user.dir") + LucenePath.ARTICLE_INDEX_PATH; - /** 删除所有运行中保存的索引 */ - public static void deleteAllIndex() { - if (FileUtil.exist(LucenePath.ARTICLE_INCREMENT_INDEX_PATH)) { - FileUtil.del(LucenePath.ARTICLE_INCREMENT_INDEX_PATH); + /** + * 删除所有运行中保存的索引 + */ + public static void deleteAllIndex() { + if (FileUtil.exist(LucenePath.ARTICLE_INCREMENT_INDEX_PATH)) { + FileUtil.del(LucenePath.ARTICLE_INCREMENT_INDEX_PATH); + } } - } - public static void addIndex(ArticleLucene t) { - creatIndex(t); - } - - public static void updateIndex(ArticleLucene t) { - deleteIndex(t.getIdArticle()); - creatIndex(t); - } - - /** - * 增加或创建单个索引 - * - * @param t - * @throws Exception - */ - private static synchronized void creatIndex(ArticleLucene t) { - System.out.println("创建单个索引"); - IndexWriter writer; - try { - writer = IndexUtil.getIndexWriter(LucenePath.ARTICLE_INCREMENT_INDEX_PATH, false); - Document doc = new Document(); - doc.add(new StringField("id", t.getIdArticle() + "", Field.Store.YES)); - doc.add(new TextField("title", t.getArticleTitle(), Field.Store.YES)); - doc.add(new TextField("summary", t.getArticleContent(), Field.Store.YES)); - writer.addDocument(doc); - writer.close(); - } catch (IOException e) { - e.printStackTrace(); + public static void addIndex(ArticleLucene t) { + creatIndex(t); } - } - /** 删除单个索引 */ - public static synchronized void deleteIndex(String id) { - Arrays.stream(FileUtil.ls(PATH)) - .forEach( - each -> { - if (each.isDirectory()) { - IndexWriter writer; - try { - writer = IndexUtil.getIndexWriter(each.getAbsolutePath(), false); - writer.deleteDocuments(new Term("id", id)); - writer.forceMergeDeletes(); // 强制删除 - writer.commit(); - writer.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - }); - } + public static void updateIndex(ArticleLucene t) { + deleteIndex(t.getIdArticle()); + creatIndex(t); + } + + /** + * 增加或创建单个索引 + * + * @param t + * @throws Exception + */ + private static void creatIndex(ArticleLucene t) { + System.out.printf("创建单个索引"); + IndexWriter writer; + ReentrantLock reentrantLock = new ReentrantLock(); + reentrantLock.lock(); + try { + boolean create = true; + if (FileUtil.exist(LucenePath.ARTICLE_INCREMENT_INDEX_PATH)) { + create = false; + } + writer = IndexUtil.getIndexWriter(LucenePath.ARTICLE_INCREMENT_INDEX_PATH, create); + Document doc = new Document(); + doc.add(new StringField("id", t.getIdArticle() + "", Field.Store.YES)); + doc.add(new TextField("title", t.getArticleTitle(), Field.Store.YES)); + doc.add(new TextField("summary", t.getArticleContent(), Field.Store.YES)); + writer.addDocument(doc); + writer.close(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + reentrantLock.unlock(); + } + } + + /** + * 删除单个索引 + */ + public static void deleteIndex(Long id) { + Arrays.stream(FileUtil.ls(PATH)) + .forEach( + each -> { + if (each.isDirectory()) { + IndexWriter writer; + ReentrantLock reentrantLock = new ReentrantLock(); + reentrantLock.lock(); + try { + writer = IndexUtil.getIndexWriter(each.getAbsolutePath(), false); + writer.deleteDocuments(new Term("id", String.valueOf(id))); + writer.forceMerge(1); + // 强制删除 + writer.forceMergeDeletes(); + writer.commit(); + writer.close(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + reentrantLock.unlock(); + } + } + }); + } } diff --git a/src/main/java/com/rymcu/forest/lucene/util/LucenePath.java b/src/main/java/com/rymcu/forest/lucene/util/LucenePath.java index 234aeb3..0595bd0 100644 --- a/src/main/java/com/rymcu/forest/lucene/util/LucenePath.java +++ b/src/main/java/com/rymcu/forest/lucene/util/LucenePath.java @@ -8,7 +8,7 @@ package com.rymcu.forest.lucene.util; public final class LucenePath { /** lucene 目录 */ - public static final String INDEX_PATH = "lucene/index"; + public static final String INDEX_PATH = "/lucene/index"; /** 文章 lucene 目录 */ public static final String ARTICLE_INDEX_PATH = INDEX_PATH + "/article"; diff --git a/src/main/java/com/rymcu/forest/lucene/util/PortfolioIndexUtil.java b/src/main/java/com/rymcu/forest/lucene/util/PortfolioIndexUtil.java index 72e6589..a36cda4 100644 --- a/src/main/java/com/rymcu/forest/lucene/util/PortfolioIndexUtil.java +++ b/src/main/java/com/rymcu/forest/lucene/util/PortfolioIndexUtil.java @@ -63,7 +63,7 @@ public class PortfolioIndexUtil { } /** 删除单个索引 */ - public static synchronized void deleteIndex(String id) { + public static synchronized void deleteIndex(Long id) { Arrays.stream(FileUtil.ls(PATH)) .forEach( each -> { @@ -71,7 +71,7 @@ public class PortfolioIndexUtil { IndexWriter writer; try { writer = IndexUtil.getIndexWriter(each.getAbsolutePath(), false); - writer.deleteDocuments(new Term("id", id)); + writer.deleteDocuments(new Term("id", String.valueOf(id))); writer.forceMergeDeletes(); // 强制删除 writer.commit(); writer.close(); diff --git a/src/main/java/com/rymcu/forest/mapper/ArticleMapper.java b/src/main/java/com/rymcu/forest/mapper/ArticleMapper.java index 8ae9083..53aa3e5 100644 --- a/src/main/java/com/rymcu/forest/mapper/ArticleMapper.java +++ b/src/main/java/com/rymcu/forest/mapper/ArticleMapper.java @@ -30,7 +30,7 @@ public interface ArticleMapper extends Mapper

{ * @param type * @return */ - ArticleDTO selectArticleDTOById(@Param("id") Integer id, @Param("type") int type); + ArticleDTO selectArticleDTOById(@Param("id") Long id, @Param("type") int type); /** * 保存文章内容 @@ -39,7 +39,7 @@ public interface ArticleMapper extends Mapper
{ * @param articleContentHtml * @return */ - Integer insertArticleContent(@Param("idArticle") Integer idArticle, @Param("articleContent") String articleContent, @Param("articleContentHtml") String articleContentHtml); + Integer insertArticleContent(@Param("idArticle") Long idArticle, @Param("articleContent") String articleContent, @Param("articleContentHtml") String articleContentHtml); /** * 更新文章内容 @@ -48,14 +48,14 @@ public interface ArticleMapper extends Mapper
{ * @param articleContentHtml * @return */ - Integer updateArticleContent(@Param("idArticle") Integer idArticle, @Param("articleContent") String articleContent, @Param("articleContentHtml") String articleContentHtml); + Integer updateArticleContent(@Param("idArticle") Long idArticle, @Param("articleContent") String articleContent, @Param("articleContentHtml") String articleContentHtml); /** * 获取文章正文内容 * @param idArticle * @return */ - ArticleContent selectArticleContent(@Param("idArticle") Integer idArticle); + ArticleContent selectArticleContent(@Param("idArticle") Long idArticle); /** * 获取主题下文章列表 @@ -76,21 +76,21 @@ public interface ArticleMapper extends Mapper
{ * @param idUser * @return */ - List selectUserArticles(@Param("idUser") Integer idUser); + List selectUserArticles(@Param("idUser") Long idUser); /** * 删除文章标签 * @param id * @return */ - Integer deleteTagArticle(@Param("id") Integer id); + Integer deleteTagArticle(@Param("id") Long id); /** * 获取文章标签列表 * @param idArticle * @return */ - List selectTags(@Param("idArticle") Integer idArticle); + List selectTags(@Param("idArticle") Long idArticle); /** * 更新文章浏览数 @@ -98,28 +98,28 @@ public interface ArticleMapper extends Mapper
{ * @param articleViewCount * @return */ - Integer updateArticleViewCount(@Param("id") Integer id, @Param("articleViewCount") Integer articleViewCount); + Integer updateArticleViewCount(@Param("id") Long id, @Param("articleViewCount") Integer articleViewCount); /** * 获取草稿列表 * @param idUser * @return */ - List selectDrafts(@Param("idUser") Integer idUser); + List selectDrafts(@Param("idUser") Long idUser); /** * 删除未使用的文章标签 * @param idArticleTag * @return */ - Integer deleteUnusedArticleTag(@Param("idArticleTag") Integer idArticleTag); + Integer deleteUnusedArticleTag(@Param("idArticleTag") Long idArticleTag); /** * 查询作品集下文章 * @param idPortfolio * @return */ - List selectArticlesByIdPortfolio(@Param("idPortfolio") Integer idPortfolio); + List selectArticlesByIdPortfolio(@Param("idPortfolio") Long idPortfolio); /** * 查询作品集未绑定文章 @@ -128,14 +128,14 @@ public interface ArticleMapper extends Mapper
{ * @param idUser * @return */ - List selectUnbindArticlesByIdPortfolio(@Param("idPortfolio") Integer idPortfolio, @Param("searchText") String searchText, @Param("idUser") Integer idUser); + List selectUnbindArticlesByIdPortfolio(@Param("idPortfolio") Long idPortfolio, @Param("searchText") String searchText, @Param("idUser") Long idUser); /** * 查询文章所属作品集列表 * @param idArticle * @return */ - List selectPortfolioArticles(@Param("idArticle") Integer idArticle); + List selectPortfolioArticles(@Param("idArticle") Long idArticle); /** * 更新文章标签 @@ -143,21 +143,21 @@ public interface ArticleMapper extends Mapper
{ * @param tags * @return */ - Integer updateArticleTags(@Param("idArticle") Integer idArticle, @Param("tags") String tags); + Integer updateArticleTags(@Param("idArticle") Long idArticle, @Param("tags") String tags); /** * 判断是否有评论 * @param id * @return */ - boolean existsCommentWithPrimaryKey(@Param("id") Integer id); + boolean existsCommentWithPrimaryKey(@Param("id") Long id); /** * 删除关联作品集数据 * @param id * @return */ - Integer deleteLinkedPortfolioData(@Param("id") Integer id); + Integer deleteLinkedPortfolioData(@Param("id") Long id); /** * 更新文章连接及预览内容 @@ -167,7 +167,7 @@ public interface ArticleMapper extends Mapper
{ * @param articlePreviewContent * @return */ - Integer updateArticleLinkAndPreviewContent(@Param("idArticle") Integer idArticle, @Param("articleLink") String articleLink, @Param("articlePermalink") String articlePermalink, @Param("articlePreviewContent") String articlePreviewContent); + Integer updateArticleLinkAndPreviewContent(@Param("idArticle") Long idArticle, @Param("articleLink") String articleLink, @Param("articlePermalink") String articlePermalink, @Param("articlePreviewContent") String articlePreviewContent); /** * 根据专题主键及当前文章排序号获取专题下文章大纲 @@ -175,7 +175,7 @@ public interface ArticleMapper extends Mapper
{ * @param sortNo * @return */ - List selectPortfolioArticlesByIdPortfolioAndSortNo(@Param("idPortfolio") Integer idPortfolio, @Param("sortNo") Integer sortNo); + List selectPortfolioArticlesByIdPortfolioAndSortNo(@Param("idPortfolio") Long idPortfolio, @Param("sortNo") Integer sortNo); /** * 更新文章优选状态 @@ -183,13 +183,13 @@ public interface ArticleMapper extends Mapper
{ * @param articlePerfect * @return */ - int updatePerfect(@Param("idArticle") Integer idArticle, @Param("articlePerfect") String articlePerfect); + int updatePerfect(@Param("idArticle") Long idArticle, @Param("articlePerfect") String articlePerfect); /** * 删除文章关联文章内容表信息 * @param idArticle */ - void deleteArticleContent(@Param("idArticle") Integer idArticle); + void deleteArticleContent(@Param("idArticle") Long idArticle); /** * 获取公告 diff --git a/src/main/java/com/rymcu/forest/mapper/ArticleThumbsUpMapper.java b/src/main/java/com/rymcu/forest/mapper/ArticleThumbsUpMapper.java index 7a192f5..7d6f78d 100644 --- a/src/main/java/com/rymcu/forest/mapper/ArticleThumbsUpMapper.java +++ b/src/main/java/com/rymcu/forest/mapper/ArticleThumbsUpMapper.java @@ -14,5 +14,5 @@ public interface ArticleThumbsUpMapper extends Mapper { * @param thumbsUpNumber * @return */ - Integer updateArticleThumbsUpNumber(@Param("idArticle") Integer idArticle, @Param("thumbsUpNumber") Integer thumbsUpNumber); + Integer updateArticleThumbsUpNumber(@Param("idArticle") Long idArticle, @Param("thumbsUpNumber") Integer thumbsUpNumber); } diff --git a/src/main/java/com/rymcu/forest/mapper/BankAccountMapper.java b/src/main/java/com/rymcu/forest/mapper/BankAccountMapper.java index a067c76..af451f7 100644 --- a/src/main/java/com/rymcu/forest/mapper/BankAccountMapper.java +++ b/src/main/java/com/rymcu/forest/mapper/BankAccountMapper.java @@ -25,7 +25,7 @@ public interface BankAccountMapper extends Mapper { * @param idBank * @return */ - BankAccountDTO selectBankAccount(@Param("idBank") Integer idBank); + BankAccountDTO selectBankAccount(@Param("idBank") Long idBank); /** * 获取当前最大卡号 @@ -39,4 +39,11 @@ public interface BankAccountMapper extends Mapper { * @return */ BankAccountDTO selectByBankAccount(@Param("bankAccount") String bankAccount); + + /** + * 查询用户个人银行账户信息 + * @param idUser + * @return + */ + BankAccountDTO findPersonBankAccountByIdUser(@Param("idUser") Long idUser); } diff --git a/src/main/java/com/rymcu/forest/mapper/CommentMapper.java b/src/main/java/com/rymcu/forest/mapper/CommentMapper.java index 4969ece..8f4b76e 100644 --- a/src/main/java/com/rymcu/forest/mapper/CommentMapper.java +++ b/src/main/java/com/rymcu/forest/mapper/CommentMapper.java @@ -39,7 +39,7 @@ public interface CommentMapper extends Mapper { * @param commentSharpUrl * @return */ - Integer updateCommentSharpUrl(@Param("idComment") Integer idComment, @Param("commentSharpUrl") String commentSharpUrl); + Integer updateCommentSharpUrl(@Param("idComment") Long idComment, @Param("commentSharpUrl") String commentSharpUrl); /** * 获取评论列表数据 diff --git a/src/main/java/com/rymcu/forest/mapper/FollowMapper.java b/src/main/java/com/rymcu/forest/mapper/FollowMapper.java index a99a955..5a8af00 100644 --- a/src/main/java/com/rymcu/forest/mapper/FollowMapper.java +++ b/src/main/java/com/rymcu/forest/mapper/FollowMapper.java @@ -18,19 +18,19 @@ public interface FollowMapper extends Mapper { * @param followingType * @return */ - Boolean isFollow(@Param("followingId") Integer followingId, @Param("followerId") Integer followerId, @Param("followingType") String followingType); + Boolean isFollow(@Param("followingId") Integer followingId, @Param("followerId") Long followerId, @Param("followingType") String followingType); /** * 查询用户粉丝 * @param idUser * @return */ - List selectUserFollowersByUser(@Param("idUser") Integer idUser); + List selectUserFollowersByUser(@Param("idUser") Long idUser); /** * 查询用户关注用户 * @param idUser * @return */ - List selectUserFollowingsByUser(@Param("idUser") Integer idUser); + List selectUserFollowingsByUser(@Param("idUser") Long idUser); } diff --git a/src/main/java/com/rymcu/forest/mapper/NotificationMapper.java b/src/main/java/com/rymcu/forest/mapper/NotificationMapper.java index d0257eb..2a9a67e 100644 --- a/src/main/java/com/rymcu/forest/mapper/NotificationMapper.java +++ b/src/main/java/com/rymcu/forest/mapper/NotificationMapper.java @@ -17,14 +17,14 @@ public interface NotificationMapper extends Mapper { * @param idUser * @return */ - List selectUnreadNotifications(@Param("idUser") Integer idUser); + List selectUnreadNotifications(@Param("idUser") Long idUser); /** * 获取消息数据 * @param idUser * @return */ - List selectNotifications(@Param("idUser") Integer idUser); + List selectNotifications(@Param("idUser") Long idUser); /** * 获取消息数据 @@ -33,7 +33,7 @@ public interface NotificationMapper extends Mapper { * @param dataType * @return */ - Notification selectNotification(@Param("idUser") Integer idUser, @Param("dataId") Integer dataId, @Param("dataType") String dataType); + Notification selectNotification(@Param("idUser") Long idUser, @Param("dataId") Long dataId, @Param("dataType") String dataType); /** * 创建消息通知 @@ -43,21 +43,21 @@ public interface NotificationMapper extends Mapper { * @param dataSummary * @return */ - Integer insertNotification(@Param("idUser") Integer idUser, @Param("dataId") Integer dataId, @Param("dataType") String dataType, @Param("dataSummary") String dataSummary); + Integer insertNotification(@Param("idUser") Long idUser, @Param("dataId") Long dataId, @Param("dataType") String dataType, @Param("dataSummary") String dataSummary); /** * 标记消息已读 * @param id * @return */ - Integer readNotification(@Param("id") Integer id); + Integer readNotification(@Param("id") Long id); /** * 标记所有消息已读 * @param idUser * @return */ - Integer readAllNotification(@Param("idUser") Integer idUser); + Integer readAllNotification(@Param("idUser") Long idUser); /** * 删除相关未读消息 @@ -65,5 +65,5 @@ public interface NotificationMapper extends Mapper { * @param dataType * @return */ - Integer deleteUnreadNotification(@Param("dataId") Integer dataId, @Param("dataType") String dataType); + Integer deleteUnreadNotification(@Param("dataId") Long dataId, @Param("dataType") String dataType); } diff --git a/src/main/java/com/rymcu/forest/mapper/PermissionMapper.java b/src/main/java/com/rymcu/forest/mapper/PermissionMapper.java index 1db3cb3..45ed3e6 100644 --- a/src/main/java/com/rymcu/forest/mapper/PermissionMapper.java +++ b/src/main/java/com/rymcu/forest/mapper/PermissionMapper.java @@ -8,5 +8,5 @@ import java.util.List; public interface PermissionMapper extends Mapper { - List selectMenuByIdRole(@Param("role") Integer role); + List selectMenuByIdRole(@Param("role") Long role); } \ No newline at end of file diff --git a/src/main/java/com/rymcu/forest/mapper/PortfolioMapper.java b/src/main/java/com/rymcu/forest/mapper/PortfolioMapper.java index c926b1c..8d9c1fa 100644 --- a/src/main/java/com/rymcu/forest/mapper/PortfolioMapper.java +++ b/src/main/java/com/rymcu/forest/mapper/PortfolioMapper.java @@ -16,7 +16,7 @@ public interface PortfolioMapper extends Mapper { * @param idUser * @return */ - List selectUserPortfoliosByIdUser(@Param("idUser") Integer idUser); + List selectUserPortfoliosByIdUser(@Param("idUser") Long idUser); /** * 查询作品集 @@ -24,14 +24,14 @@ public interface PortfolioMapper extends Mapper { * @param type * @return */ - PortfolioDTO selectPortfolioDTOById(@Param("id") Integer id, @Param("type") Integer type); + PortfolioDTO selectPortfolioDTOById(@Param("id") Long id, @Param("type") Integer type); /** * 统计作品集下文章数 * @param idPortfolio * @return */ - Integer selectCountArticleNumber(@Param("idPortfolio") Integer idPortfolio); + Integer selectCountArticleNumber(@Param("idPortfolio") Long idPortfolio); /** * 查询文章是否已绑定 @@ -39,7 +39,7 @@ public interface PortfolioMapper extends Mapper { * @param idPortfolio * @return */ - Integer selectCountPortfolioArticle(@Param("idArticle") Integer idArticle, @Param("idPortfolio") Integer idPortfolio); + Integer selectCountPortfolioArticle(@Param("idArticle") Long idArticle, @Param("idPortfolio") Long idPortfolio); /** * 插入文章与作品集绑定数据 @@ -48,14 +48,14 @@ public interface PortfolioMapper extends Mapper { * @param maxSortNo * @return */ - Integer insertPortfolioArticle(@Param("idArticle") Integer idArticle, @Param("idPortfolio") Integer idPortfolio, @Param("maxSortNo") Integer maxSortNo); + Integer insertPortfolioArticle(@Param("idArticle") Long idArticle, @Param("idPortfolio") Long idPortfolio, @Param("maxSortNo") Integer maxSortNo); /** * 查询作品集下最大排序号 * @param idPortfolio * @return */ - Integer selectMaxSortNo(@Param("idPortfolio") Integer idPortfolio); + Integer selectMaxSortNo(@Param("idPortfolio") Long idPortfolio); /** * 更新文章排序号 @@ -64,7 +64,7 @@ public interface PortfolioMapper extends Mapper { * @param sortNo * @return */ - Integer updateArticleSortNo(@Param("idPortfolio") Integer idPortfolio, @Param("idArticle") Integer idArticle, @Param("sortNo") Integer sortNo); + Integer updateArticleSortNo(@Param("idPortfolio") Long idPortfolio, @Param("idArticle") Long idArticle, @Param("sortNo") Integer sortNo); /** * 取消绑定文章 @@ -72,7 +72,7 @@ public interface PortfolioMapper extends Mapper { * @param idArticle * @return */ - Integer unbindArticle(@Param("idPortfolio") Integer idPortfolio, @Param("idArticle") Integer idArticle); + Integer unbindArticle(@Param("idPortfolio") Long idPortfolio, @Param("idArticle") Long idArticle); /** * 获取作品集列表数据 diff --git a/src/main/java/com/rymcu/forest/mapper/ProductMapper.java b/src/main/java/com/rymcu/forest/mapper/ProductMapper.java new file mode 100644 index 0000000..e03d4ae --- /dev/null +++ b/src/main/java/com/rymcu/forest/mapper/ProductMapper.java @@ -0,0 +1,39 @@ +package com.rymcu.forest.mapper; + +import com.rymcu.forest.core.mapper.Mapper; +import com.rymcu.forest.dto.ProductDTO; +import com.rymcu.forest.entity.Product; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * Created on 2022/6/13 21:53. + * + * @author ronger + * @email ronger-x@outlook.com + */ +public interface ProductMapper extends Mapper { + /** + * 保存产品详情 + * @param idProduct + * @param productContent + * @param productContentHtml + * @return + */ + Integer insertProductContent(@Param("idProduct") Integer idProduct, @Param("productContent") String productContent, @Param("productContentHtml") String productContentHtml); + + /** + * 查询产品列表 + * @return + */ + List selectProducts(); + + /** + * 获取产品详情 + * @param idProduct + * @param type + * @return + */ + ProductDTO selectProductDTOById(@Param("idProduct") Integer idProduct, @Param("type") Integer type); +} diff --git a/src/main/java/com/rymcu/forest/mapper/RoleMapper.java b/src/main/java/com/rymcu/forest/mapper/RoleMapper.java index 813d7fd..8f9fab3 100644 --- a/src/main/java/com/rymcu/forest/mapper/RoleMapper.java +++ b/src/main/java/com/rymcu/forest/mapper/RoleMapper.java @@ -8,11 +8,11 @@ import java.util.List; public interface RoleMapper extends Mapper { - List selectRoleByIdUser(@Param("id") Integer id); + List selectRoleByIdUser(@Param("id") Long id); Role selectRoleByInputCode(@Param("inputCode") String inputCode); - Integer updateStatus(@Param("idRole") Integer idRole, @Param("status") String status); + Integer updateStatus(@Param("idRole") Long idRole, @Param("status") String status); - Integer update(@Param("idRole") Integer idRole, @Param("name") String name, @Param("inputCode") String inputCode, @Param("weights") Integer weights); + Integer update(@Param("idRole") Long idRole, @Param("name") String name, @Param("inputCode") String inputCode, @Param("weights") Integer weights); } \ No newline at end of file diff --git a/src/main/java/com/rymcu/forest/mapper/SponsorMapper.java b/src/main/java/com/rymcu/forest/mapper/SponsorMapper.java index 7f36c26..9fb07a5 100644 --- a/src/main/java/com/rymcu/forest/mapper/SponsorMapper.java +++ b/src/main/java/com/rymcu/forest/mapper/SponsorMapper.java @@ -13,5 +13,5 @@ public interface SponsorMapper extends Mapper { * @param idArticle * @return */ - Integer updateArticleSponsorCount(@Param("idArticle") Integer idArticle); + Integer updateArticleSponsorCount(@Param("idArticle") Long idArticle); } diff --git a/src/main/java/com/rymcu/forest/mapper/TagMapper.java b/src/main/java/com/rymcu/forest/mapper/TagMapper.java index b4b1138..fda04c0 100644 --- a/src/main/java/com/rymcu/forest/mapper/TagMapper.java +++ b/src/main/java/com/rymcu/forest/mapper/TagMapper.java @@ -18,7 +18,7 @@ public interface TagMapper extends Mapper { * @param idArticle * @return */ - Integer insertTagArticle(@Param("idTag") Integer idTag, @Param("idArticle") Integer idArticle); + Integer insertTagArticle(@Param("idTag") Long idTag, @Param("idArticle") Long idArticle); /** * 统计标签使用数(文章) @@ -26,7 +26,7 @@ public interface TagMapper extends Mapper { * @param idArticle * @return */ - Integer selectCountTagArticleById(@Param("idTag") Integer idTag, @Param("idArticle") Integer idArticle); + Integer selectCountTagArticleById(@Param("idTag") Long idTag, @Param("idArticle") Long idArticle); /** * 获取用户标签数 @@ -34,7 +34,7 @@ public interface TagMapper extends Mapper { * @param idTag * @return */ - Integer selectCountUserTagById(@Param("idUser") Integer idUser, @Param("idTag") Integer idTag); + Integer selectCountUserTagById(@Param("idUser") Long idUser, @Param("idTag") Long idTag); /** * 插入用户标签信息 @@ -43,7 +43,7 @@ public interface TagMapper extends Mapper { * @param type * @return */ - Integer insertUserTag(@Param("idTag") Integer idTag, @Param("idUser") Integer idUser, @Param("type") Integer type); + Integer insertUserTag(@Param("idTag") Long idTag, @Param("idUser") Long idUser, @Param("type") Integer type); /** * 删除未使用标签 @@ -61,7 +61,7 @@ public interface TagMapper extends Mapper { * @param tagReservation * @return */ - Integer update(@Param("idTag") Integer idTag, @Param("tagUri") String tagUri, @Param("tagIconPath") String tagIconPath, @Param("tagStatus") String tagStatus, @Param("tagDescription") String tagDescription, @Param("tagReservation") String tagReservation); + Integer update(@Param("idTag") Long idTag, @Param("tagUri") String tagUri, @Param("tagIconPath") String tagIconPath, @Param("tagStatus") String tagStatus, @Param("tagDescription") String tagDescription, @Param("tagReservation") String tagReservation); /** * 查询标签列表 diff --git a/src/main/java/com/rymcu/forest/mapper/TopicMapper.java b/src/main/java/com/rymcu/forest/mapper/TopicMapper.java index 3c348cc..3bad454 100644 --- a/src/main/java/com/rymcu/forest/mapper/TopicMapper.java +++ b/src/main/java/com/rymcu/forest/mapper/TopicMapper.java @@ -44,21 +44,21 @@ public interface TopicMapper extends Mapper { * @param topicDescriptionHtml * @return */ - Integer update(@Param("idTopic") Integer idTopic, @Param("topicTitle") String topicTitle, @Param("topicUri") String topicUri, @Param("topicIconPath") String topicIconPath, @Param("topicNva") String topicNva, @Param("topicStatus") String topicStatus, @Param("topicSort") Integer topicSort, @Param("topicDescription") String topicDescription, @Param("topicDescriptionHtml") String topicDescriptionHtml); + Integer update(@Param("idTopic") Long idTopic, @Param("topicTitle") String topicTitle, @Param("topicUri") String topicUri, @Param("topicIconPath") String topicIconPath, @Param("topicNva") String topicNva, @Param("topicStatus") String topicStatus, @Param("topicSort") Integer topicSort, @Param("topicDescription") String topicDescription, @Param("topicDescriptionHtml") String topicDescriptionHtml); /** * @param idTopic * @param tagTitle * @return */ - List selectUnbindTagsById(@Param("idTopic") Integer idTopic, @Param("tagTitle") String tagTitle); + List selectUnbindTagsById(@Param("idTopic") Long idTopic, @Param("tagTitle") String tagTitle); - Integer insertTopicTag(@Param("idTopic") Integer idTopic, @Param("idTag") Integer idTag); + Integer insertTopicTag(@Param("idTopic") Long idTopic, @Param("idTag") Long idTag); /** * @param idTopic * @param idTag * @return */ - Integer deleteTopicTag(@Param("idTopic") Integer idTopic, @Param("idTag") Integer idTag); + Integer deleteTopicTag(@Param("idTopic") Long idTopic, @Param("idTag") Long idTag); } diff --git a/src/main/java/com/rymcu/forest/mapper/UserMapper.java b/src/main/java/com/rymcu/forest/mapper/UserMapper.java index d2f42e8..ce13898 100644 --- a/src/main/java/com/rymcu/forest/mapper/UserMapper.java +++ b/src/main/java/com/rymcu/forest/mapper/UserMapper.java @@ -28,7 +28,7 @@ public interface UserMapper extends Mapper { * @param idRole * @return */ - Integer insertUserRole(@Param("idUser") Integer idUser, @Param("idRole") Integer idRole); + Integer insertUserRole(@Param("idUser") Long idUser, @Param("idRole") Long idRole); /** * 根据账号获取获取用户信息 @@ -57,7 +57,7 @@ public interface UserMapper extends Mapper { * @param idUser * @return */ - Integer selectRoleWeightsByUser(@Param("idUser") Integer idUser); + Integer selectRoleWeightsByUser(@Param("idUser") Long idUser); /** * 更新用户权限 @@ -65,7 +65,7 @@ public interface UserMapper extends Mapper { * @param idRole * @return */ - Integer updateUserRole(@Param("idUser") Integer idUser, @Param("idRole") Integer idRole); + Integer updateUserRole(@Param("idUser") Long idUser, @Param("idRole") Long idRole); /** * 更新用户状态 @@ -73,7 +73,7 @@ public interface UserMapper extends Mapper { * @param status * @return */ - Integer updateStatus(@Param("idUser") Integer idUser, @Param("status") String status); + Integer updateStatus(@Param("idUser") Long idUser, @Param("status") String status); /** * 根据昵称获取重名用户数量 @@ -87,7 +87,7 @@ public interface UserMapper extends Mapper { * @param idUser * @return */ - UserInfoDTO selectUserInfo(@Param("idUser") Integer idUser); + UserInfoDTO selectUserInfo(@Param("idUser") Long idUser); /** * 更新用户信息 @@ -99,7 +99,7 @@ public interface UserMapper extends Mapper { * @param sex * @return */ - Integer updateUserInfo(@Param("idUser") Integer idUser, @Param("nickname") String nickname, @Param("avatarType") String avatarType, @Param("avatarUrl") String avatarUrl, @Param("signature") String signature, @Param("sex") String sex); + Integer updateUserInfo(@Param("idUser") Long idUser, @Param("nickname") String nickname, @Param("avatarType") String avatarType, @Param("avatarUrl") String avatarUrl, @Param("signature") String signature, @Param("sex") String sex); /** * 验证昵称是否重复 @@ -107,20 +107,20 @@ public interface UserMapper extends Mapper { * @param nickname * @return */ - Integer checkNicknameByIdUser(@Param("idUser") Integer idUser, @Param("nickname") String nickname); + Integer checkNicknameByIdUser(@Param("idUser") Long idUser, @Param("nickname") String nickname); /** * 根据用户 ID 获取作者信息 * @param id * @return */ - Author selectAuthor(@Param("id") Integer id); + Author selectAuthor(@Param("id") Long id); /** * 更新用户最后登录时间 * @param idUser * @return */ - Integer updateLastLoginTime(@Param("idUser") Integer idUser); + Integer updateLastLoginTime(@Param("idUser") Long idUser); /** * 更换邮箱 @@ -128,7 +128,7 @@ public interface UserMapper extends Mapper { * @param email * @return */ - Integer updateEmail(@Param("idUser") Integer idUser, @Param("email") String email); + Integer updateEmail(@Param("idUser") Long idUser, @Param("email") String email); /** * 更新密码 @@ -136,7 +136,7 @@ public interface UserMapper extends Mapper { * @param password * @return */ - Integer updatePasswordById(@Param("idUser") Integer idUser, @Param("password") String password); + Integer updatePasswordById(@Param("idUser") Long idUser, @Param("password") String password); /** * 查询用户数据 diff --git a/src/main/java/com/rymcu/forest/service/ArticleService.java b/src/main/java/com/rymcu/forest/service/ArticleService.java index 83174df..cca8f77 100644 --- a/src/main/java/com/rymcu/forest/service/ArticleService.java +++ b/src/main/java/com/rymcu/forest/service/ArticleService.java @@ -4,12 +4,11 @@ import com.rymcu.forest.core.service.Service; import com.rymcu.forest.dto.ArticleDTO; import com.rymcu.forest.dto.ArticleSearchDTO; import com.rymcu.forest.entity.Article; +import com.rymcu.forest.entity.User; import com.rymcu.forest.web.api.exception.BaseApiException; -import javax.servlet.http.HttpServletRequest; import java.io.UnsupportedEncodingException; import java.util.List; -import java.util.Map; /** * @author ronger @@ -29,7 +28,7 @@ public interface ArticleService extends Service
{ * @param type * @return * */ - ArticleDTO findArticleDTOById(Integer id, Integer type); + ArticleDTO findArticleDTOById(Long id, Integer type); /** * 查询主题下文章列表 @@ -50,17 +49,17 @@ public interface ArticleService extends Service
{ * @param idUser * @return * */ - List findUserArticlesByIdUser(Integer idUser); + List findUserArticlesByIdUser(Long idUser); /** * 新增/更新文章 * @param article - * @param request + * @param user * @throws UnsupportedEncodingException * @throws BaseApiException * @return * */ - Map postArticle(ArticleDTO article, HttpServletRequest request) throws UnsupportedEncodingException, BaseApiException; + Long postArticle(ArticleDTO article, User user) throws UnsupportedEncodingException, BaseApiException; /** * 删除文章 @@ -68,13 +67,13 @@ public interface ArticleService extends Service
{ * @return * @throws BaseApiException * */ - Map delete(Integer id) throws BaseApiException; + Integer delete(Long id) throws BaseApiException; /** * 增量文章浏览数 * @param id */ - void incrementArticleViewCount(Integer id); + void incrementArticleViewCount(Long id); /** * 获取分享链接数据 @@ -82,21 +81,20 @@ public interface ArticleService extends Service
{ * @throws BaseApiException * @return */ - Map share(Integer id) throws BaseApiException; + String share(Integer id) throws BaseApiException; /** * 查询草稿文章类别 - * @throws BaseApiException * @return */ - List findDrafts() throws BaseApiException; + List findDrafts(Long userId); /** * 查询作品集下文章 * @param idPortfolio * @return */ - List findArticlesByIdPortfolio(Integer idPortfolio); + List findArticlesByIdPortfolio(Long idPortfolio); /** * 查询作品集下未绑定文章 @@ -105,17 +103,18 @@ public interface ArticleService extends Service
{ * @param idUser * @return */ - List selectUnbindArticles(Integer idPortfolio, String searchText, Integer idUser); + List selectUnbindArticles(Long idPortfolio, String searchText, Long idUser); /** * 更新文章标签 * @param idArticle * @param tags + * @param userId * @return * @throws UnsupportedEncodingException * @throws BaseApiException */ - Map updateTags(Integer idArticle, String tags) throws UnsupportedEncodingException, BaseApiException; + Boolean updateTags(Long idArticle, String tags, Long userId) throws UnsupportedEncodingException, BaseApiException; /** * 更新文章优选状态 @@ -123,7 +122,7 @@ public interface ArticleService extends Service
{ * @param articlePerfect * @return */ - Map updatePerfect(Integer idArticle, String articlePerfect); + Boolean updatePerfect(Long idArticle, String articlePerfect); /** * 获取公告列表 diff --git a/src/main/java/com/rymcu/forest/service/ArticleThumbsUpService.java b/src/main/java/com/rymcu/forest/service/ArticleThumbsUpService.java index d565c29..8c71913 100644 --- a/src/main/java/com/rymcu/forest/service/ArticleThumbsUpService.java +++ b/src/main/java/com/rymcu/forest/service/ArticleThumbsUpService.java @@ -4,17 +4,15 @@ import com.rymcu.forest.core.service.Service; import com.rymcu.forest.entity.ArticleThumbsUp; import com.rymcu.forest.web.api.exception.BaseApiException; -import java.util.Map; - /** * @author ronger */ public interface ArticleThumbsUpService extends Service { /** * 点赞 + * * @param articleThumbsUp - * @throws BaseApiException * @return */ - Map thumbsUp(ArticleThumbsUp articleThumbsUp) throws BaseApiException; + int thumbsUp(ArticleThumbsUp articleThumbsUp); } diff --git a/src/main/java/com/rymcu/forest/service/BankAccountService.java b/src/main/java/com/rymcu/forest/service/BankAccountService.java index 1794336..d90323e 100644 --- a/src/main/java/com/rymcu/forest/service/BankAccountService.java +++ b/src/main/java/com/rymcu/forest/service/BankAccountService.java @@ -24,7 +24,7 @@ public interface BankAccountService extends Service { * @param idUser * @return */ - BankAccountDTO findBankAccountByIdUser(Integer idUser); + BankAccountDTO findBankAccountByIdUser(Long idUser); /** * 根据账户查询银行账户信息 diff --git a/src/main/java/com/rymcu/forest/service/CommentService.java b/src/main/java/com/rymcu/forest/service/CommentService.java index a6bc0ed..40ce0f3 100644 --- a/src/main/java/com/rymcu/forest/service/CommentService.java +++ b/src/main/java/com/rymcu/forest/service/CommentService.java @@ -3,11 +3,9 @@ package com.rymcu.forest.service; import com.rymcu.forest.core.service.Service; import com.rymcu.forest.dto.CommentDTO; import com.rymcu.forest.entity.Comment; -import com.rymcu.forest.web.api.exception.BaseApiException; import javax.servlet.http.HttpServletRequest; import java.util.List; -import java.util.Map; /** * @author ronger @@ -27,7 +25,7 @@ public interface CommentService extends Service { * @param request * @return */ - Map postComment(Comment comment, HttpServletRequest request) throws BaseApiException; + Comment postComment(Comment comment, HttpServletRequest request); /** * 获取评论列表数据 diff --git a/src/main/java/com/rymcu/forest/service/FollowService.java b/src/main/java/com/rymcu/forest/service/FollowService.java index d821fcc..94ba856 100644 --- a/src/main/java/com/rymcu/forest/service/FollowService.java +++ b/src/main/java/com/rymcu/forest/service/FollowService.java @@ -42,7 +42,7 @@ public interface FollowService extends Service { * @param followingId * @return */ - List findByFollowingId(String followType, Integer followingId); + List findByFollowingId(String followType, Long followingId); diff --git a/src/main/java/com/rymcu/forest/service/LoginRecordService.java b/src/main/java/com/rymcu/forest/service/LoginRecordService.java index 9d618fe..2c7ac33 100644 --- a/src/main/java/com/rymcu/forest/service/LoginRecordService.java +++ b/src/main/java/com/rymcu/forest/service/LoginRecordService.java @@ -18,7 +18,7 @@ public interface LoginRecordService extends Service { * @param idUser * @return */ - LoginRecord saveLoginRecord(Integer idUser); + LoginRecord saveLoginRecord(Long idUser); /** * 获取用户登录记录 diff --git a/src/main/java/com/rymcu/forest/service/NotificationService.java b/src/main/java/com/rymcu/forest/service/NotificationService.java index 1b3e461..034611f 100644 --- a/src/main/java/com/rymcu/forest/service/NotificationService.java +++ b/src/main/java/com/rymcu/forest/service/NotificationService.java @@ -17,14 +17,14 @@ public interface NotificationService extends Service { * @param idUser * @return */ - List findUnreadNotifications(Integer idUser); + List findUnreadNotifications(Long idUser); /** * 获取消息数据 * @param idUser * @return */ - List findNotifications(Integer idUser); + List findNotifications(Long idUser); /** * 获取消息数据 @@ -33,7 +33,7 @@ public interface NotificationService extends Service { * @param dataType * @return */ - Notification findNotification(Integer idUser, Integer dataId, String dataType); + Notification findNotification(Long idUser, Long dataId, String dataType); /** * 创建系统通知 @@ -43,14 +43,14 @@ public interface NotificationService extends Service { * @param dataSummary * @return */ - Integer save(Integer idUser, Integer dataId, String dataType, String dataSummary); + Integer save(Long idUser, Long dataId, String dataType, String dataSummary); /** * 标记消息已读 * @param id * @return */ - Integer readNotification(Integer id); + Integer readNotification(Long id); /** * 标记所有消息已读 @@ -65,5 +65,5 @@ public interface NotificationService extends Service { * @param dataType * @return */ - Integer deleteUnreadNotification(Integer dataId, String dataType); + Integer deleteUnreadNotification(Long dataId, String dataType); } diff --git a/src/main/java/com/rymcu/forest/service/PortfolioService.java b/src/main/java/com/rymcu/forest/service/PortfolioService.java index bae6059..ccf7a10 100644 --- a/src/main/java/com/rymcu/forest/service/PortfolioService.java +++ b/src/main/java/com/rymcu/forest/service/PortfolioService.java @@ -1,6 +1,9 @@ package com.rymcu.forest.service; +import com.github.pagehelper.PageInfo; +import com.rymcu.forest.core.exception.ServiceException; import com.rymcu.forest.core.service.Service; +import com.rymcu.forest.dto.ArticleDTO; import com.rymcu.forest.dto.PortfolioArticleDTO; import com.rymcu.forest.dto.PortfolioDTO; import com.rymcu.forest.dto.UserDTO; @@ -8,7 +11,6 @@ import com.rymcu.forest.entity.Portfolio; import com.rymcu.forest.web.api.exception.BaseApiException; import java.util.List; -import java.util.Map; /** * @author ronger @@ -27,7 +29,7 @@ public interface PortfolioService extends Service { * @param type * @return */ - PortfolioDTO findPortfolioDTOById(Integer idPortfolio, Integer type); + PortfolioDTO findPortfolioDTOById(Long idPortfolio, Integer type); /** * 保持/更新作品集 @@ -35,48 +37,56 @@ public interface PortfolioService extends Service { * @throws BaseApiException * @return */ - Portfolio postPortfolio(Portfolio portfolio) throws BaseApiException; + Portfolio postPortfolio(Portfolio portfolio); /** * 查询作品集下未绑定文章 - * * @param page * @param rows * @param searchText * @param idPortfolio - * @throws BaseApiException + * @param idUser * @return */ - Map findUnbindArticles(Integer page, Integer rows, String searchText, Integer idPortfolio) throws BaseApiException; + PageInfo findUnbindArticles(Integer page, Integer rows, String searchText, Long idPortfolio, Long idUser); /** * 绑定文章 * @param portfolioArticle * @return + * @throws ServiceException */ - Map bindArticle(PortfolioArticleDTO portfolioArticle); + boolean bindArticle(PortfolioArticleDTO portfolioArticle) throws ServiceException; /** * 更新文章排序号 * @param portfolioArticle * @return + * @throws ServiceException */ - Map updateArticleSortNo(PortfolioArticleDTO portfolioArticle); + boolean updateArticleSortNo(PortfolioArticleDTO portfolioArticle) throws ServiceException; /** * 取消绑定文章 + * * @param idPortfolio * @param idArticle * @return + * @throws ServiceException */ - Map unbindArticle(Integer idPortfolio, Integer idArticle); + boolean unbindArticle(Long idPortfolio, Long idArticle) throws ServiceException; + /** * 删除作品集 + * * @param idPortfolio + * @param idUser + * @param roleWeights * @return */ - Map deletePortfolio(Integer idPortfolio) throws BaseApiException; + boolean deletePortfolio(Long idPortfolio, Long idUser, Integer roleWeights); + /** * 获取作品集列表数据 diff --git a/src/main/java/com/rymcu/forest/service/ProductService.java b/src/main/java/com/rymcu/forest/service/ProductService.java new file mode 100644 index 0000000..37681d2 --- /dev/null +++ b/src/main/java/com/rymcu/forest/service/ProductService.java @@ -0,0 +1,30 @@ +package com.rymcu.forest.service; + +import com.rymcu.forest.core.service.Service; +import com.rymcu.forest.dto.ProductDTO; +import com.rymcu.forest.entity.Product; + +import java.util.List; + +/** + * Created on 2022/6/21 9:25. + * + * @author ronger + * @email ronger-x@outlook.com + * @packageName com.rymcu.forest.service + */ +public interface ProductService extends Service { + /** + * 查询产品列表 + * @return + */ + List findProducts(); + + /** + * 获取产品详情 + * @param idProduct + * @param type + * @return + */ + ProductDTO findProductDTOById(Integer idProduct, Integer type); +} diff --git a/src/main/java/com/rymcu/forest/service/RoleService.java b/src/main/java/com/rymcu/forest/service/RoleService.java index f5db02d..e8fca74 100644 --- a/src/main/java/com/rymcu/forest/service/RoleService.java +++ b/src/main/java/com/rymcu/forest/service/RoleService.java @@ -1,11 +1,11 @@ package com.rymcu.forest.service; +import com.rymcu.forest.core.exception.ServiceException; import com.rymcu.forest.core.service.Service; import com.rymcu.forest.entity.Role; import com.rymcu.forest.entity.User; import java.util.List; -import java.util.Map; /** @@ -27,20 +27,22 @@ public interface RoleService extends Service { * @param idUser * @return * */ - List findByIdUser(Integer idUser); + List findByIdUser(Long idUser); /** * 更新用户状态 * @param idRole * @param status * @return - * */ - Map updateStatus(Integer idRole, String status); + * @throws ServiceException + */ + boolean updateStatus(Long idRole, String status) throws ServiceException; /** * 添加/更新角色 * @param role * @return - * */ - Map saveRole(Role role); + * @throws ServiceException + */ + boolean saveRole(Role role) throws ServiceException; } diff --git a/src/main/java/com/rymcu/forest/service/SponsorService.java b/src/main/java/com/rymcu/forest/service/SponsorService.java index 3adf035..e2273eb 100644 --- a/src/main/java/com/rymcu/forest/service/SponsorService.java +++ b/src/main/java/com/rymcu/forest/service/SponsorService.java @@ -3,17 +3,16 @@ package com.rymcu.forest.service; import com.rymcu.forest.core.service.Service; import com.rymcu.forest.entity.Sponsor; -import java.util.Map; - /** * @author ronger */ public interface SponsorService extends Service { /** * 赞赏 + * * @param sponsor * @return * @throws Exception */ - Map sponsorship(Sponsor sponsor) throws Exception; + boolean sponsorship(Sponsor sponsor) throws Exception; } diff --git a/src/main/java/com/rymcu/forest/service/TagService.java b/src/main/java/com/rymcu/forest/service/TagService.java index 0b36b76..7290196 100644 --- a/src/main/java/com/rymcu/forest/service/TagService.java +++ b/src/main/java/com/rymcu/forest/service/TagService.java @@ -8,7 +8,6 @@ import com.rymcu.forest.web.api.exception.BaseApiException; import java.io.UnsupportedEncodingException; import java.util.List; -import java.util.Map; /** * @author ronger @@ -23,20 +22,22 @@ public interface TagService extends Service { * @throws BaseApiException * @return * */ - Integer saveTagArticle(Article article, String articleContentHtml) throws UnsupportedEncodingException, BaseApiException; + Integer saveTagArticle(Article article, String articleContentHtml, Long userId) throws UnsupportedEncodingException, BaseApiException; /** * 清除未使用标签 + * * @return - * */ - Map cleanUnusedTag(); + */ + boolean cleanUnusedTag(); /** * 添加/更新标签 + * * @param tag * @return */ - Map saveTag(Tag tag); + Tag saveTag(Tag tag) throws Exception; /** * 获取标签列表 diff --git a/src/main/java/com/rymcu/forest/service/TopicService.java b/src/main/java/com/rymcu/forest/service/TopicService.java index 4fda791..6cbe3dc 100644 --- a/src/main/java/com/rymcu/forest/service/TopicService.java +++ b/src/main/java/com/rymcu/forest/service/TopicService.java @@ -1,12 +1,13 @@ package com.rymcu.forest.service; +import com.rymcu.forest.core.exception.ServiceException; import com.rymcu.forest.core.service.Service; +import com.rymcu.forest.dto.admin.TagDTO; import com.rymcu.forest.dto.admin.TopicTagDTO; import com.rymcu.forest.entity.Tag; import com.rymcu.forest.entity.Topic; import java.util.List; -import java.util.Map; /** * @author ronger @@ -15,52 +16,60 @@ public interface TopicService extends Service { /** * 获取导航主题数据 + * * @return - * */ + */ List findTopicNav(); /** * 根据 topicUri 获取主题信息及旗下标签数据 + * * @param topicUri 主题 URI * @return - * */ + */ Topic findTopicByTopicUri(String topicUri); /** * 新增/更新主题信息 + * * @param topic 主题信息 * @return - * */ - Map saveTopic(Topic topic); + * @throws ServiceException + */ + Topic saveTopic(Topic topic) throws ServiceException; /** * 查询未绑定标签 + * * @param idTopic * @param tagTitle * @return */ - List findUnbindTagsById(Integer idTopic, String tagTitle); + List findUnbindTagsById(Long idTopic, String tagTitle); /** * 绑定标签 + * * @param topicTag * @return + * @throws ServiceException */ - Map bindTopicTag(TopicTagDTO topicTag); + TopicTagDTO bindTopicTag(TopicTagDTO topicTag) throws ServiceException; /** * 取消绑定标签 + * * @param topicTag * @return + * @throws ServiceException */ - Map unbindTopicTag(TopicTagDTO topicTag); + TopicTagDTO unbindTopicTag(TopicTagDTO topicTag) throws ServiceException; /** * 获取主题下标签列表 + * * @param topicUri - * @param page - * @param rows * @return */ - Map findTagsByTopicUri(String topicUri, Integer page, Integer rows); + List findTagsByTopicUri(String topicUri); } diff --git a/src/main/java/com/rymcu/forest/service/TransactionRecordService.java b/src/main/java/com/rymcu/forest/service/TransactionRecordService.java index e5da803..33ef0ea 100644 --- a/src/main/java/com/rymcu/forest/service/TransactionRecordService.java +++ b/src/main/java/com/rymcu/forest/service/TransactionRecordService.java @@ -15,9 +15,8 @@ public interface TransactionRecordService extends Service { * 交易 * @param transactionRecord * @return - * @throws Exception */ - TransactionRecord transfer(TransactionRecord transactionRecord) throws Exception; + TransactionRecord transfer(TransactionRecord transactionRecord); /** * 查询指定账户的交易记录 @@ -34,24 +33,21 @@ public interface TransactionRecordService extends Service { * @param formUserId * @param transactionType * @return - * @throws Exception */ - TransactionRecord userTransfer(Integer toUserId, Integer formUserId, TransactionEnum transactionType) throws Exception; + TransactionRecord userTransfer(Long toUserId, Long formUserId, TransactionEnum transactionType); /** * 社区银行转账/奖励发放 * @param idUser * @param transactionType * @return - * @throws Exception */ - TransactionRecord bankTransfer(Integer idUser, TransactionEnum transactionType) throws Exception; + TransactionRecord bankTransfer(Long idUser, TransactionEnum transactionType); /** * 发放新手奖励 * @param transactionRecord * @return - * @throws Exception */ - TransactionRecord newbieRewards(TransactionRecord transactionRecord) throws Exception; + TransactionRecord newbieRewards(TransactionRecord transactionRecord); } diff --git a/src/main/java/com/rymcu/forest/service/UserService.java b/src/main/java/com/rymcu/forest/service/UserService.java index 161669b..9c74efb 100644 --- a/src/main/java/com/rymcu/forest/service/UserService.java +++ b/src/main/java/com/rymcu/forest/service/UserService.java @@ -1,5 +1,6 @@ package com.rymcu.forest.service; +import com.rymcu.forest.core.exception.ServiceException; import com.rymcu.forest.core.service.Service; import com.rymcu.forest.dto.*; import com.rymcu.forest.entity.User; @@ -11,7 +12,6 @@ import java.util.Map; /** - * * @author CodeGenerator * @date 2018/05/29 */ @@ -19,105 +19,123 @@ public interface UserService extends Service { /** * 通过账号查询用户信息 + * * @param account - * @throws TooManyResultsException * @return User - * */ + * @throws TooManyResultsException + */ User findByAccount(String account) throws TooManyResultsException; /** * 注册接口 - * @param email 邮箱 - * @param password 密码 - * @param code 验证码 + * + * @param email 邮箱 + * @param password 密码 + * @param code 验证码 * @return Map - * */ - Map register(String email, String password, String code); + */ + boolean register(String email, String password, String code); /** * 登录接口 - * @param account 邮箱 - * @param password 密码 + * + * @param account 邮箱 + * @param password 密码 * @return Map - * */ - Map login(String account, String password); + */ + TokenUser login(String account, String password) throws ServiceException; /** * 通过 account 获取用户信息接口 + * * @param account 昵称 - * @return UserDTO - * */ + * @return UserDTO + */ UserDTO findUserDTOByAccount(String account); /** * 找回密码接口 - * @param code 验证码 + * + * @param code 验证码 * @param password 密码 * @return Map - * */ - Map forgetPassword(String code, String password); + * @throws ServiceException + */ + boolean forgetPassword(String code, String password) throws ServiceException; /** * 更新用户角色接口 + * * @param idUser 用户 id * @param idRole 角色 id * @return Map - * */ - Map updateUserRole(Integer idUser, Integer idRole); + * @throws ServiceException + */ + boolean updateUserRole(Long idUser, Long idRole) throws ServiceException; /** * 更新用户状态 + * * @param idUser 用户 id * @param status 状态 * @return Map - * */ - Map updateStatus(Integer idUser, String status); + * @throws ServiceException + */ + boolean updateStatus(Long idUser, String status) throws ServiceException; /** * 获取用户信息 + * * @param idUser * @return */ - Map findUserInfo(Integer idUser); + UserInfoDTO findUserInfo(Long idUser); /** * 更新用户信息 + * * @param user * @return + * @throws ServiceException */ - Map updateUserInfo(UserInfoDTO user); + UserInfoDTO updateUserInfo(UserInfoDTO user) throws ServiceException; /** * 验证昵称是否重复 + * * @param idUser * @param nickname * @return */ - Map checkNickname(Integer idUser, String nickname); + boolean checkNicknameByIdUser(Long idUser, String nickname); /** * 获取用户权限 + * * @param idUser * @return */ - Integer findRoleWeightsByUser(Integer idUser); + Integer findRoleWeightsByUser(Long idUser); /** * 查询作者信息 + * * @param idUser * @return */ - Author selectAuthor(Integer idUser); + Author selectAuthor(Long idUser); /** * 更新用户扩展信息 + * * @param userExtend * @return */ - Map updateUserExtend(UserExtend userExtend); + UserExtend updateUserExtend(UserExtend userExtend) throws ServiceException; /** * 获取用户扩展信息 + * * @param account * @return */ @@ -125,29 +143,42 @@ public interface UserService extends Service { /** * 更换邮箱 + * * @param changeEmailDTO * @return + * @throws ServiceException */ - Map updateEmail(ChangeEmailDTO changeEmailDTO); + boolean updateEmail(ChangeEmailDTO changeEmailDTO) throws ServiceException; /** * 更新密码 + * * @param updatePasswordDTO * @return */ - Map updatePassword(UpdatePasswordDTO updatePasswordDTO); + boolean updatePassword(UpdatePasswordDTO updatePasswordDTO); /** * 查询用户列表 + * * @param searchDTO * @return */ List findUsers(UserSearchDTO searchDTO); /** - * 通过邮箱查询用户信息 + * 通过邮箱更新用户最后登录时间 + * * @param email * @return */ Integer updateLastOnlineTimeByEmail(String email); + + /** + * 查询用户扩展信息 + * + * @param idUser + * @return + */ + UserExtend findUserExtendInfo(Long idUser); } diff --git a/src/main/java/com/rymcu/forest/service/WxUserService.java b/src/main/java/com/rymcu/forest/service/WxUserService.java deleted file mode 100644 index 89a546d..0000000 --- a/src/main/java/com/rymcu/forest/service/WxUserService.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.rymcu.forest.service; - -import com.rymcu.forest.core.service.Service; -import com.rymcu.forest.entity.WxUser; -import me.chanjar.weixin.mp.bean.result.WxMpUser; - -/** - * @author ronger - */ -public interface WxUserService extends Service { - - WxUser saveUser(WxMpUser wxMpUser, String appId); - -} diff --git a/src/main/java/com/rymcu/forest/service/impl/ArticleServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/ArticleServiceImpl.java index f0bc2f2..7456c7c 100644 --- a/src/main/java/com/rymcu/forest/service/impl/ArticleServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/ArticleServiceImpl.java @@ -1,33 +1,42 @@ package com.rymcu.forest.service.impl; import com.rymcu.forest.core.constant.NotificationConstant; +import com.rymcu.forest.core.exception.BusinessException; +import com.rymcu.forest.core.exception.ContentNotExistException; +import com.rymcu.forest.core.exception.UltraViresException; import com.rymcu.forest.core.service.AbstractService; import com.rymcu.forest.dto.*; import com.rymcu.forest.entity.Article; import com.rymcu.forest.entity.ArticleContent; import com.rymcu.forest.entity.Tag; import com.rymcu.forest.entity.User; -import com.rymcu.forest.lucene.service.LuceneService; +import com.rymcu.forest.handler.event.ArticleDeleteEvent; +import com.rymcu.forest.handler.event.ArticleEvent; import com.rymcu.forest.mapper.ArticleMapper; import com.rymcu.forest.service.ArticleService; import com.rymcu.forest.service.NotificationService; import com.rymcu.forest.service.TagService; import com.rymcu.forest.service.UserService; -import com.rymcu.forest.util.*; +import com.rymcu.forest.util.Html2TextUtil; +import com.rymcu.forest.util.UserUtils; +import com.rymcu.forest.util.Utils; +import com.rymcu.forest.util.XssUtils; import com.rymcu.forest.web.api.exception.BaseApiException; import com.rymcu.forest.web.api.exception.ErrorCode; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import tk.mybatis.mapper.entity.Condition; import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; import java.io.UnsupportedEncodingException; -import java.util.*; +import java.util.Date; +import java.util.List; +import java.util.Objects; /** * @author ronger @@ -43,9 +52,9 @@ public class ArticleServiceImpl extends AbstractService
implements Arti @Resource private UserService userService; @Resource - private LuceneService luceneService; - @Resource private NotificationService notificationService; + @Resource + private ApplicationEventPublisher publisher; @Value("${resource.domain}") private String domain; @@ -68,7 +77,7 @@ public class ArticleServiceImpl extends AbstractService
implements Arti } @Override - public ArticleDTO findArticleDTOById(Integer id, Integer type) { + public ArticleDTO findArticleDTOById(Long id, Integer type) { ArticleDTO articleDTO = articleMapper.selectArticleDTOById(id, type); if (articleDTO == null) { return null; @@ -90,7 +99,7 @@ public class ArticleServiceImpl extends AbstractService
implements Arti } @Override - public List findUserArticlesByIdUser(Integer idUser) { + public List findUserArticlesByIdUser(Long idUser) { List list = articleMapper.selectUserArticles(idUser); list.forEach(articleDTO -> genArticle(articleDTO, 0)); return list; @@ -98,38 +107,25 @@ public class ArticleServiceImpl extends AbstractService
implements Arti @Override @Transactional(rollbackFor = {UnsupportedEncodingException.class, BaseApiException.class}) - public Map postArticle(ArticleDTO article, HttpServletRequest request) throws UnsupportedEncodingException, BaseApiException { - Map map = new HashMap(1); - if (StringUtils.isBlank(article.getArticleTitle())) { - map.put("message", "标题不能为空!"); - return map; - } - if (StringUtils.isBlank(article.getArticleContent())) { - map.put("message", "正文不能为空!"); - return map; - } + public Long postArticle(ArticleDTO article, User user) throws UnsupportedEncodingException, BaseApiException { boolean isUpdate = false; String articleTitle = article.getArticleTitle(); String articleTags = article.getArticleTags(); String articleContent = article.getArticleContent(); String articleContentHtml = XssUtils.filterHtmlCode(article.getArticleContentHtml()); - User user = UserUtils.getCurrentUserByToken(); - if (Objects.isNull(user)) { - throw new BaseApiException(ErrorCode.INVALID_TOKEN); - } String reservedTag = checkTags(articleTags); boolean notification = false; if (StringUtils.isNotBlank(reservedTag)) { Integer roleWeights = userService.findRoleWeightsByUser(user.getIdUser()); if (roleWeights > ADMIN_ROLE_WEIGHTS) { - map.put("message", StringEscapeUtils.unescapeJava(reservedTag) + "标签为系统保留标签!"); - return map; + throw new UltraViresException(StringEscapeUtils.unescapeJava(reservedTag) + "标签为系统保留标签!"); } else { notification = true; } } Article newArticle; - if (article.getIdArticle() == null || article.getIdArticle() == 0) { + Long idArticle = article.getIdArticle(); + if (idArticle == null || idArticle == 0) { newArticle = new Article(); newArticle.setArticleTitle(articleTitle); newArticle.setArticleAuthorId(user.getIdUser()); @@ -140,7 +136,7 @@ public class ArticleServiceImpl extends AbstractService
implements Arti articleMapper.insertSelective(newArticle); articleMapper.insertArticleContent(newArticle.getIdArticle(), articleContent, articleContentHtml); } else { - newArticle = articleMapper.selectByPrimaryKey(article.getIdArticle()); + newArticle = articleMapper.selectByPrimaryKey(idArticle); // 如果文章之前状态为草稿则应视为新发布文章 if (DEFAULT_STATUS.equals(newArticle.getArticleStatus())) { isUpdate = true; @@ -151,40 +147,17 @@ public class ArticleServiceImpl extends AbstractService
implements Arti newArticle.setUpdatedTime(new Date()); articleMapper.updateArticleContent(newArticle.getIdArticle(), articleContent, articleContentHtml); } - - // 发送相关通知 + Long newArticleId = newArticle.getIdArticle(); + // 更新文章链接 if (DEFAULT_STATUS.equals(newArticle.getArticleStatus())) { - // 发送系统通知 - if (notification) { - NotificationUtils.sendAnnouncement(newArticle.getIdArticle(), NotificationConstant.Article, newArticle.getArticleTitle()); - } else { - // 发送关注通知 - StringBuilder dataSummary = new StringBuilder(); - if (isUpdate) { - dataSummary.append(user.getNickname()).append("更新了文章: ").append(newArticle.getArticleTitle()); - NotificationUtils.sendArticlePush(newArticle.getIdArticle(), NotificationConstant.UpdateArticle, dataSummary.toString(), newArticle.getArticleAuthorId()); - } else { - dataSummary.append(user.getNickname()).append("发布了文章: ").append(newArticle.getArticleTitle()); - NotificationUtils.sendArticlePush(newArticle.getIdArticle(), NotificationConstant.PostArticle, dataSummary.toString(), newArticle.getArticleAuthorId()); - } - } - // 草稿不更新索引 - if (isUpdate) { - log.info("更新文章索引,id={}", newArticle.getIdArticle()); - luceneService.updateArticle(newArticle.getIdArticle().toString()); - } else { - log.info("写入文章索引,id={}", newArticle.getIdArticle()); - luceneService.writeArticle(newArticle.getIdArticle().toString()); - } - // 更新文章链接 - newArticle.setArticlePermalink(domain + "/article/" + newArticle.getIdArticle()); - newArticle.setArticleLink("/article/" + newArticle.getIdArticle()); + // 文章 + newArticle.setArticlePermalink(domain + "/article/" + newArticleId); + newArticle.setArticleLink("/article/" + newArticleId); } else { - // 更新文章链接 - newArticle.setArticlePermalink(domain + "/draft/" + newArticle.getIdArticle()); - newArticle.setArticleLink("/draft/" + newArticle.getIdArticle()); + // 草稿 + newArticle.setArticlePermalink(domain + "/draft/" + newArticleId); + newArticle.setArticleLink("/draft/" + newArticleId); } - tagService.saveTagArticle(newArticle, articleContentHtml); if (StringUtils.isNotBlank(articleContentHtml)) { String previewContent = Html2TextUtil.getContent(articleContentHtml); @@ -194,66 +167,34 @@ public class ArticleServiceImpl extends AbstractService
implements Arti newArticle.setArticlePreviewContent(previewContent); } articleMapper.updateByPrimaryKeySelective(newArticle); - - map.put("id", newArticle.getIdArticle()); - return map; - } - - private String checkTags(String articleTags) { - // 判断文章是否有标签 - if (StringUtils.isBlank(articleTags)) { - return ""; + // 更新标签 + tagService.saveTagArticle(newArticle, articleContentHtml, user.getIdUser()); + if (DEFAULT_STATUS.equals(newArticle.getArticleStatus())) { + // 文章发布事件 + publisher.publishEvent(new ArticleEvent(newArticleId, newArticle.getArticleTitle(), isUpdate, notification, user.getNickname(), newArticle.getArticleAuthorId())); } - // 判断是否存在系统配置的保留标签词 - Condition condition = new Condition(Tag.class); - condition.createCriteria().andEqualTo("tagReservation", "1"); - List tags = tagService.findByCondition(condition); - if (tags.isEmpty()) { - return ""; - } else { - String[] articleTagArr = articleTags.split(","); - for (Tag tag : tags) { - if (StringUtils.isBlank(tag.getTagTitle())) { - continue; - } - - for (String articleTag : articleTagArr) { - if (StringUtils.isBlank(articleTag)) { - continue; - } - if (articleTag.equals(tag.getTagTitle())) { - return tag.getTagTitle(); - } - } - } - } - - return ""; + return newArticleId; } @Override @Transactional(rollbackFor = Exception.class) - public Map delete(Integer id) throws BaseApiException { - Map map = new HashMap(1); - int result; + public Integer delete(Long id) throws BaseApiException { // 判断是否有评论 - boolean isHavComment = articleMapper.existsCommentWithPrimaryKey(id); - if (isHavComment) { - map.put("message", "已有评论的文章不允许删除!"); - } else { + if (!articleMapper.existsCommentWithPrimaryKey(id)) { // 删除关联数据(作品集关联关系,标签关联关系) deleteLinkedData(id); // 删除文章 - result = articleMapper.deleteByPrimaryKey(id); - luceneService.deleteArticle(id.toString()); - if (result < 1) { - map.put("message", "删除失败!"); + int result = articleMapper.deleteByPrimaryKey(id); + if (result > 0) { + publisher.publishEvent(new ArticleDeleteEvent(id)); } + return result; + } else { + throw new BusinessException("已有评论的文章不允许删除!"); } - return map; } - private void deleteLinkedData(Integer id) { + private void deleteLinkedData(Long id) { // 删除关联作品集 articleMapper.deleteLinkedPortfolioData(id); // 删除引用标签记录 @@ -266,44 +207,38 @@ public class ArticleServiceImpl extends AbstractService
implements Arti @Override @Transactional(rollbackFor = Exception.class) - public void incrementArticleViewCount(Integer id) { + public void incrementArticleViewCount(Long id) { Article article = articleMapper.selectByPrimaryKey(id); Integer articleViewCount = article.getArticleViewCount() + 1; articleMapper.updateArticleViewCount(article.getIdArticle(), articleViewCount); } @Override - public Map share(Integer id) throws BaseApiException { + public String share(Integer id) throws BaseApiException { Article article = articleMapper.selectByPrimaryKey(id); User user = UserUtils.getCurrentUserByToken(); if (Objects.isNull(user)) { throw new BaseApiException(ErrorCode.INVALID_TOKEN); } - Map map = new HashMap(2); - map.put("shareUrl", article.getArticlePermalink() + "?s=" + user.getAccount()); - return map; + return article.getArticlePermalink() + "?s=" + user.getAccount(); } @Override - public List findDrafts() throws BaseApiException { - User user = UserUtils.getCurrentUserByToken(); - if (Objects.isNull(user)) { - throw new BaseApiException(ErrorCode.INVALID_TOKEN); - } - List list = articleMapper.selectDrafts(user.getIdUser()); + public List findDrafts(Long userId) { + List list = articleMapper.selectDrafts(userId); list.forEach(articleDTO -> genArticle(articleDTO, 0)); return list; } @Override - public List findArticlesByIdPortfolio(Integer idPortfolio) { + public List findArticlesByIdPortfolio(Long idPortfolio) { List list = articleMapper.selectArticlesByIdPortfolio(idPortfolio); list.forEach(articleDTO -> genArticle(articleDTO, 0)); return list; } @Override - public List selectUnbindArticles(Integer idPortfolio, String searchText, Integer idUser) { + public List selectUnbindArticles(Long idPortfolio, String searchText, Long idUser) { List list = articleMapper.selectUnbindArticlesByIdPortfolio(idPortfolio, searchText, idUser); list.forEach(articleDTO -> genArticle(articleDTO, 0)); return list; @@ -311,32 +246,23 @@ public class ArticleServiceImpl extends AbstractService
implements Arti @Override @Transactional(rollbackFor = Exception.class) - public Map updateTags(Integer idArticle, String tags) throws UnsupportedEncodingException, BaseApiException { - Map map = new HashMap(2); + public Boolean updateTags(Long idArticle, String tags, Long userId) throws UnsupportedEncodingException, BaseApiException { Article article = articleMapper.selectByPrimaryKey(idArticle); - if (Objects.nonNull(article)) { - article.setArticleTags(tags); - articleMapper.updateArticleTags(idArticle, tags); - tagService.saveTagArticle(article, ""); - map.put("success", true); - } else { - map.put("success", false); - map.put("message", "更新失败,文章不存在!"); + if (!Objects.nonNull(article)) { + throw new ContentNotExistException("更新失败,文章不存在!"); } - return map; + article.setArticleTags(tags); + articleMapper.updateArticleTags(idArticle, tags); + tagService.saveTagArticle(article, "", userId); + return true; } @Override - public Map updatePerfect(Integer idArticle, String articlePerfect) { - Map map = new HashMap(2); - int result = articleMapper.updatePerfect(idArticle, articlePerfect); - if (result == 0) { - map.put("success", false); - map.put("message", "设置优选文章失败!"); - } else { - map.put("success", true); + public Boolean updatePerfect(Long idArticle, String articlePerfect) { + if (articleMapper.updatePerfect(idArticle, articlePerfect) == 0) { + throw new ContentNotExistException("设置优选文章失败!"); } - return map; + return true; } @Override @@ -387,4 +313,36 @@ public class ArticleServiceImpl extends AbstractService
implements Arti author.setUserAccount(user.getAccount()); return author; } + + private String checkTags(String articleTags) { + // 判断文章是否有标签 + if (StringUtils.isBlank(articleTags)) { + return ""; + } + // 判断是否存在系统配置的保留标签词 + Condition condition = new Condition(Tag.class); + condition.createCriteria().andEqualTo("tagReservation", "1"); + List tags = tagService.findByCondition(condition); + if (tags.isEmpty()) { + return ""; + } else { + String[] articleTagArr = articleTags.split(","); + for (Tag tag : tags) { + if (StringUtils.isBlank(tag.getTagTitle())) { + continue; + } + + for (String articleTag : articleTagArr) { + if (StringUtils.isBlank(articleTag)) { + continue; + } + if (articleTag.equals(tag.getTagTitle())) { + return tag.getTagTitle(); + } + } + } + } + + return ""; + } } diff --git a/src/main/java/com/rymcu/forest/service/impl/ArticleThumbsUpServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/ArticleThumbsUpServiceImpl.java index 4dcf87a..feb2ee1 100644 --- a/src/main/java/com/rymcu/forest/service/impl/ArticleThumbsUpServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/ArticleThumbsUpServiceImpl.java @@ -1,21 +1,17 @@ package com.rymcu.forest.service.impl; +import com.rymcu.forest.core.exception.BusinessException; import com.rymcu.forest.core.service.AbstractService; import com.rymcu.forest.entity.Article; import com.rymcu.forest.entity.ArticleThumbsUp; -import com.rymcu.forest.entity.User; import com.rymcu.forest.mapper.ArticleThumbsUpMapper; import com.rymcu.forest.service.ArticleService; import com.rymcu.forest.service.ArticleThumbsUpService; -import com.rymcu.forest.util.UserUtils; -import com.rymcu.forest.web.api.exception.BaseApiException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.Date; -import java.util.HashMap; -import java.util.Map; import java.util.Objects; /** @@ -31,40 +27,25 @@ public class ArticleThumbsUpServiceImpl extends AbstractService @Override @Transactional(rollbackFor = Exception.class) - public Map thumbsUp(ArticleThumbsUp articleThumbsUp) throws BaseApiException { - Map map = new HashMap(3); - if (Objects.isNull(articleThumbsUp) || Objects.isNull(articleThumbsUp.getIdArticle())) { - map.put("message", "数据异常,文章不存在!"); - map.put("success", false); + public int thumbsUp(ArticleThumbsUp articleThumbsUp) { + int thumbsUpNumber = 1; + Article article = articleService.findById(String.valueOf(articleThumbsUp.getIdArticle())); + if (Objects.isNull(article)) { + throw new BusinessException("数据异常,文章不存在!"); } else { - Integer thumbsUpNumber = 1; - Article article = articleService.findById(String.valueOf(articleThumbsUp.getIdArticle())); - if (Objects.isNull(article)) { - map.put("message", "数据异常,文章不存在!"); - map.put("success", false); + ArticleThumbsUp thumbsUp = articleThumbsUpMapper.selectOne(articleThumbsUp); + if (Objects.isNull(thumbsUp)) { + // 点赞 + articleThumbsUp.setThumbsUpTime(new Date()); + articleThumbsUpMapper.insertSelective(articleThumbsUp); } else { - User user = UserUtils.getCurrentUserByToken(); - articleThumbsUp.setIdUser(user.getIdUser()); - ArticleThumbsUp thumbsUp = articleThumbsUpMapper.selectOne(articleThumbsUp); - if (Objects.isNull(thumbsUp)) { - articleThumbsUp.setThumbsUpTime(new Date()); - articleThumbsUpMapper.insertSelective(articleThumbsUp); - // 更新文章点赞数 - } else { - articleThumbsUpMapper.deleteByPrimaryKey(thumbsUp.getIdArticleThumbsUp()); - // 更新文章点赞数 - thumbsUpNumber = -1; - } - articleThumbsUpMapper.updateArticleThumbsUpNumber(articleThumbsUp.getIdArticle(), thumbsUpNumber); - map.put("success", true); - map.put("thumbsUpNumber", thumbsUpNumber); - if (thumbsUpNumber > 0) { - map.put("message", "点赞成功"); - } else { - map.put("message", "已取消点赞"); - } + // 取消点赞 + articleThumbsUpMapper.deleteByPrimaryKey(thumbsUp.getIdArticleThumbsUp()); + thumbsUpNumber = -1; } + // 更新文章点赞数 + articleThumbsUpMapper.updateArticleThumbsUpNumber(articleThumbsUp.getIdArticle(), thumbsUpNumber); + return thumbsUpNumber; } - return map; } } diff --git a/src/main/java/com/rymcu/forest/service/impl/BankAccountServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/BankAccountServiceImpl.java index 7bd4ba5..960c592 100644 --- a/src/main/java/com/rymcu/forest/service/impl/BankAccountServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/BankAccountServiceImpl.java @@ -37,7 +37,7 @@ public class BankAccountServiceImpl extends AbstractService impleme } @Override - public BankAccountDTO findBankAccountByIdUser(Integer idUser) { + public BankAccountDTO findBankAccountByIdUser(Long idUser) { BankAccount bankAccount = new BankAccount(); bankAccount.setAccountOwner(idUser); String defaultAccountType = "0"; @@ -49,7 +49,7 @@ public class BankAccountServiceImpl extends AbstractService impleme } else { bankAccount.setAccountBalance(new BigDecimal("0")); // 默认为社区发展与改革银行 - bankAccount.setIdBank(2); + bankAccount.setIdBank(2L); bankAccount.setBankAccount(nextBankAccount()); bankAccount.setCreatedTime(new Date()); bankAccountMapper.insertSelective(bankAccount); @@ -77,9 +77,9 @@ public class BankAccountServiceImpl extends AbstractService impleme @Override public BankAccount findSystemBankAccount() { BankAccount bankAccount = new BankAccount(); - bankAccount.setIdBank(1); + bankAccount.setIdBank(1L); bankAccount.setAccountType("1"); - bankAccount.setAccountOwner(2); + bankAccount.setAccountOwner(2L); return bankAccountMapper.selectOne(bankAccount); } diff --git a/src/main/java/com/rymcu/forest/service/impl/CommentServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/CommentServiceImpl.java index 6773cc1..f27149c 100644 --- a/src/main/java/com/rymcu/forest/service/impl/CommentServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/CommentServiceImpl.java @@ -1,23 +1,26 @@ package com.rymcu.forest.service.impl; -import com.rymcu.forest.core.constant.NotificationConstant; +import com.rymcu.forest.core.exception.ContentNotExistException; import com.rymcu.forest.core.service.AbstractService; import com.rymcu.forest.dto.Author; import com.rymcu.forest.dto.CommentDTO; import com.rymcu.forest.entity.Article; import com.rymcu.forest.entity.Comment; +import com.rymcu.forest.handler.event.CommentEvent; import com.rymcu.forest.mapper.CommentMapper; import com.rymcu.forest.service.ArticleService; import com.rymcu.forest.service.CommentService; -import com.rymcu.forest.util.*; -import com.rymcu.forest.web.api.exception.BaseApiException; +import com.rymcu.forest.util.Utils; +import com.rymcu.forest.util.XssUtils; import org.apache.commons.lang.StringUtils; +import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; -import java.util.*; +import java.util.Date; +import java.util.List; /** * @author ronger @@ -29,8 +32,8 @@ public class CommentServiceImpl extends AbstractService implements Comm private CommentMapper commentMapper; @Resource private ArticleService articleService; - - private static final int MAX_PREVIEW = 200; + @Resource + private ApplicationEventPublisher applicationEventPublisher; @Override public List getArticleComments(Integer idArticle) { @@ -63,25 +66,19 @@ public class CommentServiceImpl extends AbstractService implements Comm @Override @Transactional(rollbackFor = Exception.class) - public Map postComment(Comment comment, HttpServletRequest request) throws BaseApiException { - comment.setCommentAuthorId(Objects.requireNonNull(UserUtils.getCurrentUserByToken()).getIdUser()); - Map map = new HashMap(1); + public Comment postComment(Comment comment, HttpServletRequest request) { if (comment.getCommentArticleId() == null) { - map.put("message", "非法访问,文章主键异常!"); - return map; + throw new IllegalArgumentException("非法访问,文章主键异常!"); } if (comment.getCommentAuthorId() == null) { - map.put("message", "非法访问,用户未登录!"); - return map; + throw new IllegalArgumentException("非法访问,用户未登录!"); } if (StringUtils.isBlank(comment.getCommentContent())) { - map.put("message", "回帖内容不能为空!"); - return map; + throw new IllegalArgumentException("回帖内容不能为空!"); } Article article = articleService.findById(comment.getCommentArticleId().toString()); if (article == null) { - map.put("message", "文章不存在!"); - return map; + throw new ContentNotExistException("文章不存在!"); } String ip = Utils.getIpAddress(request); String ua = request.getHeader("user-agent"); @@ -95,28 +92,9 @@ public class CommentServiceImpl extends AbstractService implements Comm String commentContent = comment.getCommentContent(); if (StringUtils.isNotBlank(commentContent)) { - Integer length = commentContent.length(); - if (length > MAX_PREVIEW) { - length = 200; - } - String commentPreviewContent = commentContent.substring(0, length); - commentContent = Html2TextUtil.getContent(commentPreviewContent); - // 评论者不是作者本人则进行消息通知 - if (!article.getArticleAuthorId().equals(comment.getCommentAuthorId())) { - NotificationUtils.saveNotification(article.getArticleAuthorId(), comment.getIdComment(), NotificationConstant.Comment, commentContent); - } - // 判断是否是回复消息 - if (comment.getCommentOriginalCommentId() != null && comment.getCommentOriginalCommentId() != 0) { - Comment originalComment = commentMapper.selectByPrimaryKey(comment.getCommentOriginalCommentId()); - // 回复消息时,评论者不是上级评论作者则进行消息通知 - if (!comment.getCommentAuthorId().equals(originalComment.getCommentAuthorId())) { - NotificationUtils.saveNotification(originalComment.getCommentAuthorId(), comment.getIdComment(), NotificationConstant.Comment, commentContent); - } - } + applicationEventPublisher.publishEvent(new CommentEvent(comment.getIdComment(), article.getArticleAuthorId(), comment.getCommentAuthorId(), commentContent, comment.getCommentOriginalCommentId())); } - - - return map; + return comment; } @Override diff --git a/src/main/java/com/rymcu/forest/service/impl/DashboardServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/DashboardServiceImpl.java index 8c6bf0c..633908d 100644 --- a/src/main/java/com/rymcu/forest/service/impl/DashboardServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/DashboardServiceImpl.java @@ -13,7 +13,10 @@ import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.time.LocalDate; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; /** * @author ronger diff --git a/src/main/java/com/rymcu/forest/service/impl/FollowServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/FollowServiceImpl.java index 5985562..e069c0c 100644 --- a/src/main/java/com/rymcu/forest/service/impl/FollowServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/FollowServiceImpl.java @@ -51,7 +51,7 @@ public class FollowServiceImpl extends AbstractService implements Follow } @Override - public List findByFollowingId(String followType, Integer followingId) { + public List findByFollowingId(String followType, Long followingId) { Follow follow = new Follow(); follow.setFollowingType(followType); follow.setFollowingId(followingId); diff --git a/src/main/java/com/rymcu/forest/service/impl/LoginRecordServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/LoginRecordServiceImpl.java index b253b36..8d7e33e 100644 --- a/src/main/java/com/rymcu/forest/service/impl/LoginRecordServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/LoginRecordServiceImpl.java @@ -33,7 +33,7 @@ public class LoginRecordServiceImpl extends AbstractService impleme @Override @Transactional(rollbackFor = Exception.class) - public LoginRecord saveLoginRecord(Integer idUser) { + public LoginRecord saveLoginRecord(Long idUser) { HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); String ip = Utils.getIpAddress(request); String ua = request.getHeader("user-agent"); diff --git a/src/main/java/com/rymcu/forest/service/impl/NotificationServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/NotificationServiceImpl.java index 18143ea..82b256e 100644 --- a/src/main/java/com/rymcu/forest/service/impl/NotificationServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/NotificationServiceImpl.java @@ -28,12 +28,12 @@ public class NotificationServiceImpl extends AbstractService imple private final static String UN_READ = "0"; @Override - public List findUnreadNotifications(Integer idUser) { + public List findUnreadNotifications(Long idUser) { return notificationMapper.selectUnreadNotifications(idUser); } @Override - public List findNotifications(Integer idUser) { + public List findNotifications(Long idUser) { List list = notificationMapper.selectNotifications(idUser); list.forEach(notification -> { NotificationDTO notificationDTO = NotificationUtils.genNotification(notification); @@ -57,19 +57,19 @@ public class NotificationServiceImpl extends AbstractService imple } @Override - public Notification findNotification(Integer idUser, Integer dataId, String dataType) { + public Notification findNotification(Long idUser, Long dataId, String dataType) { return notificationMapper.selectNotification(idUser, dataId, dataType); } @Override @Transactional(rollbackFor = Exception.class) - public Integer save(Integer idUser, Integer dataId, String dataType, String dataSummary) { + public Integer save(Long idUser, Long dataId, String dataType, String dataSummary) { return notificationMapper.insertNotification(idUser, dataId, dataType, dataSummary); } @Override @Transactional(rollbackFor = Exception.class) - public Integer readNotification(Integer id) { + public Integer readNotification(Long id) { return notificationMapper.readNotification(id); } @@ -79,7 +79,7 @@ public class NotificationServiceImpl extends AbstractService imple } @Override - public Integer deleteUnreadNotification(Integer dataId, String dataType) { + public Integer deleteUnreadNotification(Long dataId, String dataType) { return notificationMapper.deleteUnreadNotification(dataId, dataType); } } diff --git a/src/main/java/com/rymcu/forest/service/impl/PortfolioServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/PortfolioServiceImpl.java index c0de668..7d417fb 100644 --- a/src/main/java/com/rymcu/forest/service/impl/PortfolioServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/PortfolioServiceImpl.java @@ -2,30 +2,26 @@ package com.rymcu.forest.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; +import com.rymcu.forest.core.exception.BusinessException; +import com.rymcu.forest.core.exception.ServiceException; +import com.rymcu.forest.core.exception.UltraViresException; import com.rymcu.forest.core.service.AbstractService; import com.rymcu.forest.dto.*; -import com.rymcu.forest.entity.Article; import com.rymcu.forest.entity.Portfolio; -import com.rymcu.forest.entity.User; import com.rymcu.forest.lucene.model.PortfolioLucene; import com.rymcu.forest.lucene.util.PortfolioIndexUtil; import com.rymcu.forest.mapper.PortfolioMapper; import com.rymcu.forest.service.ArticleService; import com.rymcu.forest.service.PortfolioService; import com.rymcu.forest.service.UserService; -import com.rymcu.forest.util.UserUtils; -import com.rymcu.forest.util.Utils; import com.rymcu.forest.util.XssUtils; import com.rymcu.forest.web.api.common.UploadController; -import com.rymcu.forest.web.api.exception.BaseApiException; import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.Date; -import java.util.HashMap; import java.util.List; -import java.util.Map; /** * @author ronger @@ -45,7 +41,7 @@ public class PortfolioServiceImpl extends AbstractService implements List list = portfolioMapper.selectUserPortfoliosByIdUser(userDTO.getIdUser()); Author author = userService.selectAuthor(userDTO.getIdUser()); list.forEach(portfolioDTO -> { - genPortfolioAuthor(portfolioDTO,author); + genPortfolioAuthor(portfolioDTO, author); Integer articleNumber = portfolioMapper.selectCountArticleNumber(portfolioDTO.getIdPortfolio()); portfolioDTO.setArticleNumber(articleNumber); }); @@ -53,34 +49,32 @@ public class PortfolioServiceImpl extends AbstractService implements } @Override - public PortfolioDTO findPortfolioDTOById(Integer idPortfolio, Integer type) { - PortfolioDTO portfolio = portfolioMapper.selectPortfolioDTOById(idPortfolio,type); + public PortfolioDTO findPortfolioDTOById(Long idPortfolio, Integer type) { + PortfolioDTO portfolio = portfolioMapper.selectPortfolioDTOById(idPortfolio, type); if (portfolio == null) { return new PortfolioDTO(); } Author author = userService.selectAuthor(portfolio.getPortfolioAuthorId()); - genPortfolioAuthor(portfolio,author); + genPortfolioAuthor(portfolio, author); Integer articleNumber = portfolioMapper.selectCountArticleNumber(portfolio.getIdPortfolio()); portfolio.setArticleNumber(articleNumber); return portfolio; } @Override - public Portfolio postPortfolio(Portfolio portfolio) throws BaseApiException { - User user = UserUtils.getCurrentUserByToken(); + public Portfolio postPortfolio(Portfolio portfolio) { if (StringUtils.isNotBlank(portfolio.getHeadImgType())) { String headImgUrl = UploadController.uploadBase64File(portfolio.getHeadImgUrl(), 0); portfolio.setHeadImgUrl(headImgUrl); } if (portfolio.getIdPortfolio() == null || portfolio.getIdPortfolio() == 0) { - portfolio.setPortfolioAuthorId(user.getIdUser()); portfolio.setCreatedTime(new Date()); portfolio.setUpdatedTime(portfolio.getCreatedTime()); portfolio.setPortfolioDescriptionHtml(XssUtils.filterHtmlCode(portfolio.getPortfolioDescription())); portfolioMapper.insertSelective(portfolio); PortfolioIndexUtil.addIndex( PortfolioLucene.builder() - .idPortfolio(portfolio.getIdPortfolio().toString()) + .idPortfolio(portfolio.getIdPortfolio()) .portfolioTitle(portfolio.getPortfolioTitle()) .portfolioDescription(portfolio.getPortfolioDescription()) .build()); @@ -89,7 +83,7 @@ public class PortfolioServiceImpl extends AbstractService implements portfolioMapper.updateByPrimaryKeySelective(portfolio); PortfolioIndexUtil.updateIndex( PortfolioLucene.builder() - .idPortfolio(portfolio.getIdPortfolio().toString()) + .idPortfolio(portfolio.getIdPortfolio()) .portfolioTitle(portfolio.getPortfolioTitle()) .portfolioDescription(portfolio.getPortfolioDescription()) .build()); @@ -98,108 +92,78 @@ public class PortfolioServiceImpl extends AbstractService implements } @Override - public Map findUnbindArticles(Integer page, Integer rows, String searchText, Integer idPortfolio) throws BaseApiException { - Map map = new HashMap(1); - User user = UserUtils.getCurrentUserByToken(); + public PageInfo findUnbindArticles(Integer page, Integer rows, String searchText, Long idPortfolio, Long idUser) { Portfolio portfolio = portfolioMapper.selectByPrimaryKey(idPortfolio); if (portfolio == null) { - map.put("message", "该作品集不存在或已被删除!"); + throw new BusinessException("该作品集不存在或已被删除!"); } else { - if (!user.getIdUser().equals(portfolio.getPortfolioAuthorId())) { - map.put("message", "非法操作!"); + if (!idUser.equals(portfolio.getPortfolioAuthorId())) { + throw new UltraViresException("非法操作!"); } else { PageHelper.startPage(page, rows); - List articles = articleService.selectUnbindArticles(idPortfolio,searchText,user.getIdUser()); - PageInfo pageInfo = new PageInfo(articles); - map = Utils.getArticlesGlobalResult(pageInfo); + List articles = articleService.selectUnbindArticles(idPortfolio, searchText, idUser); + return new PageInfo<>(articles); } } - return map; } @Override - public Map bindArticle(PortfolioArticleDTO portfolioArticle) { - Map map = new HashMap(1); + public boolean bindArticle(PortfolioArticleDTO portfolioArticle) throws ServiceException { Integer count = portfolioMapper.selectCountPortfolioArticle(portfolioArticle.getIdArticle(), portfolioArticle.getIdPortfolio()); if (count.equals(0)) { Integer maxSortNo = portfolioMapper.selectMaxSortNo(portfolioArticle.getIdPortfolio()); - portfolioMapper.insertPortfolioArticle(portfolioArticle.getIdArticle(),portfolioArticle.getIdPortfolio(),maxSortNo); - map.put("message", "绑定成功!"); + Integer result = portfolioMapper.insertPortfolioArticle(portfolioArticle.getIdArticle(), portfolioArticle.getIdPortfolio(), maxSortNo); + if (result == 0) { + throw new ServiceException("更新失败!"); + } } else { - map.put("message", "该文章已经在作品集下!!"); + throw new BusinessException("该文章已经在作品集下!!"); } - return map; + return true; } @Override - public Map updateArticleSortNo(PortfolioArticleDTO portfolioArticle) { - Map map = new HashMap(1); - if (portfolioArticle.getIdPortfolio() == null || portfolioArticle.getIdPortfolio().equals(0)) { - map.put("message", "作品集数据异常!"); + public boolean updateArticleSortNo(PortfolioArticleDTO portfolioArticle) throws ServiceException { + Integer result = portfolioMapper.updateArticleSortNo(portfolioArticle.getIdPortfolio(), portfolioArticle.getIdArticle(), portfolioArticle.getSortNo()); + if (result == 0) { + throw new ServiceException("更新失败!"); } - if (portfolioArticle.getIdArticle() == null || portfolioArticle.getIdArticle().equals(0)) { - map.put("message", "文章数据异常!"); - } - if (portfolioArticle.getSortNo() == null) { - map.put("message", "排序号不能为空!"); - } - Integer result = portfolioMapper.updateArticleSortNo(portfolioArticle.getIdPortfolio(),portfolioArticle.getIdArticle(),portfolioArticle.getSortNo()); - if (result > 0) { - map.put("message", "更新成功!"); - } else { - map.put("message", "更新失败!"); - } - return map; + return true; } @Override - public Map unbindArticle(Integer idPortfolio, Integer idArticle) { - Map map = new HashMap(1); - if (idPortfolio == null || idPortfolio.equals(0)) { - map.put("message", "作品集数据异常"); + public boolean unbindArticle(Long idPortfolio, Long idArticle) throws ServiceException { + Integer result = portfolioMapper.unbindArticle(idPortfolio, idArticle); + if (result == 0) { + throw new ServiceException("操作失败!"); } - if (idArticle == null || idArticle.equals(0)) { - map.put("message", "文章数据异常"); - } - Integer result = portfolioMapper.unbindArticle(idPortfolio,idArticle); - if (result > 0) { - map.put("message", "操作成功!"); - } else { - map.put("message", "操作失败!"); - } - return map; + return true; } @Override - public Map deletePortfolio(Integer idPortfolio) throws BaseApiException { - Map map = new HashMap(1); - if (idPortfolio == null || idPortfolio.equals(0)) { - map.put("message", "作品集数据异常"); + public boolean deletePortfolio(Long idPortfolio, Long idUser, Integer roleWeights) { + if (idPortfolio == null || idPortfolio == 0) { + throw new IllegalArgumentException("作品集数据异常!"); } // 鉴权 - User user = UserUtils.getCurrentUserByToken(); - Integer roleWeights = userService.findRoleWeightsByUser(user.getIdUser()); if (roleWeights > 2) { Portfolio portfolio = portfolioMapper.selectByPrimaryKey(idPortfolio); - if (!user.getIdUser().equals(portfolio.getPortfolioAuthorId())) { - map.put("message", "非法访问!"); - return map; + if (!idUser.equals(portfolio.getPortfolioAuthorId())) { + throw new UltraViresException("非法访问!"); } } Integer articleNumber = portfolioMapper.selectCountArticleNumber(idPortfolio); if (articleNumber > 0) { - map.put("message", "该作品集已绑定文章不允许删除!"); + throw new BusinessException("该作品集已绑定文章不允许删除!"); } else { Integer result = portfolioMapper.deleteByPrimaryKey(idPortfolio); if (result.equals(0)) { - map.put("message", "操作失败!"); - }else { - PortfolioIndexUtil.deleteIndex(String.valueOf(idPortfolio)); + throw new BusinessException("操作失败!"); } + PortfolioIndexUtil.deleteIndex(idPortfolio); + return true; } - - return map; } @Override diff --git a/src/main/java/com/rymcu/forest/service/impl/ProductServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/ProductServiceImpl.java new file mode 100644 index 0000000..3e62b56 --- /dev/null +++ b/src/main/java/com/rymcu/forest/service/impl/ProductServiceImpl.java @@ -0,0 +1,36 @@ +package com.rymcu.forest.service.impl; + +import com.rymcu.forest.core.service.AbstractService; +import com.rymcu.forest.dto.ProductDTO; +import com.rymcu.forest.entity.Product; +import com.rymcu.forest.mapper.ProductMapper; +import com.rymcu.forest.service.ProductService; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.List; + +/** + * Created on 2022/6/21 9:26. + * + * @author ronger + * @email ronger-x@outlook.com + * @packageName com.rymcu.forest.service.impl + */ +@Service +public class ProductServiceImpl extends AbstractService implements ProductService { + + @Resource + private ProductMapper productMapper; + + @Override + public List findProducts() { + return productMapper.selectProducts(); + } + + @Override + public ProductDTO findProductDTOById(Integer idProduct, Integer type) { + ProductDTO productDTO = productMapper.selectProductDTOById(idProduct, type); + return productDTO; + } +} diff --git a/src/main/java/com/rymcu/forest/service/impl/RoleServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/RoleServiceImpl.java index cc0e387..78860fb 100644 --- a/src/main/java/com/rymcu/forest/service/impl/RoleServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/RoleServiceImpl.java @@ -1,5 +1,6 @@ package com.rymcu.forest.service.impl; +import com.rymcu.forest.core.exception.ServiceException; import com.rymcu.forest.core.service.AbstractService; import com.rymcu.forest.entity.Role; import com.rymcu.forest.entity.User; @@ -10,9 +11,7 @@ import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.Date; -import java.util.HashMap; import java.util.List; -import java.util.Map; /** @@ -27,44 +26,39 @@ public class RoleServiceImpl extends AbstractService implements RoleServic @Override public List selectRoleByUser(User sysUser) { - List roles = roleMapper.selectRoleByIdUser(sysUser.getIdUser()); - return roles; + return roleMapper.selectRoleByIdUser(sysUser.getIdUser()); } @Override - public List findByIdUser(Integer idUser) { + public List findByIdUser(Long idUser) { return roleMapper.selectRoleByIdUser(idUser); } @Override - @Transactional - public Map updateStatus(Integer idRole, String status) { - Map map = new HashMap(1); - Integer result = roleMapper.updateStatus(idRole,status); - if(result == 0) { - map.put("message","更新失败!"); + @Transactional(rollbackFor = Exception.class) + public boolean updateStatus(Long idRole, String status) throws ServiceException { + Integer result = roleMapper.updateStatus(idRole, status); + if (result == 0) { + throw new ServiceException("更新失败"); } - return map; + return true; } @Override - public Map saveRole(Role role) { - Integer result = 0; + public boolean saveRole(Role role) throws ServiceException { + Integer result; if (role.getIdRole() == null) { role.setCreatedTime(new Date()); role.setUpdatedTime(role.getCreatedTime()); result = roleMapper.insertSelective(role); } else { role.setCreatedTime(new Date()); - result = roleMapper.update(role.getIdRole(),role.getName(),role.getInputCode(),role.getWeights()); + result = roleMapper.update(role.getIdRole(), role.getName(), role.getInputCode(), role.getWeights()); } - Map map = new HashMap(1); if (result == 0) { - map.put("message","操作失败!"); - } else { - map.put("role", role); + throw new ServiceException("操作失败!"); } - return map; + return true; } } diff --git a/src/main/java/com/rymcu/forest/service/impl/SponsorServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/SponsorServiceImpl.java index f8db4ea..c9f2216 100644 --- a/src/main/java/com/rymcu/forest/service/impl/SponsorServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/SponsorServiceImpl.java @@ -1,6 +1,7 @@ package com.rymcu.forest.service.impl; +import com.rymcu.forest.core.exception.ServiceException; import com.rymcu.forest.core.exception.TransactionException; import com.rymcu.forest.core.service.AbstractService; import com.rymcu.forest.dto.ArticleDTO; @@ -19,7 +20,8 @@ import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.math.BigDecimal; -import java.util.*; +import java.util.Date; +import java.util.Objects; /** * @author ronger @@ -36,32 +38,25 @@ public class SponsorServiceImpl extends AbstractService implements Spon @Override @Transactional(rollbackFor = Exception.class) - public Map sponsorship(Sponsor sponsor) throws Exception { - Map map = new HashMap(2); - if (Objects.isNull(sponsor) || Objects.isNull(sponsor.getDataId()) || Objects.isNull(sponsor.getDataType())) { - map.put("success", false); - map.put("message", "数据异常"); - } else { - TransactionEnum result = TransactionEnum.findTransactionEnum(sponsor.getDataType()); - BigDecimal money = BigDecimal.valueOf(result.getMoney()); - sponsor.setSponsorshipMoney(money); - User user = UserUtils.getCurrentUserByToken(); - sponsor.setSponsor(user.getIdUser()); - sponsor.setSponsorshipTime(new Date()); - sponsorMapper.insertSelective(sponsor); - // 赞赏金额划转 - if (result.isArticleSponsor()) { - ArticleDTO articleDTO = articleService.findArticleDTOById(sponsor.getDataId(), 1); - TransactionRecord transactionRecord = transactionRecordService.userTransfer(articleDTO.getArticleAuthorId(), user.getIdUser(), result); - if (Objects.isNull(transactionRecord.getIdTransactionRecord())) { - throw new TransactionException(TransactionCode.InsufficientBalance); - } - // 更新文章赞赏数 - sponsorMapper.updateArticleSponsorCount(articleDTO.getIdArticle()); + public boolean sponsorship(Sponsor sponsor) throws Exception { + TransactionEnum transactionEnum = TransactionEnum.findTransactionEnum(sponsor.getDataType()); + BigDecimal money = BigDecimal.valueOf(transactionEnum.getMoney()); + sponsor.setSponsorshipMoney(money); + sponsor.setSponsorshipTime(new Date()); + sponsorMapper.insertSelective(sponsor); + // 赞赏金额划转 + if (transactionEnum.isArticleSponsor()) { + ArticleDTO articleDTO = articleService.findArticleDTOById(sponsor.getDataId(), 1); + TransactionRecord transactionRecord = transactionRecordService.userTransfer(articleDTO.getArticleAuthorId(), sponsor.getSponsor(), transactionEnum); + if (Objects.isNull(transactionRecord.getIdTransactionRecord())) { + throw new TransactionException(TransactionCode.InsufficientBalance); + } + // 更新文章赞赏数 + int result = sponsorMapper.updateArticleSponsorCount(articleDTO.getIdArticle()); + if (result == 0) { + throw new ServiceException("操作失败!"); } - map.put("success", true); - map.put("message", "赞赏成功"); } - return map; + return true; } } diff --git a/src/main/java/com/rymcu/forest/service/impl/TagServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/TagServiceImpl.java index 7b6bfdf..25fcf3f 100644 --- a/src/main/java/com/rymcu/forest/service/impl/TagServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/TagServiceImpl.java @@ -1,18 +1,16 @@ package com.rymcu.forest.service.impl; +import com.rymcu.forest.core.exception.BusinessException; +import com.rymcu.forest.core.exception.ServiceException; import com.rymcu.forest.core.service.AbstractService; import com.rymcu.forest.dto.ArticleTagDTO; import com.rymcu.forest.dto.LabelModel; -import com.rymcu.forest.dto.baidu.TagNlpDTO; import com.rymcu.forest.entity.Article; import com.rymcu.forest.entity.Tag; -import com.rymcu.forest.entity.User; import com.rymcu.forest.mapper.ArticleMapper; import com.rymcu.forest.mapper.TagMapper; import com.rymcu.forest.service.TagService; -import com.rymcu.forest.util.BaiDuAipUtils; import com.rymcu.forest.util.CacheUtils; -import com.rymcu.forest.util.UserUtils; import com.rymcu.forest.util.XssUtils; import com.rymcu.forest.web.api.common.UploadController; import com.rymcu.forest.web.api.exception.BaseApiException; @@ -25,9 +23,7 @@ import javax.annotation.Resource; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Date; -import java.util.HashMap; import java.util.List; -import java.util.Map; /** * @author ronger @@ -42,8 +38,7 @@ public class TagServiceImpl extends AbstractService implements TagService { @Override @Transactional(rollbackFor = {UnsupportedEncodingException.class, BaseApiException.class}) - public Integer saveTagArticle(Article article, String articleContentHtml) throws UnsupportedEncodingException, BaseApiException { - User user = UserUtils.getCurrentUserByToken(); + public Integer saveTagArticle(Article article, String articleContentHtml, Long userId) throws UnsupportedEncodingException, BaseApiException { String articleTags = article.getArticleTags(); if (StringUtils.isNotBlank(articleTags)) { String[] tags = articleTags.split(","); @@ -80,7 +75,7 @@ public class TagServiceImpl extends AbstractService implements TagService { tagMapper.updateByPrimaryKeySelective(tag); addTagArticle = true; } - Integer countUserTag = tagMapper.selectCountUserTagById(user.getIdUser(), tag.getIdTag()); + Integer countUserTag = tagMapper.selectCountUserTagById(userId, tag.getIdTag()); if (countUserTag == 0) { addUserTag = true; } @@ -92,23 +87,13 @@ public class TagServiceImpl extends AbstractService implements TagService { tagMapper.insertTagArticle(tag.getIdTag(), article.getIdArticle()); } if (addUserTag) { - tagMapper.insertUserTag(tag.getIdTag(), user.getIdUser(), 1); + tagMapper.insertUserTag(tag.getIdTag(), userId, 1); } } return 1; } else { if (StringUtils.isNotBlank(articleContentHtml)) { - List list = BaiDuAipUtils.getKeywords(article.getArticleTitle(), articleContentHtml); - if (list.size() > 0) { - StringBuffer tags = new StringBuffer(); - for (TagNlpDTO tagNlpDTO : list) { - tags.append(tagNlpDTO.getTag()).append(","); - } - article.setArticleTags(tags.toString()); - } else { - article.setArticleTags("待分类"); - } - saveTagArticle(article, articleContentHtml); + saveTagArticle(article, articleContentHtml, userId); } } return 0; @@ -116,47 +101,41 @@ public class TagServiceImpl extends AbstractService implements TagService { @Override @Transactional(rollbackFor = Exception.class) - public Map cleanUnusedTag() { - Map map = new HashMap(1); - tagMapper.deleteUnusedTag(); - return map; + public boolean cleanUnusedTag() { + return tagMapper.deleteUnusedTag() > 0; } @Override @Transactional(rollbackFor = Exception.class) - public Map saveTag(Tag tag) { + public Tag saveTag(Tag tag) throws Exception { Integer result; - - Map map = new HashMap(1); tag.setTagDescription(XssUtils.filterHtmlCode(tag.getTagDescription())); if (tag.getIdTag() == null) { if (StringUtils.isBlank(tag.getTagTitle())) { - map.put("message", "标签名不能为空!"); - return map; + throw new IllegalArgumentException("标签名不能为空!"); } else { Condition tagCondition = new Condition(Tag.class); tagCondition.createCriteria().andCondition("tag_title =", tag.getTagTitle()); List tags = tagMapper.selectByCondition(tagCondition); if (!tags.isEmpty()) { - map.put("message", "标签 '" + tag.getTagTitle() + "' 已存在!"); - return map; + throw new BusinessException("标签 '" + tag.getTagTitle() + "' 已存在!"); } } - Tag newTag = new Tag(); - newTag.setTagTitle(tag.getTagTitle()); - newTag.setTagUri(tag.getTagUri()); + tag = new Tag(); + tag.setTagTitle(tag.getTagTitle()); + tag.setTagUri(tag.getTagUri()); if (StringUtils.isNotBlank(tag.getTagIconPath()) && tag.getTagIconPath().contains("base64")) { String tagIconPath = UploadController.uploadBase64File(tag.getTagIconPath(), 2); - newTag.setTagIconPath(tagIconPath); + tag.setTagIconPath(tagIconPath); } else { - newTag.setTagIconPath(tag.getTagIconPath()); + tag.setTagIconPath(tag.getTagIconPath()); } - newTag.setTagStatus(tag.getTagStatus()); - newTag.setTagDescription(tag.getTagDescription()); - newTag.setTagReservation(tag.getTagReservation()); - newTag.setCreatedTime(new Date()); - newTag.setUpdatedTime(tag.getCreatedTime()); - result = tagMapper.insertSelective(newTag); + tag.setTagStatus(tag.getTagStatus()); + tag.setTagDescription(tag.getTagDescription()); + tag.setTagReservation(tag.getTagReservation()); + tag.setCreatedTime(new Date()); + tag.setUpdatedTime(tag.getCreatedTime()); + result = tagMapper.insertSelective(tag); } else { tag.setUpdatedTime(new Date()); if (StringUtils.isNotBlank(tag.getTagIconPath()) && tag.getTagIconPath().contains("base64")) { @@ -166,11 +145,9 @@ public class TagServiceImpl extends AbstractService implements TagService { result = tagMapper.update(tag.getIdTag(), tag.getTagUri(), tag.getTagIconPath(), tag.getTagStatus(), tag.getTagDescription(), tag.getTagReservation()); } if (result == 0) { - map.put("message", "操作失败!"); - } else { - map.put("tag", tag); + throw new ServiceException("操作失败!"); } - return map; + return tag; } @Override diff --git a/src/main/java/com/rymcu/forest/service/impl/TopicServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/TopicServiceImpl.java index bb81f9b..d8e0746 100644 --- a/src/main/java/com/rymcu/forest/service/impl/TopicServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/TopicServiceImpl.java @@ -1,8 +1,9 @@ package com.rymcu.forest.service.impl; -import cn.hutool.http.HtmlUtil; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; +import com.rymcu.forest.core.exception.BusinessException; +import com.rymcu.forest.core.exception.ServiceException; import com.rymcu.forest.core.service.AbstractService; import com.rymcu.forest.dto.admin.TagDTO; import com.rymcu.forest.dto.admin.TopicDTO; @@ -20,9 +21,7 @@ import tk.mybatis.mapper.entity.Condition; import javax.annotation.Resource; import java.util.Date; -import java.util.HashMap; import java.util.List; -import java.util.Map; /** * @author ronger @@ -35,8 +34,7 @@ public class TopicServiceImpl extends AbstractService implements TopicSer @Override public List findTopicNav() { - List topics = topicMapper.selectTopicNav(); - return topics; + return topicMapper.selectTopicNav(); } @Override @@ -48,40 +46,37 @@ public class TopicServiceImpl extends AbstractService implements TopicSer @Override @Transactional(rollbackFor = Exception.class) - public Map saveTopic(Topic topic) { + public Topic saveTopic(Topic topic) throws ServiceException { Integer result; topic.setTopicDescriptionHtml(XssUtils.filterHtmlCode(topic.getTopicDescriptionHtml())); - Map map = new HashMap(1); if (topic.getIdTopic() == null) { if (StringUtils.isBlank(topic.getTopicTitle())) { - map.put("message","标签名不能为空!"); - return map; + throw new IllegalArgumentException("标签名不能为空!"); } else { Condition topicCondition = new Condition(Topic.class); topicCondition.createCriteria().andCondition("topic_title =", topic.getTopicTitle()); List topics = topicMapper.selectByCondition(topicCondition); if (!topics.isEmpty()) { - map.put("message","专题 '" + topic.getTopicTitle() + "' 已存在!"); - return map; + throw new BusinessException("专题 '" + topic.getTopicTitle() + "' 已存在!"); } } - Topic newTopic = new Topic(); - newTopic.setTopicTitle(topic.getTopicTitle()); - newTopic.setTopicUri(topic.getTopicUri()); + topic = new Topic(); + topic.setTopicTitle(topic.getTopicTitle()); + topic.setTopicUri(topic.getTopicUri()); if (StringUtils.isNotBlank(topic.getTopicIconPath()) && topic.getTopicIconPath().contains("base64")) { String topicIconPath = UploadController.uploadBase64File(topic.getTopicIconPath(), 3); - newTopic.setTopicIconPath(topicIconPath); + topic.setTopicIconPath(topicIconPath); } else { - newTopic.setTopicIconPath(topic.getTopicIconPath()); + topic.setTopicIconPath(topic.getTopicIconPath()); } - newTopic.setTopicNva(topic.getTopicNva()); - newTopic.setTopicStatus(topic.getTopicStatus()); - newTopic.setTopicSort(topic.getTopicSort()); - newTopic.setTopicDescription(topic.getTopicDescription()); - newTopic.setTopicDescriptionHtml(topic.getTopicDescriptionHtml()); - newTopic.setCreatedTime(new Date()); - newTopic.setUpdatedTime(topic.getCreatedTime()); - result = topicMapper.insertSelective(newTopic); + topic.setTopicNva(topic.getTopicNva()); + topic.setTopicStatus(topic.getTopicStatus()); + topic.setTopicSort(topic.getTopicSort()); + topic.setTopicDescription(topic.getTopicDescription()); + topic.setTopicDescriptionHtml(topic.getTopicDescriptionHtml()); + topic.setCreatedTime(new Date()); + topic.setUpdatedTime(topic.getCreatedTime()); + result = topicMapper.insertSelective(topic); } else { if (StringUtils.isNotBlank(topic.getTopicIconPath()) && topic.getTopicIconPath().contains("base64")) { String topicIconPath = UploadController.uploadBase64File(topic.getTopicIconPath(), 3); @@ -93,15 +88,13 @@ public class TopicServiceImpl extends AbstractService implements TopicSer ,topic.getTopicSort(),topic.getTopicDescription(),topic.getTopicDescriptionHtml()); } if (result == 0) { - map.put("message","操作失败!"); - } else { - map.put("topic", topic); + throw new ServiceException("操作失败!"); } - return map; + return topic; } @Override - public List findUnbindTagsById(Integer idTopic, String tagTitle) { + public List findUnbindTagsById(Long idTopic, String tagTitle) { if (StringUtils.isBlank(tagTitle)) { tagTitle = ""; } @@ -110,46 +103,30 @@ public class TopicServiceImpl extends AbstractService implements TopicSer @Override @Transactional(rollbackFor = Exception.class) - public Map bindTopicTag(TopicTagDTO topicTag) { + public TopicTagDTO bindTopicTag(TopicTagDTO topicTag) throws ServiceException { Integer result = topicMapper.insertTopicTag(topicTag.getIdTopic(), topicTag.getIdTag()); - Map map = new HashMap(1); if (result == 0) { - map.put("message", "操作失败!"); - } else { - map.put("topicTag", topicTag); + throw new ServiceException("操作失败!"); } - return map; + return topicTag; } @Override @Transactional(rollbackFor = Exception.class) - public Map unbindTopicTag(TopicTagDTO topicTag) { + public TopicTagDTO unbindTopicTag(TopicTagDTO topicTag) throws ServiceException { Integer result = topicMapper.deleteTopicTag(topicTag.getIdTopic(), topicTag.getIdTag()); - Map map = new HashMap(1); if (result == 0) { - map.put("message", "操作失败!"); - } else { - map.put("topicTag", topicTag); + throw new ServiceException("操作失败!"); } - return map; + return topicTag; } @Override - public Map findTagsByTopicUri(String topicUri, Integer page, Integer rows) { - Map map = new HashMap(2); + public List findTagsByTopicUri(String topicUri) { TopicDTO topic = topicMapper.selectTopicByTopicUri(topicUri); if (topic == null) { - return map; + return null; } - PageHelper.startPage(page, rows); - List list = topicMapper.selectTopicTag(topic.getIdTopic()); - PageInfo pageInfo = new PageInfo(list); - map.put("tags", pageInfo.getList()); - Map pagination = new HashMap(3); - pagination.put("pageSize",pageInfo.getPageSize()); - pagination.put("total",pageInfo.getTotal()); - pagination.put("currentPage",pageInfo.getPageNum()); - map.put("pagination", pagination); - return map; + return topicMapper.selectTopicTag(topic.getIdTopic()); } } diff --git a/src/main/java/com/rymcu/forest/service/impl/TransactionRecordServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/TransactionRecordServiceImpl.java index 4a2f7cb..bc5c5d1 100644 --- a/src/main/java/com/rymcu/forest/service/impl/TransactionRecordServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/TransactionRecordServiceImpl.java @@ -9,10 +9,11 @@ import com.rymcu.forest.entity.BankAccount; import com.rymcu.forest.entity.TransactionRecord; import com.rymcu.forest.enumerate.TransactionCode; import com.rymcu.forest.enumerate.TransactionEnum; +import com.rymcu.forest.mapper.BankAccountMapper; import com.rymcu.forest.mapper.TransactionRecordMapper; -import com.rymcu.forest.service.BankAccountService; import com.rymcu.forest.service.TransactionRecordService; import com.rymcu.forest.util.DateUtil; +import org.apache.commons.lang.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -32,13 +33,13 @@ public class TransactionRecordServiceImpl extends AbstractService 0) { return true; @@ -154,4 +163,10 @@ public class TransactionRecordServiceImpl extends AbstractService implements UserServic @Override @Transactional(rollbackFor = Exception.class) - public Map register(String email, String password, String code) { - Map map = new HashMap(2); - map.put("message", "验证码无效!"); + public boolean register(String email, String password, String code) { String vCode = redisService.get(email); if (StringUtils.isNotBlank(vCode)) { if (vCode.equals(code)) { User user = userMapper.findByAccount(email); if (user != null) { - map.put("message", "该邮箱已被注册!"); + throw new AccountExistsException("该邮箱已被注册!"); } else { user = new User(); String nickname = email.split("@")[0]; @@ -84,13 +85,12 @@ public class UserServiceImpl extends AbstractService implements UserServic .nickname(user.getNickname()) .signature(user.getSignature()) .build()); - map.put("message", "注册成功!"); - map.put("flag", 1); redisService.delete(email); + return true; } } } - return map; + throw new CaptchaException(); } private String checkNickname(String nickname) { @@ -114,8 +114,7 @@ public class UserServiceImpl extends AbstractService implements UserServic } @Override - public Map login(String account, String password) { - Map map = new HashMap(2); + public TokenUser login(String account, String password) { User user = userMapper.findByAccount(account); if (user != null) { if (Utils.comparePwd(password, user.getPassword())) { @@ -125,16 +124,15 @@ public class UserServiceImpl extends AbstractService implements UserServic BeanCopierUtil.copy(user, tokenUser); tokenUser.setToken(tokenManager.createToken(account)); tokenUser.setWeights(userMapper.selectRoleWeightsByUser(user.getIdUser())); - map.put("user", tokenUser); // 保存登录日志 loginRecordService.saveLoginRecord(tokenUser.getIdUser()); + return tokenUser; } else { - map.put("message", "密码错误!"); + throw new AuthenticationException("密码错误"); } } else { - map.put("message", "该账号不存在!"); + throw new UnknownAccountException("账号不存在"); } - return map; } @Override @@ -143,69 +141,55 @@ public class UserServiceImpl extends AbstractService implements UserServic } @Override - public Map forgetPassword(String code, String password) { - Map map = new HashMap<>(2); + public boolean forgetPassword(String code, String password) throws ServiceException { String email = redisService.get(code); if (StringUtils.isBlank(email)) { - map.put("message", "链接已失效"); + throw new ServiceException("链接已失效"); } else { - userMapper.updatePasswordByEmail(email, Utils.entryptPassword(password)); - map.put("message", "修改成功,正在跳转登录登陆界面!"); - map.put("flag", 1); + int result = userMapper.updatePasswordByEmail(email, Utils.entryptPassword(password)); + if (result == 0) { + throw new ServiceException("密码修改失败!"); + } + return true; } - return map; } @Override @Transactional(rollbackFor = Exception.class) - public Map updateUserRole(Integer idUser, Integer idRole) { - Map map = new HashMap(2); + public boolean updateUserRole(Long idUser, Long idRole) throws ServiceException { Integer result = userMapper.updateUserRole(idUser, idRole); if (result == 0) { - map.put("message", "更新失败!"); + throw new ServiceException("更新失败!"); } - return map; + return true; } @Override @Transactional(rollbackFor = Exception.class) - public Map updateStatus(Integer idUser, String status) { - Map map = new HashMap(2); + public boolean updateStatus(Long idUser, String status) throws ServiceException { Integer result = userMapper.updateStatus(idUser, status); if (result == 0) { - map.put("message", "更新失败!"); + throw new ServiceException("更新失败!"); } - return map; + return true; } @Override - public Map findUserInfo(Integer idUser) { - Map map = new HashMap(2); + public UserInfoDTO findUserInfo(Long idUser) { UserInfoDTO user = userMapper.selectUserInfo(idUser); if (user == null) { - map.put("message", "用户不存在!"); - } else { - UserExtend userExtend = userExtendMapper.selectByPrimaryKey(user.getIdUser()); - if (Objects.isNull(userExtend)) { - userExtend = new UserExtend(); - userExtend.setIdUser(user.getIdUser()); - userExtendMapper.insertSelective(userExtend); - } - map.put("user", user); - map.put("userExtend", userExtend); + throw new ContentNotExistException("用户不存在!"); } - return map; + return user; } @Override @Transactional(rollbackFor = Exception.class) - public Map updateUserInfo(UserInfoDTO user) { - Map map = new HashMap(2); + public UserInfoDTO updateUserInfo(UserInfoDTO user) throws ServiceException { user.setNickname(formatNickname(user.getNickname())); Integer number = userMapper.checkNicknameByIdUser(user.getIdUser(), user.getNickname()); if (number > 0) { - map.put("message", "该昵称已使用!"); - return map; + throw new NicknameOccupyException("该昵称已使用!"); } if (StringUtils.isNotBlank(user.getAvatarType()) && AVATAR_SVG_TYPE.equals(user.getAvatarType())) { String avatarUrl = UploadController.uploadBase64File(user.getAvatarUrl(), 0); @@ -219,47 +203,41 @@ public class UserServiceImpl extends AbstractService implements UserServic .signature(user.getSignature()) .build()); if (result == 0) { - map.put("message", "操作失败!"); - return map; + throw new ServiceException("操作失败!"); } - map.put("user", user); - return map; + + return user; } private String formatNickname(String nickname) { return nickname.replaceAll("\\.", ""); } - @Override - public Map checkNickname(Integer idUser, String nickname) { - Map map = new HashMap(2); + public boolean checkNicknameByIdUser(Long idUser, String nickname) { Integer number = userMapper.checkNicknameByIdUser(idUser, nickname); if (number > 0) { - map.put("message", "该昵称已使用!"); + return false; } - return map; + return true; } @Override - public Integer findRoleWeightsByUser(Integer idUser) { + public Integer findRoleWeightsByUser(Long idUser) { return userMapper.selectRoleWeightsByUser(idUser); } @Override - public Author selectAuthor(Integer idUser) { + public Author selectAuthor(Long idUser) { return userMapper.selectAuthor(idUser); } @Override - public Map updateUserExtend(UserExtend userExtend) { - Map map = new HashMap(2); - int result = userExtendMapper.updateByPrimaryKeySelective(userExtend); + public UserExtend updateUserExtend(UserExtend userExtend) throws ServiceException { + int result = userExtendMapper.updateByPrimaryKey(userExtend); if (result == 0) { - map.put("message", "操作失败!"); - return map; + throw new ServiceException("操作失败!"); } - map.put("userExtend", userExtend); - return map; + return userExtend; } @Override @@ -268,30 +246,26 @@ public class UserServiceImpl extends AbstractService implements UserServic } @Override - public Map updateEmail(ChangeEmailDTO changeEmailDTO) { - Map map = new HashMap(2); - map.put("message", "验证码无效!"); - Integer idUser = changeEmailDTO.getIdUser(); + public boolean updateEmail(ChangeEmailDTO changeEmailDTO) throws ServiceException { + Long idUser = changeEmailDTO.getIdUser(); String email = changeEmailDTO.getEmail(); String code = changeEmailDTO.getCode(); String vCode = redisService.get(email); - if (StringUtils.isNotBlank(vCode) && StringUtils.isNotBlank(code)) { - if (vCode.equals(code)) { - userMapper.updateEmail(idUser, email); - map.put("message", "更新成功!"); - map.put("email", email); + if (StringUtils.isNotBlank(vCode) && StringUtils.isNotBlank(code) && vCode.equals(code)) { + int result = userMapper.updateEmail(idUser, email); + if (result == 0) { + throw new ServiceException("修改邮箱失败!"); } + return true; } - return map; + throw new CaptchaException(); } @Override - public Map updatePassword(UpdatePasswordDTO updatePasswordDTO) { - Map map = new HashMap(2); + public boolean updatePassword(UpdatePasswordDTO updatePasswordDTO) { String password = Utils.entryptPassword(updatePasswordDTO.getPassword()); userMapper.updatePasswordById(updatePasswordDTO.getIdUser(), password); - map.put("message", "更新成功!"); - return map; + return true; } @Override @@ -315,4 +289,15 @@ public class UserServiceImpl extends AbstractService implements UserServic public Integer updateLastOnlineTimeByEmail(String email) { return userMapper.updateLastOnlineTimeByEmail(email); } + + @Override + public UserExtend findUserExtendInfo(Long idUser) { + UserExtend userExtend = userExtendMapper.selectByPrimaryKey(idUser); + if (Objects.isNull(userExtend)) { + userExtend = new UserExtend(); + userExtend.setIdUser(idUser); + userExtendMapper.insertSelective(userExtend); + } + return userExtend; + } } diff --git a/src/main/java/com/rymcu/forest/service/impl/WxUserServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/WxUserServiceImpl.java deleted file mode 100644 index f67d7d5..0000000 --- a/src/main/java/com/rymcu/forest/service/impl/WxUserServiceImpl.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.rymcu.forest.service.impl; - -import com.rymcu.forest.core.service.AbstractService; -import com.rymcu.forest.entity.WxUser; -import com.rymcu.forest.mapper.WxUserMapper; -import com.rymcu.forest.service.WxUserService; -import me.chanjar.weixin.mp.bean.result.WxMpUser; -import org.apache.commons.lang.StringUtils; -import org.springframework.stereotype.Service; - -import javax.annotation.Resource; -import java.util.List; - -/** - * @author ronger - */ -@Service -public class WxUserServiceImpl extends AbstractService implements WxUserService { - - @Resource - private WxUserMapper wxUserMapper; - - @Override - public WxUser saveUser(WxMpUser wxMpUser, String appId) { - WxUser searchWxUser = new WxUser(); - if (StringUtils.isBlank(wxMpUser.getUnionId())) { - searchWxUser.setUnionId(wxMpUser.getUnionId()); - } else { - searchWxUser.setAppId(appId); - searchWxUser.setOpenId(searchWxUser.getOpenId()); - } - List wxUsers = wxUserMapper.select(searchWxUser); - WxUser wxUser; - if (wxUsers.isEmpty()) { - wxUser = new WxUser(); - wxUser.setAppId(appId); - wxUser = copyWxUser(wxMpUser,wxUser); - wxUserMapper.insertSelective(wxUser); - } else { - wxUser = wxUsers.get(0); - wxUser = copyWxUser(wxMpUser,wxUser); - wxUserMapper.updateByPrimaryKeySelective(wxUser); - } - return wxUser; - } - - private WxUser copyWxUser(WxMpUser wxMpUser, WxUser wxUser) { - wxUser.setSubscribe(wxMpUser.getSubscribe()); - wxUser.setSubscribeTime(wxMpUser.getSubscribeTime()); - wxUser.setUnionId(wxMpUser.getUnionId()); - wxUser.setOpenId(wxMpUser.getOpenId()); - wxUser.setLanguage(wxMpUser.getLanguage()); - return wxUser; - } -} diff --git a/src/main/java/com/rymcu/forest/util/BaiDuAipUtils.java b/src/main/java/com/rymcu/forest/util/BaiDuAipUtils.java deleted file mode 100644 index a49c1e6..0000000 --- a/src/main/java/com/rymcu/forest/util/BaiDuAipUtils.java +++ /dev/null @@ -1,197 +0,0 @@ -package com.rymcu.forest.util; - -import com.alibaba.fastjson.JSON; -import com.baidu.aip.nlp.AipNlp; -import com.rymcu.forest.dto.baidu.TagNlpDTO; -import org.apache.commons.lang.StringUtils; -import org.json.JSONObject; - -import java.util.HashMap; -import java.util.List; - -/** - * @author ronger - */ -public class BaiDuAipUtils { - - public static final String APP_ID = "18094949"; - public static final String API_KEY = "3h3BOgejXI1En5aq1iGHeWrF"; - public static final String SECRET_KEY = "8guDNvxWF1wu8ogpVxLHlRY5FeOBE8z7"; - - public static final Integer MAX_CONTENT_LENGTH = 3000; - - public static void main(String[] args) { - String title = "51单片机第4章--跑马灯实验"; - System.out.println(title.length()); - String content = "

4.1 进制转换基础知识

\n" + - "

进制实际是一个非常简单易懂的概念,对于初学者来说也很容易上手。我们接触最多的就是十进制了,它的特点为逢十进一,包含 0,1,2,3,4,5,6,7,8,9 共十个元素。在生活中我们用到的基本都是十进制了,所以大家对它已经非常熟悉并能应用自如,但是在计算机(包括单片机)世界里,所有都是以二进制为基础的。二进制的特点为逢二进一,包含 0,1 共两个元素。计算机中的数据都是以二进制存储的,这就是我们所说的 0,1 世界。通常我们讲的 32 位或 64 位操作系统这里的位指的就是二进制位数。因为我们实际多用十进制,那么我们在和计算机系统沟通过程中,十进制与二进制之间的转换就变得很重要了。进制之间的转换如下表所示。
\n" + - "\"表4-1进制转换.png\"
\n" + - "二进制转换十进制公式如下:
\n" + - "\"进制转换公式.png\"
\n" + - "其中,n 表示二进制的位数。
\n" + - "下面我们举个例子来更加直观的说明这个公式:
\n" + - "例如:1101,这是一个 4 位的二进制数,计算如下,
\n" + - "\"进制转换公式1.png\"
\n" + - "大家可以利用这个公式计算的结果和上表进行一一对照。
\n" + - "十六进制也是我们常用的进制,它的特点为逢十六进一,包括 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F 共十六个元素。实际上十六进制是二进制的一种特殊形式,十六进制的 1 位等价于二进制的 4 位,在 C 语言编程中我们常用十六进制来表示二进制数。在实际应用中我们常常该数字之前加一个前缀来表示他的进制:“0b”表示二进制,“0x”表示十六进制。下面我们举例说明:
\n" + - "0b10010010 = 0x92
\n" + - "上面一个八位的二进制数转换为一个两位的十六进制数。二进制的前 4 位等于十六进制的第 1 位:
\n" + - "0b1001 = 0x9
\n" + - "二进制数的后 4 位等于十六进制的第 2 位:
\n" + - "0b0010 = 0x2
\n" + - "在计算机中,我们通常所说的二进制的 1 位也叫 1bit,8 位表示 1 个字节,也叫 1Byte。根据二进制与十六机制的关系,一个 2 位的十六进制数则可表示 1 个字节。在运用的过程中牢记 0~15 的十进制与二进制、十六进制之间的转换关系对于程序的编写有很大的好处。

\n" + - "

4.2 闪烁 LED 小灯

\n" + - "

怎么让 LED 小灯闪烁?我们最先想到的办法当然是先让 LED 小灯点亮,延时一段时间,熄灭 LED 小灯,再延时一段时间,一直循环上面的步骤就能实现 LED 小灯的闪烁了。根据第 3 章的知识我们知道点亮 LED 的语句为“led0 = 0;”,熄灭 LED 的语句为“led0 = 1;”。按照第 3 章介绍我们重新建立一个 LED 小灯闪烁的工程。程序代码设计如下:

\n" + - "
#include<reg52.h> //寄存器声明头文件  \n" +
-                "sbit led0 = P1^0; // 位声明,将P1.0管脚声明为led0  \n" +
-                "  \n" +
-                "void main()  //程序主函数入口,每个C语言程序有且只有一个  \n" +
-                "{  \n" +
-                " int i; //变量声明  \n" +
-                " while(1) //循环  \n" +
-                " {  \n" +
-                " led0 = 0; //赋值管脚P1.0为低电平,点亮LED小灯  \n" +
-                " for(i=0;i<5000;i++);//延时一段时间  \n" +
-                " led0 = 1;//熄灭LED小灯  \n" +
-                " for(i=0;i<5000;i++);//再延时一段时间  \n" +
-                " }  \n" +
-                "}  \n" +
-                "
\n" + - "

4.3\t跑马灯设计

\n" + - "

在我们的开发板上设计了 8 个依次排列的 LED 小灯,让小灯依次点亮和熄灭实现跑马灯的效果是我们这一节的主要内容。

\n" + - "

4.3.1 硬件设计

\n" + - "

8 个 LED 小灯的硬件电路设计原理图如下图所示:
\n" + - "\"图4-1-8位跑马灯设计原理图.png\"
\n" + - "如上图所示,8 个 LED 小灯 LED0-LED7 的正极和电源 VCC 之间均串联了一个 1K 的限流电阻。LED7-LED0 的负极与 74HC573 锁存器的 Q0-Q7 一一相连接。锁存器 74HC573 的功能我们这里不详细介绍,把它的 D0-D7 与 Q0-Q7 之间看作是电气上一一联通的。由图所示,锁存器的 D0-D7 和单片机的 P1.7-P1.0 是一一连接的。因此,LED 小灯 LED7-LED0 的负极与单片机的 P1.7~P1.0 管脚一一相连,在单片机程序中通过控制 P1.7-P1.0 管脚的高低电平便可控制 8 个 LED 小灯的亮灭。
\n" + - "该实验要实现的功能为:首先点亮 LED0,然后延迟一段时间,熄灭 LED0,熄灭 LED0 点亮 LED1,延迟一段时间,熄灭 LED1 点亮 LED2,延迟一段时间,一直到熄灭 LED6 点亮 LED7,依照上面的步骤一直循环下去,便实现了一个简单的跑马灯的效果。

\n" + - "

4.3.2 软件设计

\n" + - "

前面我们试验中都是只对 P1.0 这个管脚进行赋值,来控制 LED 小灯 led0 的亮灭。实际在编写程序的过程中我们可以对 P1 寄存器进行直接赋值来同时控制 8 个 LED 小灯。
\n" + - "\"表4-2-P1寄存器对照表.png\"
\n" + - "如上表所示,P1 寄存器是一个 8 位的寄存器,最高位到最低位依次对应的 P1.7 管脚到 P1.0 管脚。点亮某个 LED 小灯的二进制,十六进制赋值如上表所示。例如 P1 = 0xFE;表示点亮 led0,P1=0x7F;则表示点亮 led7。在软件代码设计时,我们想到的第一个方法为依次点亮小灯并延时,代码如下所示。

\n" + - "
#include<reg52.h> //加载头文件\n" +
-                "int i;\n" +
-                "\n" +
-                "void main()//主函数入口\n" +
-                "{\n" +
-                "\tP1 = 0xFE; //点亮LED0\n" +
-                "\tfor(i=0;i<5000;i++);//延时一段时间\n" +
-                "\tP1 = 0xFD; //点亮LED1\n" +
-                "\tfor(i=0;i<5000;i++);//延时一段时间\n" +
-                "\tP1 = 0xFB; //点亮LED2\n" +
-                "\tfor(i=0;i<5000;i++);//延时一段时间\n" +
-                "\tP1 = 0xF7; //点亮LED3\n" +
-                "\tfor(i=0;i<5000;i++);//延时一段时间\n" +
-                "\tP1 = 0xEF; //点亮LED4\n" +
-                "\tfor(i=0;i<5000;i++);//延时一段时间\n" +
-                "\tP1 = 0xDF; //点亮LED5\n" +
-                "\tfor(i=0;i<5000;i++);//延时一段时间\n" +
-                "\tP1 = 0xBF; //点亮LED6\n" +
-                "\tfor(i=0;i<5000;i++);//延时一段时间\n" +
-                "\tP1 = 0x7F; //点亮LED7\n" +
-                "\tfor(i=0;i<5000;i++);//延时一段时间\n" +
-                "}  \n" +
-                "
\n" + - "

我们对代码进行一下小的改进,这个方法这里称之为“左移取反”法,这个方法在很多的应用中都能用到,非常实用。代码如下图所示。

\n" + - "
#include<reg52.h> //加载头文件\n" +
-                "int i;\n" +
-                "int flag=0;\n" +
-                " \n" +
-                "void main()//主函数入口\n" +
-                "{ \n" +
-                " P0 = 0xff;\n" +
-                "\twhile(1)\n" +
-                "\t{\n" +
-                "\t\tP1 = ~(0x01<<flag);//P1的值等于1左移flag位后取反,点亮第flag位LED小灯亮\n" +
-                "\t\tfor(i=0;i<25000;i++);//延时一段时间\n" +
-                "\n" +
-                "\t\tif(flag>=8)\t  //flag大于7时,置零,从零开始\n" +
-                "\t\t{\n" +
-                "\t\t\tflag=0;\n" +
-                "\t\t}\n" +
-                "\t\telse\n" +
-                "\t\t{\n" +
-                "\t\t\tflag++;\t //flag累加\n" +
-                "\t\t}\n" +
-                "\t}\n" +
-                "}\n" +
-                "
\n" + - "

我们对上面代码进行分析,flag 是一个从 0 到 7 依次循环的数,P1 等于 1 向左移 flag 位再取反。当 flag 等于 2 时,0b0000,0001 左移 2 位等于 0b0000,0100,再取反等于 0b1111,1011=0xFB,并赋值给 P1,点亮了小灯 led2。同理,当 flag 等于 6 时,0b0000,0001 左移 6 位等于 0b0100,0000,再取反等于 0b1011,1111=0xBF 并赋值给 P1,点亮了小灯 led6。flag 为其他值时,大家可以进行一一分析。

\n" + - "

4.3.3 下载验证

\n" + - "

将程序通过 STC-isp 软件下载到单片机,观察 8 个 LED 小灯效果与设想的效果是否一致?至此,本章的内容讲解完毕,内容包括进制转换的基础知识、LED 小灯闪速程序以及跑马灯的两种程序。大家在动手操作的过程中多多下载到单片机中观察现象,加深印象。

\n"; - System.out.println(getKeywords(title, content)); - System.out.println(getNewsSummary(title, content, 200)); - - } - - public static List getKeywords(String title, String content) { - if (StringUtils.isBlank(content)) { - return null; - } - // api 限制内容不能超过 3000 字 - if (content.length() > MAX_CONTENT_LENGTH) { - content = content.substring(0, MAX_CONTENT_LENGTH); - } - // 初始化一个AipNlp - AipNlp client = new AipNlp(APP_ID, API_KEY, SECRET_KEY); - - // 可选:设置网络连接参数 - client.setConnectionTimeoutInMillis(2000); - client.setSocketTimeoutInMillis(60000); - - // 传入可选参数调用接口 - HashMap options = new HashMap(1); - - // 新闻摘要接口 - JSONObject res = client.keyword(title, Html2TextUtil.getContent(content), options); - List list = JSON.parseArray(res.get("items").toString(), TagNlpDTO.class); - return list; - } - - public static String getTopic(String title, String content) { - if (StringUtils.isBlank(content)) { - return ""; - } - // api 限制内容不能超过 3000 字 - if (content.length() > MAX_CONTENT_LENGTH) { - content = content.substring(0, MAX_CONTENT_LENGTH); - } - // 初始化一个AipNlp - AipNlp client = new AipNlp(APP_ID, API_KEY, SECRET_KEY); - - // 可选:设置网络连接参数 - client.setConnectionTimeoutInMillis(2000); - client.setSocketTimeoutInMillis(60000); - - // 传入可选参数调用接口 - HashMap options = new HashMap(1); - - // 新闻摘要接口 - JSONObject res = client.topic(title, Html2TextUtil.getContent(content), options); - return res.toString(2); - } - - public static String getNewsSummary(String title, String content, int maxSummaryLen) { - if (StringUtils.isBlank(content)) { - return ""; - } - // api 限制内容不能超过 3000 字 - if (content.length() > MAX_CONTENT_LENGTH) { - content = content.substring(0, MAX_CONTENT_LENGTH); - } - // 初始化一个AipNlp - AipNlp client = new AipNlp(APP_ID, API_KEY, SECRET_KEY); - - // 可选:设置网络连接参数 - client.setConnectionTimeoutInMillis(2000); - client.setSocketTimeoutInMillis(60000); - - // 传入可选参数调用接口 - HashMap options = new HashMap(1); - options.put("title", title); - - // 新闻摘要接口 - JSONObject res = client.newsSummary(Html2TextUtil.getContent(content), maxSummaryLen, options); - return res.getString("summary"); - } - -} diff --git a/src/main/java/com/rymcu/forest/util/BaiDuUtils.java b/src/main/java/com/rymcu/forest/util/BaiDuUtils.java index a85d72e..3e943aa 100644 --- a/src/main/java/com/rymcu/forest/util/BaiDuUtils.java +++ b/src/main/java/com/rymcu/forest/util/BaiDuUtils.java @@ -11,18 +11,18 @@ import java.util.concurrent.*; */ public class BaiDuUtils { - private final static String token = "9cdKR6bVCJzxDEJS"; + private final static String TOKEN = "9cdKR6bVCJzxDEJS"; - private final static String site = "https://rymcu.com"; + private final static String SITE = "https://rymcu.com"; public static void sendSEOData(String permalink) { - if (StringUtils.isBlank(permalink) || StringUtils.isBlank(token)) { + if (StringUtils.isBlank(permalink) || StringUtils.isBlank(TOKEN)) { return; } - ExecutorService executor= new ThreadPoolExecutor(1,1,0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); + ExecutorService executor= new ThreadPoolExecutor(1,1,0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); CompletableFuture.supplyAsync(()-> { try { - HttpResponse response = HttpRequest.post("http://data.zz.baidu.com/urls?site=" + site + "&token=" + token). + HttpResponse response = HttpRequest.post("http://data.zz.baidu.com/urls?site=" + SITE + "&token=" + TOKEN). header("User-Agent", "curl/7.12.1"). header("Host", "data.zz.baidu.com"). header("Content-Type", "text/plain"). @@ -34,17 +34,16 @@ public class BaiDuUtils { } return 0; },executor); - return; } public static void sendUpdateSEOData(String permalink) { - if (StringUtils.isBlank(permalink) || StringUtils.isBlank(token)) { + if (StringUtils.isBlank(permalink) || StringUtils.isBlank(TOKEN)) { return; } - ExecutorService executor= new ThreadPoolExecutor(1,1,0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); + ExecutorService executor= new ThreadPoolExecutor(1,1,0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); CompletableFuture.supplyAsync(()-> { try { - HttpResponse response = HttpRequest.post("http://data.zz.baidu.com/update?site=" + site + "&token=" + token). + HttpResponse response = HttpRequest.post("http://data.zz.baidu.com/update?site=" + SITE + "&token=" + TOKEN). header("User-Agent", "curl/7.12.1"). header("Host", "data.zz.baidu.com"). header("Content-Type", "text/plain"). @@ -59,13 +58,13 @@ public class BaiDuUtils { } public static void deleteSEOData(String permalink) { - if (StringUtils.isBlank(permalink) || StringUtils.isBlank(token)) { + if (StringUtils.isBlank(permalink) || StringUtils.isBlank(TOKEN)) { return; } - ExecutorService executor= new ThreadPoolExecutor(1,1,0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); + ExecutorService executor= new ThreadPoolExecutor(1,1,0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); CompletableFuture.supplyAsync(()-> { try { - HttpResponse response = HttpRequest.post("http://data.zz.baidu.com/del?site=" + site + "&token=" + token). + HttpResponse response = HttpRequest.post("http://data.zz.baidu.com/del?site=" + SITE + "&token=" + TOKEN). header("User-Agent", "curl/7.12.1"). header("Host", "data.zz.baidu.com"). header("Content-Type", "text/plain"). diff --git a/src/main/java/com/rymcu/forest/util/BeanCopierUtil.java b/src/main/java/com/rymcu/forest/util/BeanCopierUtil.java index 6186f19..230d76d 100644 --- a/src/main/java/com/rymcu/forest/util/BeanCopierUtil.java +++ b/src/main/java/com/rymcu/forest/util/BeanCopierUtil.java @@ -2,7 +2,6 @@ package com.rymcu.forest.util; import lombok.extern.slf4j.Slf4j; import org.springframework.cglib.beans.BeanCopier; -import org.springframework.util.CollectionUtils; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -16,14 +15,14 @@ public class BeanCopierUtil { * beanCopier缓存 * (A拷贝到B,确定一个beanCopier) */ - private static Map,Map, BeanCopier>> beanCopierMap = new ConcurrentHashMap<>(); + private static final Map BEAN_COPIER_MAP = new ConcurrentHashMap<>(); /** * 拷贝方法 - * @param sourceBean - * @param targetBean - * @param - * @param + * @param sourceBean 源对象 + * @param targetBean 目标对象 + * @param 源对象类型 + * @param 目标对象类型 */ public static void copy(S sourceBean,T targetBean){ @SuppressWarnings("unchecked") @@ -37,16 +36,15 @@ public class BeanCopierUtil { /** * 转换方法 - * @param sourceBean 原对象 - * @param targetClass 目标类 - * @param - * @param - * @return + * @param sourceBean 源对象 + * @param targetBean 目标对象 + * @param 源对象类型 + * @param 目标对象类型 + * @return 拷贝值后的targetBean */ - public static T convert(S sourceBean,Class targetClass){ + public static T convert(S sourceBean,T targetBean){ try { assert sourceBean!=null; - T targetBean = targetClass.newInstance(); copy(sourceBean,targetBean); return targetBean; } catch (Exception e) { @@ -56,24 +54,20 @@ public class BeanCopierUtil { } - private static BeanCopier getBeanCopier(Class sourceClass, Class targetClass ){ - Map, BeanCopier> map = beanCopierMap.get(sourceClass); - if(CollectionUtils.isEmpty(map)){ - BeanCopier newBeanCopier = BeanCopier.create(sourceClass, targetClass, false); - Map, BeanCopier> newMap = new ConcurrentHashMap<>(); - newMap.put(targetClass,newBeanCopier); - beanCopierMap.put(sourceClass,newMap); - return newBeanCopier; - } - - BeanCopier beanCopier = map.get(targetClass); - if(beanCopier == null){ - BeanCopier newBeanCopier = BeanCopier.create(sourceClass, targetClass, false); - map.put(targetClass,newBeanCopier); - - return newBeanCopier; - } - - return beanCopier; + /** + * beanCopier获取方法 + * + * 使用beanCopierMap重用BeanCopier对象 + * + * 线程安全 + * @param sourceClass 源类型 + * @param targetClass 目标类型 + * @param 源类型 + * @param 目标类型 + * @return BeanCopier实例 + */ + private static BeanCopier getBeanCopier(Class sourceClass, Class targetClass){ + String classKey = sourceClass.getTypeName() + targetClass.getTypeName(); + return BEAN_COPIER_MAP.computeIfAbsent(classKey, key -> BeanCopier.create(sourceClass, targetClass, false)); } } diff --git a/src/main/java/com/rymcu/forest/util/CacheUtils.java b/src/main/java/com/rymcu/forest/util/CacheUtils.java index 2e99989..bac94a2 100644 --- a/src/main/java/com/rymcu/forest/util/CacheUtils.java +++ b/src/main/java/com/rymcu/forest/util/CacheUtils.java @@ -5,7 +5,6 @@ import org.apache.shiro.cache.CacheManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Iterator; import java.util.Set; /** @@ -13,15 +12,15 @@ import java.util.Set; */ public class CacheUtils { - private static Logger logger = LoggerFactory.getLogger(CacheUtils.class); - private static CacheManager cacheManager = SpringContextHolder.getBean(CacheManager.class); + private static final Logger LOGGER = LoggerFactory.getLogger(CacheUtils.class); + private static final CacheManager CACHE_MANAGER = SpringContextHolder.getBean(CacheManager.class); private static final String SYS_CACHE = "system"; /** * 获取SYS_CACHE缓存 - * @param key - * @return + * @param key 键值 + * @return 缓存对象 */ public static Object get(String key) { return get(SYS_CACHE, key); @@ -29,9 +28,9 @@ public class CacheUtils { /** * 获取SYS_CACHE缓存 - * @param key - * @param defaultValue - * @return + * @param key 键值 + * @param defaultValue 默认返回值 + * @return 缓存对象或默认值 */ public static Object get(String key, Object defaultValue) { Object value = get(key); @@ -40,8 +39,8 @@ public class CacheUtils { /** * 写入SYS_CACHE缓存 - * @param key - * @return + * @param key 键值 + * @param value 被缓存对象 */ public static void put(String key, Object value) { put(SYS_CACHE, key, value); @@ -49,29 +48,28 @@ public class CacheUtils { /** * 从SYS_CACHE缓存中移除 - * @param key - * @return + * @param key 键值 */ public static void remove(String key) { remove(SYS_CACHE, key); } /** - * 获取缓存 - * @param cacheName - * @param key - * @return + * 获取指定命名空间下的缓存 + * @param cacheName 缓存命名空间 + * @param key 键值 + * @return 该命名空间下的对应键值缓存 */ public static Object get(String cacheName, String key) { return getCache(cacheName).get(getKey(key)); } /** - * 获取缓存 - * @param cacheName - * @param key - * @param defaultValue - * @return + * 获取指定命名空间下的缓存,并在无缓存对象时返回默认值 + * @param cacheName 缓存命名空间 + * @param key 键值 + * @param defaultValue 默认返回值 + * @return 缓存对象或默认值 */ public static Object get(String cacheName, String key, Object defaultValue) { Object value = get(cacheName, getKey(key)); @@ -79,41 +77,39 @@ public class CacheUtils { } /** - * 写入缓存 - * @param cacheName - * @param key - * @param value + * 向指定命名空间下存入被缓存对象 + * @param cacheName 缓存命名空间 + * @param key 键值 + * @param value 该命名空间下被缓存对象 */ public static void put(String cacheName, String key, Object value) { getCache(cacheName).put(getKey(key), value); } /** - * 从缓存中移除 - * @param cacheName - * @param key + * 将指定命名空间下的缓存移除 + * @param cacheName 缓存命名空间 + * @param key 键值 */ public static void remove(String cacheName, String key) { getCache(cacheName).remove(getKey(key)); } /** - * 从缓存中移除所有 - * @param cacheName + * 清空命名空间下所有缓存 + * @param cacheName 命名空间 */ public static void removeAll(String cacheName) { Cache cache = getCache(cacheName); Set keys = cache.keys(); - for (Iterator it = keys.iterator(); it.hasNext();){ - cache.remove(it.next()); - } - logger.info("清理缓存: {} => {}", cacheName, keys); + cache.clear(); + LOGGER.info("清理缓存: {} => {}", cacheName, keys); } /** * 获取缓存键名,多数据源下增加数据源名称前缀 - * @param key - * @return + * @param key 键值 + * @return 返回对应数据源前缀拼接键值 */ private static String getKey(String key){ // String dsName = DataSourceHolder.getDataSourceName(); @@ -124,12 +120,12 @@ public class CacheUtils { } /** - * 获得一个Cache,没有则显示日志。 - * @param cacheName - * @return + * 获得指定命名空间的Cache,没有则显示日志。 + * @param cacheName 命名空间 + * @return 命名空间对应的Cache */ private static Cache getCache(String cacheName){ - Cache cache = cacheManager.getCache(cacheName); + Cache cache = CACHE_MANAGER.getCache(cacheName); if (cache == null){ throw new RuntimeException("当前系统中没有定义“"+cacheName+"”这个缓存。"); } diff --git a/src/main/java/com/rymcu/forest/util/ContextHolderUtils.java b/src/main/java/com/rymcu/forest/util/ContextHolderUtils.java index e8fa42b..57c474e 100644 --- a/src/main/java/com/rymcu/forest/util/ContextHolderUtils.java +++ b/src/main/java/com/rymcu/forest/util/ContextHolderUtils.java @@ -8,6 +8,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.HashMap; import java.util.Map; +import java.util.Objects; /** * @ClassName: ContextHolderUtils @@ -17,24 +18,22 @@ import java.util.Map; * */ public class ContextHolderUtils { - private static final Map sessionMap = new HashMap(); + private static final Map sessionMap = new HashMap<>(); /** * SpringMvc下获取request * - * @return + * @return HttpServletRequest */ public static HttpServletRequest getRequest() { - - HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); - return request; + return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); } /** * SpringMvc下获取session * - * @return + * @return HttpSession */ public static HttpSession getSession() { HttpServletRequest request = getRequest(); @@ -54,7 +53,7 @@ public class ContextHolderUtils { } public static HttpSession getSession2() { - HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); return request.getSession(); } @@ -65,9 +64,7 @@ public class ContextHolderUtils { } public static void removeSession(String sessionId){ - if(sessionMap.containsKey(sessionId)){ - sessionMap.remove(sessionId); - } + sessionMap.remove(sessionId); } } diff --git a/src/main/java/com/rymcu/forest/util/DateUtil.java b/src/main/java/com/rymcu/forest/util/DateUtil.java index 3da5633..3dff51e 100644 --- a/src/main/java/com/rymcu/forest/util/DateUtil.java +++ b/src/main/java/com/rymcu/forest/util/DateUtil.java @@ -13,22 +13,23 @@ public class DateUtil { if (StringUtils.isBlank(s)) { s = ""; } - for (int i = 0; i < len - s.length(); ++i) { - s = "0" + s; + StringBuilder sBuilder = new StringBuilder(s); + for (int i = 0; i < len - sBuilder.length(); ++i) { + sBuilder.insert(0, "0"); } - return s; + return sBuilder.toString(); } public static String getYear(Calendar cal) { - return String.valueOf(cal.get(1)); + return String.valueOf(cal.get(Calendar.YEAR)); } public static String getMonth(Calendar cal) { - return strLen(String.valueOf(cal.get(2) + 1), 2); + return strLen(String.valueOf(cal.get(Calendar.MONTH) + 1), 2); } public static String getDay(Calendar cal) { - return strLen(String.valueOf(cal.get(5)), 2); + return strLen(String.valueOf(cal.get(Calendar.DATE)), 2); } public static String getNowDateNum() { diff --git a/src/main/java/com/rymcu/forest/util/Digests.java b/src/main/java/com/rymcu/forest/util/Digests.java index 52464cf..f6f6544 100644 --- a/src/main/java/com/rymcu/forest/util/Digests.java +++ b/src/main/java/com/rymcu/forest/util/Digests.java @@ -20,7 +20,7 @@ public class Digests { private static final String SHA1 = "SHA-1"; private static final String MD5 = "MD5"; - private static SecureRandom random = new SecureRandom(); + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); /** * 对输入字符串进行md5散列. @@ -79,7 +79,7 @@ public class Digests { Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes); byte[] bytes = new byte[numBytes]; - random.nextBytes(bytes); + SECURE_RANDOM.nextBytes(bytes); return bytes; } diff --git a/src/main/java/com/rymcu/forest/util/ErrorCode.java b/src/main/java/com/rymcu/forest/util/ErrorCode.java index 79f818e..839d1bd 100644 --- a/src/main/java/com/rymcu/forest/util/ErrorCode.java +++ b/src/main/java/com/rymcu/forest/util/ErrorCode.java @@ -17,9 +17,9 @@ public enum ErrorCode { this.message = message; } - private String code; + private final String code; - private String message; + private final String message; public String getCode() { return code; diff --git a/src/main/java/com/rymcu/forest/util/NotificationUtils.java b/src/main/java/com/rymcu/forest/util/NotificationUtils.java index 93de7d0..56a1c87 100644 --- a/src/main/java/com/rymcu/forest/util/NotificationUtils.java +++ b/src/main/java/com/rymcu/forest/util/NotificationUtils.java @@ -29,7 +29,7 @@ public class NotificationUtils { private static ArticleService articleService = SpringContextHolder.getBean(ArticleService.class); private static CommentService commentService = SpringContextHolder.getBean(CommentService.class); - public static void sendAnnouncement(Integer dataId, String dataType, String dataSummary) { + public static void sendAnnouncement(Long dataId, String dataType, String dataSummary) { ExecutorService executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); CompletableFuture.supplyAsync(() -> { try { @@ -44,7 +44,7 @@ public class NotificationUtils { }, executor); } - public static void saveNotification(Integer idUser, Integer dataId, String dataType, String dataSummary) { + public static void saveNotification(Long idUser, Long dataId, String dataType, String dataSummary) { ExecutorService executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); CompletableFuture.supplyAsync(() -> { try { @@ -70,7 +70,7 @@ public class NotificationUtils { } - public static void sendArticlePush(Integer dataId, String dataType, String dataSummary, Integer articleAuthorId) { + public static void sendArticlePush(Long dataId, String dataType, String dataSummary, Long articleAuthorId) { ExecutorService executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); CompletableFuture.supplyAsync(() -> { try { @@ -154,12 +154,10 @@ public class NotificationUtils { private static String getFollowLink(String followingType, String id) { StringBuilder url = new StringBuilder(); url.append(Utils.getProperty("resource.domain")); - switch (followingType) { - case "0": - url = url.append("/user/").append(id); - break; - default: - url.append("/notification"); + if ("0".equals(followingType)) { + url.append("/user/").append(id); + } else { + url.append("/notification"); } return url.toString(); } diff --git a/src/main/java/com/rymcu/forest/web/api/admin/AdminArticleController.java b/src/main/java/com/rymcu/forest/web/api/admin/AdminArticleController.java index 8d14194..9b2cac8 100644 --- a/src/main/java/com/rymcu/forest/web/api/admin/AdminArticleController.java +++ b/src/main/java/com/rymcu/forest/web/api/admin/AdminArticleController.java @@ -26,8 +26,9 @@ public class AdminArticleController { private ArticleService articleService; @PatchMapping("/update-perfect") - public GlobalResult updatePerfect(@RequestBody Article article) { - Map map = articleService.updatePerfect(article.getIdArticle(), article.getArticlePerfect()); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult updatePerfect(@RequestBody Article article) { + Long idArticle = article.getIdArticle(); + String articlePerfect = article.getArticlePerfect(); + return GlobalResultGenerator.genSuccessResult(articleService.updatePerfect(idArticle, articlePerfect)); } } diff --git a/src/main/java/com/rymcu/forest/web/api/admin/AdminController.java b/src/main/java/com/rymcu/forest/web/api/admin/AdminController.java index b4a297a..e96c55d 100644 --- a/src/main/java/com/rymcu/forest/web/api/admin/AdminController.java +++ b/src/main/java/com/rymcu/forest/web/api/admin/AdminController.java @@ -2,26 +2,25 @@ package com.rymcu.forest.web.api.admin; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; +import com.rymcu.forest.core.exception.ServiceException; import com.rymcu.forest.core.result.GlobalResult; import com.rymcu.forest.core.result.GlobalResultGenerator; import com.rymcu.forest.dto.*; +import com.rymcu.forest.dto.admin.TagDTO; import com.rymcu.forest.dto.admin.TopicTagDTO; import com.rymcu.forest.dto.admin.UserRoleDTO; import com.rymcu.forest.entity.*; import com.rymcu.forest.service.*; -import com.rymcu.forest.util.Utils; import org.apache.commons.lang.StringUtils; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; -import java.util.HashMap; import java.util.List; -import java.util.Map; /** * @author ronger - * */ + */ @RestController @RequestMapping("/api/v1/admin") public class AdminController { @@ -40,213 +39,192 @@ public class AdminController { private ArticleService articleService; @Resource private CommentService commentService; + @Resource + private ProductService productService; @GetMapping("/users") - public GlobalResult> users(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, UserSearchDTO searchDTO){ + public GlobalResult> users(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, UserSearchDTO searchDTO) { PageHelper.startPage(page, rows); List list = userService.findUsers(searchDTO); PageInfo pageInfo = new PageInfo<>(list); - Map map = new HashMap(2); - map.put("users", pageInfo.getList()); - Map pagination = Utils.getPagination(pageInfo); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/user/{idUser}/role") - public GlobalResult> userRole(@PathVariable Integer idUser){ + public GlobalResult> userRole(@PathVariable Long idUser) { List roles = roleService.findByIdUser(idUser); return GlobalResultGenerator.genSuccessResult(roles); } @GetMapping("/roles") - public GlobalResult> roles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows){ + public GlobalResult> roles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) { PageHelper.startPage(page, rows); List list = roleService.findAll(); PageInfo pageInfo = new PageInfo<>(list); - Map map = new HashMap(2); - map.put("roles", pageInfo.getList()); - Map pagination = Utils.getPagination(pageInfo); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @PatchMapping("/user/update-role") - public GlobalResult updateUserRole(@RequestBody UserRoleDTO userRole){ - Map map = userService.updateUserRole(userRole.getIdUser(),userRole.getIdRole()); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult updateUserRole(@RequestBody UserRoleDTO userRole) throws ServiceException { + boolean flag = userService.updateUserRole(userRole.getIdUser(), userRole.getIdRole()); + return GlobalResultGenerator.genSuccessResult(flag); } @PatchMapping("/user/update-status") - public GlobalResult updateUserStatus(@RequestBody User user){ - Map map = userService.updateStatus(user.getIdUser(),user.getStatus()); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult updateUserStatus(@RequestBody User user) throws ServiceException { + boolean flag = userService.updateStatus(user.getIdUser(), user.getStatus()); + return GlobalResultGenerator.genSuccessResult(flag); } @PatchMapping("/role/update-status") - public GlobalResult updateRoleStatus(@RequestBody Role role){ - Map map = roleService.updateStatus(role.getIdRole(),role.getStatus()); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult updateRoleStatus(@RequestBody Role role) throws ServiceException { + boolean flag = roleService.updateStatus(role.getIdRole(), role.getStatus()); + return GlobalResultGenerator.genSuccessResult(flag); } @PostMapping("/role/post") - public GlobalResult addRole(@RequestBody Role role){ - Map map = roleService.saveRole(role); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult addRole(@RequestBody Role role) throws ServiceException { + boolean flag = roleService.saveRole(role); + return GlobalResultGenerator.genSuccessResult(flag); } @PutMapping("/role/post") - public GlobalResult updateRole(@RequestBody Role role){ - Map map = roleService.saveRole(role); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult updateRole(@RequestBody Role role) throws Exception { + boolean flag = roleService.saveRole(role); + return GlobalResultGenerator.genSuccessResult(flag); } @GetMapping("/topics") - public GlobalResult> topics(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows){ + public GlobalResult> topics(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) { PageHelper.startPage(page, rows); List list = topicService.findAll(); PageInfo pageInfo = new PageInfo<>(list); - Map map = new HashMap<>(2); - map.put("topics", pageInfo.getList()); - Map pagination = Utils.getPagination(pageInfo); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/topic/{topicUri}") - public GlobalResult topic(@PathVariable String topicUri){ + public GlobalResult topic(@PathVariable String topicUri) { if (StringUtils.isBlank(topicUri)) { - return GlobalResultGenerator.genErrorResult("数据异常!"); + throw new IllegalArgumentException("参数异常!"); } Topic topic = topicService.findTopicByTopicUri(topicUri); return GlobalResultGenerator.genSuccessResult(topic); } @GetMapping("/topic/{topicUri}/tags") - public GlobalResult topicTags(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows,@PathVariable String topicUri){ + public GlobalResult> topicTags(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, @PathVariable String topicUri) { if (StringUtils.isBlank(topicUri)) { - return GlobalResultGenerator.genErrorResult("数据异常!"); + throw new IllegalArgumentException("参数异常!"); } - Map map = topicService.findTagsByTopicUri(topicUri,page,rows); - return GlobalResultGenerator.genSuccessResult(map); + PageHelper.startPage(page, rows); + List list = topicService.findTagsByTopicUri(topicUri); + PageInfo pageInfo = new PageInfo<>(list); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/topic/detail/{idTopic}") - public GlobalResult topicDetail(@PathVariable Integer idTopic){ + public GlobalResult topicDetail(@PathVariable Integer idTopic) { Topic topic = topicService.findById(idTopic.toString()); return GlobalResultGenerator.genSuccessResult(topic); } @GetMapping("/topic/unbind-topic-tags") - public GlobalResult unbindTopicTags(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, HttpServletRequest request){ - Integer idTopic = Integer.valueOf(request.getParameter("idTopic")); + public GlobalResult> unbindTopicTags(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, HttpServletRequest request) { + Long idTopic = Long.valueOf(request.getParameter("idTopic")); String tagTitle = request.getParameter("tagTitle"); PageHelper.startPage(page, rows); List list = topicService.findUnbindTagsById(idTopic, tagTitle); PageInfo pageInfo = new PageInfo<>(list); - Map map = new HashMap<>(2); - map.put("tags", pageInfo.getList()); - Map pagination = Utils.getPagination(pageInfo); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @PostMapping("/topic/bind-topic-tag") - public GlobalResult bindTopicTag(@RequestBody TopicTagDTO topicTag){ - Map map = topicService.bindTopicTag(topicTag); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult bindTopicTag(@RequestBody TopicTagDTO topicTag) throws Exception { + TopicTagDTO newTopicTagDTO = topicService.bindTopicTag(topicTag); + return GlobalResultGenerator.genSuccessResult(newTopicTagDTO); } @DeleteMapping("/topic/unbind-topic-tag") - public GlobalResult unbindTopicTag(@RequestBody TopicTagDTO topicTag){ - Map map = topicService.unbindTopicTag(topicTag); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult unbindTopicTag(@RequestBody TopicTagDTO topicTag) throws Exception { + TopicTagDTO topicTagDTO = topicService.unbindTopicTag(topicTag); + return GlobalResultGenerator.genSuccessResult(topicTagDTO); } @PostMapping("/topic/post") - public GlobalResult addTopic(@RequestBody Topic topic){ - Map map = topicService.saveTopic(topic); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult addTopic(@RequestBody Topic topic) throws Exception { + Topic newTopic = topicService.saveTopic(topic); + return GlobalResultGenerator.genSuccessResult(newTopic); } @PutMapping("/topic/post") - public GlobalResult updateTopic(@RequestBody Topic topic){ - Map map = topicService.saveTopic(topic); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult updateTopic(@RequestBody Topic topic) throws Exception { + Topic newTopic = topicService.saveTopic(topic); + return GlobalResultGenerator.genSuccessResult(newTopic); } @GetMapping("/tags") - public GlobalResult> tags(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows){ + public GlobalResult> tags(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) { PageHelper.startPage(page, rows); List list = tagService.findAll(); PageInfo pageInfo = new PageInfo<>(list); - Map map = new HashMap<>(2); - map.put("tags", pageInfo.getList()); - Map pagination = Utils.getPagination(pageInfo); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @DeleteMapping("/tag/clean-unused") - public GlobalResult> cleanUnusedTag(){ - Map map = tagService.cleanUnusedTag(); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult cleanUnusedTag() { + boolean bool = tagService.cleanUnusedTag(); + return GlobalResultGenerator.genSuccessResult(bool); } @GetMapping("/tag/detail/{idTag}") - public GlobalResult tagDetail(@PathVariable Integer idTag){ + public GlobalResult tagDetail(@PathVariable Integer idTag) { Tag tag = tagService.findById(idTag.toString()); return GlobalResultGenerator.genSuccessResult(tag); } @PostMapping("/tag/post") - public GlobalResult addTag(@RequestBody Tag tag){ - Map map = tagService.saveTag(tag); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult addTag(@RequestBody Tag tag) throws Exception { + Tag newTag = tagService.saveTag(tag); + return GlobalResultGenerator.genSuccessResult(newTag); } @PutMapping("/tag/post") - public GlobalResult updateTag(@RequestBody Tag tag){ - Map map = tagService.saveTag(tag); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult updateTag(@RequestBody Tag tag) throws Exception { + Tag newTag = tagService.saveTag(tag); + return GlobalResultGenerator.genSuccessResult(newTag); } @GetMapping("/special-days") - public GlobalResult specialDays(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) { + public GlobalResult> specialDays(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) { PageHelper.startPage(page, rows); List list = specialDayService.findAll(); PageInfo pageInfo = new PageInfo<>(list); - Map map = new HashMap<>(2); - map.put("specialDays", pageInfo.getList()); - Map pagination = Utils.getPagination(pageInfo); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/articles") - public GlobalResult articles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, ArticleSearchDTO articleSearchDTO) { + public GlobalResult> articles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, ArticleSearchDTO articleSearchDTO) { PageHelper.startPage(page, rows); List list = articleService.findArticles(articleSearchDTO); PageInfo pageInfo = new PageInfo<>(list); - Map map = new HashMap<>(2); - map.put("articles", pageInfo.getList()); - Map pagination = Utils.getPagination(pageInfo); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/comments") - public GlobalResult comments(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) { + public GlobalResult> comments(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) { PageHelper.startPage(page, rows); List list = commentService.findComments(); PageInfo pageInfo = new PageInfo<>(list); - Map map = new HashMap<>(2); - map.put("comments", pageInfo.getList()); - Map pagination = Utils.getPagination(pageInfo); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); + } + + @GetMapping("/products") + public GlobalResult> products(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) { + PageHelper.startPage(page, rows); + List list = productService.findProducts(); + PageInfo pageInfo = new PageInfo<>(list); + return GlobalResultGenerator.genSuccessResult(pageInfo); } - } diff --git a/src/main/java/com/rymcu/forest/web/api/admin/AdminCurrencyRuleController.java b/src/main/java/com/rymcu/forest/web/api/admin/AdminCurrencyRuleController.java new file mode 100644 index 0000000..39cf31a --- /dev/null +++ b/src/main/java/com/rymcu/forest/web/api/admin/AdminCurrencyRuleController.java @@ -0,0 +1,42 @@ +package com.rymcu.forest.web.api.admin; + +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.rymcu.forest.core.result.GlobalResult; +import com.rymcu.forest.core.result.GlobalResultGenerator; +import com.rymcu.forest.dto.TransactionRecordDTO; +import com.rymcu.forest.entity.CurrencyRule; +import com.rymcu.forest.service.CurrencyRuleService; +import com.rymcu.forest.util.Utils; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created on 2022/3/6 18:26. + * + * @author ronger + * @email ronger-x@outlook.com + */ +@RestController +@RequestMapping("/api/v1/admin/rule/currency") +public class AdminCurrencyRuleController { + @Resource + private CurrencyRuleService currencyRuleService; + + @GetMapping("/list") + public GlobalResult> list(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "20") Integer rows, HttpServletRequest request) { + PageHelper.startPage(page, rows); + List list = currencyRuleService.findAll(); + PageInfo pageInfo = new PageInfo(list); + return GlobalResultGenerator.genSuccessResult(pageInfo); + } + +} diff --git a/src/main/java/com/rymcu/forest/web/api/admin/DashboardController.java b/src/main/java/com/rymcu/forest/web/api/admin/DashboardController.java index 6d34e5c..6b17356 100644 --- a/src/main/java/com/rymcu/forest/web/api/admin/DashboardController.java +++ b/src/main/java/com/rymcu/forest/web/api/admin/DashboardController.java @@ -49,41 +49,26 @@ public class DashboardController { } @GetMapping("/new-users") - public GlobalResult newUsers(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) { + public GlobalResult> newUsers(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) { PageHelper.startPage(page, rows); List list = dashboardService.newUsers(); PageInfo pageInfo = new PageInfo<>(list); - Map map = new HashMap(2); - map.put("users", pageInfo.getList()); - Map pagination = Utils.getPagination(pageInfo); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/new-bank-accounts") - public GlobalResult newBankAccounts(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) { + public GlobalResult> newBankAccounts(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) { PageHelper.startPage(page, rows); List list = dashboardService.newBankAccounts(); PageInfo pageInfo = new PageInfo(list); - Map map = new HashMap(2); - map.put("bankAccounts", pageInfo.getList()); - Map pagination = new HashMap(4); - pagination.put("pageSize", pageInfo.getPageSize()); - pagination.put("total", pageInfo.getTotal()); - pagination.put("currentPage", pageInfo.getPageNum()); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/new-articles") - public GlobalResult newArticles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) { + public GlobalResult> newArticles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) { PageHelper.startPage(page, rows); List list = dashboardService.newArticles(); PageInfo pageInfo = new PageInfo<>(list); - Map map = new HashMap<>(2); - map.put("articles", pageInfo.getList()); - Map pagination = Utils.getPagination(pageInfo); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } } diff --git a/src/main/java/com/rymcu/forest/web/api/article/ArticleController.java b/src/main/java/com/rymcu/forest/web/api/article/ArticleController.java index a21f5e8..64fa34c 100644 --- a/src/main/java/com/rymcu/forest/web/api/article/ArticleController.java +++ b/src/main/java/com/rymcu/forest/web/api/article/ArticleController.java @@ -2,6 +2,7 @@ package com.rymcu.forest.web.api.article; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; +import com.rymcu.forest.core.exception.BusinessException; import com.rymcu.forest.core.result.GlobalResult; import com.rymcu.forest.core.result.GlobalResultGenerator; import com.rymcu.forest.core.service.security.annotation.AuthorshipInterceptor; @@ -10,21 +11,21 @@ import com.rymcu.forest.dto.CommentDTO; import com.rymcu.forest.entity.Article; import com.rymcu.forest.entity.ArticleThumbsUp; import com.rymcu.forest.entity.Sponsor; +import com.rymcu.forest.entity.User; import com.rymcu.forest.enumerate.Module; import com.rymcu.forest.service.ArticleService; import com.rymcu.forest.service.ArticleThumbsUpService; import com.rymcu.forest.service.CommentService; import com.rymcu.forest.service.SponsorService; -import com.rymcu.forest.util.Utils; +import com.rymcu.forest.util.UserUtils; import com.rymcu.forest.web.api.exception.BaseApiException; +import com.rymcu.forest.web.api.exception.ErrorCode; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; import java.io.UnsupportedEncodingException; -import java.util.HashMap; import java.util.List; -import java.util.Map; +import java.util.Objects; /** * @author ronger @@ -43,73 +44,86 @@ public class ArticleController { private SponsorService sponsorService; @GetMapping("/detail/{idArticle}") - public GlobalResult> detail(@PathVariable Integer idArticle, @RequestParam(defaultValue = "2") Integer type) { - ArticleDTO articleDTO = articleService.findArticleDTOById(idArticle, type); - Map map = new HashMap<>(1); - map.put("article", articleDTO); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult detail(@PathVariable Long idArticle, @RequestParam(defaultValue = "2") Integer type) { + ArticleDTO dto = articleService.findArticleDTOById(idArticle, type); + return GlobalResultGenerator.genSuccessResult(dto); } @PostMapping("/post") - public GlobalResult postArticle(@RequestBody ArticleDTO article, HttpServletRequest request) throws BaseApiException, UnsupportedEncodingException { - Map map = articleService.postArticle(article, request); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult postArticle(@RequestBody ArticleDTO article) throws BaseApiException, UnsupportedEncodingException { + User user = UserUtils.getCurrentUserByToken(); + if (Objects.isNull(user)) { + throw new BaseApiException(ErrorCode.INVALID_TOKEN); + } + return GlobalResultGenerator.genSuccessResult(articleService.postArticle(article, user)); } @PutMapping("/post") @AuthorshipInterceptor(moduleName = Module.ARTICLE) - public GlobalResult updateArticle(@RequestBody ArticleDTO article, HttpServletRequest request) throws BaseApiException, UnsupportedEncodingException { - Map map = articleService.postArticle(article, request); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult updateArticle(@RequestBody ArticleDTO article) throws BaseApiException, UnsupportedEncodingException { + User user = UserUtils.getCurrentUserByToken(); + if (Objects.isNull(user)) { + throw new BaseApiException(ErrorCode.INVALID_TOKEN); + } + return GlobalResultGenerator.genSuccessResult(articleService.postArticle(article, user)); } @DeleteMapping("/delete/{idArticle}") @AuthorshipInterceptor(moduleName = Module.ARTICLE) - public GlobalResult delete(@PathVariable Integer idArticle) throws BaseApiException { - Map map = articleService.delete(idArticle); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult delete(@PathVariable Long idArticle) throws BaseApiException { + return GlobalResultGenerator.genSuccessResult(articleService.delete(idArticle)); } @GetMapping("/{idArticle}/comments") - public GlobalResult> commons(@PathVariable Integer idArticle) { - List commentDTOList = commentService.getArticleComments(idArticle); - Map map = new HashMap<>(1); - map.put("comments", commentDTOList); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult> commons(@PathVariable Integer idArticle) { + return GlobalResultGenerator.genSuccessResult(commentService.getArticleComments(idArticle)); } @GetMapping("/drafts") - public GlobalResult drafts(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) throws BaseApiException { + public GlobalResult> drafts(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) throws BaseApiException { PageHelper.startPage(page, rows); - List list = articleService.findDrafts(); - PageInfo pageInfo = new PageInfo(list); - Map map = Utils.getArticlesGlobalResult(pageInfo); - return GlobalResultGenerator.genSuccessResult(map); + User user = UserUtils.getCurrentUserByToken(); + if (Objects.isNull(user)) { + throw new BaseApiException(ErrorCode.INVALID_TOKEN); + } + List list = articleService.findDrafts(user.getIdUser()); + PageInfo pageInfo = new PageInfo<>(list); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/{idArticle}/share") - public GlobalResult share(@PathVariable Integer idArticle) throws BaseApiException { - Map map = articleService.share(idArticle); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult share(@PathVariable Integer idArticle) throws BaseApiException { + return GlobalResultGenerator.genResult(true, articleService.share(idArticle), ""); } @PostMapping("/update-tags") @AuthorshipInterceptor(moduleName = Module.ARTICLE_TAG) - public GlobalResult updateTags(@RequestBody Article article) throws BaseApiException, UnsupportedEncodingException { - Map map = articleService.updateTags(article.getIdArticle(), article.getArticleTags()); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult updateTags(@RequestBody Article article) throws BaseApiException, UnsupportedEncodingException { + Long idArticle = article.getIdArticle(); + String articleTags = article.getArticleTags(); + User user = UserUtils.getCurrentUserByToken(); + return GlobalResultGenerator.genSuccessResult(articleService.updateTags(idArticle, articleTags, user.getIdUser())); } @PostMapping("/thumbs-up") - public GlobalResult thumbsUp(@RequestBody ArticleThumbsUp articleThumbsUp) throws BaseApiException { - Map map = articleThumbsUpService.thumbsUp(articleThumbsUp); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult thumbsUp(@RequestBody ArticleThumbsUp articleThumbsUp) throws Exception { + if (Objects.isNull(articleThumbsUp) || Objects.isNull(articleThumbsUp.getIdArticle())) { + throw new BusinessException("数据异常,文章不存在!"); + } + User user = UserUtils.getCurrentUserByToken(); + articleThumbsUp.setIdUser(user.getIdUser()); + return GlobalResultGenerator.genSuccessResult(articleThumbsUpService.thumbsUp(articleThumbsUp)); } @PostMapping("/sponsor") public GlobalResult sponsor(@RequestBody Sponsor sponsor) throws Exception { - Map map = sponsorService.sponsorship(sponsor); - return GlobalResultGenerator.genSuccessResult(map); + if (Objects.isNull(sponsor) || Objects.isNull(sponsor.getDataId()) || Objects.isNull(sponsor.getDataType())) { + throw new IllegalArgumentException("数据异常"); + } + User user = UserUtils.getCurrentUserByToken(); + sponsor.setSponsor(user.getIdUser()); + boolean flag = sponsorService.sponsorship(sponsor); + return GlobalResultGenerator.genSuccessResult(flag); } } diff --git a/src/main/java/com/rymcu/forest/web/api/bank/BankAccountController.java b/src/main/java/com/rymcu/forest/web/api/bank/BankAccountController.java index fd399ab..2e1db18 100644 --- a/src/main/java/com/rymcu/forest/web/api/bank/BankAccountController.java +++ b/src/main/java/com/rymcu/forest/web/api/bank/BankAccountController.java @@ -28,39 +28,28 @@ public class BankAccountController { private BankAccountService bankAccountService; @GetMapping("/list") - public GlobalResult banks(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, BankAccountSearchDTO bankAccountSearchDTO) { + public GlobalResult> banks(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, BankAccountSearchDTO bankAccountSearchDTO) { PageHelper.startPage(page, rows); List list = bankAccountService.findBankAccounts(bankAccountSearchDTO); PageInfo pageInfo = new PageInfo(list); - Map map = new HashMap(2); - map.put("bankAccounts", pageInfo.getList()); - Map pagination = new HashMap(4); - pagination.put("pageSize", pageInfo.getPageSize()); - pagination.put("total", pageInfo.getTotal()); - pagination.put("currentPage", pageInfo.getPageNum()); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/{idUser}") - public GlobalResult detail(@PathVariable Integer idUser) { + public GlobalResult detail(@PathVariable Long idUser) { BankAccountDTO bankAccount = bankAccountService.findBankAccountByIdUser(idUser); return GlobalResultGenerator.genSuccessResult(bankAccount); } @GetMapping("/transaction-records") - public GlobalResult transactionRecords(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "20") Integer rows, HttpServletRequest request) { + public GlobalResult> transactionRecords(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "20") Integer rows, HttpServletRequest request) { String bankAccount = request.getParameter("bankAccount"); String startDate = request.getParameter("startDate"); String endDate = request.getParameter("endDate"); PageHelper.startPage(page, rows); List list = bankAccountService.findUserTransactionRecords(bankAccount, startDate, endDate); PageInfo pageInfo = new PageInfo(list); - Map map = new HashMap(2); - map.put("records", pageInfo.getList()); - Map pagination = Utils.getPagination(pageInfo); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } } diff --git a/src/main/java/com/rymcu/forest/web/api/bank/BankController.java b/src/main/java/com/rymcu/forest/web/api/bank/BankController.java index f155982..e157a08 100644 --- a/src/main/java/com/rymcu/forest/web/api/bank/BankController.java +++ b/src/main/java/com/rymcu/forest/web/api/bank/BankController.java @@ -30,15 +30,11 @@ public class BankController { private BankService bankService; @GetMapping("/list") - public GlobalResult banks(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) { + public GlobalResult> banks(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) { PageHelper.startPage(page, rows); List list = bankService.findBanks(); PageInfo pageInfo = new PageInfo(list); - Map map = new HashMap(2); - map.put("banks", pageInfo.getList()); - Map pagination = Utils.getPagination(pageInfo); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } } diff --git a/src/main/java/com/rymcu/forest/web/api/bank/TransactionRecordController.java b/src/main/java/com/rymcu/forest/web/api/bank/TransactionRecordController.java index c3a230a..123162c 100644 --- a/src/main/java/com/rymcu/forest/web/api/bank/TransactionRecordController.java +++ b/src/main/java/com/rymcu/forest/web/api/bank/TransactionRecordController.java @@ -22,13 +22,13 @@ public class TransactionRecordController { private TransactionRecordService transactionRecordService; @PostMapping("/transfer") - public GlobalResult transfer(@RequestBody TransactionRecord transactionRecord) throws Exception { + public GlobalResult transfer(@RequestBody TransactionRecord transactionRecord) { transactionRecord = transactionRecordService.transfer(transactionRecord); return GlobalResultGenerator.genSuccessResult(transactionRecord); } @PostMapping("/newbie-rewards") - public GlobalResult newbieRewards(@RequestBody TransactionRecord transactionRecord) throws Exception { + public GlobalResult newbieRewards(@RequestBody TransactionRecord transactionRecord) { transactionRecord = transactionRecordService.newbieRewards(transactionRecord); return GlobalResultGenerator.genSuccessResult(transactionRecord); } diff --git a/src/main/java/com/rymcu/forest/web/api/bank/WalletController.java b/src/main/java/com/rymcu/forest/web/api/bank/WalletController.java index 44cb23c..e9ea1ac 100644 --- a/src/main/java/com/rymcu/forest/web/api/bank/WalletController.java +++ b/src/main/java/com/rymcu/forest/web/api/bank/WalletController.java @@ -33,25 +33,21 @@ public class WalletController { @GetMapping("/{idUser}") @SecurityInterceptor - public GlobalResult detail(@PathVariable Integer idUser) { + public GlobalResult detail(@PathVariable Long idUser) { BankAccountDTO bankAccount = bankAccountService.findBankAccountByIdUser(idUser); return GlobalResultGenerator.genSuccessResult(bankAccount); } @GetMapping("/transaction-records") @SecurityInterceptor - public GlobalResult transactionRecords(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "20") Integer rows, HttpServletRequest request) { + public GlobalResult> transactionRecords(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "20") Integer rows, HttpServletRequest request) { String idUser = request.getParameter("idUser"); String startDate = request.getParameter("startDate"); String endDate = request.getParameter("endDate"); - BankAccountDTO bankAccount = bankAccountService.findBankAccountByIdUser(Integer.valueOf(idUser)); + BankAccountDTO bankAccount = bankAccountService.findBankAccountByIdUser(Long.valueOf(idUser)); PageHelper.startPage(page, rows); List list = bankAccountService.findUserTransactionRecords(bankAccount.getBankAccount(), startDate, endDate); PageInfo pageInfo = new PageInfo(list); - Map map = new HashMap(2); - map.put("records", pageInfo.getList()); - Map pagination = Utils.getPagination(pageInfo); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } } diff --git a/src/main/java/com/rymcu/forest/web/api/comment/CommentController.java b/src/main/java/com/rymcu/forest/web/api/comment/CommentController.java index 56d8cb6..c01e172 100644 --- a/src/main/java/com/rymcu/forest/web/api/comment/CommentController.java +++ b/src/main/java/com/rymcu/forest/web/api/comment/CommentController.java @@ -4,6 +4,7 @@ import com.rymcu.forest.core.result.GlobalResult; import com.rymcu.forest.core.result.GlobalResultGenerator; import com.rymcu.forest.entity.Comment; import com.rymcu.forest.service.CommentService; +import com.rymcu.forest.util.UserUtils; import com.rymcu.forest.web.api.exception.BaseApiException; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -12,8 +13,7 @@ import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; -import java.io.UnsupportedEncodingException; -import java.util.Map; +import java.util.Objects; /** * @author ronger @@ -26,8 +26,9 @@ public class CommentController { private CommentService commentService; @PostMapping("/post") - public GlobalResult postComment(@RequestBody Comment comment, HttpServletRequest request) throws BaseApiException { - Map map = commentService.postComment(comment,request); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult postComment(@RequestBody Comment comment, HttpServletRequest request) throws BaseApiException { + comment.setCommentAuthorId(Objects.requireNonNull(UserUtils.getCurrentUserByToken()).getIdUser()); + comment = commentService.postComment(comment,request); + return GlobalResultGenerator.genSuccessResult(comment); } } diff --git a/src/main/java/com/rymcu/forest/web/api/common/CommonApiController.java b/src/main/java/com/rymcu/forest/web/api/common/CommonApiController.java index 4d1035d..9252362 100644 --- a/src/main/java/com/rymcu/forest/web/api/common/CommonApiController.java +++ b/src/main/java/com/rymcu/forest/web/api/common/CommonApiController.java @@ -2,18 +2,16 @@ package com.rymcu.forest.web.api.common; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; +import com.rymcu.forest.core.exception.AccountExistsException; +import com.rymcu.forest.core.exception.ServiceException; import com.rymcu.forest.core.result.GlobalResult; import com.rymcu.forest.core.result.GlobalResultGenerator; import com.rymcu.forest.core.result.GlobalResultMessage; import com.rymcu.forest.core.service.log.annotation.VisitLogger; import com.rymcu.forest.dto.*; import com.rymcu.forest.entity.User; -import com.rymcu.forest.service.ArticleService; -import com.rymcu.forest.service.JavaMailService; -import com.rymcu.forest.service.PortfolioService; -import com.rymcu.forest.service.UserService; -import com.rymcu.forest.util.UserUtils; -import com.rymcu.forest.util.Utils; +import com.rymcu.forest.service.*; +import org.apache.shiro.authc.UnknownAccountException; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; @@ -37,6 +35,8 @@ public class CommonApiController { private ArticleService articleService; @Resource private PortfolioService portfolioService; + @Resource + private ProductService productService; @GetMapping("/get-email-code") public GlobalResult> getEmailCode(@RequestParam("email") String email) throws MessagingException { @@ -44,7 +44,7 @@ public class CommonApiController { map.put("message", GlobalResultMessage.SEND_SUCCESS.getMessage()); User user = userService.findByAccount(email); if (user != null) { - map.put("message", "该邮箱已被注册!"); + throw new AccountExistsException("该邮箱已被注册!"); } else { Integer result = javaMailService.sendEmailCode(email); if (result == 0) { @@ -55,31 +55,29 @@ public class CommonApiController { } @GetMapping("/get-forget-password-email") - public GlobalResult> getForgetPasswordEmail(@RequestParam("email") String email) throws MessagingException { - Map map = new HashMap<>(1); - map.put("message", GlobalResultMessage.SEND_SUCCESS.getMessage()); + public GlobalResult getForgetPasswordEmail(@RequestParam("email") String email) throws MessagingException, ServiceException { User user = userService.findByAccount(email); if (user != null) { Integer result = javaMailService.sendForgetPasswordEmail(email); if (result == 0) { - map.put("message", GlobalResultMessage.SEND_FAIL.getMessage()); + throw new ServiceException(GlobalResultMessage.SEND_FAIL.getMessage()); } } else { - map.put("message", "该邮箱未注册!"); + throw new UnknownAccountException("该邮箱未注册!"); } - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(GlobalResultMessage.SEND_SUCCESS.getMessage()); } @PostMapping("/register") - public GlobalResult register(@RequestBody UserRegisterInfoDTO registerInfo) { - Map map = userService.register(registerInfo.getEmail(), registerInfo.getPassword(), registerInfo.getCode()); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult register(@RequestBody UserRegisterInfoDTO registerInfo) { + boolean flag = userService.register(registerInfo.getEmail(), registerInfo.getPassword(), registerInfo.getCode()); + return GlobalResultGenerator.genSuccessResult(flag); } @PostMapping("/login") - public GlobalResult login(@RequestBody User user) { - Map map = userService.login(user.getAccount(), user.getPassword()); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult login(@RequestBody User user) throws ServiceException { + TokenUser tokenUser = userService.login(user.getAccount(), user.getPassword()); + return GlobalResultGenerator.genSuccessResult(tokenUser); } @GetMapping("/heartbeat") @@ -89,65 +87,69 @@ public class CommonApiController { @GetMapping("/articles") @VisitLogger - public GlobalResult articles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, ArticleSearchDTO searchDTO) { + public GlobalResult> articles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, ArticleSearchDTO searchDTO) { PageHelper.startPage(page, rows); List list = articleService.findArticles(searchDTO); - PageInfo pageInfo = new PageInfo(list); - Map map = Utils.getArticlesGlobalResult(pageInfo); - return GlobalResultGenerator.genSuccessResult(map); + PageInfo pageInfo = new PageInfo<>(list); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/announcements") - public GlobalResult announcements(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "5") Integer rows) { + public GlobalResult> announcements(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "5") Integer rows) { PageHelper.startPage(page, rows); List list = articleService.findAnnouncements(); - PageInfo pageInfo = new PageInfo(list); - Map map = Utils.getArticlesGlobalResult(pageInfo); - return GlobalResultGenerator.genSuccessResult(map); + PageInfo pageInfo = new PageInfo<>(list); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/article/{id}") @VisitLogger - public GlobalResult> article(@PathVariable Integer id) { + public GlobalResult article(@PathVariable Long id) { ArticleDTO articleDTO = articleService.findArticleDTOById(id, 1); - Map map = new HashMap<>(1); - map.put("article", articleDTO); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(articleDTO); } @PatchMapping("/forget-password") - public GlobalResult forgetPassword(@RequestBody ForgetPasswordDTO forgetPassword) { - Map map = userService.forgetPassword(forgetPassword.getCode(), forgetPassword.getPassword()); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult forgetPassword(@RequestBody ForgetPasswordDTO forgetPassword) throws ServiceException { + boolean flag = userService.forgetPassword(forgetPassword.getCode(), forgetPassword.getPassword()); + return GlobalResultGenerator.genSuccessResult(flag); } @GetMapping("/portfolio/{id}") @VisitLogger - public GlobalResult> portfolio(@PathVariable Integer id) { + public GlobalResult portfolio(@PathVariable Long id) { PortfolioDTO portfolioDTO = portfolioService.findPortfolioDTOById(id, 1); - Map map = new HashMap<>(1); - map.put("portfolio", portfolioDTO); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(portfolioDTO); } @GetMapping("/portfolio/{id}/articles") - public GlobalResult articles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, @PathVariable Integer id) { + public GlobalResult> articles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, @PathVariable Long id) { PageHelper.startPage(page, rows); List list = articleService.findArticlesByIdPortfolio(id); - PageInfo pageInfo = new PageInfo(list); - Map map = Utils.getArticlesGlobalResult(pageInfo); - return GlobalResultGenerator.genSuccessResult(map); + PageInfo pageInfo = new PageInfo<>(list); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/portfolios") - public GlobalResult portfolios(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "12") Integer rows) { + public GlobalResult> portfolios(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "12") Integer rows) { PageHelper.startPage(page, rows); List list = portfolioService.findPortfolios(); - PageInfo pageInfo = new PageInfo(list); - Map map = new HashMap(2); - map.put("portfolios", pageInfo.getList()); - Map pagination = Utils.getPagination(pageInfo); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + PageInfo pageInfo = new PageInfo<>(list); + return GlobalResultGenerator.genSuccessResult(pageInfo); + } + + @GetMapping("/products") + public GlobalResult> products(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "12") Integer rows) { + PageHelper.startPage(page, rows); + List list = productService.findProducts(); + PageInfo pageInfo = new PageInfo<>(list); + return GlobalResultGenerator.genSuccessResult(pageInfo); + } + + @GetMapping("/product/{id}") + @VisitLogger + public GlobalResult product(@PathVariable Integer id) { + ProductDTO productDTO = productService.findProductDTOById(id, 1); + return GlobalResultGenerator.genSuccessResult(productDTO); } } diff --git a/src/main/java/com/rymcu/forest/web/api/notification/NotificationController.java b/src/main/java/com/rymcu/forest/web/api/notification/NotificationController.java index ac8e403..4508ecc 100644 --- a/src/main/java/com/rymcu/forest/web/api/notification/NotificationController.java +++ b/src/main/java/com/rymcu/forest/web/api/notification/NotificationController.java @@ -31,7 +31,7 @@ public class NotificationController { private NotificationService notificationService; @GetMapping("/all") - public GlobalResult notifications(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) throws BaseApiException { + public GlobalResult> notifications(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) throws BaseApiException { User user = UserUtils.getCurrentUserByToken(); if (Objects.isNull(user)) { throw new BaseApiException(ErrorCode.TOKEN_); @@ -39,12 +39,11 @@ public class NotificationController { PageHelper.startPage(page, rows); List list = notificationService.findNotifications(user.getIdUser()); PageInfo pageInfo = new PageInfo(list); - Map map = Utils.getNotificationDTOsGlobalResult(pageInfo); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/unread") - public GlobalResult unreadNotification(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) throws BaseApiException { + public GlobalResult> unreadNotification(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) throws BaseApiException { User user = UserUtils.getCurrentUserByToken(); if (Objects.isNull(user)) { throw new BaseApiException(ErrorCode.TOKEN_); @@ -52,12 +51,11 @@ public class NotificationController { PageHelper.startPage(page, rows); List list = notificationService.findUnreadNotifications(user.getIdUser()); PageInfo pageInfo = new PageInfo(list); - Map map = Utils.getNotificationsGlobalResult(pageInfo); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @PutMapping("/read/{id}") - public GlobalResult read(@PathVariable Integer id) { + public GlobalResult read(@PathVariable Long id) { Integer result = notificationService.readNotification(id); if (result == 0) { return GlobalResultGenerator.genErrorResult("标记已读失败"); diff --git a/src/main/java/com/rymcu/forest/web/api/portfolio/PortfolioController.java b/src/main/java/com/rymcu/forest/web/api/portfolio/PortfolioController.java index bff6c14..81a8e99 100644 --- a/src/main/java/com/rymcu/forest/web/api/portfolio/PortfolioController.java +++ b/src/main/java/com/rymcu/forest/web/api/portfolio/PortfolioController.java @@ -1,13 +1,18 @@ package com.rymcu.forest.web.api.portfolio; +import com.github.pagehelper.PageInfo; +import com.rymcu.forest.core.exception.ServiceException; import com.rymcu.forest.core.result.GlobalResult; import com.rymcu.forest.core.result.GlobalResultGenerator; import com.rymcu.forest.core.service.security.annotation.AuthorshipInterceptor; import com.rymcu.forest.dto.PortfolioArticleDTO; import com.rymcu.forest.dto.PortfolioDTO; import com.rymcu.forest.entity.Portfolio; +import com.rymcu.forest.entity.User; import com.rymcu.forest.enumerate.Module; import com.rymcu.forest.service.PortfolioService; +import com.rymcu.forest.service.UserService; +import com.rymcu.forest.util.UserUtils; import com.rymcu.forest.web.api.exception.BaseApiException; import org.springframework.web.bind.annotation.*; @@ -24,61 +29,98 @@ public class PortfolioController { @Resource private PortfolioService portfolioService; + @Resource + private UserService userService; @GetMapping("/detail/{idPortfolio}") - public GlobalResult detail(@PathVariable Integer idPortfolio,@RequestParam(defaultValue = "0") Integer type) { - PortfolioDTO portfolio = portfolioService.findPortfolioDTOById(idPortfolio, type); - Map map = new HashMap<>(1); - map.put("portfolio", portfolio); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult detail(@PathVariable Long idPortfolio, @RequestParam(defaultValue = "0") Integer type) { + if (idPortfolio == null || idPortfolio == 0) { + throw new IllegalArgumentException("作品集主键参数异常!"); + } + return GlobalResultGenerator.genSuccessResult(portfolioService.findPortfolioDTOById(idPortfolio, type)); } @PostMapping("/post") - public GlobalResult add(@RequestBody Portfolio portfolio) throws BaseApiException { + public GlobalResult add(@RequestBody Portfolio portfolio) throws BaseApiException { + User user = UserUtils.getCurrentUserByToken(); + portfolio.setPortfolioAuthorId(user.getIdUser()); portfolio = portfolioService.postPortfolio(portfolio); return GlobalResultGenerator.genSuccessResult(portfolio); } @PutMapping("/post") @AuthorshipInterceptor(moduleName = Module.PORTFOLIO) - public GlobalResult update(@RequestBody Portfolio portfolio) throws BaseApiException { + public GlobalResult update(@RequestBody Portfolio portfolio) throws BaseApiException { + if (portfolio.getIdPortfolio() == null || portfolio.getIdPortfolio() == 0) { + throw new IllegalArgumentException("作品集主键参数异常!"); + } + User user = UserUtils.getCurrentUserByToken(); + portfolio.setPortfolioAuthorId(user.getIdUser()); portfolio = portfolioService.postPortfolio(portfolio); return GlobalResultGenerator.genSuccessResult(portfolio); } @GetMapping("/{idPortfolio}/unbind-articles") @AuthorshipInterceptor(moduleName = Module.PORTFOLIO) - public GlobalResult unbindArticles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, @RequestParam(defaultValue = "") String searchText,@PathVariable Integer idPortfolio) throws BaseApiException { - Map map = portfolioService.findUnbindArticles(page, rows, searchText, idPortfolio); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult unbindArticles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, @RequestParam(defaultValue = "") String searchText, @PathVariable Long idPortfolio) throws BaseApiException { + if (idPortfolio == null || idPortfolio == 0) { + throw new IllegalArgumentException("作品集主键参数异常!"); + } + User user = UserUtils.getCurrentUserByToken(); + PageInfo pageInfo = portfolioService.findUnbindArticles(page, rows, searchText, idPortfolio, user.getIdUser()); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @PostMapping("/bind-article") @AuthorshipInterceptor(moduleName = Module.PORTFOLIO) - public GlobalResult bindArticle(@RequestBody PortfolioArticleDTO portfolioArticle) { - Map map = portfolioService.bindArticle(portfolioArticle); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult bindArticle(@RequestBody PortfolioArticleDTO portfolioArticle) throws ServiceException { + if (portfolioArticle.getIdPortfolio() == null || portfolioArticle.getIdPortfolio() == 0) { + throw new IllegalArgumentException("作品集主键参数异常!"); + } + boolean flag = portfolioService.bindArticle(portfolioArticle); + return GlobalResultGenerator.genSuccessResult(flag); } @PutMapping("/update-article-sort-no") @AuthorshipInterceptor(moduleName = Module.PORTFOLIO) - public GlobalResult updateArticleSortNo(@RequestBody PortfolioArticleDTO portfolioArticle) { - Map map = portfolioService.updateArticleSortNo(portfolioArticle); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult updateArticleSortNo(@RequestBody PortfolioArticleDTO portfolioArticle) throws ServiceException { + if (portfolioArticle.getIdPortfolio() == null || portfolioArticle.getIdPortfolio() == 0) { + throw new IllegalArgumentException("作品集主键参数异常!"); + } + if (portfolioArticle.getIdArticle() == null || portfolioArticle.getIdArticle() == 0) { + throw new IllegalArgumentException("文章主键参数异常!"); + } + if (portfolioArticle.getSortNo() == null) { + throw new IllegalArgumentException("排序号不能为空!"); + } + boolean flag = portfolioService.updateArticleSortNo(portfolioArticle); + return GlobalResultGenerator.genSuccessResult(flag); } @DeleteMapping("/unbind-article") @AuthorshipInterceptor(moduleName = Module.PORTFOLIO) - public GlobalResult unbindArticle(Integer idArticle,Integer idPortfolio) { - Map map = portfolioService.unbindArticle(idPortfolio,idArticle); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult unbindArticle(Long idArticle, Long idPortfolio) throws ServiceException { + if (idPortfolio == null || idPortfolio == 0) { + throw new IllegalArgumentException("作品集主键参数异常"); + } + if (idArticle == null || idArticle == 0) { + throw new IllegalArgumentException("文章主键参数异常"); + } + boolean flag = portfolioService.unbindArticle(idPortfolio, idArticle); + return GlobalResultGenerator.genSuccessResult(flag); } @DeleteMapping("/delete") @AuthorshipInterceptor(moduleName = Module.PORTFOLIO) - public GlobalResult delete(Integer idPortfolio) throws BaseApiException { - Map map = portfolioService.deletePortfolio(idPortfolio); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult delete(Long idPortfolio) throws BaseApiException { + if (idPortfolio == null || idPortfolio == 0) { + throw new IllegalArgumentException("参数异常!"); + } + User user = UserUtils.getCurrentUserByToken(); + Long idUser = user.getIdUser(); + Integer roleWeights = userService.findRoleWeightsByUser(idUser); + boolean flag = portfolioService.deletePortfolio(idPortfolio, idUser, roleWeights); + return GlobalResultGenerator.genSuccessResult(flag); } } diff --git a/src/main/java/com/rymcu/forest/web/api/product/ProductController.java b/src/main/java/com/rymcu/forest/web/api/product/ProductController.java new file mode 100644 index 0000000..6675a1f --- /dev/null +++ b/src/main/java/com/rymcu/forest/web/api/product/ProductController.java @@ -0,0 +1,23 @@ +package com.rymcu.forest.web.api.product; + +import com.rymcu.forest.service.ProductService; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; + +/** + * Created on 2022/6/21 9:30. + * + * @author ronger + * @email ronger-x@outlook.com + * @packageName com.rymcu.forest.web.api.product + */ +@RestController +@RequestMapping("/api/v1/product") +public class ProductController { + + @Resource + private ProductService productService; + +} diff --git a/src/main/java/com/rymcu/forest/web/api/tag/TagController.java b/src/main/java/com/rymcu/forest/web/api/tag/TagController.java index dda3353..9b4556a 100644 --- a/src/main/java/com/rymcu/forest/web/api/tag/TagController.java +++ b/src/main/java/com/rymcu/forest/web/api/tag/TagController.java @@ -28,12 +28,11 @@ public class TagController { private TagService tagService; @GetMapping("/{name}") - public GlobalResult articles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, @PathVariable String name){ + public GlobalResult> articles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, @PathVariable String name){ PageHelper.startPage(page, rows); List list = articleService.findArticlesByTagName(name); PageInfo pageInfo = new PageInfo(list); - Map map = Utils.getArticlesGlobalResult(pageInfo); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/tags") diff --git a/src/main/java/com/rymcu/forest/web/api/topic/TopicController.java b/src/main/java/com/rymcu/forest/web/api/topic/TopicController.java index 56d55f0..d90d1f9 100644 --- a/src/main/java/com/rymcu/forest/web/api/topic/TopicController.java +++ b/src/main/java/com/rymcu/forest/web/api/topic/TopicController.java @@ -35,11 +35,10 @@ public class TopicController { @GetMapping("/{name}") @VisitLogger - public GlobalResult articles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, @PathVariable String name){ + public GlobalResult> articles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, @PathVariable String name){ PageHelper.startPage(page, rows); List list = articleService.findArticlesByTopicUri(name); PageInfo pageInfo = new PageInfo(list); - Map map = Utils.getArticlesGlobalResult(pageInfo); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } } diff --git a/src/main/java/com/rymcu/forest/web/api/user/UserController.java b/src/main/java/com/rymcu/forest/web/api/user/UserController.java index 9976387..7e7d06f 100644 --- a/src/main/java/com/rymcu/forest/web/api/user/UserController.java +++ b/src/main/java/com/rymcu/forest/web/api/user/UserController.java @@ -45,7 +45,7 @@ public class UserController { } @GetMapping("/{account}/articles") - public GlobalResult userArticles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "12") Integer rows, @PathVariable String account){ + public GlobalResult> userArticles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "12") Integer rows, @PathVariable String account){ UserDTO userDTO = userService.findUserDTOByAccount(account); if (userDTO == null){ return GlobalResultGenerator.genErrorResult("用户不存在!"); @@ -53,12 +53,11 @@ public class UserController { PageHelper.startPage(page, rows); List list = articleService.findUserArticlesByIdUser(userDTO.getIdUser()); PageInfo pageInfo = new PageInfo(list); - Map map = Utils.getArticlesGlobalResult(pageInfo); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/{account}/portfolios") - public GlobalResult userPortfolios(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "12") Integer rows, @PathVariable String account){ + public GlobalResult> userPortfolios(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "12") Integer rows, @PathVariable String account){ UserDTO userDTO = userService.findUserDTOByAccount(account); if (userDTO == null){ return GlobalResultGenerator.genErrorResult("用户不存在!"); @@ -66,15 +65,11 @@ public class UserController { PageHelper.startPage(page, rows); List list = portfolioService.findUserPortfoliosByUser(userDTO); PageInfo pageInfo = new PageInfo(list); - Map map = new HashMap(2); - map.put("portfolios", list); - Map pagination = Utils.getPagination(pageInfo); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/{account}/followers") - public GlobalResult userFollowers(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "12") Integer rows, @PathVariable String account){ + public GlobalResult> userFollowers(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "12") Integer rows, @PathVariable String account){ UserDTO userDTO = userService.findUserDTOByAccount(account); if (userDTO == null){ return GlobalResultGenerator.genErrorResult("用户不存在!"); @@ -82,15 +77,11 @@ public class UserController { PageHelper.startPage(page, rows); List list = followService.findUserFollowersByUser(userDTO); PageInfo pageInfo = new PageInfo(list); - Map map = new HashMap(2); - map.put("users", list); - Map pagination = Utils.getPagination(pageInfo); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/{account}/followings") - public GlobalResult userFollowings(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "12") Integer rows, @PathVariable String account){ + public GlobalResult> userFollowings(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "12") Integer rows, @PathVariable String account){ UserDTO userDTO = userService.findUserDTOByAccount(account); if (userDTO == null){ return GlobalResultGenerator.genErrorResult("用户不存在!"); @@ -98,15 +89,11 @@ public class UserController { PageHelper.startPage(page, rows); List list = followService.findUserFollowingsByUser(userDTO); PageInfo pageInfo = new PageInfo(list); - Map map = new HashMap(2); - map.put("users", list); - Map pagination = Utils.getPagination(pageInfo); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/{account}/user-extend") - public GlobalResult userExtend(@PathVariable String account) { + public GlobalResult userExtend(@PathVariable String account) { UserExtend userExtend = userService.selectUserExtendByAccount(account); return GlobalResultGenerator.genSuccessResult(userExtend); } diff --git a/src/main/java/com/rymcu/forest/web/api/user/UserInfoController.java b/src/main/java/com/rymcu/forest/web/api/user/UserInfoController.java index 94e8746..46db78f 100644 --- a/src/main/java/com/rymcu/forest/web/api/user/UserInfoController.java +++ b/src/main/java/com/rymcu/forest/web/api/user/UserInfoController.java @@ -2,6 +2,7 @@ package com.rymcu.forest.web.api.user; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; +import com.rymcu.forest.core.exception.ServiceException; import com.rymcu.forest.core.result.GlobalResult; import com.rymcu.forest.core.result.GlobalResultGenerator; import com.rymcu.forest.core.service.security.annotation.SecurityInterceptor; @@ -34,57 +35,59 @@ public class UserInfoController { @GetMapping("/detail/{idUser}") @SecurityInterceptor - public GlobalResult detail(@PathVariable Integer idUser) { - Map map = userService.findUserInfo(idUser); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult detail(@PathVariable Long idUser) { + UserInfoDTO userInfo = userService.findUserInfo(idUser); + return GlobalResultGenerator.genSuccessResult(userInfo); + } + @GetMapping("/detail/{idUser}/extend-info") + @SecurityInterceptor + public GlobalResult extendInfo(@PathVariable Long idUser) { + UserExtend userExtend = userService.findUserExtendInfo(idUser); + return GlobalResultGenerator.genSuccessResult(userExtend); } @GetMapping("/check-nickname") @SecurityInterceptor - public GlobalResult checkNickname(@RequestParam Integer idUser, @RequestParam String nickname) { - Map map = userService.checkNickname(idUser, nickname); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult checkNickname(@RequestParam Long idUser, @RequestParam String nickname) { + boolean flag = userService.checkNicknameByIdUser(idUser, nickname); + return GlobalResultGenerator.genSuccessResult(flag); } @PatchMapping("/update") @SecurityInterceptor - public GlobalResult updateUserInfo(@RequestBody UserInfoDTO user) { - Map map = userService.updateUserInfo(user); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult updateUserInfo(@RequestBody UserInfoDTO user) throws ServiceException { + user = userService.updateUserInfo(user); + return GlobalResultGenerator.genSuccessResult(user); } @PatchMapping("/update-extend") @SecurityInterceptor - public GlobalResult updateUserExtend(@RequestBody UserExtend userExtend) { - Map map = userService.updateUserExtend(userExtend); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult updateUserExtend(@RequestBody UserExtend userExtend) throws ServiceException { + userExtend = userService.updateUserExtend(userExtend); + return GlobalResultGenerator.genSuccessResult(userExtend); } @PatchMapping("/update-email") @SecurityInterceptor - public GlobalResult updateEmail(@RequestBody ChangeEmailDTO changeEmailDTO) { - Map map = userService.updateEmail(changeEmailDTO); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult updateEmail(@RequestBody ChangeEmailDTO changeEmailDTO) throws ServiceException { + boolean flag = userService.updateEmail(changeEmailDTO); + return GlobalResultGenerator.genSuccessResult(flag); } @PatchMapping("/update-password") @SecurityInterceptor - public GlobalResult updatePassword(@RequestBody UpdatePasswordDTO updatePasswordDTO) { - Map map = userService.updatePassword(updatePasswordDTO); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult updatePassword(@RequestBody UpdatePasswordDTO updatePasswordDTO) { + boolean flag = userService.updatePassword(updatePasswordDTO); + return GlobalResultGenerator.genSuccessResult(flag); } @GetMapping("/login-records") @SecurityInterceptor - public GlobalResult loginRecords(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, @RequestParam Integer idUser) { + public GlobalResult> loginRecords(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, @RequestParam Integer idUser) { PageHelper.startPage(page, rows); List list = loginRecordService.findLoginRecordByIdUser(idUser); PageInfo pageInfo = new PageInfo<>(list); - Map map = new HashMap(2); - map.put("records", pageInfo.getList()); - Map pagination = Utils.getPagination(pageInfo); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } } diff --git a/src/main/java/com/rymcu/forest/wx/miniapp/config/WxMaConfiguration.java b/src/main/java/com/rymcu/forest/wx/miniapp/config/WxMaConfiguration.java deleted file mode 100644 index 2c4ddd0..0000000 --- a/src/main/java/com/rymcu/forest/wx/miniapp/config/WxMaConfiguration.java +++ /dev/null @@ -1,149 +0,0 @@ -package com.rymcu.forest.wx.miniapp.config; - -import cn.binarywang.wx.miniapp.api.WxMaService; -import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl; -import cn.binarywang.wx.miniapp.bean.WxMaKefuMessage; -import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage; -import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl; -import cn.binarywang.wx.miniapp.message.WxMaMessageHandler; -import cn.binarywang.wx.miniapp.message.WxMaMessageRouter; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import lombok.extern.slf4j.Slf4j; -import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; -import me.chanjar.weixin.common.error.WxErrorException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -import javax.annotation.PostConstruct; -import java.io.File; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * @author Binary Wang - */ -@Slf4j -@Configuration -@EnableConfigurationProperties(WxMaProperties.class) -public class WxMaConfiguration { - private final WxMaProperties properties; - - private static final Map routers = Maps.newHashMap(); - private static Map maServices; - - @Autowired - public WxMaConfiguration(WxMaProperties properties) { - this.properties = properties; - } - - public static WxMaService getMaService(String appid) { - WxMaService wxService = maServices.get(appid); - if (wxService == null) { - throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appid)); - } - - return wxService; - } - - public static WxMaMessageRouter getRouter(String appid) { - return routers.get(appid); - } - - @PostConstruct - public void init() { - List configs = this.properties.getConfigs(); - if (configs == null) { - throw new RuntimeException("大哥,拜托先看下项目首页的说明(readme文件),添加下相关配置,注意别配错了!"); - } - - maServices = configs.stream() - .map(a -> { - WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl(); -// WxMaDefaultConfigImpl config = new WxMaRedisConfigImpl(new JedisPool()); - // 使用上面的配置时,需要同时引入jedis-lock的依赖,否则会报类无法找到的异常 - config.setAppid(a.getAppId()); - config.setSecret(a.getSecret()); - config.setToken(a.getToken()); - config.setAesKey(a.getAesKey()); - config.setMsgDataFormat(a.getMsgDataFormat()); - - WxMaService service = new WxMaServiceImpl(); - service.setWxMaConfig(config); - routers.put(a.getAppId(), this.newRouter(service)); - return service; - }).collect(Collectors.toMap(s -> s.getWxMaConfig().getAppid(), a -> a)); - } - - private WxMaMessageRouter newRouter(WxMaService service) { - final WxMaMessageRouter router = new WxMaMessageRouter(service); - router - .rule().handler(logHandler).next() - .rule().async(false).content("订阅消息").handler(subscribeMsgHandler).end() - .rule().async(false).content("文本").handler(textHandler).end() - .rule().async(false).content("图片").handler(picHandler).end() - .rule().async(false).content("二维码").handler(qrcodeHandler).end(); - return router; - } - - private final WxMaMessageHandler subscribeMsgHandler = (wxMessage, context, service, sessionManager) -> { - service.getMsgService().sendSubscribeMsg(WxMaSubscribeMessage.builder() - .templateId("此处更换为自己的模板id") - .data(Lists.newArrayList( - new WxMaSubscribeMessage.MsgData("keyword1", "339208499"))) - .toUser(wxMessage.getFromUser()) - .build()); - return null; - }; - - private final WxMaMessageHandler logHandler = (wxMessage, context, service, sessionManager) -> { - log.info("收到消息:" + wxMessage.toString()); - service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("收到信息为:" + wxMessage.toJson()) - .toUser(wxMessage.getFromUser()).build()); - return null; - }; - - private final WxMaMessageHandler textHandler = (wxMessage, context, service, sessionManager) -> { - service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("回复文本消息") - .toUser(wxMessage.getFromUser()).build()); - return null; - }; - - private final WxMaMessageHandler picHandler = (wxMessage, context, service, sessionManager) -> { - try { - WxMediaUploadResult uploadResult = service.getMediaService() - .uploadMedia("image", "png", - ClassLoader.getSystemResourceAsStream("tmp.png")); - service.getMsgService().sendKefuMsg( - WxMaKefuMessage - .newImageBuilder() - .mediaId(uploadResult.getMediaId()) - .toUser(wxMessage.getFromUser()) - .build()); - } catch (WxErrorException e) { - e.printStackTrace(); - } - - return null; - }; - - private final WxMaMessageHandler qrcodeHandler = (wxMessage, context, service, sessionManager) -> { - try { - final File file = service.getQrcodeService().createQrcode("123", 430); - WxMediaUploadResult uploadResult = service.getMediaService().uploadMedia("image", file); - service.getMsgService().sendKefuMsg( - WxMaKefuMessage - .newImageBuilder() - .mediaId(uploadResult.getMediaId()) - .toUser(wxMessage.getFromUser()) - .build()); - } catch (WxErrorException e) { - e.printStackTrace(); - } - - return null; - }; - -} diff --git a/src/main/java/com/rymcu/forest/wx/miniapp/config/WxMaProperties.java b/src/main/java/com/rymcu/forest/wx/miniapp/config/WxMaProperties.java deleted file mode 100644 index f91fbff..0000000 --- a/src/main/java/com/rymcu/forest/wx/miniapp/config/WxMaProperties.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.rymcu.forest.wx.miniapp.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; - -import java.util.List; - -/** - * @author Binary Wang - */ -@Data -@ConfigurationProperties(prefix = "wx.miniapp") -public class WxMaProperties { - - private List configs; - - @Data - public static class Config { - /** - * 设置微信小程序的appid - */ - private String appId; - - /** - * 设置微信小程序的Secret - */ - private String secret; - - /** - * 设置微信小程序消息服务器配置的token - */ - private String token; - - /** - * 设置微信小程序消息服务器配置的EncodingAESKey - */ - private String aesKey; - - /** - * 消息格式,XML或者JSON - */ - private String msgDataFormat; - } - -} diff --git a/src/main/java/com/rymcu/forest/wx/miniapp/controller/WxMaMediaController.java b/src/main/java/com/rymcu/forest/wx/miniapp/controller/WxMaMediaController.java deleted file mode 100644 index 3fae69c..0000000 --- a/src/main/java/com/rymcu/forest/wx/miniapp/controller/WxMaMediaController.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.rymcu.forest.wx.miniapp.controller; - -import cn.binarywang.wx.miniapp.api.WxMaService; -import cn.binarywang.wx.miniapp.constant.WxMaConstants; -import com.google.common.collect.Lists; -import com.google.common.io.Files; -import com.rymcu.forest.wx.miniapp.config.WxMaConfiguration; -import me.chanjar.weixin.common.bean.result.WxMediaUploadResult; -import me.chanjar.weixin.common.error.WxErrorException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; -import org.springframework.web.multipart.MultipartHttpServletRequest; -import org.springframework.web.multipart.commons.CommonsMultipartResolver; - -import javax.servlet.http.HttpServletRequest; -import java.io.File; -import java.io.IOException; -import java.util.Iterator; -import java.util.List; - -/** - *
- *  小程序临时素材接口
- *  Created by BinaryWang on 2017/6/16.
- * 
- * - * @author Binary Wang - */ -@RestController -@RequestMapping("/wx/media/{appId}") -public class WxMaMediaController { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - /** - * 上传临时素材 - * - * @return 素材的media_id列表,实际上如果有的话,只会有一个 - */ - @PostMapping("/upload") - public List uploadMedia(@PathVariable String appId, HttpServletRequest request) throws WxErrorException { - final WxMaService wxService = WxMaConfiguration.getMaService(appId); - - CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext()); - - if (!resolver.isMultipart(request)) { - return Lists.newArrayList(); - } - - MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; - Iterator it = multiRequest.getFileNames(); - List result = Lists.newArrayList(); - while (it.hasNext()) { - try { - MultipartFile file = multiRequest.getFile(it.next()); - File newFile = new File(Files.createTempDir(), file.getOriginalFilename()); - this.logger.info("filePath is :" + newFile.toString()); - file.transferTo(newFile); - WxMediaUploadResult uploadResult = wxService.getMediaService().uploadMedia(WxMaConstants.KefuMsgType.IMAGE, newFile); - this.logger.info("media_id : " + uploadResult.getMediaId()); - result.add(uploadResult.getMediaId()); - } catch (IOException e) { - this.logger.error(e.getMessage(), e); - } - } - - return result; - } - - /** - * 下载临时素材 - */ - @GetMapping("/download/{mediaId}") - public File getMedia(@PathVariable String appId, @PathVariable String mediaId) throws WxErrorException { - final WxMaService wxService = WxMaConfiguration.getMaService(appId); - - return wxService.getMediaService().getMedia(mediaId); - } -} diff --git a/src/main/java/com/rymcu/forest/wx/miniapp/controller/WxMaUserController.java b/src/main/java/com/rymcu/forest/wx/miniapp/controller/WxMaUserController.java deleted file mode 100644 index e628940..0000000 --- a/src/main/java/com/rymcu/forest/wx/miniapp/controller/WxMaUserController.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.rymcu.forest.wx.miniapp.controller; - -import cn.binarywang.wx.miniapp.api.WxMaService; -import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult; -import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo; -import cn.binarywang.wx.miniapp.bean.WxMaUserInfo; -import com.rymcu.forest.wx.miniapp.config.WxMaConfiguration; -import com.rymcu.forest.wx.miniapp.utils.JsonUtils; -import me.chanjar.weixin.common.error.WxErrorException; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -/** - * 微信小程序用户接口 - * - * @author Binary Wang - */ -@RestController -@RequestMapping("/wx/user/{appId}") -public class WxMaUserController { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - /** - * 登陆接口 - */ - @GetMapping("/login") - public String login(@PathVariable String appId, String code) { - if (StringUtils.isBlank(code)) { - return "empty jscode"; - } - - final WxMaService wxService = WxMaConfiguration.getMaService(appId); - - try { - WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code); - this.logger.info(session.getSessionKey()); - this.logger.info(session.getOpenid()); - //TODO 可以增加自己的逻辑,关联业务相关数据 - return JsonUtils.toJson(session); - } catch (WxErrorException e) { - this.logger.error(e.getMessage(), e); - return e.toString(); - } - } - - /** - *
-     * 获取用户信息接口
-     * 
- */ - @GetMapping("/info") - public String info(@PathVariable String appId, String sessionKey, - String signature, String rawData, String encryptedData, String iv) { - final WxMaService wxService = WxMaConfiguration.getMaService(appId); - - // 用户信息校验 - if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) { - return "user check failed"; - } - - // 解密用户信息 - WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv); - - return JsonUtils.toJson(userInfo); - } - - /** - *
-     * 获取用户绑定手机号信息
-     * 
- */ - @GetMapping("/phone") - public String phone(@PathVariable String appId, String sessionKey, String signature, - String rawData, String encryptedData, String iv) { - final WxMaService wxService = WxMaConfiguration.getMaService(appId); - - // 用户信息校验 - if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) { - return "user check failed"; - } - - // 解密 - WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv); - - return JsonUtils.toJson(phoneNoInfo); - } - -} diff --git a/src/main/java/com/rymcu/forest/wx/miniapp/utils/JsonUtils.java b/src/main/java/com/rymcu/forest/wx/miniapp/utils/JsonUtils.java deleted file mode 100644 index 3687ab9..0000000 --- a/src/main/java/com/rymcu/forest/wx/miniapp/utils/JsonUtils.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.rymcu.forest.wx.miniapp.utils; - -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; - -/** - * @author Binary Wang - */ -public class JsonUtils { - private static final ObjectMapper JSON = new ObjectMapper(); - - static { - JSON.setSerializationInclusion(Include.NON_NULL); - JSON.configure(SerializationFeature.INDENT_OUTPUT, Boolean.TRUE); - } - - public static String toJson(Object obj) { - try { - return JSON.writeValueAsString(obj); - } catch (JsonProcessingException e) { - e.printStackTrace(); - } - - return null; - } -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/builder/AbstractBuilder.java b/src/main/java/com/rymcu/forest/wx/mp/builder/AbstractBuilder.java deleted file mode 100644 index 0a0dc86..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/builder/AbstractBuilder.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.rymcu.forest.wx.mp.builder; - -import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; -import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Binary Wang(https://github.com/binarywang) - */ -public abstract class AbstractBuilder { - protected final Logger logger = LoggerFactory.getLogger(getClass()); - - public abstract WxMpXmlOutMessage build(String content, - WxMpXmlMessage wxMessage, WxMpService service); -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/builder/ImageBuilder.java b/src/main/java/com/rymcu/forest/wx/mp/builder/ImageBuilder.java deleted file mode 100644 index 7c12ec2..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/builder/ImageBuilder.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.rymcu.forest.wx.mp.builder; - -import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; -import me.chanjar.weixin.mp.bean.message.WxMpXmlOutImageMessage; -import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; - -/** - * @author Binary Wang(https://github.com/binarywang) - */ -public class ImageBuilder extends AbstractBuilder { - - @Override - public WxMpXmlOutMessage build(String content, WxMpXmlMessage wxMessage, - WxMpService service) { - - WxMpXmlOutImageMessage m = WxMpXmlOutMessage.IMAGE().mediaId(content) - .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()) - .build(); - - return m; - } - -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/builder/TextBuilder.java b/src/main/java/com/rymcu/forest/wx/mp/builder/TextBuilder.java deleted file mode 100644 index 097d402..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/builder/TextBuilder.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.rymcu.forest.wx.mp.builder; - -import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; -import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; -import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage; - -/** - * @author Binary Wang(https://github.com/binarywang) - */ -public class TextBuilder extends AbstractBuilder { - - @Override - public WxMpXmlOutMessage build(String content, WxMpXmlMessage wxMessage, - WxMpService service) { - WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT().content(content) - .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()) - .build(); - return m; - } - -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/config/WxMpConfiguration.java b/src/main/java/com/rymcu/forest/wx/mp/config/WxMpConfiguration.java deleted file mode 100644 index 694b0f2..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/config/WxMpConfiguration.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.rymcu.forest.wx.mp.config; - -import com.rymcu.forest.wx.mp.handler.*; -import lombok.AllArgsConstructor; -import me.chanjar.weixin.mp.api.WxMpMessageRouter; -import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl; -import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import java.util.List; -import java.util.stream.Collectors; - -import static me.chanjar.weixin.common.api.WxConsts.EventType; -import static me.chanjar.weixin.common.api.WxConsts.EventType.SUBSCRIBE; -import static me.chanjar.weixin.common.api.WxConsts.EventType.UNSUBSCRIBE; -import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType; -import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType.EVENT; -import static me.chanjar.weixin.mp.constant.WxMpEventConstants.CustomerService.*; -import static me.chanjar.weixin.mp.constant.WxMpEventConstants.POI_CHECK_NOTIFY; - -/** - * wechat mp configuration - * - * @author Binary Wang(https://github.com/binarywang) - */ -@AllArgsConstructor -@Configuration -@EnableConfigurationProperties(WxMpProperties.class) -public class WxMpConfiguration { - private final LogHandler logHandler; - private final NullHandler nullHandler; - private final KfSessionHandler kfSessionHandler; - private final StoreCheckNotifyHandler storeCheckNotifyHandler; - private final LocationHandler locationHandler; - private final MenuHandler menuHandler; - private final MsgHandler msgHandler; - private final UnsubscribeHandler unsubscribeHandler; - private final SubscribeHandler subscribeHandler; - private final ScanHandler scanHandler; - private final WxMpProperties properties; - - @Bean - public WxMpService wxMpService() { - // 代码里 getConfigs()处报错的同学,请注意仔细阅读项目说明,你的IDE需要引入lombok插件!!!! - final List configs = this.properties.getConfigs(); - if (configs == null) { - throw new RuntimeException("大哥,拜托先看下项目首页的说明(readme文件),添加下相关配置,注意别配错了!"); - } - - WxMpService service = new WxMpServiceImpl(); - service.setMultiConfigStorages(configs - .stream().map(a -> { - WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl(); - configStorage.setAppId(a.getAppId()); - configStorage.setSecret(a.getSecret()); - configStorage.setToken(a.getToken()); - configStorage.setAesKey(a.getAesKey()); - return configStorage; - }).collect(Collectors.toMap(WxMpDefaultConfigImpl::getAppId, a -> a, (o, n) -> o))); - return service; - } - - @Bean - public WxMpMessageRouter messageRouter(WxMpService wxMpService) { - final WxMpMessageRouter newRouter = new WxMpMessageRouter(wxMpService); - - // 记录所有事件的日志 (异步执行) - newRouter.rule().handler(this.logHandler).next(); - - // 接收客服会话管理事件 - newRouter.rule().async(false).msgType(EVENT).event(KF_CREATE_SESSION) - .handler(this.kfSessionHandler).end(); - newRouter.rule().async(false).msgType(EVENT).event(KF_CLOSE_SESSION) - .handler(this.kfSessionHandler).end(); - newRouter.rule().async(false).msgType(EVENT).event(KF_SWITCH_SESSION) - .handler(this.kfSessionHandler).end(); - - // 门店审核事件 - newRouter.rule().async(false).msgType(EVENT).event(POI_CHECK_NOTIFY).handler(this.storeCheckNotifyHandler).end(); - - // 自定义菜单事件 - newRouter.rule().async(false).msgType(EVENT).event(EventType.CLICK).handler(this.menuHandler).end(); - - // 点击菜单连接事件 - newRouter.rule().async(false).msgType(EVENT).event(EventType.VIEW).handler(this.nullHandler).end(); - - // 关注事件 - newRouter.rule().async(false).msgType(EVENT).event(SUBSCRIBE).handler(this.subscribeHandler).end(); - - // 取消关注事件 - newRouter.rule().async(false).msgType(EVENT).event(UNSUBSCRIBE).handler(this.unsubscribeHandler).end(); - - // 上报地理位置事件 - newRouter.rule().async(false).msgType(EVENT).event(EventType.LOCATION).handler(this.locationHandler).end(); - - // 接收地理位置消息 - newRouter.rule().async(false).msgType(XmlMsgType.LOCATION).handler(this.locationHandler).end(); - - // 扫码事件 - newRouter.rule().async(false).msgType(EVENT).event(EventType.SCAN).handler(this.scanHandler).end(); - - // 默认 - newRouter.rule().async(false).handler(this.msgHandler).end(); - - return newRouter; - } - -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/config/WxMpProperties.java b/src/main/java/com/rymcu/forest/wx/mp/config/WxMpProperties.java deleted file mode 100644 index 234e0c6..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/config/WxMpProperties.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.rymcu.forest.wx.mp.config; - -import com.rymcu.forest.wx.mp.utils.JsonUtils; -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; - -import java.util.List; - -/** - * wechat mp properties - * - * @author Binary Wang(https://github.com/binarywang) - */ -@Data -@ConfigurationProperties(prefix = "wx.mp") -public class WxMpProperties { - private List configs; - - @Data - public static class MpConfig { - /** - * 设置微信公众号的appid - */ - private String appId; - - /** - * 设置微信公众号的app secret - */ - private String secret; - - /** - * 设置微信公众号的token - */ - private String token; - - /** - * 设置微信公众号的EncodingAESKey - */ - private String aesKey; - } - - @Override - public String toString() { - return JsonUtils.toJson(this); - } -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/controller/WxMenuController.java b/src/main/java/com/rymcu/forest/wx/mp/controller/WxMenuController.java deleted file mode 100644 index 1a0e8ad..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/controller/WxMenuController.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.rymcu.forest.wx.mp.controller; - -import com.rymcu.forest.wx.mp.service.WxMenuService; -import lombok.AllArgsConstructor; -import me.chanjar.weixin.common.bean.menu.WxMenu; -import me.chanjar.weixin.common.bean.menu.WxMenuButton; -import me.chanjar.weixin.common.error.WxErrorException; -import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.bean.menu.WxMpGetSelfMenuInfoResult; -import me.chanjar.weixin.mp.bean.menu.WxMpMenu; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -import javax.annotation.Resource; -import java.io.IOException; -import java.net.MalformedURLException; - -import static me.chanjar.weixin.common.api.WxConsts.MenuButtonType; - -/** - * @author Binary Wang(https://github.com/binarywang) - */ -@AllArgsConstructor -@RestController -@RequestMapping("/wx/menu/{appId}") -public class WxMenuController { - private final WxMpService wxService; - @Resource - private WxMenuService wxMenuService; - /** - *
-     * 自定义菜单创建接口
-     * 详情请见:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141013&token=&lang=zh_CN
-     * 如果要创建个性化菜单,请设置matchrule属性
-     * 详情请见:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1455782296&token=&lang=zh_CN
-     * 
- * - * @return 如果是个性化菜单,则返回menuid,否则返回null - */ - @PostMapping("/create") - public String menuCreate(@PathVariable String appId, @RequestBody WxMenu menu) throws WxErrorException { - return this.wxService.switchoverTo(appId).getMenuService().menuCreate(menu); - } - - @GetMapping("/create") - public String menuCreateSample(@PathVariable String appId) throws WxErrorException, IOException { - this.wxService.switchover(appId); - return this.wxService.getMenuService().menuCreate(wxMenuService.getMenus()); - } - - /** - *
-     * 自定义菜单创建接口
-     * 详情请见: https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141013&token=&lang=zh_CN
-     * 如果要创建个性化菜单,请设置matchrule属性
-     * 详情请见:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1455782296&token=&lang=zh_CN
-     * 
- * - * @return 如果是个性化菜单,则返回menuid,否则返回null - */ - @PostMapping("/createByJson") - public String menuCreate(@PathVariable String appId, @RequestBody String json) throws WxErrorException { - return this.wxService.switchoverTo(appId).getMenuService().menuCreate(json); - } - - /** - *
-     * 自定义菜单删除接口
-     * 详情请见: https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141015&token=&lang=zh_CN
-     * 
- */ - @GetMapping("/delete") - public void menuDelete(@PathVariable String appId) throws WxErrorException { - this.wxService.switchoverTo(appId).getMenuService().menuDelete(); - } - - /** - *
-     * 删除个性化菜单接口
-     * 详情请见: https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1455782296&token=&lang=zh_CN
-     * 
- * - * @param menuId 个性化菜单的menuid - */ - @GetMapping("/delete/{menuId}") - public void menuDelete(@PathVariable String appId, @PathVariable String menuId) throws WxErrorException { - this.wxService.switchoverTo(appId).getMenuService().menuDelete(menuId); - } - - /** - *
-     * 自定义菜单查询接口
-     * 详情请见: https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141014&token=&lang=zh_CN
-     * 
- */ - @GetMapping("/get") - public WxMpMenu menuGet(@PathVariable String appId) throws WxErrorException { - return this.wxService.switchoverTo(appId).getMenuService().menuGet(); - } - - /** - *
-     * 测试个性化菜单匹配结果
-     * 详情请见: http://mp.weixin.qq.com/wiki/0/c48ccd12b69ae023159b4bfaa7c39c20.html
-     * 
- * - * @param userid 可以是粉丝的OpenID,也可以是粉丝的微信号。 - */ - @GetMapping("/menuTryMatch/{userid}") - public WxMenu menuTryMatch(@PathVariable String appId, @PathVariable String userid) throws WxErrorException { - return this.wxService.switchoverTo(appId).getMenuService().menuTryMatch(userid); - } - - /** - *
-     * 获取自定义菜单配置接口
-     * 本接口将会提供公众号当前使用的自定义菜单的配置,如果公众号是通过API调用设置的菜单,则返回菜单的开发配置,而如果公众号是在公众平台官网通过网站功能发布菜单,则本接口返回运营者设置的菜单配置。
-     * 请注意:
-     * 1、第三方平台开发者可以通过本接口,在旗下公众号将业务授权给你后,立即通过本接口检测公众号的自定义菜单配置,并通过接口再次给公众号设置好自动回复规则,以提升公众号运营者的业务体验。
-     * 2、本接口与自定义菜单查询接口的不同之处在于,本接口无论公众号的接口是如何设置的,都能查询到接口,而自定义菜单查询接口则仅能查询到使用API设置的菜单配置。
-     * 3、认证/未认证的服务号/订阅号,以及接口测试号,均拥有该接口权限。
-     * 4、从第三方平台的公众号登录授权机制上来说,该接口从属于消息与菜单权限集。
-     * 5、本接口中返回的图片/语音/视频为临时素材(临时素材每次获取都不同,3天内有效,通过素材管理-获取临时素材接口来获取这些素材),本接口返回的图文消息为永久素材素材(通过素材管理-获取永久素材接口来获取这些素材)。
-     *  接口调用请求说明:
-     * http请求方式: GET(请使用https协议)
-     * https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=ACCESS_TOKEN
-     * 
- */ - @GetMapping("/getSelfMenuInfo") - public WxMpGetSelfMenuInfoResult getSelfMenuInfo(@PathVariable String appId) throws WxErrorException { - return this.wxService.switchoverTo(appId).getMenuService().getSelfMenuInfo(); - } -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/controller/WxPortalController.java b/src/main/java/com/rymcu/forest/wx/mp/controller/WxPortalController.java deleted file mode 100644 index c3fc4ae..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/controller/WxPortalController.java +++ /dev/null @@ -1,112 +0,0 @@ -package com.rymcu.forest.wx.mp.controller; - -import lombok.AllArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import me.chanjar.weixin.mp.api.WxMpMessageRouter; -import org.apache.commons.lang3.StringUtils; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; -import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; - -/** - * @author Binary Wang(https://github.com/binarywang) - */ -@Slf4j -@AllArgsConstructor -@RestController -@RequestMapping("/wx/portal/{appId}") -public class WxPortalController { - private final WxMpService wxService; - private final WxMpMessageRouter messageRouter; - - @GetMapping(produces = "text/plain;charset=utf-8") - public String authGet(@PathVariable String appId, - @RequestParam(name = "signature", required = false) String signature, - @RequestParam(name = "timestamp", required = false) String timestamp, - @RequestParam(name = "nonce", required = false) String nonce, - @RequestParam(name = "echostr", required = false) String echostr) { - - log.info("\n接收到来自微信服务器的认证消息:[{}, {}, {}, {}]", signature, - timestamp, nonce, echostr); - if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) { - throw new IllegalArgumentException("请求参数非法,请核实!"); - } - - if (!this.wxService.switchover(appId)) { - throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appId)); - } - - if (wxService.checkSignature(timestamp, nonce, signature)) { - return echostr; - } - - return "非法请求"; - } - - @PostMapping(produces = "application/xml; charset=UTF-8") - public String post(@PathVariable String appId, - @RequestBody String requestBody, - @RequestParam("signature") String signature, - @RequestParam("timestamp") String timestamp, - @RequestParam("nonce") String nonce, - @RequestParam("openid") String openid, - @RequestParam(name = "encrypt_type", required = false) String encType, - @RequestParam(name = "msg_signature", required = false) String msgSignature) { - log.info("\n接收微信请求:[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}]," - + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ", - openid, signature, encType, msgSignature, timestamp, nonce, requestBody); - - if (!this.wxService.switchover(appId)) { - throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appId)); - } - - if (!wxService.checkSignature(timestamp, nonce, signature)) { - throw new IllegalArgumentException("非法请求,可能属于伪造的请求!"); - } - - String out = null; - if (encType == null) { - // 明文传输的消息 - WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody); - WxMpXmlOutMessage outMessage = this.route(inMessage); - if (outMessage == null) { - return ""; - } - - out = outMessage.toXml(); - } else if ("aes".equalsIgnoreCase(encType)) { - // aes加密的消息 - WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxService.getWxMpConfigStorage(), - timestamp, nonce, msgSignature); - log.debug("\n消息解密后内容为:\n{} ", inMessage.toString()); - WxMpXmlOutMessage outMessage = this.route(inMessage); - if (outMessage == null) { - return ""; - } - - out = outMessage.toEncryptedXml(wxService.getWxMpConfigStorage()); - } - - log.debug("\n组装回复信息:{}", out); - return out; - } - - private WxMpXmlOutMessage route(WxMpXmlMessage message) { - try { - return this.messageRouter.route(message); - } catch (Exception e) { - log.error("路由消息时出现异常!", e); - } - - return null; - } - -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/controller/WxRedirectController.java b/src/main/java/com/rymcu/forest/wx/mp/controller/WxRedirectController.java deleted file mode 100644 index 2e0364c..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/controller/WxRedirectController.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.rymcu.forest.wx.mp.controller; - -import lombok.AllArgsConstructor; -import me.chanjar.weixin.common.bean.WxOAuth2UserInfo; -import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken; -import me.chanjar.weixin.common.error.WxErrorException; -import me.chanjar.weixin.mp.api.WxMpService; -import org.springframework.stereotype.Controller; -import org.springframework.ui.ModelMap; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; - -/** - * @author Edward - */ -@AllArgsConstructor -@Controller -@RequestMapping("/wx/redirect/{appId}") -public class WxRedirectController { - private final WxMpService wxService; - - @RequestMapping("/greet") - public String greetUser(@PathVariable String appId, @RequestParam String code, ModelMap map) { - if (!this.wxService.switchover(appId)) { - throw new IllegalArgumentException(String.format("未找到对应appId=[%s]的配置,请核实!", appId)); - } - - try { - WxOAuth2AccessToken accessToken = wxService.getOAuth2Service().getAccessToken(code); - WxOAuth2UserInfo user = wxService.getOAuth2Service().getUserInfo(accessToken, null); - map.put("user", user); - } catch (WxErrorException e) { - e.printStackTrace(); - } - - return "greet_user"; - } -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/controller/WxoAuthController.java b/src/main/java/com/rymcu/forest/wx/mp/controller/WxoAuthController.java deleted file mode 100644 index 8638bf5..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/controller/WxoAuthController.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.rymcu.forest.wx.mp.controller; - -import com.rymcu.forest.service.WxUserService; -import com.rymcu.forest.util.ContextHolderUtils; -import me.chanjar.weixin.common.api.WxConsts; -import me.chanjar.weixin.common.bean.WxJsapiSignature; -import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken; -import me.chanjar.weixin.common.error.WxErrorException; -import me.chanjar.weixin.common.util.http.URIUtil; -import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.bean.result.WxMpUser; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.*; - -import javax.annotation.Resource; - -/** - * @author ronger - */ -@Controller -@RequestMapping("/wx/oauth/{appId}") -public class WxoAuthController { - - @Resource - private WxMpService wxMpService; - @Resource - private WxUserService wxUserService; - - @Value("${resource.domain}") - private String domain; - - @Value("${server.servlet.context-path}") - private String contextPath; - - @GetMapping - public String wxAuth(@PathVariable String appId, @RequestParam(name = "redirectUrl") String redirectUrl) { - StringBuilder baseUrl; - wxMpService.switchoverTo(appId); - // 测试号 - if ("wxa49093339a5a822b".equals(appId)) { - baseUrl = new StringBuilder("http://1wx.rymcu.com").append(contextPath); - } else { - baseUrl = new StringBuilder(domain).append(contextPath); - } - StringBuilder accessTokenUrl = baseUrl.append("/wx/oauth/" + appId + "/getAccessToken?redirectUrl=").append(URIUtil.encodeURIComponent(redirectUrl)); - String oauth2Url = wxMpService.getOAuth2Service().buildAuthorizationUrl(accessTokenUrl.toString(), WxConsts.OAuth2Scope.SNSAPI_USERINFO, null); - - return "redirect:" + oauth2Url; - } - - @GetMapping("getAccessToken") - public String getAccessToken(@PathVariable String appId, @RequestParam(name = "code") String code, @RequestParam(name = "redirectUrl") String redirectUrl) throws Exception { - wxMpService.switchoverTo(appId); - WxOAuth2AccessToken oAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code); - boolean valid = wxMpService.getOAuth2Service().validateAccessToken(oAuth2AccessToken); - if (!valid) { - throw new Exception("无权限"); - } - - WxMpUser wxMpUser = wxMpService.getUserService().userInfo(oAuth2AccessToken.getOpenId()); - wxUserService.saveUser(wxMpUser, appId); - ContextHolderUtils.getSession2().setAttribute("wxUser", wxMpUser); - return "redirect:" + redirectUrl; - } - - @GetMapping("validJs") - @ResponseBody - public WxJsapiSignature validJs(String url) throws WxErrorException { - return wxMpService.createJsapiSignature(url); - } - - @GetMapping("t") - public String reOauth() { - return "wx/oauth"; - } -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/error/ErrorController.java b/src/main/java/com/rymcu/forest/wx/mp/error/ErrorController.java deleted file mode 100644 index e345a88..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/error/ErrorController.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.rymcu.forest.wx.mp.error; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; - -/** - *
- * 出错页面控制器
- * Created by Binary Wang on 2018/8/25.
- * 
- * - * @author Binary Wang - */ -@Controller -@RequestMapping("/error") -public class ErrorController { - - @GetMapping(value = "/404") - public String error404() { - return "error"; - } - - @GetMapping(value = "/500") - public String error500() { - return "error"; - } - -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/error/ErrorPageConfiguration.java b/src/main/java/com/rymcu/forest/wx/mp/error/ErrorPageConfiguration.java deleted file mode 100644 index 39dec24..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/error/ErrorPageConfiguration.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.rymcu.forest.wx.mp.error; - -import org.springframework.boot.web.server.ErrorPage; -import org.springframework.boot.web.server.ErrorPageRegistrar; -import org.springframework.boot.web.server.ErrorPageRegistry; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Component; - -/** - *
- * 配置错误状态与对应访问路径
- * Created by Binary Wang on 2018/8/25.
- * 
- * - * @author Binary Wang - */ -@Component -public class ErrorPageConfiguration implements ErrorPageRegistrar { - @Override - public void registerErrorPages(ErrorPageRegistry errorPageRegistry) { - errorPageRegistry.addErrorPages( - new ErrorPage(HttpStatus.NOT_FOUND, "/error/404"), - new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500") - ); - } - -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/handler/AbstractHandler.java b/src/main/java/com/rymcu/forest/wx/mp/handler/AbstractHandler.java deleted file mode 100644 index f241032..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/handler/AbstractHandler.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.rymcu.forest.wx.mp.handler; - -import me.chanjar.weixin.mp.api.WxMpMessageHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Binary Wang(https://github.com/binarywang) - */ -public abstract class AbstractHandler implements WxMpMessageHandler { - protected Logger logger = LoggerFactory.getLogger(getClass()); -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/handler/KfSessionHandler.java b/src/main/java/com/rymcu/forest/wx/mp/handler/KfSessionHandler.java deleted file mode 100644 index 464a85d..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/handler/KfSessionHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.rymcu.forest.wx.mp.handler; - -import me.chanjar.weixin.common.session.WxSessionManager; -import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; -import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; -import org.springframework.stereotype.Component; - -import java.util.Map; - -/** - * @author Binary Wang(https://github.com/binarywang) - */ -@Component -public class KfSessionHandler extends AbstractHandler { - - @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, - Map context, WxMpService wxMpService, - WxSessionManager sessionManager) { - //TODO 对会话做处理 - return null; - } - -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/handler/LocationHandler.java b/src/main/java/com/rymcu/forest/wx/mp/handler/LocationHandler.java deleted file mode 100644 index 7502c6d..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/handler/LocationHandler.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.rymcu.forest.wx.mp.handler; - -import com.rymcu.forest.wx.mp.builder.TextBuilder; -import me.chanjar.weixin.common.session.WxSessionManager; -import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; -import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; -import org.springframework.stereotype.Component; - -import java.util.Map; - -import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType; - -/** - * @author Binary Wang(https://github.com/binarywang) - */ -@Component -public class LocationHandler extends AbstractHandler { - - @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, - Map context, WxMpService wxMpService, - WxSessionManager sessionManager) { - if (wxMessage.getMsgType().equals(XmlMsgType.LOCATION)) { - //TODO 接收处理用户发送的地理位置消息 - try { - String content = "感谢反馈,您的的地理位置已收到!"; - return new TextBuilder().build(content, wxMessage, null); - } catch (Exception e) { - this.logger.error("位置消息接收处理失败", e); - return null; - } - } - - //上报地理位置事件 - this.logger.info("上报地理位置,纬度 : {},经度 : {},精度 : {}", - wxMessage.getLatitude(), wxMessage.getLongitude(), String.valueOf(wxMessage.getPrecision())); - - //TODO 可以将用户地理位置信息保存到本地数据库,以便以后使用 - - return null; - } - -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/handler/LogHandler.java b/src/main/java/com/rymcu/forest/wx/mp/handler/LogHandler.java deleted file mode 100644 index 8744d49..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/handler/LogHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.rymcu.forest.wx.mp.handler; - -import com.rymcu.forest.wx.mp.utils.JsonUtils; -import me.chanjar.weixin.common.session.WxSessionManager; -import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; -import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; -import org.springframework.stereotype.Component; - -import java.util.Map; - -/** - * @author Binary Wang(https://github.com/binarywang) - */ -@Component -public class LogHandler extends AbstractHandler { - @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, - Map context, WxMpService wxMpService, - WxSessionManager sessionManager) { - this.logger.info("\n接收到请求消息,内容:{}", JsonUtils.toJson(wxMessage)); - return null; - } - -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/handler/MenuHandler.java b/src/main/java/com/rymcu/forest/wx/mp/handler/MenuHandler.java deleted file mode 100644 index 0faedf0..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/handler/MenuHandler.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.rymcu.forest.wx.mp.handler; - -import me.chanjar.weixin.common.session.WxSessionManager; -import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; -import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; -import org.springframework.stereotype.Component; - -import java.util.Map; - -import static me.chanjar.weixin.common.api.WxConsts.EventType; - -/** - * @author Binary Wang(https://github.com/binarywang) - */ -@Component -public class MenuHandler extends AbstractHandler { - - @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, - Map context, WxMpService weixinService, - WxSessionManager sessionManager) { - String msg = String.format("type:%s, event:%s, key:%s", - wxMessage.getMsgType(), wxMessage.getEvent(), - wxMessage.getEventKey()); - if (EventType.VIEW.equals(wxMessage.getEvent())) { - return null; - } - - return WxMpXmlOutMessage.TEXT().content(msg) - .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser()) - .build(); - } - -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/handler/MsgHandler.java b/src/main/java/com/rymcu/forest/wx/mp/handler/MsgHandler.java deleted file mode 100644 index 9aec3ec..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/handler/MsgHandler.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.rymcu.forest.wx.mp.handler; - -import com.rymcu.forest.wx.mp.builder.TextBuilder; -import me.chanjar.weixin.common.session.WxSessionManager; -import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; -import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; -import org.apache.commons.lang3.StringUtils; -import org.springframework.stereotype.Component; - -import java.util.Map; - -import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType; - -/** - * @author Binary Wang(https://github.com/binarywang) - */ -@Component -public class MsgHandler extends AbstractHandler { - - @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, - Map context, WxMpService wxMpService, - WxSessionManager sessionManager) { - - if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) { - //TODO 可以选择将消息保存到本地 - } - - if (wxMessage == null || StringUtils.isBlank(wxMessage.getContent())) { - return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE() - .fromUser(wxMessage.getToUser()) - .toUser(wxMessage.getFromUser()).build(); - } - - logger.info("\n接收到 {} 公众号请求消息,内容:{}", wxMpService.getWxMpConfigStorage().getAppId(), wxMessage); - - - String content = "我们已经收到您的留言,稍后客服将会联系您!"; - - return new TextBuilder().build(content, wxMessage, wxMpService); - - } - -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/handler/NullHandler.java b/src/main/java/com/rymcu/forest/wx/mp/handler/NullHandler.java deleted file mode 100644 index 907cba4..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/handler/NullHandler.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.rymcu.forest.wx.mp.handler; - -import me.chanjar.weixin.common.session.WxSessionManager; -import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; -import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; -import org.springframework.stereotype.Component; - -import java.util.Map; - -/** - * @author Binary Wang(https://github.com/binarywang) - */ -@Component -public class NullHandler extends AbstractHandler { - - @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, - Map context, WxMpService wxMpService, - WxSessionManager sessionManager) { - return null; - } - -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/handler/ScanHandler.java b/src/main/java/com/rymcu/forest/wx/mp/handler/ScanHandler.java deleted file mode 100644 index c4f3ab1..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/handler/ScanHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.rymcu.forest.wx.mp.handler; - -import java.util.Map; - -import org.springframework.stereotype.Component; - -import me.chanjar.weixin.common.error.WxErrorException; -import me.chanjar.weixin.common.session.WxSessionManager; -import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; -import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; - -/** - * @author Binary Wang(https://github.com/binarywang) - */ -@Component -public class ScanHandler extends AbstractHandler { - - @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, Map map, - WxMpService wxMpService, WxSessionManager wxSessionManager) throws WxErrorException { - // 扫码事件处理 - return null; - } -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/handler/StoreCheckNotifyHandler.java b/src/main/java/com/rymcu/forest/wx/mp/handler/StoreCheckNotifyHandler.java deleted file mode 100644 index bcc973b..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/handler/StoreCheckNotifyHandler.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.rymcu.forest.wx.mp.handler; - -import me.chanjar.weixin.common.session.WxSessionManager; -import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; -import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; -import org.springframework.stereotype.Component; - -import java.util.Map; - -/** - * 门店审核事件处理 - * - * @author Binary Wang(https://github.com/binarywang) - */ -@Component -public class StoreCheckNotifyHandler extends AbstractHandler { - - @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, - Map context, WxMpService wxMpService, - WxSessionManager sessionManager) { - // TODO 处理门店审核事件 - return null; - } - -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/handler/SubscribeHandler.java b/src/main/java/com/rymcu/forest/wx/mp/handler/SubscribeHandler.java deleted file mode 100644 index 1e1f4da..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/handler/SubscribeHandler.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.rymcu.forest.wx.mp.handler; - -import java.util.Map; - -import com.rymcu.forest.wx.mp.builder.TextBuilder; -import org.springframework.stereotype.Component; - -import me.chanjar.weixin.common.error.WxErrorException; -import me.chanjar.weixin.common.session.WxSessionManager; -import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; -import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; -import me.chanjar.weixin.mp.bean.result.WxMpUser; - -/** - * @author Binary Wang(https://github.com/binarywang) - */ -@Component -public class SubscribeHandler extends AbstractHandler { - - @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, - Map context, WxMpService weixinService, - WxSessionManager sessionManager) throws WxErrorException { - - this.logger.info("新关注用户 OPENID: " + wxMessage.getFromUser()); - - // 获取微信用户基本信息 - try { - WxMpUser userWxInfo = weixinService.getUserService() - .userInfo(wxMessage.getFromUser(), null); - if (userWxInfo != null) { - // TODO 可以添加关注用户到本地数据库 - } - } catch (WxErrorException e) { - if (e.getError().getErrorCode() == 48001) { - this.logger.info("该公众号没有获取用户信息权限!"); - } - } - - - WxMpXmlOutMessage responseResult = null; - try { - responseResult = this.handleSpecial(wxMessage); - } catch (Exception e) { - this.logger.error(e.getMessage(), e); - } - - if (responseResult != null) { - return responseResult; - } - - try { - return new TextBuilder().build("感谢关注", wxMessage, weixinService); - } catch (Exception e) { - this.logger.error(e.getMessage(), e); - } - - return null; - } - - /** - * 处理特殊请求,比如如果是扫码进来的,可以做相应处理 - */ - private WxMpXmlOutMessage handleSpecial(WxMpXmlMessage wxMessage) - throws Exception { - //TODO - return null; - } - -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/handler/UnsubscribeHandler.java b/src/main/java/com/rymcu/forest/wx/mp/handler/UnsubscribeHandler.java deleted file mode 100644 index 1e84cee..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/handler/UnsubscribeHandler.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.rymcu.forest.wx.mp.handler; - -import me.chanjar.weixin.common.session.WxSessionManager; -import me.chanjar.weixin.mp.api.WxMpService; -import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; -import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; -import org.springframework.stereotype.Component; - -import java.util.Map; - -/** - * @author Binary Wang(https://github.com/binarywang) - */ -@Component -public class UnsubscribeHandler extends AbstractHandler { - - @Override - public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, - Map context, WxMpService wxMpService, - WxSessionManager sessionManager) { - String openId = wxMessage.getFromUser(); - this.logger.info("取消关注用户 OPENID: " + openId); - // TODO 可以更新本地数据库为取消关注状态 - return null; - } - -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/service/WxMenuService.java b/src/main/java/com/rymcu/forest/wx/mp/service/WxMenuService.java deleted file mode 100644 index b67745d..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/service/WxMenuService.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.rymcu.forest.wx.mp.service; - -import me.chanjar.weixin.common.bean.menu.WxMenu; - -import java.io.IOException; - -/** - * @author ronger - */ -public interface WxMenuService { - /** - * 获取公众号菜单配置 - * @return - * @throws IOException - */ - WxMenu getMenus() throws IOException; -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/service/impl/WxMenuServiceImpl.java b/src/main/java/com/rymcu/forest/wx/mp/service/impl/WxMenuServiceImpl.java deleted file mode 100644 index f70493c..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/service/impl/WxMenuServiceImpl.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.rymcu.forest.wx.mp.service.impl; - -import com.rymcu.forest.wx.mp.service.WxMenuService; -import me.chanjar.weixin.common.bean.menu.WxMenu; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.io.Resource; -import org.springframework.stereotype.Service; - -import java.io.File; -import java.io.IOException; -import java.util.Scanner; - -/** - * @author ronger - */ -@Service -public class WxMenuServiceImpl implements WxMenuService { - @Value("classpath:wxMpMenus.json") - private Resource menuResource; - - @Override - public WxMenu getMenus() throws IOException { - File file = menuResource.getFile(); - String menuJson = this.jsonRead(file); - WxMenu wxMenu = WxMenu.fromJson(menuJson); - return wxMenu; - } - - private String jsonRead(File file) { - Scanner scanner = null; - StringBuilder buffer = new StringBuilder(); - try { - scanner = new Scanner(file, "utf-8"); - while (scanner.hasNextLine()) { - buffer.append(scanner.nextLine()); - } - } catch (Exception e) { - - } finally { - if (scanner != null) { - scanner.close(); - } - } - return buffer.toString(); - } -} diff --git a/src/main/java/com/rymcu/forest/wx/mp/utils/JsonUtils.java b/src/main/java/com/rymcu/forest/wx/mp/utils/JsonUtils.java deleted file mode 100644 index c0520b6..0000000 --- a/src/main/java/com/rymcu/forest/wx/mp/utils/JsonUtils.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.rymcu.forest.wx.mp.utils; - -import com.alibaba.fastjson.JSONObject; - -public class JsonUtils { - public static String toJson(Object obj) { - return JSONObject.toJSONString(obj); - } -} diff --git a/src/main/java/com/rymcu/forest/wx/open/config/WxOpenProperties.java b/src/main/java/com/rymcu/forest/wx/open/config/WxOpenProperties.java deleted file mode 100644 index 184c738..0000000 --- a/src/main/java/com/rymcu/forest/wx/open/config/WxOpenProperties.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.rymcu.forest.wx.open.config; - -import lombok.Getter; -import lombok.Setter; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; -import org.springframework.boot.context.properties.ConfigurationProperties; - - -/** - * @author 007 - */ -@Getter -@Setter -@ConfigurationProperties(prefix = "wx.open") -public class WxOpenProperties { - /** - * 设置微信三方平台的appid - */ - private String componentAppId; - - /** - * 设置微信三方平台的app secret - */ - private String componentSecret; - - /** - * 设置微信三方平台的token - */ - private String componentToken; - - /** - * 设置微信三方平台的EncodingAESKey - */ - private String componentAesKey; - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, - ToStringStyle.MULTI_LINE_STYLE); - } -} diff --git a/src/main/java/com/rymcu/forest/wx/open/controller/WxOpenApiController.java b/src/main/java/com/rymcu/forest/wx/open/controller/WxOpenApiController.java deleted file mode 100644 index 96837a6..0000000 --- a/src/main/java/com/rymcu/forest/wx/open/controller/WxOpenApiController.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.rymcu.forest.wx.open.controller; - -import com.rymcu.forest.wx.open.handler.WxOpenServiceHandler; -import me.chanjar.weixin.common.error.WxErrorException; -import me.chanjar.weixin.open.bean.result.WxOpenAuthorizerInfoResult; -import me.chanjar.weixin.open.bean.result.WxOpenQueryAuthResult; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; - -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -/** - * @author 007 - */ -@Controller -@RequestMapping("/wx/open/auth") -public class WxOpenApiController { - - private final Logger logger = LoggerFactory.getLogger(getClass()); - - @Resource - private WxOpenServiceHandler wxOpenServiceHandler; - - @GetMapping("/goto_auth_url_show") - @ResponseBody - public String gotoPreAuthUrlShow(){ - return "go"; - } - - @GetMapping("/goto_auth_url") - public void gotoPreAuthUrl(HttpServletRequest request, HttpServletResponse response){ - System.out.println("===================================Host:"); - System.out.println(request.getHeader("host")); - String host = request.getHeader("host"); - String url = "http://"+host+"/open/auth/jump"; - try { - url = wxOpenServiceHandler.getWxOpenComponentService().getPreAuthUrl(url); - // 添加来源,解决302跳转来源丢失的问题 - response.addHeader("Referer", "http://"+host); - response.sendRedirect(url); - } catch (WxErrorException | IOException e) { - logger.error("gotoPreAuthUrl", e); - throw new RuntimeException(e); - } - } - - @GetMapping("/jump") - @ResponseBody - public WxOpenQueryAuthResult jump(@RequestParam("auth_code") String authorizationCode){ - try { - WxOpenQueryAuthResult queryAuthResult = wxOpenServiceHandler.getWxOpenComponentService().getQueryAuth(authorizationCode); - logger.info("getQueryAuth", queryAuthResult); - return queryAuthResult; - } catch (WxErrorException e) { - logger.error("gotoPreAuthUrl", e); - throw new RuntimeException(e); - } - } - - @GetMapping("/get_auth_info") - @ResponseBody - public WxOpenAuthorizerInfoResult getAuthInfo(@RequestParam String appId){ - try { - return wxOpenServiceHandler.getWxOpenComponentService().getAuthorizerInfo(appId); - } catch (WxErrorException e) { - logger.error("getAuthInfo", e); - throw new RuntimeException(e); - } - } -} diff --git a/src/main/java/com/rymcu/forest/wx/open/controller/WxOpenNotifyController.java b/src/main/java/com/rymcu/forest/wx/open/controller/WxOpenNotifyController.java deleted file mode 100644 index 0a83d0e..0000000 --- a/src/main/java/com/rymcu/forest/wx/open/controller/WxOpenNotifyController.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.rymcu.forest.wx.open.controller; - -import com.rymcu.forest.wx.open.handler.WxOpenServiceHandler; -import me.chanjar.weixin.common.api.WxConsts; -import me.chanjar.weixin.common.error.WxErrorException; -import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage; -import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage; -import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage; -import me.chanjar.weixin.open.bean.message.WxOpenXmlMessage; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.*; - -/** - * @author 007 - */ -@RestController -@RequestMapping("/wx/notify") -public class WxOpenNotifyController { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - protected WxOpenServiceHandler wxOpenService; - - /** - * 全网发布官方测试小程序 AppId - */ - private final static String testMiniProgramAppId = "wxd101a85aa106f53e"; - /** - * 全网发布官方测试公众号 AppId - */ - private final static String testMpAppId = "wx570bc396a51b8ff8"; - private final static String TESTCOMPONENT_MSG_TYPE_TEXT = "TESTCOMPONENT_MSG_TYPE_TEXT"; - private final static String TESTCOMPONENT_MSG_TYPE_TEXT_callback = "TESTCOMPONENT_MSG_TYPE_TEXT_callback"; - - @RequestMapping("/receive_ticket") - public Object receiveTicket(@RequestBody(required = false) String requestBody, @RequestParam("timestamp") String timestamp, - @RequestParam("nonce") String nonce, @RequestParam("signature") String signature, - @RequestParam(name = "encrypt_type", required = false) String encType, - @RequestParam(name = "msg_signature", required = false) String msgSignature) { - this.logger.info( - "\n接收微信请求:[signature=[{}], encType=[{}], msgSignature=[{}]," - + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ", - signature, encType, msgSignature, timestamp, nonce, requestBody); - - if (!StringUtils.equalsIgnoreCase("aes", encType) - || !wxOpenService.getWxOpenComponentService().checkSignature(timestamp, nonce, signature)) { - throw new IllegalArgumentException("非法请求,可能属于伪造的请求!"); - } - - // aes加密的消息 - WxOpenXmlMessage inMessage = WxOpenXmlMessage.fromEncryptedXml(requestBody, - wxOpenService.getWxOpenConfigStorage(), timestamp, nonce, msgSignature); - this.logger.debug("\n消息解密后内容为:\n{} ", inMessage.toString()); - try { - String out = wxOpenService.getWxOpenComponentService().route(inMessage); - this.logger.debug("\n组装回复信息:{}", out); - } catch (WxErrorException e) { - this.logger.error("receive_ticket", e); - } - - - return "success"; - } - - @RequestMapping("/{appId}/callback") - public Object callback(@RequestBody(required = false) String requestBody, - @PathVariable("appId") String appId, - @RequestParam("signature") String signature, - @RequestParam("timestamp") String timestamp, - @RequestParam("nonce") String nonce, - @RequestParam("openid") String openid, - @RequestParam("encrypt_type") String encType, - @RequestParam("msg_signature") String msgSignature) { - this.logger.info( - "\n接收微信请求:[appId=[{}], openid=[{}], signature=[{}], encType=[{}], msgSignature=[{}]," - + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ", - appId, openid, signature, encType, msgSignature, timestamp, nonce, requestBody); - if (!StringUtils.equalsIgnoreCase("aes", encType) - || !wxOpenService.getWxOpenComponentService().checkSignature(timestamp, nonce, signature)) { - throw new IllegalArgumentException("非法请求,可能属于伪造的请求!"); - } - - String out = ""; - // aes加密的消息 - WxMpXmlMessage inMessage = WxOpenXmlMessage.fromEncryptedMpXml(requestBody, - wxOpenService.getWxOpenConfigStorage(), timestamp, nonce, msgSignature); - this.logger.debug("\n消息解密后内容为:\n{} ", inMessage.toString()); - // 全网发布测试用例 - if (StringUtils.equalsAnyIgnoreCase(appId, testMiniProgramAppId, testMpAppId)) { - try { - if (StringUtils.equals(inMessage.getMsgType(), WxConsts.XmlMsgType.TEXT)) { - if (StringUtils.equals(inMessage.getContent(), TESTCOMPONENT_MSG_TYPE_TEXT)) { - out = WxOpenXmlMessage.wxMpOutXmlMessageToEncryptedXml( - WxMpXmlOutMessage.TEXT().content(TESTCOMPONENT_MSG_TYPE_TEXT_callback) - .fromUser(inMessage.getToUser()) - .toUser(inMessage.getFromUser()) - .build(), - wxOpenService.getWxOpenConfigStorage() - ); - } else if (StringUtils.startsWith(inMessage.getContent(), "QUERY_AUTH_CODE:")) { - String msg = inMessage.getContent().replace("QUERY_AUTH_CODE:", "") + "_from_api"; - WxMpKefuMessage kefuMessage = WxMpKefuMessage.TEXT().content(msg).toUser(inMessage.getFromUser()).build(); - wxOpenService.getWxOpenComponentService().getWxMpServiceByAppid(appId).getKefuService().sendKefuMessage(kefuMessage); - } - } else if (StringUtils.equals(inMessage.getMsgType(), "event")) { - WxMpKefuMessage kefuMessage = WxMpKefuMessage.TEXT().content(inMessage.getEvent() + "from_callback").toUser(inMessage.getFromUser()).build(); - wxOpenService.getWxOpenComponentService().getWxMpServiceByAppid(appId).getKefuService().sendKefuMessage(kefuMessage); - } - } catch (WxErrorException e) { - logger.error("callback", e); - } - } else { - WxMpXmlOutMessage outMessage = wxOpenService.getWxOpenMessageRouter().route(inMessage, appId); - if (outMessage != null) { - out = WxOpenXmlMessage.wxMpOutXmlMessageToEncryptedXml(outMessage, wxOpenService.getWxOpenConfigStorage()); - } - } - return out; - } -} diff --git a/src/main/java/com/rymcu/forest/wx/open/handler/WxOpenServiceHandler.java b/src/main/java/com/rymcu/forest/wx/open/handler/WxOpenServiceHandler.java deleted file mode 100644 index bbf2b33..0000000 --- a/src/main/java/com/rymcu/forest/wx/open/handler/WxOpenServiceHandler.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.rymcu.forest.wx.open.handler; - -import com.rymcu.forest.config.RedisProperties; -import com.rymcu.forest.wx.open.config.WxOpenProperties; -import me.chanjar.weixin.open.api.impl.WxOpenInRedisConfigStorage; -import me.chanjar.weixin.open.api.impl.WxOpenMessageRouter; -import me.chanjar.weixin.open.api.impl.WxOpenServiceImpl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.stereotype.Service; -import redis.clients.jedis.JedisPool; - -import javax.annotation.PostConstruct; -import javax.annotation.Resource; - -/** - * @author ronger - */ -@Service -@EnableConfigurationProperties({WxOpenProperties.class, RedisProperties.class}) -public class WxOpenServiceHandler extends WxOpenServiceImpl { - - private Logger logger = LoggerFactory.getLogger(getClass()); - - @Resource - private WxOpenProperties wxOpenProperties; - @Resource - private RedisProperties redisProperties; - private static JedisPool pool; - private WxOpenMessageRouter wxOpenMessageRouter; - - @PostConstruct - public void init() { - WxOpenInRedisConfigStorage inRedisConfigStorage = new WxOpenInRedisConfigStorage(getJedisPool()); - inRedisConfigStorage.setComponentAppId(wxOpenProperties.getComponentAppId()); - inRedisConfigStorage.setComponentAppSecret(wxOpenProperties.getComponentSecret()); - inRedisConfigStorage.setComponentToken(wxOpenProperties.getComponentToken()); - inRedisConfigStorage.setComponentAesKey(wxOpenProperties.getComponentAesKey()); - setWxOpenConfigStorage(inRedisConfigStorage); - wxOpenMessageRouter = new WxOpenMessageRouter(this); - wxOpenMessageRouter.rule().handler((wxMpXmlMessage, map, wxMpService, wxSessionManager) -> { - logger.info("\n接收到 {} 公众号请求消息,内容:{}", wxMpService.getWxMpConfigStorage().getAppId(), wxMpXmlMessage); - return null; - }).next(); - } - - private JedisPool getJedisPool() { - if (pool == null) { - synchronized (WxOpenServiceHandler.class) { - if (pool == null) { - pool = new JedisPool(redisProperties, redisProperties.getHost(), - redisProperties.getPort(), redisProperties.getConnectionTimeout(), - redisProperties.getSoTimeout(), redisProperties.getPassword(), - redisProperties.getDatabase(), redisProperties.getClientName(), - redisProperties.isSsl(), redisProperties.getSslSocketFactory(), - redisProperties.getSslParameters(), redisProperties.getHostnameVerifier()); - } - } - } - return pool; - } - - public WxOpenMessageRouter getWxOpenMessageRouter() { - return wxOpenMessageRouter; - } -} diff --git a/src/main/java/mapper/ArticleMapper.xml b/src/main/java/mapper/ArticleMapper.xml index 3e9d852..d17086c 100644 --- a/src/main/java/mapper/ArticleMapper.xml +++ b/src/main/java/mapper/ArticleMapper.xml @@ -5,7 +5,7 @@ - + diff --git a/src/main/java/mapper/BankAccountMapper.xml b/src/main/java/mapper/BankAccountMapper.xml index ff935f7..4ab4f2a 100644 --- a/src/main/java/mapper/BankAccountMapper.xml +++ b/src/main/java/mapper/BankAccountMapper.xml @@ -26,16 +26,27 @@ + \ No newline at end of file diff --git a/src/main/java/mapper/ProductMapper.xml b/src/main/java/mapper/ProductMapper.xml new file mode 100644 index 0000000..438aca3 --- /dev/null +++ b/src/main/java/mapper/ProductMapper.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + insert into forest_product_content(id_product, + product_content, + product_content_html, + created_time, + updated_time) + values (#{idProduct}, + #{productContent}, + #{productContentHtml}, + sysdate(), + sysdate()) + + + + \ No newline at end of file diff --git a/src/main/java/mapper/UserMapper.xml b/src/main/java/mapper/UserMapper.xml index 11b203c..f2c6cef 100644 --- a/src/main/java/mapper/UserMapper.xml +++ b/src/main/java/mapper/UserMapper.xml @@ -20,6 +20,7 @@ + @@ -35,6 +36,7 @@ + @@ -43,6 +45,7 @@ + @@ -86,7 +89,7 @@ select id, nickname, sex, avatar_type, avatar_url, email, phone, account, status, signature, last_login_time, last_online_time from forest_user where account = #{account} diff --git a/src/main/java/mapper/lucene/PortfolioLuceneMapper.xml b/src/main/java/mapper/lucene/PortfolioLuceneMapper.xml index b1d09d4..2079fdf 100644 --- a/src/main/java/mapper/lucene/PortfolioLuceneMapper.xml +++ b/src/main/java/mapper/lucene/PortfolioLuceneMapper.xml @@ -39,6 +39,6 @@ diff --git a/src/main/java/mapper/lucene/UserLuceneMapper.xml b/src/main/java/mapper/lucene/UserLuceneMapper.xml index 5c0be15..db196c2 100644 --- a/src/main/java/mapper/lucene/UserLuceneMapper.xml +++ b/src/main/java/mapper/lucene/UserLuceneMapper.xml @@ -36,7 +36,7 @@ diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index b28d3ae..1f0ad51 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -4,7 +4,7 @@ spring: thymeleaf: prefix: classpath:/templates/ suffix: .html - mode: LEGACYHTML5 + mode: HTML encoding: UTF-8 servlet: content-type: text/html diff --git a/src/main/resources/static/forest.sql b/src/main/resources/static/forest.sql index 86a58df..fbde953 100644 --- a/src/main/resources/static/forest.sql +++ b/src/main/resources/static/forest.sql @@ -43,7 +43,7 @@ create table forest_article_thumbs_up id_article bigint null comment '文章表主键', id_user bigint null comment '用户表主键', thumbs_up_time datetime null comment '点赞时间' -) comment '文章点赞表 '; +) comment '文章点赞表 ' collate = utf8mb4_unicode_ci; create table forest_bank ( @@ -54,7 +54,7 @@ create table forest_bank bank_description varchar(512) null comment '银行描述', created_by bigint null comment '创建人', created_time datetime null comment '创建时间' -) comment '银行表 '; +) comment '银行表 ' collate = utf8mb4_unicode_ci; create table forest_bank_account ( @@ -66,7 +66,7 @@ create table forest_bank_account account_owner bigint null comment '账户所有者', created_time datetime null comment '创建时间', account_type char default '0' null comment '0: 普通账户 1: 银行账户' -) comment '银行账户表 '; +) comment '银行账户表 ' collate = utf8mb4_unicode_ci; create table forest_comment ( @@ -93,7 +93,7 @@ create table forest_currency_issue issue_value decimal(32, 8) null comment '发行数额', created_by bigint null comment '发行人', created_time datetime null comment '发行时间' -) comment '货币发行表 '; +) comment '货币发行表 ' collate = utf8mb4_unicode_ci; create table forest_currency_rule ( @@ -107,7 +107,7 @@ create table forest_currency_rule maximum_money decimal(32, 8) null comment '上限金额', repeat_days int default 0 null comment '重复(0: 不重复,单位:天)', status char default '0' null comment '状态' -) comment '货币规则表 '; +) comment '货币规则表 ' collate = utf8mb4_unicode_ci; create table forest_follow ( @@ -173,7 +173,7 @@ create table forest_sponsor sponsor bigint null comment '赞赏人', sponsorship_time datetime null comment '赞赏日期', sponsorship_money decimal(32, 8) null comment '赞赏金额' -) comment '赞赏表 '; +) comment '赞赏表 ' collate = utf8mb4_unicode_ci; create table forest_tag ( @@ -251,7 +251,7 @@ create table forest_transaction_record money decimal(32, 8) null comment '交易金额', transaction_type char default '0' null comment '交易类型', transaction_time datetime null comment '交易时间' -) comment '交易记录表 '; +) comment '交易记录表 ' collate = utf8mb4_unicode_ci; create table forest_user ( @@ -271,7 +271,8 @@ create table forest_user updated_time datetime null comment '更新时间', last_login_time datetime null comment '最后登录时间', signature varchar(128) null comment '签名', - last_online_time datetime null comment '最后在线时间' + last_online_time datetime null comment '最后在线时间', + bg_img_url varchar(512) null comment '背景图片' ) comment '用户表 ' collate = utf8mb4_unicode_ci; create table forest_user_extend @@ -282,7 +283,7 @@ create table forest_user_extend weixin varchar(32) null comment '微信', qq varchar(32) null comment 'qq', blog varchar(500) null comment '博客' -) comment '用户扩展表 '; +) comment '用户扩展表 ' collate = utf8mb4_unicode_ci; create table forest_user_role ( @@ -323,7 +324,7 @@ create table forest_lucene_user_dic dic char(32) null comment '字典', constraint forest_lucene_user_dic_id_uindex unique (id) -) comment '用户扩展字典'; +) comment '用户扩展字典' collate = utf8mb4_unicode_ci; alter table forest_lucene_user_dic add primary key (id); @@ -341,6 +342,10 @@ insert into forest.forest_user (id, account, password, nickname, real_name, sex, status, created_time, updated_time, last_login_time, signature) values (1, 'admin', '8ce2dd866238958ac4f07870766813cdaa39a9b83a8c75e26aa50f23', 'admin', 'admin', '0', '0', null, 'admin@rymcu.com', null, '0', '2021-01-25 18:21:51', '2021-01-25 18:21:54', null, null); +insert into forest.forest_user (id, account, password, nickname, real_name, sex, avatar_type, avatar_url, email, phone, + status, created_time, updated_time, last_login_time, signature) +values (2, 'testUser', '8ce2dd866238958ac4f07870766813cdaa39a9b83a8c75e26aa50f23', 'testUser', 'testUser', '0', '0', null, 'testUser@rymcu.com', + null, '0', '2021-01-25 18:21:51', '2021-01-25 18:21:54', null, null); insert into forest.forest_user_role (id_user, id_role, created_time) values (1, 1, '2021-01-25 18:22:12'); @@ -357,7 +362,7 @@ create table forest_file created_by int null comment '创建人', file_size int null comment '文件大小', file_type varchar(10) null comment '文件类型' -) comment '文件上传记录表'; +) comment '文件上传记录表' collate = utf8mb4_unicode_ci; create index index_md5_value_created_by on forest_file (md5_value, created_by); @@ -382,4 +387,4 @@ create table forest_login_record login_device_id varchar(512) null comment '登录设备/浏览器指纹', constraint forest_login_record_id_uindex unique (id) -) comment '登录记录表'; +) comment '登录记录表' collate = utf8mb4_unicode_ci; diff --git a/src/main/resources/static/jb_beam.svg b/src/main/resources/static/jb_beam.svg new file mode 100644 index 0000000..c4fe87c --- /dev/null +++ b/src/main/resources/static/jb_beam.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/src/test/java/com/rymcu/forest/service/ArticleServiceTest.java b/src/test/java/com/rymcu/forest/service/ArticleServiceTest.java new file mode 100644 index 0000000..3944f32 --- /dev/null +++ b/src/test/java/com/rymcu/forest/service/ArticleServiceTest.java @@ -0,0 +1,229 @@ +package com.rymcu.forest.service; + +import com.rymcu.forest.dto.ArticleDTO; +import com.rymcu.forest.dto.ArticleSearchDTO; +import com.rymcu.forest.dto.ArticleTagDTO; +import com.rymcu.forest.dto.Author; +import com.rymcu.forest.entity.User; +import com.rymcu.forest.web.api.exception.BaseApiException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.transaction.annotation.Transactional; + +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.*; + +@SpringBootTest +@ExtendWith(SpringExtension.class) +@Transactional +// 顺序执行单元测试 +@TestMethodOrder(MethodOrderer.Random.class) +class ArticleServiceTest { + + /** + * 测试用的Article数据,用于该单元测试的一系列操作 + */ + private final ArticleDTO testArticle; + + /** + * 与Article相关联的测试User数据(建表时提前放入) + */ + private final User testUser = new User(); + + { + // 构建数据之间的关联结构 + Author testAuthor = Author.builder() + .idUser(2L) + .userArticleCount("0") + .userAccount("testUser") + .userNickname("testUser") + .userAvatarURL(null) + .build(); + BeanUtils.copyProperties(testAuthor, testUser); + + ArticleTagDTO tagDTO = ArticleTagDTO.builder() + .tagTitle("Test") + .tagDescription("Test") + .idTag(111) + .tagAuthorId(testUser.getIdUser()) + .build(); + + List tags = new ArrayList<>(); + tags.add(tagDTO); + + testArticle = ArticleDTO.builder() + .articleAuthor(testAuthor) + .articleAuthorId(testAuthor.getIdUser()) + .articleContent("Test") + .articleLink("Test") + .articlePerfect("0") + .articlePermalink("Test") + .articleAuthorName(testAuthor.getUserNickname()) + .articleCommentCount(0) + .articleStatus("0") + .articleTags("Test") + .articleContentHtml("

Test

") + .articleTitle("Test") + .articleType("0") + .articlePreviewContent("Test") + .articleSponsorCount(12) + .articlePermalink("Test") + .articleViewCount(0) + .tags(tags) + .build(); + } + + @Autowired + private ArticleService articleService; + + /** + * 将测试用的Article数据插入数据库中(会回滚的:)) + * + * 测试数据是否会返回Article的Id,并且Id会填充到测试数据中 + * @throws UnsupportedEncodingException + * @throws BaseApiException + */ + @Test + @BeforeEach + public void postArticle() throws UnsupportedEncodingException, BaseApiException { + Long articleId = articleService.postArticle(testArticle, testUser); + testArticle.setIdArticle(articleId); + assertNotNull(articleId); + } + + /** + * 测试条件查询 + *

+ * 无参数时返回所有Article + */ + @Test + void findArticles() { + // 无参数时返回参数不应为EmptyList + List articlesAll = articleService.findArticles(new ArticleSearchDTO()); + assertNotNull(articlesAll); + assertNotEquals(Collections.emptyList(), articlesAll); + + // 测试条件查询是否含有目标数据 + ArticleSearchDTO articleSearchDTO = new ArticleSearchDTO(); + articleSearchDTO.setSearchText(testArticle.getArticleContent()); + Map idArticleMap = articleService.findArticles(articleSearchDTO) + .stream() + .collect(Collectors.toMap(ArticleDTO::getIdArticle, item -> item)); + assertNotNull(idArticleMap.get(testArticle.getIdArticle())); + } + + /** + * 测试通过Id获取Article + */ + @Test + void findArticleDTOById() { + // 测试参数为 + ArticleDTO articleDTOByIdNull = articleService.findArticleDTOById(null, 0); + assertNull(articleDTOByIdNull); + ArticleDTO articleDTOById = articleService.findArticleDTOById(testArticle.getIdArticle(), 0); + assertNotNull(articleDTOById); + } + +// @Test +// void findArticlesByTopicUri() { +// List articlesByTopicUri = articleService.findArticlesByTopicUri(); +// } + +// @Test +// void findArticlesByTagName() { +// List articlesByTagName = articleService.findArticlesByTagName(); +// } + + /** + * 通过UserId获取对应的Articles + */ + @Test + void findUserArticlesByIdUser() { + List userArticlesByIdUser = articleService.findUserArticlesByIdUser(testArticle.getArticleAuthorId()); + assertNotEquals(Collections.emptyList(), userArticlesByIdUser); + } + + /** + * 测试文章浏览增量后是否成功 + */ + @Test + void incrementArticleViewCount() { + ArticleDTO articleDTOByIdBefore = articleService.findArticleDTOById(testArticle.getIdArticle(), 0); + articleService.incrementArticleViewCount(testArticle.getIdArticle()); + ArticleDTO articleDTOByIdAfter = articleService.findArticleDTOById(testArticle.getIdArticle(), 0); + assertEquals(articleDTOByIdBefore.getArticleViewCount() + 1, articleDTOByIdAfter.getArticleViewCount()); + } + +// @Test +// void share() { +// String share = articleService.share(); +// } + +// @Test +// void findDrafts() { +// List drafts = articleService.findDrafts(testArticle.getArticleAuthorId()); +// } + +// @Test +// void findArticlesByIdPortfolio() { +// List articlesByIdPortfolio = articleService.findArticlesByIdPortfolio(); +// } + +// @Test +// void selectUnbindArticles() { +// List articleDTOS = articleService.selectUnbindArticles(); +// } + +// @Test +// void findAnnouncements() { +// List announcements = articleService.findAnnouncements(); +// } + +// @Test +// void updateTags() { +// Boolean aBoolean = articleService.updateTags(); +// } + + /** + * 测试更新文章为优选\非优选 + */ + @Test + void updatePerfect() { + articleService.updatePerfect(testArticle.getIdArticle(), "1"); + ArticleDTO articleDTOByIdAfter1 = articleService.findArticleDTOById(testArticle.getIdArticle(), 0); + assertEquals("1", articleDTOByIdAfter1.getArticlePerfect()); + + articleService.updatePerfect(testArticle.getIdArticle(), "0"); + ArticleDTO articleDTOByIdAfter2 = articleService.findArticleDTOById(testArticle.getIdArticle(), 0); + assertEquals("0", articleDTOByIdAfter2.getArticlePerfect()); + } + + /** + * 测试数据删除是否成功 + *

+ * 运行该测试时,可能会产生以下错误: + * cn.hutool.core.io.IORuntimeException: Path [xxxxxxx] is not directory! + * 这是由于Lucene的路径通配符默认为linux的,解决方式: + * 将ArticleIndexUtil.deleteIndex()方法中的PATH改为WINDOW_PATH即可 :) + * @throws BaseApiException 基础Api错误 + */ + @Test + void delete() throws BaseApiException { + articleService.delete(testArticle.getIdArticle()); + ArticleDTO articleDTOByIdAfter = articleService.findArticleDTOById(testArticle.getIdArticle(), 0); + assertNull(articleDTOByIdAfter); + } +} \ No newline at end of file