From e650e39d109c7c7c6595620861851c0e4578bb50 Mon Sep 17 00:00:00 2001 From: ronger Date: Wed, 8 Jun 2022 10:30:38 +0800 Subject: [PATCH 01/25] =?UTF-8?q?:art:=20=E6=9B=BF=E6=8D=A2=20Lucene=20?= =?UTF-8?q?=E5=A4=B1=E6=95=88=E6=96=B9=E6=B3=95=20TokenSources.getAnyToken?= =?UTF-8?q?Stream=20=E4=B8=BA=20TokenSources.getTokenStream?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/impl/LuceneServiceImpl.java | 10 +- .../impl/PortfolioLuceneServiceImpl.java | 281 +++++++++--------- .../service/impl/UserLuceneServiceImpl.java | 19 +- 3 files changed, 153 insertions(+), 157 deletions(-) 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..39c25c8 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 @@ -156,12 +156,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 +172,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(); 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..bec4e2f 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,149 @@ 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; + 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(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.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.toString()); + } + } + // 获取到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(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..d88d557 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)) { From 0fc7503e65007e953439cfd8601e8a6338908160 Mon Sep 17 00:00:00 2001 From: ronger Date: Sat, 11 Jun 2022 12:37:15 +0800 Subject: [PATCH 02/25] =?UTF-8?q?:art:=20forest=5Fuser=20=E8=A1=A8?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20bg=5Fimg=5Furl=20=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/rymcu/forest/dto/UserDTO.java | 2 ++ .../com/rymcu/forest/dto/UserInfoDTO.java | 2 ++ .../java/com/rymcu/forest/entity/User.java | 6 +++++ src/main/java/mapper/UserMapper.xml | 5 +++- src/main/resources/static/forest.sql | 25 ++++++++++--------- 5 files changed, 27 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/rymcu/forest/dto/UserDTO.java b/src/main/java/com/rymcu/forest/dto/UserDTO.java index a4d755e..469a457 100644 --- a/src/main/java/com/rymcu/forest/dto/UserDTO.java +++ b/src/main/java/com/rymcu/forest/dto/UserDTO.java @@ -19,4 +19,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..aa1b041 100644 --- a/src/main/java/com/rymcu/forest/dto/UserInfoDTO.java +++ b/src/main/java/com/rymcu/forest/dto/UserInfoDTO.java @@ -46,4 +46,6 @@ public class UserInfoDTO implements Serializable { private Integer onlineStatus; + private String bgImgUrl; + } diff --git a/src/main/java/com/rymcu/forest/entity/User.java b/src/main/java/com/rymcu/forest/entity/User.java index 8654f99..642bc03 100644 --- a/src/main/java/com/rymcu/forest/entity/User.java +++ b/src/main/java/com/rymcu/forest/entity/User.java @@ -120,4 +120,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/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} + select * + from forest_product + order by weights + + \ No newline at end of file From 3974e77aa6a554764559a6591a6c44e4637b848a Mon Sep 17 00:00:00 2001 From: Kould <91525956+KKould@users.noreply.github.com> Date: Fri, 1 Jul 2022 21:58:56 +0800 Subject: [PATCH 06/25] =?UTF-8?q?style(utils):=20=E5=91=BD=E5=90=8D?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E3=80=81=E6=B3=A8=E9=87=8A=E8=A1=A5=E5=85=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 个别工具命名优化、注释补全,BeanCopierUtils的getBeanCopier方法实现优化 --- .../com/rymcu/forest/util/BaiDuUtils.java | 23 +++--- .../com/rymcu/forest/util/BeanCopierUtil.java | 58 +++++++------- .../com/rymcu/forest/util/CacheUtils.java | 76 +++++++++---------- .../rymcu/forest/util/ContextHolderUtils.java | 17 ++--- .../java/com/rymcu/forest/util/DateUtil.java | 13 ++-- .../java/com/rymcu/forest/util/Digests.java | 4 +- .../java/com/rymcu/forest/util/ErrorCode.java | 4 +- 7 files changed, 91 insertions(+), 104 deletions(-) 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; From 0744e48eb941af2875241baf3ac06cbca6f6b240 Mon Sep 17 00:00:00 2001 From: Kould <91525956+KKould@users.noreply.github.com> Date: Sun, 10 Jul 2022 22:31:58 +0800 Subject: [PATCH 07/25] =?UTF-8?q?style(entity,dto,service,...):=20?= =?UTF-8?q?=E5=AE=9E=E4=BD=93=E7=AD=89pojo=E4=B8=BB=E9=94=AE=E5=8F=98?= =?UTF-8?q?=E4=B8=BALong=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 主要对article实体等pojo主键变为Long类型,并对其涉及到的代码作一系列适配 article部分代码对service实现返回map做一系列修正 --- .../rymcu/forest/config/BaseShiroRealm.java | 6 +- .../exception/ContentNotExistException.java | 24 +++ .../exception/DataDuplicationException.java | 25 +++ .../core/exception/UltraViresException.java | 26 +++ .../forest/core/service/log/VisitAspect.java | 2 +- .../service/security/AuthorshipAspect.java | 2 +- .../java/com/rymcu/forest/dto/ArticleDTO.java | 7 +- .../com/rymcu/forest/dto/ArticleTagDTO.java | 11 +- .../java/com/rymcu/forest/dto/Author.java | 4 +- .../com/rymcu/forest/dto/NotificationDTO.java | 4 +- .../rymcu/forest/dto/PortfolioArticleDTO.java | 10 +- .../com/rymcu/forest/dto/PortfolioDTO.java | 7 +- .../java/com/rymcu/forest/dto/UserDTO.java | 4 +- .../com/rymcu/forest/dto/UserInfoDTO.java | 4 +- .../java/com/rymcu/forest/entity/Article.java | 7 +- .../rymcu/forest/entity/ArticleThumbsUp.java | 4 +- .../com/rymcu/forest/entity/BankAccount.java | 4 +- .../java/com/rymcu/forest/entity/Comment.java | 13 +- .../java/com/rymcu/forest/entity/Follow.java | 10 +- .../com/rymcu/forest/entity/Notification.java | 10 +- .../com/rymcu/forest/entity/Portfolio.java | 7 +- .../java/com/rymcu/forest/entity/Sponsor.java | 7 +- .../java/com/rymcu/forest/entity/User.java | 4 +- .../com/rymcu/forest/entity/UserExtend.java | 2 +- .../rymcu/forest/lucene/model/UserLucene.java | 4 +- .../service/impl/UserLuceneServiceImpl.java | 2 +- .../rymcu/forest/mapper/ArticleMapper.java | 40 ++-- .../rymcu/forest/mapper/CommentMapper.java | 2 +- .../com/rymcu/forest/mapper/FollowMapper.java | 6 +- .../forest/mapper/NotificationMapper.java | 14 +- .../rymcu/forest/mapper/PortfolioMapper.java | 16 +- .../com/rymcu/forest/mapper/RoleMapper.java | 2 +- .../rymcu/forest/mapper/SponsorMapper.java | 2 +- .../com/rymcu/forest/mapper/TagMapper.java | 8 +- .../com/rymcu/forest/mapper/UserMapper.java | 14 +- .../rymcu/forest/service/ArticleService.java | 20 +- .../forest/service/BankAccountService.java | 2 +- .../rymcu/forest/service/FollowService.java | 2 +- .../forest/service/NotificationService.java | 12 +- .../forest/service/PortfolioService.java | 8 +- .../com/rymcu/forest/service/RoleService.java | 2 +- .../service/TransactionRecordService.java | 4 +- .../com/rymcu/forest/service/UserService.java | 8 +- .../service/impl/ArticleServiceImpl.java | 181 ++++++++---------- .../service/impl/BankAccountServiceImpl.java | 4 +- .../service/impl/FollowServiceImpl.java | 2 +- .../service/impl/NotificationServiceImpl.java | 12 +- .../service/impl/PortfolioServiceImpl.java | 10 +- .../forest/service/impl/RoleServiceImpl.java | 2 +- .../impl/TransactionRecordServiceImpl.java | 4 +- .../forest/service/impl/UserServiceImpl.java | 8 +- .../rymcu/forest/util/NotificationUtils.java | 16 +- .../web/api/admin/AdminArticleController.java | 7 +- .../forest/web/api/admin/AdminController.java | 2 +- .../web/api/article/ArticleController.java | 49 ++--- .../web/api/bank/BankAccountController.java | 2 +- .../forest/web/api/bank/WalletController.java | 4 +- .../web/api/common/CommonApiController.java | 6 +- .../notification/NotificationController.java | 2 +- .../api/portfolio/PortfolioController.java | 8 +- .../web/api/user/UserInfoController.java | 2 +- src/main/java/mapper/ArticleMapper.xml | 2 +- 62 files changed, 393 insertions(+), 302 deletions(-) create mode 100644 src/main/java/com/rymcu/forest/core/exception/ContentNotExistException.java create mode 100644 src/main/java/com/rymcu/forest/core/exception/DataDuplicationException.java create mode 100644 src/main/java/com/rymcu/forest/core/exception/UltraViresException.java 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/core/exception/ContentNotExistException.java b/src/main/java/com/rymcu/forest/core/exception/ContentNotExistException.java new file mode 100644 index 0000000..4afaf5b --- /dev/null +++ b/src/main/java/com/rymcu/forest/core/exception/ContentNotExistException.java @@ -0,0 +1,24 @@ +package com.rymcu.forest.core.exception; + +public class ContentNotExistException extends RuntimeException{ + 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/DataDuplicationException.java b/src/main/java/com/rymcu/forest/core/exception/DataDuplicationException.java new file mode 100644 index 0000000..6d50510 --- /dev/null +++ b/src/main/java/com/rymcu/forest/core/exception/DataDuplicationException.java @@ -0,0 +1,25 @@ +package com.rymcu.forest.core.exception; + +public class DataDuplicationException extends RuntimeException { + + private static final long serialVersionUID = 3206744387536223284L; + + public DataDuplicationException() { + } + + public DataDuplicationException(String message) { + super(message); + } + + public DataDuplicationException(String message, Throwable cause) { + super(message, cause); + } + + public DataDuplicationException(Throwable cause) { + super(cause); + } + + public DataDuplicationException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} 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..6734208 --- /dev/null +++ b/src/main/java/com/rymcu/forest/core/exception/UltraViresException.java @@ -0,0 +1,26 @@ +package com.rymcu.forest.core.exception; + +public class UltraViresException extends RuntimeException { + + 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..baad171 100644 --- a/src/main/java/com/rymcu/forest/dto/ArticleDTO.java +++ b/src/main/java/com/rymcu/forest/dto/ArticleDTO.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 java.util.Date; @@ -11,13 +12,15 @@ import java.util.List; */ @Data 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..c43cc23 100644 --- a/src/main/java/com/rymcu/forest/dto/ArticleTagDTO.java +++ b/src/main/java/com/rymcu/forest/dto/ArticleTagDTO.java @@ -1,5 +1,6 @@ package com.rymcu.forest.dto; +import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; /** @@ -7,12 +8,13 @@ import lombok.Data; */ @Data 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 +24,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..c0c06f8 100644 --- a/src/main/java/com/rymcu/forest/dto/Author.java +++ b/src/main/java/com/rymcu/forest/dto/Author.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 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/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/UserDTO.java b/src/main/java/com/rymcu/forest/dto/UserDTO.java index 469a457..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; diff --git a/src/main/java/com/rymcu/forest/dto/UserInfoDTO.java b/src/main/java/com/rymcu/forest/dto/UserInfoDTO.java index aa1b041..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; 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/ArticleThumbsUp.java b/src/main/java/com/rymcu/forest/entity/ArticleThumbsUp.java index b7729dd..2d6f72a 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; @@ -29,7 +30,8 @@ public class ArticleThumbsUp implements Serializable, Cloneable { /** * 用户表主键 */ - private Integer idUser; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idUser; /** * 点赞时间 */ diff --git a/src/main/java/com/rymcu/forest/entity/BankAccount.java b/src/main/java/com/rymcu/forest/entity/BankAccount.java index 3c3374a..f7498a9 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; @@ -29,7 +30,8 @@ public class 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/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/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/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/Sponsor.java b/src/main/java/com/rymcu/forest/entity/Sponsor.java index a9eeaef..edb8b4a 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; @@ -28,11 +29,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/User.java b/src/main/java/com/rymcu/forest/entity/User.java index 642bc03..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; /** * 登录账号 diff --git a/src/main/java/com/rymcu/forest/entity/UserExtend.java b/src/main/java/com/rymcu/forest/entity/UserExtend.java index b4e339a..7df4944 100644 --- a/src/main/java/com/rymcu/forest/entity/UserExtend.java +++ b/src/main/java/com/rymcu/forest/entity/UserExtend.java @@ -13,7 +13,7 @@ import javax.persistence.Table; public class UserExtend { @Id - private Integer idUser; + private Long idUser; private String github; 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/impl/UserLuceneServiceImpl.java b/src/main/java/com/rymcu/forest/lucene/service/impl/UserLuceneServiceImpl.java index d88d557..4481e7f 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 @@ -161,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)) 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/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/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/RoleMapper.java b/src/main/java/com/rymcu/forest/mapper/RoleMapper.java index 813d7fd..89d2a4b 100644 --- a/src/main/java/com/rymcu/forest/mapper/RoleMapper.java +++ b/src/main/java/com/rymcu/forest/mapper/RoleMapper.java @@ -8,7 +8,7 @@ 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); 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..63a1500 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") Integer 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") Integer 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") Integer 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") Integer idTag, @Param("idUser") Long idUser, @Param("type") Integer type); /** * 删除未使用标签 diff --git a/src/main/java/com/rymcu/forest/mapper/UserMapper.java b/src/main/java/com/rymcu/forest/mapper/UserMapper.java index d2f42e8..2cdfef5 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") Integer 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); /** * 更新用户权限 @@ -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); /** * 根据昵称获取重名用户数量 @@ -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); /** * 更换邮箱 diff --git a/src/main/java/com/rymcu/forest/service/ArticleService.java b/src/main/java/com/rymcu/forest/service/ArticleService.java index 83174df..84f997f 100644 --- a/src/main/java/com/rymcu/forest/service/ArticleService.java +++ b/src/main/java/com/rymcu/forest/service/ArticleService.java @@ -29,7 +29,7 @@ public interface ArticleService extends Service
{ * @param type * @return * */ - ArticleDTO findArticleDTOById(Integer id, Integer type); + ArticleDTO findArticleDTOById(Long id, Integer type); /** * 查询主题下文章列表 @@ -50,7 +50,7 @@ public interface ArticleService extends Service
{ * @param idUser * @return * */ - List findUserArticlesByIdUser(Integer idUser); + List findUserArticlesByIdUser(Long idUser); /** * 新增/更新文章 @@ -60,7 +60,7 @@ public interface ArticleService extends Service
{ * @throws BaseApiException * @return * */ - Map postArticle(ArticleDTO article, HttpServletRequest request) throws UnsupportedEncodingException, BaseApiException; + Long postArticle(ArticleDTO article, HttpServletRequest request) throws UnsupportedEncodingException, BaseApiException; /** * 删除文章 @@ -68,13 +68,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,7 +82,7 @@ public interface ArticleService extends Service
{ * @throws BaseApiException * @return */ - Map share(Integer id) throws BaseApiException; + public String share(Integer id) throws BaseApiException; /** * 查询草稿文章类别 @@ -96,7 +96,7 @@ public interface ArticleService extends Service
{ * @param idPortfolio * @return */ - List findArticlesByIdPortfolio(Integer idPortfolio); + List findArticlesByIdPortfolio(Long idPortfolio); /** * 查询作品集下未绑定文章 @@ -105,7 +105,7 @@ public interface ArticleService extends Service
{ * @param idUser * @return */ - List selectUnbindArticles(Integer idPortfolio, String searchText, Integer idUser); + List selectUnbindArticles(Long idPortfolio, String searchText, Long idUser); /** * 更新文章标签 @@ -115,7 +115,7 @@ public interface ArticleService extends Service
{ * @throws UnsupportedEncodingException * @throws BaseApiException */ - Map updateTags(Integer idArticle, String tags) throws UnsupportedEncodingException, BaseApiException; + Boolean updateTags(Long idArticle, String tags) throws UnsupportedEncodingException, BaseApiException; /** * 更新文章优选状态 @@ -123,7 +123,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/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/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/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..13e83b8 100644 --- a/src/main/java/com/rymcu/forest/service/PortfolioService.java +++ b/src/main/java/com/rymcu/forest/service/PortfolioService.java @@ -27,7 +27,7 @@ public interface PortfolioService extends Service { * @param type * @return */ - PortfolioDTO findPortfolioDTOById(Integer idPortfolio, Integer type); + PortfolioDTO findPortfolioDTOById(Long idPortfolio, Integer type); /** * 保持/更新作品集 @@ -47,7 +47,7 @@ public interface PortfolioService extends Service { * @throws BaseApiException * @return */ - Map findUnbindArticles(Integer page, Integer rows, String searchText, Integer idPortfolio) throws BaseApiException; + Map findUnbindArticles(Integer page, Integer rows, String searchText, Long idPortfolio) throws BaseApiException; /** * 绑定文章 @@ -69,14 +69,14 @@ public interface PortfolioService extends Service { * @param idArticle * @return */ - Map unbindArticle(Integer idPortfolio, Integer idArticle); + Map unbindArticle(Long idPortfolio, Long idArticle); /** * 删除作品集 * @param idPortfolio * @return */ - Map deletePortfolio(Integer idPortfolio) throws BaseApiException; + Map deletePortfolio(Long idPortfolio) throws BaseApiException; /** * 获取作品集列表数据 diff --git a/src/main/java/com/rymcu/forest/service/RoleService.java b/src/main/java/com/rymcu/forest/service/RoleService.java index f5db02d..3afa2ce 100644 --- a/src/main/java/com/rymcu/forest/service/RoleService.java +++ b/src/main/java/com/rymcu/forest/service/RoleService.java @@ -27,7 +27,7 @@ public interface RoleService extends Service { * @param idUser * @return * */ - List findByIdUser(Integer idUser); + List findByIdUser(Long idUser); /** * 更新用户状态 diff --git a/src/main/java/com/rymcu/forest/service/TransactionRecordService.java b/src/main/java/com/rymcu/forest/service/TransactionRecordService.java index e5da803..6d8f7e0 100644 --- a/src/main/java/com/rymcu/forest/service/TransactionRecordService.java +++ b/src/main/java/com/rymcu/forest/service/TransactionRecordService.java @@ -36,7 +36,7 @@ public interface TransactionRecordService extends Service { * @return * @throws Exception */ - TransactionRecord userTransfer(Integer toUserId, Integer formUserId, TransactionEnum transactionType) throws Exception; + TransactionRecord userTransfer(Long toUserId, Long formUserId, TransactionEnum transactionType) throws Exception; /** * 社区银行转账/奖励发放 @@ -45,7 +45,7 @@ public interface TransactionRecordService extends Service { * @return * @throws Exception */ - TransactionRecord bankTransfer(Integer idUser, TransactionEnum transactionType) throws Exception; + TransactionRecord bankTransfer(Long idUser, TransactionEnum transactionType) throws Exception; /** * 发放新手奖励 diff --git a/src/main/java/com/rymcu/forest/service/UserService.java b/src/main/java/com/rymcu/forest/service/UserService.java index 161669b..fa6dbcb 100644 --- a/src/main/java/com/rymcu/forest/service/UserService.java +++ b/src/main/java/com/rymcu/forest/service/UserService.java @@ -71,7 +71,7 @@ public interface UserService extends Service { * @param status 状态 * @return Map * */ - Map updateStatus(Integer idUser, String status); + Map updateStatus(Long idUser, String status); /** * 获取用户信息 @@ -93,21 +93,21 @@ public interface UserService extends Service { * @param nickname * @return */ - Map checkNickname(Integer idUser, String nickname); + Map checkNickname(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); /** * 更新用户扩展信息 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..90b2c83 100644 --- a/src/main/java/com/rymcu/forest/service/impl/ArticleServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/ArticleServiceImpl.java @@ -1,6 +1,9 @@ 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.exception.DataDuplicationException; +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; @@ -68,7 +71,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 +93,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,16 +101,7 @@ 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, HttpServletRequest request) throws UnsupportedEncodingException, BaseApiException { boolean isUpdate = false; String articleTitle = article.getArticleTitle(); String articleTags = article.getArticleTags(); @@ -122,14 +116,14 @@ public class ArticleServiceImpl extends AbstractService
implements Arti 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 +134,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,38 +145,38 @@ 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()); + NotificationUtils.sendAnnouncement(newArticleId, 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()); + NotificationUtils.sendArticlePush(newArticleId, 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()); + NotificationUtils.sendArticlePush(newArticleId, NotificationConstant.PostArticle, dataSummary.toString(), newArticle.getArticleAuthorId()); } } // 草稿不更新索引 if (isUpdate) { - log.info("更新文章索引,id={}", newArticle.getIdArticle()); - luceneService.updateArticle(newArticle.getIdArticle().toString()); + log.info("更新文章索引,id={}", newArticleId); + luceneService.updateArticle(newArticleId.toString()); } else { - log.info("写入文章索引,id={}", newArticle.getIdArticle()); - luceneService.writeArticle(newArticle.getIdArticle().toString()); + log.info("写入文章索引,id={}", newArticleId); + luceneService.writeArticle(newArticleId.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); @@ -194,66 +188,24 @@ 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 ""; - } - // 判断是否存在系统配置的保留标签词 - 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); + int result = articleMapper.deleteByPrimaryKey(id); luceneService.deleteArticle(id.toString()); - if (result < 1) { - map.put("message", "删除失败!"); - } - } - return map; + return result; + } else throw new DataDuplicationException("已有评论的文章不允许删除!"); } - private void deleteLinkedData(Integer id) { + private void deleteLinkedData(Long id) { // 删除关联作品集 articleMapper.deleteLinkedPortfolioData(id); // 删除引用标签记录 @@ -266,22 +218,20 @@ 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 @@ -296,14 +246,14 @@ public class ArticleServiceImpl extends AbstractService
implements Arti } @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 +261,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) 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, ""); + 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 +328,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/BankAccountServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/BankAccountServiceImpl.java index 7bd4ba5..7ee2b2f 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"; @@ -79,7 +79,7 @@ public class BankAccountServiceImpl extends AbstractService impleme BankAccount bankAccount = new BankAccount(); bankAccount.setIdBank(1); bankAccount.setAccountType("1"); - bankAccount.setAccountOwner(2); + bankAccount.setAccountOwner(2L); return bankAccountMapper.selectOne(bankAccount); } 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/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..8e067bd 100644 --- a/src/main/java/com/rymcu/forest/service/impl/PortfolioServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/PortfolioServiceImpl.java @@ -4,7 +4,6 @@ import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; 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; @@ -53,7 +52,7 @@ public class PortfolioServiceImpl extends AbstractService implements } @Override - public PortfolioDTO findPortfolioDTOById(Integer idPortfolio, Integer type) { + public PortfolioDTO findPortfolioDTOById(Long idPortfolio, Integer type) { PortfolioDTO portfolio = portfolioMapper.selectPortfolioDTOById(idPortfolio,type); if (portfolio == null) { return new PortfolioDTO(); @@ -68,6 +67,7 @@ public class PortfolioServiceImpl extends AbstractService implements @Override public Portfolio postPortfolio(Portfolio portfolio) throws BaseApiException { User user = UserUtils.getCurrentUserByToken(); + assert user != null; if (StringUtils.isNotBlank(portfolio.getHeadImgType())) { String headImgUrl = UploadController.uploadBase64File(portfolio.getHeadImgUrl(), 0); portfolio.setHeadImgUrl(headImgUrl); @@ -98,7 +98,7 @@ public class PortfolioServiceImpl extends AbstractService implements } @Override - public Map findUnbindArticles(Integer page, Integer rows, String searchText, Integer idPortfolio) throws BaseApiException { + public Map findUnbindArticles(Integer page, Integer rows, String searchText, Long idPortfolio) throws BaseApiException { Map map = new HashMap(1); User user = UserUtils.getCurrentUserByToken(); Portfolio portfolio = portfolioMapper.selectByPrimaryKey(idPortfolio); @@ -153,7 +153,7 @@ public class PortfolioServiceImpl extends AbstractService implements } @Override - public Map unbindArticle(Integer idPortfolio, Integer idArticle) { + public Map unbindArticle(Long idPortfolio, Long idArticle) { Map map = new HashMap(1); if (idPortfolio == null || idPortfolio.equals(0)) { map.put("message", "作品集数据异常"); @@ -171,7 +171,7 @@ public class PortfolioServiceImpl extends AbstractService implements } @Override - public Map deletePortfolio(Integer idPortfolio) throws BaseApiException { + public Map deletePortfolio(Long idPortfolio) throws BaseApiException { Map map = new HashMap(1); if (idPortfolio == null || idPortfolio.equals(0)) { map.put("message", "作品集数据异常"); 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..7a0df7b 100644 --- a/src/main/java/com/rymcu/forest/service/impl/RoleServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/RoleServiceImpl.java @@ -32,7 +32,7 @@ public class RoleServiceImpl extends AbstractService implements RoleServic } @Override - public List findByIdUser(Integer idUser) { + public List findByIdUser(Long idUser) { return roleMapper.selectRoleByIdUser(idUser); } 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..c1f3837 100644 --- a/src/main/java/com/rymcu/forest/service/impl/TransactionRecordServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/TransactionRecordServiceImpl.java @@ -70,7 +70,7 @@ public class TransactionRecordServiceImpl extends AbstractService implements UserServic @Override @Transactional(rollbackFor = Exception.class) - public Map updateStatus(Integer idUser, String status) { + public Map updateStatus(Long idUser, String status) { Map map = new HashMap(2); Integer result = userMapper.updateStatus(idUser, status); if (result == 0) { @@ -231,7 +231,7 @@ public class UserServiceImpl extends AbstractService implements UserServic } @Override - public Map checkNickname(Integer idUser, String nickname) { + public Map checkNickname(Long idUser, String nickname) { Map map = new HashMap(2); Integer number = userMapper.checkNicknameByIdUser(idUser, nickname); if (number > 0) { @@ -241,12 +241,12 @@ public class UserServiceImpl extends AbstractService implements UserServic } @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); } 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..a8ec9f4 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 @@ -54,7 +54,7 @@ public class AdminController { } @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); } 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..8408da5 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 @@ -43,61 +43,52 @@ 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, HttpServletRequest request) throws BaseApiException, UnsupportedEncodingException { + return GlobalResultGenerator.genSuccessResult(articleService.postArticle(article, request)); } @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, HttpServletRequest request) throws BaseApiException, UnsupportedEncodingException { + return GlobalResultGenerator.genSuccessResult(articleService.postArticle(article, request)); } @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); + 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.genSuccessResult(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(); + return GlobalResultGenerator.genSuccessResult(articleService.updateTags(idArticle, articleTags)); } @PostMapping("/thumbs-up") 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..37f1d87 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 @@ -43,7 +43,7 @@ public class BankAccountController { } @GetMapping("/{idUser}") - public GlobalResult detail(@PathVariable Integer idUser) { + public GlobalResult detail(@PathVariable Long idUser) { BankAccountDTO bankAccount = bankAccountService.findBankAccountByIdUser(idUser); return GlobalResultGenerator.genSuccessResult(bankAccount); } 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..9714ee6 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,7 +33,7 @@ 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); } @@ -44,7 +44,7 @@ public class WalletController { 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); 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 490a1c8..1d31609 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 @@ -106,7 +106,7 @@ public class CommonApiController { @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); @@ -121,7 +121,7 @@ public class CommonApiController { @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); @@ -129,7 +129,7 @@ public class CommonApiController { } @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); 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..4150e3f 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 @@ -57,7 +57,7 @@ public class NotificationController { } @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..d81c7ef 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 @@ -26,7 +26,7 @@ public class PortfolioController { private PortfolioService portfolioService; @GetMapping("/detail/{idPortfolio}") - public GlobalResult detail(@PathVariable Integer idPortfolio,@RequestParam(defaultValue = "0") Integer type) { + public GlobalResult detail(@PathVariable Long idPortfolio,@RequestParam(defaultValue = "0") Integer type) { PortfolioDTO portfolio = portfolioService.findPortfolioDTOById(idPortfolio, type); Map map = new HashMap<>(1); map.put("portfolio", portfolio); @@ -48,7 +48,7 @@ public class PortfolioController { @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 { + public GlobalResult unbindArticles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, @RequestParam(defaultValue = "") String searchText,@PathVariable Long idPortfolio) throws BaseApiException { Map map = portfolioService.findUnbindArticles(page, rows, searchText, idPortfolio); return GlobalResultGenerator.genSuccessResult(map); } @@ -69,14 +69,14 @@ public class PortfolioController { @DeleteMapping("/unbind-article") @AuthorshipInterceptor(moduleName = Module.PORTFOLIO) - public GlobalResult unbindArticle(Integer idArticle,Integer idPortfolio) { + public GlobalResult unbindArticle(Long idArticle, Long idPortfolio) { Map map = portfolioService.unbindArticle(idPortfolio,idArticle); return GlobalResultGenerator.genSuccessResult(map); } @DeleteMapping("/delete") @AuthorshipInterceptor(moduleName = Module.PORTFOLIO) - public GlobalResult delete(Integer idPortfolio) throws BaseApiException { + public GlobalResult delete(Long idPortfolio) throws BaseApiException { Map map = portfolioService.deletePortfolio(idPortfolio); return GlobalResultGenerator.genSuccessResult(map); } 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..7a6f826 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 @@ -41,7 +41,7 @@ public class UserInfoController { @GetMapping("/check-nickname") @SecurityInterceptor - public GlobalResult checkNickname(@RequestParam Integer idUser, @RequestParam String nickname) { + public GlobalResult checkNickname(@RequestParam Long idUser, @RequestParam String nickname) { Map map = userService.checkNickname(idUser, nickname); return GlobalResultGenerator.genSuccessResult(map); } 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 @@ - + From 89aef7a87b2c1c3d24b03d2b9ca02b7494b03b1f Mon Sep 17 00:00:00 2001 From: ronger Date: Wed, 13 Jul 2022 22:21:33 +0800 Subject: [PATCH 08/25] =?UTF-8?q?:art:=20style(entity,dto,service,...):=20?= =?UTF-8?q?=E5=AE=9E=E4=BD=93=E7=AD=89pojo=E4=B8=BB=E9=94=AE=E5=8F=98?= =?UTF-8?q?=E4=B8=BALong=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/rymcu/forest/dto/TokenUser.java | 4 +++- src/main/java/com/rymcu/forest/entity/LoginRecord.java | 7 +++++-- src/main/java/com/rymcu/forest/entity/Visit.java | 7 +++++-- .../java/com/rymcu/forest/service/LoginRecordService.java | 2 +- .../rymcu/forest/service/impl/LoginRecordServiceImpl.java | 2 +- .../rymcu/forest/web/api/common/CommonApiController.java | 6 ++---- 6 files changed, 17 insertions(+), 11 deletions(-) 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/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/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/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/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/web/api/common/CommonApiController.java b/src/main/java/com/rymcu/forest/web/api/common/CommonApiController.java index 1d31609..0ad2e31 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 @@ -106,11 +106,9 @@ public class CommonApiController { @GetMapping("/article/{id}") @VisitLogger - public GlobalResult> article(@PathVariable Long 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") From 15e82e3ded86fc922d31c90e1bb989a8657b98b3 Mon Sep 17 00:00:00 2001 From: ronger Date: Fri, 22 Jul 2022 21:52:31 +0800 Subject: [PATCH 09/25] =?UTF-8?q?:art:=20=E4=BF=AE=E6=94=B9=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E6=8E=A5=E5=8F=A3=E7=BB=9F=E4=B8=80=E8=BF=94=E5=9B=9E?= =?UTF-8?q?=20PageInfo=20=E5=AF=B9=E8=B1=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lucene/api/LuceneSearchController.java | 6 +- .../forest/web/api/admin/AdminController.java | 76 +++++++------------ .../admin/AdminCurrencyRuleController.java | 8 +- .../web/api/admin/DashboardController.java | 27 ++----- .../web/api/bank/BankAccountController.java | 21 ++--- .../forest/web/api/bank/BankController.java | 8 +- .../forest/web/api/bank/WalletController.java | 10 +-- .../web/api/common/CommonApiController.java | 31 +++----- .../notification/NotificationController.java | 10 +-- .../forest/web/api/tag/TagController.java | 5 +- .../forest/web/api/topic/TopicController.java | 5 +- .../forest/web/api/user/UserController.java | 31 +++----- 12 files changed, 75 insertions(+), 163 deletions(-) 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..9717152 100755 --- a/src/main/java/com/rymcu/forest/lucene/api/LuceneSearchController.java +++ b/src/main/java/com/rymcu/forest/lucene/api/LuceneSearchController.java @@ -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); } /** @@ -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); } /** @@ -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/web/api/admin/AdminController.java b/src/main/java/com/rymcu/forest/web/api/admin/AdminController.java index a8ec9f4..05875d5 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 @@ -40,17 +40,15 @@ 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") @@ -60,15 +58,11 @@ public class AdminController { } @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") @@ -102,15 +96,11 @@ public class AdminController { } @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}") @@ -138,17 +128,13 @@ public class AdminController { } @GetMapping("/topic/unbind-topic-tags") - public GlobalResult unbindTopicTags(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, HttpServletRequest request){ + public GlobalResult> unbindTopicTags(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, HttpServletRequest request){ Integer idTopic = Integer.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") @@ -176,19 +162,15 @@ public class AdminController { } @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(){ + public GlobalResult cleanUnusedTag(){ Map map = tagService.cleanUnusedTag(); return GlobalResultGenerator.genSuccessResult(map); } @@ -212,39 +194,35 @@ public class AdminController { } @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 index 8c1ce41..39cf31a 100644 --- a/src/main/java/com/rymcu/forest/web/api/admin/AdminCurrencyRuleController.java +++ b/src/main/java/com/rymcu/forest/web/api/admin/AdminCurrencyRuleController.java @@ -32,15 +32,11 @@ public class AdminCurrencyRuleController { private CurrencyRuleService currencyRuleService; @GetMapping("/list") - public GlobalResult list(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "20") Integer rows, HttpServletRequest request) { + public GlobalResult> list(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "20") Integer rows, HttpServletRequest request) { PageHelper.startPage(page, rows); List list = currencyRuleService.findAll(); - Map map = new HashMap(2); PageInfo pageInfo = new PageInfo(list); - map.put("rules", 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/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/bank/BankAccountController.java b/src/main/java/com/rymcu/forest/web/api/bank/BankAccountController.java index 37f1d87..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 Long 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/WalletController.java b/src/main/java/com/rymcu/forest/web/api/bank/WalletController.java index 9714ee6..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,14 +33,14 @@ public class WalletController { @GetMapping("/{idUser}") @SecurityInterceptor - public GlobalResult detail(@PathVariable Long 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"); @@ -48,10 +48,6 @@ public class WalletController { 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/common/CommonApiController.java b/src/main/java/com/rymcu/forest/web/api/common/CommonApiController.java index 0ad2e31..5f1ed82 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 @@ -87,21 +87,19 @@ 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); + 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); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/article/{id}") @@ -127,36 +125,27 @@ public class CommonApiController { } @GetMapping("/portfolio/{id}/articles") - public GlobalResult articles(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows, @PathVariable Long 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); + 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); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/products") - public GlobalResult products(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "12") Integer rows) { + 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); - Map map = new HashMap(2); - map.put("products", pageInfo.getList()); - Map pagination = Utils.getPagination(pageInfo); - map.put("pagination", pagination); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/product/{id}") 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 4150e3f..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,8 +51,7 @@ 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}") 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); } From 35cc83ec00e3d061054915ecea7f149f7cdd171b Mon Sep 17 00:00:00 2001 From: ronger Date: Mon, 25 Jul 2022 06:43:13 +0800 Subject: [PATCH 10/25] =?UTF-8?q?:art:=20style(entity,dto,service,...):=20?= =?UTF-8?q?=E5=AE=9E=E4=BD=93=E7=AD=89pojo=E4=B8=BB=E9=94=AE=E5=8F=98?= =?UTF-8?q?=E4=B8=BALong=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/rymcu/forest/dto/ChangeEmailDTO.java | 4 +++- .../java/com/rymcu/forest/dto/UpdatePasswordDTO.java | 4 +++- .../java/com/rymcu/forest/dto/admin/TopicTagDTO.java | 7 +++++-- .../java/com/rymcu/forest/dto/admin/UserRoleDTO.java | 8 ++++++-- .../java/com/rymcu/forest/entity/ArticleContent.java | 4 +++- .../java/com/rymcu/forest/entity/ArticleThumbsUp.java | 6 ++++-- src/main/java/com/rymcu/forest/entity/Bank.java | 9 ++++++--- src/main/java/com/rymcu/forest/entity/BankAccount.java | 6 ++++-- .../java/com/rymcu/forest/entity/CurrencyIssue.java | 7 +++++-- .../java/com/rymcu/forest/entity/CurrencyRule.java | 4 +++- src/main/java/com/rymcu/forest/entity/Permission.java | 4 +++- src/main/java/com/rymcu/forest/entity/Product.java | 4 +++- .../java/com/rymcu/forest/entity/ProductContent.java | 4 +++- src/main/java/com/rymcu/forest/entity/Role.java | 4 +++- src/main/java/com/rymcu/forest/entity/SpecialDay.java | 4 +++- src/main/java/com/rymcu/forest/entity/Sponsor.java | 3 ++- src/main/java/com/rymcu/forest/entity/Tag.java | 4 +++- src/main/java/com/rymcu/forest/entity/Topic.java | 4 +++- .../com/rymcu/forest/entity/TransactionRecord.java | 4 +++- src/main/java/com/rymcu/forest/entity/UserExtend.java | 2 ++ src/main/java/com/rymcu/forest/entity/WxUser.java | 4 +++- .../com/rymcu/forest/mapper/ArticleThumbsUpMapper.java | 2 +- .../com/rymcu/forest/mapper/BankAccountMapper.java | 2 +- .../java/com/rymcu/forest/mapper/PermissionMapper.java | 2 +- src/main/java/com/rymcu/forest/mapper/RoleMapper.java | 4 ++-- src/main/java/com/rymcu/forest/mapper/TagMapper.java | 10 +++++----- src/main/java/com/rymcu/forest/mapper/TopicMapper.java | 8 ++++---- src/main/java/com/rymcu/forest/mapper/UserMapper.java | 10 +++++----- .../java/com/rymcu/forest/service/RoleService.java | 2 +- .../java/com/rymcu/forest/service/TopicService.java | 2 +- .../java/com/rymcu/forest/service/UserService.java | 4 ++-- .../forest/service/impl/BankAccountServiceImpl.java | 4 ++-- .../com/rymcu/forest/service/impl/RoleServiceImpl.java | 2 +- .../rymcu/forest/service/impl/TopicServiceImpl.java | 2 +- .../com/rymcu/forest/service/impl/UserServiceImpl.java | 6 +++--- .../rymcu/forest/web/api/admin/AdminController.java | 2 +- .../rymcu/forest/web/api/user/UserInfoController.java | 2 +- 37 files changed, 105 insertions(+), 59 deletions(-) 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/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/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/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 2d6f72a..3ff6332 100644 --- a/src/main/java/com/rymcu/forest/entity/ArticleThumbsUp.java +++ b/src/main/java/com/rymcu/forest/entity/ArticleThumbsUp.java @@ -22,11 +22,13 @@ 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; /** * 用户表主键 */ 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 f7498a9..c6a3a85 100644 --- a/src/main/java/com/rymcu/forest/entity/BankAccount.java +++ b/src/main/java/com/rymcu/forest/entity/BankAccount.java @@ -22,9 +22,11 @@ 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; /** 账户余额 */ 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/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/Product.java b/src/main/java/com/rymcu/forest/entity/Product.java index fdbcf6c..88c670d 100644 --- a/src/main/java/com/rymcu/forest/entity/Product.java +++ b/src/main/java/com/rymcu/forest/entity/Product.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; @@ -26,7 +27,8 @@ public class Product implements Serializable, Cloneable { @Id @GeneratedValue(generator = "JDBC") @Column(name = "id") - private Integer idProduct; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idProduct; /** * 产品名 */ diff --git a/src/main/java/com/rymcu/forest/entity/ProductContent.java b/src/main/java/com/rymcu/forest/entity/ProductContent.java index deafecd..70d2066 100644 --- a/src/main/java/com/rymcu/forest/entity/ProductContent.java +++ b/src/main/java/com/rymcu/forest/entity/ProductContent.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.Table; @@ -20,7 +21,8 @@ public class ProductContent implements Serializable, Cloneable { /** * 产品表主键 */ - private Integer idProduct; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long idProduct; /** * 产品详情原文 */ 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 edb8b4a..1dbb03f 100644 --- a/src/main/java/com/rymcu/forest/entity/Sponsor.java +++ b/src/main/java/com/rymcu/forest/entity/Sponsor.java @@ -21,7 +21,8 @@ public class Sponsor implements Serializable, Cloneable { */ @Id @GeneratedValue(generator = "JDBC") - private Integer id; + @JsonFormat(shape = JsonFormat.Shape.STRING) + private Long id; /** * 数据类型 */ 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/UserExtend.java b/src/main/java/com/rymcu/forest/entity/UserExtend.java index 7df4944..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,6 +14,7 @@ import javax.persistence.Table; public class UserExtend { @Id + @JsonFormat(shape = JsonFormat.Shape.STRING) private Long idUser; private String github; 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/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..151905b 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); /** * 获取当前最大卡号 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/RoleMapper.java b/src/main/java/com/rymcu/forest/mapper/RoleMapper.java index 89d2a4b..8f9fab3 100644 --- a/src/main/java/com/rymcu/forest/mapper/RoleMapper.java +++ b/src/main/java/com/rymcu/forest/mapper/RoleMapper.java @@ -12,7 +12,7 @@ public interface RoleMapper extends Mapper { 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/TagMapper.java b/src/main/java/com/rymcu/forest/mapper/TagMapper.java index 63a1500..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") Long 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") Long 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") Long 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") Long 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 2cdfef5..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") Long idUser, @Param("idRole") Integer idRole); + Integer insertUserRole(@Param("idUser") Long idUser, @Param("idRole") Long idRole); /** * 根据账号获取获取用户信息 @@ -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); /** * 更新用户状态 @@ -87,7 +87,7 @@ public interface UserMapper extends Mapper { * @param idUser * @return */ - UserInfoDTO selectUserInfo(@Param("idUser") Integer idUser); + UserInfoDTO selectUserInfo(@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/RoleService.java b/src/main/java/com/rymcu/forest/service/RoleService.java index 3afa2ce..a63ae5e 100644 --- a/src/main/java/com/rymcu/forest/service/RoleService.java +++ b/src/main/java/com/rymcu/forest/service/RoleService.java @@ -35,7 +35,7 @@ public interface RoleService extends Service { * @param status * @return * */ - Map updateStatus(Integer idRole, String status); + Map updateStatus(Long idRole, String status); /** * 添加/更新角色 diff --git a/src/main/java/com/rymcu/forest/service/TopicService.java b/src/main/java/com/rymcu/forest/service/TopicService.java index 4fda791..2e4a04a 100644 --- a/src/main/java/com/rymcu/forest/service/TopicService.java +++ b/src/main/java/com/rymcu/forest/service/TopicService.java @@ -39,7 +39,7 @@ public interface TopicService extends Service { * @param tagTitle * @return */ - List findUnbindTagsById(Integer idTopic, String tagTitle); + List findUnbindTagsById(Long idTopic, String tagTitle); /** * 绑定标签 diff --git a/src/main/java/com/rymcu/forest/service/UserService.java b/src/main/java/com/rymcu/forest/service/UserService.java index fa6dbcb..04e7665 100644 --- a/src/main/java/com/rymcu/forest/service/UserService.java +++ b/src/main/java/com/rymcu/forest/service/UserService.java @@ -63,7 +63,7 @@ public interface UserService extends Service { * @param idRole 角色 id * @return Map * */ - Map updateUserRole(Integer idUser, Integer idRole); + Map updateUserRole(Long idUser, Long idRole); /** * 更新用户状态 @@ -78,7 +78,7 @@ public interface UserService extends Service { * @param idUser * @return */ - Map findUserInfo(Integer idUser); + Map findUserInfo(Long idUser); /** * 更新用户信息 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 7ee2b2f..960c592 100644 --- a/src/main/java/com/rymcu/forest/service/impl/BankAccountServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/BankAccountServiceImpl.java @@ -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,7 +77,7 @@ 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(2L); return bankAccountMapper.selectOne(bankAccount); 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 7a0df7b..e7fec58 100644 --- a/src/main/java/com/rymcu/forest/service/impl/RoleServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/RoleServiceImpl.java @@ -38,7 +38,7 @@ public class RoleServiceImpl extends AbstractService implements RoleServic @Override @Transactional - public Map updateStatus(Integer idRole, String status) { + public Map updateStatus(Long idRole, String status) { Map map = new HashMap(1); Integer result = roleMapper.updateStatus(idRole,status); if(result == 0) { 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..b514a96 100644 --- a/src/main/java/com/rymcu/forest/service/impl/TopicServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/TopicServiceImpl.java @@ -101,7 +101,7 @@ public class TopicServiceImpl extends AbstractService implements TopicSer } @Override - public List findUnbindTagsById(Integer idTopic, String tagTitle) { + public List findUnbindTagsById(Long idTopic, String tagTitle) { if (StringUtils.isBlank(tagTitle)) { tagTitle = ""; } diff --git a/src/main/java/com/rymcu/forest/service/impl/UserServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/UserServiceImpl.java index 455cd0f..932786c 100644 --- a/src/main/java/com/rymcu/forest/service/impl/UserServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/UserServiceImpl.java @@ -158,7 +158,7 @@ public class UserServiceImpl extends AbstractService implements UserServic @Override @Transactional(rollbackFor = Exception.class) - public Map updateUserRole(Integer idUser, Integer idRole) { + public Map updateUserRole(Long idUser, Long idRole) { Map map = new HashMap(2); Integer result = userMapper.updateUserRole(idUser, idRole); if (result == 0) { @@ -179,7 +179,7 @@ public class UserServiceImpl extends AbstractService implements UserServic } @Override - public Map findUserInfo(Integer idUser) { + public Map findUserInfo(Long idUser) { Map map = new HashMap(2); UserInfoDTO user = userMapper.selectUserInfo(idUser); if (user == null) { @@ -271,7 +271,7 @@ public class UserServiceImpl extends AbstractService implements UserServic public Map updateEmail(ChangeEmailDTO changeEmailDTO) { Map map = new HashMap(2); map.put("message", "验证码无效!"); - Integer idUser = changeEmailDTO.getIdUser(); + Long idUser = changeEmailDTO.getIdUser(); String email = changeEmailDTO.getEmail(); String code = changeEmailDTO.getCode(); String vCode = redisService.get(email); 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 05875d5..214400c 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 @@ -129,7 +129,7 @@ public class AdminController { @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")); + Long idTopic = Long.valueOf(request.getParameter("idTopic")); String tagTitle = request.getParameter("tagTitle"); PageHelper.startPage(page, rows); List list = topicService.findUnbindTagsById(idTopic, tagTitle); 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 7a6f826..204b357 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 @@ -34,7 +34,7 @@ public class UserInfoController { @GetMapping("/detail/{idUser}") @SecurityInterceptor - public GlobalResult detail(@PathVariable Integer idUser) { + public GlobalResult detail(@PathVariable Long idUser) { Map map = userService.findUserInfo(idUser); return GlobalResultGenerator.genSuccessResult(map); } From ff187244327e22e4145a20d52ae1d4797fbb04be Mon Sep 17 00:00:00 2001 From: ronger Date: Mon, 1 Aug 2022 21:47:32 +0800 Subject: [PATCH 11/25] =?UTF-8?q?:art:=20=E7=BB=9F=E4=B8=80=E5=BC=82?= =?UTF-8?q?=E5=B8=B8=E5=A4=84=E7=90=86=E5=A2=9E=E5=8A=A0=20DataDuplication?= =?UTF-8?q?Exception=20=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/rymcu/forest/config/BaseExceptionHandler.java | 7 +++++++ .../forest/core/exception/DataDuplicationException.java | 3 +++ 2 files changed, 10 insertions(+) diff --git a/src/main/java/com/rymcu/forest/config/BaseExceptionHandler.java b/src/main/java/com/rymcu/forest/config/BaseExceptionHandler.java index 632a1ad..ee053fd 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.DataDuplicationException; 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 DataDuplicationException) { + 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 DataDuplicationException) { + 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/core/exception/DataDuplicationException.java b/src/main/java/com/rymcu/forest/core/exception/DataDuplicationException.java index 6d50510..0e5faa2 100644 --- a/src/main/java/com/rymcu/forest/core/exception/DataDuplicationException.java +++ b/src/main/java/com/rymcu/forest/core/exception/DataDuplicationException.java @@ -1,5 +1,8 @@ package com.rymcu.forest.core.exception; +/** + * @author KKould + */ public class DataDuplicationException extends RuntimeException { private static final long serialVersionUID = 3206744387536223284L; From 280fac5c1036127e7e313bcdd18785c89c37845f Mon Sep 17 00:00:00 2001 From: ronger Date: Mon, 1 Aug 2022 22:15:25 +0800 Subject: [PATCH 12/25] =?UTF-8?q?:bug:=20=E6=97=A0=E6=B3=95=E5=88=86?= =?UTF-8?q?=E4=BA=AB=E6=96=87=E7=AB=A0=E9=97=AE=E9=A2=98=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/rymcu/forest/web/api/article/ArticleController.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) 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 8408da5..6fa41a1 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 @@ -15,14 +15,12 @@ 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.web.api.exception.BaseApiException; 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; @@ -80,7 +78,7 @@ public class ArticleController { @GetMapping("/{idArticle}/share") public GlobalResult share(@PathVariable Integer idArticle) throws BaseApiException { - return GlobalResultGenerator.genSuccessResult(articleService.share(idArticle)); + return GlobalResultGenerator.genResult(true, articleService.share(idArticle), ""); } @PostMapping("/update-tags") From bc395e29979df74a60c5750d8ff8b4bed0352483 Mon Sep 17 00:00:00 2001 From: ronger Date: Mon, 1 Aug 2022 22:16:08 +0800 Subject: [PATCH 13/25] =?UTF-8?q?:art:=20style(entity,dto,service,...):=20?= =?UTF-8?q?=E5=AE=9E=E4=BD=93=E7=AD=89pojo=E4=B8=BB=E9=94=AE=E5=8F=98?= =?UTF-8?q?=E4=B8=BALong=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../forest/lucene/api/LuceneSearchController.java | 6 +++--- .../forest/lucene/mapper/ArticleLuceneMapper.java | 4 ++-- .../forest/lucene/mapper/PortfolioLuceneMapper.java | 4 ++-- .../rymcu/forest/lucene/mapper/UserLuceneMapper.java | 2 +- .../com/rymcu/forest/lucene/model/ArticleLucene.java | 4 +++- .../rymcu/forest/lucene/model/PortfolioLucene.java | 4 +++- .../rymcu/forest/lucene/service/LuceneService.java | 8 ++++---- .../lucene/service/PortfolioLuceneService.java | 8 ++++---- .../forest/lucene/service/UserLuceneService.java | 2 +- .../lucene/service/impl/LuceneServiceImpl.java | 12 ++++++------ .../service/impl/PortfolioLuceneServiceImpl.java | 12 ++++++------ .../lucene/service/impl/UserLuceneServiceImpl.java | 2 +- .../rymcu/forest/lucene/util/ArticleIndexUtil.java | 4 ++-- .../rymcu/forest/lucene/util/PortfolioIndexUtil.java | 4 ++-- .../com/rymcu/forest/service/ArticleService.java | 2 +- .../forest/service/impl/ArticleServiceImpl.java | 10 ++++++---- .../forest/service/impl/PortfolioServiceImpl.java | 6 +++--- src/main/java/mapper/lucene/UserLuceneMapper.xml | 2 +- 18 files changed, 51 insertions(+), 45 deletions(-) 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 9717152..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; // 写入文章关键词信息 @@ -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; // 写入文章关键词信息 @@ -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; // 写入文章关键词信息 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/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 9790111..64c0bba 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 @@ -94,7 +94,7 @@ public class LuceneServiceImpl implements LuceneService { } @Override - public void writeArticle(String id) { + public void writeArticle(Long id) { writeArticle(luceneMapper.getById(id)); } @@ -104,12 +104,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); } @@ -181,7 +181,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)) @@ -205,9 +205,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 bec4e2f..964ac3c 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 @@ -83,7 +83,7 @@ public class PortfolioLuceneServiceImpl implements PortfolioLuceneService { } @Override - public void writePortfolio(String id) { + public void writePortfolio(Long id) { writePortfolio(portfolioLuceneMapper.getById(id)); } @@ -94,12 +94,12 @@ public class PortfolioLuceneServiceImpl implements PortfolioLuceneService { @Override - public void updatePortfolio(String id) { + public void updatePortfolio(Long id) { PortfolioIndexUtil.updateIndex(portfolioLuceneMapper.getById(id)); } @Override - public void deletePortfolio(String id) { + public void deletePortfolio(Long id) { PortfolioIndexUtil.deleteIndex(id); } @@ -109,7 +109,7 @@ public class PortfolioLuceneServiceImpl implements PortfolioLuceneService { } @Override - public List getPortfoliosByIds(String[] ids) { + public List getPortfoliosByIds(Long[] ids) { return portfolioLuceneMapper.getPortfoliosByIds(ids); } @@ -156,7 +156,7 @@ public class PortfolioLuceneServiceImpl implements PortfolioLuceneService { if ((textFragment != null) && (textFragment.getScore() > 0)) { // if ((frag[j] != null)) { // 获取 summary 的值 - sb.append(textFragment.toString()); + sb.append(textFragment); } } // 获取到title @@ -172,7 +172,7 @@ public class PortfolioLuceneServiceImpl implements PortfolioLuceneService { } resList.add( PortfolioLucene.builder() - .idPortfolio(hitDoc.get("id")) + .idPortfolio(Long.valueOf(hitDoc.get("id"))) .portfolioTitle(titleValue.toString()) .portfolioDescription(sb.toString()) .score(String.valueOf(score)) 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 4481e7f..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 @@ -182,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..ecbf6f4 100644 --- a/src/main/java/com/rymcu/forest/lucene/util/ArticleIndexUtil.java +++ b/src/main/java/com/rymcu/forest/lucene/util/ArticleIndexUtil.java @@ -63,7 +63,7 @@ public class ArticleIndexUtil { } /** 删除单个索引 */ - 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 ArticleIndexUtil { 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/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/service/ArticleService.java b/src/main/java/com/rymcu/forest/service/ArticleService.java index 84f997f..f483229 100644 --- a/src/main/java/com/rymcu/forest/service/ArticleService.java +++ b/src/main/java/com/rymcu/forest/service/ArticleService.java @@ -82,7 +82,7 @@ public interface ArticleService extends Service
{ * @throws BaseApiException * @return */ - public String share(Integer id) throws BaseApiException; + String share(Integer id) throws BaseApiException; /** * 查询草稿文章类别 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 90b2c83..dc7c9ad 100644 --- a/src/main/java/com/rymcu/forest/service/impl/ArticleServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/ArticleServiceImpl.java @@ -165,10 +165,10 @@ public class ArticleServiceImpl extends AbstractService
implements Arti // 草稿不更新索引 if (isUpdate) { log.info("更新文章索引,id={}", newArticleId); - luceneService.updateArticle(newArticleId.toString()); + luceneService.updateArticle(newArticleId); } else { log.info("写入文章索引,id={}", newArticleId); - luceneService.writeArticle(newArticleId.toString()); + luceneService.writeArticle(newArticleId); } // 更新文章链接 newArticle.setArticlePermalink(domain + "/article/" + newArticleId); @@ -200,9 +200,11 @@ public class ArticleServiceImpl extends AbstractService
implements Arti deleteLinkedData(id); // 删除文章 int result = articleMapper.deleteByPrimaryKey(id); - luceneService.deleteArticle(id.toString()); + luceneService.deleteArticle(id); return result; - } else throw new DataDuplicationException("已有评论的文章不允许删除!"); + } else { + throw new DataDuplicationException("已有评论的文章不允许删除!"); + } } private void deleteLinkedData(Long id) { 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 8e067bd..bb6d2b7 100644 --- a/src/main/java/com/rymcu/forest/service/impl/PortfolioServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/PortfolioServiceImpl.java @@ -80,7 +80,7 @@ public class PortfolioServiceImpl extends AbstractService implements portfolioMapper.insertSelective(portfolio); PortfolioIndexUtil.addIndex( PortfolioLucene.builder() - .idPortfolio(portfolio.getIdPortfolio().toString()) + .idPortfolio(portfolio.getIdPortfolio()) .portfolioTitle(portfolio.getPortfolioTitle()) .portfolioDescription(portfolio.getPortfolioDescription()) .build()); @@ -89,7 +89,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()); @@ -195,7 +195,7 @@ public class PortfolioServiceImpl extends AbstractService implements if (result.equals(0)) { map.put("message", "操作失败!"); }else { - PortfolioIndexUtil.deleteIndex(String.valueOf(idPortfolio)); + PortfolioIndexUtil.deleteIndex(idPortfolio); } } diff --git a/src/main/java/mapper/lucene/UserLuceneMapper.xml b/src/main/java/mapper/lucene/UserLuceneMapper.xml index 5c0be15..31cb8f9 100644 --- a/src/main/java/mapper/lucene/UserLuceneMapper.xml +++ b/src/main/java/mapper/lucene/UserLuceneMapper.xml @@ -36,7 +36,7 @@ From a907571ac6d23866d3614d3d68ed05dcac0f4264 Mon Sep 17 00:00:00 2001 From: "kould.li" Date: Thu, 4 Aug 2022 15:51:09 +0800 Subject: [PATCH 14/25] =?UTF-8?q?feat(test):=20=E6=96=B0=E5=A2=9EArticleSe?= =?UTF-8?q?rvice=E9=83=A8=E5=88=86=E5=8D=95=E5=85=83=E6=B5=8B=E8=AF=95,?= =?UTF-8?q?=E9=83=A8=E5=88=86=E5=8A=9F=E8=83=BD=E4=BC=98=E5=8C=96,sql?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E6=96=B0=E5=A2=9E=E6=B5=8B=E8=AF=95=E6=95=B0?= =?UTF-8?q?=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 涵盖ArticleService单元测试方法: postArticle findArticles findArticleDTOById findUserArticlesByIdUser incrementArticleViewCount updatePerfect delete ArticleService将用户获取逻辑转移到Controller中 sql文件新增用户测试数据 --- pom.xml | 5 + .../java/com/rymcu/forest/dto/ArticleDTO.java | 6 + .../com/rymcu/forest/dto/ArticleTagDTO.java | 6 + .../java/com/rymcu/forest/dto/Author.java | 6 + .../service/impl/LuceneServiceImpl.java | 3 +- .../impl/PortfolioLuceneServiceImpl.java | 3 +- .../forest/lucene/util/ArticleIndexUtil.java | 3 + .../rymcu/forest/service/ArticleService.java | 13 +- .../com/rymcu/forest/service/TagService.java | 2 +- .../service/impl/ArticleServiceImpl.java | 20 +- .../forest/service/impl/TagServiceImpl.java | 9 +- .../web/api/article/ArticleController.java | 30 ++- src/main/resources/static/forest.sql | 4 + .../forest/service/ArticleServiceTest.java | 229 ++++++++++++++++++ 14 files changed, 303 insertions(+), 36 deletions(-) create mode 100644 src/test/java/com/rymcu/forest/service/ArticleServiceTest.java diff --git a/pom.xml b/pom.xml index 336080b..cb92596 100644 --- a/pom.xml +++ b/pom.xml @@ -292,6 +292,11 @@ + + junit + junit + test + diff --git a/src/main/java/com/rymcu/forest/dto/ArticleDTO.java b/src/main/java/com/rymcu/forest/dto/ArticleDTO.java index baad171..4b7e370 100644 --- a/src/main/java/com/rymcu/forest/dto/ArticleDTO.java +++ b/src/main/java/com/rymcu/forest/dto/ArticleDTO.java @@ -2,7 +2,10 @@ 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; @@ -11,6 +14,9 @@ import java.util.List; * @author ronger */ @Data +@Builder +@NoArgsConstructor +@AllArgsConstructor public class ArticleDTO { @JsonFormat(shape = JsonFormat.Shape.STRING) private Long idArticle; diff --git a/src/main/java/com/rymcu/forest/dto/ArticleTagDTO.java b/src/main/java/com/rymcu/forest/dto/ArticleTagDTO.java index c43cc23..44585b2 100644 --- a/src/main/java/com/rymcu/forest/dto/ArticleTagDTO.java +++ b/src/main/java/com/rymcu/forest/dto/ArticleTagDTO.java @@ -1,12 +1,18 @@ 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 { @JsonFormat(shape = JsonFormat.Shape.STRING) private Long idArticleTag; diff --git a/src/main/java/com/rymcu/forest/dto/Author.java b/src/main/java/com/rymcu/forest/dto/Author.java index c0c06f8..a15cc53 100644 --- a/src/main/java/com/rymcu/forest/dto/Author.java +++ b/src/main/java/com/rymcu/forest/dto/Author.java @@ -1,12 +1,18 @@ 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 { @JsonFormat(shape = JsonFormat.Shape.STRING) 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 64c0bba..8d8b8d3 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 @@ -65,7 +65,8 @@ public class LuceneServiceImpl implements LuceneService { try { int totalCount = list.size(); int perThreadCount = 3000; - int threadCount = totalCount / perThreadCount + (totalCount % perThreadCount == 0 ? 0 : 1); + // 加1避免线程池的参数为0 + int threadCount = totalCount / perThreadCount + (totalCount % perThreadCount == 0 ? 0 : 1) + 1; ExecutorService pool = Executors.newFixedThreadPool(threadCount); CountDownLatch countDownLatch1 = new CountDownLatch(1); CountDownLatch countDownLatch2 = new CountDownLatch(threadCount); 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 964ac3c..4d35c34 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 @@ -55,7 +55,8 @@ public class PortfolioLuceneServiceImpl implements PortfolioLuceneService { try { int totalCount = list.size(); int perThreadCount = 3000; - int threadCount = totalCount / perThreadCount + (totalCount % perThreadCount == 0 ? 0 : 1); + // 加1避免线程池的参数为0 + int threadCount = totalCount / perThreadCount + (totalCount % perThreadCount == 0 ? 0 : 1) + 1; ExecutorService pool = Executors.newFixedThreadPool(threadCount); CountDownLatch countDownLatch1 = new CountDownLatch(1); CountDownLatch countDownLatch2 = new CountDownLatch(threadCount); 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 ecbf6f4..9b3880e 100644 --- a/src/main/java/com/rymcu/forest/lucene/util/ArticleIndexUtil.java +++ b/src/main/java/com/rymcu/forest/lucene/util/ArticleIndexUtil.java @@ -24,6 +24,9 @@ public class ArticleIndexUtil { private static final String PATH = System.getProperty("user.dir") + StrUtil.SLASH + LucenePath.ARTICLE_INDEX_PATH; + private static final String WINDOW_PATH = + System.getProperty("user.dir") + StrUtil.BACKSLASH + "lucene\\index\\article"; + /** 删除所有运行中保存的索引 */ public static void deleteAllIndex() { if (FileUtil.exist(LucenePath.ARTICLE_INCREMENT_INDEX_PATH)) { diff --git a/src/main/java/com/rymcu/forest/service/ArticleService.java b/src/main/java/com/rymcu/forest/service/ArticleService.java index f483229..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 @@ -55,12 +54,12 @@ public interface ArticleService extends Service
{ /** * 新增/更新文章 * @param article - * @param request + * @param user * @throws UnsupportedEncodingException * @throws BaseApiException * @return * */ - Long postArticle(ArticleDTO article, HttpServletRequest request) throws UnsupportedEncodingException, BaseApiException; + Long postArticle(ArticleDTO article, User user) throws UnsupportedEncodingException, BaseApiException; /** * 删除文章 @@ -86,10 +85,9 @@ public interface ArticleService extends Service
{ /** * 查询草稿文章类别 - * @throws BaseApiException * @return */ - List findDrafts() throws BaseApiException; + List findDrafts(Long userId); /** * 查询作品集下文章 @@ -111,11 +109,12 @@ public interface ArticleService extends Service
{ * 更新文章标签 * @param idArticle * @param tags + * @param userId * @return * @throws UnsupportedEncodingException * @throws BaseApiException */ - Boolean updateTags(Long idArticle, String tags) throws UnsupportedEncodingException, BaseApiException; + Boolean updateTags(Long idArticle, String tags, Long userId) throws UnsupportedEncodingException, BaseApiException; /** * 更新文章优选状态 diff --git a/src/main/java/com/rymcu/forest/service/TagService.java b/src/main/java/com/rymcu/forest/service/TagService.java index 0b36b76..9affe2d 100644 --- a/src/main/java/com/rymcu/forest/service/TagService.java +++ b/src/main/java/com/rymcu/forest/service/TagService.java @@ -23,7 +23,7 @@ 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; /** * 清除未使用标签 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 dc7c9ad..14f043c 100644 --- a/src/main/java/com/rymcu/forest/service/impl/ArticleServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/ArticleServiceImpl.java @@ -101,16 +101,12 @@ public class ArticleServiceImpl extends AbstractService
implements Arti @Override @Transactional(rollbackFor = {UnsupportedEncodingException.class, BaseApiException.class}) - public Long postArticle(ArticleDTO article, HttpServletRequest request) throws UnsupportedEncodingException, BaseApiException { + 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)) { @@ -178,7 +174,7 @@ public class ArticleServiceImpl extends AbstractService
implements Arti newArticle.setArticlePermalink(domain + "/draft/" + newArticleId); newArticle.setArticleLink("/draft/" + newArticleId); } - tagService.saveTagArticle(newArticle, articleContentHtml); + tagService.saveTagArticle(newArticle, articleContentHtml, user.getIdUser()); if (StringUtils.isNotBlank(articleContentHtml)) { String previewContent = Html2TextUtil.getContent(articleContentHtml); @@ -237,12 +233,8 @@ public class ArticleServiceImpl extends AbstractService
implements Arti } @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; } @@ -263,14 +255,14 @@ public class ArticleServiceImpl extends AbstractService
implements Arti @Override @Transactional(rollbackFor = Exception.class) - public Boolean updateTags(Long idArticle, String tags) throws UnsupportedEncodingException, BaseApiException { + public Boolean updateTags(Long idArticle, String tags, Long userId) throws UnsupportedEncodingException, BaseApiException { Article article = articleMapper.selectByPrimaryKey(idArticle); if (!Objects.nonNull(article)) { throw new ContentNotExistException("更新失败,文章不存在!"); } article.setArticleTags(tags); articleMapper.updateArticleTags(idArticle, tags); - tagService.saveTagArticle(article, ""); + tagService.saveTagArticle(article, "", userId); 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..c59c9a4 100644 --- a/src/main/java/com/rymcu/forest/service/impl/TagServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/TagServiceImpl.java @@ -42,8 +42,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 +79,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,7 +91,7 @@ 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; @@ -108,7 +107,7 @@ public class TagServiceImpl extends AbstractService implements TagService { } else { article.setArticleTags("待分类"); } - saveTagArticle(article, articleContentHtml); + saveTagArticle(article, articleContentHtml, userId); } } return 0; 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 6fa41a1..9fc6272 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 @@ -10,19 +10,22 @@ 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.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.List; import java.util.Map; +import java.util.Objects; /** * @author ronger @@ -47,14 +50,22 @@ public class ArticleController { } @PostMapping("/post") - public GlobalResult postArticle(@RequestBody ArticleDTO article, HttpServletRequest request) throws BaseApiException, UnsupportedEncodingException { - return GlobalResultGenerator.genSuccessResult(articleService.postArticle(article, request)); + 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 { - return GlobalResultGenerator.genSuccessResult(articleService.postArticle(article, request)); + 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}") @@ -71,7 +82,11 @@ public class ArticleController { @GetMapping("/drafts") public GlobalResult> drafts(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer rows) throws BaseApiException { PageHelper.startPage(page, rows); - List list = articleService.findDrafts(); + 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); } @@ -86,7 +101,8 @@ public class ArticleController { public GlobalResult updateTags(@RequestBody Article article) throws BaseApiException, UnsupportedEncodingException { Long idArticle = article.getIdArticle(); String articleTags = article.getArticleTags(); - return GlobalResultGenerator.genSuccessResult(articleService.updateTags(idArticle, articleTags)); + User user = UserUtils.getCurrentUserByToken(); + return GlobalResultGenerator.genSuccessResult(articleService.updateTags(idArticle, articleTags, user.getIdUser())); } @PostMapping("/thumbs-up") diff --git a/src/main/resources/static/forest.sql b/src/main/resources/static/forest.sql index b6d5752..fbde953 100644 --- a/src/main/resources/static/forest.sql +++ b/src/main/resources/static/forest.sql @@ -342,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'); 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..1b0baee --- /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.FixMethodOrder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +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 +@RunWith(SpringRunner.class) +@Transactional +// 顺序执行单元测试 +@FixMethodOrder(MethodSorters.DEFAULT) +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 From d31822133cd99254d844914f39f1d6b244303a34 Mon Sep 17 00:00:00 2001 From: ronger Date: Fri, 5 Aug 2022 09:17:29 +0800 Subject: [PATCH 15/25] =?UTF-8?q?:art:=20spring-boot-starter-test=20?= =?UTF-8?q?=E5=B7=B2=E5=BC=95=E5=85=A5=20junit5=EF=BC=8C=E6=95=85=E5=8E=BB?= =?UTF-8?q?=E9=99=A4=20junit=20=E4=BE=9D=E8=B5=96=EF=BC=8C=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=20junit5=20=E5=AE=9E=E7=8E=B0=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 5 ----- .../com/rymcu/forest/service/ArticleServiceTest.java | 12 ++++++------ 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/pom.xml b/pom.xml index cb92596..336080b 100644 --- a/pom.xml +++ b/pom.xml @@ -292,11 +292,6 @@ - - junit - junit - test - diff --git a/src/test/java/com/rymcu/forest/service/ArticleServiceTest.java b/src/test/java/com/rymcu/forest/service/ArticleServiceTest.java index 1b0baee..3944f32 100644 --- a/src/test/java/com/rymcu/forest/service/ArticleServiceTest.java +++ b/src/test/java/com/rymcu/forest/service/ArticleServiceTest.java @@ -6,15 +6,15 @@ 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.FixMethodOrder; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; +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.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.transaction.annotation.Transactional; import java.io.UnsupportedEncodingException; @@ -27,10 +27,10 @@ import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest -@RunWith(SpringRunner.class) +@ExtendWith(SpringExtension.class) @Transactional // 顺序执行单元测试 -@FixMethodOrder(MethodSorters.DEFAULT) +@TestMethodOrder(MethodOrderer.Random.class) class ArticleServiceTest { /** From 42eaab1a871e5e2e09885d140275e931b380ddb6 Mon Sep 17 00:00:00 2001 From: ronger Date: Wed, 17 Aug 2022 09:46:19 +0800 Subject: [PATCH 16/25] =?UTF-8?q?:art:=20=E4=BB=A3=E7=A0=81=E4=BC=98?= =?UTF-8?q?=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../forest/config/BaseExceptionHandler.java | 6 +- .../core/exception/BusinessException.java | 28 +++++++++ .../exception/ContentNotExistException.java | 5 +- .../exception/DataDuplicationException.java | 28 --------- .../core/exception/UltraViresException.java | 5 +- .../rymcu/forest/handler/CommentHandler.java | 57 +++++++++++++++++++ .../forest/handler/event/CommentEvent.java | 26 +++++++++ .../rymcu/forest/service/CommentService.java | 4 +- .../forest/service/PortfolioService.java | 8 ++- .../com/rymcu/forest/service/UserService.java | 2 +- .../service/impl/ArticleServiceImpl.java | 5 +- .../service/impl/CommentServiceImpl.java | 54 ++++++------------ .../service/impl/PortfolioServiceImpl.java | 39 ++++++------- .../forest/service/impl/UserServiceImpl.java | 19 ++++--- .../web/api/comment/CommentController.java | 11 ++-- .../web/api/common/CommonApiController.java | 19 +++---- .../api/portfolio/PortfolioController.java | 12 +++- 17 files changed, 199 insertions(+), 129 deletions(-) create mode 100644 src/main/java/com/rymcu/forest/core/exception/BusinessException.java delete mode 100644 src/main/java/com/rymcu/forest/core/exception/DataDuplicationException.java create mode 100644 src/main/java/com/rymcu/forest/handler/CommentHandler.java create mode 100644 src/main/java/com/rymcu/forest/handler/event/CommentEvent.java diff --git a/src/main/java/com/rymcu/forest/config/BaseExceptionHandler.java b/src/main/java/com/rymcu/forest/config/BaseExceptionHandler.java index ee053fd..73b0279 100644 --- a/src/main/java/com/rymcu/forest/config/BaseExceptionHandler.java +++ b/src/main/java/com/rymcu/forest/config/BaseExceptionHandler.java @@ -1,7 +1,7 @@ package com.rymcu.forest.config; import com.alibaba.fastjson.support.spring.FastJsonJsonView; -import com.rymcu.forest.core.exception.DataDuplicationException; +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; @@ -63,7 +63,7 @@ public class BaseExceptionHandler { } else if (ex instanceof ServletException) { result.setCode(ResultCode.FAIL.getCode()); result.setMessage(ex.getMessage()); - } else if (ex instanceof DataDuplicationException) { + } else if (ex instanceof BusinessException) { result.setCode(ResultCode.FAIL.getCode()); result.setMessage(ex.getMessage()); } else if (ex instanceof TransactionException) { @@ -112,7 +112,7 @@ public class BaseExceptionHandler { } else if (ex instanceof ServletException) { attributes.put("code", ResultCode.FAIL.getCode()); attributes.put("message", ex.getMessage()); - } else if (ex instanceof DataDuplicationException) { + } else if (ex instanceof BusinessException) { attributes.put("code", ResultCode.FAIL.getCode()); attributes.put("message", ex.getMessage()); } else if (ex instanceof TransactionException) { 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 index 4afaf5b..7a31d9b 100644 --- a/src/main/java/com/rymcu/forest/core/exception/ContentNotExistException.java +++ b/src/main/java/com/rymcu/forest/core/exception/ContentNotExistException.java @@ -1,6 +1,9 @@ package com.rymcu.forest.core.exception; -public class ContentNotExistException extends RuntimeException{ +/** + * @author KKould + */ +public class ContentNotExistException extends BusinessException { private static final long serialVersionUID = 3206734387536223284L; public ContentNotExistException() { diff --git a/src/main/java/com/rymcu/forest/core/exception/DataDuplicationException.java b/src/main/java/com/rymcu/forest/core/exception/DataDuplicationException.java deleted file mode 100644 index 0e5faa2..0000000 --- a/src/main/java/com/rymcu/forest/core/exception/DataDuplicationException.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.rymcu.forest.core.exception; - -/** - * @author KKould - */ -public class DataDuplicationException extends RuntimeException { - - private static final long serialVersionUID = 3206744387536223284L; - - public DataDuplicationException() { - } - - public DataDuplicationException(String message) { - super(message); - } - - public DataDuplicationException(String message, Throwable cause) { - super(message, cause); - } - - public DataDuplicationException(Throwable cause) { - super(cause); - } - - public DataDuplicationException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } -} diff --git a/src/main/java/com/rymcu/forest/core/exception/UltraViresException.java b/src/main/java/com/rymcu/forest/core/exception/UltraViresException.java index 6734208..8ade8f1 100644 --- a/src/main/java/com/rymcu/forest/core/exception/UltraViresException.java +++ b/src/main/java/com/rymcu/forest/core/exception/UltraViresException.java @@ -1,6 +1,9 @@ package com.rymcu.forest.core.exception; -public class UltraViresException extends RuntimeException { +/** + * @author KKould + */ +public class UltraViresException extends BusinessException { private static final long serialVersionUID = 3206744387536228284L; 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..906e1fe --- /dev/null +++ b/src/main/java/com/rymcu/forest/handler/CommentHandler.java @@ -0,0 +1,57 @@ +package com.rymcu.forest.handler; + +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 com.rymcu.forest.wx.mp.utils.JsonUtils; +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]", JsonUtils.toJson(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/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/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/PortfolioService.java b/src/main/java/com/rymcu/forest/service/PortfolioService.java index 13e83b8..b7cb859 100644 --- a/src/main/java/com/rymcu/forest/service/PortfolioService.java +++ b/src/main/java/com/rymcu/forest/service/PortfolioService.java @@ -71,12 +71,18 @@ public interface PortfolioService extends Service { */ Map unbindArticle(Long idPortfolio, Long idArticle); + /** * 删除作品集 + * * @param idPortfolio + * @param idUser + * @param roleWeights * @return + * @throws BaseApiException + * @throws IllegalAccessException */ - Map deletePortfolio(Long idPortfolio) throws BaseApiException; + boolean deletePortfolio(Long idPortfolio, Long idUser, Integer roleWeights) throws BaseApiException, IllegalAccessException; /** * 获取作品集列表数据 diff --git a/src/main/java/com/rymcu/forest/service/UserService.java b/src/main/java/com/rymcu/forest/service/UserService.java index 04e7665..b2d3772 100644 --- a/src/main/java/com/rymcu/forest/service/UserService.java +++ b/src/main/java/com/rymcu/forest/service/UserService.java @@ -40,7 +40,7 @@ public interface UserService extends Service { * @param password 密码 * @return Map * */ - Map login(String account, String password); + TokenUser login(String account, String password); /** * 通过 account 获取用户信息接口 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 14f043c..58585f3 100644 --- a/src/main/java/com/rymcu/forest/service/impl/ArticleServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/ArticleServiceImpl.java @@ -2,7 +2,7 @@ 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.exception.DataDuplicationException; +import com.rymcu.forest.core.exception.BusinessException; import com.rymcu.forest.core.exception.UltraViresException; import com.rymcu.forest.core.service.AbstractService; import com.rymcu.forest.dto.*; @@ -28,7 +28,6 @@ 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.*; @@ -199,7 +198,7 @@ public class ArticleServiceImpl extends AbstractService

implements Arti luceneService.deleteArticle(id); return result; } else { - throw new DataDuplicationException("已有评论的文章不允许删除!"); + throw new BusinessException("已有评论的文章不允许删除!"); } } 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/PortfolioServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/PortfolioServiceImpl.java index bb6d2b7..8ff425d 100644 --- a/src/main/java/com/rymcu/forest/service/impl/PortfolioServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/PortfolioServiceImpl.java @@ -2,6 +2,7 @@ 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.service.AbstractService; import com.rymcu.forest.dto.*; import com.rymcu.forest.entity.Portfolio; @@ -44,7 +45,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,12 +54,12 @@ public class PortfolioServiceImpl extends AbstractService implements @Override public PortfolioDTO findPortfolioDTOById(Long idPortfolio, Integer type) { - PortfolioDTO portfolio = portfolioMapper.selectPortfolioDTOById(idPortfolio,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; @@ -109,7 +110,7 @@ public class PortfolioServiceImpl extends AbstractService implements map.put("message", "非法操作!"); } else { PageHelper.startPage(page, rows); - List articles = articleService.selectUnbindArticles(idPortfolio,searchText,user.getIdUser()); + List articles = articleService.selectUnbindArticles(idPortfolio, searchText, user.getIdUser()); PageInfo pageInfo = new PageInfo(articles); map = Utils.getArticlesGlobalResult(pageInfo); } @@ -123,7 +124,7 @@ public class PortfolioServiceImpl extends AbstractService implements 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); + portfolioMapper.insertPortfolioArticle(portfolioArticle.getIdArticle(), portfolioArticle.getIdPortfolio(), maxSortNo); map.put("message", "绑定成功!"); } else { map.put("message", "该文章已经在作品集下!!"); @@ -143,7 +144,7 @@ public class PortfolioServiceImpl extends AbstractService implements if (portfolioArticle.getSortNo() == null) { map.put("message", "排序号不能为空!"); } - Integer result = portfolioMapper.updateArticleSortNo(portfolioArticle.getIdPortfolio(),portfolioArticle.getIdArticle(),portfolioArticle.getSortNo()); + Integer result = portfolioMapper.updateArticleSortNo(portfolioArticle.getIdPortfolio(), portfolioArticle.getIdArticle(), portfolioArticle.getSortNo()); if (result > 0) { map.put("message", "更新成功!"); } else { @@ -161,7 +162,7 @@ public class PortfolioServiceImpl extends AbstractService implements if (idArticle == null || idArticle.equals(0)) { map.put("message", "文章数据异常"); } - Integer result = portfolioMapper.unbindArticle(idPortfolio,idArticle); + Integer result = portfolioMapper.unbindArticle(idPortfolio, idArticle); if (result > 0) { map.put("message", "操作成功!"); } else { @@ -171,35 +172,29 @@ public class PortfolioServiceImpl extends AbstractService implements } @Override - public Map deletePortfolio(Long 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) throws BaseApiException, IllegalAccessException { + 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 IllegalAccessException("非法访问!"); } } 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(idPortfolio); + throw new BusinessException("操作失败!"); } + PortfolioIndexUtil.deleteIndex(idPortfolio); + return true; } - - return map; } @Override diff --git a/src/main/java/com/rymcu/forest/service/impl/UserServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/UserServiceImpl.java index 932786c..c8792ff 100644 --- a/src/main/java/com/rymcu/forest/service/impl/UserServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/UserServiceImpl.java @@ -1,5 +1,7 @@ package com.rymcu.forest.service.impl; +import com.rymcu.forest.core.exception.CaptchaException; +import com.rymcu.forest.core.exception.ContentNotExistException; import com.rymcu.forest.core.service.AbstractService; import com.rymcu.forest.core.service.redis.RedisService; import com.rymcu.forest.dto.*; @@ -20,6 +22,8 @@ import com.rymcu.forest.util.Utils; import com.rymcu.forest.web.api.common.UploadController; import org.apache.commons.lang.StringUtils; import org.apache.ibatis.exceptions.TooManyResultsException; +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authc.UnknownAccountException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -114,8 +118,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 +128,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 @@ -183,7 +185,7 @@ public class UserServiceImpl extends AbstractService implements UserServic Map map = new HashMap(2); UserInfoDTO user = userMapper.selectUserInfo(idUser); if (user == null) { - map.put("message", "用户不存在!"); + throw new ContentNotExistException("用户不存在!"); } else { UserExtend userExtend = userExtendMapper.selectByPrimaryKey(user.getIdUser()); if (Objects.isNull(userExtend)) { @@ -270,7 +272,6 @@ public class UserServiceImpl extends AbstractService implements UserServic @Override public Map updateEmail(ChangeEmailDTO changeEmailDTO) { Map map = new HashMap(2); - map.put("message", "验证码无效!"); Long idUser = changeEmailDTO.getIdUser(); String email = changeEmailDTO.getEmail(); String code = changeEmailDTO.getCode(); @@ -282,7 +283,7 @@ public class UserServiceImpl extends AbstractService implements UserServic map.put("email", email); } } - return map; + throw new CaptchaException(); } @Override 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 5f1ed82..ab9f04e 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 @@ -9,7 +9,6 @@ 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.*; -import com.rymcu.forest.util.Utils; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; @@ -75,9 +74,9 @@ public class CommonApiController { } @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) { + TokenUser tokenUser = userService.login(user.getAccount(), user.getPassword()); + return GlobalResultGenerator.genSuccessResult(tokenUser); } @GetMapping("/heartbeat") @@ -117,11 +116,9 @@ public class CommonApiController { @GetMapping("/portfolio/{id}") @VisitLogger - public GlobalResult> portfolio(@PathVariable Long 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") @@ -150,10 +147,8 @@ public class CommonApiController { @GetMapping("/product/{id}") @VisitLogger - public GlobalResult> product(@PathVariable Integer id) { + public GlobalResult product(@PathVariable Integer id) { ProductDTO productDTO = productService.findProductDTOById(id, 1); - Map map = new HashMap<>(1); - map.put("product", productDTO); - return GlobalResultGenerator.genSuccessResult(map); + return GlobalResultGenerator.genSuccessResult(productDTO); } } 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 d81c7ef..e9324d3 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 @@ -6,8 +6,11 @@ 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,6 +27,8 @@ public class PortfolioController { @Resource private PortfolioService portfolioService; + @Resource + private UserService userService; @GetMapping("/detail/{idPortfolio}") public GlobalResult detail(@PathVariable Long idPortfolio,@RequestParam(defaultValue = "0") Integer type) { @@ -76,8 +81,11 @@ public class PortfolioController { @DeleteMapping("/delete") @AuthorshipInterceptor(moduleName = Module.PORTFOLIO) - public GlobalResult delete(Long idPortfolio) throws BaseApiException { - Map map = portfolioService.deletePortfolio(idPortfolio); + public GlobalResult delete(Long idPortfolio) throws BaseApiException, IllegalAccessException { + User user = UserUtils.getCurrentUserByToken(); + Long idUser = user.getIdUser(); + Integer roleWeights = userService.findRoleWeightsByUser(idUser); + boolean map = portfolioService.deletePortfolio(idPortfolio, idUser, roleWeights); return GlobalResultGenerator.genSuccessResult(map); } From 97375a3dbd30ef2a5742ddeabb49b2896b34987a Mon Sep 17 00:00:00 2001 From: ronger Date: Wed, 17 Aug 2022 09:52:14 +0800 Subject: [PATCH 17/25] =?UTF-8?q?:art:=20=E5=BC=80=E5=90=AF=E5=BC=82?= =?UTF-8?q?=E6=AD=A5=E6=89=A7=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/rymcu/forest/ForestApplication.java | 2 ++ 1 file changed, 2 insertions(+) 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 { From a019078802a9ce8ee955758525a22077de25ec49 Mon Sep 17 00:00:00 2001 From: ronger Date: Sat, 20 Aug 2022 19:11:30 +0800 Subject: [PATCH 18/25] =?UTF-8?q?:art:=20=E6=96=87=E7=AB=A0=E5=8F=91?= =?UTF-8?q?=E5=B8=83/=E6=9B=B4=E6=96=B0/=E5=88=A0=E9=99=A4=E5=90=8E?= =?UTF-8?q?=E7=BB=AD=E4=BA=8B=E4=BB=B6=E6=89=A7=E8=A1=8C=E8=BF=87=E7=A8=8B?= =?UTF-8?q?=E8=A7=A3=E8=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 7 +- .../rymcu/forest/handler/ArticleHandler.java | 66 +++++++++ .../handler/event/ArticleDeleteEvent.java | 18 +++ .../forest/handler/event/ArticleEvent.java | 27 ++++ .../service/impl/LuceneServiceImpl.java | 2 +- .../impl/PortfolioLuceneServiceImpl.java | 2 +- .../forest/lucene/util/ArticleIndexUtil.java | 137 ++++++++++-------- .../rymcu/forest/lucene/util/LucenePath.java | 2 +- .../service/impl/ArticleServiceImpl.java | 58 ++++---- .../mapper/lucene/ArticleLuceneMapper.xml | 4 +- .../mapper/lucene/PortfolioLuceneMapper.xml | 2 +- .../java/mapper/lucene/UserLuceneMapper.xml | 2 +- 12 files changed, 226 insertions(+), 101 deletions(-) create mode 100644 src/main/java/com/rymcu/forest/handler/ArticleHandler.java create mode 100644 src/main/java/com/rymcu/forest/handler/event/ArticleDeleteEvent.java create mode 100644 src/main/java/com/rymcu/forest/handler/event/ArticleEvent.java diff --git a/README.md b/README.md index fa3ff2f..6796675 100644 --- a/README.md +++ b/README.md @@ -97,4 +97,9 @@ forest([ˈfôrəst],n.森林)是一款现代化的知识社区项目,使 ## 鸣谢 - 感谢 `JetBrains` 对本项目的帮助,为作者提供了开源许可版 `JetBrains` 全家桶 -![JetBrains](src/main/resources/static/jb_beam.svg) \ No newline at end of file +![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/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..8627f62 --- /dev/null +++ b/src/main/java/com/rymcu/forest/handler/ArticleHandler.java @@ -0,0 +1,66 @@ +package com.rymcu.forest.handler; + +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 com.rymcu.forest.wx.mp.utils.JsonUtils; +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]", JsonUtils.toJson(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]", JsonUtils.toJson(articleDeleteEvent))); + luceneService.deleteArticle(articleDeleteEvent.getIdArticle()); + log.info("执行完成文章删除相关事件...id={}", articleDeleteEvent.getIdArticle()); + } +} 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/lucene/service/impl/LuceneServiceImpl.java b/src/main/java/com/rymcu/forest/lucene/service/impl/LuceneServiceImpl.java index 8d8b8d3..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 @@ -66,7 +66,7 @@ public class LuceneServiceImpl implements LuceneService { int totalCount = list.size(); int perThreadCount = 3000; // 加1避免线程池的参数为0 - int threadCount = totalCount / perThreadCount + (totalCount % perThreadCount == 0 ? 0 : 1) + 1; + int threadCount = totalCount / perThreadCount + (totalCount % perThreadCount == 0 ? 0 : 1); ExecutorService pool = Executors.newFixedThreadPool(threadCount); CountDownLatch countDownLatch1 = new CountDownLatch(1); CountDownLatch countDownLatch2 = new CountDownLatch(threadCount); 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 4d35c34..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 @@ -56,7 +56,7 @@ public class PortfolioLuceneServiceImpl implements PortfolioLuceneService { int totalCount = list.size(); int perThreadCount = 3000; // 加1避免线程池的参数为0 - int threadCount = totalCount / perThreadCount + (totalCount % perThreadCount == 0 ? 0 : 1) + 1; + int threadCount = totalCount / perThreadCount + (totalCount % perThreadCount == 0 ? 0 : 1); ExecutorService pool = Executors.newFixedThreadPool(threadCount); CountDownLatch countDownLatch1 = new CountDownLatch(1); CountDownLatch countDownLatch2 = new CountDownLatch(threadCount); 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 9b3880e..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,68 +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; - private static final String WINDOW_PATH = - System.getProperty("user.dir") + StrUtil.BACKSLASH + "lucene\\index\\article"; - - /** 删除所有运行中保存的索引 */ - 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(Long 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", String.valueOf(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/service/impl/ArticleServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/ArticleServiceImpl.java index 58585f3..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,8 +1,8 @@ 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.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.*; @@ -10,26 +10,33 @@ 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 java.io.UnsupportedEncodingException; -import java.util.*; +import java.util.Date; +import java.util.List; +import java.util.Objects; /** * @author ronger @@ -45,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; @@ -141,39 +148,16 @@ public class ArticleServiceImpl extends AbstractService
implements Arti articleMapper.updateArticleContent(newArticle.getIdArticle(), articleContent, articleContentHtml); } Long newArticleId = newArticle.getIdArticle(); - // 发送相关通知 + // 更新文章链接 if (DEFAULT_STATUS.equals(newArticle.getArticleStatus())) { - // 发送系统通知 - if (notification) { - NotificationUtils.sendAnnouncement(newArticleId, NotificationConstant.Article, newArticle.getArticleTitle()); - } else { - // 发送关注通知 - StringBuilder dataSummary = new StringBuilder(); - if (isUpdate) { - dataSummary.append(user.getNickname()).append("更新了文章: ").append(newArticle.getArticleTitle()); - NotificationUtils.sendArticlePush(newArticleId, NotificationConstant.UpdateArticle, dataSummary.toString(), newArticle.getArticleAuthorId()); - } else { - dataSummary.append(user.getNickname()).append("发布了文章: ").append(newArticle.getArticleTitle()); - NotificationUtils.sendArticlePush(newArticleId, NotificationConstant.PostArticle, dataSummary.toString(), newArticle.getArticleAuthorId()); - } - } - // 草稿不更新索引 - if (isUpdate) { - log.info("更新文章索引,id={}", newArticleId); - luceneService.updateArticle(newArticleId); - } else { - log.info("写入文章索引,id={}", newArticleId); - luceneService.writeArticle(newArticleId); - } - // 更新文章链接 + // 文章 newArticle.setArticlePermalink(domain + "/article/" + newArticleId); newArticle.setArticleLink("/article/" + newArticleId); } else { - // 更新文章链接 + // 草稿 newArticle.setArticlePermalink(domain + "/draft/" + newArticleId); newArticle.setArticleLink("/draft/" + newArticleId); } - tagService.saveTagArticle(newArticle, articleContentHtml, user.getIdUser()); if (StringUtils.isNotBlank(articleContentHtml)) { String previewContent = Html2TextUtil.getContent(articleContentHtml); @@ -183,6 +167,12 @@ public class ArticleServiceImpl extends AbstractService
implements Arti newArticle.setArticlePreviewContent(previewContent); } articleMapper.updateByPrimaryKeySelective(newArticle); + // 更新标签 + 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())); + } return newArticleId; } @@ -195,7 +185,9 @@ public class ArticleServiceImpl extends AbstractService
implements Arti deleteLinkedData(id); // 删除文章 int result = articleMapper.deleteByPrimaryKey(id); - luceneService.deleteArticle(id); + if (result > 0) { + publisher.publishEvent(new ArticleDeleteEvent(id)); + } return result; } else { throw new BusinessException("已有评论的文章不允许删除!"); diff --git a/src/main/java/mapper/lucene/ArticleLuceneMapper.xml b/src/main/java/mapper/lucene/ArticleLuceneMapper.xml index 95a8c61..9efadf7 100755 --- a/src/main/java/mapper/lucene/ArticleLuceneMapper.xml +++ b/src/main/java/mapper/lucene/ArticleLuceneMapper.xml @@ -35,7 +35,7 @@ select art.id, art.article_title, content.article_content_html as article_content from forest_article art join forest_article_content content on art.id = content.id_article - where article_status = 0; + where article_status = 0 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 31cb8f9..db196c2 100644 --- a/src/main/java/mapper/lucene/UserLuceneMapper.xml +++ b/src/main/java/mapper/lucene/UserLuceneMapper.xml @@ -37,6 +37,6 @@ From 4c17685ff07038e2d2501a73ef32c1c61a68a012 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BD=A0=E4=B8=80=E4=B8=AA=E4=BA=BA=E5=9C=A8=E8=BF=99?= =?UTF-8?q?=E5=84=BF=E5=B9=B2=E5=98=9B=E4=BD=A0=E6=98=AF=E6=9D=A5=E6=8B=89?= =?UTF-8?q?=E5=B1=8E=E7=9A=84=E5=90=A7?= <123456@qq.com> Date: Sun, 21 Aug 2022 17:35:29 +0800 Subject: [PATCH 19/25] =?UTF-8?q?:bug:=20map=E8=BF=94=E5=9B=9E=E4=BF=AE?= =?UTF-8?q?=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/ArticleThumbsUpService.java | 7 +- .../forest/service/PortfolioService.java | 16 ++-- .../com/rymcu/forest/service/RoleService.java | 11 +-- .../rymcu/forest/service/SponsorService.java | 5 +- .../com/rymcu/forest/service/TagService.java | 9 +- .../rymcu/forest/service/TopicService.java | 16 ++-- .../com/rymcu/forest/service/UserService.java | 53 +++++++----- .../impl/ArticleThumbsUpServiceImpl.java | 20 ++--- .../service/impl/DashboardServiceImpl.java | 5 +- .../service/impl/PortfolioServiceImpl.java | 52 +++++------- .../forest/service/impl/RoleServiceImpl.java | 27 +++--- .../service/impl/SponsorServiceImpl.java | 14 ++-- .../forest/service/impl/TagServiceImpl.java | 48 +++++------ .../forest/service/impl/TopicServiceImpl.java | 76 +++++++---------- .../forest/service/impl/UserServiceImpl.java | 81 +++++++----------- .../forest/web/api/admin/AdminController.java | 82 +++++++++---------- .../web/api/article/ArticleController.java | 11 ++- .../web/api/common/CommonApiController.java | 15 ++-- .../api/portfolio/PortfolioController.java | 25 +++--- .../web/api/user/UserInfoController.java | 27 +++--- 20 files changed, 273 insertions(+), 327 deletions(-) diff --git a/src/main/java/com/rymcu/forest/service/ArticleThumbsUpService.java b/src/main/java/com/rymcu/forest/service/ArticleThumbsUpService.java index d565c29..bfe17d8 100644 --- a/src/main/java/com/rymcu/forest/service/ArticleThumbsUpService.java +++ b/src/main/java/com/rymcu/forest/service/ArticleThumbsUpService.java @@ -4,17 +4,16 @@ 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 + * @throws BaseApiException */ - Map thumbsUp(ArticleThumbsUp articleThumbsUp) throws BaseApiException; + String thumbsUp(ArticleThumbsUp articleThumbsUp) throws Exception; } diff --git a/src/main/java/com/rymcu/forest/service/PortfolioService.java b/src/main/java/com/rymcu/forest/service/PortfolioService.java index b7cb859..120d0ed 100644 --- a/src/main/java/com/rymcu/forest/service/PortfolioService.java +++ b/src/main/java/com/rymcu/forest/service/PortfolioService.java @@ -1,5 +1,6 @@ package com.rymcu.forest.service; +import com.github.pagehelper.PageInfo; import com.rymcu.forest.core.service.Service; import com.rymcu.forest.dto.PortfolioArticleDTO; import com.rymcu.forest.dto.PortfolioDTO; @@ -8,7 +9,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 @@ -44,32 +44,35 @@ public interface PortfolioService extends Service { * @param rows * @param searchText * @param idPortfolio - * @throws BaseApiException * @return + * @throws BaseApiException */ - Map findUnbindArticles(Integer page, Integer rows, String searchText, Long idPortfolio) throws BaseApiException; + PageInfo findUnbindArticles(Integer page, Integer rows, String searchText, Long idPortfolio) throws Exception; /** * 绑定文章 + * * @param portfolioArticle * @return */ - Map bindArticle(PortfolioArticleDTO portfolioArticle); + boolean bindArticle(PortfolioArticleDTO portfolioArticle) throws Exception; /** * 更新文章排序号 + * * @param portfolioArticle * @return */ - Map updateArticleSortNo(PortfolioArticleDTO portfolioArticle); + boolean updateArticleSortNo(PortfolioArticleDTO portfolioArticle) throws Exception; /** * 取消绑定文章 + * * @param idPortfolio * @param idArticle * @return */ - Map unbindArticle(Long idPortfolio, Long idArticle); + boolean unbindArticle(Long idPortfolio, Long idArticle) throws Exception; /** @@ -84,6 +87,7 @@ public interface PortfolioService extends Service { */ boolean deletePortfolio(Long idPortfolio, Long idUser, Integer roleWeights) throws BaseApiException, IllegalAccessException; + /** * 获取作品集列表数据 * @return diff --git a/src/main/java/com/rymcu/forest/service/RoleService.java b/src/main/java/com/rymcu/forest/service/RoleService.java index a63ae5e..3103fba 100644 --- a/src/main/java/com/rymcu/forest/service/RoleService.java +++ b/src/main/java/com/rymcu/forest/service/RoleService.java @@ -5,7 +5,6 @@ import com.rymcu.forest.entity.Role; import com.rymcu.forest.entity.User; import java.util.List; -import java.util.Map; /** @@ -31,16 +30,18 @@ public interface RoleService extends Service { /** * 更新用户状态 + * * @param idRole * @param status * @return - * */ - Map updateStatus(Long idRole, String status); + */ + boolean updateStatus(Long idRole, String status) throws Exception; /** * 添加/更新角色 + * * @param role * @return - * */ - Map saveRole(Role role); + */ + boolean saveRole(Role role) throws Exception; } 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 9affe2d..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 @@ -27,16 +26,18 @@ public interface TagService extends Service { /** * 清除未使用标签 + * * @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 2e4a04a..7bb5641 100644 --- a/src/main/java/com/rymcu/forest/service/TopicService.java +++ b/src/main/java/com/rymcu/forest/service/TopicService.java @@ -1,12 +1,12 @@ package com.rymcu.forest.service; +import com.github.pagehelper.PageInfo; import com.rymcu.forest.core.service.Service; 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 @@ -28,10 +28,11 @@ public interface TopicService extends Service { /** * 新增/更新主题信息 + * * @param topic 主题信息 * @return - * */ - Map saveTopic(Topic topic); + */ + Topic saveTopic(Topic topic) throws Exception; /** * 查询未绑定标签 @@ -43,24 +44,27 @@ public interface TopicService extends Service { /** * 绑定标签 + * * @param topicTag * @return */ - Map bindTopicTag(TopicTagDTO topicTag); + TopicTagDTO bindTopicTag(TopicTagDTO topicTag) throws Exception; /** * 取消绑定标签 + * * @param topicTag * @return */ - Map unbindTopicTag(TopicTagDTO topicTag); + TopicTagDTO unbindTopicTag(TopicTagDTO topicTag) throws Exception; /** * 获取主题下标签列表 + * * @param topicUri * @param page * @param rows * @return */ - Map findTagsByTopicUri(String topicUri, Integer page, Integer rows); + PageInfo findTagsByTopicUri(String topicUri, Integer page, Integer rows); } diff --git a/src/main/java/com/rymcu/forest/service/UserService.java b/src/main/java/com/rymcu/forest/service/UserService.java index b2d3772..0dc6fd3 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; @@ -27,20 +28,22 @@ public interface UserService extends Service { /** * 注册接口 - * @param email 邮箱 - * @param password 密码 - * @param code 验证码 + * + * @param email 邮箱 + * @param password 密码 + * @param code 验证码 * @return Map - * */ - Map register(String email, String password, String code); + */ + void register(String email, String password, String code) throws ServiceException; /** * 登录接口 - * @param account 邮箱 - * @param password 密码 + * + * @param account 邮箱 + * @param password 密码 * @return Map - * */ - TokenUser login(String account, String password); + */ + TokenUser login(String account, String password) throws ServiceException; /** * 通过 account 获取用户信息接口 @@ -51,27 +54,30 @@ public interface UserService extends Service { /** * 找回密码接口 - * @param code 验证码 + * + * @param code 验证码 * @param password 密码 * @return Map - * */ - Map forgetPassword(String code, String password); + */ + String forgetPassword(String code, String password) throws ServiceException; /** * 更新用户角色接口 + * * @param idUser 用户 id * @param idRole 角色 id * @return Map - * */ - Map updateUserRole(Long idUser, Long idRole); + */ + boolean updateUserRole(Long idUser, Long idRole) throws ServiceException; /** * 更新用户状态 + * * @param idUser 用户 id * @param status 状态 * @return Map - * */ - Map updateStatus(Long idUser, String status); + */ + boolean updateStatus(Long idUser, String status) throws ServiceException; /** * 获取用户信息 @@ -82,18 +88,20 @@ public interface UserService extends Service { /** * 更新用户信息 + * * @param user * @return */ - Map updateUserInfo(UserInfoDTO user); + UserInfoDTO updateUserInfo(UserInfoDTO user) throws Exception; /** * 验证昵称是否重复 + * * @param idUser * @param nickname * @return */ - Map checkNickname(Long idUser, String nickname); + boolean checkNickname(Long idUser, String nickname) throws ServiceException; /** * 获取用户权限 @@ -111,10 +119,11 @@ public interface UserService extends Service { /** * 更新用户扩展信息 + * * @param userExtend * @return */ - Map updateUserExtend(UserExtend userExtend); + UserExtend updateUserExtend(UserExtend userExtend) throws ServiceException; /** * 获取用户扩展信息 @@ -125,17 +134,19 @@ public interface UserService extends Service { /** * 更换邮箱 + * * @param changeEmailDTO * @return */ - Map updateEmail(ChangeEmailDTO changeEmailDTO); + String updateEmail(ChangeEmailDTO changeEmailDTO) throws ServiceException; /** * 更新密码 + * * @param updatePasswordDTO * @return */ - Map updatePassword(UpdatePasswordDTO updatePasswordDTO); + boolean updatePassword(UpdatePasswordDTO updatePasswordDTO); /** * 查询用户列表 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..7bfd346 100644 --- a/src/main/java/com/rymcu/forest/service/impl/ArticleThumbsUpServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/ArticleThumbsUpServiceImpl.java @@ -1,5 +1,6 @@ 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; @@ -8,14 +9,11 @@ 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,17 +29,14 @@ public class ArticleThumbsUpServiceImpl extends AbstractService @Override @Transactional(rollbackFor = Exception.class) - public Map thumbsUp(ArticleThumbsUp articleThumbsUp) throws BaseApiException { - Map map = new HashMap(3); + public String thumbsUp(ArticleThumbsUp articleThumbsUp) throws Exception { if (Objects.isNull(articleThumbsUp) || Objects.isNull(articleThumbsUp.getIdArticle())) { - map.put("message", "数据异常,文章不存在!"); - map.put("success", false); + 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); + throw new BusinessException("数据异常,文章不存在!"); } else { User user = UserUtils.getCurrentUserByToken(); articleThumbsUp.setIdUser(user.getIdUser()); @@ -56,15 +51,12 @@ public class ArticleThumbsUpServiceImpl extends AbstractService thumbsUpNumber = -1; } articleThumbsUpMapper.updateArticleThumbsUpNumber(articleThumbsUp.getIdArticle(), thumbsUpNumber); - map.put("success", true); - map.put("thumbsUpNumber", thumbsUpNumber); if (thumbsUpNumber > 0) { - map.put("message", "点赞成功"); + return "点赞成功"; } else { - map.put("message", "已取消点赞"); + return "已取消点赞"; } } } - return map; } } 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/PortfolioServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/PortfolioServiceImpl.java index 8ff425d..c1b622c 100644 --- a/src/main/java/com/rymcu/forest/service/impl/PortfolioServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/PortfolioServiceImpl.java @@ -3,6 +3,7 @@ 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.service.AbstractService; import com.rymcu.forest.dto.*; import com.rymcu.forest.entity.Portfolio; @@ -14,7 +15,6 @@ 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; @@ -23,9 +23,7 @@ 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 @@ -99,76 +97,66 @@ public class PortfolioServiceImpl extends AbstractService implements } @Override - public Map findUnbindArticles(Integer page, Integer rows, String searchText, Long idPortfolio) throws BaseApiException { - Map map = new HashMap(1); + public PageInfo findUnbindArticles(Integer page, Integer rows, String searchText, Long idPortfolio) throws Exception { User user = UserUtils.getCurrentUserByToken(); Portfolio portfolio = portfolioMapper.selectByPrimaryKey(idPortfolio); if (portfolio == null) { - map.put("message", "该作品集不存在或已被删除!"); + throw new ServiceException("该作品集不存在或已被删除!"); } else { if (!user.getIdUser().equals(portfolio.getPortfolioAuthorId())) { - map.put("message", "非法操作!"); + throw new ServiceException("非法操作!"); } else { PageHelper.startPage(page, rows); List articles = articleService.selectUnbindArticles(idPortfolio, searchText, user.getIdUser()); PageInfo pageInfo = new PageInfo(articles); - map = Utils.getArticlesGlobalResult(pageInfo); + return pageInfo; } } - return map; } @Override - public Map bindArticle(PortfolioArticleDTO portfolioArticle) { - Map map = new HashMap(1); + public boolean bindArticle(PortfolioArticleDTO portfolioArticle) throws Exception { 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", "绑定成功!"); + return true; } else { - map.put("message", "该文章已经在作品集下!!"); + throw new ServiceException("该文章已经在作品集下!!"); } - return map; } @Override - public Map updateArticleSortNo(PortfolioArticleDTO portfolioArticle) { - Map map = new HashMap(1); + public boolean updateArticleSortNo(PortfolioArticleDTO portfolioArticle) throws Exception { if (portfolioArticle.getIdPortfolio() == null || portfolioArticle.getIdPortfolio().equals(0)) { - map.put("message", "作品集数据异常!"); + throw new ServiceException("作品集数据异常!"); } if (portfolioArticle.getIdArticle() == null || portfolioArticle.getIdArticle().equals(0)) { - map.put("message", "文章数据异常!"); + throw new ServiceException("文章数据异常!"); } if (portfolioArticle.getSortNo() == null) { - map.put("message", "排序号不能为空!"); + throw new ServiceException("排序号不能为空!"); } Integer result = portfolioMapper.updateArticleSortNo(portfolioArticle.getIdPortfolio(), portfolioArticle.getIdArticle(), portfolioArticle.getSortNo()); if (result > 0) { - map.put("message", "更新成功!"); - } else { - map.put("message", "更新失败!"); + throw new ServiceException("更新失败!"); } - return map; + return true; } @Override - public Map unbindArticle(Long idPortfolio, Long idArticle) { - Map map = new HashMap(1); + public boolean unbindArticle(Long idPortfolio, Long idArticle) throws Exception { if (idPortfolio == null || idPortfolio.equals(0)) { - map.put("message", "作品集数据异常"); + throw new ServiceException("作品集数据异常"); } if (idArticle == null || idArticle.equals(0)) { - map.put("message", "文章数据异常"); + throw new ServiceException("文章数据异常"); } Integer result = portfolioMapper.unbindArticle(idPortfolio, idArticle); - if (result > 0) { - map.put("message", "操作成功!"); - } else { - map.put("message", "操作失败!"); + if (result == 0) { + throw new ServiceException("操作失败!"); } - return map; + return true; } @Override 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 e7fec58..c1f8ffd 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; /** @@ -38,33 +37,29 @@ public class RoleServiceImpl extends AbstractService implements RoleServic @Override @Transactional - public Map updateStatus(Long idRole, String status) { - Map map = new HashMap(1); - Integer result = roleMapper.updateStatus(idRole,status); - if(result == 0) { - map.put("message","更新失败!"); + public boolean updateStatus(Long idRole, String status) throws Exception { + 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 Exception { + 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..8418188 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,11 +38,9 @@ public class SponsorServiceImpl extends AbstractService implements Spon @Override @Transactional(rollbackFor = Exception.class) - public Map sponsorship(Sponsor sponsor) throws Exception { - Map map = new HashMap(2); + public boolean sponsorship(Sponsor sponsor) throws Exception { if (Objects.isNull(sponsor) || Objects.isNull(sponsor.getDataId()) || Objects.isNull(sponsor.getDataType())) { - map.put("success", false); - map.put("message", "数据异常"); + throw new ServiceException("数据异常"); } else { TransactionEnum result = TransactionEnum.findTransactionEnum(sponsor.getDataType()); BigDecimal money = BigDecimal.valueOf(result.getMoney()); @@ -59,9 +59,7 @@ public class SponsorServiceImpl extends AbstractService implements Spon // 更新文章赞赏数 sponsorMapper.updateArticleSponsorCount(articleDTO.getIdArticle()); } - 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 c59c9a4..2382e6f 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,17 @@ package com.rymcu.forest.service.impl; +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 +24,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 @@ -115,47 +112,42 @@ 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 ServiceException("标签名不能为空!"); } 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 ServiceException("标签 '" + 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")) { @@ -165,11 +157,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 b514a96..4a3cb39 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,8 @@ 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.ServiceException; import com.rymcu.forest.core.service.AbstractService; import com.rymcu.forest.dto.admin.TagDTO; import com.rymcu.forest.dto.admin.TopicDTO; @@ -20,9 +20,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 @@ -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 Exception { 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 ServiceException("标签名不能为空!"); } 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 ServiceException("专题 '" + 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,11 +88,9 @@ 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 @@ -110,46 +103,33 @@ public class TopicServiceImpl extends AbstractService implements TopicSer @Override @Transactional(rollbackFor = Exception.class) - public Map bindTopicTag(TopicTagDTO topicTag) { + public TopicTagDTO bindTopicTag(TopicTagDTO topicTag) throws Exception { 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 Exception { 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 PageInfo findTagsByTopicUri(String topicUri, Integer page, Integer rows) { 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 pageInfo; } } diff --git a/src/main/java/com/rymcu/forest/service/impl/UserServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/UserServiceImpl.java index c8792ff..fc97c7a 100644 --- a/src/main/java/com/rymcu/forest/service/impl/UserServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/UserServiceImpl.java @@ -2,6 +2,7 @@ package com.rymcu.forest.service.impl; import com.rymcu.forest.core.exception.CaptchaException; import com.rymcu.forest.core.exception.ContentNotExistException; +import com.rymcu.forest.core.exception.ServiceException; import com.rymcu.forest.core.service.AbstractService; import com.rymcu.forest.core.service.redis.RedisService; import com.rymcu.forest.dto.*; @@ -60,15 +61,13 @@ public class UserServiceImpl 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 void register(String email, String password, String code) throws ServiceException { 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 ServiceException("该邮箱已被注册!"); } else { user = new User(); String nickname = email.split("@")[0]; @@ -88,13 +87,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; } } } - return map; + throw new ServiceException("验证码无效!"); } private String checkNickname(String nickname) { @@ -145,39 +143,34 @@ public class UserServiceImpl extends AbstractService implements UserServic } @Override - public Map forgetPassword(String code, String password) { - Map map = new HashMap<>(2); + public String 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); + return "修改成功,正在跳转登录登陆界面!"; } - return map; } @Override @Transactional(rollbackFor = Exception.class) - public Map updateUserRole(Long idUser, Long 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(Long 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 @@ -201,13 +194,11 @@ public class UserServiceImpl extends AbstractService implements UserServic @Override @Transactional(rollbackFor = Exception.class) - public Map updateUserInfo(UserInfoDTO user) { - Map map = new HashMap(2); + public UserInfoDTO updateUserInfo(UserInfoDTO user) throws Exception { user.setNickname(formatNickname(user.getNickname())); Integer number = userMapper.checkNicknameByIdUser(user.getIdUser(), user.getNickname()); if (number > 0) { - map.put("message", "该昵称已使用!"); - return map; + throw new ServiceException("该昵称已使用!"); } if (StringUtils.isNotBlank(user.getAvatarType()) && AVATAR_SVG_TYPE.equals(user.getAvatarType())) { String avatarUrl = UploadController.uploadBase64File(user.getAvatarUrl(), 0); @@ -221,11 +212,10 @@ 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) { @@ -233,13 +223,13 @@ public class UserServiceImpl extends AbstractService implements UserServic } @Override - public Map checkNickname(Long idUser, String nickname) { + public boolean checkNickname(Long idUser, String nickname) throws ServiceException { Map map = new HashMap(2); Integer number = userMapper.checkNicknameByIdUser(idUser, nickname); if (number > 0) { - map.put("message", "该昵称已使用!"); + throw new ServiceException("该昵称已使用!"); } - return map; + return true; } @Override @@ -253,15 +243,12 @@ public class UserServiceImpl extends AbstractService implements UserServic } @Override - public Map updateUserExtend(UserExtend userExtend) { - Map map = new HashMap(2); + public UserExtend updateUserExtend(UserExtend userExtend) throws ServiceException { int result = userExtendMapper.updateByPrimaryKeySelective(userExtend); if (result == 0) { - map.put("message", "操作失败!"); - return map; + throw new ServiceException("操作失败!"); } - map.put("userExtend", userExtend); - return map; + return userExtend; } @Override @@ -270,29 +257,23 @@ public class UserServiceImpl extends AbstractService implements UserServic } @Override - public Map updateEmail(ChangeEmailDTO changeEmailDTO) { - Map map = new HashMap(2); + public String 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)) { + userMapper.updateEmail(idUser, email); + return email; } 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 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 214400c..dba0cea 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,6 +2,7 @@ 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.*; @@ -9,15 +10,12 @@ 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 @@ -66,33 +64,33 @@ public class AdminController { } @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 Exception { + 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 Exception { + boolean flag = roleService.saveRole(role); + return GlobalResultGenerator.genSuccessResult(role); } @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(role); } @GetMapping("/topics") @@ -113,12 +111,12 @@ public class AdminController { } @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("数据异常!"); } - Map map = topicService.findTagsByTopicUri(topicUri,page,rows); - return GlobalResultGenerator.genSuccessResult(map); + PageInfo pageInfo = topicService.findTagsByTopicUri(topicUri, page, rows); + return GlobalResultGenerator.genSuccessResult(pageInfo); } @GetMapping("/topic/detail/{idTopic}") @@ -138,27 +136,27 @@ public class AdminController { } @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") @@ -170,9 +168,9 @@ public class AdminController { } @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}") @@ -182,15 +180,15 @@ public class AdminController { } @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") 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 9fc6272..a2e1170 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 @@ -24,7 +24,6 @@ import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.io.UnsupportedEncodingException; import java.util.List; -import java.util.Map; import java.util.Objects; /** @@ -106,15 +105,15 @@ public class ArticleController { } @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 { + String str = articleThumbsUpService.thumbsUp(articleThumbsUp); + return GlobalResultGenerator.genSuccessResult(str); } @PostMapping("/sponsor") public GlobalResult sponsor(@RequestBody Sponsor sponsor) throws Exception { - Map map = sponsorService.sponsorship(sponsor); - return GlobalResultGenerator.genSuccessResult(map); + boolean flag = sponsorService.sponsorship(sponsor); + return GlobalResultGenerator.genSuccessResult(flag); } } 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 ab9f04e..1c2058f 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,6 +2,7 @@ package com.rymcu.forest.web.api.common; 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.result.GlobalResultMessage; @@ -68,13 +69,13 @@ public class CommonApiController { } @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) throws ServiceException { + userService.register(registerInfo.getEmail(), registerInfo.getPassword(), registerInfo.getCode()); + return GlobalResultGenerator.genSuccessResult(); } @PostMapping("/login") - public GlobalResult login(@RequestBody User user) { + public GlobalResult login(@RequestBody User user) throws ServiceException { TokenUser tokenUser = userService.login(user.getAccount(), user.getPassword()); return GlobalResultGenerator.genSuccessResult(tokenUser); } @@ -109,9 +110,9 @@ public class CommonApiController { } @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 { + String str = userService.forgetPassword(forgetPassword.getCode(), forgetPassword.getPassword()); + return GlobalResultGenerator.genSuccessResult(str); } @GetMapping("/portfolio/{id}") 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 e9324d3..5f69fec 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,5 +1,6 @@ package com.rymcu.forest.web.api.portfolio; +import com.github.pagehelper.PageInfo; import com.rymcu.forest.core.result.GlobalResult; import com.rymcu.forest.core.result.GlobalResultGenerator; import com.rymcu.forest.core.service.security.annotation.AuthorshipInterceptor; @@ -53,30 +54,30 @@ public class PortfolioController { @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 Long 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 Exception { + PageInfo pageInfo = portfolioService.findUnbindArticles(page, rows, searchText, idPortfolio); + 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 Exception { + 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 Exception { + boolean flag = portfolioService.updateArticleSortNo(portfolioArticle); + return GlobalResultGenerator.genSuccessResult(flag); } @DeleteMapping("/unbind-article") @AuthorshipInterceptor(moduleName = Module.PORTFOLIO) - public GlobalResult unbindArticle(Long idArticle, Long idPortfolio) { - Map map = portfolioService.unbindArticle(idPortfolio,idArticle); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult unbindArticle(Long idArticle, Long idPortfolio) throws Exception { + boolean flag = portfolioService.unbindArticle(idPortfolio, idArticle); + return GlobalResultGenerator.genSuccessResult(flag); } @DeleteMapping("/delete") 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 204b357..0abfa84 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; @@ -41,37 +42,37 @@ public class UserInfoController { @GetMapping("/check-nickname") @SecurityInterceptor - public GlobalResult checkNickname(@RequestParam Long idUser, @RequestParam String nickname) { - Map map = userService.checkNickname(idUser, nickname); - return GlobalResultGenerator.genSuccessResult(map); + public GlobalResult checkNickname(@RequestParam Long idUser, @RequestParam String nickname) throws ServiceException { + boolean flag = userService.checkNickname(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 Exception { + UserInfoDTO newUsers = userService.updateUserInfo(user); + return GlobalResultGenerator.genSuccessResult(newUsers); } @PatchMapping("/update-extend") @SecurityInterceptor - public GlobalResult updateUserExtend(@RequestBody UserExtend userExtend) { - Map map = userService.updateUserExtend(userExtend); + public GlobalResult updateUserExtend(@RequestBody UserExtend userExtend) throws ServiceException { + UserExtend map = userService.updateUserExtend(userExtend); return GlobalResultGenerator.genSuccessResult(map); } @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 { + String email = userService.updateEmail(changeEmailDTO); + return GlobalResultGenerator.genSuccessResult(email); } @PatchMapping("/update-password") @SecurityInterceptor public GlobalResult updatePassword(@RequestBody UpdatePasswordDTO updatePasswordDTO) { - Map map = userService.updatePassword(updatePasswordDTO); - return GlobalResultGenerator.genSuccessResult(map); + boolean flag = userService.updatePassword(updatePasswordDTO); + return GlobalResultGenerator.genSuccessResult(flag); } @GetMapping("/login-records") From db8625005d740aba1d5f51144c9f4c3b9b31e297 Mon Sep 17 00:00:00 2001 From: ronger Date: Wed, 24 Aug 2022 15:12:04 +0800 Subject: [PATCH 20/25] =?UTF-8?q?:bug:=20=E5=BE=AA=E7=8E=AF=E5=BC=95?= =?UTF-8?q?=E7=94=A8=E9=97=AE=E9=A2=98=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../rymcu/forest/handler/AccountHandler.java | 26 ++++++++++++++ .../rymcu/forest/handler/CommentHandler.java | 4 +-- .../forest/handler/event/AccountEvent.java | 19 ++++++++++ .../forest/jwt/service/RedisTokenManager.java | 7 ++-- .../forest/mapper/BankAccountMapper.java | 7 ++++ .../impl/TransactionRecordServiceImpl.java | 35 +++++++++++++------ src/main/java/mapper/BankAccountMapper.xml | 25 +++++++++---- 7 files changed, 101 insertions(+), 22 deletions(-) create mode 100644 src/main/java/com/rymcu/forest/handler/AccountHandler.java create mode 100644 src/main/java/com/rymcu/forest/handler/event/AccountEvent.java 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/CommentHandler.java b/src/main/java/com/rymcu/forest/handler/CommentHandler.java index 906e1fe..b8cab12 100644 --- a/src/main/java/com/rymcu/forest/handler/CommentHandler.java +++ b/src/main/java/com/rymcu/forest/handler/CommentHandler.java @@ -1,12 +1,12 @@ 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 com.rymcu.forest.wx.mp.utils.JsonUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.context.event.EventListener; import org.springframework.scheduling.annotation.Async; @@ -32,7 +32,7 @@ public class CommentHandler { @Async @EventListener public void processCommentCreatedEvent(CommentEvent commentEvent) throws InterruptedException { - log.info(String.format("开始执行评论发布事件:[%s]", JsonUtils.toJson(commentEvent))); + log.info(String.format("开始执行评论发布事件:[%s]", JSON.toJSONString(commentEvent))); String commentContent = commentEvent.getContent(); Integer length = commentContent.length(); if (length > MAX_PREVIEW) { 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/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/mapper/BankAccountMapper.java b/src/main/java/com/rymcu/forest/mapper/BankAccountMapper.java index 151905b..af451f7 100644 --- a/src/main/java/com/rymcu/forest/mapper/BankAccountMapper.java +++ b/src/main/java/com/rymcu/forest/mapper/BankAccountMapper.java @@ -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/service/impl/TransactionRecordServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/TransactionRecordServiceImpl.java index c1f3837..b065e2e 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,7 +33,7 @@ public class TransactionRecordServiceImpl extends AbstractService 0) { return true; @@ -154,4 +163,10 @@ public class TransactionRecordServiceImpl extends AbstractService + \ No newline at end of file From 546a46fa6b781460abe2b0dbc92a80b6251f6390 Mon Sep 17 00:00:00 2001 From: ronger Date: Thu, 25 Aug 2022 10:11:49 +0800 Subject: [PATCH 21/25] =?UTF-8?q?:arrow=5Fup:=20=E5=8D=87=E7=BA=A7=20sprin?= =?UTF-8?q?gboot=20=E7=89=88=E6=9C=AC=E8=87=B3=202.7.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 93 +++++++------------ .../rymcu/forest/config/WebMvcConfigurer.java | 3 +- 2 files changed, 34 insertions(+), 62 deletions(-) diff --git a/pom.xml b/pom.xml index 336080b..3ff8226 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,7 +97,7 @@ tk.mybatis mapper - 4.1.5 + 4.2.1 net.sourceforge.jtds @@ -95,32 +108,31 @@ 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 +163,7 @@ com.alibaba druid-spring-boot-starter - 1.2.8 + 1.2.11 org.apache.logging.log4j @@ -163,7 +175,7 @@ org.apache.logging.log4j log4j-to-slf4j - 2.17.1 + 2.18.0 org.apache.logging.log4j @@ -174,7 +186,7 @@ org.apache.logging.log4j log4j-api - 2.17.1 + 2.18.0 org.springframework.boot @@ -185,11 +197,6 @@ org.springframework.boot spring-boot-starter-thymeleaf - - net.sourceforge.nekohtml - nekohtml - 1.9.22 - org.springframework.boot spring-boot-starter-websocket @@ -197,26 +204,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 +216,6 @@ jedis-lock 1.0.0 - - com.baidu.aip - java-sdk - 4.16.5 - - - org.slf4j - slf4j-simple - - - com.google.guava - guava - - - @@ -273,12 +246,12 @@ cn.hutool hutool-core - 5.7.20 + 5.8.5 cn.hutool hutool-http - 5.7.20 + 5.8.5 @@ -292,8 +265,6 @@ - - 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"); } From 0ec8b17c8abc69b0777907c97110c7f19236bcbe Mon Sep 17 00:00:00 2001 From: ronger Date: Thu, 25 Aug 2022 10:14:36 +0800 Subject: [PATCH 22/25] =?UTF-8?q?:fire:=20=E5=88=A0=E9=99=A4=E6=97=A0?= =?UTF-8?q?=E6=95=88=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/rymcu/forest/config/ShiroConfig.java | 56 +---- .../rymcu/forest/handler/ArticleHandler.java | 6 +- .../rymcu/forest/service/WxUserService.java | 14 -- .../forest/service/impl/TagServiceImpl.java | 14 -- .../service/impl/WxUserServiceImpl.java | 55 ----- .../com/rymcu/forest/util/BaiDuAipUtils.java | 197 ------------------ .../wx/miniapp/config/WxMaConfiguration.java | 149 ------------- .../wx/miniapp/config/WxMaProperties.java | 45 ---- .../controller/WxMaMediaController.java | 80 ------- .../controller/WxMaUserController.java | 93 --------- .../forest/wx/miniapp/utils/JsonUtils.java | 28 --- .../forest/wx/mp/builder/AbstractBuilder.java | 17 -- .../forest/wx/mp/builder/ImageBuilder.java | 24 --- .../forest/wx/mp/builder/TextBuilder.java | 22 -- .../wx/mp/config/WxMpConfiguration.java | 111 ---------- .../forest/wx/mp/config/WxMpProperties.java | 46 ---- .../wx/mp/controller/WxMenuController.java | 133 ------------ .../wx/mp/controller/WxPortalController.java | 112 ---------- .../mp/controller/WxRedirectController.java | 39 ---- .../wx/mp/controller/WxoAuthController.java | 77 ------- .../forest/wx/mp/error/ErrorController.java | 29 --- .../wx/mp/error/ErrorPageConfiguration.java | 27 --- .../forest/wx/mp/handler/AbstractHandler.java | 12 -- .../wx/mp/handler/KfSessionHandler.java | 25 --- .../forest/wx/mp/handler/LocationHandler.java | 44 ---- .../forest/wx/mp/handler/LogHandler.java | 25 --- .../forest/wx/mp/handler/MenuHandler.java | 35 ---- .../forest/wx/mp/handler/MsgHandler.java | 45 ---- .../forest/wx/mp/handler/NullHandler.java | 24 --- .../forest/wx/mp/handler/ScanHandler.java | 25 --- .../mp/handler/StoreCheckNotifyHandler.java | 27 --- .../wx/mp/handler/SubscribeHandler.java | 71 ------- .../wx/mp/handler/UnsubscribeHandler.java | 27 --- .../forest/wx/mp/service/WxMenuService.java | 17 -- .../wx/mp/service/impl/WxMenuServiceImpl.java | 46 ---- .../rymcu/forest/wx/mp/utils/JsonUtils.java | 9 - .../wx/open/config/WxOpenProperties.java | 42 ---- .../open/controller/WxOpenApiController.java | 78 ------- .../controller/WxOpenNotifyController.java | 122 ----------- .../wx/open/handler/WxOpenServiceHandler.java | 67 ------ 40 files changed, 5 insertions(+), 2110 deletions(-) delete mode 100644 src/main/java/com/rymcu/forest/service/WxUserService.java delete mode 100644 src/main/java/com/rymcu/forest/service/impl/WxUserServiceImpl.java delete mode 100644 src/main/java/com/rymcu/forest/util/BaiDuAipUtils.java delete mode 100644 src/main/java/com/rymcu/forest/wx/miniapp/config/WxMaConfiguration.java delete mode 100644 src/main/java/com/rymcu/forest/wx/miniapp/config/WxMaProperties.java delete mode 100644 src/main/java/com/rymcu/forest/wx/miniapp/controller/WxMaMediaController.java delete mode 100644 src/main/java/com/rymcu/forest/wx/miniapp/controller/WxMaUserController.java delete mode 100644 src/main/java/com/rymcu/forest/wx/miniapp/utils/JsonUtils.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/builder/AbstractBuilder.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/builder/ImageBuilder.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/builder/TextBuilder.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/config/WxMpConfiguration.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/config/WxMpProperties.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/controller/WxMenuController.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/controller/WxPortalController.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/controller/WxRedirectController.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/controller/WxoAuthController.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/error/ErrorController.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/error/ErrorPageConfiguration.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/handler/AbstractHandler.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/handler/KfSessionHandler.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/handler/LocationHandler.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/handler/LogHandler.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/handler/MenuHandler.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/handler/MsgHandler.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/handler/NullHandler.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/handler/ScanHandler.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/handler/StoreCheckNotifyHandler.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/handler/SubscribeHandler.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/handler/UnsubscribeHandler.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/service/WxMenuService.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/service/impl/WxMenuServiceImpl.java delete mode 100644 src/main/java/com/rymcu/forest/wx/mp/utils/JsonUtils.java delete mode 100644 src/main/java/com/rymcu/forest/wx/open/config/WxOpenProperties.java delete mode 100644 src/main/java/com/rymcu/forest/wx/open/controller/WxOpenApiController.java delete mode 100644 src/main/java/com/rymcu/forest/wx/open/controller/WxOpenNotifyController.java delete mode 100644 src/main/java/com/rymcu/forest/wx/open/handler/WxOpenServiceHandler.java 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/handler/ArticleHandler.java b/src/main/java/com/rymcu/forest/handler/ArticleHandler.java index 8627f62..b3d372d 100644 --- a/src/main/java/com/rymcu/forest/handler/ArticleHandler.java +++ b/src/main/java/com/rymcu/forest/handler/ArticleHandler.java @@ -1,11 +1,11 @@ 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 com.rymcu.forest.wx.mp.utils.JsonUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.context.event.EventListener; import org.springframework.scheduling.annotation.Async; @@ -29,7 +29,7 @@ public class ArticleHandler { @Async public void processArticlePostEvent(ArticleEvent articleEvent) throws InterruptedException { Thread.sleep(1000); - log.info(String.format("执行文章发布相关事件:[%s]", JsonUtils.toJson(articleEvent))); + log.info(String.format("执行文章发布相关事件:[%s]", JSON.toJSONString(articleEvent))); // 发送系统通知 if (articleEvent.getNotification()) { NotificationUtils.sendAnnouncement(articleEvent.getIdArticle(), NotificationConstant.Article, articleEvent.getArticleTitle()); @@ -59,7 +59,7 @@ public class ArticleHandler { @Async public void processArticleDeleteEvent(ArticleDeleteEvent articleDeleteEvent) throws InterruptedException { Thread.sleep(1000); - log.info(String.format("执行文章删除相关事件:[%s]", JsonUtils.toJson(articleDeleteEvent))); + 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/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/TagServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/TagServiceImpl.java index c59c9a4..59b72c3 100644 --- a/src/main/java/com/rymcu/forest/service/impl/TagServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/TagServiceImpl.java @@ -3,16 +3,12 @@ package com.rymcu.forest.service.impl; 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; @@ -97,16 +93,6 @@ public class TagServiceImpl extends AbstractService implements TagService { 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, userId); } } 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/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; - } -} From e9c0475e50edfcb5d4df252fc9c16f7c0fd01c58 Mon Sep 17 00:00:00 2001 From: ronger Date: Sat, 27 Aug 2022 12:15:04 +0800 Subject: [PATCH 23/25] =?UTF-8?q?:art:=20=E4=BB=A3=E7=A0=81=E4=BC=98?= =?UTF-8?q?=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../exception/AccountExistsException.java | 28 ++++++++ .../exception/NicknameOccupyException.java | 32 +++++++++ .../core/exception/TransactionException.java | 2 +- .../service/ArticleThumbsUpService.java | 3 +- .../forest/service/PortfolioService.java | 24 +++---- .../com/rymcu/forest/service/RoleService.java | 9 +-- .../rymcu/forest/service/TopicService.java | 23 ++++--- .../service/TransactionRecordService.java | 12 ++-- .../com/rymcu/forest/service/UserService.java | 44 ++++++++---- .../impl/ArticleThumbsUpServiceImpl.java | 41 +++++------- .../service/impl/PortfolioServiceImpl.java | 59 ++++++---------- .../forest/service/impl/RoleServiceImpl.java | 9 ++- .../service/impl/SponsorServiceImpl.java | 35 +++++----- .../forest/service/impl/TagServiceImpl.java | 6 +- .../forest/service/impl/TopicServiceImpl.java | 21 +++--- .../impl/TransactionRecordServiceImpl.java | 8 +-- .../forest/service/impl/UserServiceImpl.java | 67 ++++++++++--------- .../forest/web/api/admin/AdminController.java | 42 ++++++------ .../web/api/article/ArticleController.java | 16 ++++- .../api/bank/TransactionRecordController.java | 4 +- .../web/api/common/CommonApiController.java | 36 +++++----- .../api/portfolio/PortfolioController.java | 63 ++++++++++++----- .../web/api/user/UserInfoController.java | 44 ++++++------ 23 files changed, 361 insertions(+), 267 deletions(-) create mode 100644 src/main/java/com/rymcu/forest/core/exception/AccountExistsException.java create mode 100644 src/main/java/com/rymcu/forest/core/exception/NicknameOccupyException.java 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/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/service/ArticleThumbsUpService.java b/src/main/java/com/rymcu/forest/service/ArticleThumbsUpService.java index bfe17d8..8c71913 100644 --- a/src/main/java/com/rymcu/forest/service/ArticleThumbsUpService.java +++ b/src/main/java/com/rymcu/forest/service/ArticleThumbsUpService.java @@ -13,7 +13,6 @@ public interface ArticleThumbsUpService extends Service { * * @param articleThumbsUp * @return - * @throws BaseApiException */ - String thumbsUp(ArticleThumbsUp articleThumbsUp) throws Exception; + int thumbsUp(ArticleThumbsUp articleThumbsUp); } diff --git a/src/main/java/com/rymcu/forest/service/PortfolioService.java b/src/main/java/com/rymcu/forest/service/PortfolioService.java index 120d0ed..ccf7a10 100644 --- a/src/main/java/com/rymcu/forest/service/PortfolioService.java +++ b/src/main/java/com/rymcu/forest/service/PortfolioService.java @@ -1,7 +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; @@ -35,35 +37,34 @@ 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 + * @param idUser * @return - * @throws BaseApiException */ - PageInfo findUnbindArticles(Integer page, Integer rows, String searchText, Long idPortfolio) throws Exception; + PageInfo findUnbindArticles(Integer page, Integer rows, String searchText, Long idPortfolio, Long idUser); /** * 绑定文章 - * * @param portfolioArticle * @return + * @throws ServiceException */ - boolean bindArticle(PortfolioArticleDTO portfolioArticle) throws Exception; + boolean bindArticle(PortfolioArticleDTO portfolioArticle) throws ServiceException; /** * 更新文章排序号 - * * @param portfolioArticle * @return + * @throws ServiceException */ - boolean updateArticleSortNo(PortfolioArticleDTO portfolioArticle) throws Exception; + boolean updateArticleSortNo(PortfolioArticleDTO portfolioArticle) throws ServiceException; /** * 取消绑定文章 @@ -71,8 +72,9 @@ public interface PortfolioService extends Service { * @param idPortfolio * @param idArticle * @return + * @throws ServiceException */ - boolean unbindArticle(Long idPortfolio, Long idArticle) throws Exception; + boolean unbindArticle(Long idPortfolio, Long idArticle) throws ServiceException; /** @@ -82,10 +84,8 @@ public interface PortfolioService extends Service { * @param idUser * @param roleWeights * @return - * @throws BaseApiException - * @throws IllegalAccessException */ - boolean deletePortfolio(Long idPortfolio, Long idUser, Integer roleWeights) throws BaseApiException, IllegalAccessException; + boolean deletePortfolio(Long idPortfolio, Long idUser, Integer roleWeights); /** diff --git a/src/main/java/com/rymcu/forest/service/RoleService.java b/src/main/java/com/rymcu/forest/service/RoleService.java index 3103fba..e8fca74 100644 --- a/src/main/java/com/rymcu/forest/service/RoleService.java +++ b/src/main/java/com/rymcu/forest/service/RoleService.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.entity.Role; import com.rymcu.forest.entity.User; @@ -30,18 +31,18 @@ public interface RoleService extends Service { /** * 更新用户状态 - * * @param idRole * @param status * @return + * @throws ServiceException */ - boolean updateStatus(Long idRole, String status) throws Exception; + boolean updateStatus(Long idRole, String status) throws ServiceException; /** * 添加/更新角色 - * * @param role * @return + * @throws ServiceException */ - boolean saveRole(Role role) throws Exception; + boolean saveRole(Role role) throws ServiceException; } diff --git a/src/main/java/com/rymcu/forest/service/TopicService.java b/src/main/java/com/rymcu/forest/service/TopicService.java index 7bb5641..6cbe3dc 100644 --- a/src/main/java/com/rymcu/forest/service/TopicService.java +++ b/src/main/java/com/rymcu/forest/service/TopicService.java @@ -1,7 +1,8 @@ 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.admin.TagDTO; import com.rymcu.forest.dto.admin.TopicTagDTO; import com.rymcu.forest.entity.Tag; import com.rymcu.forest.entity.Topic; @@ -15,15 +16,17 @@ public interface TopicService extends Service { /** * 获取导航主题数据 + * * @return - * */ + */ List findTopicNav(); /** * 根据 topicUri 获取主题信息及旗下标签数据 + * * @param topicUri 主题 URI * @return - * */ + */ Topic findTopicByTopicUri(String topicUri); /** @@ -31,11 +34,13 @@ public interface TopicService extends Service { * * @param topic 主题信息 * @return + * @throws ServiceException */ - Topic saveTopic(Topic topic) throws Exception; + Topic saveTopic(Topic topic) throws ServiceException; /** * 查询未绑定标签 + * * @param idTopic * @param tagTitle * @return @@ -47,24 +52,24 @@ public interface TopicService extends Service { * * @param topicTag * @return + * @throws ServiceException */ - TopicTagDTO bindTopicTag(TopicTagDTO topicTag) throws Exception; + TopicTagDTO bindTopicTag(TopicTagDTO topicTag) throws ServiceException; /** * 取消绑定标签 * * @param topicTag * @return + * @throws ServiceException */ - TopicTagDTO unbindTopicTag(TopicTagDTO topicTag) throws Exception; + TopicTagDTO unbindTopicTag(TopicTagDTO topicTag) throws ServiceException; /** * 获取主题下标签列表 * * @param topicUri - * @param page - * @param rows * @return */ - PageInfo 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 6d8f7e0..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(Long toUserId, Long formUserId, TransactionEnum transactionType) throws Exception; + TransactionRecord userTransfer(Long toUserId, Long formUserId, TransactionEnum transactionType); /** * 社区银行转账/奖励发放 * @param idUser * @param transactionType * @return - * @throws Exception */ - TransactionRecord bankTransfer(Long 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 0dc6fd3..9c74efb 100644 --- a/src/main/java/com/rymcu/forest/service/UserService.java +++ b/src/main/java/com/rymcu/forest/service/UserService.java @@ -12,7 +12,6 @@ import java.util.Map; /** - * * @author CodeGenerator * @date 2018/05/29 */ @@ -20,10 +19,11 @@ public interface UserService extends Service { /** * 通过账号查询用户信息 + * * @param account - * @throws TooManyResultsException * @return User - * */ + * @throws TooManyResultsException + */ User findByAccount(String account) throws TooManyResultsException; /** @@ -34,7 +34,7 @@ public interface UserService extends Service { * @param code 验证码 * @return Map */ - void register(String email, String password, String code) throws ServiceException; + boolean register(String email, String password, String code); /** * 登录接口 @@ -47,9 +47,10 @@ public interface UserService extends Service { /** * 通过 account 获取用户信息接口 + * * @param account 昵称 - * @return UserDTO - * */ + * @return UserDTO + */ UserDTO findUserDTOByAccount(String account); /** @@ -58,8 +59,9 @@ public interface UserService extends Service { * @param code 验证码 * @param password 密码 * @return Map + * @throws ServiceException */ - String forgetPassword(String code, String password) throws ServiceException; + boolean forgetPassword(String code, String password) throws ServiceException; /** * 更新用户角色接口 @@ -67,6 +69,7 @@ public interface UserService extends Service { * @param idUser 用户 id * @param idRole 角色 id * @return Map + * @throws ServiceException */ boolean updateUserRole(Long idUser, Long idRole) throws ServiceException; @@ -76,23 +79,26 @@ public interface UserService extends Service { * @param idUser 用户 id * @param status 状态 * @return Map + * @throws ServiceException */ boolean updateStatus(Long idUser, String status) throws ServiceException; /** * 获取用户信息 + * * @param idUser * @return */ - Map findUserInfo(Long idUser); + UserInfoDTO findUserInfo(Long idUser); /** * 更新用户信息 * * @param user * @return + * @throws ServiceException */ - UserInfoDTO updateUserInfo(UserInfoDTO user) throws Exception; + UserInfoDTO updateUserInfo(UserInfoDTO user) throws ServiceException; /** * 验证昵称是否重复 @@ -101,10 +107,11 @@ public interface UserService extends Service { * @param nickname * @return */ - boolean checkNickname(Long idUser, String nickname) throws ServiceException; + boolean checkNicknameByIdUser(Long idUser, String nickname); /** * 获取用户权限 + * * @param idUser * @return */ @@ -112,6 +119,7 @@ public interface UserService extends Service { /** * 查询作者信息 + * * @param idUser * @return */ @@ -127,6 +135,7 @@ public interface UserService extends Service { /** * 获取用户扩展信息 + * * @param account * @return */ @@ -137,8 +146,9 @@ public interface UserService extends Service { * * @param changeEmailDTO * @return + * @throws ServiceException */ - String updateEmail(ChangeEmailDTO changeEmailDTO) throws ServiceException; + boolean updateEmail(ChangeEmailDTO changeEmailDTO) throws ServiceException; /** * 更新密码 @@ -150,15 +160,25 @@ public interface UserService extends Service { /** * 查询用户列表 + * * @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/impl/ArticleThumbsUpServiceImpl.java b/src/main/java/com/rymcu/forest/service/impl/ArticleThumbsUpServiceImpl.java index 7bfd346..feb2ee1 100644 --- a/src/main/java/com/rymcu/forest/service/impl/ArticleThumbsUpServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/ArticleThumbsUpServiceImpl.java @@ -4,11 +4,9 @@ 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 org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -29,34 +27,25 @@ public class ArticleThumbsUpServiceImpl extends AbstractService @Override @Transactional(rollbackFor = Exception.class) - public String thumbsUp(ArticleThumbsUp articleThumbsUp) throws Exception { - if (Objects.isNull(articleThumbsUp) || Objects.isNull(articleThumbsUp.getIdArticle())) { + 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)) { - throw new BusinessException("数据异常,文章不存在!"); + 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); - if (thumbsUpNumber > 0) { - return "点赞成功"; - } else { - return "已取消点赞"; - } + // 取消点赞 + articleThumbsUpMapper.deleteByPrimaryKey(thumbsUp.getIdArticleThumbsUp()); + thumbsUpNumber = -1; } + // 更新文章点赞数 + articleThumbsUpMapper.updateArticleThumbsUpNumber(articleThumbsUp.getIdArticle(), thumbsUpNumber); + return thumbsUpNumber; } } } 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 c1b622c..7d417fb 100644 --- a/src/main/java/com/rymcu/forest/service/impl/PortfolioServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/PortfolioServiceImpl.java @@ -4,20 +4,18 @@ 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.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.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; @@ -64,15 +62,12 @@ public class PortfolioServiceImpl extends AbstractService implements } @Override - public Portfolio postPortfolio(Portfolio portfolio) throws BaseApiException { - User user = UserUtils.getCurrentUserByToken(); - assert user != null; + 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())); @@ -97,61 +92,47 @@ public class PortfolioServiceImpl extends AbstractService implements } @Override - public PageInfo findUnbindArticles(Integer page, Integer rows, String searchText, Long idPortfolio) throws Exception { - 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) { - throw new ServiceException("该作品集不存在或已被删除!"); + throw new BusinessException("该作品集不存在或已被删除!"); } else { - if (!user.getIdUser().equals(portfolio.getPortfolioAuthorId())) { - throw new ServiceException("非法操作!"); + 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); - return pageInfo; + List articles = articleService.selectUnbindArticles(idPortfolio, searchText, idUser); + return new PageInfo<>(articles); } } } @Override - public boolean bindArticle(PortfolioArticleDTO portfolioArticle) throws Exception { + 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); - return true; + Integer result = portfolioMapper.insertPortfolioArticle(portfolioArticle.getIdArticle(), portfolioArticle.getIdPortfolio(), maxSortNo); + if (result == 0) { + throw new ServiceException("更新失败!"); + } } else { - throw new ServiceException("该文章已经在作品集下!!"); + throw new BusinessException("该文章已经在作品集下!!"); } + return true; } @Override - public boolean updateArticleSortNo(PortfolioArticleDTO portfolioArticle) throws Exception { - if (portfolioArticle.getIdPortfolio() == null || portfolioArticle.getIdPortfolio().equals(0)) { - throw new ServiceException("作品集数据异常!"); - } - if (portfolioArticle.getIdArticle() == null || portfolioArticle.getIdArticle().equals(0)) { - throw new ServiceException("文章数据异常!"); - } - if (portfolioArticle.getSortNo() == null) { - throw new ServiceException("排序号不能为空!"); - } + public boolean updateArticleSortNo(PortfolioArticleDTO portfolioArticle) throws ServiceException { Integer result = portfolioMapper.updateArticleSortNo(portfolioArticle.getIdPortfolio(), portfolioArticle.getIdArticle(), portfolioArticle.getSortNo()); - if (result > 0) { + if (result == 0) { throw new ServiceException("更新失败!"); } return true; } @Override - public boolean unbindArticle(Long idPortfolio, Long idArticle) throws Exception { - if (idPortfolio == null || idPortfolio.equals(0)) { - throw new ServiceException("作品集数据异常"); - } - if (idArticle == null || idArticle.equals(0)) { - throw new ServiceException("文章数据异常"); - } + public boolean unbindArticle(Long idPortfolio, Long idArticle) throws ServiceException { Integer result = portfolioMapper.unbindArticle(idPortfolio, idArticle); if (result == 0) { throw new ServiceException("操作失败!"); @@ -160,7 +141,7 @@ public class PortfolioServiceImpl extends AbstractService implements } @Override - public boolean deletePortfolio(Long idPortfolio, Long idUser, Integer roleWeights) throws BaseApiException, IllegalAccessException { + public boolean deletePortfolio(Long idPortfolio, Long idUser, Integer roleWeights) { if (idPortfolio == null || idPortfolio == 0) { throw new IllegalArgumentException("作品集数据异常!"); } @@ -168,7 +149,7 @@ public class PortfolioServiceImpl extends AbstractService implements if (roleWeights > 2) { Portfolio portfolio = portfolioMapper.selectByPrimaryKey(idPortfolio); if (!idUser.equals(portfolio.getPortfolioAuthorId())) { - throw new IllegalAccessException("非法访问!"); + throw new UltraViresException("非法访问!"); } } 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 c1f8ffd..78860fb 100644 --- a/src/main/java/com/rymcu/forest/service/impl/RoleServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/RoleServiceImpl.java @@ -26,8 +26,7 @@ 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 @@ -36,8 +35,8 @@ public class RoleServiceImpl extends AbstractService implements RoleServic } @Override - @Transactional - public boolean updateStatus(Long idRole, String status) throws Exception { + @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("更新失败"); @@ -46,7 +45,7 @@ public class RoleServiceImpl extends AbstractService implements RoleServic } @Override - public boolean saveRole(Role role) throws Exception { + public boolean saveRole(Role role) throws ServiceException { Integer result; if (role.getIdRole() == null) { role.setCreatedTime(new Date()); 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 8418188..c9f2216 100644 --- a/src/main/java/com/rymcu/forest/service/impl/SponsorServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/SponsorServiceImpl.java @@ -39,25 +39,22 @@ public class SponsorServiceImpl extends AbstractService implements Spon @Override @Transactional(rollbackFor = Exception.class) public boolean sponsorship(Sponsor sponsor) throws Exception { - if (Objects.isNull(sponsor) || Objects.isNull(sponsor.getDataId()) || Objects.isNull(sponsor.getDataType())) { - throw new ServiceException("数据异常"); - } 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()); + 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("操作失败!"); } } 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 2382e6f..6c24ce7 100644 --- a/src/main/java/com/rymcu/forest/service/impl/TagServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/TagServiceImpl.java @@ -1,5 +1,6 @@ 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; @@ -120,17 +121,16 @@ public class TagServiceImpl extends AbstractService implements TagService { @Transactional(rollbackFor = Exception.class) public Tag saveTag(Tag tag) throws Exception { Integer result; - tag.setTagDescription(XssUtils.filterHtmlCode(tag.getTagDescription())); if (tag.getIdTag() == null) { if (StringUtils.isBlank(tag.getTagTitle())) { - throw new ServiceException("标签名不能为空!"); + 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()) { - throw new ServiceException("标签 '" + tag.getTagTitle() + "' 已存在!"); + throw new BusinessException("标签 '" + tag.getTagTitle() + "' 已存在!"); } } tag = new Tag(); 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 4a3cb39..d8e0746 100644 --- a/src/main/java/com/rymcu/forest/service/impl/TopicServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/TopicServiceImpl.java @@ -2,6 +2,7 @@ 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.service.AbstractService; import com.rymcu.forest.dto.admin.TagDTO; @@ -33,8 +34,7 @@ public class TopicServiceImpl extends AbstractService implements TopicSer @Override public List findTopicNav() { - List topics = topicMapper.selectTopicNav(); - return topics; + return topicMapper.selectTopicNav(); } @Override @@ -46,18 +46,18 @@ public class TopicServiceImpl extends AbstractService implements TopicSer @Override @Transactional(rollbackFor = Exception.class) - public Topic saveTopic(Topic topic) throws Exception { + public Topic saveTopic(Topic topic) throws ServiceException { Integer result; topic.setTopicDescriptionHtml(XssUtils.filterHtmlCode(topic.getTopicDescriptionHtml())); if (topic.getIdTopic() == null) { if (StringUtils.isBlank(topic.getTopicTitle())) { - throw new ServiceException("标签名不能为空!"); + 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()) { - throw new ServiceException("专题 '" + topic.getTopicTitle() + "' 已存在!"); + throw new BusinessException("专题 '" + topic.getTopicTitle() + "' 已存在!"); } } topic = new Topic(); @@ -103,7 +103,7 @@ public class TopicServiceImpl extends AbstractService implements TopicSer @Override @Transactional(rollbackFor = Exception.class) - public TopicTagDTO bindTopicTag(TopicTagDTO topicTag) throws Exception { + public TopicTagDTO bindTopicTag(TopicTagDTO topicTag) throws ServiceException { Integer result = topicMapper.insertTopicTag(topicTag.getIdTopic(), topicTag.getIdTag()); if (result == 0) { throw new ServiceException("操作失败!"); @@ -113,7 +113,7 @@ public class TopicServiceImpl extends AbstractService implements TopicSer @Override @Transactional(rollbackFor = Exception.class) - public TopicTagDTO unbindTopicTag(TopicTagDTO topicTag) throws Exception { + public TopicTagDTO unbindTopicTag(TopicTagDTO topicTag) throws ServiceException { Integer result = topicMapper.deleteTopicTag(topicTag.getIdTopic(), topicTag.getIdTag()); if (result == 0) { throw new ServiceException("操作失败!"); @@ -122,14 +122,11 @@ public class TopicServiceImpl extends AbstractService implements TopicSer } @Override - public PageInfo findTagsByTopicUri(String topicUri, Integer page, Integer rows) { + public List findTagsByTopicUri(String topicUri) { TopicDTO topic = topicMapper.selectTopicByTopicUri(topicUri); if (topic == null) { return null; } - PageHelper.startPage(page, rows); - List list = topicMapper.selectTopicTag(topic.getIdTopic()); - PageInfo pageInfo = new PageInfo(list); - return pageInfo; + 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 c1f3837..6c7dced 100644 --- a/src/main/java/com/rymcu/forest/service/impl/TransactionRecordServiceImpl.java +++ b/src/main/java/com/rymcu/forest/service/impl/TransactionRecordServiceImpl.java @@ -38,7 +38,7 @@ public class TransactionRecordServiceImpl extends AbstractService implements UserServic @Override @Transactional(rollbackFor = Exception.class) - public void register(String email, String password, String code) throws ServiceException { + 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) { - throw new ServiceException("该邮箱已被注册!"); + throw new AccountExistsException("该邮箱已被注册!"); } else { user = new User(); String nickname = email.split("@")[0]; @@ -88,11 +86,11 @@ public class UserServiceImpl extends AbstractService implements UserServic .signature(user.getSignature()) .build()); redisService.delete(email); - return; + return true; } } } - throw new ServiceException("验证码无效!"); + throw new CaptchaException(); } private String checkNickname(String nickname) { @@ -143,13 +141,16 @@ public class UserServiceImpl extends AbstractService implements UserServic } @Override - public String forgetPassword(String code, String password) throws ServiceException { + public boolean forgetPassword(String code, String password) throws ServiceException { String email = redisService.get(code); if (StringUtils.isBlank(email)) { throw new ServiceException("链接已失效"); } else { - userMapper.updatePasswordByEmail(email, Utils.entryptPassword(password)); - return "修改成功,正在跳转登录登陆界面!"; + int result = userMapper.updatePasswordByEmail(email, Utils.entryptPassword(password)); + if (result == 0) { + throw new ServiceException("密码修改失败!"); + } + return true; } } @@ -174,31 +175,21 @@ public class UserServiceImpl extends AbstractService implements UserServic } @Override - public Map findUserInfo(Long idUser) { - Map map = new HashMap(2); + public UserInfoDTO findUserInfo(Long idUser) { UserInfoDTO user = userMapper.selectUserInfo(idUser); if (user == null) { throw new ContentNotExistException("用户不存在!"); - } 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); } - return map; + return user; } @Override @Transactional(rollbackFor = Exception.class) - public UserInfoDTO updateUserInfo(UserInfoDTO user) throws Exception { + public UserInfoDTO updateUserInfo(UserInfoDTO user) throws ServiceException { user.setNickname(formatNickname(user.getNickname())); Integer number = userMapper.checkNicknameByIdUser(user.getIdUser(), user.getNickname()); if (number > 0) { - throw new ServiceException("该昵称已使用!"); + throw new NicknameOccupyException("该昵称已使用!"); } if (StringUtils.isNotBlank(user.getAvatarType()) && AVATAR_SVG_TYPE.equals(user.getAvatarType())) { String avatarUrl = UploadController.uploadBase64File(user.getAvatarUrl(), 0); @@ -222,12 +213,10 @@ public class UserServiceImpl extends AbstractService implements UserServic return nickname.replaceAll("\\.", ""); } - @Override - public boolean checkNickname(Long idUser, String nickname) throws ServiceException { - Map map = new HashMap(2); + public boolean checkNicknameByIdUser(Long idUser, String nickname) { Integer number = userMapper.checkNicknameByIdUser(idUser, nickname); if (number > 0) { - throw new ServiceException("该昵称已使用!"); + return false; } return true; } @@ -244,7 +233,7 @@ public class UserServiceImpl extends AbstractService implements UserServic @Override public UserExtend updateUserExtend(UserExtend userExtend) throws ServiceException { - int result = userExtendMapper.updateByPrimaryKeySelective(userExtend); + int result = userExtendMapper.updateByPrimaryKey(userExtend); if (result == 0) { throw new ServiceException("操作失败!"); } @@ -257,14 +246,17 @@ public class UserServiceImpl extends AbstractService implements UserServic } @Override - public String updateEmail(ChangeEmailDTO changeEmailDTO) throws ServiceException { + 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) && vCode.equals(code)) { - userMapper.updateEmail(idUser, email); - return email; + int result = userMapper.updateEmail(idUser, email); + if (result == 0) { + throw new ServiceException("修改邮箱失败!"); + } + return true; } throw new CaptchaException(); } @@ -297,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/web/api/admin/AdminController.java b/src/main/java/com/rymcu/forest/web/api/admin/AdminController.java index dba0cea..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 @@ -6,6 +6,7 @@ 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.*; @@ -19,7 +20,7 @@ import java.util.List; /** * @author ronger - * */ + */ @RestController @RequestMapping("/api/v1/admin") public class AdminController { @@ -42,7 +43,7 @@ public class AdminController { 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); @@ -50,13 +51,13 @@ public class AdminController { } @GetMapping("/user/{idUser}/role") - public GlobalResult> userRole(@PathVariable Long 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); @@ -76,25 +77,25 @@ public class AdminController { } @PatchMapping("/role/update-status") - public GlobalResult updateRoleStatus(@RequestBody Role role) throws Exception { + 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) throws Exception { + public GlobalResult addRole(@RequestBody Role role) throws ServiceException { boolean flag = roleService.saveRole(role); - return GlobalResultGenerator.genSuccessResult(role); + return GlobalResultGenerator.genSuccessResult(flag); } @PutMapping("/role/post") - public GlobalResult updateRole(@RequestBody Role role) throws Exception { + public GlobalResult updateRole(@RequestBody Role role) throws Exception { boolean flag = roleService.saveRole(role); - return GlobalResultGenerator.genSuccessResult(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); @@ -102,31 +103,33 @@ public class AdminController { } @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("参数异常!"); } - PageInfo pageInfo = topicService.findTagsByTopicUri(topicUri, page, rows); + 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){ + 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); @@ -160,7 +163,7 @@ public class AdminController { } @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); @@ -174,7 +177,7 @@ public class AdminController { } @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); } @@ -224,5 +227,4 @@ public class AdminController { } - } 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 a2e1170..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; @@ -105,13 +106,22 @@ public class ArticleController { } @PostMapping("/thumbs-up") - public GlobalResult thumbsUp(@RequestBody ArticleThumbsUp articleThumbsUp) throws Exception { - String str = articleThumbsUpService.thumbsUp(articleThumbsUp); - return GlobalResultGenerator.genSuccessResult(str); + 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 { + 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/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/common/CommonApiController.java b/src/main/java/com/rymcu/forest/web/api/common/CommonApiController.java index 1c2058f..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,6 +2,7 @@ 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; @@ -10,6 +11,7 @@ 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.*; +import org.apache.shiro.authc.UnknownAccountException; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; @@ -42,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) { @@ -53,25 +55,23 @@ 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) throws ServiceException { - userService.register(registerInfo.getEmail(), registerInfo.getPassword(), registerInfo.getCode()); - return GlobalResultGenerator.genSuccessResult(); + public GlobalResult register(@RequestBody UserRegisterInfoDTO registerInfo) { + boolean flag = userService.register(registerInfo.getEmail(), registerInfo.getPassword(), registerInfo.getCode()); + return GlobalResultGenerator.genSuccessResult(flag); } @PostMapping("/login") @@ -90,7 +90,7 @@ public class CommonApiController { 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); + PageInfo pageInfo = new PageInfo<>(list); return GlobalResultGenerator.genSuccessResult(pageInfo); } @@ -98,7 +98,7 @@ public class CommonApiController { 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); + PageInfo pageInfo = new PageInfo<>(list); return GlobalResultGenerator.genSuccessResult(pageInfo); } @@ -110,9 +110,9 @@ public class CommonApiController { } @PatchMapping("/forget-password") - public GlobalResult forgetPassword(@RequestBody ForgetPasswordDTO forgetPassword) throws ServiceException { - String str = userService.forgetPassword(forgetPassword.getCode(), forgetPassword.getPassword()); - return GlobalResultGenerator.genSuccessResult(str); + public GlobalResult forgetPassword(@RequestBody ForgetPasswordDTO forgetPassword) throws ServiceException { + boolean flag = userService.forgetPassword(forgetPassword.getCode(), forgetPassword.getPassword()); + return GlobalResultGenerator.genSuccessResult(flag); } @GetMapping("/portfolio/{id}") @@ -126,7 +126,7 @@ public class CommonApiController { 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); + PageInfo pageInfo = new PageInfo<>(list); return GlobalResultGenerator.genSuccessResult(pageInfo); } @@ -134,7 +134,7 @@ public class CommonApiController { 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); + PageInfo pageInfo = new PageInfo<>(list); return GlobalResultGenerator.genSuccessResult(pageInfo); } @@ -142,7 +142,7 @@ public class CommonApiController { 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); + PageInfo pageInfo = new PageInfo<>(list); return GlobalResultGenerator.genSuccessResult(pageInfo); } 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 5f69fec..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,6 +1,7 @@ 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; @@ -32,62 +33,94 @@ public class PortfolioController { private UserService userService; @GetMapping("/detail/{idPortfolio}") - public GlobalResult detail(@PathVariable Long 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 Long idPortfolio) throws Exception { - PageInfo pageInfo = portfolioService.findUnbindArticles(page, rows, searchText, idPortfolio); + 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) throws Exception { + 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) throws Exception { + 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(Long idArticle, Long idPortfolio) throws Exception { + 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(Long idPortfolio) throws BaseApiException, IllegalAccessException { + 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 map = portfolioService.deletePortfolio(idPortfolio, idUser, roleWeights); - return GlobalResultGenerator.genSuccessResult(map); + boolean flag = portfolioService.deletePortfolio(idPortfolio, idUser, roleWeights); + return GlobalResultGenerator.genSuccessResult(flag); } } 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 0abfa84..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 @@ -35,57 +35,59 @@ public class UserInfoController { @GetMapping("/detail/{idUser}") @SecurityInterceptor - public GlobalResult detail(@PathVariable Long 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 Long idUser, @RequestParam String nickname) throws ServiceException { - boolean flag = userService.checkNickname(idUser, nickname); + 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) throws Exception { - UserInfoDTO newUsers = userService.updateUserInfo(user); - return GlobalResultGenerator.genSuccessResult(newUsers); + 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) throws ServiceException { - UserExtend 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) throws ServiceException { - String email = userService.updateEmail(changeEmailDTO); - return GlobalResultGenerator.genSuccessResult(email); + 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) { + 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); } } From 4ee0aaacd4b38dd8da73f7ff2fee16b385bb57e9 Mon Sep 17 00:00:00 2001 From: ronger Date: Sat, 27 Aug 2022 20:44:45 +0800 Subject: [PATCH 24/25] =?UTF-8?q?:fire:=20=E5=88=A0=E9=99=A4=E6=97=A0?= =?UTF-8?q?=E6=95=88=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/pom.xml b/pom.xml index 3ff8226..78ce411 100644 --- a/pom.xml +++ b/pom.xml @@ -99,11 +99,6 @@ mapper 4.2.1 - - net.sourceforge.jtds - jtds - 1.3.1 - com.github.pagehelper From 00a4c4bf70755aa10080676250ddb32b5773a739 Mon Sep 17 00:00:00 2001 From: ronger Date: Sat, 27 Aug 2022 22:15:41 +0800 Subject: [PATCH 25/25] =?UTF-8?q?:art:=20=E4=BB=A3=E7=A0=81=E4=BC=98?= =?UTF-8?q?=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/rymcu/forest/config/MybatisConfigurer.java | 3 +-- src/main/java/com/rymcu/forest/entity/ForestFile.java | 8 ++++++-- src/main/resources/application.yml | 2 +- 3 files changed, 8 insertions(+), 5 deletions(-) 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/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/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