Commit 22f4c62c authored by alex yao's avatar alex yao

INIT

parents
/target/
/.idea/
marketingai-edu-api.iml
\ No newline at end of file
pipeline {
agent {
docker {
image 'maven:3.3.9'
args '-v /root/jenkins/data/mvn/settings.xml:/usr/share/maven/conf/settings.xml -v /root/jenkins/data/mvn/maven-repo:/data/maven-repo -v /var/run/docker.sock:/var/run/docker.sock -v /usr/bin/docker:/usr/bin/docker -u root:994'
}
}
stages {
stage('Build') {
steps {
sh 'mvn clean package -U -Dmaven.test.skip=true'
}
}
stage('Build Docker Image') {
steps {
sh '''mvn docker:build
IFS=$\'
\';
for info in $(docker images|grep $image_prefix/$docker_image_name);
do
repository=`echo $info | awk \'{print $1}\'`;
image_name=`echo $repository | awk -F \'/\' \'{print $2}\'`;
tag=`echo $info | awk \'{print $2}\'`;
image_id=`echo $info | awk \'{print $3}\'`;
printf "%-35s %-25s %-10s %-17s " $repository $image_name $tag $image_id
docker tag $image_id $registry_address/$docker_image_group_name/$docker_image_name:$tag
done
'''
}
}
stage('Push Docker Image') {
steps {
sh '''docker login -u deployment -p deployment123 $registry_address
start_time=`date +'%Y-%m-%d,%H:%m:%S'`
docker images |grep $registry_address/$docker_image_group_name/$docker_image_name|awk \'{system("docker push " $1":"$2)}\'
end_time=`date +'%Y-%m-%d,%H:%m:%S'`'''
}
}
stage('Deploy to SIT') {
steps {
sh '''# docker-compose pull env
curl -X PUT http://$dcui_address/api/v1/projects --data \'{"id":"\'$dcui_project_id\'"}\' -H\'Content-type: application/json\''''
sh '''# docker-compose up
curl -X POST http://$dcui_address/api/v1/projects --data \'{"id":"\'$dcui_project_id\'"}\' -H\'Content-type: application/json\''''
}
}
stage('Cleanup') {
steps {
sh '''if [ "$(docker images |grep /$docker_image_group_name/$docker_image_name |awk {\'print $3\'})" = "" ] ; then
echo "No orphan images found"
else
docker rmi -f $(docker images |grep /$docker_image_group_name/$docker_image_name |awk {\'print $3\'})
fi'''
cleanWs(deleteDirs: true)
}
}
}
environment {
// Docker Compose UI的地址
dcui_address = '192.168.21.102:5000'
dcui_project_id = 'poc'
// 私有仓库地址
registry_address = 'nexus3.gsstcloud.com:8092'
// mvn docker:build的镜像前缀
image_prefix = 'dev-localhost'
docker_image_group_name = 'poc'
docker_image_name = 'poc-api'
}
}
pipeline {
agent {
docker {
image 'node:lts'
args '-v /var/run/docker.sock:/var/run/docker.sock -v /usr/bin/docker:/usr/bin/docker -v /usr/bin/sshpass:/usr/bin/sshpass'
}
}
stages {
stage('PUSH IMAGE') {
steps {
sh '''docker login --username=rcsadmin@gsst -p 9HRpm_hk registry.cn-shenzhen.aliyuncs.com
docker pull $get_image_address/$image_name:latest
docker tag $get_image_address/$image_name:latest $registry_address/$image_name:latest
docker push $registry_address/$image_name:latest'''
}
}
stage('Cleanup') {
steps {
cleanWs(deleteDirs: true)
}
}
}
environment {
registry_address = 'registry.cn-shenzhen.aliyuncs.com/gsst'
get_image_address = 'nexus3.gsstcloud.com:8092/ibt'
image_name = 'ibt-cantonese-api'
}
}
# poc-api
POC-api层
\ No newline at end of file
This diff is collapsed.
FROM tomcat:9-jdk8-openjdk
RUN echo "Asia/Shanghai" > /etc/timezone
EXPOSE 8080
EXPOSE 40083
EXPOSE 40088
ARG targetFile
ADD $targetFile /usr/local/tomcat/webapps/api.war
\ No newline at end of file
package cn.com.poc.audio_generation.aggregation;
import cn.com.poc.audio_generation.entity.BatchGenerateEntity;
import cn.com.poc.audio_generation.entity.GenerationStatusEntity;
import java.util.List;
public interface AudioGenerationService {
/**
* 创建文本转音频任务
*
* @param text
* @param voiceId
* @param speed
* @return 任务ID
*/
Long createTextToAudioTask(String text, String voiceId, Double speed);
/**
* 批量创建文本转音频任务
*
* @param entities 任务实体
* @return 任务ID
*/
List<Long> batchCreateTextToAudioTask(List<BatchGenerateEntity> entities);
/**
* 获取任务状态
*/
String getTaskStatus(Long taskId);
/**
* 批量获取任务状态
*/
List<GenerationStatusEntity> batchGetAudioGenerationTask(List<Long> taskIds);
}
package cn.com.poc.audio_generation.aggregation.impl;
import cn.com.poc.audio_generation.aggregation.AudioGenerationService;
import cn.com.poc.audio_generation.constant.AudioGenerationTaskStatusConstant;
import cn.com.poc.audio_generation.entity.BatchGenerateEntity;
import cn.com.poc.audio_generation.entity.BizAudioGenerationTaskEntity;
import cn.com.poc.audio_generation.entity.GenerationStatusEntity;
import cn.com.poc.audio_generation.service.BizAudioGenerationTaskService;
import cn.com.poc.common.constant.CommonConstant;
import cn.com.poc.common.utils.Assert;
import cn.com.poc.message.entity.AudioGenerationMessage;
import cn.com.poc.message.service.AudioGenerationProducerService;
import cn.com.yict.framemax.core.exception.BusinessException;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Component
public class AudioGenerationServiceImpl implements AudioGenerationService {
@Resource
private BizAudioGenerationTaskService bizAudioGenerationTaskService;
@Resource
private AudioGenerationProducerService audioGenerationProducerService;
@Override
public Long createTextToAudioTask(String text, String voiceId, Double speed) {
Assert.notBlank(text, "text is blank");
Assert.notBlank(voiceId, "voiceId is blank");
BizAudioGenerationTaskEntity bizAudioGenerationTaskEntity = new BizAudioGenerationTaskEntity();
bizAudioGenerationTaskEntity.setTextContent(text);
bizAudioGenerationTaskEntity.setVoiceId(voiceId);
bizAudioGenerationTaskEntity.setTaskStatus(AudioGenerationTaskStatusConstant.Running);
bizAudioGenerationTaskEntity.setIsDeleted(CommonConstant.IsDeleted.N);
BizAudioGenerationTaskEntity taskEntity = bizAudioGenerationTaskService.save(bizAudioGenerationTaskEntity);
// 创建任务后,需要调用语音合成服务,生成音频文件
AudioGenerationMessage audioGenerationMessage = new AudioGenerationMessage();
audioGenerationMessage.setTaskId(taskEntity.getTaskId());
audioGenerationMessage.setTextContent(text);
audioGenerationMessage.setVoiceId(voiceId);
audioGenerationMessage.setSpeed(speed);
audioGenerationProducerService.generateAudio(audioGenerationMessage);
return taskEntity.getTaskId();
}
@Override
public List<Long> batchCreateTextToAudioTask(List<BatchGenerateEntity> entities) {
Assert.notEmpty(entities, "entities is empty");
List<Long> taskIds = new ArrayList<>();
entities.forEach(entity -> {
taskIds.add(createTextToAudioTask(entity.getTextContent(), entity.getVoiceId(), entity.getSpeed()));
});
return taskIds;
}
@Override
public String getTaskStatus(Long taskId) {
BizAudioGenerationTaskEntity bizAudioGenerationTaskEntity = bizAudioGenerationTaskService.get(taskId);
if (null == bizAudioGenerationTaskEntity) {
throw new BusinessException("taskId is not exist");
}
return bizAudioGenerationTaskEntity.getTaskStatus();
}
@Override
public List<GenerationStatusEntity> batchGetAudioGenerationTask(List<Long> taskIds) {
Assert.notEmpty(taskIds, "taskIds is empty");
List<GenerationStatusEntity> generationStatusEntities = new ArrayList<>();
for (Long taskId : taskIds) {
BizAudioGenerationTaskEntity bizAudioGenerationTaskEntity = bizAudioGenerationTaskService.get(taskId);
if (null == bizAudioGenerationTaskEntity) {
throw new BusinessException("taskId is not exist");
}
GenerationStatusEntity generationStatusEntity = new GenerationStatusEntity();
generationStatusEntity.setTaskStatus(bizAudioGenerationTaskEntity.getTaskStatus());
generationStatusEntity.setTaskId(taskId);
generationStatusEntity.setAudioUrl(bizAudioGenerationTaskEntity.getAudioUrl());
generationStatusEntities.add(generationStatusEntity);
}
return generationStatusEntities;
}
}
package cn.com.poc.audio_generation.constant;
public interface AudioGenerationTaskStatusConstant {
String Running = "Running";
String Success = "Success";
String Fail = "Fail";
String Cancel = "Cancel";
}
package cn.com.poc.audio_generation.convert;
import cn.com.poc.audio_generation.entity.BizAudioGenerationTaskEntity;
import cn.com.poc.audio_generation.model.BizAudioGenerationTaskModel;
public class AudioGenerationTaskConvert {
public static BizAudioGenerationTaskEntity modelToEntity(BizAudioGenerationTaskModel model) {
BizAudioGenerationTaskEntity bizAudioGenerationTaskEntity = new BizAudioGenerationTaskEntity();
bizAudioGenerationTaskEntity.setTaskId(model.getTaskId());
bizAudioGenerationTaskEntity.setTextContent(model.getTextContent());
bizAudioGenerationTaskEntity.setVoiceId(model.getVoiceId());
bizAudioGenerationTaskEntity.setTaskInfo(model.getTaskInfo());
bizAudioGenerationTaskEntity.setTaskStatus(model.getTaskStatus());
bizAudioGenerationTaskEntity.setAudioUrl(model.getAudioUrl());
bizAudioGenerationTaskEntity.setIsDeleted(model.getIsDeleted());
return bizAudioGenerationTaskEntity;
}
public static BizAudioGenerationTaskModel entityToModel(BizAudioGenerationTaskEntity entity) {
BizAudioGenerationTaskModel bizAudioGenerationTaskModel = new BizAudioGenerationTaskModel();
bizAudioGenerationTaskModel.setTaskId(entity.getTaskId());
bizAudioGenerationTaskModel.setTextContent(entity.getTextContent());
bizAudioGenerationTaskModel.setVoiceId(entity.getVoiceId());
bizAudioGenerationTaskModel.setTaskInfo(entity.getTaskInfo());
bizAudioGenerationTaskModel.setTaskStatus(entity.getTaskStatus());
bizAudioGenerationTaskModel.setAudioUrl(entity.getAudioUrl());
bizAudioGenerationTaskModel.setIsDeleted(entity.getIsDeleted());
return bizAudioGenerationTaskModel;
}
}
package cn.com.poc.audio_generation.dto;
import java.io.Serializable;
public class BatchGenerateDto implements Serializable {
private String textContent;
private String voiceId;
public String getTextContent() {
return textContent;
}
public void setTextContent(String textContent) {
this.textContent = textContent;
}
public String getVoiceId() {
return voiceId;
}
public void setVoiceId(String voiceId) {
this.voiceId = voiceId;
}
}
package cn.com.poc.audio_generation.dto;
public class GenerationStatusDto {
private String taskStatus;
private Long taskId;
private String audioUrl;
public String getTaskStatus() {
return taskStatus;
}
public void setTaskStatus(String taskStatus) {
this.taskStatus = taskStatus;
}
public Long getTaskId() {
return taskId;
}
public void setTaskId(Long taskId) {
this.taskId = taskId;
}
public String getAudioUrl() {
return audioUrl;
}
public void setAudioUrl(String audioUrl) {
this.audioUrl = audioUrl;
}
}
package cn.com.poc.audio_generation.entity;
import java.io.Serializable;
public class BatchGenerateEntity implements Serializable {
private String textContent;
private String voiceId;
private Double speed;
public Double getSpeed() {
return speed;
}
public void setSpeed(Double speed) {
this.speed = speed;
}
public String getTextContent() {
return textContent;
}
public void setTextContent(String textContent) {
this.textContent = textContent;
}
public String getVoiceId() {
return voiceId;
}
public void setVoiceId(String voiceId) {
this.voiceId = voiceId;
}
}
package cn.com.poc.audio_generation.entity;
/**
* Model class for biz_audio_generation_task
* 音频生成任务表
*/
public class BizAudioGenerationTaskEntity {
/**
* task_id
* 任务ID
*/
private Long taskId;
public Long getTaskId() {
return this.taskId;
}
public void setTaskId(Long taskId) {
this.taskId = taskId;
}
/**
* text_content
* 文本内容
*/
private String textContent;
public String getTextContent() {
return this.textContent;
}
public void setTextContent(String textContent) {
this.textContent = textContent;
}
/**
* voice_id
* 发音者ID
*/
private String voiceId;
public String getVoiceId() {
return this.voiceId;
}
public void setVoiceId(String voiceId) {
this.voiceId = voiceId;
}
/**
* task_status
* 任务状态
*/
private String taskStatus;
public String getTaskStatus() {
return this.taskStatus;
}
public void setTaskStatus(String taskStatus) {
this.taskStatus = taskStatus;
}
/**
* audio_url
* 音频地址
*/
private String audioUrl;
public String getAudioUrl() {
return this.audioUrl;
}
public void setAudioUrl(String audioUrl) {
this.audioUrl = audioUrl;
}
/** task_info
*任务信息 - 记录任务错误/失败信息
*/
private java.lang.String taskInfo;
public java.lang.String getTaskInfo(){
return this.taskInfo;
}
public void setTaskInfo(java.lang.String taskInfo){
this.taskInfo = taskInfo;
}
/**
* is_deleted
* 是否删除 1、Y 是 2、N 否
*/
private String isDeleted;
public String getIsDeleted() {
return this.isDeleted;
}
public void setIsDeleted(String isDeleted) {
this.isDeleted = isDeleted;
}
}
\ No newline at end of file
package cn.com.poc.audio_generation.entity;
public class GenerationStatusEntity {
private String taskStatus;
private Long taskId;
private String audioUrl;
public String getTaskStatus() {
return taskStatus;
}
public void setTaskStatus(String taskStatus) {
this.taskStatus = taskStatus;
}
public Long getTaskId() {
return taskId;
}
public void setTaskId(Long taskId) {
this.taskId = taskId;
}
public String getAudioUrl() {
return audioUrl;
}
public void setAudioUrl(String audioUrl) {
this.audioUrl = audioUrl;
}
}
package cn.com.poc.audio_generation.model;
import java.io.Serializable;
import cn.com.yict.framemax.data.model.BaseModelClass;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.Version;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
/**
* Model class for biz_audio_generation_task
* 音频生成任务表
*/
@Entity
@Table(name = "biz_audio_generation_task")
@DynamicInsert
@DynamicUpdate
public class BizAudioGenerationTaskModel extends BaseModelClass implements Serializable {
private static final long serialVersionUID = 1L;
/** task_id
*任务ID
*/
private java.lang.Long taskId;
@Column(name = "task_id",length = 19)
@Id @GeneratedValue(strategy = GenerationType.AUTO)
public java.lang.Long getTaskId(){
return this.taskId;
}
public void setTaskId(java.lang.Long taskId){
this.taskId = taskId;
super.addValidField("taskId");
}
/** text_content
*文本内容
*/
private java.lang.String textContent;
@Column(name = "text_content",length = 65535)
public java.lang.String getTextContent(){
return this.textContent;
}
public void setTextContent(java.lang.String textContent){
this.textContent = textContent;
super.addValidField("textContent");
}
/** voice_id
*发音者ID
*/
private java.lang.String voiceId;
@Column(name = "voice_id",length = 125)
public java.lang.String getVoiceId(){
return this.voiceId;
}
public void setVoiceId(java.lang.String voiceId){
this.voiceId = voiceId;
super.addValidField("voiceId");
}
/** task_status
*任务状态
*/
private java.lang.String taskStatus;
@Column(name = "task_status",length = 10)
public java.lang.String getTaskStatus(){
return this.taskStatus;
}
public void setTaskStatus(java.lang.String taskStatus){
this.taskStatus = taskStatus;
super.addValidField("taskStatus");
}
/** audio_url
*音频地址
*/
private java.lang.String audioUrl;
@Column(name = "audio_url",length = 225)
public java.lang.String getAudioUrl(){
return this.audioUrl;
}
public void setAudioUrl(java.lang.String audioUrl){
this.audioUrl = audioUrl;
super.addValidField("audioUrl");
}
/** task_info
*任务信息 - 记录任务错误/失败信息
*/
private java.lang.String taskInfo;
@Column(name = "task_info",length = 225)
public java.lang.String getTaskInfo(){
return this.taskInfo;
}
public void setTaskInfo(java.lang.String taskInfo){
this.taskInfo = taskInfo;
super.addValidField("taskInfo");
}
/** is_deleted
*是否删除 1、Y 是 2、N 否
*/
private java.lang.String isDeleted;
@Column(name = "is_deleted",length = 1)
public java.lang.String getIsDeleted(){
return this.isDeleted;
}
public void setIsDeleted(java.lang.String isDeleted){
this.isDeleted = isDeleted;
super.addValidField("isDeleted");
}
/** CREATOR
*创建人
*/
private java.lang.String creator;
@Column(name = "CREATOR",length = 225)
public java.lang.String getCreator(){
return this.creator;
}
public void setCreator(java.lang.String creator){
this.creator = creator;
super.addValidField("creator");
}
/** CREATED_TIME
*创建时间
*/
private java.util.Date createdTime;
@Column(name = "CREATED_TIME",length = 19)
public java.util.Date getCreatedTime(){
return this.createdTime;
}
public void setCreatedTime(java.util.Date createdTime){
this.createdTime = createdTime;
super.addValidField("createdTime");
}
/** MODIFIER
*修改人
*/
private java.lang.String modifier;
@Column(name = "MODIFIER",length = 225)
public java.lang.String getModifier(){
return this.modifier;
}
public void setModifier(java.lang.String modifier){
this.modifier = modifier;
super.addValidField("modifier");
}
/** MODIFIED_TIME
*修改时间
*/
private java.util.Date modifiedTime;
@Column(name = "MODIFIED_TIME",length = 19)
public java.util.Date getModifiedTime(){
return this.modifiedTime;
}
public void setModifiedTime(java.util.Date modifiedTime){
this.modifiedTime = modifiedTime;
super.addValidField("modifiedTime");
}
/** SYS_VERSION
*乐观锁,版本号
*/
private java.lang.Integer sysVersion;
@Column(name = "SYS_VERSION",length = 10)
@Version
public java.lang.Integer getSysVersion(){
return this.sysVersion;
}
public void setSysVersion(java.lang.Integer sysVersion){
this.sysVersion = sysVersion;
super.addValidField("sysVersion");
}
}
\ No newline at end of file
package cn.com.poc.audio_generation.repository;
import cn.com.yict.framemax.data.repository.Repository;
import cn.com.poc.audio_generation.model.BizAudioGenerationTaskModel;
public interface BizAudioGenerationTaskRepository extends Repository<BizAudioGenerationTaskModel,java.lang.Long> {
}
\ No newline at end of file
package cn.com.poc.audio_generation.rest;
import cn.com.poc.audio_generation.dto.BatchGenerateDto;
import cn.com.poc.audio_generation.dto.GenerationStatusDto;
import cn.com.yict.framemax.core.rest.BaseRest;
import cn.com.yict.framemax.web.permission.Access;
import cn.com.yict.framemax.web.permission.Permission;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
@Permission(Access.Safety)
public interface GeneratedAudioRest extends BaseRest {
/**
* 批量创建音频生成任务
*
* @param generateDtoList
* @return
*/
List<Long> batchGenerate(@RequestBody List<BatchGenerateDto> generateDtoList);
/**
* 查询音频生成任务状态
*/
List<GenerationStatusDto> generatedStatus(@RequestBody List<Long> taskIdList);
}
package cn.com.poc.audio_generation.rest.impl;
import cn.com.poc.audio_generation.aggregation.AudioGenerationService;
import cn.com.poc.audio_generation.dto.BatchGenerateDto;
import cn.com.poc.audio_generation.dto.GenerationStatusDto;
import cn.com.poc.audio_generation.entity.BatchGenerateEntity;
import cn.com.poc.audio_generation.entity.GenerationStatusEntity;
import cn.com.poc.audio_generation.rest.GeneratedAudioRest;
import cn.com.poc.common.utils.Assert;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class GeneratedAudioRestImpl implements GeneratedAudioRest {
@Resource
private AudioGenerationService audioGenerationService;
@Override
public List<Long> batchGenerate(List<BatchGenerateDto> generateDtoList) {
Assert.notEmpty(generateDtoList, "参数不能为空");
List<BatchGenerateEntity> entities = generateDtoList.stream().map(dto -> {
BatchGenerateEntity entity = new BatchGenerateEntity();
entity.setTextContent(dto.getTextContent());
entity.setVoiceId(dto.getVoiceId());
return entity;
}).collect(Collectors.toList());
return audioGenerationService.batchCreateTextToAudioTask(entities);
}
@Override
public List<GenerationStatusDto> generatedStatus(List<Long> taskIdList) {
Assert.notEmpty(taskIdList, "参数不能为空");
List<GenerationStatusEntity> generationStatusEntities = audioGenerationService.batchGetAudioGenerationTask(taskIdList);
List<GenerationStatusDto> result = generationStatusEntities.stream().map(entity -> {
GenerationStatusDto dto = new GenerationStatusDto();
dto.setTaskId(entity.getTaskId());
dto.setTaskStatus(entity.getTaskStatus());
dto.setAudioUrl(entity.getAudioUrl());
return dto;
}).collect(Collectors.toList());
return result;
}
}
package cn.com.poc.audio_generation.service;
import cn.com.poc.audio_generation.entity.BizAudioGenerationTaskEntity;
import cn.com.yict.framemax.core.service.BaseService;
import cn.com.poc.audio_generation.model.BizAudioGenerationTaskModel;
import cn.com.yict.framemax.data.model.PagingInfo;
import java.util.Collection;
import java.util.List;
public interface BizAudioGenerationTaskService extends BaseService {
BizAudioGenerationTaskEntity get(java.lang.Long id);
List<BizAudioGenerationTaskEntity> findByExample(BizAudioGenerationTaskEntity entity, PagingInfo pagingInfo);
void deleteById(java.lang.Long id);
BizAudioGenerationTaskEntity save(BizAudioGenerationTaskEntity entity);
BizAudioGenerationTaskEntity update(BizAudioGenerationTaskEntity entity);
}
\ No newline at end of file
package cn.com.poc.audio_generation.service.impl;
import cn.com.poc.audio_generation.convert.AudioGenerationTaskConvert;
import cn.com.poc.audio_generation.entity.BizAudioGenerationTaskEntity;
import cn.com.poc.audio_generation.model.BizAudioGenerationTaskModel;
import cn.com.poc.audio_generation.repository.BizAudioGenerationTaskRepository;
import cn.com.poc.audio_generation.service.BizAudioGenerationTaskService;
import cn.com.poc.common.constant.CommonConstant;
import cn.com.poc.common.utils.Assert;
import cn.com.yict.framemax.core.service.impl.BaseServiceImpl;
import cn.com.yict.framemax.data.model.PagingInfo;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Service
public class BizAudioGenerationTaskServiceImpl extends BaseServiceImpl
implements BizAudioGenerationTaskService {
@Resource
private BizAudioGenerationTaskRepository repository;
@Override
public BizAudioGenerationTaskEntity get(Long id) {
Assert.notNull(id, "id is null");
BizAudioGenerationTaskModel model = this.repository.get(id);
if (model == null || model.getIsDeleted().equals(CommonConstant.IsDeleted.Y)) {
return null;
}
return AudioGenerationTaskConvert.modelToEntity(model);
}
@Override
public List<BizAudioGenerationTaskEntity> findByExample(BizAudioGenerationTaskEntity entity, PagingInfo pagingInfo) {
List<BizAudioGenerationTaskEntity> result = new ArrayList<>();
BizAudioGenerationTaskModel model = AudioGenerationTaskConvert.entityToModel(entity);
List<BizAudioGenerationTaskModel> models = this.repository.findByExample(model, pagingInfo);
if (CollectionUtils.isNotEmpty(models)) {
result = models.stream().map(AudioGenerationTaskConvert::modelToEntity).collect(java.util.stream.Collectors.toList());
}
return result;
}
@Override
public void deleteById(Long id) {
Assert.notNull(id, "id is null");
BizAudioGenerationTaskModel model = this.repository.get(id);
if (model == null || model.getIsDeleted().equals(CommonConstant.IsDeleted.Y)) {
return;
}
model.setIsDeleted(CommonConstant.IsDeleted.Y);
this.repository.save(model);
}
@Override
public BizAudioGenerationTaskEntity save(BizAudioGenerationTaskEntity entity) {
Assert.notNull(entity, "entity is null");
Assert.notBlank(entity.getTextContent(), "text content is null");
Assert.notBlank(entity.getTaskStatus(), "task status is null");
Assert.notBlank(entity.getVoiceId(), "voice id is null");
entity.setTaskId(null);
entity.setIsDeleted(CommonConstant.IsDeleted.N);
BizAudioGenerationTaskModel saveModel = this.repository.save(AudioGenerationTaskConvert.entityToModel(entity));
return AudioGenerationTaskConvert.modelToEntity(saveModel);
}
@Override
public BizAudioGenerationTaskEntity update(BizAudioGenerationTaskEntity entity) {
Assert.notNull(entity, "entity is null");
Assert.notNull(entity.getTaskId(), "task id is null");
BizAudioGenerationTaskModel model = this.repository.get(entity.getTaskId());
if (model == null || model.getIsDeleted().equals(CommonConstant.IsDeleted.Y)) {
return null;
}
CopyOptions copyOptions = new CopyOptions().ignoreNullValue();
BeanUtil.copyProperties(entity, model, copyOptions);
model.setIsDeleted(CommonConstant.IsDeleted.N);
return AudioGenerationTaskConvert.modelToEntity(this.repository.save(model));
}
}
\ No newline at end of file
package cn.com.poc.common.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Aspect
@Component
public class RateLimitAspect {
private Map<String, Long> accessMap = new ConcurrentHashMap<>();
@Around("execution(public * cn.com.poc.common.rest.SmsRest.smsDelivered(..))")
public Object limitAccess(ProceedingJoinPoint joinPoint) throws Throwable {
Object[] args = joinPoint.getArgs();
String phone = String.valueOf(args[0]);
// 检查访问计数和时间
if (isLimitExceeded(phone)) {
throw new RuntimeException("Too many requests. Please try again later.");
}
Object result = joinPoint.proceed();
// 更新访问计数和时间
updateAccess(phone);
return result;
}
private boolean isLimitExceeded(String phone) {
long now = System.currentTimeMillis();
//获取上次访问时间(phone作为key,上一次访问的时间作为value)
long lastAccessTime = accessMap.getOrDefault(phone, 0L);
long interval = now - lastAccessTime;
long limitInterval = 60000; // Example: 限制每1分钟调用一次
return interval < limitInterval;
}
private void updateAccess(String phone) {
accessMap.put(phone, System.currentTimeMillis());
}
}
package cn.com.poc.common.aspect;
import cn.com.poc.common.utils.JsonUtils;
import cn.com.yict.framemax.core.exception.BusinessException;
import cn.com.yict.framemax.core.utils.JSON;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
@Aspect
@Component
@Order(-10)
public class RestLoggingAspect {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Pointcut("execution(* *..rest..*Rest.*(..))")
public void restMethod() { // Do nothing
}
@Around("restMethod()")
public Object restMethodAround(ProceedingJoinPoint pjp) throws Throwable {
Date before = new Date();
Object retVal = null;
Object[] args = pjp.getArgs();
String requestPath = StringUtils.EMPTY;
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes sra = (ServletRequestAttributes) ra;
if (sra == null) {
return null;
}
HttpServletRequest request = sra.getRequest();
requestPath = request.getRequestURI();
//将controller入参中的 HttpServletRequest,HttpServletResponse类型参数剔除 不输出日志
List<Object> objects = new ArrayList<>(Arrays.asList(args));
objects.removeIf(next -> next instanceof HttpServletRequest || next instanceof HttpServletResponse);
String argJson = JSON.serialize(objects);
String className = pjp.getTarget().getClass().getSimpleName();
String methodName = pjp.getSignature().getName();
String remoteAddr = request.getRemoteAddr();
//避免上传图片将图片base64 字符打印
if (requestPath.toLowerCase().contains("upload")) {
logger.info("[Class:{}][Method:{}][Path:{}][Arguments:{}][Start]", className, methodName, requestPath, "upload images");
} else {
Map<String, String[]> parameterMap = request.getParameterMap();
if (parameterMap != null && parameterMap.size() > 0) {
logger.info("[Class:{}][Method:{}][Path:{}][RequestParams:{}][Arguments:{}][Start]", className, methodName, requestPath, JsonUtils.serialize(parameterMap), argJson);
} else {
logger.info("[Class:{}][Method:{}][Path:{}][Arguments:{}][Start]", className, methodName, requestPath, argJson);
}
}
try {
retVal = pjp.proceed();
} catch (BusinessException e) { // 业务层异常
logger.error("[Class:{}][Method:{}][Path:{}][BizException:{}-{}]", className, methodName, requestPath, e.getErrorCode(), e.getMessage());
throw e;
} catch (Throwable e) {// 系統异常
logger.error("[Class:{}][Method:{}][Path:{}][Exception:{}]", className, methodName, requestPath, e.getMessage());
throw e;
} finally {
try {
String printResponse = null;
if (retVal != null) {
printResponse = JsonUtils.serialize(retVal);
//返回数据过大,不打印
if (StringUtils.isNotBlank(printResponse) && printResponse.length() > 2048) {
printResponse = "返回数据过长,忽略输出";
}
}
logger.info("[Class:{}][Method:{}][Path:{}][results:{}][Interval:{}ms][End]", className, methodName, requestPath, printResponse,
System.currentTimeMillis() - before.getTime());
} catch (Exception e) {
logger.error("输出日志结果异常,忽略", e);
}
}
return retVal;
}
}
package cn.com.poc.common.aspect;
import cn.com.yict.framemax.core.exception.BusinessException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* @author Focan.Zhong
*/
@Aspect
@Component
public class ServiceLoggingAspect {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Pointcut(value = "execution(* *..service.*Service.*(..))")
public void serviceMethod() {
}
@Around("serviceMethod()")
public Object serviceMethodAround(ProceedingJoinPoint pjp) throws Throwable {
Date before = new Date();
String methodName = pjp.getSignature().getName();
Object object = pjp.getTarget();
Object retVal = null;
logger.info("[Class:{}][Method:{}][Start]", object.getClass(), methodName);
long interval = 0;
try {
retVal = pjp.proceed();
} catch (Throwable e) {
logException(methodName, object, e);
} finally {
Date after = new Date();
interval = after.getTime() - before.getTime();
logger.info("[Class:{}][Method:{}][Interval:{}ms][End]", object.getClass(), methodName, interval);
}
return retVal;
}
private void logException(String methodName, Object object, Throwable e) throws Throwable {
//业务层异常
if (e instanceof BusinessException) {
BusinessException be = (BusinessException) e;
logger.info("[Class:{}][Method:{}][BizException:{}-{}]", object.getClass(), methodName, be.getErrorCode(), be.getMessage());
//系統异常
} else {
logger.error("[Class:{}][Method:{}]Exception:{}", object.getClass(), methodName, e.getMessage());
}
throw e;
}
}
package cn.com.poc.common.constant;
/**
* @author Roger Wu
*/
public enum BizSnKeyEnum {
/**
* 渠道号
*/
channelConfigFlowNo("blo.marketing.channel.config","CCF"),
/**
* 订单编号
*/
paySn("blo.marketing.pay.payOrderSn","PS"),
/**
* 订单编号
*/
payLogSn("blo.marketing.pay.log.payLogSn","PL"),
;
/**
* redis key 前缀
*/
String redisKeyPrefix;
/**
* 生成标号前缀
*/
String snPrefix;
BizSnKeyEnum(String redisKeyPrefix, String snPrefix) {
this.redisKeyPrefix = redisKeyPrefix;
this.snPrefix = snPrefix;
}
public String getRedisKeyPrefix() {
return redisKeyPrefix;
}
public String getSnPrefix() {
return snPrefix;
}
}
package cn.com.poc.common.constant;
public enum BizSnRedisKeyEnum {
/**
* 订单编号
*/
channelConfigFlowNo("blo.marketing.channel.config","CCF"),
/**
* 订单编号
*/
payLogSn("blo.marketing.pay.log.payLogSn","PL"),
/**
* 订单编号
*/
paySn("blo.marketing.pay.paySn","PS"),
/**
* SKU
*/
sku("blo.product.sku.serialNumber", "PS"),
/**
* 商品编号
*/
product("blo.product.product.serialNumber", "P"),
/**
* 订单编号
*/
orderSn("blo.order.order.serialNumber","OS"),
/**
* 订单编号
*/
integralFlowNo("blo.user.integral.integralFlowNo","IF"),
/**
* 订单编号
*/
discountFlowNo("blo.user.disount.discountFlowNo","DF"),
/**
* 订单编号
*/
contentFlowNo("blo.content.contentFlowNo","CF"),
/**
* 出门单
*/
contentOutFlowNo("blo.content.out","CC"),
/**
* 游戏
*/
marketingGameFlowNo("blo.marketing.game","GF"),
/**
* 游戏奖励
*/
marketingGameAwardFlowNo("blo.marketing.game.award","GAF"),
/**
* 订单编号
*/
marketingGameRecordFlowNo("blo.marketing.game.record","GR"),
/**
* 场景值
*/
scenceCode("blo.common.scence.code","SC"),
;
/**
* redis key 前缀
*/
String redisKeyPrefix;
/**
* 生成标号前缀
*/
String snPrefix;
BizSnRedisKeyEnum(String redisKeyPrefix, String snPrefix) {
this.redisKeyPrefix = redisKeyPrefix;
this.snPrefix = snPrefix;
}
public String getRedisKeyPrefix() {
return redisKeyPrefix;
}
public String getSnPrefix() {
return snPrefix;
}
}
package cn.com.poc.common.constant;
/**
* @author alex.yao
* @date 2022/10/8
**/
public interface BizWechatDesignConstant {
/**
* slideShow : 长轮播 marquee: 文字轮播 indexPopupWindow: 弹窗 quickAccessArea:金刚区 resourceData:资源位
* //activityDisplayNum
* //articleDisplayNum
* //couponDisplayNum
* //isDisplaySignInIcon
* //isShowPopup
*/
interface type{
String slideShow = "slideShow";
String marquee = "marquee";
String indexPopupWindow = "indexPopupWindow";
String quickAccessArea = "quickAccessArea";
String resourceData = "resourceData";
String activityDisplayNum = "activityDisplayNum";
String articleDisplayNum = "articleDisplayNum";
String couponDisplayNum = "couponDisplayNum";
String isDisplaySignInIcon = "isDisplaySignInIcon";
String isShowPopup = "isShowPopup";
String gameType = "gameType";
String other = "other";
}
}
package cn.com.poc.common.constant;
/**
* @author Focan Zhong
* @create 2021/7/2
*/
public interface BloAppVersionConstant {
public class UpdateModel {
public static String wgt = "Wgt";
public static String installPackage = "Package";
}
public class Platform {
public static String ios = "ios";
public static String android = "android";
}
}
\ No newline at end of file
package cn.com.poc.common.constant;
public class ChangedLogConstant {
public enum ChangedLogEnum{
APPLICATION_ADD(BUSINESS_TYPE.APPLICATION,BUSINESS_DETAIL_TYPE.APPLICATION_ADD,REMARK.APPLICATION_ADD),
APPLICATION_AUDITED(BUSINESS_TYPE.APPLICATION,BUSINESS_DETAIL_TYPE.APPLICATION_AUDITED,REMARK.APPLICATION_AUDITED),
APPLICATION_CONFIRM(BUSINESS_TYPE.APPLICATION,BUSINESS_DETAIL_TYPE.APPLICATION_CONFIRM,REMARK.APPLICATION_CONFIRM),
APPLICATION_COMPLETED(BUSINESS_TYPE.APPLICATION,BUSINESS_DETAIL_TYPE.APPLICATION_COMPLETED,REMARK.APPLICATION_COMPLETED),
APPLICATION_REJECT(BUSINESS_TYPE.APPLICATION,BUSINESS_DETAIL_TYPE.APPLICATION_REJECT,REMARK.APPLICATION_REJECT);
private String businessType;
private String businessDetailType;
private String remark;
public String getBusinessDetailType() {
return businessDetailType;
}
public void setBusinessDetailType(String businessDetailType) {
this.businessDetailType = businessDetailType;
}
public String getBusinessType() {
return businessType;
}
public void setBusinessType(String businessType) {
this.businessType = businessType;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
ChangedLogEnum(String businessType, String businessDetailType, String remark) {
this.businessType = businessType;
this.businessDetailType = businessDetailType;
this.remark = remark;
}
}
public class BUSINESS_DETAIL_TYPE {
public static final String CALL_CENTER = "CallCenter";
public static final String RECALL = "Recall";
public static final String LOST_ADD = "LostAdd";
public static final String LOST_CHANGED = "LostChanged";
public static final String APPLICATION_ADD = "ApplicationAdd";
public static final String APPLICATION_AUDITED = "ApplicationAudited";
public static final String APPLICATION_REJECT = "ApplicationReject";
public static final String APPLICATION_COMPLETED = "ApplicationCompleted";
public static final String APPLICATION_CONFIRM = "ApplicationComfirm";
public static final String USER_RECEIVE = "UserReceive";
public static final String USER_STORE_RECEIVE = "UserStoreReceive";
}
public class REMARK{
public static final String APPLICATION_ADD = "创建申请单";
public static final String APPLICATION_AUDITED = "通过申请单";
public static final String APPLICATION_REJECT = "拒绝申请单";
public static final String APPLICATION_COMPLETED = "放行申请单";
public static final String APPLICATION_CONFIRM = "确认申请单";
}
public class BUSINESS_TYPE {
public static final String LOST = "Lost";
public static final String APPLICATION = "Application";
}
}
package cn.com.poc.common.constant;
/**
* @author Focan.Zhong
*/
public interface CommonConstant {
/**
* 是否删除 Y-是 N-否
*/
interface IsDeleted {
String Y = "Y";
String N = "N";
}
/**
* 使用中 使用中,0:默认,非使用中|1:使用中
*/
interface IsUsed {
/**
* 使用中
*/
Integer Y = 0;
/**
* 未使用
*/
Integer N = 1;
}
/**
*
*/
interface YOrN {
String Y = "Y";
String N = "N";
}
/**
*
*/
interface SYSTEM_FIELD {
String SYSTEM = "SYSTEM";
}
int ZERO = 0;
}
package cn.com.poc.common.constant;
/**
* @author Roger Wu
*/
public interface FmxParamConfigConstant {
//token过期时间配置
String TOKEN_EXPIRED_HOURS = "login.tokenExpiredHours";
interface Prefix {
/**
* 营销工具中台
*/
public static final String DG_TOOLS = "dg.tools.project";
}
/**
* 营销中台
*/
interface Dgtools {
/**
* 项目key
*/
public static final String PROJECT_KEY ="dg.tools.project.key";
/**
* 项目密钥
*/
public static final String PROJECT_SECRET ="dg.tools.project.secret";
/**
* 加密私钥
*/
public static final String PRIVATE_KEY ="dg.tools.project.private.key";
/**
* 加密偏移量
*/
public static final String VI ="dg.tools.project.vi";
}
/**
* String TOKEN_EXPIRED_HOURS = "login.tokenExpiredHours";
* <p>
* <p>
* /**
* 小程序设计轮播图、文字轮播配置
*/
interface Design {
String PREFIX = "mp.design.config.list";
//跑马灯
String MARQUEE = "marquee";
//轮播图
String SLIDE_SHOW = "slideshow";
//content-detail
String CONTENT_DETAIL = "content-detail";
//jumpType
String JUMP_TYPE = "jumpType";
//jumpQuery
String JUMP_QUERY = "jumpQuery";
//contentId
String CONTENT_ID = "contentId";
}
}
package cn.com.poc.common.constant;
/**
* @author Helen
* @date 2021/12/20 10:50
*/
public interface FormReportingConstant {
/**
* 报表类型
*/
interface REPORT_TYPE {
/**
* 兑换记录
*/
public String EXCHANGE_LOG = "exchangeLog";
/**
* 积分兑换
*/
public String INTERNAL_EXCHANGE = "internalExchange";
/**
* 会员
*/
public String MEMBER = "member";
/**
* 员工
*/
public String STAFF = "staff";
/**
* vip预约
*/
public String RESERVATION = "vipReservation";
/**
* 员工排版
*/
public String STAFF_CLASSES = "staffClasses";
/**
* 公告
*/
public String NOTICE = "notice";
/**
* 店铺
*/
public String STORE = "store";
/**
* 店铺员工打卡
*/
public String STAFF_CLOCK_DATA = "staffClockData";
//申请管理
/**
* 出门申请
*/
public String OUT_APPLY = "Out";
/**
* 活动申请
*/
public String ACTIVITY_APPLY = "Activity";
/**
* 加班申请
*/
public String OT_APPLY = "Ot";
/**
* 广播申请
*/
public String BROADCAST_APPLY = "Broadcast";
//营业额管理
/**
* 营业额审批
*/
public String SALE_DATA = "SaleData";
/**
* 营业数据
*/
public String BUSINESS_DATA = "businessData";
/**
* 问卷活动报表
*/
public String MARKETING_GAME_ACTIVITY = "marketingGameActivity";
//束流数据
/**
* 客流数据
*/
public String CUSTOMER_FLOW = "customerFlow";
/**
* 活动数据
*/
public String ORDER_DATA = "orderData";
/**
* B端投票活动候选人名单
*/
public String B_PORT_CANDIDATE_LIST = "bPortCandidateList";
}
interface EXCEL_CONFIG {
public int COLUMN_WIDTH = 5000;
}
}
package cn.com.poc.common.constant;
/**
* 第三方登录渠道
**/
public enum Member3ptLoginChannel {
/**
* 微信小程序
*/
wx_mini,
/**
* 公众号
*/
wx_pub,
/**
* 手机验证码
*/
app_verification_code,
/**
* 密码登录
*/
app_password,
ibt,
;
}
package cn.com.poc.common.constant;
/**
* 第三方注册渠道
*
* @author Focan.Zhong
*/
public enum Member3ptRegisterChannel {
/**
* 微信小程序 (百联)
*/
bl_wx_mini,
/**
* 手机号 (百联)
*/
bl_mobile,
;
}
package cn.com.poc.common.constant;
public interface MkpRedisKeyConstant {
/**
* 刷新 公众号网页授权accessToken 令牌
*/
String pub_refresh_token = "pub_refresh_token";
/**
* 接口调用凭证
* access_token:[appId]
*/
String ACCESS_TOKEN = "access_token";
/**
* 会员调用凭证
* member_token:[会员id]
*/
String MEMBER_TOKEN = "member_token";
/**
* 订单过期
*/
String ACTIVITY_EXPIRED = "activity_expired";
/**
* 付款订单过期
*/
String PRE_PAY_ORDER_EXPIRED = "pre_pay_order_expired";
/**
* 营销中台apptoken
*/
String DGTOOLS_APP_TOKEN = "dgtools_app_token";
/**
* 佣金收入
*/
String BROKERAGE_INCOME = "brokerage-income";
/**
* AIGC活动奖励个数限制
*/
String AIGC_ACTIVITY_AWARD = "aigc_activity_award";
}
\ No newline at end of file
package cn.com.poc.common.constant;
public class NotificationConstants {
public interface BUSINESS_TYPE {
/**
* 公告
*/
public static final String NOTICE = "Notice";
}
}
\ No newline at end of file
package cn.com.poc.common.constant;
/**
* OCR常量
*
* @author Focan.Zhong
*/
public interface OcrConstant {
/**
* 第三方ocr渠道
*/
enum Channel {
/**
* 百度
*/
baidu,
;
}
}
package cn.com.poc.common.constant;
/**
* @author Helen
* @date 2021/12/2 14:55
*/
public interface RedisConstant {
String CALLBACK_KEY_PREFIX = "CALLBACK_KEY";
String CALLBACK_KEY_INTERVAL = "-";
interface CALLBACK_KEY_TYPE {
String COUPON_EXPIRED = "COUPON_EXPIRED";
String ACTIVITY_END = "ACTIVITY_END";
}
/**
* redis key过期提前量
*/
long CALLBACK_KEY_EXPIRED_IN_ADVANCE = 2l;
}
package cn.com.poc.common.constant;
/**
*
*/
public interface RedisKeyConstant {
public class Code{
/**
* 验证码授权码
*/
public final static String AUTH_CODE = "auth_code:";
}
}
\ No newline at end of file
package cn.com.poc.common.constant;
public interface TemplateMessageConstant {
public class status{
//草稿
public static final String PENDING = "Pending";
//已发送
public static final String SENDED = "Sended";
}
}
package cn.com.poc.common.constant.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
/**
* @author Helen
* @date 2021/12/2 16:24
*/
@Configuration
public class RedisConfig {
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
return container;
}
}
\ No newline at end of file
package cn.com.poc.common.domain;
import java.io.Serializable;
/**
* 微信请求状态数据
*/
public class BaseResult implements Serializable {
private static final String SUCCESS_CODE = "0";
private String errcode;
private String errmsg;
public BaseResult() {
}
public BaseResult(String errcode, String errmsg) {
this.errcode = errcode;
this.errmsg = errmsg;
}
public String getErrcode() {
return errcode;
}
public void setErrcode(String errcode) {
this.errcode = errcode;
}
public String getErrmsg() {
return errmsg;
}
public void setErrmsg(String errmsg) {
this.errmsg = errmsg;
}
public boolean isSuccess() {
return errcode == null || "".equals(errcode) || errcode.equals(SUCCESS_CODE);
}
}
package cn.com.poc.common.domain;
import javax.xml.bind.annotation.XmlTransient;
public abstract class MchBase {
protected String return_code;
protected String return_msg;
protected String appid;
protected String mch_id;
protected String nonce_str;
protected String sign;
protected String sign_type;
protected String result_code;
protected String err_code;
protected String err_code_des;
/**
* @since 2.8.5
*/
protected String sub_appid;
/**
* @since 2.8.5
*/
protected String sub_mch_id;
@XmlTransient
protected Boolean sign_status;
public String getReturn_code() {
return return_code;
}
public void setReturn_code(String return_code) {
this.return_code = return_code;
}
public String getReturn_msg() {
return return_msg;
}
public void setReturn_msg(String return_msg) {
this.return_msg = return_msg;
}
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getMch_id() {
return mch_id;
}
public void setMch_id(String mch_id) {
this.mch_id = mch_id;
}
public String getNonce_str() {
return nonce_str;
}
public void setNonce_str(String nonce_str) {
this.nonce_str = nonce_str;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getResult_code() {
return result_code;
}
public void setResult_code(String result_code) {
this.result_code = result_code;
}
public String getErr_code() {
return err_code;
}
public void setErr_code(String err_code) {
this.err_code = err_code;
}
public String getErr_code_des() {
return err_code_des;
}
public void setErr_code_des(String err_code_des) {
this.err_code_des = err_code_des;
}
public String getSub_appid() {
return sub_appid;
}
public void setSub_appid(String sub_appid) {
this.sub_appid = sub_appid;
}
public String getSub_mch_id() {
return sub_mch_id;
}
public void setSub_mch_id(String sub_mch_id) {
this.sub_mch_id = sub_mch_id;
}
public String getSign_type() {
return sign_type;
}
public Boolean getSign_status() {
return sign_status;
}
public void setSign_status(Boolean sign_status) {
this.sign_status = sign_status;
}
public void setSign_type(String sign_type) {
this.sign_type = sign_type;
}
}
package cn.com.poc.common.dto;
import cn.com.poc.support.sms.constant.SmsConstant;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.io.Serializable;
/**
* @author Focan.Zhong
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class SmsDto implements Serializable {
private SmsConstant.Channel channel;
/**
* 手机号
*/
private String mobilePhone;
/**
* 手机验证码
*/
private String smsCode;
//验证码请求体
/**
* verifyCodeType String 是 短信验证码类型(必传)
* * 1.发送快捷登录或注册短信,
* * 2.发送语音短信,
* * 4.重置密码发送短信,
* * 5.风控发送短信
* verifyImgType String 是 图形、滑块验证类型(必传) 2.图形验证码,3.滑块验证
* verifyImgCode String 否 图形验证码(verifyImgType=2时必填)
* uniqueFlag String 是 滑块唯一标识(verifyImgType=3时必填)
* xPercent String 是 滑块横坐标所占比例 (verifyImgType=3时必填) @mock=1
*/
private String verifyCodeType;
private String verifyImgType;
private String verifyImgCode;
private String uniqueFlag;
private String xPercent;
/**
* 滑块开关
*/
private String captchaSwitch;
/**
* 滑块大图
*/
private String oriCopyImages;
/**
* 滑块图
*/
private String slideImages;
public SmsConstant.Channel getChannel() {
return channel;
}
public void setChannel(SmsConstant.Channel channel) {
this.channel = channel;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getSmsCode() {
return smsCode;
}
public void setSmsCode(String smsCode) {
this.smsCode = smsCode;
}
public String getVerifyCodeType() {
return verifyCodeType;
}
public void setVerifyCodeType(String verifyCodeType) {
this.verifyCodeType = verifyCodeType;
}
public String getVerifyImgType() {
return verifyImgType;
}
public void setVerifyImgType(String verifyImgType) {
this.verifyImgType = verifyImgType;
}
public String getVerifyImgCode() {
return verifyImgCode;
}
public void setVerifyImgCode(String verifyImgCode) {
this.verifyImgCode = verifyImgCode;
}
public String getUniqueFlag() {
return uniqueFlag;
}
public void setUniqueFlag(String uniqueFlag) {
this.uniqueFlag = uniqueFlag;
}
public String getxPercent() {
return xPercent;
}
public void setxPercent(String xPercent) {
this.xPercent = xPercent;
}
public String getCaptchaSwitch() {
return captchaSwitch;
}
public void setCaptchaSwitch(String captchaSwitch) {
this.captchaSwitch = captchaSwitch;
}
public String getOriCopyImages() {
return oriCopyImages;
}
public void setOriCopyImages(String oriCopyImages) {
this.oriCopyImages = oriCopyImages;
}
public String getSlideImages() {
return slideImages;
}
public void setSlideImages(String slideImages) {
this.slideImages = slideImages;
}
}
package cn.com.poc.common.dto;
public class SysErrorMessageDto {
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
package cn.com.poc.common.entity;
import java.util.List;
/**
* @author alex.yao
* @date 2024/1/8
**/
public class BatchInsertResult {
private String insertSQL;
private List<Object[]> insertParams;
public String getInsertSQL() {
return insertSQL;
}
public void setInsertSQL(String insertSQL) {
this.insertSQL = insertSQL;
}
public List<Object[]> getInsertParams() {
return insertParams;
}
public void setInsertParams(List<Object[]> insertParams) {
this.insertParams = insertParams;
}
}
package cn.com.poc.common.entity.media;
import cn.com.poc.common.domain.BaseResult;
public class Media extends BaseResult {
private String type;
private String media_id;
private Long created_at;
private String url;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMedia_id() {
return media_id;
}
public void setMedia_id(String mediaId) {
media_id = mediaId;
}
public Long getCreated_at() {
return created_at;
}
public void setCreated_at(Long createdAt) {
created_at = createdAt;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
package cn.com.poc.common.entity.media;
import cn.com.poc.common.domain.BaseResult;
public class MediaGetResult extends BaseResult {
private String filename;
private String contentType;
private byte[] bytes;
private String video_url; //如果返回的是视频消息素材
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public byte[] getBytes() {
return bytes;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
public String getVideo_url() {
return video_url;
}
public void setVideo_url(String video_url) {
this.video_url = video_url;
}
}
package cn.com.poc.common.entity.media;
public enum MediaType{
image {
@Override
public String fileSuffix() {
return "jpg";
}
@Override
public String uploadType() {
return "image";
}
},voice_mp3 {
@Override
public String fileSuffix() {
return "mp3";
}
@Override
public String uploadType() {
return "voice";
}
},voice_amr {
@Override
public String fileSuffix() {
return "amr";
}
@Override
public String uploadType() {
return "voice";
}
},video {
@Override
public String fileSuffix() {
return "mp4";
}
@Override
public String uploadType() {
return "video";
}
},thumb {
@Override
public String fileSuffix() {
return "jpg";
}
@Override
public String uploadType() {
return "thumb";
}
},file {
@Override
public String fileSuffix() {
return "";
}
@Override
public String uploadType() {
return "file";
}
};
public abstract String fileSuffix();
/**
* 上传类型
* @return uploadType
*/
public abstract String uploadType();
}
package cn.com.poc.common.entity.media;
import cn.com.poc.common.domain.BaseResult;
public class UploadimgResult extends BaseResult {
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
package cn.com.poc.common.entity.oss;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Simon.Liu on 2017/12/8.
*/
public class ImageUrl implements Serializable {
private List<String> imageUrls = new ArrayList<>();
private String htmlStr;
private String scene;
public String getScene() {
return scene;
}
public void setScene(String scene) {
this.scene = scene;
}
public List<String> getImageUrls() {
return imageUrls;
}
public void setImageUrls(List<String> imageUrls) {
this.imageUrls = imageUrls;
}
public String getHtmlStr() {
return htmlStr;
}
public void setHtmlStr(String htmlStr) {
this.htmlStr = htmlStr;
}
}
package cn.com.poc.common.handler;
import cn.com.yict.framemax.core.exception.BusinessException;
import cn.com.yict.framemax.core.exception.ErrorCoded;
import cn.com.yict.framemax.core.spring.rest.RestServiceRegistration;
import cn.com.yict.framemax.core.utils.BeanUtils;
import cn.com.yict.framemax.data.exception.ValidationException;
import cn.com.yict.framemax.security.oauth.OauthAccesstokenFilter;
import cn.com.yict.framemax.security.oauth.exception.TokenExpiredException;
import cn.com.yict.framemax.web.utils.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.PriorityOrdered;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
* 统一异常处理器
*
* @author Focan Zhong
* @create 2021/8/7
* <p>
* 框架统一异常处理器
* @see cn.com.yict.framemax.core.spring.rest.RestHandlerExceptionResolver
*/
public class RestHandlerExceptionResolver implements HandlerExceptionResolver, PriorityOrdered {
private int order = -10;
private Map<Integer, String> statusCodeMap = new HashMap<Integer, String>() {
private static final long serialVersionUID = 1L;
{
this.put(HttpServletResponse.SC_UNAUTHORIZED,
"NoneLoginException,AuthenticationException");
}
};
private int statusCode = HttpServletResponse.SC_OK;
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
if (!RestServiceRegistration.isRestHandler(handler)) {
return null;
}
Throwable throwable = ex;
if (ex.getCause() != null) {
throwable = ex.getCause();
}
String simpleName = ',' + throwable.getClass().getSimpleName();
String name = ',' + throwable.getClass().getName();
int sc = statusCode;
for (Map.Entry<Integer, String> entry : statusCodeMap.entrySet()) {
String source = ',' + entry.getValue();
if (source.contains(simpleName) || source.contains(name)) {
sc = entry.getKey();
break;
}
}
request.setAttribute(cn.com.yict.framemax.core.spring.rest.RestHandlerExceptionResolver.class.getName(), throwable.getMessage());
return new ModelAndView(new RestExceptionView(throwable, sc));
}
public static class RestExceptionView implements View {
/**
* Log variable for all child classes.
*/
protected final Logger log = LoggerFactory.getLogger(this.getClass());
private Throwable ex;
private int statusCode;
public RestExceptionView(Throwable ex) {
this(ex, HttpServletResponse.SC_OK);
}
public RestExceptionView(Throwable ex, int statusCode) {
this.ex = ex;
this.statusCode = statusCode;
}
@Override
public String getContentType() {
return "application/json;charset=utf-8";
}
@Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
map.put("code", -1);
map.put("message", BeanUtils.ifnull(ex.getMessage(), ex.toString()));
if (ex instanceof ValidationException) {
ValidationException ve = (ValidationException) ex;
map.put("errors", ve.getErrors());
}
if (ex instanceof ErrorCoded) {
ErrorCoded eec = (ErrorCoded) ex;
map.put("code", eec.getErrorCode());
}
if (ex instanceof TokenExpiredException) {
map.put("code", OauthAccesstokenFilter.USERNAME_PWD_ERROR_CODE);
}
if (ex instanceof BusinessException) {
map.put("message", "业务异常:[" + ex.getMessage() + "]");
}
if (ex instanceof IllegalArgumentException) {
map.put("message", "参数异常:[" + ex.getMessage() + "]");
}
/*
* if (ex instanceof NoneLoginException || ex instanceof
* AuthenticationException) {
* response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); }else{
* response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
* }
*/
response.setStatus(statusCode);
HttpUtils.outJson(map, request, response);
if (ex instanceof BusinessException) {
log.error("业务异常:", ex);
return;
}
if (ex instanceof IllegalArgumentException) {
//若出现:Name for argument type [java.lang.String] not available, and parameter name information not found in class file either.
//请检查url带参时 @RequestParam注解是否给name值
log.error("参数异常:", ex);
return;
}
if (ex instanceof TokenExpiredException) {
log.error("Token异常:", ex);
return;
}
log.error("系统异常:", ex);
}
}
@Override
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
public void setStatusCodeMap(Map<Integer, String> statusCodeMap) {
if (statusCodeMap != null) {
this.statusCodeMap.putAll(statusCodeMap);
}
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
}
package cn.com.poc.common.interceptor;
import cn.com.poc.thirdparty.resource.demand.auth.service.BizProjectService;
import cn.com.yict.framemax.core.spring.mvc.MvcHandlerInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class AuthenticationInterceptor implements MvcHandlerInterceptor {
private final Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);
@Resource
private BizProjectService bizProjectService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
logger.info("request请求地址path[{}] uri[{}]", request.getServletPath(), request.getRequestURI());
// 直接放行获取Token
// String token = request.getHeader("x-request-token");
// if (StringUtils.isBlank(token)) {
// return true;
// }
// if (RunEnv.dev.equals(Config.getRunEnv())) {
// return true;
// }
//
// String headerTimestamp = request.getHeader("timestamp");
// String headerSign = request.getHeader("x-request-sign");
// if (StringUtils.isBlank(headerSign) && StringUtils.isBlank(headerTimestamp)) {
// throw new BusinessException("Missing parameters in request header");
// }
//
// //计算签名
// UserBaseEntity currentUser = BlContext.getCurrentUser();
// String appKey = currentUser.getUserAccount();
// BizProjectEntity bizProjectEntity = bizProjectService.getSecretByAppKey(appKey);
// SignUtil.signVerification(headerSign, bizProjectEntity.getAppSecret(), headerTimestamp, request.getRequestURI());
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
}
package cn.com.poc.common.interceptor;
import cn.com.yict.framemax.core.spring.mvc.MvcHandlerInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
/**
* @author Focan Zhong
* @create 2021/8/7
*/
public class TraceInterceptor implements MvcHandlerInterceptor {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final String LOG_KEY = "log_trace_id";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
//生成日志追踪id
try {
String traceId = UUID.randomUUID().toString().replaceAll("-", "");
MDC.put(LOG_KEY, traceId);
response.setHeader("TraceId", traceId);
} catch (Exception e) {
logger.error("生成日志追踪id异常:" + e.getMessage(), e);
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, Exception e) throws Exception {
MDC.remove(LOG_KEY);
}
}
\ No newline at end of file
package cn.com.poc.common.listener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
/**
* @author Helen
* @date 2021/11/12 14:46
*/
public class RedisKeyExpiredListener extends KeyExpirationEventMessageListener {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public RedisKeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer);
}
@Override
public void onMessage(Message message, byte[] pattern) {
}
}
package cn.com.poc.common.model;
import java.io.Serializable;
import cn.com.yict.framemax.data.model.BaseModelClass;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import javax.persistence.Version;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
/**
* Model class for sys_error_log
*
*/
@Entity
@Table(name = "sys_error_log")
@DynamicInsert
@DynamicUpdate
public class SysErrorLogModel extends BaseModelClass implements Serializable {
private static final long serialVersionUID = 1L;
/** id
*
*/
private java.lang.Integer id;
@Column(name = "id",length = 10)
@Id @GeneratedValue(strategy = GenerationType.AUTO)
public java.lang.Integer getId(){
return this.id;
}
public void setId(java.lang.Integer id){
this.id = id;
super.addValidField("id");
}
/** error_message
*
*/
private java.lang.String errorMessage;
@Column(name = "error_message",length = 1073741824)
public java.lang.String getErrorMessage(){
return this.errorMessage;
}
public void setErrorMessage(java.lang.String errorMessage){
this.errorMessage = errorMessage;
super.addValidField("errorMessage");
}
/** CREATOR
*创建人
*/
private java.lang.String creator;
@Column(name = "CREATOR",length = 225)
public java.lang.String getCreator(){
return this.creator;
}
public void setCreator(java.lang.String creator){
this.creator = creator;
super.addValidField("creator");
}
/** CREATED_TIME
*创建时间
*/
private java.util.Date createdTime;
@Column(name = "CREATED_TIME",length = 19)
public java.util.Date getCreatedTime(){
return this.createdTime;
}
public void setCreatedTime(java.util.Date createdTime){
this.createdTime = createdTime;
super.addValidField("createdTime");
}
/** MODIFIER
*修改人
*/
private java.lang.String modifier;
@Column(name = "MODIFIER",length = 225)
public java.lang.String getModifier(){
return this.modifier;
}
public void setModifier(java.lang.String modifier){
this.modifier = modifier;
super.addValidField("modifier");
}
/** MODIFIED_TIME
*修改时间
*/
private java.util.Date modifiedTime;
@Column(name = "MODIFIED_TIME",length = 19)
public java.util.Date getModifiedTime(){
return this.modifiedTime;
}
public void setModifiedTime(java.util.Date modifiedTime){
this.modifiedTime = modifiedTime;
super.addValidField("modifiedTime");
}
/** SYS_VERSION
*乐观锁,版本号
*/
private java.lang.Integer sysVersion;
@Column(name = "SYS_VERSION",length = 10)
@Version
public java.lang.Integer getSysVersion(){
return this.sysVersion;
}
public void setSysVersion(java.lang.Integer sysVersion){
this.sysVersion = sysVersion;
super.addValidField("sysVersion");
}
}
\ No newline at end of file
package cn.com.poc.common.pool;
import cn.com.yict.framemax.core.exception.BusinessException;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
/**
* Communication 线程池
*/
public class CommunicationThreadPoolExecutor {
final private static String THREAD_POOL_NAME = "CommunicationThreadExecutor";
final private static int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors();
final private static int MAXIMUM_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 5;
final private static int KEEP_ALIVE_TIME = 60;
final private static LinkedBlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<>(CORE_POOL_SIZE * 2);
final private static ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder().setNameFormat(THREAD_POOL_NAME + "-%d").setDaemon(false).build();
private static ThreadPoolExecutor THREAD_POOL_EXECUTOR;
static {
initThreadPool();
}
private static void initThreadPool() {
THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, java.util.concurrent.TimeUnit.SECONDS, WORK_QUEUE, THREAD_FACTORY, new ThreadPoolExecutor.CallerRunsPolicy());
}
public static void addTask(Runnable task) {
try {
THREAD_POOL_EXECUTOR.execute(task);
} catch (Exception e) {
throw new BusinessException("当前任务过多,请稍后重试");
}
}
}
package cn.com.poc.common.pool;
import cn.com.yict.framemax.core.exception.BusinessException;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
/**
* SpeechToText 线程池
*/
public class SpeechToTextThreadPoolExecutor {
final private static String THREAD_POOL_NAME = "SpeechToTextThreadExecutor";
final private static int CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors();
final private static int MAXIMUM_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 5;
final private static int KEEP_ALIVE_TIME = 30;
final private static LinkedBlockingQueue<Runnable> WORK_QUEUE = new LinkedBlockingQueue<>(CORE_POOL_SIZE * 2);
final private static ThreadFactory THREAD_FACTORY = new ThreadFactoryBuilder().setNameFormat(THREAD_POOL_NAME + "-%d").setDaemon(false).build();
private static ThreadPoolExecutor THREAD_POOL_EXECUTOR;
static {
initThreadPool();
}
private static void initThreadPool() {
THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, java.util.concurrent.TimeUnit.SECONDS, WORK_QUEUE, THREAD_FACTORY, new ThreadPoolExecutor.CallerRunsPolicy());
}
public static void addTask(Runnable task) {
try {
THREAD_POOL_EXECUTOR.execute(task);
} catch (Exception e) {
throw new BusinessException("当前任务过多,请稍后重试");
}
}
}
package cn.com.poc.common.repository;
import cn.com.yict.framemax.data.repository.Repository;
import cn.com.poc.common.model.SysErrorLogModel;
public interface SysErrorLogRepository extends Repository<SysErrorLogModel,java.lang.Integer> {
}
\ No newline at end of file
package cn.com.poc.common.rest;
import cn.com.yict.framemax.core.rest.BaseRest;
import cn.com.yict.framemax.web.permission.Access;
import cn.com.yict.framemax.web.permission.Permission;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@Permission(Access.Safety)
public interface BosRest extends BaseRest {
/**
* 文件上传
*
* @param file 文件
* @return
*/
String upload(@RequestParam MultipartFile file) throws IOException;
}
package cn.com.poc.common.rest;
import cn.com.yict.framemax.core.exception.BusinessException;
import cn.com.yict.framemax.core.rest.BaseRest;
import cn.com.yict.framemax.web.permission.Access;
import cn.com.yict.framemax.web.permission.Permission;
import org.springframework.web.bind.annotation.RequestParam;
@Permission(Access.Anonymous)
public interface JudgeCodeRest extends BaseRest {
/**
* 校验验证码是否正确
*
* @param account,code
* @throws Exception
*/
boolean judgeCode(@RequestParam String account, @RequestParam String code) throws BusinessException;
/**
* 校验验证码是否正确,正确的话就返回授权码,可以给别的业务操作
*
* @param account,code
* @throws Exception
*/
String judgeCodeReturnAuthCode(@RequestParam String account, @RequestParam String code) throws BusinessException;
}
package cn.com.poc.common.rest;
import cn.com.yict.framemax.core.rest.BaseRest;
import cn.com.yict.framemax.web.permission.Access;
import cn.com.yict.framemax.web.permission.Permission;
import org.springframework.web.bind.annotation.RequestParam;
@Permission(Access.Anonymous)
public interface SendEmailRest extends BaseRest {
/**
* 发送邮件 验证码发送
* @param emailAddress
* @throws Exception
* */
void sendEmailCode(@RequestParam String emailAddress) throws Exception;
}
package cn.com.poc.common.rest;
import cn.com.yict.framemax.core.rest.BaseRest;
import cn.com.yict.framemax.web.permission.Access;
import cn.com.yict.framemax.web.permission.Permission;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @author jennie.chen
* @date 2024/7/22
**/
@Permission(Access.Anonymous)
public interface SmsRest extends BaseRest{
/**
* 短信下发(获取验证码)
*
* @param phone
* @throws Exception
*/
void smsDelivered(@RequestParam String phone) throws Exception;
}
package cn.com.poc.common.rest;
import cn.com.poc.common.dto.SysErrorMessageDto;
import cn.com.yict.framemax.core.rest.BaseRest;
import cn.com.yict.framemax.web.permission.Access;
import cn.com.yict.framemax.web.permission.Permission;
import org.springframework.web.bind.annotation.RequestBody;
@Permission(Access.Anonymous)
public interface SysErrorRest extends BaseRest {
void report(@RequestBody SysErrorMessageDto dto) throws Exception;
}
package cn.com.poc.common.rest.impl;
import cn.com.poc.common.rest.BosRest;
import cn.com.poc.common.service.BosConfigService;
import cn.com.poc.common.utils.Assert;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
@Component
public class BosRestImpl implements BosRest {
@Resource
private BosConfigService bosConfigService;
@Override
public String upload(MultipartFile file) throws IOException {
Assert.notNull(file, "文件不能为空");
String contentType = file.getContentType();
String originalFilename = file.getOriginalFilename();
String prefix = originalFilename.substring(originalFilename.lastIndexOf(".")).replaceAll("\\.", "");
return bosConfigService.upload(file.getInputStream(), prefix, contentType);
}
}
package cn.com.poc.common.rest.impl;
import cn.com.poc.common.service.JudgeCodeService;
import cn.com.poc.common.utils.Assert;
import cn.com.poc.common.rest.JudgeCodeRest;
import cn.com.yict.framemax.core.exception.BusinessException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class JudgeCodeRestImpl implements JudgeCodeRest {
@Resource
private JudgeCodeService judgeCodeService;
@Override
public boolean judgeCode(String account, String code) throws BusinessException {
Assert.notBlank(account, "用户登录,登录账号不能为空");
Assert.notBlank(code, "验证码不能为空");
return judgeCodeService.judgeCode(account, code);
}
@Override
public String judgeCodeReturnAuthCode(String account, String code) throws BusinessException {
Assert.notBlank(account, "用户登录,登录账号不能为空");
Assert.notBlank(code, "验证码不能为空");
return judgeCodeService.judgeCodeReturnAuthCode(account, code);
}
}
package cn.com.poc.common.rest.impl;
import cn.com.poc.common.rest.SendEmailRest;
import cn.com.poc.common.service.SendEmailService;
import cn.com.poc.common.utils.Assert;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
public class SendEmailRestImpl implements SendEmailRest {
@Resource
private SendEmailService sendEmailService;
@Override
public void sendEmailCode(String emailAddress) throws Exception {
Assert.notBlank(emailAddress, "用户登录,登录账号不能为空");
sendEmailService.sendEmailCode(emailAddress);
}
}
package cn.com.poc.common.rest.impl;
import cn.com.poc.common.rest.SmsRest;
import cn.com.poc.common.service.SmsService;
import cn.com.poc.common.utils.Assert;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.regex.Pattern;
@Component
public class SmsRestImpl implements SmsRest {
@Resource
private SmsService smsService;
/**
* 短信下发(百度SMS)
*
* @param phone
* @throws Exception
*/
@Override
public void smsDelivered(String phone) throws Exception {
Assert.notBlank(phone, "用户登录,登录账号不能为空");
//校验手机号格式(其中包含大陆和港澳台的校验)
//正则表达式使用了多个正则模式,每个模式使用|分隔,表示多个模式中的任何一个匹配即可。这样,它可以用于校验多种手机号的格式
boolean matches = Pattern.matches(
"(?:0|86|\\+86)?1[3-9]\\d{9}|" + //移动电话MOBILE
"(?:0|852|\\+852)?\\d{8}|" + //MOBILE_HK
"(?:0|886|\\+886)?(?:|-)09\\d{8}|" + //MOBILE_TW
"(?:0|853|\\+853)?(?:|-)6\\d{7}", phone); //MOBILE_MO
Assert.isTrue(matches, "手机号格式错误!请重试!");
smsService.smsDelivered(phone);
}
}
package cn.com.poc.common.rest.impl;
import cn.com.poc.common.dto.SysErrorMessageDto;
import cn.com.poc.common.model.SysErrorLogModel;
import cn.com.poc.common.rest.SysErrorRest;
import cn.com.poc.common.service.SysErrorLogService;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
public class SysErrorRestImpl implements SysErrorRest {
@Resource
private SysErrorLogService service;
@Override
public void report(SysErrorMessageDto dto) throws Exception {
SysErrorLogModel sysErrorLogModel = new SysErrorLogModel();
sysErrorLogModel.setErrorMessage(dto.getErrorMessage());
service.save(sysErrorLogModel);
}
}
package cn.com.poc.common.service;
import cn.com.yict.framemax.core.service.BaseService;
import java.io.IOException;
import java.io.InputStream;
public interface BosConfigService extends BaseService {
String uploadFileByByteArray2Oss(byte[] decodedByte, String uploadFolder, String fileName, String fileType) throws IOException;
String uploadFileByByteArray2Oss(byte[] decodedByte, String fileName, String fileType) throws IOException;
String upload(InputStream inputStream,String fileType,String contentType) throws IOException;
}
package cn.com.poc.common.service;
import cn.com.yict.framemax.core.exception.BusinessException;
public interface JudgeCodeService {
/**
* 校验验证码是否正确
*
* @param account,code
* @throws Exception
*/
boolean judgeCode(String account, String code) throws BusinessException;
/**
* 校验验证码是否正确,正确的话就返回授权码,可以给别的业务操作
*
* @param account,code
* @throws Exception
*/
String judgeCodeReturnAuthCode(String account, String code) throws BusinessException;
}
This diff is collapsed.
package cn.com.poc.common.service;
public interface SendEmailService {
/**
* 发送邮箱 验证码发送
*
* */
void sendEmailCode(String emailAddress) throws Exception;
}
package cn.com.poc.common.service;
public interface SmsService {
/**
* 短信下发(获取验证码)
*
* @param phone
* @throws Exception
*/
void smsDelivered(String phone) throws Exception;
}
package cn.com.poc.common.service;
import cn.com.yict.framemax.core.service.BaseService;
import cn.com.poc.common.model.SysErrorLogModel;
import cn.com.yict.framemax.data.model.PagingInfo;
import java.util.Collection;
import java.util.List;
public interface SysErrorLogService extends BaseService {
SysErrorLogModel get(java.lang.Integer id) throws Exception;
List<SysErrorLogModel> findByExample(SysErrorLogModel example,PagingInfo pagingInfo) throws Exception;
void delete(SysErrorLogModel model) throws Exception;
void deleteById(java.lang.Integer id) throws Exception;
void deleteAll(Collection<java.lang.Integer> ids) throws Exception;
SysErrorLogModel save(SysErrorLogModel model) throws Exception;
Collection<SysErrorLogModel> saveAll(Collection<SysErrorLogModel> models) throws Exception;
}
\ No newline at end of file
package cn.com.poc.common.service.impl;
import cn.com.poc.common.service.BosConfigService;
import cn.com.yict.framemax.core.config.Config;
import cn.com.yict.framemax.core.exception.BusinessException;
import cn.com.yict.framemax.frame.service.FmxParamConfigService;
import com.baidubce.auth.BceCredentials;
import com.baidubce.auth.DefaultBceCredentials;
import com.baidubce.services.bos.BosClient;
import com.baidubce.services.bos.BosClientConfiguration;
import com.baidubce.services.bos.model.ObjectMetadata;
import com.baidubce.services.bos.model.PutObjectRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Optional;
@Service
public class BosConfigServiceImpl implements BosConfigService {
@Resource
private FmxParamConfigService fmxParamConfigService;
@Override
public String uploadFileByByteArray2Oss(byte[] decodedByte, String uploadFolder, String fileName, String fileType) throws IOException {
String BUCKET_NAME = fmxParamConfigService.getParam("bos.bucketName");
String END_POINT = fmxParamConfigService.getParam("bos.endPoint");
String FILE_NAME = fileName + "." + fileType;
BosClient client = getClient();
ObjectMetadata meta = new ObjectMetadata();
// 设置内容被下载时的名称。
if (StringUtils.isNoneBlank(FILE_NAME)) {
meta.setContentDisposition("attachment; filename=" + FILE_NAME);
}
// 设置内容被下载时的编码格式。
meta.setContentEncoding("utf-8");
meta.setContentLength(decodedByte.length);
// 设置上传目录
String PUT_OBJECT_REQUEST_KEY = uploadFolder + FILE_NAME;
//上传文件
client.putObject(BUCKET_NAME, PUT_OBJECT_REQUEST_KEY, decodedByte);
client.shutdown();
// 拼接下载地址
return "https://" +
BUCKET_NAME +
"." +
END_POINT.replaceAll("http://", "").replaceAll("https://", "") +
"/" +
PUT_OBJECT_REQUEST_KEY;
}
@Override
public String uploadFileByByteArray2Oss(byte[] decodedByte, String fileName, String fileType) throws IOException {
String date = DateUtils.formatDate(new Date(), "yyyyMMdd");
String UPLOAD_FLODER = fmxParamConfigService.getParam("bos.uploadFolder");
if (UPLOAD_FLODER.endsWith("/")) {
UPLOAD_FLODER = UPLOAD_FLODER + date + "/";
} else {
UPLOAD_FLODER = UPLOAD_FLODER + "/" + date + "/";
}
return this.uploadFileByByteArray2Oss(decodedByte, UPLOAD_FLODER, fileName, fileType);
}
@Override
public String upload(InputStream inputStream, String fileType, String contentType) {
String BUCKET_NAME = fmxParamConfigService.getParam("bos.bucketName");
String END_POINT = fmxParamConfigService.getParam("bos.endPoint");
String FILE_NAME = createFileName(fileType);
BosClient client = getClient();
try {
ObjectMetadata meta = new ObjectMetadata();
meta.setContentType(contentType);
// 设置内容被下载时的名称。
if (StringUtils.isNoneBlank(FILE_NAME)) {
meta.setContentDisposition("attachment; filename=" + FILE_NAME);
}
// 设置内容被下载时的编码格式。
meta.setContentEncoding("utf-8");
meta.setContentLength(inputStream.available());
// 设置上传目录
String date = DateUtils.formatDate(new Date(), "yyyyMMdd");
String UPLOAD_FLODER = fmxParamConfigService.getParam("bos.uploadFolder");
// 如果上传目录不以【/】结尾,加上
if (UPLOAD_FLODER.endsWith("/")) {
UPLOAD_FLODER = UPLOAD_FLODER + date + "/";
} else {
UPLOAD_FLODER = UPLOAD_FLODER + "/" + date + "/";
}
String PUT_OBJECT_REQUEST_KEY = UPLOAD_FLODER + FILE_NAME;
//上传文件
PutObjectRequest request = new PutObjectRequest(BUCKET_NAME, PUT_OBJECT_REQUEST_KEY, inputStream);
request.withStorageClass(BosClient.STORAGE_CLASS_STANDARD);
request.setObjectMetadata(meta);
client.putObject(request);
client.shutdown();
inputStream.close();
// 拼接下载地址
return "https://" +
BUCKET_NAME +
"." +
END_POINT.replaceAll("http://", "").replaceAll("https://", "") +
"/" +
PUT_OBJECT_REQUEST_KEY;
} catch (IOException e) {
throw new RuntimeException(e.getLocalizedMessage());
} finally {
client.shutdown();
}
}
//返回即将创建的文件名
private String createFileName(String fileType) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(System.currentTimeMillis()).
append(".").
append(Optional.ofNullable(fileType).orElse(""));
return stringBuilder.toString();
}
private BosClient getClient() {
String ACCESS_KEY_ID = Config.get("baidu.code.keyId");
String SECRET_ACCESS_KEY = Config.get("baidu.code.keySecret");
String END_POINT = fmxParamConfigService.getParam("bos.endPoint");
BceCredentials credentials = new DefaultBceCredentials(ACCESS_KEY_ID, SECRET_ACCESS_KEY);
BosClientConfiguration config = new BosClientConfiguration();
config.setCredentials(credentials);
config.setEndpoint(END_POINT);
return new BosClient(config);
}
}
package cn.com.poc.common.service.impl;
import cn.com.poc.common.constant.RedisKeyConstant;
import cn.com.poc.common.service.JudgeCodeService;
import cn.com.poc.common.service.RedisService;
import cn.com.poc.common.utils.UUIDTool;
import cn.com.yict.framemax.core.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.regex.Pattern;
@Component
public class JudgeCodeServiceImpl implements JudgeCodeService {
@Resource
private RedisService redisService;
@Override
public boolean judgeCode(String account, String code) throws BusinessException {
//验证次数
String accountKey = "JUDGE_CODE_COUNT:" + account;
//校验校验验证码:从redis获取发送的验证码
String mobileCode = (String) redisService.get(account);
if (StringUtils.isEmpty(mobileCode)) {
throw new BusinessException("验证码已过期,请重新获取");
}
// 防止撞库攻击
if (!redisService.hasKey(accountKey)) {
redisService.set(accountKey, 1, 60);
}
//如果没有验证过
int verifyCount = Integer.parseInt(String.valueOf(redisService.get(accountKey)));
if (verifyCount > 5) {
throw new BusinessException("验证次数已达上限");
}
//验证次数自增
verifyCount++;
redisService.set(accountKey, verifyCount, redisService.getExpire(accountKey));
//验证逻辑
boolean isValid = mobileCode.equals(code);
//如果成功,删除验证码和验证码次数
if (isValid) {
redisService.del(account);
redisService.del(accountKey);
return true;
}
return false;
}
@Override
public String judgeCodeReturnAuthCode(String account, String code) throws BusinessException {
//验证验证码是否正确
if (!judgeCode(account, code)) {
return StringUtils.EMPTY;
}
//验证次数
String authCode = UUIDTool.getUUID();
//校验手机号格式
boolean matches = Pattern.matches(
"(?:0|86|\\+86)?1[3-9]\\d{9}|" +
"(?:0|852|\\+852)?\\d{8}|" +
"(?:0|886|\\+886)?(?:|-)09\\d{8}|" +
"(?:0|853|\\+853)?(?:|-)6\\d{7}", account);
if(matches){ //是手机号
redisService.set(RedisKeyConstant.Code.AUTH_CODE + account, authCode, 60 * 5);
}else{
redisService.set(RedisKeyConstant.Code.AUTH_CODE + account, authCode, 60 * 15);
}
return authCode;
}
}
package cn.com.poc.common.service.impl;
import cn.com.poc.common.service.RedisService;
import cn.com.poc.common.service.SendEmailService;
import cn.com.poc.common.utils.Assert;
import cn.com.poc.common.utils.DateUtils;
import cn.com.poc.common.utils.RandomCodeUtils;
import cn.com.yict.framemax.core.exception.BusinessException;
import cn.com.yict.framemax.frame.entity.EmailSenderEntity;
import cn.com.yict.framemax.frame.service.EmailSenderService;
import cn.com.yict.framemax.frame.service.FmxParamConfigService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
@Service
public class SendEmailServiceImpl implements SendEmailService {
@Resource
private EmailSenderService emailSenderService;
@Resource
private FmxParamConfigService fmxParamConfigService;
@Resource
private RedisService redisService;
@Override
public void sendEmailCode(String emailAddress) throws Exception {
Assert.notBlank(emailAddress, "用户登录,登录账号不能为空");
EmailSenderEntity entity = new EmailSenderEntity();
String code = RandomCodeUtils.generateNumber(6);
String projectName = fmxParamConfigService.getParam("project.name");
String body = fmxParamConfigService.getParam("login.email.send.body");
body = body.replaceAll("\\$\\{projectName}",projectName)
.replaceAll("\\$\\{emailAddress}",emailAddress)
.replaceAll("\\$\\{authCode}",code)
.replaceAll("\\$\\{CurrDate}",DateUtils.getCurrDate());
entity.setBody(body);
List<String> list = new LinkedList<>();
list.add(emailAddress);
entity.setTo(list); //接收者
if(emailSenderService.sendMail(entity,null)){
// 如果成功发送,则把验证码存入redis当中,并设置15分钟的过期时间
redisService.set(emailAddress, code, 900);
} else {
throw new BusinessException("验证码发送失败!请重试");
}
}
}
package cn.com.poc.common.service.impl;
import cn.com.poc.common.dto.SmsDto;
import cn.com.poc.common.service.RedisService;
import cn.com.poc.common.service.SmsService;
import cn.com.poc.support.sms.channel.baidu.BaiDuThirdPlatformService;
import cn.com.yict.framemax.core.exception.BusinessException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Random;
@Service
public class SmsServiceImpl implements SmsService {
@Resource
private BaiDuThirdPlatformService baiDuThirdPlatformService;
@Resource
private RedisService redisService;
@Override
public void smsDelivered(String phone) throws Exception {
SmsDto smsDto = new SmsDto();
Random random = new Random();
// 随机生成六位数的随机数字
int randomNum = 100000 + random.nextInt(900000); // 生成[10000, 99999]范围内的随机数
String code = Integer.toString(randomNum);
smsDto.setMobilePhone(phone);
smsDto.setSmsCode(code);
boolean isSend = baiDuThirdPlatformService.doSend(smsDto);
if (isSend) {
// 如果成功发送,则把验证码存入redis当中,并设置五分钟的过期时间
redisService.set(phone, code, 300);
} else {
throw new BusinessException("验证码发送失败!请重试");
}
}
}
package cn.com.poc.common.service.impl;
import cn.com.yict.framemax.core.service.impl.BaseServiceImpl;
import cn.com.poc.common.service.SysErrorLogService;
import cn.com.poc.common.model.SysErrorLogModel;
import cn.com.poc.common.repository.SysErrorLogRepository;
import cn.com.yict.framemax.data.model.PagingInfo;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.List;
import javax.annotation.Resource;
@Service
public class SysErrorLogServiceImpl extends BaseServiceImpl
implements SysErrorLogService {
@Resource
private SysErrorLogRepository repository;
public SysErrorLogModel get(java.lang.Integer id) throws Exception{
return this.repository.get(id);
}
public List<SysErrorLogModel> findByExample(SysErrorLogModel example,PagingInfo pagingInfo) throws Exception{
if(example == null){
example = new SysErrorLogModel();
}
return this.repository.findByExample(example,pagingInfo);
}
public void delete(SysErrorLogModel model) throws Exception{
this.repository.remove(model);
}
public void deleteById(java.lang.Integer id) throws Exception{
this.repository.removeByPk(id);
}
public void deleteAll(Collection<java.lang.Integer> ids) throws Exception{
this.repository.removeAllByPk(ids);
}
public SysErrorLogModel save(SysErrorLogModel model) throws Exception{
return this.repository.save(model);
}
public Collection<SysErrorLogModel> saveAll(Collection<SysErrorLogModel> models) throws Exception{
return this.repository.saveAll(models);
}
}
\ No newline at end of file
package cn.com.poc.common.utils;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class AESDecode {
/*
* 计算MD5+BASE64
*/
public static String MD5Base64(String s) {
if (s == null)
return null;
String encodeStr = "";
byte[] utfBytes = s.getBytes();
MessageDigest mdTemp;
try {
mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(utfBytes);
byte[] md5Bytes = mdTemp.digest();
encodeStr = Base64.encodeBase64String(md5Bytes);
} catch (Exception e) {
throw new Error("Failed to generate MD5 : " + e.getMessage());
}
return encodeStr;
}
/*
* 计算 HMAC-SHA1
*/
public static String HMACSha1(String data, String key) {
String result;
try {
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(data.getBytes());
result = Base64.encodeBase64String(rawHmac);
} catch (Exception e) {
throw new Error("Failed to generate HMAC : " + e.getMessage());
}
return result;
}
/*
* 等同于javaScript中的 new Date().toUTCString();
*/
public static String toGMTString(Date date) {
SimpleDateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z", Locale.UK);
df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));
return df.format(date);
}
}
\ No newline at end of file
package cn.com.poc.common.utils;
public class ArticleUtils {
public String cutArticleUrl(String articleUrl){
return articleUrl.substring(0,articleUrl.indexOf("&chksm")-1);
}
}
package cn.com.poc.common.utils;
public class Assert extends org.springframework.util.Assert {
public static void notBlank(String text) {
if (StringUtils.isBlank(text)) {
throw new IllegalArgumentException("缺少必要参数");
}
}
public static void notBlank(String text, String message) {
if (StringUtils.isBlank(text)) {
throw new IllegalArgumentException("缺少必要参数-[" + message + "]");
}
}
public static void notNull(Object text, String message) {
if (text == null) {
throw new IllegalArgumentException("缺少必要参数-[" + message + "]");
}
}
}
package cn.com.poc.common.utils;
import cn.com.poc.support.security.oauth.constants.OauthConstants;
import cn.com.poc.support.security.oauth.entity.OpenPlatformEntity;
import cn.com.poc.support.security.oauth.entity.UserBaseEntity;
import cn.com.poc.user.entity.MemberInfoEntity;
import cn.com.yict.framemax.core.context.Context;
import cn.com.yict.framemax.data.model.UserBaseModel;
import cn.com.yict.framemax.frame.entity.UserSessionEntity;
import cn.com.yict.framemax.security.oauth.exception.TokenExpiredException;
import org.springframework.beans.BeanUtils;
/**
* @author Focan Zhong
* @create 2021/8/6
*/
public class BlContext {
/**
* 获取上下文用户
*
* @return
*/
public static UserBaseEntity getCurrentUser() {
UserBaseModel userBaseModel = Context.get().getCurrentUser();
if (userBaseModel == null) {
throw new TokenExpiredException();
}
return distinguishUserType(userBaseModel);
}
/**
* 获取上下文用户 无异常
*
* @return
*/
public static UserBaseEntity getCurrentUserNotException() {
UserBaseModel userBaseModel = Context.get().getCurrentUser();
if (userBaseModel == null) {
return null;
}
return distinguishUserType(userBaseModel);
}
/**
* 区分用户类型
*
* @param userBaseModel
* @return
*/
private static UserBaseEntity distinguishUserType(UserBaseModel userBaseModel) {
UserBaseEntity userBaseEntity = new UserBaseEntity();
BeanUtils.copyProperties(userBaseModel, userBaseEntity);
if (Context.get().getCurrentUser() instanceof MemberInfoEntity) {
userBaseEntity.setType(OauthConstants.OauthEnum.MEMBER_DOMAIN.name());
}
return userBaseEntity;
}
}
package cn.com.poc.common.utils;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ChineseCharacterUtil {
/**
* 获取汉字首字母或全拼大写字母
*
* @param chinese 汉字
* @param isFull 是否全拼 true:表示全拼 false表示:首字母
* @return 全拼或者首字母大写字符窜
*/
public static String getUpperCase(String chinese, boolean isFull) {
return convertHanzi2Pinyin(chinese, isFull).toUpperCase();
}
/**
* 获取汉字首字母或全拼小写字母
*
* @param chinese 汉字
* @param isFull 是否全拼 true:表示全拼 false表示:首字母
* @return 全拼或者首字母小写字符窜
*/
public static String getLowerCase(String chinese, boolean isFull) {
return convertHanzi2Pinyin(chinese, isFull).toLowerCase();
}
/**
* 将汉字转成拼音
* <p>
* 取首字母或全拼
*
* @param hanzi 汉字字符串
* @param isFull 是否全拼 true:表示全拼 false表示:首字母
* @return 拼音
*/
public static String convertHanzi2Pinyin(String hanzi, boolean isFull) {
/***
* ^[\u2E80-\u9FFF]+$ 匹配所有东亚区的语言
* ^[\u4E00-\u9FFF]+$ 匹配简体和繁体
* ^[\u4E00-\u9FA5]+$ 匹配简体
*/
String regExp = "^[\u4E00-\u9FFF]+$";
StringBuffer sb = new StringBuffer();
if (hanzi == null || "".equals(hanzi.trim())) {
return "";
}
String pinyin = "";
for (int i = 0; i < hanzi.length(); i++) {
char unit = hanzi.charAt(i);
//是汉字,则转拼音
if (match(String.valueOf(unit), regExp)) {
pinyin = convertSingleHanzi2Pinyin(unit);
if (isFull) {
sb.append(pinyin);
} else if (StringUtils.isNoneBlank(pinyin)) {
sb.append(pinyin.charAt(0));
}
} else {
sb.append(unit);
}
}
return sb.toString();
}
/**
* 将单个汉字转成拼音
*
* @param hanzi 汉字字符
* @return 拼音
*/
private static String convertSingleHanzi2Pinyin(char hanzi) {
HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
String[] res;
StringBuffer sb = new StringBuffer();
try {
res = PinyinHelper.toHanyuPinyinStringArray(hanzi, outputFormat);
if (res != null) {
sb.append(res[0]);//对于多音字,只用第一个拼音
}
} catch (Exception e) {
e.printStackTrace();
return "";
}
return sb.toString();
}
/***
* 匹配
* <P>
* 根据字符和正则表达式进行匹配
*
* @param str 源字符串
* @param regex 正则表达式
*
* @return true:匹配成功 false:匹配失败
*/
private static boolean match(String str, String regex) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
return matcher.find();
}
public static boolean isChineseChar(char c) {
try {
return String.valueOf(c).getBytes("UTF-8").length > 1;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return false;
}
}
/**
* 判断字符串是否中文
*/
public static boolean isChinese(String content) {
return match(content, "[\u4e00-\u9fa5]");
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment