设置三级表单 定时任务提交

master
bynt 3 years ago
parent a9cc324795
commit f3c554b3c6

@ -11,30 +11,42 @@ package me.zhengjie.common.http;
*/
public enum ResponseCode {
/**成功*/
SUCCESS(0,"SUCCESS"),
/**失败*/
ERROR(1,"ERROR"),
// 成功的一些特殊提示
/**成功的一些特殊提示*/
SUCCESS_ONCE_LINK_MSG(0,"下载成功,一次性链接已经失效"),
// 通用请求参数校验
/**通用请求参数校验*/
ILLEGAL_ARGUMENT(1,"请求参数格式错误"),
/**请求参数为空*/
EMPTY_ARGUMENT(1,"请求参数为空"),
/** modeify by wzx
*/
NO_SMS_BAD(1,"短信内容有问题"),
/**不能满足要求的参数设置*/
NO_MATCH_ARGUMENT_SET(1,"不能满足要求的参数设置"),
/***/
NO_FILE_INPUT(1,"没有文件输入"),
// 特殊需要进行前端返回说明的参数定义
/**任务名称已经存在*/
TASK_NAME_IS_EXIST(1,"任务名称已经存在"),
/**链接失效,下载文件失败*/
ONCE_LINK_MSG_ERROR(1,"链接失效,下载文件失败~"),
// 请求结果性的错误
/**查询结果为空*/
NODATA_ERROR(1,"查询结果为空"),
/**任务建立失败*/
TASK_BUILD_ERROR(1,"任务建立失败"),
/**未查询到相关内容*/
NO_RELEVANT_CONTENT_WAS_FOUND(1,"未查询到相关内容"),
DECRYPT_ERROR(1,"解密错误,请联系我");
/**解密错误,请联系我*/
DECRYPT_ERROR(1,"解密错误,请联系我"),
/**当前任务含有子任务 请先删除子任务*/
DELETE_ERROR(1,"当前任务含有子任务 请先删除子任务"),
/**执行任务失败 手动异常事务回滚*/
TASK_ERROR(1,"执行任务失败 手动异常事务回滚"),
/**当前级别不允许放置 请重新拖拽*/
CHANGE_TASK_ERROR(1,"当前级别不允许放置 请重新拖拽");
private final int code;
private final String desc;

@ -0,0 +1,160 @@
package me.zhengjie.to;
import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
/**
* @author
*
*/
public class ResponseResult<T> {
private int code;
private String message;
private Object data;
/**
*
*
* @param data
*/
public ResponseResult<T> success(Object data) {
this.code = HttpStatus.OK.value();
this.message = "操作成功";
this.data = data;
return this;
}
/**
*
*
*/
public static <T> ResponseResult<T> successfulOperation() {
return new ResponseResult<T>().success("操作成功");
}
public ResponseResult<T> fail(int code, String message) {
this.code = code;
this.message = message;
this.data = message;
return this;
}
/**
*
*/
public ResponseResult<T> failed() {
this.code = HttpStatus.INTERNAL_SERVER_ERROR.value();
this.message = "操作失败";
return this;
}
/**
*
*/
public ResponseResult<T> error(String message) {
this.code = HttpStatus.INTERNAL_SERVER_ERROR.value();
this.message = message;
return this;
}
/**
* 使
*
* @param message
*/
public ResponseResult<T> validateFailed(String message) {
this.code = HttpStatus.NOT_FOUND.value();
this.message = message;
return this;
}
/**
* 使
*
* @param message
*/
public ResponseResult<T> unauthorized(String message) {
this.code = HttpStatus.UNAUTHORIZED.value();
this.message = "暂未登录或token已经过期";
this.data = message;
return this;
}
/**
* 使
*
* @param message
*/
public ResponseResult<T> forbidden(String message) {
this.code = HttpStatus.FORBIDDEN.value();
this.message = message;
this.data = message;
return this;
}
public ResponseResult<T> forbidden() {
this.code = HttpStatus.NOT_IMPLEMENTED.value();
this.message = "请先登录";
this.data = message;
return this;
}
/**
* 使
*
* @param message
*/
public ResponseResult<T> forbidden(int code,String message) {
this.code = code;
this.message = "没有相关权限";
this.data = message;
return this;
}
/**
* 使
* @param result
*/
public ResponseResult<T> validateFailed(BindingResult result) {
validateFailed(result.getFieldError().getDefaultMessage());
return this;
}
@Override
public String toString() {
return JSON.toJSONString(this);
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}

@ -97,6 +97,16 @@ public class ThreadPoolConfig {
private String remoteTaskThreadNamePrefix = "RemoteTaskExecutor-"; // fixme 这个属性暂时没用起来
/**
* Schedule buildRecordTask create Enzo
* maxPoolSize
*/
@Value(value = "${remoteRec.task.thread_pool.corePoolSize}")
private int buildTaskDataCorePoolSize;
@Value(value = "${remoteRec.task.thread_pool.maxPoolSize}")
private int buildTaskMaxPoolSize;
@Value(value = "${remoteRec.task.thread_pool.queueCapacity}")
private int buildTaskQueueCapacity;
/**
@ -139,6 +149,7 @@ public class ThreadPoolConfig {
/**
* - 线
*
* @return
*/
@Bean(value = "MergeRecordTaskExecutor")
@ -156,7 +167,7 @@ public class ThreadPoolConfig {
}
@Bean(value = "ProduceBigDataTaskExecutor")
public Executor produceBigDataTaskExecutor(){
public Executor produceBigDataTaskExecutor() {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
produceBigDataCorePoolSize,
produceBigDataMaxPoolSize,
@ -170,7 +181,7 @@ public class ThreadPoolConfig {
}
@Bean(value = "SendBigDataTaskExecutor")
public Executor SendBigDataTaskExecutor(){
public Executor SendBigDataTaskExecutor() {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
sendBigDataCorePoolSize,
sendBigDataMaxPoolSize,
@ -184,7 +195,7 @@ public class ThreadPoolConfig {
}
@Bean(value = "RemoteTaskExecutor")
public Executor remoteTaskExecutor(){
public Executor remoteTaskExecutor() {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
remoteTaskDataCorePoolSize,
remoteTaskMaxPoolSize,
@ -197,4 +208,42 @@ public class ThreadPoolConfig {
return threadPoolExecutor;
}
/**
* 线
* @return
*/
@Bean(value = "buildTaskExecutor")
public Executor buildTaskExecutor() {
return new ThreadPoolExecutor(
buildTaskDataCorePoolSize,
buildTaskMaxPoolSize,
// 设置线程超时1分钟
1,
TimeUnit.MINUTES,
new LinkedBlockingDeque<>(remoteTaskQueueCapacity),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);
}
/**
* 线
*
* @return
*/
@Bean(value = "resendBuildTaskExecutor")
public Executor resendBuildTaskExecutor() {
return new ThreadPoolExecutor(
buildTaskDataCorePoolSize,
buildTaskMaxPoolSize,
// 设置线程超市1分钟
1,
TimeUnit.MINUTES,
new LinkedBlockingDeque<>(remoteTaskQueueCapacity),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);
}
}

@ -15,19 +15,17 @@
*/
package me.zhengjie.modules.buildrecord.domain;
import lombok.Data;
import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.ApiModelProperty;
import cn.hutool.core.bean.copier.CopyOptions;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.sql.Timestamp;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.List;
/**
* @website https://el-admin.vip
@ -101,8 +99,31 @@ public class BuildRecord implements Serializable {
private Long taskBuildId;
@Column(name = "level")
@ApiModelProperty(value = "等级")
private Integer level;
@Column(name = "parent_id")
@ApiModelProperty(value = "父类id")
private Integer parentId;
@Column(name = "sort_value")
@ApiModelProperty(value = "排序值")
private Integer sortValue;
@Column(name = "is_timed_task")
@ApiModelProperty(value = "是否定时任务")
private Boolean isTimedTask;
@Transient
@ApiModelProperty(value = "子类集合")
private List<BuildRecord> children;
public void copy(BuildRecord source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
}
}

@ -18,6 +18,11 @@ package me.zhengjie.modules.buildrecord.repository;
import me.zhengjie.modules.buildrecord.domain.BuildRecord;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import javax.validation.constraints.NotNull;
import java.util.List;
/**
* @website https://el-admin.vip
@ -25,4 +30,81 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
* @date 2020-09-10
**/
public interface BuildRecordRepository extends JpaRepository<BuildRecord, Integer>, JpaSpecificationExecutor<BuildRecord> {
}
/**
*
* @param level
* @return
*/
List<BuildRecord> findByLevel(Integer level);
/**
* id
* @param id
* @return
*/
Integer countByParentId(Integer id);
/**
*
* @param parentId
* @return
*/
List<BuildRecord> findByParentId(Integer parentId);
/**
*
* @param sortValue
* @param originalParentId
*/
@Modifying
@Query(value = "update BuildRecord set sortValue = sortValue + 1 where sortValue > ?1 and parentId = ?2")
void incrSortValue(Integer sortValue, @NotNull(message = "原始父类id") Integer originalParentId);
/**
*
* @param sortValue
* @param originalParentId
*/
@Modifying
@Query(value = "update BuildRecord set sortValue = sortValue - 1 where sortValue > ?1 and parentId = ?2")
void decreaseSortValue(Integer sortValue, Integer originalParentId);
/**
*
* @param id
* @param changeParentId
* @param reSubscript
*/
@Modifying
@Query(value = "update BuildRecord set parentId = ?2,sortValue = ?3 where id = ?1")
void updateParentAndSortValue(Integer id, Integer changeParentId, Integer reSubscript);
/**
*
* @param changeTimeTask
* @param id
* @return
*/
@Modifying
@Query(value = "update BuildRecord set isTimedTask = ?1 where id = ?2")
int updateTimeTask(Boolean changeTimeTask,Integer id);
/**
*
* @return
* @param aTrue
*/
List<BuildRecord> findByIsTimedTask(Boolean aTrue);
/**
*
* @param id
* @param nonFinishSendStatus
*/
@Modifying
@Query(value = "update BuildRecord set isSend = ?1 where id = ?1")
void updateIsSendByRecordId(Integer id, int nonFinishSendStatus);
}

@ -16,6 +16,9 @@
package me.zhengjie.modules.buildrecord.rest;
import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.common.http.CommonResponse;
@ -30,28 +33,26 @@ import me.zhengjie.modules.buildrecord.task.ProduceBigDataTask;
import me.zhengjie.modules.buildrecord.task.SendBigDataTask;
import me.zhengjie.modules.buildrecord.task.dto.SendBigDataDTO;
import me.zhengjie.modules.buildrecord.util.WordFilter;
import me.zhengjie.to.ResponseResult;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
/**
* @website https://el-admin.vip
* @author x
* @date 2020-09-10
**/
* @author x
* @website https://el-admin.vip
* @date 2020-09-10
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "buildRecord管理")
@ -82,6 +83,15 @@ public class BuildRecordController {
return new ResponseEntity<>(buildRecordService.queryAll(criteria,pageable),HttpStatus.OK);
}
@GetMapping("/getBuildList")
@Log("根据等级查询buildList")
@ApiOperation("根据等级查询buildList")
@PreAuthorize("@el.check('buildRecord:list')")
public ResponseEntity<List<BuildRecord>> buildList(Integer level) {
return new ResponseEntity<>(buildRecordService.queryBuildListByLevel(level), HttpStatus.OK);
}
@PostMapping
@Log("新增buildRecord")
@ApiOperation("新增buildRecord")
@ -247,4 +257,4 @@ public class BuildRecordController {
//// buildRecordService.updateSmsContent(smsContent,94);
// return new ResponseEntity<>(CommonResponse.createBySuccess(), HttpStatus.OK);
// }
}
}

@ -0,0 +1,30 @@
package me.zhengjie.modules.buildrecord.rest.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotNull;
/**
* @author Enzo
* @date : 2021/4/28
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ChangeBuildRecordVo {
@NotNull(message = "修改id")
private Integer id;
@NotNull(message = "下标位置不能为空")
private Integer reSubscript;
@NotNull(message = "修改父类id不能为空")
private Integer changeParentId;
@NotNull(message = "原始父类id")
private Integer originalParentId;
}

@ -19,10 +19,11 @@ import me.zhengjie.modules.buildrecord.domain.BuildRecord;
import me.zhengjie.modules.buildrecord.service.dto.BuildRecordDto;
import me.zhengjie.modules.buildrecord.service.dto.BuildRecordQueryCriteria;
import org.springframework.data.domain.Pageable;
import java.util.Map;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* @website https://el-admin.vip
@ -80,4 +81,47 @@ public interface BuildRecordService {
* @throws IOException /
*/
void download(List<BuildRecordDto> all, HttpServletResponse response) throws IOException;
}
/**
*
* @param level
* @return
*/
List<BuildRecord> queryBuildListByLevel(Integer level);
/**
*
* @param id
*/
void deleteById(Integer id);
/**
* id
* @param id
* @return
*/
Integer findByParentId(Integer id);
/**
*
* @param changeTimeTask
* @param id
* @return
*/
boolean changeTimeTask(Boolean changeTimeTask, Integer id);
/**
* list
* @return
* @param aTrue
*/
List<BuildRecord> getBuildRecordByIsTimedTask(Boolean aTrue);
/**
*
* @param id
* @param nonFinishSendStatus
*/
void updateIsSendByRecordId(Integer id, int nonFinishSendStatus);
}

@ -16,8 +16,10 @@
package me.zhengjie.modules.buildrecord.service.dto;
import lombok.Data;
import java.sql.Timestamp;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.List;
/**
* @website https://el-admin.vip
@ -70,4 +72,14 @@ public class BuildRecordDto implements Serializable {
* ID
*/
private Long taskBuildId;
}
/** 等级 */
private Integer level;
/** 父类ID */
private Integer parentId;
private Boolean isTimedTask;
/** 子类集合 */
private List<BuildRecordDto> children;
}

@ -16,7 +16,6 @@
package me.zhengjie.modules.buildrecord.service.dto;
import lombok.Data;
import java.util.List;
import me.zhengjie.annotation.Query;
/**
@ -31,5 +30,14 @@ public class BuildRecordQueryCriteria{
@Query(type = Query.Type.INNER_LIKE)
private String taskName;
@Query(type = Query.Type.EQUAL)
private Integer parentId;
}
@Query(type = Query.Type.EQUAL)
private Integer level;
@Query(type = Query.Type.EQUAL)
private Boolean flag;
}

@ -1,77 +1,99 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.zhengjie.modules.buildrecord.service.impl;
import me.zhengjie.modules.buildrecord.domain.BuildRecord;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.buildrecord.domain.BuildRecord;
import me.zhengjie.modules.buildrecord.repository.BuildRecordRepository;
import me.zhengjie.modules.buildrecord.service.BuildRecordService;
import me.zhengjie.modules.buildrecord.service.dto.BuildRecordDto;
import me.zhengjie.modules.buildrecord.service.dto.BuildRecordQueryCriteria;
import me.zhengjie.modules.buildrecord.service.mapstruct.BuildRecordMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.modules.common.consts.DefaultConstant;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
/**
* @website https://el-admin.vip
* @description
* @author x
* @date 2020-09-10
**/
* @author x
* @website https://el-admin.vip
* @description
* @date 2020-09-10
**/
@Service
@RequiredArgsConstructor
public class BuildRecordServiceImpl implements BuildRecordService {
private final BuildRecordRepository buildRecordRepository;
private final BuildRecordMapper buildRecordMapper;
@Override
public Map<String,Object> queryAll(BuildRecordQueryCriteria criteria, Pageable pageable){
Page<BuildRecord> page = buildRecordRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
public Map<String, Object> queryAll(BuildRecordQueryCriteria criteria, Pageable pageable) {
criteria.setParentId(DefaultConstant.ZERO_NUMBER);
if (criteria.getFlag() != null && !criteria.getFlag()) {
criteria.setParentId(null);
criteria.setLevel(DefaultConstant.THREE_NUMBER);
}
// 无实体对应 赋初始值
criteria.setFlag(null);
Page<BuildRecord> page = buildRecordRepository
.findAll((root, criteriaQuery, criteriaBuilder) ->
QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
List<BuildRecord> all = buildRecordRepository.findAll();
page.getContent().forEach
(buildRecord ->
buildRecord.setChildren
(getChildren(buildRecord, all)));
return PageUtil.toPage(page.map(buildRecordMapper::toDto));
}
@Override
public List<BuildRecordDto> queryAll(BuildRecordQueryCriteria criteria){
return buildRecordMapper.toDto(buildRecordRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
public List<BuildRecordDto> queryAll(BuildRecordQueryCriteria criteria) {
return buildRecordMapper.toDto(buildRecordRepository.findAll(
(root, criteriaQuery, criteriaBuilder) ->
QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
}
@Override
@Transactional
public BuildRecordDto findById(Integer id) {
BuildRecord buildRecord = buildRecordRepository.findById(id).orElseGet(BuildRecord::new);
ValidationUtil.isNull(buildRecord.getId(),"BuildRecord","id",id);
ValidationUtil.isNull(buildRecord.getId(), "BuildRecord", "id", id);
return buildRecordMapper.toDto(buildRecord);
}
@Override
@Transactional(rollbackFor = Exception.class)
public BuildRecordDto create(BuildRecord resources) {
if (resources.getLevel().equals(DefaultConstant.ONE_NUMBER)) {
resources.setParentId(DefaultConstant.ZERO_NUMBER);
}
return buildRecordMapper.toDto(buildRecordRepository.save(resources));
}
@ -79,7 +101,7 @@ public class BuildRecordServiceImpl implements BuildRecordService {
@Transactional(rollbackFor = Exception.class)
public void update(BuildRecord resources) {
BuildRecord buildRecord = buildRecordRepository.findById(resources.getId()).orElseGet(BuildRecord::new);
ValidationUtil.isNull( buildRecord.getId(),"BuildRecord","id",resources.getId());
ValidationUtil.isNull(buildRecord.getId(), "BuildRecord", "id", resources.getId());
buildRecord.copy(resources);
buildRecordRepository.save(buildRecord);
}
@ -95,7 +117,7 @@ public class BuildRecordServiceImpl implements BuildRecordService {
public void download(List<BuildRecordDto> all, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (BuildRecordDto buildRecord : all) {
Map<String,Object> map = new LinkedHashMap<>();
Map<String, Object> map = new LinkedHashMap<>();
map.put("创建时间", buildRecord.getGmtCreate());
map.put("修改时间", buildRecord.getGmtModified());
map.put("任务名称", buildRecord.getTaskName());
@ -112,4 +134,57 @@ public class BuildRecordServiceImpl implements BuildRecordService {
}
FileUtil.downloadExcel(list, response);
}
}
@Override
public List<BuildRecord> queryBuildListByLevel(Integer level) {
return buildRecordRepository.findByLevel(level);
}
@Override
public void deleteById(Integer id) {
buildRecordRepository.deleteById(id);
}
@Override
public Integer findByParentId(Integer id) {
return buildRecordRepository.countByParentId(id);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean changeTimeTask(Boolean changeTimeTask, Integer id) {
return buildRecordRepository.updateTimeTask(changeTimeTask, id) > 0;
}
@Override
public List<BuildRecord> getBuildRecordByIsTimedTask(Boolean aTrue) {
return buildRecordRepository.findByIsTimedTask(aTrue);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateIsSendByRecordId(Integer id, int nonFinishSendStatus) {
buildRecordRepository.updateIsSendByRecordId(id, nonFinishSendStatus);
}
/**
*
*/
private List<BuildRecord> getChildren(BuildRecord buildRecord, List<BuildRecord> all) {
return all.stream().
// 过滤
filter(record -> record.getParentId() != null && record.getParentId().equals(buildRecord.getId())).
peek(record -> {
// 设置子节点
List<BuildRecord> children = getChildren(record, all);
record.setChildren(children != null ? children : new ArrayList<>());
})
// 排序
.sorted(Comparator.comparingInt(buildRecordFirst ->
(buildRecordFirst.getSortValue() == null ? 0 : buildRecordFirst.getSortValue())))
.collect(Collectors.toList());
}
}

@ -0,0 +1,67 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.zhengjie.modules.buildtask.domain;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* @website https://el-admin.vip
* @description /
* @author Enzo
* @date 2021-04-30
**/
@Entity
@Data
@Table(name="tb_build_task")
public class BuildTask implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
@ApiModelProperty(value = "id")
private Integer id;
@Column(name = "gmt_create")
@ApiModelProperty(value = "gmtCreate")
private Timestamp gmtCreate;
@Column(name = "gmt_modified")
@ApiModelProperty(value = "gmtModified")
private Timestamp gmtModified;
@Column(name = "build_id")
@ApiModelProperty(value = "发送id")
private Integer buildId;
@Column(name = "send_time")
@ApiModelProperty(value = "发送时间")
private Timestamp sendTime;
@Column(name = "is_send")
@ApiModelProperty(value = "发送状态 1成功 0失败")
private Integer isSend;
public void copy(BuildTask source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
}

@ -0,0 +1,76 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.zhengjie.modules.buildtask.repository;
import cn.hutool.core.date.DateTime;
import me.zhengjie.modules.buildtask.domain.BuildTask;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import java.time.LocalTime;
import java.util.List;
/**
* @author Enzo
* @website https://el-admin.vip
* @date 2021-04-30
**/
public interface BuildTaskRepository extends JpaRepository<BuildTask, Integer>, JpaSpecificationExecutor<BuildTask> {
/**
* id
* @param recordId
* @param now
* @return
*/
@Query(value =
"select t.* from tb_build_task t where t.build_id = ?1 and TO_DAYS(t.gmt_create)=TO_DAYS(?2)",
nativeQuery = true)
BuildTask findBuildByRecordIdAndDate(Integer recordId, LocalTime now);
/**
*
* @param buildTaskId
* @return
*/
@Modifying
@Query(value = "update BuildTask set isSend = 1 where id = ?1")
int updateSendStatusById(Integer buildTaskId);
/**
*
* @param offsetDay
* @return
*/
@Query(value =
"select t.* from tb_build_task t where is_send = 0 and TO_DAYS(t.gmt_create)=TO_DAYS(?1) ",
nativeQuery = true)
List<BuildTask> findBuildTaskByTime(String offsetDay);
/**
*
* @param beginOfDay
* @param endOfDay
* @return
*/
@Query("select t from BuildTask t where t.isSend = 0 and t.gmtCreate between ?1 and ?2")
List<BuildTask> findBuildTaskByTime(DateTime beginOfDay, DateTime endOfDay);
}

@ -0,0 +1,87 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.zhengjie.modules.buildtask.rest;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.buildtask.domain.BuildTask;
import me.zhengjie.modules.buildtask.service.BuildTaskService;
import me.zhengjie.modules.buildtask.service.dto.BuildTaskQueryCriteria;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
* @website https://el-admin.vip
* @author Enzo
* @date 2021-04-30
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "buildTask管理")
@RequestMapping("/api/buildTask")
public class BuildTaskController {
private final BuildTaskService buildTaskService;
@Log("导出数据")
@ApiOperation("导出数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('buildTask:list')")
public void download(HttpServletResponse response, BuildTaskQueryCriteria criteria) throws IOException {
buildTaskService.download(buildTaskService.queryAll(criteria), response);
}
@GetMapping
@Log("查询buildTask")
@ApiOperation("查询buildTask")
@PreAuthorize("@el.check('buildTask:list')")
public ResponseEntity<Object> query(BuildTaskQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(buildTaskService.queryAll(criteria,pageable),HttpStatus.OK);
}
@PostMapping
@Log("新增buildTask")
@ApiOperation("新增buildTask")
@PreAuthorize("@el.check('buildTask:add')")
public ResponseEntity<Object> create(@Validated @RequestBody BuildTask resources){
return new ResponseEntity<>(buildTaskService.create(resources),HttpStatus.CREATED);
}
@PutMapping
@Log("修改buildTask")
@ApiOperation("修改buildTask")
@PreAuthorize("@el.check('buildTask:edit')")
public ResponseEntity<Object> update(@Validated @RequestBody BuildTask resources){
buildTaskService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除buildTask")
@ApiOperation("删除buildTask")
@PreAuthorize("@el.check('buildTask:del')")
@DeleteMapping
public ResponseEntity<Object> delete(@RequestBody Integer[] ids) {
buildTaskService.deleteAll(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
}

@ -0,0 +1,116 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.zhengjie.modules.buildtask.service;
import cn.hutool.core.date.DateTime;
import me.zhengjie.modules.buildtask.domain.BuildTask;
import me.zhengjie.modules.buildtask.service.dto.BuildTaskDto;
import me.zhengjie.modules.buildtask.service.dto.BuildTaskQueryCriteria;
import org.springframework.data.domain.Pageable;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
/**
* @website https://el-admin.vip
* @description
* @author Enzo
* @date 2021-04-30
**/
public interface BuildTaskService {
/**
*
* @param criteria
* @param pageable
* @return Map<String,Object>
*/
Map<String,Object> queryAll(BuildTaskQueryCriteria criteria, Pageable pageable);
/**
*
* @param criteria
* @return List<BuildTaskDto>
*/
List<BuildTaskDto> queryAll(BuildTaskQueryCriteria criteria);
/**
* ID
* @param id ID
* @return BuildTaskDto
*/
BuildTaskDto findById(Integer id);
/**
*
* @param resources /
* @return BuildTaskDto
*/
BuildTaskDto create(BuildTask resources);
/**
*
* @param resources /
*/
void update(BuildTask resources);
/**
*
* @param ids /
*/
void deleteAll(Integer[] ids);
/**
*
* @param all
* @param response /
* @throws IOException /
*/
void download(List<BuildTaskDto> all, HttpServletResponse response) throws IOException;
/**
*
* @param recordId
* @param now
* @return
*/
BuildTask queryBuildTaskByBuildIdAndTime(Integer recordId, LocalTime now);
/**
*
* @param buildTaskId
* @return
*/
boolean updateSendBuildTaskById(Integer buildTaskId);
/**
*
* @param offsetDay
* @return
*/
List<BuildTask> getBuildTaskByTime(String offsetDay);
/**
*
* @param beginOfDay
* @param endOfDay
* @return
*/
List<BuildTask> getBuildTaskByTime(DateTime beginOfDay, DateTime endOfDay);
}

@ -0,0 +1,45 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.zhengjie.modules.buildtask.service.dto;
import lombok.Data;
import java.sql.Timestamp;
import java.io.Serializable;
/**
* @website https://el-admin.vip
* @description /
* @author Enzo
* @date 2021-04-30
**/
@Data
public class BuildTaskDto implements Serializable {
private Integer id;
private Timestamp gmtCreate;
private Timestamp gmtModified;
/** 发送id */
private Long buildId;
/** 发送时间 */
private Timestamp sendTime;
/** 发送状态 1成功 0失败 */
private Integer isSend;
}

@ -0,0 +1,37 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.zhengjie.modules.buildtask.service.dto;
import cn.hutool.core.date.DateTime;
import lombok.Data;
import me.zhengjie.annotation.Query;
import java.util.List;
/**
* @website https://el-admin.vip
* @author Enzo
* @date 2021-04-30
**/
@Data
public class BuildTaskQueryCriteria{
@Query(type = Query.Type.BETWEEN)
private List<DateTime> createTime;
}

@ -0,0 +1,131 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.zhengjie.modules.buildtask.service.impl;
import cn.hutool.core.date.DateTime;
import me.zhengjie.modules.buildtask.domain.BuildTask;
import me.zhengjie.modules.common.consts.DefaultConstant;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.buildtask.repository.BuildTaskRepository;
import me.zhengjie.modules.buildtask.service.BuildTaskService;
import me.zhengjie.modules.buildtask.service.dto.BuildTaskDto;
import me.zhengjie.modules.buildtask.service.dto.BuildTaskQueryCriteria;
import me.zhengjie.modules.buildtask.service.mapstruct.BuildTaskMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import java.time.LocalTime;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
/**
* @website https://el-admin.vip
* @description
* @author Enzo
* @date 2021-04-30
**/
@Service
@RequiredArgsConstructor
public class BuildTaskServiceImpl implements BuildTaskService {
private final BuildTaskRepository buildTaskRepository;
private final BuildTaskMapper buildTaskMapper;
@Override
public Map<String,Object> queryAll(BuildTaskQueryCriteria criteria, Pageable pageable){
Page<BuildTask> page = buildTaskRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
return PageUtil.toPage(page.map(buildTaskMapper::toDto));
}
@Override
public List<BuildTaskDto> queryAll(BuildTaskQueryCriteria criteria){
return buildTaskMapper.toDto(buildTaskRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
}
@Override
@Transactional
public BuildTaskDto findById(Integer id) {
BuildTask buildTask = buildTaskRepository.findById(id).orElseGet(BuildTask::new);
ValidationUtil.isNull(buildTask.getId(),"BuildTask","id",id);
return buildTaskMapper.toDto(buildTask);
}
@Override
@Transactional(rollbackFor = Exception.class)
public BuildTaskDto create(BuildTask resources) {
return buildTaskMapper.toDto(buildTaskRepository.save(resources));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(BuildTask resources) {
BuildTask buildTask = buildTaskRepository.findById(resources.getId()).orElseGet(BuildTask::new);
ValidationUtil.isNull( buildTask.getId(),"BuildTask","id",resources.getId());
buildTask.copy(resources);
buildTaskRepository.save(buildTask);
}
@Override
public void deleteAll(Integer[] ids) {
for (Integer id : ids) {
buildTaskRepository.deleteById(id);
}
}
@Override
public void download(List<BuildTaskDto> all, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (BuildTaskDto buildTask : all) {
Map<String,Object> map = new LinkedHashMap<>();
map.put(" gmtCreate", buildTask.getGmtCreate());
map.put(" gmtModified", buildTask.getGmtModified());
map.put("发送id", buildTask.getBuildId());
map.put("发送时间", buildTask.getSendTime());
map.put("发送状态 1成功 0失败", buildTask.getIsSend());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
@Override
public BuildTask queryBuildTaskByBuildIdAndTime(Integer recordId, LocalTime now) {
return buildTaskRepository.findBuildByRecordIdAndDate(recordId, now);
}
@Override
public boolean updateSendBuildTaskById(Integer buildTaskId) {
return buildTaskRepository.updateSendStatusById(buildTaskId) > DefaultConstant.ZERO_NUMBER;
}
@Override
public List<BuildTask> getBuildTaskByTime(String offsetDay) {
return buildTaskRepository.findBuildTaskByTime(offsetDay);
}
@Override
public List<BuildTask> getBuildTaskByTime(DateTime beginOfDay, DateTime endOfDay) {
return buildTaskRepository.findBuildTaskByTime(beginOfDay,endOfDay);
}
}

@ -0,0 +1,32 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.zhengjie.modules.buildtask.service.mapstruct;
import me.zhengjie.base.BaseMapper;
import me.zhengjie.modules.buildtask.domain.BuildTask;
import me.zhengjie.modules.buildtask.service.dto.BuildTaskDto;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
/**
* @website https://el-admin.vip
* @author Enzo
* @date 2021-04-30
**/
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface BuildTaskMapper extends BaseMapper<BuildTaskDto, BuildTask> {
}

@ -0,0 +1,52 @@
package me.zhengjie.modules.common.consts;
import com.sun.org.apache.xpath.internal.operations.Minus;
/**
* @author E
* @date
*/
public class DefaultConstant {
/**
* -1
*/
public static final int MINUS_ONE_NUMBER = -1;
/**
* 0
*/
public static final int ZERO_NUMBER = 0;
/**
* 1
*/
public static final int ONE_NUMBER = 1;
/**
* 2
*/
public static final int TWO_NUMBER = 2;
/**
* 3
*/
public static final int THREE_NUMBER = 3;
/**
* 5
*/
public static final int FIVE_NUMBER = 5;
/**
* 10
*/
public static final int TEN_NUMBER = 10;
}

@ -0,0 +1,180 @@
package me.zhengjie.modules.common.handler;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.distance.DistanceUtils;
import com.spatial4j.core.shape.Rectangle;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.buildrecord.domain.BuildRecord;
import me.zhengjie.modules.buildrecord.service.BuildRecordService;
import me.zhengjie.modules.buildrecord.service.dto.BuildRecordDto;
import me.zhengjie.modules.buildrecord.task.convert.BuildTaskQueryParamJsonConvert;
import me.zhengjie.modules.buildtask.domain.BuildTask;
import me.zhengjie.modules.buildtask.service.BuildTaskService;
import me.zhengjie.modules.buildtask.service.dto.BuildTaskDto;
import me.zhengjie.modules.common.consts.DefaultConstant;
import me.zhengjie.modules.tag.service.TagService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalTime;
import java.util.List;
/**
* @author Enzo
* @date : 2021/4/29
*/
@Component
@Slf4j
public class BuildRecordScheduled {
@Resource
private TagService tagService;
@Resource
private BuildTaskService buildTaskService;
@Resource
private BuildRecordService buildRecordService;
@Scheduled(cron = "0 0 22 * * ?")
//@Scheduled(cron = "0 0/1 * * * ?")
public void runBuildRecordTask() {
log.info("scheduled runBuildRecordTask start time [{}]", LocalTime.now());
// 获取所有开启定时任务开关
List<BuildRecord> buildRecords = buildRecordService.getBuildRecordByIsTimedTask(Boolean.TRUE);
if (!CollectionUtils.isEmpty(buildRecords)) {
for (BuildRecord record : buildRecords) {
/* 0
BuildTask buildTask = buildTaskService.queryBuildTaskByBuildIdAndTime(record.getId(), LocalTime.now());
if (buildTask == null) {*/
BuildTask buildTask = new BuildTask();
buildTask.setBuildId(record.getId());
buildTask.setIsSend(DefaultConstant.ZERO_NUMBER);
buildTask.setGmtCreate(new Timestamp(System.currentTimeMillis()));
BuildTaskDto buildTaskDto = buildTaskService.create(buildTask);
if (buildTaskDto != null) {
deleteBuildTaskAndSendBuildTask(record, buildTaskDto.getId());
}
log.info(" ========================== insert buildTask id as [{}] ===========================", buildTaskDto != null ? buildTaskDto.getId() : null);
/*}*/
}
log.info("scheduled runBuildRecordTask end time [{}] task size as [{}]", LocalTime.now(), buildRecords.size());
}
}
@Async(value = "buildTaskExecutor")
void deleteBuildTaskAndSendBuildTask(BuildRecord record, Integer buildTaskId) {
// 解析数据
BuildTaskQueryParamJsonConvert convert = getBuildTaskQueryParamJsonConvert(record.getParams());
Rectangle rectangle = null;
// 地图点进行计算,获取选点范围
Integer range = convert.getRange();
String localCode = convert.getLocalCode();
if (StringUtils.isNotBlank(localCode) && range != null) {
rectangle = calculateLocalPoint(localCode, range);
}
if (rectangle == null && StringUtils.isBlank(localCode)) {
log.error(" ====================== {please check localPoint calculate is ok ! } ==========================");
return;
}
// 删除并新增任务
boolean deleteTagByParam = tagService.deleteAndInsertTagByParam
(record.getId(), buildTaskId,
convert.getCityCode(),
convert.getStuGrade(),
rectangle);
log.info("buildRecordTask taskName as [{}] result as [{}] result time as [{}]", record.getTaskName(), deleteTagByParam, LocalTime.now());
}
@Scheduled(cron = "0 0 4 * * ?")
// @Scheduled(cron = "0 0/1 * * * ?")
public void resendBuildRecordTask() {
log.info("scheduled resendBuildRecordTask start time [{}]", LocalTime.now());
// 偏移天数
DateTime dateTime = DateUtil.offsetDay(DateUtil.date(),
DefaultConstant.MINUS_ONE_NUMBER);
// 当天开始时间
DateTime beginOfDay = DateUtil.beginOfDay(dateTime);
// 当天结束时间
DateTime endOfDay = DateUtil.endOfDay(dateTime);
// 查询前一天定时任务
List<BuildTask> buildRecords = buildTaskService.getBuildTaskByTime(beginOfDay, endOfDay);
if (!CollectionUtils.isEmpty(buildRecords)) {
for (BuildTask task : buildRecords) {
if (task.getBuildId() != null) {
BuildRecordDto buildRecordDto = buildRecordService.findById(task.getBuildId());
if (buildRecordDto != null) {
resendDeleteBuildTaskAndSendBuildTask(buildRecordDto, task.getId());
}
log.info(" ========================== insert resendBuildRecordTask id as [{}] ===========================", buildRecordDto != null ? buildRecordDto.getId() : null);
}
}
log.info("scheduled runBuildRecordTask end time [{}] task size as [{}]", LocalTime.now(), buildRecords.size());
}
}
private Rectangle calculateLocalPoint(String localCode, Integer range) {
// 处理切割横纵坐标字符串
String[] split = StringUtils.split(localCode.trim(), StrUtil.COMMA);
if (split.length != DefaultConstant.TWO_NUMBER) {
return null;
}
// 转换类型
double x = Double.parseDouble(split[0]);
double y = Double.parseDouble(split[1]);
// 坐标计算
SpatialContext geo = SpatialContext.GEO;
return geo.getDistCalc().
calcBoxByDistFromPt
(geo.makePoint(x, y),
range * DistanceUtils.KM_TO_DEG,
geo, null);
}
@Async(value = "resendBuildTaskExecutor")
void resendDeleteBuildTaskAndSendBuildTask(BuildRecordDto record, Integer buildTaskId) {
BuildTaskQueryParamJsonConvert convert = getBuildTaskQueryParamJsonConvert(record.getParams());
Rectangle rectangle = null;
// 地图点进行计算,获取选点范围
Integer range = convert.getRange();
String localCode = convert.getLocalCode();
if (StringUtils.isNotBlank(localCode) && range != null) {
rectangle = calculateLocalPoint(localCode, range);
}
if (rectangle == null && StringUtils.isNotBlank(localCode)) {
log.error(" ====================== {please check localPoint calculate is ok ! } ==========================");
return;
}
// 删除并新增任务
boolean deleteTagByParam = tagService.deleteAndInsertTagByParam
(record.getId(), buildTaskId,
convert.getCityCode(),
convert.getStuGrade(), rectangle);
log.info("buildRecordTask taskName as [{}] result as [{}] result time as [{}]", record.getTaskName(), deleteTagByParam, LocalTime.now());
}
private BuildTaskQueryParamJsonConvert getBuildTaskQueryParamJsonConvert(String params) {
// 解析数据
JSONObject jsonObject1 =
JSONUtil.parseObj(params, true);
// 构建解析类对Json进行解析
return JSONUtil.toBean(jsonObject1, BuildTaskQueryParamJsonConvert.class);
}
}

@ -15,14 +15,15 @@
*/
package me.zhengjie.modules.remoterec.domain;
import lombok.Data;
import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.ApiModelProperty;
import cn.hutool.core.bean.copier.CopyOptions;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.sql.Timestamp;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.List;
/**
* @website https://el-admin.vip
@ -85,7 +86,19 @@ public class RemoteRecord implements Serializable {
@ApiModelProperty(value = "短信链接")
private String linkUrl;
@Column(name = "level")
@ApiModelProperty(value = "等级")
private Integer level;
@Column(name = "parent_id")
@ApiModelProperty(value = "父类id")
private Integer parentId;
@Transient
@ApiModelProperty(value = "子类集合")
private List<RemoteRecord> children;
public void copy(RemoteRecord source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
}
}

@ -18,6 +18,9 @@ package me.zhengjie.modules.remoterec.repository;
import me.zhengjie.modules.remoterec.domain.RemoteRecord;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
/**
* @website https://el-admin.vip
@ -25,4 +28,29 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
* @date 2021-01-07
**/
public interface RemoteRecordRepository extends JpaRepository<RemoteRecord, Integer>, JpaSpecificationExecutor<RemoteRecord> {
}
/**
*
* @param operation
* @return
*/
@Query(value = "select r from RemoteRecord r where r.operation = ?1")
List<RemoteRecord> findByOperation(String operation);
/**
* MySQL
* @return
*/
@Query(value = "SELECT DISTINCT operation FROM tb_remote_record", nativeQuery = true)
List<String> findRecordByOperation();
/**
*
* @param level
* @return
*/
List<RemoteRecord> findByLevel(Integer level);
}

@ -15,6 +15,9 @@
*/
package me.zhengjie.modules.remoterec.rest;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.common.http.CommonResponse;
@ -25,16 +28,16 @@ import me.zhengjie.modules.remoterec.service.dto.RemoteRecordQueryCriteria;
import me.zhengjie.modules.remoterec.task.DownloadSFTPFileTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;
/**
* @website https://el-admin.vip
@ -116,4 +119,20 @@ public class RemoteRecordController {
remoteRecordService.deleteAll(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
}
@Log("生成一级上传目录")
@ApiOperation("生成一级上传目录")
@PostMapping("createRemoteRecord")
public ResponseEntity<Object> createFirstLevel() {
remoteRecordService.createRecord();
return new ResponseEntity<>(HttpStatus.OK);
}
@GetMapping("/getRemoteList")
@Log("根据等级查询RemoteList")
@ApiOperation("根据等级查询RemoteList")
@PreAuthorize("@el.check('remoteRecord:list')")
public ResponseEntity<List<RemoteRecord>> remoteList(Integer level) {
return new ResponseEntity<>(remoteRecordService.queryRemoteListByLevel(level), HttpStatus.OK);
}
}

@ -19,10 +19,11 @@ import me.zhengjie.modules.remoterec.domain.RemoteRecord;
import me.zhengjie.modules.remoterec.service.dto.RemoteRecordDto;
import me.zhengjie.modules.remoterec.service.dto.RemoteRecordQueryCriteria;
import org.springframework.data.domain.Pageable;
import java.util.Map;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* @website https://el-admin.vip
@ -80,4 +81,23 @@ public interface RemoteRecordService {
* @throws IOException /
*/
void download(List<RemoteRecordDto> all, HttpServletResponse response) throws IOException;
}
/**
*
* @param operation
*/
void createRecordByOperation(String operation);
/**
*
*/
void createRecord();
/**
*
* @param level
* @return
*/
List<RemoteRecord> queryRemoteListByLevel(Integer level);
}

@ -16,8 +16,10 @@
package me.zhengjie.modules.remoterec.service.dto;
import lombok.Data;
import java.sql.Timestamp;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.List;
/**
* @website https://el-admin.vip
@ -49,9 +51,18 @@ public class RemoteRecordDto implements Serializable {
/** 权重值 */
private Integer weight;
/** 元洪城呢个上传任务的名称*/
/** c远端上传任务的名称*/
private String uploadRemoteTaskName;
/* 成功上穿的數量 **/
/** 成功上传的数量 */
private Long successSendCount;
}
/** 等级*/
private Integer level;
/** 父类id*/
private Integer parentId;
/** 子类集合 */
private List<RemoteRecordDto> children;
}

@ -32,10 +32,23 @@ public class RemoteRecordQueryCriteria{
@Query(type = Query.Type.INNER_LIKE)
private String operation;
/** 精确 */
@Query
private Integer tag;
/** 父类id*/
@Query(type = Query.Type.EQUAL)
private Integer parentId;
/** 等级*/
@Query(type = Query.Type.EQUAL)
private Integer level;
@Query(type = Query.Type.EQUAL)
private Boolean flag;
/** BETWEEN */
@Query(type = Query.Type.BETWEEN)
private List<Timestamp> uploadTime;
}
}

@ -1,77 +1,108 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.zhengjie.modules.remoterec.service.impl;
import me.zhengjie.modules.remoterec.domain.RemoteRecord;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.common.consts.DefaultConstant;
import me.zhengjie.modules.remoterec.domain.RemoteRecord;
import me.zhengjie.modules.remoterec.repository.RemoteRecordRepository;
import me.zhengjie.modules.remoterec.service.RemoteRecordService;
import me.zhengjie.modules.remoterec.service.dto.RemoteRecordDto;
import me.zhengjie.modules.remoterec.service.dto.RemoteRecordQueryCriteria;
import me.zhengjie.modules.remoterec.service.mapstruct.RemoteRecordMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @website https://el-admin.vip
* @description
* @author x
* @date 2021-01-07
**/
* @author x
* @website https://el-admin.vip
* @description
* @date 2021-01-07
**/
@Slf4j
@Service
@RequiredArgsConstructor
public class RemoteRecordServiceImpl implements RemoteRecordService {
private final RemoteRecordRepository remoteRecordRepository;
private final RemoteRecordMapper remoteRecordMapper;
@Override
public Map<String,Object> queryAll(RemoteRecordQueryCriteria criteria, Pageable pageable){
Page<RemoteRecord> page = remoteRecordRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
public Map<String, Object> queryAll(RemoteRecordQueryCriteria criteria, Pageable pageable) {
criteria.setParentId(DefaultConstant.ZERO_NUMBER);
if (criteria.getFlag() != null && !criteria.getFlag()) {
criteria.setParentId(null);
criteria.setLevel(DefaultConstant.THREE_NUMBER);
}
// 无实体对应 赋初始值
criteria.setFlag(null);
Page<RemoteRecord> page = remoteRecordRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
List<RemoteRecord> all = remoteRecordRepository.findAll();
page.getContent().forEach
(buildRecord ->
buildRecord.setChildren
(getChildren(buildRecord, all)));
return PageUtil.toPage(page.map(remoteRecordMapper::toDto));
}
@Override
public List<RemoteRecordDto> queryAll(RemoteRecordQueryCriteria criteria){
return remoteRecordMapper.toDto(remoteRecordRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
public List<RemoteRecordDto> queryAll(RemoteRecordQueryCriteria criteria) {
return remoteRecordMapper.toDto(remoteRecordRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
}
@Override
@Transactional
public RemoteRecordDto findById(Integer id) {
RemoteRecord remoteRecord = remoteRecordRepository.findById(id).orElseGet(RemoteRecord::new);
ValidationUtil.isNull(remoteRecord.getId(),"RemoteRecord","id",id);
ValidationUtil.isNull(remoteRecord.getId(), "RemoteRecord", "id", id);
return remoteRecordMapper.toDto(remoteRecord);
}
@Override
@Transactional(rollbackFor = Exception.class)
public RemoteRecordDto create(RemoteRecord resources) {
// 上传记录
if (resources.getParentId() != null) {
RemoteRecord remoteRecord = remoteRecordRepository.findById(resources.getParentId()).orElseGet(RemoteRecord::new);
resources.setWeight(DefaultConstant.ONE_NUMBER);
resources.setOperation(remoteRecord.getOperation() + StrUtil.UNDERLINE + resources.getUploadRemoteTaskName());
resources.setLocalSavePath(remoteRecord.getOperation());
resources.setUploadRemoteTaskName(remoteRecord.getOperation());
resources.setFileTransSuccessCount(DefaultConstant.ZERO_NUMBER);
resources.setUploadTime(new Timestamp(System.currentTimeMillis()));
}
return remoteRecordMapper.toDto(remoteRecordRepository.save(resources));
}
@ -79,7 +110,7 @@ public class RemoteRecordServiceImpl implements RemoteRecordService {
@Transactional(rollbackFor = Exception.class)
public void update(RemoteRecord resources) {
RemoteRecord remoteRecord = remoteRecordRepository.findById(resources.getId()).orElseGet(RemoteRecord::new);
ValidationUtil.isNull( remoteRecord.getId(),"RemoteRecord","id",resources.getId());
ValidationUtil.isNull(remoteRecord.getId(), "RemoteRecord", "id", resources.getId());
remoteRecord.copy(resources);
remoteRecordRepository.save(remoteRecord);
}
@ -95,7 +126,7 @@ public class RemoteRecordServiceImpl implements RemoteRecordService {
public void download(List<RemoteRecordDto> all, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (RemoteRecordDto remoteRecord : all) {
Map<String,Object> map = new LinkedHashMap<>();
Map<String, Object> map = new LinkedHashMap<>();
map.put("上传时间", remoteRecord.getUploadTime());
map.put("上传人/公司", remoteRecord.getOperation());
map.put("成功保存数量", remoteRecord.getFileTransSuccessCount());
@ -106,4 +137,58 @@ public class RemoteRecordServiceImpl implements RemoteRecordService {
}
FileUtil.downloadExcel(list, response);
}
}
@Override
public void createRecordByOperation(String operation) {
List<RemoteRecord> remoteRecordList = remoteRecordRepository.findByOperation(operation);
log.info("remoteRecordList size as [{}]", remoteRecordList.size());
// 为空进行插入
if (CollectionUtils.isEmpty(remoteRecordList)) {
RemoteRecord remoteRecord = new RemoteRecord();
remoteRecord.setOperation(operation);
remoteRecord.setLocalSavePath(operation);
remoteRecord.setUploadRemoteTaskName(operation);
remoteRecord.setLevel(DefaultConstant.ONE_NUMBER);
remoteRecord.setWeight(DefaultConstant.ONE_NUMBER);
remoteRecord.setParentId(DefaultConstant.ZERO_NUMBER);
remoteRecord.setFileTransSuccessCount(DefaultConstant.ZERO_NUMBER);
remoteRecord.setUploadTime(new Timestamp(System.currentTimeMillis()));
remoteRecordRepository.save(remoteRecord);
log.info("Save remoteRecord operation [{}]", operation);
}
}
@Override
public void createRecord() {
List<String> remoteRecordsList = remoteRecordRepository.findRecordByOperation();
for (String operation : remoteRecordsList) {
String[] split = operation.split(StrUtil.UNDERLINE);
if (split.length > DefaultConstant.ZERO_NUMBER) {
// 保存记录
createRecordByOperation(split[0]);
}
}
}
@Override
public List<RemoteRecord> queryRemoteListByLevel(Integer level) {
return remoteRecordRepository.findByLevel(level);
}
/**
*
*/
private List<RemoteRecord> getChildren(RemoteRecord remoteRecord, List<RemoteRecord> all) {
return all.stream().
// 过滤
filter(record -> record.getParentId() != null && record.getParentId().equals(remoteRecord.getId()))
.peek(record -> {
// 设置子节点
List<RemoteRecord> children = getChildren(record, all);
record.setChildren(children != null ? children : new ArrayList<>());
})
.collect(Collectors.toList());
}
}

@ -1,22 +1,14 @@
package me.zhengjie.modules.remoterec.task;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Timestamp;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ssh.JschUtil;
import cn.hutool.extra.ssh.Sftp;
import cn.hutool.system.OsInfo;
import cn.hutool.system.SystemUtil;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.buildrecord.domain.BuildRecord;
import me.zhengjie.modules.buildrecord.service.BuildRecordService;
import me.zhengjie.modules.buildrecord.service.dto.BuildRecordDto;
import me.zhengjie.modules.common.consts.DefaultConstant;
import me.zhengjie.modules.remoterec.domain.RemoteRecord;
import me.zhengjie.modules.remoterec.service.RemoteRecordService;
import me.zhengjie.modules.remoterec.service.dto.RemoteRecordDto;
@ -30,6 +22,9 @@ import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
@ -85,6 +80,7 @@ public class DownloadSFTPFileTask {
}
private void runTask(RemoteRecord resources) {
remoteRecordService.createRecordByOperation(resources.getOperation());
resources.setOperation(resources.getOperation() + FILE_NAME_SPLIT + resources.getUploadRemoteTaskName());
// 更新一条记录,然后状态为待取回状态
RemoteRecordDto remoteRecordDto = remoteRecordService.create(resources);
@ -117,9 +113,9 @@ public class DownloadSFTPFileTask {
remoteRecord.setTag(READY_TAG);
remoteRecord.setLocalSavePath(resources.getLocalSavePath());
remoteRecord.setWeight(0);
remoteRecord.setWeight(DefaultConstant.ZERO_NUMBER);
remoteRecord.setLevel(DefaultConstant.THREE_NUMBER);
remoteRecord.setUploadRemoteTaskName(resources.getUploadRemoteTaskName());
remoteRecordService.update(remoteRecord);
// sftp.close();

@ -119,6 +119,8 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.antMatchers("/druid/**").permitAll()
// 放行OPTIONS请求
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
// 放开生成一级分类链接
.antMatchers(HttpMethod.POST, "/api/remoteRecord/createRemoteRecord").permitAll()
// 自定义匿名访问所有url放行允许匿名和带Token访问细腻化到每个 Request 类型
// GET
.antMatchers(HttpMethod.GET, anonymousUrls.get(RequestMethodEnum.GET.getType()).toArray(new String[0])).permitAll()

@ -125,4 +125,16 @@ public interface TagService {
* @return
*/
Long countSendSum(Long taskId, Integer pushStatus);
}
/**
*
* @param id
* @param buildTaskId
* @param cityCode
* @param stuGrade
* @param rectangle
* @return
*/
boolean deleteAndInsertTagByParam(Integer id, Integer buildTaskId, List<Integer> cityCode, List<Integer> stuGrade, Rectangle rectangle);
}

@ -17,37 +17,39 @@ package me.zhengjie.modules.tag.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import com.spatial4j.core.shape.Rectangle;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.student.domain.Student;
import me.zhengjie.common.http.ResponseCode;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.buildtask.service.BuildTaskService;
import me.zhengjie.modules.common.consts.DefaultConstant;
import me.zhengjie.modules.school.repository.SchoolRepository;
import me.zhengjie.modules.tag.domain.Tag;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.tag.repository.TagRepository;
import me.zhengjie.modules.tag.service.TagService;
import me.zhengjie.modules.tag.service.dto.TagDto;
import me.zhengjie.modules.tag.service.dto.TagQueryCriteria;
import me.zhengjie.modules.tag.service.mapstruct.TagMapper;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.CollectionUtils;
import java.math.BigInteger;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TemporalType;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
/**
* @website https://el-admin.vip
@ -55,14 +57,15 @@ import javax.servlet.http.HttpServletResponse;
* @author x
* @date 2020-09-22
**/
@Slf4j
@Service
@RequiredArgsConstructor
@Slf4j
public class TagServiceImpl implements TagService {
@Value("${tag.split-table.sum}")
private Integer tableSum;
private final BuildTaskService buildTaskService;
private final TagRepository tagRepository;
private final TagMapper tagMapper;
@ -181,7 +184,6 @@ public class TagServiceImpl implements TagService {
insertSql.append(" ORDER BY RAND()");
//创建本地sql查询实例
Query dataQuery = entityManager.createNativeQuery(insertSql.toString());
log.info("========================== [insertSql is {} ] ==========================", insertSql.toString());
// 设置参数
if (CollectionUtil.isNotEmpty(stuGrade)){
dataQuery.setParameter("stuGrade", stuGrade);
@ -219,4 +221,72 @@ public class TagServiceImpl implements TagService {
public Long countSendSum(Long taskId, Integer pushStatus) {
return tagRepository.countByTaskIdAndPushStatus(taskId, pushStatus);
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean deleteAndInsertTagByParam(Integer id, Integer buildTaskId, List<Integer> cityCode, List<Integer> stuGrade, Rectangle rectangle) {
// 获取分表下标
int resultId = id % tableSum;
String deleteStr =
"DELETE FROM dc_tag" + resultId
+ " WHERE task_id = :id";
Query deleteQuery = entityManager.createNativeQuery(deleteStr);
deleteQuery.setParameter("id", id);
// 执行删除任务
int updateResult = deleteQuery.executeUpdate();
if (updateResult > DefaultConstant.ZERO_NUMBER) {
// 执行插入条件
StringBuilder insertSql = new StringBuilder();
insertSql.append("INSERT INTO dc_tag")
.append(resultId)
.append(" (uid, task_id, push_status) SELECT e.uid, ")
.append(id)
.append(", 0 FROM dc_school s JOIN dc_edu e ON s.oldid = e.mid ");
// 拼接where条件
StringBuilder whereSql = new StringBuilder(" WHERE 1 = 1");
// 年级
if (!CollectionUtils.isEmpty(stuGrade)) {
whereSql.append(" AND e.level IN (:stuGrade)");
}
// 城市ID
if (!CollectionUtils.isEmpty(cityCode)) {
whereSql.append(" AND s.city_code IN (:cityCode)");
}
// 坐标
if (Objects.nonNull(rectangle)) {
whereSql.append(" AND s.lng >= :minX AND s.lng < :maxX AND s.lat >= :minY AND s.lat < :maxY ");
}
// 拼接成完整sql
insertSql.append(whereSql);
// 拼接乱序
insertSql.append(" ORDER BY RAND()");
//创建本地sql查询实例
Query dataQuery = entityManager.createNativeQuery(insertSql.toString());
// 设置参数
if (!CollectionUtils.isEmpty(stuGrade)) {
dataQuery.setParameter("stuGrade", stuGrade);
}
if (!CollectionUtils.isEmpty(cityCode)) {
dataQuery.setParameter("cityCode", cityCode);
}
if (Objects.nonNull(rectangle)) {
// 经度范围
dataQuery.setParameter("minX", rectangle.getMinX());
dataQuery.setParameter("maxX", rectangle.getMaxX());
// 纬度范围
dataQuery.setParameter("minY", rectangle.getMinY());
dataQuery.setParameter("maxY", rectangle.getMaxY());
}
// 返回执行结果
boolean resultFlag = dataQuery.executeUpdate() > DefaultConstant.ZERO_NUMBER;
if (!resultFlag) {
log.error(" buildTask delete success but insert fail manual exception");
throw new BadRequestException(ResponseCode.TASK_ERROR.getDesc());
}
// 更新发送状态
return buildTaskService.updateSendBuildTaskById(buildTaskId);
}
return Boolean.FALSE;
}
}

@ -26,6 +26,7 @@ import javax.persistence.Table;
import org.hibernate.annotations.*;
import java.sql.Timestamp;
import java.io.Serializable;
import java.util.List;
/**
* @website https://el-admin.vip
@ -98,7 +99,21 @@ public class TaskRecord implements Serializable {
@ApiModelProperty(value = "任务推送ID")
private Long taskPushId;
@Column(name = "level")
@ApiModelProperty(value = "等级")
private Integer level;
@Column(name = "parent_id")
@ApiModelProperty(value = "父类id")
private Integer parentId;
@Transient
@ApiModelProperty(value = "父类id")
private List<TaskRecord> children;
public void copy(TaskRecord source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
}
}

@ -18,13 +18,23 @@ package me.zhengjie.modules.taskrecord.repository;
import me.zhengjie.modules.taskrecord.domain.TaskRecord;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @website https://el-admin.vip
* @author x
* @date 2020-09-09
**/
@Repository
public interface TaskRecordRepository extends JpaRepository<TaskRecord, Integer>, JpaSpecificationExecutor<TaskRecord> {
/**
*
* @param parentId
* @return
*/
List<TaskRecord> findByParentId(Long parentId);
}
}

@ -18,6 +18,7 @@ package me.zhengjie.modules.taskrecord.service.dto;
import lombok.Data;
import java.sql.Timestamp;
import java.io.Serializable;
import java.util.List;
/**
* @website https://el-admin.vip
@ -70,4 +71,7 @@ public class TaskRecordDto implements Serializable {
* ID
*/
private Long taskPushId;
}
/*** 子数据*/
private List<TaskRecordDto> children;
}

@ -46,4 +46,7 @@ public class TaskRecordQueryCriteria{
/** 精确 */
@Query
private String oprationName;
}
@Query
private Long parentId;
}

@ -1,18 +1,18 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.zhengjie.modules.taskrecord.service.impl;
import me.zhengjie.modules.taskrecord.domain.TaskRecord;
@ -36,13 +36,14 @@ import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.stream.Collectors;
/**
* @website https://el-admin.vip
* @description
* @author x
* @date 2020-09-09
**/
* @author x
* @website https://el-admin.vip
* @description
* @date 2020-09-09
**/
@Service
@RequiredArgsConstructor
public class TaskRecordServiceImpl implements TaskRecordService {
@ -51,26 +52,34 @@ public class TaskRecordServiceImpl implements TaskRecordService {
private final TaskRecordMapper taskRecordMapper;
@Override
public Map<String,Object> queryAll(TaskRecordQueryCriteria criteria, Pageable pageable){
Page<TaskRecord> page = taskRecordRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
public Map<String, Object> queryAll(TaskRecordQueryCriteria criteria, Pageable pageable) {
// 查询出一级
criteria.setParentId(0L);
Page<TaskRecord> page =
taskRecordRepository.findAll
((root, criteriaQuery, criteriaBuilder) ->
QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
// 找出所有
List<TaskRecord> all = taskRecordRepository.findAll();
page.getContent().stream().peek(taskRecord -> taskRecord.setChildren(getChildrens(taskRecord, all))).collect(Collectors.toList());
return PageUtil.toPage(page.map(taskRecordMapper::toDto));
}
@Override
public List<TaskRecordDto> queryAll(TaskRecordQueryCriteria criteria){
return taskRecordMapper.toDto(taskRecordRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
public List<TaskRecordDto> queryAll(TaskRecordQueryCriteria criteria) {
return taskRecordMapper.toDto(taskRecordRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
}
@Override
@Transactional
public TaskRecordDto findById(Integer id) {
TaskRecord taskRecord = taskRecordRepository.findById(id).orElseGet(TaskRecord::new);
ValidationUtil.isNull(taskRecord.getId(),"TaskRecord","id",id);
ValidationUtil.isNull(taskRecord.getId(), "TaskRecord", "id", id);
return taskRecordMapper.toDto(taskRecord);
}
@Override
@Transactional(rollbackFor = Exception.class)
public TaskRecordDto create(TaskRecord resources) {
@ -83,7 +92,7 @@ public class TaskRecordServiceImpl implements TaskRecordService {
@Transactional(rollbackFor = Exception.class)
public TaskRecord update(TaskRecord resources) {
TaskRecord taskRecord = taskRecordRepository.findById(resources.getId()).orElseGet(TaskRecord::new);
ValidationUtil.isNull( taskRecord.getId(),"TaskRecord","id",resources.getId());
ValidationUtil.isNull(taskRecord.getId(), "TaskRecord", "id", resources.getId());
taskRecord.copy(resources);
return taskRecordRepository.save(taskRecord);
}
@ -99,7 +108,7 @@ public class TaskRecordServiceImpl implements TaskRecordService {
public void download(List<TaskRecordDto> all, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (TaskRecordDto taskRecord : all) {
Map<String,Object> map = new LinkedHashMap<>();
Map<String, Object> map = new LinkedHashMap<>();
map.put("创建时间", taskRecord.getGmtCreate());
map.put("修改时间", taskRecord.getGmtModified());
map.put("任务名称", taskRecord.getTaskName());
@ -116,4 +125,14 @@ public class TaskRecordServiceImpl implements TaskRecordService {
}
FileUtil.downloadExcel(list, response);
}
}
/**
*
*/
private List<TaskRecord> getChildrens(TaskRecord taskRecord, List<TaskRecord> all) {
return all.stream().filter(categoryEntity -> categoryEntity.getParentId().equals(taskRecord.getId())).peek(categoryEntity -> {
//1、找到子任务
categoryEntity.setChildren(getChildrens(categoryEntity, all));
}).collect(Collectors.toList());
}
}

@ -218,6 +218,11 @@ remoteRec:
maxPoolSize: 16
queueCapacity: 3
ThreadNamePrefix: 'RemoteRecTaskExecutor-'
buildRecord:
task:
thread_pool:
corePoolSize: 4
queueCapacity: 3
# 增加日志相关的配置
logging:
level:
@ -237,4 +242,4 @@ remote:
address: 'http://localhost:8000/api/temp/file/download'
file-base-path-linux: /home/eladmin/file/temp/
file-base-path-windows: C:\eladmin\file\temp\
file-base-path-mac: ~/file/eladmin/temp/
file-base-path-mac: ~/file/eladmin/temp/

@ -173,6 +173,13 @@ remoteRec:
maxPoolSize: 16
queueCapacity: 3
ThreadNamePrefix: 'RemoteRecTaskExecutor-'
buildRecord:
task:
thread_pool:
corePoolSize: 4
maxPoolSize: 50
queueCapacity: 3
# 增加日志相关的配置
logging:
level:
@ -192,4 +199,4 @@ remote:
address: 'http://118.178.137.129:8000/api/temp/file/download'
file-base-path-linux: /home/eladmin/file/temp/
file-base-path-windows: C:\eladmin\file\temp\
file-base-path-mac: ~/file/eladmin/temp/
file-base-path-mac: ~/file/eladmin/temp/

@ -215,6 +215,12 @@ remoteRec:
maxPoolSize: 16
queueCapacity: 3
ThreadNamePrefix: 'RemoteRecTaskExecutor-'
buildRecord:
task:
thread_pool:
corePoolSize: 4
maxPoolSize: 50
queueCapacity: 3
# 增加日志相关的配置
logging:
level:
@ -234,4 +240,4 @@ remote:
address: 'http://116.62.197.152:8000/api/temp/file/download'
file-base-path-linux: /home/eladmin/file/temp/
file-base-path-windows: C:\eladmin\file\temp\
file-base-path-mac: ~/file/eladmin/temp/
file-base-path-mac: ~/file/eladmin/temp/

@ -219,6 +219,12 @@ remoteRec:
maxPoolSize: 16
queueCapacity: 3
ThreadNamePrefix: 'RemoteRecTaskExecutor-'
buildRecord:
task:
thread_pool:
corePoolSize: 4
maxPoolSize: 50
queueCapacity: 3
# 增加日志相关的配置
logging:
level:

@ -1,19 +1,104 @@
package me.zhengjie;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.sun.org.apache.bcel.internal.generic.NEW;
import me.zhengjie.modules.buildrecord.domain.BuildRecord;
import me.zhengjie.modules.buildrecord.repository.BuildRecordRepository;
import me.zhengjie.modules.buildrecord.rest.vo.BuildRecordBuildVO;
import me.zhengjie.modules.buildrecord.service.BuildRecordService;
import me.zhengjie.modules.buildrecord.service.dto.BuildRecordDto;
import me.zhengjie.modules.buildrecord.task.ProduceBigDataTask;
import me.zhengjie.modules.edu.domain.Edu;
import me.zhengjie.modules.edu.service.EduService;
import me.zhengjie.modules.school.domain.School;
import me.zhengjie.modules.school.service.SchoolService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Random;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class EladminSystemApplicationTests {
@Autowired
private SchoolService schoolService;
@Autowired
private BuildRecordService buildRecordService;
@Autowired
private ProduceBigDataTask produceBigDataTask;
@Autowired
private BuildRecordRepository buildRecordRepository;
@Autowired
private EduService eduService;
@Test
public void contextLoads() {
}
public static void main(String[] args) {
}
@Test
public void insertBuildRecord(){
for (int i = 0; i < 10; i++) {
School school = new School();
int oldId = RandomUtil.randomInt(4);
school.setCityCode(RandomUtil.randomInt(4));
school.setLng(randomLonLat(105,125,25,50,"Lon"));
school.setLat(randomLonLat(105,125,25,50,""));
school.setOldid(oldId);
school.setType(1);
schoolService.create(school);
Edu edu = new Edu();
edu.setLevel(i + 1);
edu.setMid(oldId);
edu.setUid(Base64.encode(RandomUtil.randomNumbers(11)));
eduService.create(edu);
}
}
@Test
public void insertTag(){
BuildRecord buildRecord = new BuildRecord();
buildRecord.setTaskName("商圈珠江中路" + StrUtil.UNDERLINE);
buildRecord.setTimePeriod(100);
buildRecord.setIsBuild(1);
buildRecord.setDescription("11.4");
buildRecord.setParams("{\"stuGrade\":[\"4\",\"5\",\"6\",\"7\",\"8\",\"9\"],\"cityCode\":[3205],\"localCode\":\"110.979626,36.38156\",\"range\":\"3\"}");
buildRecord.setTotal(2000L);
buildRecord.setLevel(3);
buildRecord.setParentId(99);
buildRecord.setIsTimedTask(true);
// produceBigDataTask.runTask(buildRecord);
}
public static String randomLonLat(double MinLon, double MaxLon, double MinLat, double MaxLat, String type) {
BigDecimal db = new BigDecimal(Math.random() * (MaxLon - MinLon) + MinLon);
String lon = db.setScale(6, BigDecimal.ROUND_HALF_UP).toString();// 小数后6位
db = new BigDecimal(Math.random() * (MaxLat - MinLat) + MinLat);
String lat = db.setScale(6, BigDecimal.ROUND_HALF_UP).toString();
if (type.equals("Lon")) {
return lon;
} else {
return lat;
}
}
}

Loading…
Cancel
Save