code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
package com.heima.behavior.service;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
public interface ApReadBehaviorService {
/**
* 保存阅读行为
* @param dto
* @return
*/
public ResponseResult readBehavior(ReadBehaviorDto dto);
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-behavior/src/main/java/com/heima/behavior/service/ApReadBehaviorService.java
|
Java
|
unknown
| 323
|
package com.heima.behavior.service;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
/**
* <p>
* APP不喜欢行为表 服务类
* </p>
*
* @author itheima
*/
public interface ApUnlikesBehaviorService {
/**
* 不喜欢
* @param dto
* @return
*/
public ResponseResult unLike(UnLikesBehaviorDto dto);
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-behavior/src/main/java/com/heima/behavior/service/ApUnlikesBehaviorService.java
|
Java
|
unknown
| 397
|
package com.heima.behavior.service.impl;
import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
@Slf4j
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {
@Autowired
private CacheService cacheService;
@Override
public ResponseResult like(LikesBehaviorDto dto) {
//1.检查参数
if (dto == null || dto.getArticleId() == null || checkParam(dto)) {
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
//2.是否登录
ApUser user = AppThreadLocalUtil.getUser();
if (user == null) {
return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
}
//3.点赞 保存数据
if (dto.getOperation() == 0) {
Object obj = cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
if (obj != null) {
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已点赞");
}
// 保存当前key
log.info("保存当前key:{} ,{}, {}", dto.getArticleId(), user.getId(), dto);
cacheService.hPut(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString(), JSON.toJSONString(dto));
} else {
// 删除当前key
log.info("删除当前key:{}, {}", dto.getArticleId(), user.getId());
cacheService.hDelete(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
}
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
/**
* 检查参数
*
* @return
*/
private boolean checkParam(LikesBehaviorDto dto) {
if (dto.getType() > 2 || dto.getType() < 0 || dto.getOperation() > 1 || dto.getOperation() < 0) {
return true;
}
return false;
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-behavior/src/main/java/com/heima/behavior/service/impl/ApLikesBehaviorServiceImpl.java
|
Java
|
unknown
| 2,543
|
package com.heima.behavior.service.impl;
import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
@Autowired
private CacheService cacheService;
@Override
public ResponseResult readBehavior(ReadBehaviorDto dto) {
//1.检查参数
if (dto == null || dto.getArticleId() == null) {
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
//2.是否登录
ApUser user = AppThreadLocalUtil.getUser();
if (user == null) {
return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
}
//更新阅读次数
String readBehaviorJson = (String) cacheService.hGet(BehaviorConstants.READ_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
if (StringUtils.isNotBlank(readBehaviorJson)) {
ReadBehaviorDto readBehaviorDto = JSON.parseObject(readBehaviorJson, ReadBehaviorDto.class);
dto.setCount((short) (readBehaviorDto.getCount() + dto.getCount()));
}
// 保存当前key
log.info("保存当前key:{} {} {}", dto.getArticleId(), user.getId(), dto);
cacheService.hPut(BehaviorConstants.READ_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString(), JSON.toJSONString(dto));
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-behavior/src/main/java/com/heima/behavior/service/impl/ApReadBehaviorServiceImpl.java
|
Java
|
unknown
| 2,093
|
package com.heima.behavior.service.impl;
import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApUnlikesBehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.UnLikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* <p>
* APP不喜欢行为表 服务实现类
* </p>
*
* @author itheima
*/
@Slf4j
@Service
public class ApUnlikesBehaviorServiceImpl implements ApUnlikesBehaviorService {
@Autowired
private CacheService cacheService;
@Override
public ResponseResult unLike(UnLikesBehaviorDto dto) {
if (dto.getArticleId() == null) {
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
ApUser user = AppThreadLocalUtil.getUser();
if (user == null) {
return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
}
if (dto.getType() == 0) {
log.info("保存当前key:{} ,{}, {}", dto.getArticleId(), user.getId(), dto);
cacheService.hPut(BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString(), JSON.toJSONString(dto));
} else {
log.info("删除当前key:{} ,{}, {}", dto.getArticleId(), user.getId(), dto);
cacheService.hDelete(BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
}
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-behavior/src/main/java/com/heima/behavior/service/impl/ApUnlikesBehaviorServiceImpl.java
|
Java
|
unknown
| 1,831
|
package com.heima.search;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableDiscoveryClient
@EnableAsync
public class SearchApplication {
public static void main(String[] args) {
SpringApplication.run(SearchApplication.class,args);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/SearchApplication.java
|
Java
|
unknown
| 490
|
package com.heima.search.config;
import lombok.Getter;
import lombok.Setter;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticSearchConfig {
private String host;
private int port;
@Bean
public RestHighLevelClient client(){
System.out.println(host);
System.out.println(port);
return new RestHighLevelClient(RestClient.builder(
new HttpHost(
host,
port,
"http"
)
));
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/config/ElasticSearchConfig.java
|
Java
|
unknown
| 899
|
package com.heima.search.config;
import com.heima.search.interceptor.AppTokenInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* author Link
*
* @version 1.0
* @date 2025/4/6 16:29
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AppTokenInterceptor()).addPathPatterns("/**");
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/config/WebMvcConfig.java
|
Java
|
unknown
| 616
|
package com.heima.search.controller.v1;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ApAssociateWordsService;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
/**
* author Link
*
* @version 1.0
* @date 2025/4/14 19:43
*/
@RestController
@RequestMapping("/api/v1/associate")
public class ApAssociateWordsController {
@Autowired
private ApAssociateWordsService apAssociateWordsService;
/**
* 联想词
* @param dto
* @return
*/
@PostMapping("/search")
public ResponseResult search(@RequestBody UserSearchDto dto){
return apAssociateWordsService.search(dto);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/controller/v1/ApAssociateWordsController.java
|
Java
|
unknown
| 972
|
package com.heima.search.controller.v1;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ApUserSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import java.io.IOException;
/**
* author Link
*
* @version 1.0
* @date 2025/4/14 18:58
*/
@RestController
@RequestMapping("/api/v1/history")
@Slf4j
public class ApUserSearchController {
@Autowired
ApUserSearchService apUserSearchService;
/**
* 加载搜索历史
* @return
*/
@PostMapping("/load")
public ResponseResult load() {
log.info("加载搜索历史");
return apUserSearchService.load();
}
/**
* 删除搜索历史
* @param historySearchDto
*/
@PostMapping("/del")
public ResponseResult del(@RequestBody HistorySearchDto historySearchDto){
log.info("删除搜索历史:{}",historySearchDto);
return apUserSearchService.del(historySearchDto);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/controller/v1/ApUserSearchController.java
|
Java
|
unknown
| 1,361
|
package com.heima.search.controller.v1;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import java.io.IOException;
/**
* author Link
*
* @version 1.0
* @date 2025/4/14 14:06
*/
@RestController
@RequestMapping("/api/v1/article/search")
@Slf4j
public class ArticleSearchController {
@Autowired
ArticleSearchService articleSearchService;
@PostMapping("/search")
public ResponseResult search(@RequestBody UserSearchDto dto) throws IOException {
return articleSearchService.search(dto);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/controller/v1/ArticleSearchController.java
|
Java
|
unknown
| 978
|
package com.heima.search.interceptor;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AppTokenInterceptor implements HandlerInterceptor {
/**
* 得到header中的用户信息,并且存入到当前线程中
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String userId = request.getHeader("userId");
if (userId!=null){
ApUser apUser=new ApUser();
apUser.setId(Integer.valueOf(userId));
AppThreadLocalUtil.setUser(apUser);
}
return true;
}
/**
* 清理线程中的数据
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
AppThreadLocalUtil.clear();
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/interceptor/AppTokenInterceptor.java
|
Java
|
unknown
| 1,293
|
package com.heima.search.listener;
import com.alibaba.fastjson.JSON;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.search.vos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
@Slf4j
public class SyncArticleListener {
@Autowired
private RestHighLevelClient restHighLevelClient;
@KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
public void onMessage(String message){
if(StringUtils.isNotBlank(message)){
log.info("消费者SyncArticleListener,message={}",message);
SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);
IndexRequest indexRequest = new IndexRequest("app_info_article");
indexRequest.id(searchArticleVo.getId().toString());
indexRequest.source(message, XContentType.JSON);
try {
restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
log.error("消费者失败sync es error={}",e);
}
}
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/listener/SyncArticleListener.java
|
Java
|
unknown
| 1,585
|
package com.heima.search.pojos;
import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* 联想词表
* </p>
*
* @author itheima
*/
@Data
@Document("ap_associate_words")
public class ApAssociateWords implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
/**
* 联想词
*/
private String associateWords;
/**
* 创建时间
*/
private Date createdTime;
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/pojos/ApAssociateWords.java
|
Java
|
unknown
| 541
|
package com.heima.search.pojos;
import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* APP用户搜索信息表
* </p>
* @author itheima
*/
@Data
@Document("ap_user_search")
public class ApUserSearch implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
private String id;
/**
* 用户ID
*/
private Integer userId;
/**
* 搜索词
*/
private String keyword;
/**
* 创建时间
*/
private Date createdTime;
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/pojos/ApUserSearch.java
|
Java
|
unknown
| 626
|
package com.heima.search.service;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
/**
* author Link
*
* @version 1.0
* @date 2025/4/14 19:45
*/
public interface ApAssociateWordsService {
/**
* 联想词
* @param dto
* @return
*/
public ResponseResult search(UserSearchDto dto);
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/service/ApAssociateWordsService.java
|
Java
|
unknown
| 370
|
package com.heima.search.service;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.HistorySearchDto;
/**
* author Link
*
* @version 1.0
* @date 2025/4/14 17:03
*/
public interface ApUserSearchService {
/**
* 保存用户搜索记录
* @param keyword
* @param userId
*/
public void insert(String keyword,Integer userId);
/**
* 加载搜索历史
* @return
*/
ResponseResult load();
/**
* 删除搜索历史
* @param historySearchDto
*/
ResponseResult del(HistorySearchDto historySearchDto);
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/service/ApUserSearchService.java
|
Java
|
unknown
| 617
|
package com.heima.search.service;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import java.io.IOException;
/**
* author Link
*
* @version 1.0
* @date 2025/4/14 14:10
*/
public interface ArticleSearchService {
public ResponseResult search(UserSearchDto dto) throws IOException;
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/service/ArticleSearchService.java
|
Java
|
unknown
| 350
|
package com.heima.search.service.impl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.pojos.ApAssociateWords;
import com.heima.search.service.ApAssociateWordsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* author Link
*
* @version 1.0
* @date 2025/4/14 19:46
*/
@Service
@Slf4j
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {
@Autowired
MongoTemplate mongoTemplate;
/**
* 关键词搜索
* @param userSearchDto
* @return
*/
@Override
public ResponseResult search(UserSearchDto userSearchDto) {
//1 参数检查
if(userSearchDto == null || StringUtils.isBlank(userSearchDto.getSearchWords())){
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
//分页检查
if (userSearchDto.getPageSize() > 20) {
userSearchDto.setPageSize(20);
}
//3 执行查询 模糊查询
Query query = Query.query(Criteria.where("associateWords").regex(".*?\\" + userSearchDto.getSearchWords() + ".*"));
query.limit(userSearchDto.getPageSize());
List<ApAssociateWords> wordsList = mongoTemplate.find(query, ApAssociateWords.class);
return ResponseResult.okResult(wordsList);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/service/impl/ApAssociateWordsServiceImpl.java
|
Java
|
unknown
| 1,758
|
package com.heima.search.service.impl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 保存用户搜索历史记录
* @param keyword
* @param userId
*/
@Override
@Async
public void insert(String keyword, Integer userId) {
//1.查询当前用户的搜索关键词
Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);
//2.存在 更新创建时间
if(apUserSearch != null){
apUserSearch.setCreatedTime(new Date());
mongoTemplate.save(apUserSearch);
return;
}
//3.不存在,判断当前历史记录总数量是否超过10
apUserSearch = new ApUserSearch();
apUserSearch.setUserId(userId);
apUserSearch.setKeyword(keyword);
apUserSearch.setCreatedTime(new Date());
Query query1 = Query.query(Criteria.where("userId").is(userId));
query1.with(Sort.by(Sort.Direction.DESC,"createdTime"));
List<ApUserSearch> apUserSearchList = mongoTemplate.find(query1, ApUserSearch.class);
if(apUserSearchList == null || apUserSearchList.size() < 10){
mongoTemplate.save(apUserSearch);
}else {
ApUserSearch lastUserSearch = apUserSearchList.get(apUserSearchList.size() - 1);
mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(lastUserSearch.getId())),apUserSearch);
}
}
/**
* 加载搜索历史
* @return
*/
@Override
public ResponseResult load() {
ApUser user = AppThreadLocalUtil.getUser();
if(user==null){
ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
}
List<ApUserSearch> userSearchList = mongoTemplate.find(Query.query(Criteria.where("userId").is(user.getId()))
.with(Sort.by(Sort.Direction.DESC, "createdTime")),
ApUserSearch.class);
return ResponseResult.okResult(userSearchList);
}
/**
* 删除搜索历史
* @param historySearchDto
* @return
*/
@Override
public ResponseResult del(HistorySearchDto historySearchDto) {
if(historySearchDto.getId() == null){
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
ApUser user = AppThreadLocalUtil.getUser();
if(user==null){
return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
}
mongoTemplate.remove(Query.query(Criteria.where("id").is(historySearchDto.getId())
.and("userId").is(user.getId())),
ApUserSearch.class);
/*ApUser user = AppThreadLocalUtil.getUser();
if(historySearchDto.getId() != null && user != null){
mongoTemplate.remove(Query.query(Criteria.where("id").is(historySearchDto.getId())
.and("userId").is(user.getId())),
ApUserSearch.class);
}*/
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/service/impl/ApUserSearchServiceImpl.java
|
Java
|
unknown
| 4,051
|
package com.heima.search.service.impl;
import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
@Autowired
private RestHighLevelClient restHighLevelClient;
@Autowired
private ApUserSearchService apUserSearchService;
/**
* es文章分页检索
*
* @param dto
* @return
*/
@Override
public ResponseResult search(UserSearchDto dto) throws IOException {
//1.检查参数
if(dto == null || StringUtils.isBlank(dto.getSearchWords())){
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
//异步调用保存搜索记录
ApUser user = AppThreadLocalUtil.getUser();
if (user!=null && dto.getFromIndex()==0){
apUserSearchService.insert(dto.getSearchWords(),user.getId() );
}
//2.设置查询条件
SearchRequest searchRequest = new SearchRequest("app_info_article");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//布尔查询
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//关键字的分词之后查询
QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").field("content").defaultOperator(Operator.OR);
boolQueryBuilder.must(queryStringQueryBuilder);
//查询小于mindate的数据
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime().getTime());
boolQueryBuilder.filter(rangeQueryBuilder);
//分页查询
searchSourceBuilder.from(0);
searchSourceBuilder.size(dto.getPageSize());
//按照发布时间倒序查询
searchSourceBuilder.sort("publishTime", SortOrder.DESC);
//设置高亮 title
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("title");
highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
highlightBuilder.postTags("</font>");
searchSourceBuilder.highlighter(highlightBuilder);
searchSourceBuilder.query(boolQueryBuilder);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//3.结果封装返回
List<Map> list = new ArrayList<>();
SearchHit[] hits = searchResponse.getHits().getHits();
for (SearchHit hit : hits) {
String json = hit.getSourceAsString();
Map map = JSON.parseObject(json, Map.class);
//处理高亮
if(hit.getHighlightFields() != null && hit.getHighlightFields().size() > 0){
Text[] titles = hit.getHighlightFields().get("title").getFragments();
String title = StringUtils.join(titles);
//高亮标题
map.put("h_title",title);
}else {
//原始标题
map.put("h_title",map.get("title"));
}
list.add(map);
}
return ResponseResult.okResult(list);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-search/src/main/java/com/heima/search/service/impl/ArticleSearchServiceImpl.java
|
Java
|
unknown
| 4,410
|
package com.heima.user;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
* author Link
*
* @version 1.0
* @date 2025/4/2 16:17
*/
@SpringBootApplication
@EnableDiscoveryClient
@MapperScan("com.heima.user.mapper")
@EnableFeignClients(basePackages = "com.heima.apis")
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class,args);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/UserApplication.java
|
Java
|
unknown
| 677
|
package com.heima.user.config;
import com.heima.user.interceptor.AppTokenInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AppTokenInterceptor()).addPathPatterns("/**");
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/config/WebMvcConfig.java
|
Java
|
unknown
| 543
|
package com.heima.user.controller.v1;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.LoginDto;
import com.heima.user.service.ApUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
/**
* author Link
*
* @version 1.0
* @date 2025/4/2 16:23
*/
@RequestMapping("/api/v1/login")
@RestController
@Api(value = "app端用户登录", tags = "app端用户登录")
public class ApUserLoginController {
@Autowired
private ApUserService apUserService;
@PostMapping("login_auth")
@ApiOperation("用户登入")
public ResponseResult login(@RequestBody LoginDto dto){
return apUserService.login(dto);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/controller/v1/ApUserLoginController.java
|
Java
|
unknown
| 1,016
|
package com.heima.user.controller.v1;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.service.ApUserRealnameService;
import com.heima.user.service.ApUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
/**
* author Link
*
* @version 1.0
* @date 2025/4/17 13:38
*/
@RestController
@RequestMapping("/api/v1/auth")
@Slf4j
public class ApUserRealnameController {
@Autowired
private ApUserRealnameService apUserRealnameService;
/**
* 用户审核查询列表
* @return
*/
@PostMapping("/list")
public ResponseResult list(@RequestBody AuthDto dto){
log.info("用户审核查询列表:{}",dto);
return apUserRealnameService.listRelname(dto);
}
/**
* 用户身份审核通过
* @param dto
* @return
*/
@PostMapping("/authPass")
public ResponseResult authPass(@RequestBody AuthDto dto){
log.info("用户身份审核通过:{}",dto);
return apUserRealnameService.updateStatus(dto, ApUserRealname.Status.PASS.getCode());
}
/**
* 用户身份审核失败
* @param dto
* @return
*/
@PostMapping("/authFail")
public ResponseResult authFail(@RequestBody AuthDto dto){
log.info("用户身份审核失败:{}",dto);
return apUserRealnameService.updateStatus(dto,ApUserRealname.Status.FAILED.getCode());
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/controller/v1/ApUserRealnameController.java
|
Java
|
unknown
| 1,780
|
package com.heima.user.controller.v1;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.user.service.ApUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
@RestController
@RequestMapping("/api/v1/user")
public class UserRelationController {
@Autowired
private ApUserRelationService apUserRelationService;
@PostMapping("/user_follow")
public ResponseResult follow(@RequestBody UserRelationDto dto){
return apUserRelationService.follow(dto);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/controller/v1/UserRelationController.java
|
Java
|
unknown
| 823
|
package com.heima.user.interceptor;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AppTokenInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String userId = request.getHeader("userId");
if(userId != null){
//存入到当前线程中
ApUser apUser = new ApUser();
apUser.setId(Integer.valueOf(userId));
AppThreadLocalUtil.setUser(apUser);
}
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
AppThreadLocalUtil.clear();
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/interceptor/AppTokenInterceptor.java
|
Java
|
unknown
| 982
|
package com.heima.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.heima.model.user.pojos.ApUser;
import org.apache.ibatis.annotations.Mapper;
/**
* author Link
*
* @version 1.0
* @date 2025/4/2 16:32
*/
@Mapper
public interface ApUserMapper extends BaseMapper<ApUser> {
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/mapper/ApUserMapper.java
|
Java
|
unknown
| 312
|
package com.heima.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.heima.model.user.pojos.ApUserRealname;
import org.apache.ibatis.annotations.Mapper;
/**
* author Link
*
* @version 1.0
* @date 2025/4/17 13:49
*/
@Mapper
public interface ApUserRealnameMapper extends BaseMapper<ApUserRealname> {
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/mapper/ApUserRealnameMapper.java
|
Java
|
unknown
| 337
|
package com.heima.user.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUserRealname;
/**
* author Link
*
* @version 1.0
* @date 2025/4/17 13:48
*/
public interface ApUserRealnameService extends IService<ApUserRealname> {
/**
* 用户审核查询列表
* @param dto
* @return
*/
ResponseResult listRelname(AuthDto dto);
/**
* 用户身份审核 2:失败 9:通过
* @param dto
* @return
*/
ResponseResult updateStatus(AuthDto dto,Short status);
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/service/ApUserRealnameService.java
|
Java
|
unknown
| 664
|
package com.heima.user.service;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.UserRelationDto;
public interface ApUserRelationService {
/**
* 用户关注/取消关注
* @param dto
* @return
*/
public ResponseResult follow(UserRelationDto dto);
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/service/ApUserRelationService.java
|
Java
|
unknown
| 316
|
package com.heima.user.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
/**
* author Link
*
* @version 1.0
* @date 2025/4/2 16:31
*/
public interface ApUserService extends IService<ApUser> {
/**
* 用户登入
* @param dto
* @return
*/
public ResponseResult login(LoginDto dto);
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/service/ApUserService.java
|
Java
|
unknown
| 516
|
package com.heima.user.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
/**
* author Link
*
* @version 1.0
* @date 2025/4/17 13:48
*/
@Service
@Transactional
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
@Autowired
private ApUserMapper apUserMapper;
@Autowired
private IWemediaClient wemediaClient;
/**
* 用户审核查询列表
*
* @param dto
* @return
*/
@Override
public ResponseResult listRelname(AuthDto dto) {
if (dto == null) {
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
dto.checkParam();
IPage page = new Page(dto.getPage(), dto.getSize());
LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.<ApUserRealname>lambdaQuery().orderByDesc(ApUserRealname::getCreatedTime);
if (dto.getStatus() != null) {
wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
}
page = page(page, wrapper);
ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
responseResult.setData(page.getRecords());
return responseResult;
}
/**
* 用户身份审核
*
* @param dto
* @return
*/
@Override
public ResponseResult updateStatus(AuthDto dto , Short status) {
if (dto == null ||dto.getId()==null) {
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
ApUserRealname apUserRealname = new ApUserRealname();
apUserRealname.setId(dto.getId());
apUserRealname.setStatus(status);
if (StringUtils.isNotBlank(dto.getMsg())){
apUserRealname.setReason(dto.getMsg());
}
updateById(apUserRealname);
//审核成功,需要创建自媒体用户
if (apUserRealname.getStatus()==ApUserRealname.Status.PASS.getCode()){
ResponseResult responseResult = createWmUserAndAuthor(dto);
if(responseResult != null){
return responseResult;
}
}
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
/**
* 创建自媒体用户
* @param dto
* @return
*/
private ResponseResult createWmUserAndAuthor(AuthDto dto) {
Integer userRealnameId = dto.getId();
//查询用户认证信息
ApUserRealname apUserRealname = getById(userRealnameId);
if(apUserRealname == null){
return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
}
//查询app端用户信息
Integer userId = apUserRealname.getUserId();
ApUser apUser = apUserMapper.selectById(userId);
if(apUser == null){
return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
}
//创建自媒体账户
WmUser wmUser = wemediaClient.findWmUserByName(apUser.getName());
if(wmUser == null){
wmUser= new WmUser();
wmUser.setApUserId(apUser.getId());
wmUser.setCreatedTime(new Date());
wmUser.setName(apUser.getName());
wmUser.setPassword(apUser.getPassword());
wmUser.setSalt(apUser.getSalt());
wmUser.setPhone(apUser.getPhone());
wmUser.setStatus(9);
wemediaClient.saveWmUser(wmUser);
}
apUser.setFlag((short)1);
apUserMapper.updateById(apUser);
return null;
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/service/impl/ApUserRealnameServiceImpl.java
|
Java
|
unknown
| 4,651
|
package com.heima.user.service.impl;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {
@Autowired
RedisTemplate redisTemplate;
@Autowired
private CacheService cacheService;
/**
* 用户关注/取消关注
*
* @param dto
* @return
*/
@Override
public ResponseResult follow(UserRelationDto dto) {
//1 参数校验
if (dto.getOperation() == null || dto.getOperation() < 0 || dto.getOperation() > 1) {
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
//2 判断是否登录
ApUser user = AppThreadLocalUtil.getUser();
if (user == null) {
return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
}
Integer apUserId = user.getId();
//3 关注 apuser:follow: apuser:fans:
Integer followUserId = dto.getAuthorId();
if (dto.getOperation() == 0) {
// 将对方写入我的关注中
cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION + apUserId, followUserId.toString(), System.currentTimeMillis());
// 将我写入对方的粉丝中
cacheService.zAdd(BehaviorConstants.APUSER_FANS_RELATION+ followUserId, apUserId.toString(), System.currentTimeMillis());
} else {
// 取消关注
cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION + apUserId, followUserId.toString());
cacheService.zRemove(BehaviorConstants.APUSER_FANS_RELATION + followUserId, apUserId.toString());
}
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/service/impl/ApUserRelationServiceImpl.java
|
Java
|
unknown
| 2,249
|
package com.heima.user.service.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import java.util.HashMap;
import java.util.Map;
/**
* author Link
*
* @version 1.0
* @date 2025/4/2 16:31
*/
@Service
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
@Override
public ResponseResult login(LoginDto dto) {
//1.正常登入,用户名和密码
if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())){
ApUser dbUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone,dto.getPhone()));
if(dbUser==null){
return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在");
}
//对比密码
String salt = dbUser.getSalt();
String oldPassword = dbUser.getPassword();
String password = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
if(!password.equals(oldPassword)){
return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
}
//登入成功
String token = AppJwtUtil.getToken(dbUser.getId().longValue());
Map<String, Object> map = new HashMap<>();
map.put("token", token);
dbUser.setSalt("");
dbUser.setPassword("");
map.put("user", dbUser);
return ResponseResult.okResult(map);
}else {
//游客登入
Map<String, Object> map = new HashMap<>();
String token = AppJwtUtil.getToken(0L);
map.put("token", token);
return ResponseResult.okResult(map);
}
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-user/src/main/java/com/heima/user/service/impl/ApUserServiceImpl.java
|
Java
|
unknown
| 2,565
|
package com.heima.wemedia;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableDiscoveryClient
@MapperScan("com.heima.wemedia.mapper")
@EnableFeignClients(basePackages = "com.heima.apis")
@EnableAsync //开启异步调用
public class WemediaApplication {
public static void main(String[] args) {
SpringApplication.run(WemediaApplication.class,args);
}
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
@Bean
public MessageConverter messageConverter(){
// 1.定义消息转换器
Jackson2JsonMessageConverter jackson2JsonMessageConverter = new Jackson2JsonMessageConverter();
// 2.配置自动创建消息id,用于识别不同消息,也可以在业务中基于ID判断是否是重复消息
jackson2JsonMessageConverter.setCreateMessageIds(true);
return jackson2JsonMessageConverter;
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/WemediaApplication.java
|
Java
|
unknown
| 1,836
|
package com.heima.wemedia.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* author Link
*
* @version 1.0
* @date 2025/4/9 16:19
*/
@Configuration
@ComponentScan("com.heima.apis.article.fallback")
public class InitConfig {
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/config/InitConfig.java
|
Java
|
unknown
| 318
|
package com.heima.wemedia.config;
import com.heima.wemedia.interceptor.WmTokenInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* author Link
*
* @version 1.0
* @date 2025/4/6 16:29
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new WmTokenInterceptor()).addPathPatterns("/**");
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/config/WebMvcConfig.java
|
Java
|
unknown
| 616
|
package com.heima.wemedia.controller.v1;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
@Slf4j
@RestController
@RequestMapping("/login")
public class LoginController {
@Autowired
private WmUserService wmUserService;
@PostMapping("/in")
public ResponseResult login(@RequestBody WmLoginDto dto){
log.info("自媒体端登录:{}",dto);
return wmUserService.login(dto);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/controller/v1/LoginController.java
|
Java
|
unknown
| 854
|
package com.heima.wemedia.controller.v1;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.ChannelPageDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.wemedia.service.WmChannelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* <p>
* 频道信息表 前端控制器
* </p>
*
* @author azl
* @since 2025-04-06
*/
@RestController
@RequestMapping("/api/v1/channel")
@Slf4j
public class WmChannelController {
@Autowired
private WmChannelService wmChannelService;
/**
* 查询所有频道
* @return
*/
@GetMapping("/channels")
public ResponseResult findAll() {
log.info("查询所有频道");
return wmChannelService.findAll();
}
/**
* 频道名称模糊分页查询
* @return
*/
@PostMapping("/list")
public ResponseResult list(@RequestBody ChannelPageDto dto){
log.info("频道名称模糊分页查询:{}",dto);
return wmChannelService.listPage(dto);
}
/**
* 新增频道
* @param wmChannel
* @return
*/
@PostMapping("/save")
public ResponseResult saveChannel(@RequestBody WmChannel wmChannel){
log.info("新增频道:{}",wmChannel);
return wmChannelService.saveChannel(wmChannel);
}
/**
* 删除频道
* @param id
* @return
*/
@GetMapping("/del/{id}")
public ResponseResult delChannel(@PathVariable("id") Integer id){
log.info("删除频道:{}",id);
return wmChannelService.delChannel(id);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/controller/v1/WmChannelController.java
|
Java
|
unknown
| 1,682
|
package com.heima.wemedia.controller.v1;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/**
* author Link
*
* @version 1.0
* @date 2025/4/6 16:37
*/
@RestController
@RequestMapping("/api/v1/material")
@Slf4j
public class WmMaterialController {
@Autowired
private WmMaterialService wmMaterialService;
@Autowired
private WmMaterialMapper wmMaterialMapper;
/**
* 图片上传
* @param multipartFile
* @return
*/
@PostMapping("/upload_picture")
public ResponseResult uploadPicture(MultipartFile multipartFile){
log.info("图片上传:{}", multipartFile);
return wmMaterialService.uploadPicture(multipartFile);
}
/**
* 分页查询图片
* @param dto
* @return
*/
@PostMapping("/list")
public ResponseResult list(@RequestBody WmMaterialDto dto){
log.info("分页查询图片:{}", dto);
return wmMaterialService.list(dto);
}
/**
* 根据id删除素材
* @param id
*/
@GetMapping("/del_picture/{id}")
public void deletePicture(@PathVariable Integer id){
log.info("根据id删除素材:{}",id);
wmMaterialMapper.deleteById(id);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/controller/v1/WmMaterialController.java
|
Java
|
unknown
| 1,584
|
package com.heima.wemedia.controller.v1;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* <p>
* 自媒体图文内容信息表 前端控制器
* </p>
*
* @author azl
* @since 2025-04-06
*/
@RestController
@RequestMapping("/api/v1/news")
@Slf4j
public class WmNewsController {
@Autowired
private WmNewsService wmNewsService;
/**
* 文章列表
* @param dto
* @return
*/
@PostMapping("/list")
public ResponseResult list(@RequestBody WmNewsPageReqDto dto){
log.info("查询文章列表:{}", dto);
return wmNewsService.list(dto);
}
/**
* 提交或保存文章
* @param dto
* @return
*/
@PostMapping("/submit")
public ResponseResult submitNews(@RequestBody WmNewsDto dto){
log.info("提交或保存文章:{}",dto);
return wmNewsService.submitNews(dto);
}
/**
* 文章上架或下架
* @param dto
* @return
*/
@PostMapping("/down_or_up")
public ResponseResult downOrUp(@RequestBody WmNewsDto dto){
log.info("文章上架或下架:{}",dto);
return wmNewsService.downOrUp(dto);
}
/**
* 管理员查询文章列表
* @param dto
* @return
*/
@PostMapping("/list_vo")
public ResponseResult list_vo(@RequestBody NewsAuthDto dto){
log.info("管理员查询文章列表:{}", dto);
return wmNewsService.listVo(dto);
}
/**
* 管理员查询文章详情
* @return
*/
@GetMapping("/one_vo/{id}")
public ResponseResult one_vo(@PathVariable Integer id){
log.info("管理员查询文章详情:{}", id);
return wmNewsService.one_vo(id);
}
/**
* 审核失败
* @return
*/
@PostMapping("/auth_fail")
public ResponseResult auth_fail(@RequestBody NewsAuthDto dto){
log.info("审核失败:{}",dto);
return wmNewsService.auth_fail(dto);
}
/**
* 审核通过
* @param dto
* @return
*/
@PostMapping("/auth_pass")
public ResponseResult auth_pass(@RequestBody NewsAuthDto dto){
log.info("人工审核通过:{}",dto);
return wmNewsService.auth_pass(dto);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/controller/v1/WmNewsController.java
|
Java
|
unknown
| 2,570
|
package com.heima.wemedia.controller.v1;
/**
* author Link
*
* @version 1.0
* @date 2025/4/16 13:31
*/
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmSensitivePageDto;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.wemedia.service.WmSensitiveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController()
@RequestMapping("/api/v1/sensitive")
@Slf4j
public class WmSensitiveController {
@Autowired
private WmSensitiveService wmSensitiveService;
/**
* 新增敏感词
* @return
*/
@PostMapping("/save")
public ResponseResult save(@RequestBody WmSensitive dto){
log.info("新增敏感词");
return wmSensitiveService.addSensitive(dto);
}
/**
* 查询敏感词列表
* @param dto
* @return
*/
@PostMapping("/list")
public ResponseResult list(@RequestBody WmSensitivePageDto dto){
log.info("查询敏感词列表:{}",dto);
return wmSensitiveService.listSensitive(dto);
}
/**
* 修改敏感词
* @param wmSensitive
* @return
*/
@PostMapping("/update")
public ResponseResult update(@RequestBody WmSensitive wmSensitive){
log.info("修改敏感词:{}",wmSensitive);
return wmSensitiveService.updateSensitive(wmSensitive);
}
/**
* 删除敏感词
* @param id
* @return
*/
@DeleteMapping("/del/{id}")
public ResponseResult delete(@PathVariable Integer id){
log.info("删除敏感词:{}",id);
return wmSensitiveService.deleteSensitive(id);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/controller/v1/WmSensitiveController.java
|
Java
|
unknown
| 1,735
|
package com.heima.wemedia.feign;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.service.WmUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* author Link
*
* @version 1.0
* @date 2025/4/17 14:58
*/
@RestController
public class WemediaClient implements IWemediaClient {
@Autowired
private WmUserService wmUserService;
@Override
@GetMapping("/api/v1/user/findByName/{name}")
public WmUser findWmUserByName(@PathVariable("name") String name) {
return wmUserService.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, name));
}
@Override
@PostMapping("/api/v1/wm_user/save")
public ResponseResult saveWmUser(@RequestBody WmUser wmUser) {
wmUserService.save(wmUser);
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
@Override
@GetMapping("/api/v1/channel/list")
public ResponseResult getChannels() {
return null;
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/feign/WemediaClient.java
|
Java
|
unknown
| 1,236
|
package com.heima.wemedia.interceptor;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* author Link
*
* @version 1.0
* @date 2025/4/6 16:16
*/
public class WmTokenInterceptor implements HandlerInterceptor {
/**
* 得到header中的用户信息,并且存入到当前线程中
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String userId = request.getHeader("userId");
if (userId!=null){
WmUser wmUser = new WmUser();
wmUser.setId(Integer.valueOf(userId));
WmThreadLocalUtil.setUser(wmUser);
}
return true;
}
/**
* 清理线程中的数据
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//WmThreadLocalUtil.clear();
}
/**
* 清理线程中的数据
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
WmThreadLocalUtil.clear();
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/interceptor/WmTokenInterceptor.java
|
Java
|
unknown
| 1,786
|
package com.heima.wemedia.listener;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* author Link
*
* @version 1.0
* @date 2025/4/13 15:25
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class ReviewArticleDelayListener {
private final WmNewsAutoScanService wmNewsAutoScanService;
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "ReviewArticleDelay.queue"),
exchange = @Exchange(name = "ReviewArticleDelay.direct",delayed = "true"),
key = {"ReviewArticleDelay"}
))
public void listenReviewArticleDelay(Integer id){
try {
wmNewsAutoScanService.autoScanWmNews(id);
} catch (Exception e) {
log.error("审核文章的消息发送失败,文章id:{}",id, e);
}
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/listener/ReviewArticleDelayListener.java
|
Java
|
unknown
| 1,180
|
package com.heima.wemedia.listener;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* author Link
*
* @version 1.0
* @date 2025/4/13 14:19
*/
@Component
@RequiredArgsConstructor
@Slf4j
public class ReviewArticleListener {
private final WmNewsAutoScanService wmNewsAutoScanService;
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "ReviewArticle.queue"),
exchange = @Exchange(name = "ReviewArticle.direct",type = ExchangeTypes.DIRECT),
key = {"ReviewArticle"}
))
public void listenReviewArticle(Integer id){
try {
wmNewsAutoScanService.autoScanWmNews(id);
} catch (Exception e) {
log.error("审核文章的消息发送失败,文章id:{}",id, e);
}
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/listener/ReviewArticleListener.java
|
Java
|
unknown
| 1,218
|
package com.heima.wemedia.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.heima.model.wemedia.pojos.WmChannel;
/**
* <p>
* 频道信息表 Mapper 接口
* </p>
*
* @author azl
* @since 2025-04-06
*/
public interface WmChannelMapper extends BaseMapper<WmChannel> {
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/mapper/WmChannelMapper.java
|
Java
|
unknown
| 303
|
package com.heima.wemedia.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.heima.model.wemedia.pojos.WmMaterial;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface WmMaterialMapper extends BaseMapper<WmMaterial> {
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/mapper/WmMaterialMapper.java
|
Java
|
unknown
| 262
|
package com.heima.wemedia.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.heima.model.wemedia.pojos.WmNews;
/**
* <p>
* 自媒体图文内容信息表 Mapper 接口
* </p>
*
* @author azl
* @since 2025-04-06
*/
public interface WmNewsMapper extends BaseMapper<WmNews> {
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/mapper/WmNewsMapper.java
|
Java
|
unknown
| 310
|
package com.heima.wemedia.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface WmNewsMaterialMapper extends BaseMapper<WmNewsMaterial> {
void saveRelations(@Param("materialIds") List<Integer> materialIds,
@Param("newsId") Integer newsId,
@Param("type")Short type);
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/mapper/WmNewsMaterialMapper.java
|
Java
|
unknown
| 524
|
package com.heima.wemedia.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.heima.model.wemedia.pojos.WmSensitive;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface WmSensitiveMapper extends BaseMapper<WmSensitive> {
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/mapper/WmSensitiveMapper.java
|
Java
|
unknown
| 267
|
package com.heima.wemedia.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.heima.model.wemedia.pojos.WmUser;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface WmUserMapper extends BaseMapper<WmUser> {
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/mapper/WmUserMapper.java
|
Java
|
unknown
| 296
|
package com.heima.wemedia.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.ChannelPageDto;
import com.heima.model.wemedia.pojos.WmChannel;
/**
* <p>
* 频道信息表 服务类
* </p>
*
* @author azl
* @since 2025-04-06
*/
public interface WmChannelService extends IService<WmChannel> {
/**
* 查询所有频道
* @return
*/
public ResponseResult findAll();
/**
* 频道名称模糊分页查询
* @param dto
* @return
*/
ResponseResult listPage(ChannelPageDto dto);
/**
* 新增频道
* @param wmChannel
* @return
*/
ResponseResult saveChannel(WmChannel wmChannel);
/**
* 删除频道
* @param id
* @return
*/
ResponseResult delChannel(Integer id);
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/service/WmChannelService.java
|
Java
|
unknown
| 878
|
package com.heima.wemedia.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import org.springframework.web.multipart.MultipartFile;
public interface WmMaterialService extends IService<WmMaterial> {
/**
* 图片上传
* @param multipartFile
* @return
*/
public ResponseResult uploadPicture(MultipartFile multipartFile);
/**
* 分页查询图片
* @param dto
* @return
*/
public ResponseResult list(WmMaterialDto dto);
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/service/WmMaterialService.java
|
Java
|
unknown
| 648
|
package com.heima.wemedia.service;
public interface WmNewsAutoScanService {
/**
* 自媒体文章审核
* @param id 自媒体文章id
*/
public void autoScanWmNews(Integer id);
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/service/WmNewsAutoScanService.java
|
Java
|
unknown
| 204
|
package com.heima.wemedia.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmNews;
/**
* <p>
* 自媒体图文内容信息表 服务类
* </p>
*
* @author azl
* @since 2025-04-06
*/
public interface WmNewsService extends IService<WmNews> {
/**
* 文章列表
* @param dto
* @return
*/
public ResponseResult list(WmNewsPageReqDto dto);
/**
* 提交或保存文章
* @param dto
* @return
*/
public ResponseResult submitNews(WmNewsDto dto);
/**
* 文章上架或下架
* @param dto
* @return
*/
ResponseResult downOrUp(WmNewsDto dto);
/**
* 管理员查询文章列表
* @param dto
* @return
*/
ResponseResult listVo(NewsAuthDto dto);
/**
* 管理员查询文章详情
* @param id
* @return
*/
ResponseResult one_vo(Integer id);
/**
* 审核失败
* @param dto
* @return
*/
ResponseResult auth_fail(NewsAuthDto dto);
/**
* 审核通过
* @param dto
* @return
*/
ResponseResult auth_pass(NewsAuthDto dto);
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/service/WmNewsService.java
|
Java
|
unknown
| 1,374
|
package com.heima.wemedia.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmSensitivePageDto;
import com.heima.model.wemedia.pojos.WmSensitive;
/**
* author Link
*
* @version 1.0
* @date 2025/4/9 17:02
*/
public interface WmSensitiveService extends IService<WmSensitive> {
/**
* 新增敏感词
* @param dto
* @return
*/
public ResponseResult addSensitive(WmSensitive dto);
/**
* 查询敏感词列表
* @param dto
* @return
*/
ResponseResult listSensitive(WmSensitivePageDto dto);
/**
* 修改敏感词
* @param wmSensitive
* @return
*/
ResponseResult updateSensitive(WmSensitive wmSensitive);
/**
* id
* @param id
* @return
*/
ResponseResult deleteSensitive(Integer id);
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/service/WmSensitiveService.java
|
Java
|
unknown
| 908
|
package com.heima.wemedia.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
public interface WmUserService extends IService<WmUser> {
/**
* 自媒体端登录
* @param dto
* @return
*/
public ResponseResult login(WmLoginDto dto);
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/service/WmUserService.java
|
Java
|
unknown
| 426
|
package com.heima.wemedia.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.ChannelPageDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.service.WmChannelService;
import com.sun.xml.bind.v2.TODO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Objects;
/**
* <p>
* 频道信息表 服务实现类
* </p>
*
* @author azl
* @since 2025-04-06
*/
@Service
@Transactional
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {
/**
* 查询所有频道
* @return
*/
@Override
public ResponseResult findAll() {
return ResponseResult.okResult(list());
}
/**
* 频道名称模糊分页查询
* @param dto
* @return
*/
@Override
public ResponseResult listPage(ChannelPageDto dto) {
if(dto==null){
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
dto.checkParam();
Page page = new Page(dto.getPage(), dto.getSize());
LambdaQueryWrapper<WmChannel> wrapper = new LambdaQueryWrapper<>();
wrapper.orderByDesc(WmChannel::getCreatedTime);
if(dto.getStatus()!=null){
wrapper=wrapper.eq(WmChannel::getStatus, dto.getStatus());
}
if(StringUtils.isNotBlank(dto.getName())&&!dto.getName().equals("")){
wrapper = Wrappers.<WmChannel>lambdaQuery().like(WmChannel::getName, dto.getName());
}
page = page(page, wrapper);
ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
responseResult.setData(page.getRecords());
return responseResult;
}
/**
* 新增频道
* @param wmChannel
* @return
*/
@Override
public ResponseResult saveChannel(WmChannel wmChannel) {
if(wmChannel==null|| StringUtils.isBlank(wmChannel.getName())){
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
List<WmChannel> list = list();
for (WmChannel channel : list) {
if(channel.getName().equals(wmChannel.getName())){
return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
}
}
wmChannel.setCreatedTime(new Date());
//todo 设置默认排序
//wmChannel.setOrd(1);
save(wmChannel);
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
/**
* 删除频道
* @param id
* @return
*/
@Override
public ResponseResult delChannel(Integer id) {
if(id==null){
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
removeById(id);
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/service/impl/WmChannelServiceImpl.java
|
Java
|
unknown
| 3,479
|
package com.heima.wemedia.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;
@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
@Autowired
private FileStorageService fileStorageService;
/**
* 上传图片
* @param multipartFile
* @return
*/
@Override
public ResponseResult uploadPicture(MultipartFile multipartFile) {
//1.检查参数
if (multipartFile==null || multipartFile.getSize() == 0){
return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
}
//2.上传图片到minio
String fileName = UUID.randomUUID().toString().replace("-", "");
//aa.jpg
String originalFilename = multipartFile.getOriginalFilename();
String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
String fileId = null;
try {
fileId = fileStorageService.uploadImgFile("", fileName + postfix, multipartFile.getInputStream());
log.info("上传图片到minio,fileId:{}",fileId);
} catch (IOException e) {
e.printStackTrace();
log.info("WmMaterialServiceImpl---上传图片到minio失败");
}
//3.保存图片信息到mysql
WmMaterial wmMaterial = new WmMaterial();
wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
wmMaterial.setUrl(fileId);
wmMaterial.setIsCollection((short) 0);
wmMaterial.setType((short) 0);
wmMaterial.setCreatedTime(new Date());
save(wmMaterial);
//4.返回结果
return ResponseResult.okResult(wmMaterial);
}
/**
* 分页查询图片
* @param dto
* @return
*/
@Override
public ResponseResult list(WmMaterialDto dto) {
dto.checkParam();
IPage page = new Page(dto.getPage(), dto.getSize());
LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
if (dto.getIsCollection()!=null && dto.getIsCollection()==1){
lambdaQueryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
}
//分页查询
lambdaQueryWrapper.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId())
.orderByDesc(WmMaterial::getCreatedTime);
page = page(page, lambdaQueryWrapper);
ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
responseResult.setData(page.getRecords());
return responseResult;
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/service/impl/WmMaterialServiceImpl.java
|
Java
|
unknown
| 3,706
|
package com.heima.wemedia.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;
/**
* author Link
*
* @version 1.0
* @date 2025/4/8 16:56
*/
@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
@Autowired
private WmNewsMapper wmNewsMapper;
/**
* 自媒体文章审核
* @param id 自媒体文章id
*/
@Override
@Async //标明当前方法是一个异步方法
public void autoScanWmNews(Integer id) {
WmNews wmNews = wmNewsMapper.selectById(id);
if(wmNews==null){
throw new RuntimeException("WmNewsAutoScanServiceImpl--文章不存在");
}
if(wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
//从内容中提取纯文本内容和图片
Map<String, Object> textAndImages = handleTextAndImages(wmNews);
//自管理的敏感词过滤
boolean isSensitiveScan = handleSensitiveScan((String) textAndImages.get("content"),wmNews);
if(!isSensitiveScan)return;
//审核文本
boolean isTestScan= handleTextScan((String) textAndImages.get("content"),wmNews);
if (!isTestScan)return;
//审核图片
boolean isImageScan= handleImageScan((List<String>) textAndImages.get("image"),wmNews);
if (!isImageScan)return;
//审核成功,保存app端的相关文章数据
ResponseResult responseResult = saveAppArticle(wmNews);
if (!responseResult.getCode().equals(200)){
throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核:保存app端的相关文章数据失败");
}
//回填article的id
wmNews.setArticleId((Long) responseResult.getData());
//修改状态
updateWmNews(wmNews,(short) 9,"审核成功");
log.info("审核成功,已发布!:{}",id);
}
}
@Autowired
private WmSensitiveMapper wmSensitiveMapper;
/**
* 自管理的敏感词审核
* @param content
* @param wmNews
* @return
*/
private boolean handleSensitiveScan(String content, WmNews wmNews) {
boolean flag=true;
//1.获取所有的敏感词
List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));
List<String> sensitives = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
//2.初始化敏感词库
SensitiveWordUtil.initMap(sensitives);
//3.查看文章中是否包含敏感词
Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
if(map.size()>0){
//存在敏感词,修改审核状态为审核失败
updateWmNews(wmNews,(short) 2,"审核失败,内容存在敏感词"+map);
flag=false;
}
return flag;
}
/**
* 修改文章内容
* @param wmNews
* @param status
* @param reason
*/
private void updateWmNews(WmNews wmNews, short status, String reason) {
wmNews.setStatus(status);
wmNews.setReason(reason);
wmNewsMapper.updateById(wmNews);
}
@Autowired
private IArticleClient articleClient;
@Autowired
private WmChannelMapper wmChannelMapper;
@Autowired
private WmUserMapper wmUserMapper;
/**
* 保存app端的相关文章数据
* @param wmNews
*/
private ResponseResult saveAppArticle(WmNews wmNews) {
ArticleDto dto = new ArticleDto();
//属性拷贝
BeanUtils.copyProperties(wmNews,dto);
//文章的布局
dto.setLayout(wmNews.getType());
//频道
WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
if(wmChannel!=null){
dto.setChannelName(wmChannel.getName());
}
//作者
dto.setAuthorId(wmNews.getUserId().longValue());
WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
if(wmUser!=null){
dto.setAuthorName(wmUser.getName());
}
//设置文章id
if(wmNews.getArticleId()!=null){
dto.setId(wmNews.getArticleId());
}
dto.setCreatedTime(new Date());
return articleClient.saveArticle(dto);
}
/**
* 审核图片
* @param image
* @param wmNews
* @return
*/
private boolean handleImageScan(List<String> image, WmNews wmNews) {
//1.下载图片到minio
//2.审核图片
return true;
}
/**
* 审核文本
* @param content
* @param wmNews
* @return
*/
private boolean handleTextScan(String content, WmNews wmNews) {
//1.阿里云自动审核
//2.修改wmnews的状态
return true;
}
/**
* 从内容中提取纯文本内容和图片
* @param wmNews
* @return
*/
private Map<String, Object> handleTextAndImages(WmNews wmNews) {
//储存纯文本内容
StringBuilder text = new StringBuilder();
//储存图片路径
List<String> images = new ArrayList<>();
List<Map> maps = JSONArray.parseArray(wmNews.getContent(), Map.class);
for (Map map : maps) {
if (map.get("type").equals("text")){
text.append(map.get("value"));
}
if(map.get("type").equals("image")){
images.add((String) map.get("value"));
}
}
//2.提取文章的封面图片
if(StringUtils.isNotBlank(wmNews.getImages())){
String[] split = wmNews.getImages().split(",");
images.addAll(Arrays.asList(split));
}
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("content",text.toString());
resultMap.put("images",images);
return resultMap;
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/service/impl/WmNewsAutoScanServiceImpl.java
|
Java
|
unknown
| 7,131
|
package com.heima.wemedia.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.article.IArticleClient;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.*;
import com.heima.model.wemedia.vos.NewsAuthVo;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.*;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.configuration.beanutils.BeanHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;
/**
* <p>
* 自媒体图文内容信息表 服务实现类
* </p>
*
* @author azl
* @since 2025-04-06
*/
@Service
@Slf4j
@RequiredArgsConstructor
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
private final WmNewsMaterialMapper wmNewsMaterialMapper;
private final WmMaterialMapper wmMaterialMapper;
private final RabbitTemplate rabbitTemplate;
private final WmNewsAutoScanService wmNewsAutoScanService;
private final KafkaTemplate<String,Object> kafkaTemplate;
private final WmUserMapper wmUserMapper;
private final WmChannelMapper wmChannelMapper;
private final IArticleClient articleClient;
/**
* 文章列表
*
* @param dto
* @return
*/
@Override
public ResponseResult list(WmNewsPageReqDto dto) {
IPage page = new Page(dto.getPage(), dto.getSize());
LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
if (dto.getStatus() != null) {
lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
}
if (dto.getChannelId() != null) {
lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
}
if (StringUtils.isNotBlank(dto.getKeyword())) {
lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
}
if (dto.getBeginPubDate() != null) {
lambdaQueryWrapper.ge(WmNews::getPublishTime, dto.getBeginPubDate());
}
if (dto.getEndPubDate() != null) {
lambdaQueryWrapper.le(WmNews::getPublishTime, dto.getEndPubDate());
}
lambdaQueryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
lambdaQueryWrapper.orderByDesc(WmNews::getPublishTime);
page = page(page, lambdaQueryWrapper);
ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
responseResult.setData(page.getRecords());
return responseResult;
}
/**
* 提交或保存文章
*
* @param dto
* @return
*/
@Override
public ResponseResult submitNews(WmNewsDto dto) {
//0.条件判断
if (dto == null || dto.getContent() == null) {
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
//1.保存或修改文章
WmNews wmNews = new WmNews();
//属性拷贝 属性名词和类型相同才能拷贝
BeanUtils.copyProperties(dto, wmNews);
//封面图片 list---> string
if (dto.getImages() != null && dto.getImages().size() > 0) {
String images = StringUtils.join(dto.getImages(), ",");
wmNews.setImages(images);
}
//如果当前封面类型为自动 -1
if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
wmNews.setType(null);
}
saveOrUpdateWmNews(wmNews);
//2.判断是否为草稿 如果为草稿结束当前方法
if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
log.info("存入草稿成功!");
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
//3.不是草稿,保存文章内容图片与素材的关系
//获取到文章内容中的图片信息
List<String> materials = extractUrlInfo(dto.getContent());
saveRelativeInfoForContent(materials,wmNews.getId());
//4.不是草稿,保存文章封面图片与素材的关系,如果当前布局是自动,需要匹配封面图片
saveRelativeInfoForCover(dto,wmNews,materials);
//审核文章
//wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
if(dto.getPublishTime().getTime()<=System.currentTimeMillis()){
rabbitTemplate.convertAndSend("ReviewArticle.direct","ReviewArticle",wmNews.getId());
}else{
Integer time = (int) (wmNews.getPublishTime().getTime() - System.currentTimeMillis());
rabbitTemplate.convertAndSend("ReviewArticleDelay.direct",
"ReviewArticleDelay",
wmNews.getId(),
message -> {message.getMessageProperties().setDelay(time);
return message;}
);
}
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
/**
* 文章的上下架
* @param dto
* @return
*/
@Override
public ResponseResult downOrUp(WmNewsDto dto) {
//1.检查参数
if(dto.getId() == null){
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
//2.查询文章
WmNews wmNews = getById(dto.getId());
if(wmNews == null){
return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
}
//3.判断文章是否已发布
if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前文章不是发布状态,不能上下架");
}
//4.修改文章enable
if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable,dto.getEnable())
.eq(WmNews::getId,wmNews.getId()));
log.info("修改文章成功!文章id:{},修改文章配置enable:{}",wmNews.getId(),dto.getEnable());
}
//发送消息,通知article端修改文章配置
if(wmNews.getArticleId() != null){
Map<String,Object> map = new HashMap<>();
map.put("articleId",wmNews.getArticleId());
map.put("enable",dto.getEnable());
kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
log.info("生产者发送消息成功!");
}
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
/**
* 第一个功能:如果当前封面类型为自动,则设置封面类型的数据
* 匹配规则:
* 1,如果内容图片大于等于1,小于3 单图 type 1
* 2,如果内容图片大于等于3 多图 type 3
* 3,如果内容没有图片,无图 type 0
*
* 第二个功能:保存封面图片与素材的关系
* @param dto
* @param wmNews
* @param materials
*/
private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
List<String> images = dto.getImages();
//如果当前封面类型为自动,则设置封面类型的数据
if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
//多图
if(materials.size() >= 3){
wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
images = materials.stream().limit(3).collect(Collectors.toList());
}else if(materials.size() >= 1 && materials.size() < 3){
//单图
wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
images = materials.stream().limit(1).collect(Collectors.toList());
}else {
//无图
wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
}
//修改文章
if(images != null && images.size() > 0){
wmNews.setImages(StringUtils.join(images,","));
}
updateById(wmNews);
}
if(images != null && images.size() > 0){
saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
}
}
/**
* 获取到文章内容中的图片信息
* @param content
* @return
*/
private List<String> extractUrlInfo(String content) {
List<String> materials = new ArrayList<>();
List<Map> maps = JSONArray.parseArray(content, Map.class);
for (Map map : maps) {
if (map.get("type").equals("image")){
String imageUrl = (String) map.get("value");
materials.add(imageUrl);
}
}
return materials;
}
/**
* 保存文章内容图片与素材的关系
*/
private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
saveRelativeInfo(materials, newsId, WemediaConstants.WM_CONTENT_REFERENCE);
}
/**
* 保存文章图片与素材的关系到数据库中
* @param materials
* @param newsId
* @param wmContentReference
*/
private void saveRelativeInfo(List<String> materials, Integer newsId, Short wmContentReference) {
if(materials!=null&&!materials.isEmpty()){
List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));
if(wmMaterials==null||wmMaterials.size()==0){
throw new CustomException(AppHttpCodeEnum.MATERIALS_REFERENCE_FAIL);
}
if(wmMaterials.size()!=materials.size()){
throw new CustomException(AppHttpCodeEnum.MATERIALS_REFERENCE_FAIL);
}
/*List<Integer> ids = new ArrayList<>();
for (WmMaterial wmMaterial : wmMaterials) {
Integer id = wmMaterial.getId();
ids.add(id);
}*/
List<Integer> ids = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
wmNewsMaterialMapper.saveRelations(ids,newsId,wmContentReference);
}
}
/**
* 保存或修改文章
*
* @param wmNews
*/
private void saveOrUpdateWmNews(WmNews wmNews) {
//补全属性
wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
wmNews.setCreatedTime(new Date());
wmNews.setSubmitedTime(new Date());
wmNews.setEnable((short) 1);//默认上架
if (wmNews.getId() == null) {
//保存
save(wmNews);
} else {
//修改
//删除文章图片与素材的关系
wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
updateById(wmNews);
}
}
/**
* 管理员查询文章详情
* @param id
* @return
*/
@Override
public ResponseResult one_vo(Integer id) {
WmNews wmNews = baseMapper.selectById(id);
NewsAuthVo newsAuthVo = new NewsAuthVo();
BeanUtils.copyProperties(wmNews,newsAuthVo);
WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
newsAuthVo.setAuthorName(wmUser.getName());
return ResponseResult.okResult(newsAuthVo);
}
/**
* 审核失败
* @param dto
* @return
*/
@Override
public ResponseResult auth_fail(NewsAuthDto dto) {
if (dto==null){
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
lambdaUpdate().set(WmNews::getStatus,WmNews.Status.FAIL.getCode())
.set(WmNews::getReason,dto.getMsg())
.eq(WmNews::getId,dto.getId())
.update();
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
/**
* 管理员查询文章列表
* @param dto
* @return
*/
@Override
public ResponseResult listVo(NewsAuthDto dto) {
dto.checkParam();
if(dto == null){
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
LambdaQueryWrapper<WmNews> wrapper = Wrappers.<WmNews>lambdaQuery().orderByDesc(WmNews::getCreatedTime);
//状态条件
if(dto.getStatus()!=null){
wrapper=wrapper.eq(WmNews::getStatus, dto.getStatus());
}
//标题模糊查询
if(StringUtils.isNotBlank(dto.getTitle())&&!dto.getTitle().equals("")){
wrapper = wrapper.like(WmNews::getTitle, dto.getTitle());
}
IPage page = new Page(dto.getPage(), dto.getSize());
page = page(page, wrapper);
List<WmNews> wmNewsList = page.getRecords();
List<NewsAuthVo> vos = new ArrayList<>();
for (WmNews wmNews : wmNewsList) {
NewsAuthVo vo = new NewsAuthVo();
BeanUtils.copyProperties(wmNews, vo);
if(wmNews.getUserId()!=null){
WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
if(wmUser!=null){
vo.setAuthorName(wmUser.getName());
vos.add(vo);
}
}
}
ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
responseResult.setData(vos);
return responseResult;
}
/**
* 审核通过
* @param dto
* @return
*/
@Override
public ResponseResult auth_pass(NewsAuthDto dto) {
if(dto==null){
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
WmNews wmNews = baseMapper.selectById(dto.getId());
//审核成功,保存app端的相关文章数据
ResponseResult responseResult =saveAppArticle(wmNews);
if (!responseResult.getCode().equals(200)){
throw new RuntimeException("WmNewsServiceImpl-管理员文章审核:保存app端的相关文章数据失败");
}
//回填article的id
wmNews.setArticleId((Long) responseResult.getData());
//修改状态
wmNews.setStatus(WmNews.Status.ADMIN_SUCCESS.getCode());
if(dto.getMsg()!=null&&StringUtils.isNotBlank(dto.getMsg())){
wmNews.setReason(dto.getMsg());
}
baseMapper.updateById(wmNews);
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
/**
* 保存app端的相关文章数据
* @param wmNews
*/
private ResponseResult saveAppArticle(WmNews wmNews) {
ArticleDto dto = new ArticleDto();
//属性拷贝
BeanUtils.copyProperties(wmNews,dto);
//文章的布局
dto.setLayout(wmNews.getType());
//频道
WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
if(wmChannel!=null){
dto.setChannelName(wmChannel.getName());
}
//作者
dto.setAuthorId(wmNews.getUserId().longValue());
WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
if(wmUser!=null){
dto.setAuthorName(wmUser.getName());
}
//设置文章id
if(wmNews.getArticleId()!=null){
dto.setId(wmNews.getArticleId());
}
dto.setCreatedTime(new Date());
return articleClient.saveArticle(dto);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/service/impl/WmNewsServiceImpl.java
|
Java
|
unknown
| 16,960
|
package com.heima.wemedia.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmSensitivePageDto;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.WmSensitiveService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
/**
* author Link
*
* @version 1.0
* @date 2025/4/16 13:43
*/
@Service
@Transactional
public class WmSensitiveServiceImpl extends ServiceImpl<WmSensitiveMapper, WmSensitive> implements WmSensitiveService {
/**
* 新增敏感词
* @param dto
* @return
*/
@Override
public ResponseResult addSensitive(WmSensitive dto) {
if(dto==null || StringUtils.isBlank(dto.getSensitives())){
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
List<WmSensitive> wmSensitiveList = list();
for (WmSensitive wmSensitive : wmSensitiveList) {
if(wmSensitive.getSensitives().equals(dto.getSensitives())){
return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
}
}
dto.setCreatedTime(new Date());
save(dto);
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
/**
* 查询敏感词列表
* @param dto
* @return
*/
@Override
public ResponseResult listSensitive(WmSensitivePageDto dto) {
//1.检查参数
if(dto == null){
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
//检查分页
dto.checkParam();
//2.模糊查询 + 分页
IPage page = new Page(dto.getPage(),dto.getSize());
LambdaQueryWrapper<WmSensitive> lambdaQueryWrapper = new LambdaQueryWrapper<>();
if(StringUtils.isNotBlank(dto.getName())){
lambdaQueryWrapper.like(WmSensitive::getSensitives,dto.getName());
}
lambdaQueryWrapper.orderByDesc(WmSensitive::getCreatedTime);
page = page(page,lambdaQueryWrapper);
//3.结果返回
ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
responseResult.setData(page.getRecords());
return responseResult;
}
/**
* 修改敏感词
* @param wmSensitive
* @return
*/
@Override
public ResponseResult updateSensitive(WmSensitive wmSensitive) {
if(wmSensitive==null){
return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
}
if (wmSensitive.getId()==null){
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
update(Wrappers.<WmSensitive>lambdaUpdate().set(WmSensitive::getSensitives, wmSensitive.getSensitives())
.set(WmSensitive::getCreatedTime, new Date())
.eq(WmSensitive::getId, wmSensitive.getId())
);
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
/**
* 删除敏感词
* @param id
* @return
*/
@Override
public ResponseResult deleteSensitive(Integer id) {
if(id==null){
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
}
baseMapper.deleteById(id);
return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/service/impl/WmSensitiveServiceImpl.java
|
Java
|
unknown
| 4,096
|
package com.heima.wemedia.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import java.util.HashMap;
import java.util.Map;
@Service
@Transactional
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
@Override
public ResponseResult login(WmLoginDto dto) {
//1.检查参数
if(StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())){
return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码为空");
}
//2.查询用户
WmUser wmUser = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
if(wmUser == null){
return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
}
//3.比对密码
String salt = wmUser.getSalt();
String pswd = dto.getPassword();
pswd = DigestUtils.md5DigestAsHex((pswd + salt).getBytes());
if(pswd.equals(wmUser.getPassword())){
//4.返回数据 jwt
Map<String,Object> map = new HashMap<>();
map.put("token", AppJwtUtil.getToken(wmUser.getId().longValue()));
wmUser.setSalt("");
wmUser.setPassword("");
map.put("user",wmUser);
return ResponseResult.okResult(map);
}else {
return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
}
}
}
|
2201_75631765/heima
|
heima-leadnews-service/heima-leadnews-wemedia/src/main/java/com/heima/wemedia/service/impl/WmUserServiceImpl.java
|
Java
|
unknown
| 2,073
|
package com.heima.es;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @Description:
* @Version: V1.0
*/
@SpringBootApplication
@MapperScan("com.heima.es.mapper")
public class EsInitApplication {
public static void main(String[] args) {
SpringApplication.run(EsInitApplication.class, args);
}
}
|
2201_75631765/heima
|
heima-leadnews-test/es-init/src/main/java/com/heima/es/EsInitApplication.java
|
Java
|
unknown
| 444
|
package com.heima.es.config;
import lombok.Getter;
import lombok.Setter;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ElasticSearchConfig {
private String host;
private int port;
@Bean
public RestHighLevelClient client(){
return new RestHighLevelClient(RestClient.builder(
new HttpHost(
host,
port,
"http"
)
));
}
}
|
2201_75631765/heima
|
heima-leadnews-test/es-init/src/main/java/com/heima/es/config/ElasticSearchConfig.java
|
Java
|
unknown
| 828
|
package com.heima.es.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.heima.es.pojo.SearchArticleVo;
import com.heima.model.article.pojos.ApArticle;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface ApArticleMapper extends BaseMapper<ApArticle> {
public List<SearchArticleVo> loadArticleList();
}
|
2201_75631765/heima
|
heima-leadnews-test/es-init/src/main/java/com/heima/es/mapper/ApArticleMapper.java
|
Java
|
unknown
| 375
|
package com.heima.es.pojo;
import lombok.Data;
import java.util.Date;
@Data
public class SearchArticleVo {
// 文章id
private Long id;
// 文章标题
private String title;
// 文章发布时间
private Date publishTime;
// 文章布局
private Integer layout;
// 封面
private String images;
// 作者id
private Long authorId;
// 作者名词
private String authorName;
//静态url
private String staticUrl;
//文章内容
private String content;
}
|
2201_75631765/heima
|
heima-leadnews-test/es-init/src/main/java/com/heima/es/pojo/SearchArticleVo.java
|
Java
|
unknown
| 527
|
package com.heima.freemarker;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* author Link
*
* @version 1.0
* @date 2025/4/4 14:51
*/
@SpringBootApplication
public class FreemarkerDemoApplication {
public static void main(String[] args) {
SpringApplication.run(FreemarkerDemoApplication.class,args);
}
}
|
2201_75631765/heima
|
heima-leadnews-test/freemarker-demo/src/main/java/com/heima/freemarker/FreemarkerDemoApplication.java
|
Java
|
unknown
| 405
|
package com.heima.freemarker.controller;
import com.heima.freemarker.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HelloController {
@GetMapping("/basic")
public String test(Model model) {
//1.纯文本形式的参数
model.addAttribute("name", "freemarker");
//2.实体类相关的参数
Student student = new Student();
student.setName("小明");
student.setAge(18);
model.addAttribute("stu", student);
return "01-basic";
}
}
|
2201_75631765/heima
|
heima-leadnews-test/freemarker-demo/src/main/java/com/heima/freemarker/controller/HelloController.java
|
Java
|
unknown
| 651
|
package com.heima.freemarker.entity;
import lombok.Data;
import java.util.Date;
/**
* author Link
*
* @version 1.0
* @date 2025/4/4 14:43
*/
@Data
public class Student {
private String name;//姓名
private int age;//年龄
private Date birthday;//生日
private Float money;//钱包
}
|
2201_75631765/heima
|
heima-leadnews-test/freemarker-demo/src/main/java/com/heima/freemarker/entity/Student.java
|
Java
|
unknown
| 311
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello World!</title>
</head>
<body>
<b>普通文本 String 展示:</b><br><br>
Hello ${name} <br>
<hr>
<b>对象Student中的数据展示:</b><br/>
姓名:${stu.name}<br/>
年龄:${stu.age}
<hr>
</body>
</html>
|
2201_75631765/heima
|
heima-leadnews-test/freemarker-demo/src/main/resources/templates/ 01-basic.ftl
|
FreeMarker
|
unknown
| 286
|
package com.heima.minio;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* author Link
*
* @version 1.0
* @date 2025/4/5 10:33
*/
@SpringBootApplication
public class MinIOApplication {
public static void main(String[] args) {
SpringApplication.run(MinIOApplication.class, args);
}
}
|
2201_75631765/heima
|
heima-leadnews-test/minio-demo/src/main/java/com/heima/minio/MinIOApplication.java
|
Java
|
unknown
| 383
|
package com.itheima.mongo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MongoApplication {
public static void main(String[] args) {
SpringApplication.run(MongoApplication.class,args);
}
}
|
2201_75631765/heima
|
heima-leadnews-test/mongo-demo/src/main/java/com/itheima/mongo/MongoApplication.java
|
Java
|
unknown
| 319
|
package com.itheima.mongo.pojo;
import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* 联想词表
* </p>
*
* @author itheima
*/
@Data
@Document("ap_associate_words")
public class ApAssociateWords implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
/**
* 联想词
*/
private String associateWords;
/**
* 创建时间
*/
private Date createdTime;
}
|
2201_75631765/heima
|
heima-leadnews-test/mongo-demo/src/main/java/com/itheima/mongo/pojo/ApAssociateWords.java
|
Java
|
unknown
| 541
|
package com.heima.tess4j;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import java.io.File;
public class Application {
public static void main(String[] args) {
try {
//获取本地图片
File file = new File("C:\\Users\\Lenovo\\Desktop\\image\\1.png");
//创建Tesseract对象
ITesseract tesseract = new Tesseract();
//设置字体库路径
tesseract.setDatapath("F:\\itheimaALL\\heima-toutiao-ALL\\heima-leadnews\\heima-leadnews-test\\tess4j\\src\\main\\resources\\tessdata");
//中文识别
tesseract.setLanguage("chi_sim");
//执行ocr识别
String result = tesseract.doOCR(file);
//替换回车和tal键 使结果为一行
result = result.replaceAll("\\r|\\n","-").replaceAll(" ","");
System.out.println("识别的结果为:"+result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
2201_75631765/heima
|
heima-leadnews-test/tess4j/src/main/java/com/heima/tess4j/Application.java
|
Java
|
unknown
| 1,034
|
package com.heima.utils.common;
import io.jsonwebtoken.*;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;
public class AppJwtUtil {
// TOKEN的有效期一天(S)
private static final int TOKEN_TIME_OUT = 3_600;
// 加密KEY
private static final String TOKEN_ENCRY_KEY = "MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY";
// 最小刷新间隔(S)
private static final int REFRESH_TIME = 300;
// 生产ID
public static String getToken(Long id){
Map<String, Object> claimMaps = new HashMap<>();
claimMaps.put("id",id);
long currentTime = System.currentTimeMillis();
return Jwts.builder()
.setId(UUID.randomUUID().toString())
.setIssuedAt(new Date(currentTime)) //签发时间
.setSubject("system") //说明
.setIssuer("heima") //签发者信息
.setAudience("app") //接收用户
.compressWith(CompressionCodecs.GZIP) //数据压缩方式
.signWith(SignatureAlgorithm.HS512, generalKey()) //加密方式
.setExpiration(new Date(currentTime + TOKEN_TIME_OUT * 1000)) //过期时间戳
.addClaims(claimMaps) //cla信息
.compact();
}
/**
* 获取token中的claims信息
*
* @param token
* @return
*/
private static Jws<Claims> getJws(String token) {
return Jwts.parser()
.setSigningKey(generalKey())
.parseClaimsJws(token);
}
/**
* 获取payload body信息
*
* @param token
* @return
*/
public static Claims getClaimsBody(String token) {
try {
return getJws(token).getBody();
}catch (ExpiredJwtException e){
return null;
}
}
/**
* 获取hearder body信息
*
* @param token
* @return
*/
public static JwsHeader getHeaderBody(String token) {
return getJws(token).getHeader();
}
/**
* 是否过期
*
* @param claims
* @return -1:有效,0:有效,1:过期,2:过期
*/
public static int verifyToken(Claims claims) {
if(claims==null){
return 1;
}
try {
claims.getExpiration()
.before(new Date());
// 需要自动刷新TOKEN
if((claims.getExpiration().getTime()-System.currentTimeMillis())>REFRESH_TIME*1000){
return -1;
}else {
return 0;
}
} catch (ExpiredJwtException ex) {
return 1;
}catch (Exception e){
return 2;
}
}
/**
* 由字符串生成加密key
*
* @return
*/
public static SecretKey generalKey() {
byte[] encodedKey = Base64.getEncoder().encode(TOKEN_ENCRY_KEY.getBytes());
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return key;
}
public static void main(String[] args) {
/* Map map = new HashMap();
map.put("id","11");*/
System.out.println(AppJwtUtil.getToken(1102L));
Jws<Claims> jws = AppJwtUtil.getJws("eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAADWLQQqEMAwA_5KzhURNt_qb1KZYQSi0wi6Lf9942NsMw3zh6AVW2DYmDGl2WabkZgreCaM6VXzhFBfJMcMARTqsxIG9Z888QLui3e3Tup5Pb81013KKmVzJTGo11nf9n8v4nMUaEY73DzTabjmDAAAA.4SuqQ42IGqCgBai6qd4RaVpVxTlZIWC826QA9kLvt9d-yVUw82gU47HDaSfOzgAcloZedYNNpUcd18Ne8vvjQA");
Claims claims = jws.getBody();
System.out.println(claims.get("id"));
}
}
|
2201_75631765/heima
|
heima-leadnews-utils/src/main/java/com/heima/utils/common/AppJwtUtil.java
|
Java
|
unknown
| 3,672
|
// Copyright (c) 2006 Damien Miller <djm@mindrot.org>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package com.heima.utils.common;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
/**
* BCrypt implements OpenBSD-style Blowfish password hashing using
* the scheme described in "A Future-Adaptable Password Scheme" by
* Niels Provos and David Mazieres.
* <p>
* This password hashing system tries to thwart off-line password
* cracking using a computationally-intensive hashing algorithm,
* based on Bruce Schneier's Blowfish cipher. The work factor of
* the algorithm is parameterised, so it can be increased as
* computers get faster.
* <p>
* Usage is really simple. To hash a password for the first time,
* call the hashpw method with a random salt, like this:
* <p>
* <code>
* String pw_hash = BCrypt.hashpw(plain_password, BCrypt.gensalt()); <br />
* </code>
* <p>
* To check whether a plaintext password matches one that has been
* hashed previously, use the checkpw method:
* <p>
* <code>
* if (BCrypt.checkpw(candidate_password, stored_hash))<br />
* System.out.println("It matches");<br />
* else<br />
* System.out.println("It does not match");<br />
* </code>
* <p>
* The gensalt() method takes an optional parameter (log_rounds)
* that determines the computational complexity of the hashing:
* <p>
* <code>
* String strong_salt = BCrypt.gensalt(10)<br />
* String stronger_salt = BCrypt.gensalt(12)<br />
* </code>
* <p>
* The amount of work increases exponentially (2**log_rounds), so
* each increment is twice as much work. The default log_rounds is
* 10, and the valid range is 4 to 30.
*
* @author Damien Miller
* @version 0.2
*/
public class BCrypt {
// BCrypt parameters
private static final int GENSALT_DEFAULT_LOG2_ROUNDS = 10;
private static final int BCRYPT_SALT_LEN = 16;
// Blowfish parameters
private static final int BLOWFISH_NUM_ROUNDS = 16;
// Initial contents of key schedule
private static final int P_orig[] = {
0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
0x9216d5d9, 0x8979fb1b
};
private static final int S_orig[] = {
0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
};
// bcrypt IV: "OrpheanBeholderScryDoubt". The C implementation calls
// this "ciphertext", but it is really plaintext or an IV. We keep
// the name to make code comparison easier.
static private final int bf_crypt_ciphertext[] = {
0x4f727068, 0x65616e42, 0x65686f6c,
0x64657253, 0x63727944, 0x6f756274
};
// Table for Base64 encoding
static private final char base64_code[] = {
'.', '/', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9'
};
// Table for Base64 decoding
static private final byte index_64[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, 0, 1, 54, 55,
56, 57, 58, 59, 60, 61, 62, 63, -1, -1,
-1, -1, -1, -1, -1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
-1, -1, -1, -1, -1, -1, 28, 29, 30,
31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
51, 52, 53, -1, -1, -1, -1, -1
};
// Expanded Blowfish key
private int P[];
private int S[];
/**
* Encode a byte array using bcrypt's slightly-modified base64
* encoding scheme. Note that this is *not* compatible with
* the standard MIME-base64 encoding.
*
* @param d the byte array to encode
* @param len the number of bytes to encode
* @return base64-encoded string
* @exception IllegalArgumentException if the length is invalid
*/
private static String encode_base64(byte d[], int len)
throws IllegalArgumentException {
int off = 0;
StringBuffer rs = new StringBuffer();
int c1, c2;
if (len <= 0 || len > d.length)
throw new IllegalArgumentException ("Invalid len");
while (off < len) {
c1 = d[off++] & 0xff;
rs.append(base64_code[(c1 >> 2) & 0x3f]);
c1 = (c1 & 0x03) << 4;
if (off >= len) {
rs.append(base64_code[c1 & 0x3f]);
break;
}
c2 = d[off++] & 0xff;
c1 |= (c2 >> 4) & 0x0f;
rs.append(base64_code[c1 & 0x3f]);
c1 = (c2 & 0x0f) << 2;
if (off >= len) {
rs.append(base64_code[c1 & 0x3f]);
break;
}
c2 = d[off++] & 0xff;
c1 |= (c2 >> 6) & 0x03;
rs.append(base64_code[c1 & 0x3f]);
rs.append(base64_code[c2 & 0x3f]);
}
return rs.toString();
}
/**
* Look up the 3 bits base64-encoded by the specified character,
* range-checking againt conversion table
* @param x the base64-encoded value
* @return the decoded value of x
*/
private static byte char64(char x) {
if ((int)x < 0 || (int)x > index_64.length)
return -1;
return index_64[(int)x];
}
/**
* Decode a string encoded using bcrypt's base64 scheme to a
* byte array. Note that this is *not* compatible with
* the standard MIME-base64 encoding.
* @param s the string to decode
* @param maxolen the maximum number of bytes to decode
* @return an array containing the decoded bytes
* @throws IllegalArgumentException if maxolen is invalid
*/
private static byte[] decode_base64(String s, int maxolen)
throws IllegalArgumentException {
StringBuffer rs = new StringBuffer();
int off = 0, slen = s.length(), olen = 0;
byte ret[];
byte c1, c2, c3, c4, o;
if (maxolen <= 0)
throw new IllegalArgumentException ("Invalid maxolen");
while (off < slen - 1 && olen < maxolen) {
c1 = char64(s.charAt(off++));
c2 = char64(s.charAt(off++));
if (c1 == -1 || c2 == -1)
break;
o = (byte)(c1 << 2);
o |= (c2 & 0x30) >> 4;
rs.append((char)o);
if (++olen >= maxolen || off >= slen)
break;
c3 = char64(s.charAt(off++));
if (c3 == -1)
break;
o = (byte)((c2 & 0x0f) << 4);
o |= (c3 & 0x3c) >> 2;
rs.append((char)o);
if (++olen >= maxolen || off >= slen)
break;
c4 = char64(s.charAt(off++));
o = (byte)((c3 & 0x03) << 6);
o |= c4;
rs.append((char)o);
++olen;
}
ret = new byte[olen];
for (off = 0; off < olen; off++)
ret[off] = (byte)rs.charAt(off);
return ret;
}
/**
* Blowfish encipher a single 64-bit block encoded as
* two 32-bit halves
* @param lr an array containing the two 32-bit half blocks
* @param off the position in the array of the blocks
*/
private final void encipher(int lr[], int off) {
int i, n, l = lr[off], r = lr[off + 1];
l ^= P[0];
for (i = 0; i <= BLOWFISH_NUM_ROUNDS - 2;) {
// Feistel substitution on left word
n = S[(l >> 24) & 0xff];
n += S[0x100 | ((l >> 16) & 0xff)];
n ^= S[0x200 | ((l >> 8) & 0xff)];
n += S[0x300 | (l & 0xff)];
r ^= n ^ P[++i];
// Feistel substitution on right word
n = S[(r >> 24) & 0xff];
n += S[0x100 | ((r >> 16) & 0xff)];
n ^= S[0x200 | ((r >> 8) & 0xff)];
n += S[0x300 | (r & 0xff)];
l ^= n ^ P[++i];
}
lr[off] = r ^ P[BLOWFISH_NUM_ROUNDS + 1];
lr[off + 1] = l;
}
/**
* Cycically extract a word of key material
* @param data the string to extract the data from
* @param offp a "pointer" (as a one-entry array) to the
* current offset into data
* @return the next word of material from data
*/
private static int streamtoword(byte data[], int offp[]) {
int i;
int word = 0;
int off = offp[0];
for (i = 0; i < 4; i++) {
word = (word << 8) | (data[off] & 0xff);
off = (off + 1) % data.length;
}
offp[0] = off;
return word;
}
/**
* Initialise the Blowfish key schedule
*/
private void init_key() {
P = (int[])P_orig.clone();
S = (int[])S_orig.clone();
}
/**
* Key the Blowfish cipher
* @param key an array containing the key
*/
private void key(byte key[]) {
int i;
int koffp[] = { 0 };
int lr[] = { 0, 0 };
int plen = P.length, slen = S.length;
for (i = 0; i < plen; i++)
P[i] = P[i] ^ streamtoword(key, koffp);
for (i = 0; i < plen; i += 2) {
encipher(lr, 0);
P[i] = lr[0];
P[i + 1] = lr[1];
}
for (i = 0; i < slen; i += 2) {
encipher(lr, 0);
S[i] = lr[0];
S[i + 1] = lr[1];
}
}
/**
* Perform the "enhanced key schedule" step described by
* Provos and Mazieres in "A Future-Adaptable Password Scheme"
* http://www.openbsd.org/papers/bcrypt-paper.ps
* @param data salt information
* @param key password information
*/
private void ekskey(byte data[], byte key[]) {
int i;
int koffp[] = { 0 }, doffp[] = { 0 };
int lr[] = { 0, 0 };
int plen = P.length, slen = S.length;
for (i = 0; i < plen; i++)
P[i] = P[i] ^ streamtoword(key, koffp);
for (i = 0; i < plen; i += 2) {
lr[0] ^= streamtoword(data, doffp);
lr[1] ^= streamtoword(data, doffp);
encipher(lr, 0);
P[i] = lr[0];
P[i + 1] = lr[1];
}
for (i = 0; i < slen; i += 2) {
lr[0] ^= streamtoword(data, doffp);
lr[1] ^= streamtoword(data, doffp);
encipher(lr, 0);
S[i] = lr[0];
S[i + 1] = lr[1];
}
}
/**
* Perform the central password hashing step in the
* bcrypt scheme
* @param password the password to hash
* @param salt the binary salt to hash with the password
* @param log_rounds the binary logarithm of the number
* of rounds of hashing to apply
* @param cdata the plaintext to encrypt
* @return an array containing the binary hashed password
*/
public byte[] crypt_raw(byte password[], byte salt[], int log_rounds,
int cdata[]) {
int rounds, i, j;
int clen = cdata.length;
byte ret[];
if (log_rounds < 4 || log_rounds > 30)
throw new IllegalArgumentException ("Bad number of rounds");
rounds = 1 << log_rounds;
if (salt.length != BCRYPT_SALT_LEN)
throw new IllegalArgumentException ("Bad salt length");
init_key();
ekskey(salt, password);
for (i = 0; i != rounds; i++) {
key(password);
key(salt);
}
for (i = 0; i < 64; i++) {
for (j = 0; j < (clen >> 1); j++)
encipher(cdata, j << 1);
}
ret = new byte[clen * 4];
for (i = 0, j = 0; i < clen; i++) {
ret[j++] = (byte)((cdata[i] >> 24) & 0xff);
ret[j++] = (byte)((cdata[i] >> 16) & 0xff);
ret[j++] = (byte)((cdata[i] >> 8) & 0xff);
ret[j++] = (byte)(cdata[i] & 0xff);
}
return ret;
}
/**
* Hash a password using the OpenBSD bcrypt scheme
* @param password the password to hash
* @param salt the salt to hash with (perhaps generated
* using BCrypt.gensalt)
* @return the hashed password
*/
public static String hashpw(String password, String salt) {
BCrypt B;
String real_salt;
byte passwordb[], saltb[], hashed[];
char minor = (char)0;
int rounds, off = 0;
StringBuffer rs = new StringBuffer();
if (salt.charAt(0) != '$' || salt.charAt(1) != '2')
throw new IllegalArgumentException ("Invalid salt version");
if (salt.charAt(2) == '$')
off = 3;
else {
minor = salt.charAt(2);
if (minor != 'a' || salt.charAt(3) != '$')
throw new IllegalArgumentException ("Invalid salt revision");
off = 4;
}
// Extract number of rounds
if (salt.charAt(off + 2) > '$')
throw new IllegalArgumentException ("Missing salt rounds");
rounds = Integer.parseInt(salt.substring(off, off + 2));
real_salt = salt.substring(off + 3, off + 25);
try {
passwordb = (password + (minor >= 'a' ? "\000" : "")).getBytes("UTF-8");
} catch (UnsupportedEncodingException uee) {
throw new AssertionError("UTF-8 is not supported");
}
saltb = decode_base64(real_salt, BCRYPT_SALT_LEN);
B = new BCrypt();
hashed = B.crypt_raw(passwordb, saltb, rounds,
(int[])bf_crypt_ciphertext.clone());
rs.append("$2");
if (minor >= 'a')
rs.append(minor);
rs.append("$");
if (rounds < 10)
rs.append("0");
if (rounds > 30) {
throw new IllegalArgumentException(
"rounds exceeds maximum (30)");
}
rs.append(Integer.toString(rounds));
rs.append("$");
rs.append(encode_base64(saltb, saltb.length));
rs.append(encode_base64(hashed,
bf_crypt_ciphertext.length * 4 - 1));
return rs.toString();
}
/**
* Generate a salt for use with the BCrypt.hashpw() method
* @param log_rounds the log2 of the number of rounds of
* hashing to apply - the work factor therefore increases as
* 2**log_rounds.
* @param random an instance of SecureRandom to use
* @return an encoded salt value
*/
public static String gensalt(int log_rounds, SecureRandom random) {
StringBuffer rs = new StringBuffer();
byte rnd[] = new byte[BCRYPT_SALT_LEN];
random.nextBytes(rnd);
rs.append("$2a$");
if (log_rounds < 10)
rs.append("0");
if (log_rounds > 30) {
throw new IllegalArgumentException(
"log_rounds exceeds maximum (30)");
}
rs.append(Integer.toString(log_rounds));
rs.append("$");
rs.append(encode_base64(rnd, rnd.length));
return rs.toString();
}
/**
* Generate a salt for use with the BCrypt.hashpw() method
* @param log_rounds the log2 of the number of rounds of
* hashing to apply - the work factor therefore increases as
* 2**log_rounds.
* @return an encoded salt value
*/
public static String gensalt(int log_rounds) {
return gensalt(log_rounds, new SecureRandom());
}
/**
* Generate a salt for use with the BCrypt.hashpw() method,
* selecting a reasonable default for the number of hashing
* rounds to apply
* @return an encoded salt value
*/
public static String gensalt() {
return gensalt(GENSALT_DEFAULT_LOG2_ROUNDS);
}
/**
* Check that a plaintext password matches a previously hashed
* one
* @param plaintext the plaintext password to verify
* @param hashed the previously-hashed password
* @return true if the passwords match, false otherwise
*/
public static boolean checkpw(String plaintext, String hashed) {
byte hashed_bytes[];
byte try_bytes[];
try {
String try_pw = hashpw(plaintext, hashed);
hashed_bytes = hashed.getBytes("UTF-8");
try_bytes = try_pw.getBytes("UTF-8");
} catch (UnsupportedEncodingException uee) {
return false;
}
if (hashed_bytes.length != try_bytes.length)
return false;
byte ret = 0;
for (int i = 0; i < try_bytes.length; i++)
ret |= hashed_bytes[i] ^ try_bytes[i];
return ret == 0;
}
}
|
2201_75631765/heima
|
heima-leadnews-utils/src/main/java/com/heima/utils/common/BCrypt.java
|
Java
|
unknown
| 28,022
|
package com.heima.utils.common;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Base64Utils {
/**
* 解码
* @param base64
* @return
*/
public static byte[] decode(String base64){
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] b = decoder.decodeBuffer(base64);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
return b;
} catch (Exception e) {
return null;
}
}
/**
* 编码
* @param data
* @return
* @throws Exception
*/
public static String encode(byte[] data) {
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
}
|
2201_75631765/heima
|
heima-leadnews-utils/src/main/java/com/heima/utils/common/Base64Utils.java
|
Java
|
unknown
| 883
|
package com.heima.utils.common;
/**
* 分片桶字段算法
*/
public class BurstUtils {
public final static String SPLIT_CHAR = "-";
/**
* 用-符号链接
* @param fileds
* @return
*/
public static String encrypt(Object... fileds){
StringBuffer sb = new StringBuffer();
if(fileds!=null&&fileds.length>0) {
sb.append(fileds[0]);
for (int i = 1; i < fileds.length; i++) {
sb.append(SPLIT_CHAR).append(fileds[i]);
}
}
return sb.toString();
}
/**
* 默认第一组
* @param fileds
* @return
*/
public static String groudOne(Object... fileds){
StringBuffer sb = new StringBuffer();
if(fileds!=null&&fileds.length>0) {
sb.append("0");
for (int i = 0; i < fileds.length; i++) {
sb.append(SPLIT_CHAR).append(fileds[i]);
}
}
return sb.toString();
}
}
|
2201_75631765/heima
|
heima-leadnews-utils/src/main/java/com/heima/utils/common/BurstUtils.java
|
Java
|
unknown
| 988
|
package com.heima.utils.common;
import javax.swing.border.TitledBorder;
import java.text.NumberFormat;
import java.util.Locale;
public class Compute {
public static void main(String[] args) {
String content = "最近公司由于业务拓展,需要进行小程序相关的开发,本着朝全栈开发者努力,决定学习下Vue,去年csdn送了一本《Vue.js权威指南》";
String title = "VueVueVue";
double ss = SimilarDegree(content, title);
System.out.println(ss);
}
/*
* 计算相似度
* */
public static double SimilarDegree(String strA, String strB) {
String newStrA = removeSign(strA);
String newStrB = removeSign(strB);
//用较大的字符串长度作为分母,相似子串作为分子计算出字串相似度
int temp = Math.max(newStrA.length(), newStrB.length());
int temp2 = longestCommonSubstring(newStrA, newStrB).length();
return temp2 * 1.0 / temp;
}
/*
* 将字符串的所有数据依次写成一行
* */
public static String removeSign(String str) {
StringBuffer sb = new StringBuffer();
//遍历字符串str,如果是汉字数字或字母,则追加到ab上面
for (char item : str.toCharArray()) {
if (charReg(item)) {
sb.append(item);
}
}
return sb.toString();
}
/*
* 判断字符是否为汉字,数字和字母,
* 因为对符号进行相似度比较没有实际意义,故符号不加入考虑范围。
* */
public static boolean charReg(char charValue) {
return (charValue >= 0x4E00 && charValue <= 0X9FA5) || (charValue >= 'a' && charValue <= 'z')
|| (charValue >= 'A' && charValue <= 'Z') || (charValue >= '0' && charValue <= '9');
}
/*
* 求公共子串,采用动态规划算法。
* 其不要求所求得的字符在所给的字符串中是连续的。
*
* */
public static String longestCommonSubstring(String strA, String strB) {
char[] chars_strA = strA.toCharArray();
char[] chars_strB = strB.toCharArray();
int m = chars_strA.length;
int n = chars_strB.length;
/*
* 初始化矩阵数据,matrix[0][0]的值为0,
* 如果字符数组chars_strA和chars_strB的对应位相同,则matrix[i][j]的值为左上角的值加1,
* 否则,matrix[i][j]的值等于左上方最近两个位置的较大值,
* 矩阵中其余各点的值为0.
*/
int[][] matrix = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (chars_strA[i - 1] == chars_strB[j - 1]) {
matrix[i][j] = matrix[i - 1][j - 1] + 1;
} else {
matrix[i][j] = Math.max(matrix[i][j - 1], matrix[i - 1][j]);
}
}
}
/*
* 矩阵中,如果matrix[m][n]的值不等于matrix[m-1][n]的值也不等于matrix[m][n-1]的值,
* 则matrix[m][n]对应的字符为相似字符元,并将其存入result数组中。
*
*/
char[] result = new char[matrix[m][n]];
int currentIndex = result.length - 1;
while (matrix[m][n] != 0) {
if (matrix[n] == matrix[n - 1]){
n--;
} else if (matrix[m][n] == matrix[m - 1][n]){
m--;
}else {
result[currentIndex] = chars_strA[m - 1];
currentIndex--;
n--;
m--;
}
}
return new String(result);
}
/*
* 结果转换成百分比形式
* */
public static String similarityResult(double resule) {
return NumberFormat.getPercentInstance(new Locale("en ", "US ")).format(resule);
}
}
|
2201_75631765/heima
|
heima-leadnews-utils/src/main/java/com/heima/utils/common/Compute.java
|
Java
|
unknown
| 3,933
|
package com.heima.utils.common;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
public class DESUtils {
public static final String key = "12345678";
/**
* 加密
* @param content
* @param keyBytes
* @return
*/
private static byte[] encrypt(byte[] content, byte[] keyBytes) {
try {
DESKeySpec keySpec = new DESKeySpec(keyBytes);
String algorithm = "DES";//指定使什么样的算法
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
SecretKey key = keyFactory.generateSecret(keySpec);
String transformation = "DES/CBC/PKCS5Padding"; //用什么样的转型方式
Cipher cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(keySpec.getKey()));
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 解密
* @param content
* @param keyBytes
* @return
*/
private static byte[] decrypt(byte[] content, byte[] keyBytes) {
try {
DESKeySpec keySpec = new DESKeySpec(keyBytes);
String algorithm = "DES";
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm );
SecretKey key = keyFactory.generateSecret(keySpec);
String transformation = "DES/CBC/PKCS5Padding";
Cipher cipher = Cipher.getInstance(transformation );
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(keyBytes));
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 二进制转16进制
* @param bytes
* @return
*/
private static String byteToHexString(byte[] bytes) {
StringBuffer sb = new StringBuffer();
String sTemp;
for (int i = 0; i<bytes.length; i++) {
sTemp = Integer.toHexString(0xFF & bytes[i]);
if (sTemp.length() < 2) {
sb.append(0);
}
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
/**
* 16进制字符串转bytes
* @param hex
* @return
*/
public static byte[] hexStringToByte(String hex) {
int len = 0;
int num=0;
//判断字符串的长度是否是两位
if(hex.length()>=2){
//判断字符喜欢是否是偶数
len=(hex.length() / 2);
num = (hex.length() % 2);
if (num == 1) {
hex = "0" + hex;
len=len+1;
}
}else{
hex = "0" + hex;
len=1;
}
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}
private static int toByte(char c) {
if (c >= 'a')
return (c - 'a' + 10) & 0x0f;
if (c >= 'A')
return (c - 'A' + 10) & 0x0f;
return (c - '0') & 0x0f;
}
private static byte[] hexToByteArr(String strIn) {
byte[] arrB = strIn.getBytes();
int iLen = arrB.length;
// 两个字符表示一个字节,所以字节数组长度是字符串长度除以2
byte[] arrOut = new byte[iLen / 2];
for (int i = 0; i < iLen; i = i + 2) {
String strTmp = new String(arrB, i, 2);
arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
}
return arrOut;
}
/**
* 加密
* @param pass
* @return
*/
public static String encode(String pass){
return byteToHexString(encrypt(pass.getBytes(), key.getBytes()));
}
/**
* 解密
* @param passcode
* @return
*/
public static String decode(String passcode){
return byteToHexString(decrypt(hexToByteArr(passcode), key.getBytes()));
}
public static void main(String[] args) {
String content = "password111111111111111";
System.out.println("加密前 "+ byteToHexString(content.getBytes()));
byte[] encrypted = encrypt(content.getBytes(), key.getBytes());
System.out.println("加密后:"+ byteToHexString(encrypted));
byte[] decrypted=decrypt(encrypted, key.getBytes());
System.out.println("解密后:"+ byteToHexString(decrypted));
System.out.println(encode(content));
String s = new String(hexStringToByte(decode("159CF72C0BD2A8183D536215768C2E91556D77642F214E34")));
System.out.println(s);
}
}
|
2201_75631765/heima
|
heima-leadnews-utils/src/main/java/com/heima/utils/common/DESUtils.java
|
Java
|
unknown
| 4,998
|
package com.heima.utils.common;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtils {
public static String DATE_FORMAT = "yyyy-MM-dd";
public static String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String DATE_TIME_STAMP_FORMATE = "yyyyMMddHHmmss";
//2019年07月09日
public static String DATE_FORMAT_CHINESE = "yyyy年M月d日";
//2019年07月09日 14:00:32
public static String DATE_TIME_FORMAT_CHINESE = "yyyy年M月d日 HH:mm:ss";
/**
* 获取当前日期
*
* @return
*/
public static String getCurrentDate() {
String datestr = null;
SimpleDateFormat df = new SimpleDateFormat(DateUtils.DATE_FORMAT);
datestr = df.format(new Date());
return datestr;
}
/**
* 获取当前日期时间
*
* @return
*/
public static String getCurrentDateTime() {
String datestr = null;
SimpleDateFormat df = new SimpleDateFormat(DateUtils.DATE_TIME_FORMAT);
datestr = df.format(new Date());
return datestr;
}
/**
* 获取当前日期时间
*
* @return
*/
public static String getCurrentDateTime(String Dateformat) {
String datestr = null;
SimpleDateFormat df = new SimpleDateFormat(Dateformat);
datestr = df.format(new Date());
return datestr;
}
public static String dateToDateTime(Date date) {
String datestr = null;
SimpleDateFormat df = new SimpleDateFormat(DateUtils.DATE_TIME_FORMAT);
datestr = df.format(date);
return datestr;
}
/**
* 将字符串日期转换为日期格式
*
* @param datestr
* @return
*/
public static Date stringToDate(String datestr) {
if (datestr == null || datestr.equals("")) {
return null;
}
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat(DateUtils.DATE_FORMAT);
try {
date = df.parse(datestr);
} catch (ParseException e) {
date = DateUtils.stringToDate(datestr, "yyyyMMdd");
}
return date;
}
/**
* 将字符串日期转换为日期格式
* 自定義格式
*
* @param datestr
* @return
*/
public static Date stringToDate(String datestr, String dateformat) {
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat(dateformat);
try {
date = df.parse(datestr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
* 将日期格式日期转换为字符串格式
*
* @param date
* @return
*/
public static String dateToString(Date date) {
String datestr = null;
SimpleDateFormat df = new SimpleDateFormat(DateUtils.DATE_FORMAT);
datestr = df.format(date);
return datestr;
}
/**
* 将日期格式日期转换为字符串格式 自定義格式
*
* @param date
* @param dateformat
* @return
*/
public static String dateToString(Date date, String dateformat) {
String datestr = null;
SimpleDateFormat df = new SimpleDateFormat(dateformat);
datestr = df.format(date);
return datestr;
}
/**
* 获取日期的DAY值
*
* @param date 输入日期
* @return
*/
public static int getDayOfDate(Date date) {
int d = 0;
Calendar cd = Calendar.getInstance();
cd.setTime(date);
d = cd.get(Calendar.DAY_OF_MONTH);
return d;
}
/**
* 获取日期的MONTH值
*
* @param date 输入日期
* @return
*/
public static int getMonthOfDate(Date date) {
int m = 0;
Calendar cd = Calendar.getInstance();
cd.setTime(date);
m = cd.get(Calendar.MONTH) + 1;
return m;
}
/**
* 获取日期的YEAR值
*
* @param date 输入日期
* @return
*/
public static int getYearOfDate(Date date) {
int y = 0;
Calendar cd = Calendar.getInstance();
cd.setTime(date);
y = cd.get(Calendar.YEAR);
return y;
}
/**
* 获取星期几
*
* @param date 输入日期
* @return
*/
public static int getWeekOfDate(Date date) {
int wd = 0;
Calendar cd = Calendar.getInstance();
cd.setTime(date);
wd = cd.get(Calendar.DAY_OF_WEEK) - 1;
return wd;
}
/**
* 获取输入日期的当月第一天
*
* @param date 输入日期
* @return
*/
public static Date getFirstDayOfMonth(Date date) {
Calendar cd = Calendar.getInstance();
cd.setTime(date);
cd.set(Calendar.DAY_OF_MONTH, 1);
return cd.getTime();
}
/**
* 获得输入日期的当月最后一天
*
* @param date
*/
public static Date getLastDayOfMonth(Date date) {
return DateUtils.addDay(DateUtils.getFirstDayOfMonth(DateUtils.addMonth(date, 1)), -1);
}
/**
* 判断是否是闰年
*
* @param date 输入日期
* @return 是true 否false
*/
public static boolean isLeapYEAR(Date date) {
Calendar cd = Calendar.getInstance();
cd.setTime(date);
int year = cd.get(Calendar.YEAR);
if (year % 4 == 0 && year % 100 != 0 | year % 400 == 0) {
return true;
} else {
return false;
}
}
/**
* 根据整型数表示的年月日,生成日期类型格式
*
* @param year 年
* @param month 月
* @param day 日
* @return
*/
public static Date getDateByYMD(int year, int month, int day) {
Calendar cd = Calendar.getInstance();
cd.set(year, month - 1, day);
return cd.getTime();
}
/**
* 获取年周期对应日
*
* @param date 输入日期
* @param iyear 年数 負數表示之前
* @return
*/
public static Date getYearCycleOfDate(Date date, int iyear) {
Calendar cd = Calendar.getInstance();
cd.setTime(date);
cd.add(Calendar.YEAR, iyear);
return cd.getTime();
}
/**
* 获取月周期对应日
*
* @param date 输入日期
* @param i
* @return
*/
public static Date getMonthCycleOfDate(Date date, int i) {
Calendar cd = Calendar.getInstance();
cd.setTime(date);
cd.add(Calendar.MONTH, i);
return cd.getTime();
}
/**
* 计算 fromDate 到 toDate 相差多少年
*
* @param fromDate
* @param toDate
* @return 年数
*/
public static int getYearByMinusDate(Date fromDate, Date toDate) {
Calendar df = Calendar.getInstance();
df.setTime(fromDate);
Calendar dt = Calendar.getInstance();
dt.setTime(toDate);
return dt.get(Calendar.YEAR) - df.get(Calendar.YEAR);
}
/**
* 计算 fromDate 到 toDate 相差多少个月
*
* @param fromDate
* @param toDate
* @return 月数
*/
public static int getMonthByMinusDate(Date fromDate, Date toDate) {
Calendar df = Calendar.getInstance();
df.setTime(fromDate);
Calendar dt = Calendar.getInstance();
dt.setTime(toDate);
return dt.get(Calendar.YEAR) * 12 + dt.get(Calendar.MONTH) -
(df.get(Calendar.YEAR) * 12 + df.get(Calendar.MONTH));
}
/**
* 计算 fromDate 到 toDate 相差多少天
*
* @param fromDate
* @param toDate
* @return 天数
*/
public static long getDayByMinusDate(Object fromDate, Object toDate) {
Date f = DateUtils.chgObject(fromDate);
Date t = DateUtils.chgObject(toDate);
long fd = f.getTime();
long td = t.getTime();
return (td - fd) / (24L * 60L * 60L * 1000L);
}
/**
* 计算年龄
*
* @param birthday 生日日期
* @param calcDate 要计算的日期点
* @return
*/
public static int calcAge(Date birthday, Date calcDate) {
int cYear = DateUtils.getYearOfDate(calcDate);
int cMonth = DateUtils.getMonthOfDate(calcDate);
int cDay = DateUtils.getDayOfDate(calcDate);
int bYear = DateUtils.getYearOfDate(birthday);
int bMonth = DateUtils.getMonthOfDate(birthday);
int bDay = DateUtils.getDayOfDate(birthday);
if (cMonth > bMonth || (cMonth == bMonth && cDay > bDay)) {
return cYear - bYear;
} else {
return cYear - 1 - bYear;
}
}
/**
* 从身份证中获取出生日期
*
* @param idno 身份证号码
* @return
*/
public static String getBirthDayFromIDCard(String idno) {
Calendar cd = Calendar.getInstance();
if (idno.length() == 15) {
cd.set(Calendar.YEAR, Integer.valueOf("19" + idno.substring(6, 8))
.intValue());
cd.set(Calendar.MONTH, Integer.valueOf(idno.substring(8, 10))
.intValue() - 1);
cd.set(Calendar.DAY_OF_MONTH,
Integer.valueOf(idno.substring(10, 12)).intValue());
} else if (idno.length() == 18) {
cd.set(Calendar.YEAR, Integer.valueOf(idno.substring(6, 10))
.intValue());
cd.set(Calendar.MONTH, Integer.valueOf(idno.substring(10, 12))
.intValue() - 1);
cd.set(Calendar.DAY_OF_MONTH,
Integer.valueOf(idno.substring(12, 14)).intValue());
}
return DateUtils.dateToString(cd.getTime());
}
/**
* 在输入日期上增加(+)或减去(-)天数
*
* @param date 输入日期
* @param iday 要增加或减少的天数
*/
public static Date addDay(Date date, int iday) {
Calendar cd = Calendar.getInstance();
cd.setTime(date);
cd.add(Calendar.DAY_OF_MONTH, iday);
return cd.getTime();
}
/**
* 在输入日期上增加(+)或减去(-)月份
*
* @param date 输入日期
* @param imonth 要增加或减少的月分数
*/
public static Date addMonth(Date date, int imonth) {
Calendar cd = Calendar.getInstance();
cd.setTime(date);
cd.add(Calendar.MONTH, imonth);
return cd.getTime();
}
/**
* 在输入日期上增加(+)或减去(-)年份
*
* @param date 输入日期
* @param iyear 要增加或减少的年数
*/
public static Date addYear(Date date, int iyear) {
Calendar cd = Calendar.getInstance();
cd.setTime(date);
cd.add(Calendar.YEAR, iyear);
return cd.getTime();
}
/**
* 將OBJECT類型轉換為Date
*
* @param date
* @return
*/
public static Date chgObject(Object date) {
if (date != null && date instanceof Date) {
return (Date) date;
}
if (date != null && date instanceof String) {
return DateUtils.stringToDate((String) date);
}
return null;
}
public static long getAgeByBirthday(String date) {
Date birthday = stringToDate(date, "yyyy-MM-dd");
long sec = new Date().getTime() - birthday.getTime();
long age = sec / (1000 * 60 * 60 * 24) / 365;
return age;
}
/**
* @param args
*/
public static void main(String[] args) {
//String temp = DateUtil.dateToString(getLastDayOfMonth(new Date()),
/// DateUtil.DATE_FORMAT_CHINESE);
//String s=DateUtil.dateToString(DateUtil.addDay(DateUtil.addYear(new Date(),1),-1));
long s = DateUtils.getDayByMinusDate("2012-01-01", "2012-12-31");
System.err.println(s);
}
}
|
2201_75631765/heima
|
heima-leadnews-utils/src/main/java/com/heima/utils/common/DateUtils.java
|
Java
|
unknown
| 12,010
|
package com.heima.utils.common;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class FileUtils {
/**
* 重资源流中读取第一行内容
* @param in
* @return
* @throws IOException
*/
public static String readFristLineFormResource(InputStream in) throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(in));
return br.readLine();
}
}
|
2201_75631765/heima
|
heima-leadnews-utils/src/main/java/com/heima/utils/common/FileUtils.java
|
Java
|
unknown
| 500
|
package com.heima.utils.common;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/**
* 数字ID混淆器,用于前后端数据通信时候的处理
*/
public class IdsUtils {
private static final String KEY_AES = "AES";
private static final String KEY_SECART = "12345678901234561234567890123456";
public static String encryptNumber(Long number) throws Exception{
String src = String.format("%d%013d",0,number);
return encrypt(src);
}
public static Long decryptLong(String src) throws Exception{
String val =decrypt(src);
return Long.valueOf(val);
}
public static Integer decryptInt(String src) throws Exception{
String val =decrypt(src);
return Integer.valueOf(val);
}
private static String encrypt(String src) throws Exception {
byte[] raw = KEY_SECART.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_AES);
Cipher cipher = Cipher.getInstance(KEY_AES);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(src.getBytes());
return byte2hex(encrypted);
}
private static String decrypt(String src) throws Exception {
byte[] raw = KEY_SECART.getBytes();
SecretKeySpec skeySpec = new SecretKeySpec(raw, KEY_AES);
Cipher cipher = Cipher.getInstance(KEY_AES);
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = hex2byte(src);
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString;
}
private static byte[] hex2byte(String strhex) {
if (strhex == null) {
return null;
}
int l = strhex.length();
if (l % 2 == 1) {
return null;
}
byte[] b = new byte[l / 2];
for (int i = 0; i != l / 2; i++) {
b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),
16);
}
return b;
}
private static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
public static void main(String[] args) throws Exception{
System.out.println("========:"+encryptNumber(2l));
}
}
|
2201_75631765/heima
|
heima-leadnews-utils/src/main/java/com/heima/utils/common/IdsUtils.java
|
Java
|
unknown
| 2,579
|
package com.heima.utils.common;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Utils {
/**
* MD5加密
* @param str
* @return
*/
public final static String encode(String str) {
try {
//创建具有指定算法名称的摘要
MessageDigest md = MessageDigest.getInstance("MD5");
//使用指定的字节数组更新摘要
md.update(str.getBytes());
//进行哈希计算并返回一个字节数组
byte mdBytes[] = md.digest();
String hash = "";
//循环字节数组
for (int i = 0; i < mdBytes.length; i++) {
int temp;
//如果有小于0的字节,则转换为正数
if (mdBytes[i] < 0)
temp = 256 + mdBytes[i];
else
temp = mdBytes[i];
if (temp < 16)
hash += "0";
//将字节转换为16进制后,转换为字符串
hash += Integer.toString(temp, 16);
}
return hash;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
public static String encodeWithSalt(String numStr, String salt) {
return encode(encode(numStr) + salt);
}
public static void main(String[] args) {
System.out.println(encode("test"));//e10adc3949ba59abbe56e057f20f883e
System.out.println(encodeWithSalt("123456","123456"));//5f1d7a84db00d2fce00b31a7fc73224f
}
}
|
2201_75631765/heima
|
heima-leadnews-utils/src/main/java/com/heima/utils/common/MD5Utils.java
|
Java
|
unknown
| 1,626
|
package com.heima.utils.common;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ReflectUtils {
/**
* 转换为Map
*
* @param bean
* @return
*/
public static Map<String, Object> beanToMap(Object bean) {
PropertyDescriptor[] propertyDescriptorArray = getPropertyDescriptorArray(bean);
Map<String, Object> parameterMap = new HashMap<String, Object>();
for (PropertyDescriptor propertyDescriptor : propertyDescriptorArray) {
Object value = getPropertyDescriptorValue(bean, propertyDescriptor);
parameterMap.put(propertyDescriptor.getName(), value);
}
return parameterMap;
}
/**
* 通过反射设置属性
*
* @param bean
* @param key
* @param value
*/
public static void setPropertie(Object bean, String key, Object value) {
if (null != bean && StringUtils.isNotEmpty(key)) {
PropertyDescriptor[] descriptor = getPropertyDescriptorArray(bean);
PropertyDescriptor propertyDescriptor = getPropertyDescriptor(descriptor, key);
setPropertyDescriptorValue(bean, propertyDescriptor, value);
}
}
/**
* 通过反射设置属性
*
* @param bean
* @param key
* @param value
* @param skipExist 是否跳过已存在的属性
*/
public static void setPropertie(Object bean, String key, Object value, boolean skipExist) {
if (null != bean && StringUtils.isNotEmpty(key)) {
if (skipExist) {
Object propValue = getPropertie(bean, key);
if (null == propValue) {
setPropertie(bean, key, value);
}
} else {
setPropertie(bean, key, value);
}
}
}
/**
* 通过反射将map的key value 映射到实体类中
*
* @param bean
* @param skipExist 是否跳过已存在的属性
*/
public static void setPropertie(Object bean, Map<String, Object> parameterMap, boolean skipExist) {
if (null != bean && null != parameterMap && !parameterMap.isEmpty()) {
for (Map.Entry<String, Object> entry : parameterMap.entrySet()) {
setPropertie(bean, entry.getKey(), entry.getValue());
}
}
}
/**
* 获取属性的值
*
* @param bean
* @param key
* @return
*/
public static Object getPropertie(Object bean, String key) {
Object value = null;
if (null != bean && StringUtils.isNotEmpty(key)) {
PropertyDescriptor[] descriptor = getPropertyDescriptorArray(bean);
PropertyDescriptor propertyDescriptor = getPropertyDescriptor(descriptor, key);
value = getPropertyDescriptorValue(bean, propertyDescriptor);
}
return value;
}
public static Object getPropertyDescriptorValue(Object bean, PropertyDescriptor propertyDescriptor) {
Object value = null;
if (null != propertyDescriptor) {
Method readMethod = propertyDescriptor.getReadMethod();
value = invok(readMethod, bean, propertyDescriptor.getPropertyType(), null);
}
return value;
}
public static void setPropertyDescriptorValue(Object bean, PropertyDescriptor propertyDescriptor, Object value) {
if (null != propertyDescriptor) {
Method writeMethod = propertyDescriptor.getWriteMethod();
invok(writeMethod, bean, propertyDescriptor.getPropertyType(), value);
}
}
/**
* 获取 PropertyDescriptor 属性
*
* @param propertyDescriptorArray
* @param key
* @return
*/
public static PropertyDescriptor getPropertyDescriptor(PropertyDescriptor[] propertyDescriptorArray, String key) {
PropertyDescriptor propertyDescriptor = null;
for (PropertyDescriptor descriptor : propertyDescriptorArray) {
String fieldName = descriptor.getName();
if (fieldName.equals(key)) {
propertyDescriptor = descriptor;
break;
}
}
return propertyDescriptor;
}
/**
* 获取 PropertyDescriptor 属性
*
* @param bean
* @param key
* @return
*/
public static PropertyDescriptor getPropertyDescriptor(Object bean, String key) {
PropertyDescriptor[] propertyDescriptorArray = getPropertyDescriptorArray(bean);
return getPropertyDescriptor(propertyDescriptorArray, key);
}
/**
* invok 调用方法
*
* @param methodName
* @param bean
* @param targetType
* @param value
* @return
*/
public static Object invok(String methodName, Object bean, Class<?> targetType, Object value) {
Object resultValue = null;
if (StringUtils.isNotEmpty(methodName) && null != bean) {
Method method = getMethod(bean.getClass(), methodName);
if (null != method) {
resultValue = invok(method, bean, targetType, value);
}
}
return resultValue;
}
/**
* 调用 invok 方法
*
* @param method
* @param bean
* @param value
*/
public static Object invok(Method method, Object bean, Class<?> targetType, Object value) {
// System.out.println("method:" + method.getName() + " bean:" + bean.getClass().getName() + " " + value);
Object resultValue = null;
if (null != method && null != bean) {
try {
int count = method.getParameterCount();
if (count >= 1) {
if (null != value) {
value = ConvertUtils.convert(value, targetType);
}
resultValue = method.invoke(bean, value);
} else {
resultValue = method.invoke(bean);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return resultValue;
}
/**
* 获取内省的属性
*
* @param bean
* @return
*/
public static PropertyDescriptor[] getPropertyDescriptorArray(Object bean) {
BeanInfo beanInfo = null;
PropertyDescriptor[] propertyDescriptors = null;
try {
beanInfo = Introspector.getBeanInfo(bean.getClass());
} catch (IntrospectionException e) {
e.printStackTrace();
}
if (null != beanInfo) {
propertyDescriptors = beanInfo.getPropertyDescriptors();
}
return propertyDescriptors;
}
/**
* 获取method 方法
*
* @param clazz
* @param methodName
* @return
*/
private static Method getMethod(Class clazz, String methodName) {
Method method = null;
if (null != clazz) {
try {
method = clazz.getDeclaredMethod(methodName);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
return method;
}
private static Object getBean(Class clazz) {
Object bean = null;
if (null != clazz) {
try {
bean = clazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return bean;
}
/**
* 同步 bean 中的数据
*
* @param oldBean
* @param newBean
* @param <T>
*/
public static <T> void syncBeanData(T oldBean, T newBean) {
PropertyDescriptor[] descriptorArray = getPropertyDescriptorArray(newBean);
for (PropertyDescriptor propertyDescriptor : descriptorArray) {
Object newValue = getPropertyDescriptorValue(newBean, propertyDescriptor);
Object oldValue = getPropertyDescriptorValue(oldBean, propertyDescriptor);
if (null == newValue && oldValue != null) {
setPropertyDescriptorValue(newBean, propertyDescriptor, oldValue);
}
}
}
/**
* 通过反射获取class字节码文件
*
* @param className
* @return
*/
public static Class getClassForName(String className) {
Class clazz = null;
if (StringUtils.isNotEmpty(className)) {
try {
clazz = Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return clazz;
}
/**
* 通过反射获取对象
*
* @param className
* @return
*/
public static Object getClassForBean(String className) {
Object bean = null;
Class clazz = getClassForName(className);
if (null != clazz) {
try {
bean = clazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return bean;
}
/**
* 获取属性字段的注解属性
*
* @param bean
* @param propertyDescriptor
* @return
*/
public static Annotation[] getFieldAnnotations(Object bean, PropertyDescriptor propertyDescriptor) {
List<Field> fieldList = Arrays.asList(bean.getClass().getDeclaredFields()).stream().filter(f -> f.getName().equals(propertyDescriptor.getName())).collect(Collectors.toList());
if (null != fieldList && fieldList.size() > 0) {
return fieldList.get(0).getDeclaredAnnotations();
}
return null;
}
/**
* 获取属性字段的注解属性
*
* @param bean
* @param key
* @return
*/
public static Annotation[] getFieldAnnotations(Object bean, String key) {
PropertyDescriptor propertyDescriptor = getPropertyDescriptor(bean, key);
return getFieldAnnotations(bean, propertyDescriptor);
}
}
|
2201_75631765/heima
|
heima-leadnews-utils/src/main/java/com/heima/utils/common/ReflectUtils.java
|
Java
|
unknown
| 10,712
|
package com.heima.utils.common;
import java.util.*;
public class SensitiveWordUtil {
public static Map<String, Object> dictionaryMap = new HashMap<>();
/**
* 生成关键词字典库
* @param words
* @return
*/
public static void initMap(Collection<String> words) {
if (words == null) {
System.out.println("敏感词列表不能为空");
return ;
}
// map初始长度words.size(),整个字典库的入口字数(小于words.size(),因为不同的词可能会有相同的首字)
Map<String, Object> map = new HashMap<>(words.size());
// 遍历过程中当前层次的数据
Map<String, Object> curMap = null;
Iterator<String> iterator = words.iterator();
while (iterator.hasNext()) {
String word = iterator.next();
curMap = map;
int len = word.length();
for (int i =0; i < len; i++) {
// 遍历每个词的字
String key = String.valueOf(word.charAt(i));
// 当前字在当前层是否存在, 不存在则新建, 当前层数据指向下一个节点, 继续判断是否存在数据
Map<String, Object> wordMap = (Map<String, Object>) curMap.get(key);
if (wordMap == null) {
// 每个节点存在两个数据: 下一个节点和isEnd(是否结束标志)
wordMap = new HashMap<>(2);
wordMap.put("isEnd", "0");
curMap.put(key, wordMap);
}
curMap = wordMap;
// 如果当前字是词的最后一个字,则将isEnd标志置1
if (i == len -1) {
curMap.put("isEnd", "1");
}
}
}
dictionaryMap = map;
}
/**
* 搜索文本中某个文字是否匹配关键词
* @param text
* @param beginIndex
* @return
*/
private static int checkWord(String text, int beginIndex) {
if (dictionaryMap == null) {
throw new RuntimeException("字典不能为空");
}
boolean isEnd = false;
int wordLength = 0;
Map<String, Object> curMap = dictionaryMap;
int len = text.length();
// 从文本的第beginIndex开始匹配
for (int i = beginIndex; i < len; i++) {
String key = String.valueOf(text.charAt(i));
// 获取当前key的下一个节点
curMap = (Map<String, Object>) curMap.get(key);
if (curMap == null) {
break;
} else {
wordLength ++;
if ("1".equals(curMap.get("isEnd"))) {
isEnd = true;
}
}
}
if (!isEnd) {
wordLength = 0;
}
return wordLength;
}
/**
* 获取匹配的关键词和命中次数
* @param text
* @return
*/
public static Map<String, Integer> matchWords(String text) {
Map<String, Integer> wordMap = new HashMap<>();
int len = text.length();
for (int i = 0; i < len; i++) {
int wordLength = checkWord(text, i);
if (wordLength > 0) {
String word = text.substring(i, i + wordLength);
// 添加关键词匹配次数
if (wordMap.containsKey(word)) {
wordMap.put(word, wordMap.get(word) + 1);
} else {
wordMap.put(word, 1);
}
i += wordLength - 1;
}
}
return wordMap;
}
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("法轮");
list.add("法轮功");
list.add("冰毒");
initMap(list);
String content="我是一个好人,并不会卖冰毒,也不操练法轮功,我真的不卖冰毒";
Map<String, Integer> map = matchWords(content);
System.out.println(map);
}
}
|
2201_75631765/heima
|
heima-leadnews-utils/src/main/java/com/heima/utils/common/SensitiveWordUtil.java
|
Java
|
unknown
| 4,099
|
package com.heima.utils.common;
import com.hankcs.hanlp.seg.common.Term;
import com.hankcs.hanlp.tokenizer.StandardTokenizer;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("all")
public class SimHashUtils {
/**
* 清除html标签
* @param content
* @return
*/
private static String cleanResume(String content) {
// 若输入为HTML,下面会过滤掉所有的HTML的tag
content = Jsoup.clean(content, Whitelist.none());
content = StringUtils.lowerCase(content);
String[] strings = {" ", "\n", "\r", "\t", "\\r", "\\n", "\\t", " "};
for (String s : strings) {
content = content.replaceAll(s, "");
}
return content;
}
/**
* 这个是对整个字符串进行hash计算
* @return
*/
private static BigInteger simHash(String token,int hashbits) {
token = cleanResume(token); // cleanResume 删除一些特殊字符
int[] v = new int[hashbits];
List<Term> termList = StandardTokenizer.segment(token); // 对字符串进行分词
//对分词的一些特殊处理 : 比如: 根据词性添加权重 , 过滤掉标点符号 , 过滤超频词汇等;
Map<String, Integer> weightOfNature = new HashMap<String, Integer>(); // 词性的权重
weightOfNature.put("n", 2); //给名词的权重是2;
Map<String, String> stopNatures = new HashMap<String, String>();//停用的词性 如一些标点符号之类的;
stopNatures.put("w", ""); //
int overCount = 5; //设定超频词汇的界限 ;
Map<String, Integer> wordCount = new HashMap<String, Integer>();
for (Term term : termList) {
String word = term.word; //分词字符串
String nature = term.nature.toString(); // 分词属性;
// 过滤超频词
if (wordCount.containsKey(word)) {
int count = wordCount.get(word);
if (count > overCount) {
continue;
}
wordCount.put(word, count + 1);
} else {
wordCount.put(word, 1);
}
// 过滤停用词性
if (stopNatures.containsKey(nature)) {
continue;
}
// 2、将每一个分词hash为一组固定长度的数列.比如 64bit 的一个整数.
BigInteger t = hash(word,hashbits);
for (int i = 0; i < hashbits; i++) {
BigInteger bitmask = new BigInteger("1").shiftLeft(i);
// 3、建立一个长度为64的整数数组(假设要生成64位的数字指纹,也可以是其它数字),
// 对每一个分词hash后的数列进行判断,如果是1000...1,那么数组的第一位和末尾一位加1,
// 中间的62位减一,也就是说,逢1加1,逢0减1.一直到把所有的分词hash数列全部判断完毕.
int weight = 1; //添加权重
if (weightOfNature.containsKey(nature)) {
weight = weightOfNature.get(nature);
}
if (t.and(bitmask).signum() != 0) {
// 这里是计算整个文档的所有特征的向量和
v[i] += weight;
} else {
v[i] -= weight;
}
}
}
BigInteger fingerprint = new BigInteger("0");
for (int i = 0; i < hashbits; i++) {
if (v[i] >= 0) {
fingerprint = fingerprint.add(new BigInteger("1").shiftLeft(i));
}
}
return fingerprint;
}
/**
* 对单个的分词进行hash计算;
* @param source
* @return
*/
private static BigInteger hash(String source,int hashbits) {
if (source == null || source.length() == 0) {
return new BigInteger("0");
} else {
/**
* 当sourece 的长度过短,会导致hash算法失效,因此需要对过短的词补偿
*/
while (source.length() < 3) {
source = source + source.charAt(0);
}
char[] sourceArray = source.toCharArray();
BigInteger x = BigInteger.valueOf(((long) sourceArray[0]) << 7);
BigInteger m = new BigInteger("1000003");
BigInteger mask = new BigInteger("2").pow(hashbits).subtract(new BigInteger("1"));
for (char item : sourceArray) {
BigInteger temp = BigInteger.valueOf((long) item);
x = x.multiply(m).xor(temp).and(mask);
}
x = x.xor(new BigInteger(String.valueOf(source.length())));
if (x.equals(new BigInteger("-1"))) {
x = new BigInteger("-2");
}
return x;
}
}
/**
* 计算海明距离,海明距离越小说明越相似;
* @param other
* @return
*/
private static int hammingDistance(String token1,String token2,int hashbits) {
BigInteger m = new BigInteger("3").shiftLeft(hashbits).subtract(
new BigInteger("3"));
BigInteger x = simHash(token1,hashbits).xor(simHash(token2,hashbits)).and(m);
int tot = 0;
while (x.signum() != 0) {
tot += 1;
x = x.and(x.subtract(new BigInteger("3")));
}
return tot;
}
public static double getSemblance(String token1,String token2){
double i = (double) hammingDistance(token1,token2, 64);
return 1 - i/64 ;
}
public static void main(String[] args) {
String s1 = "....";
String s2 = "最近公司由于业务拓展,需要进行小程序相关的开发,本着朝全栈开发者努力,决定学习下Vue,去年csdn送了一本《Vue.js权威指南》,那就从这本书开始练起来吧。哟吼。一,环境搭建\n" +
"今天主要说一下如何搭建环境,以及如何运行。1,npm安装\n" +
"brew install npm\n" +
"1\n" +
"如果brew没有安装的话,大家可以brew如何安装哦,这里就不再详细说明了。本来是有一个Vue的图标的,被我给去掉了,方便后面的调试。\n" +
"\n" +
"三,Vue.js 权威指南的第一个demo\n" +
"一切准备就绪,接下来我们开始练习《Vue.js权威指南》这本书中的demo,在网上找了许久,也没有找到书中的源码,很是遗憾啊。第一个demo的代码保存为jk.vue \n" +
"我这边将第一个demo的代码如下:\n" +
"--------------------- \n" +
"作者:JackLee18 \n" +
"来源:CSDN \n" +
"原文:https://blog.csdn.net/hanhailong18/article/details/81509952 \n" +
"版权声明:本文为博主原创文章,转载请附上博文链接!";
double semblance = getSemblance(s1, s2);
System.out.println(semblance);
}
}
|
2201_75631765/heima
|
heima-leadnews-utils/src/main/java/com/heima/utils/common/SimHashUtils.java
|
Java
|
unknown
| 7,254
|
package com.heima.utils.common;
/**
* Twitter_Snowflake<br>
* SnowFlake的结构如下(每部分用-分开):<br>
* 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
* 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br>
* 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截)
* 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br>
* 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId<br>
* 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号<br>
* 加起来刚好64位,为一个Long型。<br>
* SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。
*/
public class SnowflakeIdWorker {
// ==============================Fields===========================================
/** 开始时间截 (2015-01-01) */
private final long twepoch = 1420041600000L;
/** 机器id所占的位数 */
private final long workerIdBits = 5L;
/** 数据标识id所占的位数 */
private final long datacenterIdBits = 5L;
/** 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) */
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
/** 支持的最大数据标识id,结果是31 */
private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
/** 序列在id中占的位数 */
private final long sequenceBits = 12L;
/** 机器ID向左移12位 */
private final long workerIdShift = sequenceBits;
/** 数据标识id向左移17位(12+5) */
private final long datacenterIdShift = sequenceBits + workerIdBits;
/** 时间截向左移22位(5+5+12) */
private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
/** 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095) */
private final long sequenceMask = -1L ^ (-1L << sequenceBits);
/** 工作机器ID(0~31) */
private long workerId;
/** 数据中心ID(0~31) */
private long datacenterId;
/** 毫秒内序列(0~4095) */
private long sequence = 0L;
/** 上次生成ID的时间截 */
private long lastTimestamp = -1L;
//==============================Constructors=====================================
/**
* 构造函数
* @param workerId 工作ID (0~31)
* @param datacenterId 数据中心ID (0~31)
*/
public SnowflakeIdWorker(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
// ==============================Methods==========================================
/**
* 获得下一个ID (该方法是线程安全的)
* @return SnowflakeId
*/
public synchronized long nextId() {
long timestamp = timeGen();
//如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
if (timestamp < lastTimestamp) {
throw new RuntimeException(
String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
//如果是同一时间生成的,则进行毫秒内序列
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
//毫秒内序列溢出
if (sequence == 0) {
//阻塞到下一个毫秒,获得新的时间戳
timestamp = tilNextMillis(lastTimestamp);
}
}
//时间戳改变,毫秒内序列重置
else {
sequence = 0L;
}
//上次生成ID的时间截
lastTimestamp = timestamp;
//移位并通过或运算拼到一起组成64位的ID
return ((timestamp - twepoch) << timestampLeftShift) //
| (datacenterId << datacenterIdShift) //
| (workerId << workerIdShift) //
| sequence;
}
/**
* 阻塞到下一个毫秒,直到获得新的时间戳
* @param lastTimestamp 上次生成ID的时间截
* @return 当前时间戳
*/
protected long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
/**
* 返回以毫秒为单位的当前时间
* @return 当前时间(毫秒)
*/
protected long timeGen() {
return System.currentTimeMillis();
}
//==============================Test=============================================
/** 测试 */
public static void main(String[] args) {
SnowflakeIdWorker idWorker = new SnowflakeIdWorker(10, 10);
for (int i = 0; i < 10000; i++) {
long id = idWorker.nextId();
System.out.println(id);
}
}
}
|
2201_75631765/heima
|
heima-leadnews-utils/src/main/java/com/heima/utils/common/SnowflakeIdWorker.java
|
Java
|
unknown
| 6,014
|
package com.heima.utils.common;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import java.util.Map;
import java.util.SortedMap;
public enum UrlSignUtils {
getUrlSignUtils;
private static final Logger logger = LoggerFactory.getLogger(UrlSignUtils.class);
/**
* @param params 所有的请求参数都会在这里进行排序加密
* @return 得到签名
*/
public String getSign(SortedMap<String, String> params) {
StringBuilder sb = new StringBuilder();
for (Map.Entry entry : params.entrySet()) {
if (!entry.getKey().equals("sign")) { //拼装参数,排除sign
if (!StringUtils.isEmpty(entry.getKey()) && !StringUtils.isEmpty(entry.getValue()))
sb.append(entry.getKey()).append('=').append(entry.getValue());
}
}
logger.info("Before Sign : {}", sb.toString());
return DigestUtils.md5Hex(sb.toString()).toUpperCase();
}
/**
* @param params 所有的请求参数都会在这里进行排序加密
* @return 验证签名结果
*/
public boolean verifySign(SortedMap<String, String> params) {
if (params == null || StringUtils.isEmpty(params.get("sign"))) return false;
String sign = getSign(params);
logger.info("verify Sign : {}", sign);
return !StringUtils.isEmpty(sign) && params.get("sign").equals(sign);
}
}
|
2201_75631765/heima
|
heima-leadnews-utils/src/main/java/com/heima/utils/common/UrlSignUtils.java
|
Java
|
unknown
| 1,517
|
package com.heima.utils.common;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.*;
/**
* 字符串压缩
*/
public class ZipUtils {
/**
* 使用gzip进行压缩
*/
public static String gzip(String primStr) {
if (primStr == null || primStr.length() == 0) {
return primStr;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = null;
try {
gzip = new GZIPOutputStream(out);
gzip.write(primStr.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzip != null) {
try {
gzip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new sun.misc.BASE64Encoder().encode(out.toByteArray());
}
/**
* <p>
* Description:使用gzip进行解压缩
* </p>
*
* @param compressedStr
* @return
*/
public static String gunzip(String compressedStr) {
if (compressedStr == null) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = null;
GZIPInputStream ginzip = null;
byte[] compressed = null;
String decompressed = null;
try {
compressed = new sun.misc.BASE64Decoder().decodeBuffer(compressedStr);
in = new ByteArrayInputStream(compressed);
ginzip = new GZIPInputStream(in);
byte[] buffer = new byte[1024];
int offset = -1;
while ((offset = ginzip.read(buffer)) != -1) {
out.write(buffer, 0, offset);
}
decompressed = out.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ginzip != null) {
try {
ginzip.close();
} catch (IOException e) {
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
return decompressed;
}
/**
* 使用zip进行压缩
*
* @param str 压缩前的文本
* @return 返回压缩后的文本
*/
public static final String zip(String str) {
if (str == null)
return null;
byte[] compressed;
ByteArrayOutputStream out = null;
ZipOutputStream zout = null;
String compressedStr = null;
try {
out = new ByteArrayOutputStream();
zout = new ZipOutputStream(out);
zout.putNextEntry(new ZipEntry("0"));
zout.write(str.getBytes());
zout.closeEntry();
compressed = out.toByteArray();
compressedStr = new sun.misc.BASE64Encoder().encodeBuffer(compressed);
} catch (IOException e) {
compressed = null;
} finally {
if (zout != null) {
try {
zout.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
return compressedStr;
}
/**
* 使用zip进行解压缩
*
* @param compressedStr 压缩后的文本
* @return 解压后的字符串
*/
public static final String unzip(String compressedStr) {
if (compressedStr == null) {
return null;
}
ByteArrayOutputStream out = null;
ByteArrayInputStream in = null;
ZipInputStream zin = null;
String decompressed = null;
try {
byte[] compressed = new sun.misc.BASE64Decoder().decodeBuffer(compressedStr);
out = new ByteArrayOutputStream();
in = new ByteArrayInputStream(compressed);
zin = new ZipInputStream(in);
zin.getNextEntry();
byte[] buffer = new byte[1024];
int offset = -1;
while ((offset = zin.read(buffer)) != -1) {
out.write(buffer, 0, offset);
}
decompressed = out.toString();
} catch (IOException e) {
decompressed = null;
} finally {
if (zin != null) {
try {
zin.close();
} catch (IOException e) {
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
return decompressed;
}
}
|
2201_75631765/heima
|
heima-leadnews-utils/src/main/java/com/heima/utils/common/ZipUtils.java
|
Java
|
unknown
| 5,256
|
package com.heima.utils.thread;
import com.heima.model.user.pojos.ApUser;
/**
* author Link
*
* @version 1.0
* @date 2025/4/6 16:21
*/
public class AppThreadLocalUtil {
private final static ThreadLocal<ApUser> WM_USER_THREAD_LOCAL = new ThreadLocal<>();
//存入线程
public static void setUser(ApUser apUser){
WM_USER_THREAD_LOCAL.set(apUser);
}
//从线程中获取
public static ApUser getUser(){
return WM_USER_THREAD_LOCAL.get();
}
//清理
public static void clear(){
WM_USER_THREAD_LOCAL.remove();
}
}
|
2201_75631765/heima
|
heima-leadnews-utils/src/main/java/com/heima/utils/thread/AppThreadLocalUtil.java
|
Java
|
unknown
| 583
|
package com.heima.utils.thread;
import com.heima.model.wemedia.pojos.WmUser;
/**
* author Link
*
* @version 1.0
* @date 2025/4/6 16:21
*/
public class WmThreadLocalUtil {
private final static ThreadLocal<WmUser> WM_USER_THREAD_LOCAL = new ThreadLocal<>();
//存入线程
public static void setUser(WmUser wmUser){
WM_USER_THREAD_LOCAL.set(wmUser);
}
//从线程中获取
public static WmUser getUser(){
return WM_USER_THREAD_LOCAL.get();
}
//清理
public static void clear(){
WM_USER_THREAD_LOCAL.remove();
}
}
|
2201_75631765/heima
|
heima-leadnews-utils/src/main/java/com/heima/utils/thread/WmThreadLocalUtil.java
|
Java
|
unknown
| 585
|
package com.jcm.system.api;
import com.jcm.common.core.constant.SecurityConstants;
import com.jcm.common.core.constant.ServiceNameConstants;
import com.jcm.common.core.domain.R;
import com.jcm.system.api.domain.SysLogininfor;
import com.jcm.system.api.domain.SysOperLog;
import com.jcm.system.api.factory.RemoteLogFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
/**
* 日志服务
*
* @author junchenmo
*/
@FeignClient(contextId = "remoteLogService", value = ServiceNameConstants.SYSTEM_SERVICE, fallbackFactory = RemoteLogFallbackFactory.class)
public interface RemoteLogService
{
/**
* 保存系统日志
*
* @param sysOperLog 日志实体
* @param source 请求来源
* @return 结果
*/
@PostMapping("/operlog")
public R<Boolean> saveLog(@RequestBody SysOperLog sysOperLog, @RequestHeader(SecurityConstants.FROM_SOURCE) String source) throws Exception;
/**
* 保存访问记录
*
* @param sysLogininfor 访问实体
* @param source 请求来源
* @return 结果
*/
@PostMapping("/logininfor")
public R<Boolean> saveLogininfor(@RequestBody SysLogininfor sysLogininfor, @RequestHeader(SecurityConstants.FROM_SOURCE) String source);
}
|
2022521971/JUNCHENMO-After
|
jcm-api/jcm-api-system/src/main/java/com/jcm/system/api/RemoteLogService.java
|
Java
|
unknown
| 1,435
|
package com.jcm.system.api;
import com.jcm.common.core.constant.SecurityConstants;
import com.jcm.common.core.constant.ServiceNameConstants;
import com.jcm.common.core.domain.R;
import com.jcm.system.api.domain.SysUser;
import com.jcm.system.api.factory.RemoteUserFallbackFactory;
import com.jcm.system.api.model.LoginUser;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
/**
* 用户服务
*
* @author junchenmo
*/
@FeignClient(contextId = "remoteUserService", value = ServiceNameConstants.SYSTEM_SERVICE, fallbackFactory = RemoteUserFallbackFactory.class)
public interface RemoteUserService
{
/**
* 通过用户名查询用户信息
*
* @param username 用户名
* @param source 请求来源
* @return 结果
*/
@GetMapping("/user/info/{username}")
public R<LoginUser> getUserInfo(@PathVariable("username") String username, @RequestHeader(SecurityConstants.FROM_SOURCE) String source);
/**
* 注册用户信息
*
* @param sysUser 用户信息
* @param source 请求来源
* @return 结果
*/
@PostMapping("/user/register")
public R<Boolean> registerUserInfo(@RequestBody SysUser sysUser, @RequestHeader(SecurityConstants.FROM_SOURCE) String source);
/**
* 修改用户最后登录时间和登录IP
*
* @param sysUser 用户信息
* @param source 请求来源
* @return 结果
*/
@PutMapping("/user/changeLoginInfo")
public R<Integer> changeLoginInfo(@RequestBody SysUser sysUser, @RequestHeader(SecurityConstants.FROM_SOURCE) String source);
}
|
2022521971/JUNCHENMO-After
|
jcm-api/jcm-api-system/src/main/java/com/jcm/system/api/RemoteUserService.java
|
Java
|
unknown
| 1,638
|
package com.jcm.system.api.domain;
import com.alibaba.excel.annotation.ExcelIgnoreUnannotated;
import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.jcm.common.core.domain.BaseEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
/**
* logininfor对象 sys_logininfor
*
* @author lvshihao
* @date 2025-01-11
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@ExcelIgnoreUnannotated
@TableName("sys_logininfor")
public class SysLogininfor extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 访问ID */
@TableId(type = IdType.AUTO)
@ExcelProperty(value = "登录日志ID")
private Long infoId;
/** 用户账号 */
@ExcelProperty(value = "用户账号")
private String userName;
/** 登录IP地址 */
@ExcelProperty(value = "登录IP地址")
private String ipaddr;
/** 登录地点 */
@ExcelProperty(value = "登录地点")
private String loginLocation;
/** 浏览器类型 */
@ExcelProperty(value = "浏览器类型")
private String browser;
/** 操作系统 */
@ExcelProperty(value = "操作系统")
private String os;
/** 登录状态(0成功 1失败) */
@ExcelProperty(value = "登录状态(0成功 1失败)")
private String status;
/** 提示消息 */
@ExcelProperty(value = "提示消息")
private String msg;
/** 访问时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ExcelProperty(value = "访问时间")
private LocalDateTime loginTime;
}
|
2022521971/JUNCHENMO-After
|
jcm-api/jcm-api-system/src/main/java/com/jcm/system/api/domain/SysLogininfor.java
|
Java
|
unknown
| 1,926
|
package com.jcm.system.api.domain;
import com.alibaba.excel.annotation.ExcelIgnoreUnannotated;
import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.jcm.common.core.domain.BaseEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
/**
* <p>
* 操作日志记录
* </p>
*
* @author 吕世昊
* @since 2024-05-03
*/
@Data
@ExcelIgnoreUnannotated
@TableName("sys_oper_log")
@Schema(description="操作日志记录")
public class SysOperLog extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 日志主键
* 在Excel导入导出中,对应表头名称为"日志主键",列索引默认为0(按定义顺序依次递增)
*/
@Schema(description = "日志主键")
@ExcelProperty(value = "日志主键")
@TableId(value = "oper_id", type = IdType.AUTO)
private Long operId;
/**
* 模块标题
* 在Excel导入导出中,对应表头名称为"模块标题",列索引为1
*/
@Schema(description = "模块标题")
@ExcelProperty(value = "模块标题", index = 1)
private String title;
/**
* 业务名称
* 在Excel导入导出中,对应表头名称为"业务名称",列索引为2
*/
@Schema(description = "业务名称")
@ExcelProperty(value = "业务名称", index = 2)
private String businessName;
/**
* 业务类型(0其它 1新增 2修改 3删除)
* 在Excel导入导出中,对应表头名称为"业务类型",列索引为3
*/
@Schema(description = "业务类型(0其它 1新增 2修改 3删除)")
@ExcelProperty(value = "业务类型", index = 3)
private Integer businessType;
/**
* 操作日志
* 在Excel导入导出中,对应表头名称为"操作日志",列索引为4
*/
@Schema(description = "操作日志")
@ExcelProperty(value = "操作日志", index = 4)
private String description;
/**
* 操作日志Html
*/
@Schema(description = "操作日志Html")
private String descriptionHtml;
/**
* 方法名称
* 在Excel导入导出中,对应表头名称为"方法名称",列索引为5
*/
@Schema(description = "方法名称")
@ExcelProperty(value = "方法名称", index = 5)
private String method;
/**
* 请求方式
* 在Excel导入导出中,对应表头名称为"请求方式",列索引为6
*/
@Schema(description = "请求方式")
@ExcelProperty(value = "请求方式", index = 6)
private String requestMethod;
/**
* 请求时间
* 在Excel导入导出中,对应表头名称为"请求时间",列索引为7。
* 同时使用了 @JsonFormat 和 @DateTimeFormat 注解来规范时间格式的序列化与反序列化,在Excel中期望的格式为 "yyyy-MM-dd HH:mm:ss"
*/
@Schema(description = "请求时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ExcelProperty(value = "请求时间", index = 7)
private LocalDateTime requestTime;
/**
* 操作人员
* 在Excel导入导出中,对应表头名称为"操作人员",列索引为9
*/
@Schema(description = "操作人员")
@ExcelProperty(value = "操作人员", index = 9)
private String operName;
/**
* 请求URL
* 在Excel导入导出中,对应表头名称为"请求URL",列索引为10
*/
@Schema(description = "请求URL")
@ExcelProperty(value = "请求URL", index = 10)
private String operUrl;
/**
* 主机地址
* 在Excel导入导出中,对应表头名称为"主机地址",列索引为11
*/
@Schema(description = "主机地址")
@ExcelProperty(value = "主机地址", index = 11)
private String operIp;
/**
* 操作地点
* 在Excel导入导出中,对应表头名称为"操作地点",列索引为12
*/
@Schema(description = "操作地点")
@ExcelProperty(value = "操作地点", index = 12)
private String operLocation;
/**
* 请求参数
* 在Excel导入导出中,对应表头名称为"请求参数",列索引为13
*/
@Schema(description = "请求参数")
@ExcelProperty(value = "请求参数", index = 13)
private String operParam;
/**
* 返回参数
* 在Excel导入导出中,对应表头名称为"返回参数",列索引为14
*/
@Schema(description = "返回参数")
@ExcelProperty(value = "返回参数", index = 14)
private String jsonResult;
/**
* 操作状态(0正常 1异常)
* 在Excel导入导出中,对应表头名称为"操作状态",列索引为15
*/
@Schema(description = "操作状态(0正常 1异常)")
@ExcelProperty(value = "操作状态", index = 15)
private Integer status;
/**
* 错误消息
* 在Excel导入导出中,对应表头名称为"错误消息",列索引为16
*/
@Schema(description = "错误消息")
@ExcelProperty(value = "错误消息", index = 16)
private String errorMsg;
/**
* 错误消息
*/
@Schema(description = "错误消息Html")
private String errorMsgHtml;
/**
* 消耗时间
* 在Excel导入导出中,对应表头名称为"消耗时间",列索引为17
*/
@Schema(description = "消耗时间")
@ExcelProperty(value = "消耗时间", index = 17)
private Long costTime;
}
|
2022521971/JUNCHENMO-After
|
jcm-api/jcm-api-system/src/main/java/com/jcm/system/api/domain/SysOperLog.java
|
Java
|
unknown
| 6,318
|
package com.jcm.system.api.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.jcm.common.core.domain.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
/**
* <p>
* 用户表
* </p>
*
* @author 吕世昊
* @since 2024-04-01
*/
@Data
@Accessors(chain = true)
@TableName("sys_user")
@ApiModel(description = "用户信息")
public class SysUser extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 用户ID,自增主键
*/
@ApiModelProperty(value = "用户ID,自增主键", example = "1")
@TableId(type = IdType.AUTO)
private Long userId;
/**
* 用户名
*/
@ApiModelProperty(value = "用户名", example = "admin")
private String username;
/**
* 密码
*/
@ApiModelProperty(value = "密码", example = "password")
private String password;
/**
* 用户昵称
*/
@ApiModelProperty(value = "用户昵称", example = "管理员")
private String nickname;
/**
* 邮箱
*/
@ApiModelProperty(value = "邮箱", example = "admin@example.com")
private String email;
/**
* 手机号
*/
@ApiModelProperty(value = "手机号", example = "13800138000")
private String mobile;
/**
* 性别(0男,1女,2未知)
*/
@ApiModelProperty(value = "性别(0男,1女,2未知)", example = "0")
private Integer sex;
/**
* 头像
*/
@ApiModelProperty(value = "头像", example = "http://example.com/avatar.jpg")
private String avatar;
/**
* 状态(0正常,1禁用)
*/
@ApiModelProperty(value = "状态(0正常,1禁用)", example = "0")
private Integer status;
/**
* 最后登录IP地址
*/
@ApiModelProperty(value = "最后登录IP地址", example = "127.0.0.1")
private String loginIp;
/**
* 最后登录时间
*/
@ApiModelProperty(value = "最后登录时间", example = "2024-12-28 00:00:00")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime loginDate;
public boolean isAdmin()
{
return isAdmin(this.userId);
}
public static boolean isAdmin(Long userId)
{
return userId != null && 1L == userId;
}
}
|
2022521971/JUNCHENMO-After
|
jcm-api/jcm-api-system/src/main/java/com/jcm/system/api/domain/SysUser.java
|
Java
|
unknown
| 2,665
|