Commit 7c35a79c authored by ZhengJie's avatar ZhengJie
Browse files

[新增功能](el-admin v2.5): v2.5 beta

详情 https://www.ydyno.com/archives/1225.html
parent d35ffc9d
/*
* 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.system.service.dto; package me.zhengjie.modules.system.service.dto;
import lombok.Data; import lombok.Data;
......
/*
* 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.system.service.impl; package me.zhengjie.modules.system.service.impl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException; import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.Dept; import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.service.dto.DeptDto; import me.zhengjie.modules.system.service.dto.DeptDto;
...@@ -27,19 +43,14 @@ import java.util.stream.Collectors; ...@@ -27,19 +43,14 @@ import java.util.stream.Collectors;
* @date 2019-03-25 * @date 2019-03-25
*/ */
@Service @Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "dept") @CacheConfig(cacheNames = "dept")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class) @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DeptServiceImpl implements DeptService { public class DeptServiceImpl implements DeptService {
private final DeptRepository deptRepository; private final DeptRepository deptRepository;
private final DeptMapper deptMapper; private final DeptMapper deptMapper;
public DeptServiceImpl(DeptRepository deptRepository, DeptMapper deptMapper) {
this.deptRepository = deptRepository;
this.deptMapper = deptMapper;
}
@Override @Override
@Cacheable @Cacheable
public List<DeptDto> queryAll(DeptQueryCriteria criteria) { public List<DeptDto> queryAll(DeptQueryCriteria criteria) {
......
/*
* 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.system.service.impl; package me.zhengjie.modules.system.service.impl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.domain.DictDetail; import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.service.dto.DictDetailQueryCriteria; import me.zhengjie.modules.system.service.dto.DictDetailQueryCriteria;
import me.zhengjie.utils.PageUtil; import me.zhengjie.utils.PageUtil;
...@@ -24,19 +40,14 @@ import java.util.Map; ...@@ -24,19 +40,14 @@ import java.util.Map;
* @date 2019-04-10 * @date 2019-04-10
*/ */
@Service @Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "dictDetail") @CacheConfig(cacheNames = "dictDetail")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class) @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DictDetailServiceImpl implements DictDetailService { public class DictDetailServiceImpl implements DictDetailService {
private final DictDetailRepository dictDetailRepository; private final DictDetailRepository dictDetailRepository;
private final DictDetailMapper dictDetailMapper; private final DictDetailMapper dictDetailMapper;
public DictDetailServiceImpl(DictDetailRepository dictDetailRepository, DictDetailMapper dictDetailMapper) {
this.dictDetailRepository = dictDetailRepository;
this.dictDetailMapper = dictDetailMapper;
}
@Override @Override
@Cacheable @Cacheable
public Map<String,Object> queryAll(DictDetailQueryCriteria criteria, Pageable pageable) { public Map<String,Object> queryAll(DictDetailQueryCriteria criteria, Pageable pageable) {
......
/*
* 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.system.service.impl; package me.zhengjie.modules.system.service.impl;
import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.collection.CollectionUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.domain.Dict; import me.zhengjie.modules.system.domain.Dict;
import me.zhengjie.modules.system.service.dto.DictDetailDto; import me.zhengjie.modules.system.service.dto.DictDetailDto;
import me.zhengjie.modules.system.service.dto.DictQueryCriteria; import me.zhengjie.modules.system.service.dto.DictQueryCriteria;
...@@ -20,7 +36,6 @@ import org.springframework.data.domain.Pageable; ...@@ -20,7 +36,6 @@ import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.*;
...@@ -30,19 +45,14 @@ import java.util.*; ...@@ -30,19 +45,14 @@ import java.util.*;
* @date 2019-04-10 * @date 2019-04-10
*/ */
@Service @Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "dict") @CacheConfig(cacheNames = "dict")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class) @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DictServiceImpl implements DictService { public class DictServiceImpl implements DictService {
private final DictRepository dictRepository; private final DictRepository dictRepository;
private final DictMapper dictMapper; private final DictMapper dictMapper;
public DictServiceImpl(DictRepository dictRepository, DictMapper dictMapper) {
this.dictRepository = dictRepository;
this.dictMapper = dictMapper;
}
@Override @Override
@Cacheable @Cacheable
public Map<String, Object> queryAll(DictQueryCriteria dict, Pageable pageable){ public Map<String, Object> queryAll(DictQueryCriteria dict, Pageable pageable){
...@@ -98,7 +108,7 @@ public class DictServiceImpl implements DictService { ...@@ -98,7 +108,7 @@ public class DictServiceImpl implements DictService {
for (DictDetailDto dictDetail : dictDTO.getDictDetails()) { for (DictDetailDto dictDetail : dictDTO.getDictDetails()) {
Map<String,Object> map = new LinkedHashMap<>(); Map<String,Object> map = new LinkedHashMap<>();
map.put("字典名称", dictDTO.getName()); map.put("字典名称", dictDTO.getName());
map.put("字典描述", dictDTO.getRemark()); map.put("字典描述", dictDTO.getDescription());
map.put("字典标签", dictDetail.getLabel()); map.put("字典标签", dictDetail.getLabel());
map.put("字典值", dictDetail.getValue()); map.put("字典值", dictDetail.getValue());
map.put("创建日期", dictDetail.getCreateTime()); map.put("创建日期", dictDetail.getCreateTime());
...@@ -107,7 +117,7 @@ public class DictServiceImpl implements DictService { ...@@ -107,7 +117,7 @@ public class DictServiceImpl implements DictService {
} else { } else {
Map<String,Object> map = new LinkedHashMap<>(); Map<String,Object> map = new LinkedHashMap<>();
map.put("字典名称", dictDTO.getName()); map.put("字典名称", dictDTO.getName());
map.put("字典描述", dictDTO.getRemark()); map.put("字典描述", dictDTO.getDescription());
map.put("字典标签", null); map.put("字典标签", null);
map.put("字典值", null); map.put("字典值", null);
map.put("创建日期", dictDTO.getCreateTime()); map.put("创建日期", dictDTO.getCreateTime());
......
/*
* 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.system.service.impl; package me.zhengjie.modules.system.service.impl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.modules.system.domain.Job; import me.zhengjie.modules.system.domain.Job;
import me.zhengjie.modules.system.repository.DeptRepository;
import me.zhengjie.modules.system.service.dto.JobQueryCriteria; import me.zhengjie.modules.system.service.dto.JobQueryCriteria;
import me.zhengjie.utils.FileUtil; import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil; import me.zhengjie.utils.PageUtil;
...@@ -19,7 +35,6 @@ import org.springframework.data.domain.Pageable; ...@@ -19,7 +35,6 @@ import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.*;
...@@ -29,31 +44,19 @@ import java.util.*; ...@@ -29,31 +44,19 @@ import java.util.*;
* @date 2019-03-29 * @date 2019-03-29
*/ */
@Service @Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "job") @CacheConfig(cacheNames = "job")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class) @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class JobServiceImpl implements JobService { public class JobServiceImpl implements JobService {
private final JobRepository jobRepository; private final JobRepository jobRepository;
private final JobMapper jobMapper; private final JobMapper jobMapper;
private final DeptRepository deptRepository;
public JobServiceImpl(JobRepository jobRepository, JobMapper jobMapper, DeptRepository deptRepository) {
this.jobRepository = jobRepository;
this.jobMapper = jobMapper;
this.deptRepository = deptRepository;
}
@Override @Override
@Cacheable @Cacheable
public Map<String,Object> queryAll(JobQueryCriteria criteria, Pageable pageable) { public Map<String,Object> queryAll(JobQueryCriteria criteria, Pageable pageable) {
Page<Job> page = jobRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable); Page<Job> page = jobRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
List<JobDto> jobs = new ArrayList<>(); return PageUtil.toPage(page.map(jobMapper::toDto).getContent(),page.getTotalElements());
for (Job job : page.getContent()) {
jobs.add(jobMapper.toDto(job,deptRepository.findNameById(job.getDept().getPid())));
}
return PageUtil.toPage(jobs,page.getTotalElements());
} }
@Override @Override
...@@ -75,6 +78,10 @@ public class JobServiceImpl implements JobService { ...@@ -75,6 +78,10 @@ public class JobServiceImpl implements JobService {
@CacheEvict(allEntries = true) @CacheEvict(allEntries = true)
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public JobDto create(Job resources) { public JobDto create(Job resources) {
Job job = jobRepository.findByName(resources.getName());
if(job != null){
throw new EntityExistException(Job.class,"name",resources.getName());
}
return jobMapper.toDto(jobRepository.save(resources)); return jobMapper.toDto(jobRepository.save(resources));
} }
...@@ -83,6 +90,10 @@ public class JobServiceImpl implements JobService { ...@@ -83,6 +90,10 @@ public class JobServiceImpl implements JobService {
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void update(Job resources) { public void update(Job resources) {
Job job = jobRepository.findById(resources.getId()).orElseGet(Job::new); Job job = jobRepository.findById(resources.getId()).orElseGet(Job::new);
Job old = jobRepository.findByName(resources.getName());
if(old != null && !old.getId().equals(resources.getId())){
throw new EntityExistException(Job.class,"name",resources.getName());
}
ValidationUtil.isNull( job.getId(),"Job","id",resources.getId()); ValidationUtil.isNull( job.getId(),"Job","id",resources.getId());
resources.setId(job.getId()); resources.setId(job.getId());
jobRepository.save(resources); jobRepository.save(resources);
...@@ -103,7 +114,6 @@ public class JobServiceImpl implements JobService { ...@@ -103,7 +114,6 @@ public class JobServiceImpl implements JobService {
for (JobDto jobDTO : jobDtos) { for (JobDto jobDTO : jobDtos) {
Map<String,Object> map = new LinkedHashMap<>(); Map<String,Object> map = new LinkedHashMap<>();
map.put("岗位名称", jobDTO.getName()); map.put("岗位名称", jobDTO.getName());
map.put("所属部门", jobDTO.getDept().getName());
map.put("岗位状态", jobDTO.getEnabled() ? "启用" : "停用"); map.put("岗位状态", jobDTO.getEnabled() ? "启用" : "停用");
map.put("创建日期", jobDTO.getCreateTime()); map.put("创建日期", jobDTO.getCreateTime());
list.add(map); list.add(map);
......
/*
* 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.system.service.impl; package me.zhengjie.modules.system.service.impl;
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.domain.Menu; import me.zhengjie.modules.system.domain.Menu;
import me.zhengjie.modules.system.domain.vo.MenuMetaVo; import me.zhengjie.modules.system.domain.vo.MenuMetaVo;
import me.zhengjie.modules.system.domain.vo.MenuVo; import me.zhengjie.modules.system.domain.vo.MenuVo;
...@@ -33,26 +49,18 @@ import java.util.stream.Collectors; ...@@ -33,26 +49,18 @@ import java.util.stream.Collectors;
* @author Zheng Jie * @author Zheng Jie
*/ */
@Service @Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "menu") @CacheConfig(cacheNames = "menu")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class) @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class MenuServiceImpl implements MenuService { public class MenuServiceImpl implements MenuService {
private final MenuRepository menuRepository; private final MenuRepository menuRepository;
private final MenuMapper menuMapper; private final MenuMapper menuMapper;
private final RoleService roleService; private final RoleService roleService;
public MenuServiceImpl(MenuRepository menuRepository, MenuMapper menuMapper, RoleService roleService) {
this.menuRepository = menuRepository;
this.menuMapper = menuMapper;
this.roleService = roleService;
}
@Override @Override
@Cacheable @Cacheable
public List<MenuDto> queryAll(MenuQueryCriteria criteria){ public List<MenuDto> queryAll(MenuQueryCriteria criteria){
// Sort sort = new Sort(Sort.Direction.DESC,"id");
return menuMapper.toDto(menuRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder))); return menuMapper.toDto(menuRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
} }
...@@ -67,15 +75,15 @@ public class MenuServiceImpl implements MenuService { ...@@ -67,15 +75,15 @@ public class MenuServiceImpl implements MenuService {
@Override @Override
public List<MenuDto> findByRoles(List<RoleSmallDto> roles) { public List<MenuDto> findByRoles(List<RoleSmallDto> roles) {
Set<Long> roleIds = roles.stream().map(RoleSmallDto::getId).collect(Collectors.toSet()); Set<Long> roleIds = roles.stream().map(RoleSmallDto::getId).collect(Collectors.toSet());
LinkedHashSet<Menu> menus = menuRepository.findByRoles_IdInAndTypeNotOrderBySortAsc(roleIds, 2); LinkedHashSet<Menu> menus = menuRepository.findByRoles_IdInAndTypeNotOrderByMenuSortAsc(roleIds, 2);
return menus.stream().map(menuMapper::toDto).collect(Collectors.toList()); return menus.stream().map(menuMapper::toDto).collect(Collectors.toList());
} }
@Override @Override
@CacheEvict(allEntries = true) @CacheEvict(allEntries = true)
public MenuDto create(Menu resources) { public MenuDto create(Menu resources) {
if(menuRepository.findByName(resources.getName()) != null){ if(menuRepository.findByTitle(resources.getTitle()) != null){
throw new EntityExistException(Menu.class,"name",resources.getName()); throw new EntityExistException(Menu.class,"title",resources.getTitle());
} }
if(StringUtils.isNotBlank(resources.getComponentName())){ if(StringUtils.isNotBlank(resources.getComponentName())){
if(menuRepository.findByComponentName(resources.getComponentName()) != null){ if(menuRepository.findByComponentName(resources.getComponentName()) != null){
...@@ -106,10 +114,10 @@ public class MenuServiceImpl implements MenuService { ...@@ -106,10 +114,10 @@ public class MenuServiceImpl implements MenuService {
throw new BadRequestException("外链必须以http://或者https://开头"); throw new BadRequestException("外链必须以http://或者https://开头");
} }
} }
Menu menu1 = menuRepository.findByName(resources.getName()); Menu menu1 = menuRepository.findByTitle(resources.getTitle());
if(menu1 != null && !menu1.getId().equals(menu.getId())){ if(menu1 != null && !menu1.getId().equals(menu.getId())){
throw new EntityExistException(Menu.class,"name",resources.getName()); throw new EntityExistException(Menu.class,"title",resources.getTitle());
} }
if(StringUtils.isNotBlank(resources.getComponentName())){ if(StringUtils.isNotBlank(resources.getComponentName())){
...@@ -118,13 +126,13 @@ public class MenuServiceImpl implements MenuService { ...@@ -118,13 +126,13 @@ public class MenuServiceImpl implements MenuService {
throw new EntityExistException(Menu.class,"componentName",resources.getComponentName()); throw new EntityExistException(Menu.class,"componentName",resources.getComponentName());
} }
} }
menu.setName(resources.getName()); menu.setTitle(resources.getTitle());
menu.setComponent(resources.getComponent()); menu.setComponent(resources.getComponent());
menu.setPath(resources.getPath()); menu.setPath(resources.getPath());
menu.setIcon(resources.getIcon()); menu.setIcon(resources.getIcon());
menu.setIFrame(resources.getIFrame()); menu.setIFrame(resources.getIFrame());
menu.setPid(resources.getPid()); menu.setPid(resources.getPid());
menu.setSort(resources.getSort()); menu.setMenuSort(resources.getMenuSort());
menu.setCache(resources.getCache()); menu.setCache(resources.getCache());
menu.setHidden(resources.getHidden()); menu.setHidden(resources.getHidden());
menu.setComponentName(resources.getComponentName()); menu.setComponentName(resources.getComponentName());
...@@ -165,7 +173,7 @@ public class MenuServiceImpl implements MenuService { ...@@ -165,7 +173,7 @@ public class MenuServiceImpl implements MenuService {
List<Menu> menuList = menuRepository.findByPid(menu.getId()); List<Menu> menuList = menuRepository.findByPid(menu.getId());
Map<String,Object> map = new HashMap<>(16); Map<String,Object> map = new HashMap<>(16);
map.put("id",menu.getId()); map.put("id",menu.getId());
map.put("label",menu.getName()); map.put("label",menu.getTitle());
if(menuList!=null && menuList.size()!=0){ if(menuList!=null && menuList.size()!=0){
map.put("children",getMenuTree(menuList)); map.put("children",getMenuTree(menuList));
} }
...@@ -216,7 +224,7 @@ public class MenuServiceImpl implements MenuService { ...@@ -216,7 +224,7 @@ public class MenuServiceImpl implements MenuService {
if (menuDTO!=null){ if (menuDTO!=null){
List<MenuDto> menuDtoList = menuDTO.getChildren(); List<MenuDto> menuDtoList = menuDTO.getChildren();
MenuVo menuVo = new MenuVo(); MenuVo menuVo = new MenuVo();
menuVo.setName(ObjectUtil.isNotEmpty(menuDTO.getComponentName()) ? menuDTO.getComponentName() : menuDTO.getName()); menuVo.setName(ObjectUtil.isNotEmpty(menuDTO.getComponentName()) ? menuDTO.getComponentName() : menuDTO.getTitle());
// 一级目录需要加斜杠,不然会报警告 // 一级目录需要加斜杠,不然会报警告
menuVo.setPath(menuDTO.getPid() == 0 ? "/" + menuDTO.getPath() :menuDTO.getPath()); menuVo.setPath(menuDTO.getPid() == 0 ? "/" + menuDTO.getPath() :menuDTO.getPath());
menuVo.setHidden(menuDTO.getHidden()); menuVo.setHidden(menuDTO.getHidden());
...@@ -228,7 +236,7 @@ public class MenuServiceImpl implements MenuService { ...@@ -228,7 +236,7 @@ public class MenuServiceImpl implements MenuService {
menuVo.setComponent(menuDTO.getComponent()); menuVo.setComponent(menuDTO.getComponent());
} }
} }
menuVo.setMeta(new MenuMetaVo(menuDTO.getName(),menuDTO.getIcon(),!menuDTO.getCache())); menuVo.setMeta(new MenuMetaVo(menuDTO.getTitle(),menuDTO.getIcon(),!menuDTO.getCache()));
if(menuDtoList !=null && menuDtoList.size()!=0){ if(menuDtoList !=null && menuDtoList.size()!=0){
menuVo.setAlwaysShow(true); menuVo.setAlwaysShow(true);
menuVo.setRedirect("noredirect"); menuVo.setRedirect("noredirect");
...@@ -271,7 +279,7 @@ public class MenuServiceImpl implements MenuService { ...@@ -271,7 +279,7 @@ public class MenuServiceImpl implements MenuService {
List<Map<String, Object>> list = new ArrayList<>(); List<Map<String, Object>> list = new ArrayList<>();
for (MenuDto menuDTO : menuDtos) { for (MenuDto menuDTO : menuDtos) {
Map<String,Object> map = new LinkedHashMap<>(); Map<String,Object> map = new LinkedHashMap<>();
map.put("菜单名称", menuDTO.getName()); map.put("菜单标题", menuDTO.getTitle());
map.put("菜单类型", menuDTO.getType() == 0 ? "目录" : menuDTO.getType() == 1 ? "菜单" : "按钮"); map.put("菜单类型", menuDTO.getType() == 0 ? "目录" : menuDTO.getType() == 1 ? "菜单" : "按钮");
map.put("权限标识", menuDTO.getPermission()); map.put("权限标识", menuDTO.getPermission());
map.put("外链菜单", menuDTO.getIFrame() ? "是" : "否"); map.put("外链菜单", menuDTO.getIFrame() ? "是" : "否");
......
/*
* 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.system.service.impl;
import cn.hutool.core.date.BetweenFormater;
import cn.hutool.core.date.DateUtil;
import me.zhengjie.modules.system.service.MonitorService;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.StringUtils;
import org.springframework.stereotype.Service;
import oshi.SystemInfo;
import oshi.hardware.*;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;
import oshi.util.FormatUtil;
import oshi.util.Util;
import java.lang.management.ManagementFactory;
import java.text.DecimalFormat;
import java.util.*;
/**
* @author Zheng Jie
* @date 2020-05-02
*/
@Service
public class MonitorServiceImpl implements MonitorService {
private final DecimalFormat df = new DecimalFormat("0.00");
@Override
public Map<String,Object> getServers(){
Map<String, Object> resultMap = new LinkedHashMap<>(8);
try {
SystemInfo si = new SystemInfo();
OperatingSystem os = si.getOperatingSystem();
HardwareAbstractionLayer hal = si.getHardware();
// 系统信息
resultMap.put("sys", getSystemInfo(os));
// cpu 信息
resultMap.put("cpu", getCpuInfo(hal.getProcessor()));
// 内存信息
resultMap.put("memory", getMemoryInfo(hal.getMemory()));
// 交换区信息
resultMap.put("swap", getSwapInfo(hal.getMemory()));
// 磁盘
resultMap.put("disk", getDiskInfo(hal.getDiskStores(), os));
resultMap.put("time", DateUtil.format(new Date(), "HH:mm:ss"));
} catch (Exception e) {
e.printStackTrace();
}
return resultMap;
}
/**
* 获取磁盘信息
* @param diskStores /
* @return /
*/
private Map<String,Object> getDiskInfo(HWDiskStore[] diskStores, OperatingSystem os) {
Map<String,Object> diskInfo = new LinkedHashMap<>();
long total = 0;
for (HWDiskStore disk : diskStores) {
boolean readwrite = disk.getReads() > 0 || disk.getWrites() > 0;
total = disk.getSize();
diskInfo.put("reads", readwrite ? FormatUtil.formatBytes(disk.getReadBytes()) : "?");
diskInfo.put("writes", readwrite ? FormatUtil.formatBytes(disk.getWriteBytes()) : "?");
break;
}
FileSystem fileSystem = os.getFileSystem();
OSFileStore[] fsArray = fileSystem.getFileStores();
for (OSFileStore fs : fsArray){
diskInfo.put("total", fs.getTotalSpace() > 0 ? FileUtil.getSize(fs.getTotalSpace()) : "?");
long used = fs.getTotalSpace() - fs.getUsableSpace();
diskInfo.put("available", FileUtil.getSize(fs.getUsableSpace()));
diskInfo.put("used", FileUtil.getSize(used));
diskInfo.put("usageRate", df.format(used/(double)fs.getTotalSpace() * 100));
}
return diskInfo;
}
/**
* 获取交换区信息
* @param memory /
* @return /
*/
private Map<String,Object> getSwapInfo(GlobalMemory memory) {
Map<String,Object> swapInfo = new LinkedHashMap<>();
swapInfo.put("total", FormatUtil.formatBytes(memory.getVirtualMemory().getSwapTotal()));
swapInfo.put("used", FormatUtil.formatBytes(memory.getVirtualMemory().getSwapUsed()));
swapInfo.put("available", FormatUtil.formatBytes(memory.getVirtualMemory().getSwapTotal() - memory.getVirtualMemory().getSwapUsed()));
swapInfo.put("usageRate", df.format(memory.getVirtualMemory().getSwapUsed()/(double)memory.getVirtualMemory().getSwapTotal() * 100));
return swapInfo;
}
/**
* 获取内存信息
* @param memory /
* @return /
*/
private Map<String,Object> getMemoryInfo(GlobalMemory memory) {
Map<String,Object> memoryInfo = new LinkedHashMap<>();
memoryInfo.put("total", FormatUtil.formatBytes(memory.getTotal()));
memoryInfo.put("available", FormatUtil.formatBytes(memory.getAvailable()));
memoryInfo.put("used", FormatUtil.formatBytes(memory.getTotal() - memory.getAvailable()));
memoryInfo.put("usageRate", df.format((memory.getTotal() - memory.getAvailable())/(double)memory.getTotal() * 100));
return memoryInfo;
}
/**
* 获取Cpu相关信息
* @param processor /
* @return /
*/
private Map<String,Object> getCpuInfo(CentralProcessor processor) {
Map<String,Object> cpuInfo = new LinkedHashMap<>();
cpuInfo.put("name", processor.getProcessorIdentifier().getName());
cpuInfo.put("package", processor.getPhysicalPackageCount() + "个物理CPU");
cpuInfo.put("core", processor.getPhysicalProcessorCount() + "个物理核心");
cpuInfo.put("coreNumber", processor.getPhysicalProcessorCount());
cpuInfo.put("logic", processor.getLogicalProcessorCount() + "个逻辑CPU");
// CPU信息
long[] prevTicks = processor.getSystemCpuLoadTicks();
// 等待1秒...
Util.sleep(1000);
long[] ticks = processor.getSystemCpuLoadTicks();
long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
long sys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
long totalCpu = user + nice + sys + idle + iowait + irq + softirq + steal;
cpuInfo.put("used", df.format(100d * user / totalCpu + 100d * sys / totalCpu));
cpuInfo.put("idle", df.format(100d * idle / totalCpu));
return cpuInfo;
}
/**
* 获取系统相关信息,系统、运行天数、系统IP
* @param os /
* @return /
*/
private Map<String,Object> getSystemInfo(OperatingSystem os){
Map<String,Object> systemInfo = new LinkedHashMap<>();
// jvm 运行时间
long time = ManagementFactory.getRuntimeMXBean().getStartTime();
Date date = new Date(time);
// 计算项目运行时间
String formatBetween = DateUtil.formatBetween(date, new Date(),BetweenFormater.Level.HOUR);
// 系统信息
systemInfo.put("os", os.toString());
systemInfo.put("day", formatBetween);
systemInfo.put("ip", StringUtils.getLocalIp());
return systemInfo;
}
}
/*
* 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.system.service.impl; package me.zhengjie.modules.system.service.impl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.domain.Menu; import me.zhengjie.modules.system.domain.Menu;
import me.zhengjie.modules.system.domain.Role; import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.exception.EntityExistException; import me.zhengjie.exception.EntityExistException;
...@@ -22,7 +38,6 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; ...@@ -22,7 +38,6 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.*;
...@@ -33,22 +48,15 @@ import java.util.stream.Collectors; ...@@ -33,22 +48,15 @@ import java.util.stream.Collectors;
* @date 2018-12-03 * @date 2018-12-03
*/ */
@Service @Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "role") @CacheConfig(cacheNames = "role")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class) @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class RoleServiceImpl implements RoleService { public class RoleServiceImpl implements RoleService {
private final RoleRepository roleRepository; private final RoleRepository roleRepository;
private final RoleMapper roleMapper; private final RoleMapper roleMapper;
private final RoleSmallMapper roleSmallMapper; private final RoleSmallMapper roleSmallMapper;
public RoleServiceImpl(RoleRepository roleRepository, RoleMapper roleMapper, RoleSmallMapper roleSmallMapper) {
this.roleRepository = roleRepository;
this.roleMapper = roleMapper;
this.roleSmallMapper = roleSmallMapper;
}
@Override @Override
@Cacheable @Cacheable
public Object queryAll(Pageable pageable) { public Object queryAll(Pageable pageable) {
...@@ -98,16 +106,11 @@ public class RoleServiceImpl implements RoleService { ...@@ -98,16 +106,11 @@ public class RoleServiceImpl implements RoleService {
if(role1 != null && !role1.getId().equals(role.getId())){ if(role1 != null && !role1.getId().equals(role.getId())){
throw new EntityExistException(Role.class,"username",resources.getName()); throw new EntityExistException(Role.class,"username",resources.getName());
} }
role1 = roleRepository.findByPermission(resources.getPermission());
if(role1 != null && !role1.getId().equals(role.getId())){
throw new EntityExistException(Role.class,"permission",resources.getPermission());
}
role.setName(resources.getName()); role.setName(resources.getName());
role.setRemark(resources.getRemark()); role.setDescription(resources.getDescription());
role.setDataScope(resources.getDataScope()); role.setDataScope(resources.getDataScope());
role.setDepts(resources.getDepts()); role.setDepts(resources.getDepts());
role.setLevel(resources.getLevel()); role.setLevel(resources.getLevel());
role.setPermission(resources.getPermission());
roleRepository.save(role); roleRepository.save(role);
} }
...@@ -154,13 +157,17 @@ public class RoleServiceImpl implements RoleService { ...@@ -154,13 +157,17 @@ public class RoleServiceImpl implements RoleService {
@Override @Override
@Cacheable(key = "'loadPermissionByUser:' + #p0.username") @Cacheable(key = "'loadPermissionByUser:' + #p0.username")
public List<GrantedAuthority> mapToGrantedAuthorities(UserDto user) { public List<GrantedAuthority> mapToGrantedAuthorities(UserDto user) {
Set<String> permissions = new HashSet<>();
// 如果是管理员直接返回
if(user.getIsAdmin()){
permissions.add("admin");
return permissions.stream().map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
}
Set<Role> roles = roleRepository.findByUsers_Id(user.getId()); Set<Role> roles = roleRepository.findByUsers_Id(user.getId());
Set<String> permissions = roles.stream().filter(role -> StringUtils.isNotBlank(role.getPermission())).map(Role::getPermission).collect(Collectors.toSet()); permissions = roles.stream().flatMap(role -> role.getMenus().stream())
permissions.addAll( .filter(menu -> StringUtils.isNotBlank(menu.getPermission()))
roles.stream().flatMap(role -> role.getMenus().stream()) .map(Menu::getPermission).collect(Collectors.toSet());
.filter(menu -> StringUtils.isNotBlank(menu.getPermission()))
.map(Menu::getPermission).collect(Collectors.toSet())
);
return permissions.stream().map(SimpleGrantedAuthority::new) return permissions.stream().map(SimpleGrantedAuthority::new)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
...@@ -171,9 +178,8 @@ public class RoleServiceImpl implements RoleService { ...@@ -171,9 +178,8 @@ public class RoleServiceImpl implements RoleService {
for (RoleDto role : roles) { for (RoleDto role : roles) {
Map<String,Object> map = new LinkedHashMap<>(); Map<String,Object> map = new LinkedHashMap<>();
map.put("角色名称", role.getName()); map.put("角色名称", role.getName());
map.put("默认权限", role.getPermission());
map.put("角色级别", role.getLevel()); map.put("角色级别", role.getLevel());
map.put("描述", role.getRemark()); map.put("描述", role.getDescription());
map.put("创建日期", role.getCreateTime()); map.put("创建日期", role.getCreateTime());
list.add(map); list.add(map);
} }
......
/*
* 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.system.service.impl; package me.zhengjie.modules.system.service.impl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.config.FileProperties; import me.zhengjie.config.FileProperties;
import me.zhengjie.modules.system.domain.User; import me.zhengjie.modules.system.domain.User;
import me.zhengjie.exception.EntityExistException; import me.zhengjie.exception.EntityExistException;
import me.zhengjie.exception.EntityNotFoundException; import me.zhengjie.exception.EntityNotFoundException;
import me.zhengjie.modules.system.domain.UserAvatar;
import me.zhengjie.modules.system.repository.UserAvatarRepository;
import me.zhengjie.modules.system.repository.UserRepository; import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.UserService; import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.JobSmallDto;
import me.zhengjie.modules.system.service.dto.RoleSmallDto; import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.system.service.dto.UserDto; import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.modules.system.service.dto.UserQueryCriteria; import me.zhengjie.modules.system.service.dto.UserQueryCriteria;
...@@ -33,6 +48,7 @@ import java.util.stream.Collectors; ...@@ -33,6 +48,7 @@ import java.util.stream.Collectors;
* @date 2018-11-23 * @date 2018-11-23
*/ */
@Service @Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "user") @CacheConfig(cacheNames = "user")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class) @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserServiceImpl implements UserService { public class UserServiceImpl implements UserService {
...@@ -40,15 +56,7 @@ public class UserServiceImpl implements UserService { ...@@ -40,15 +56,7 @@ public class UserServiceImpl implements UserService {
private final UserRepository userRepository; private final UserRepository userRepository;
private final UserMapper userMapper; private final UserMapper userMapper;
private final RedisUtils redisUtils; private final RedisUtils redisUtils;
private final UserAvatarRepository userAvatarRepository;
private final FileProperties properties; private final FileProperties properties;
public UserServiceImpl(UserRepository userRepository, UserMapper userMapper, RedisUtils redisUtils, UserAvatarRepository userAvatarRepository, FileProperties properties) {
this.userRepository = userRepository;
this.userMapper = userMapper;
this.redisUtils = redisUtils;
this.userAvatarRepository = userAvatarRepository;
this.properties = properties;
}
@Override @Override
@Cacheable @Cacheable
...@@ -115,10 +123,10 @@ public class UserServiceImpl implements UserService { ...@@ -115,10 +123,10 @@ public class UserServiceImpl implements UserService {
user.setEnabled(resources.getEnabled()); user.setEnabled(resources.getEnabled());
user.setRoles(resources.getRoles()); user.setRoles(resources.getRoles());
user.setDept(resources.getDept()); user.setDept(resources.getDept());
user.setJob(resources.getJob()); user.setJobs(resources.getJobs());
user.setPhone(resources.getPhone()); user.setPhone(resources.getPhone());
user.setNickName(resources.getNickName()); user.setNickName(resources.getNickName());
user.setSex(resources.getSex()); user.setGender(resources.getGender());
userRepository.save(user); userRepository.save(user);
} }
...@@ -129,7 +137,7 @@ public class UserServiceImpl implements UserService { ...@@ -129,7 +137,7 @@ public class UserServiceImpl implements UserService {
User user = userRepository.findById(resources.getId()).orElseGet(User::new); User user = userRepository.findById(resources.getId()).orElseGet(User::new);
user.setNickName(resources.getNickName()); user.setNickName(resources.getNickName());
user.setPhone(resources.getPhone()); user.setPhone(resources.getPhone());
user.setSex(resources.getSex()); user.setGender(resources.getGender());
userRepository.save(user); userRepository.save(user);
} }
...@@ -170,15 +178,10 @@ public class UserServiceImpl implements UserService { ...@@ -170,15 +178,10 @@ public class UserServiceImpl implements UserService {
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void updateAvatar(MultipartFile multipartFile) { public void updateAvatar(MultipartFile multipartFile) {
User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername()); User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername());
UserAvatar userAvatar = user.getUserAvatar(); String oldPath = user.getAvatarPath();
String oldPath = "";
if(userAvatar != null){
oldPath = userAvatar.getPath();
}
File file = FileUtil.upload(multipartFile, properties.getPath().getAvatar()); File file = FileUtil.upload(multipartFile, properties.getPath().getAvatar());
assert file != null; user.setAvatarPath(Objects.requireNonNull(file).getPath());
userAvatar = userAvatarRepository.save(new UserAvatar(userAvatar,file.getName(), file.getPath(), FileUtil.getSize(multipartFile.getSize()))); user.setAvatarName(file.getName());
user.setUserAvatar(userAvatar);
userRepository.save(user); userRepository.save(user);
if(StringUtils.isNotBlank(oldPath)){ if(StringUtils.isNotBlank(oldPath)){
FileUtil.del(oldPath); FileUtil.del(oldPath);
...@@ -199,14 +202,13 @@ public class UserServiceImpl implements UserService { ...@@ -199,14 +202,13 @@ public class UserServiceImpl implements UserService {
List<String> roles = userDTO.getRoles().stream().map(RoleSmallDto::getName).collect(Collectors.toList()); List<String> roles = userDTO.getRoles().stream().map(RoleSmallDto::getName).collect(Collectors.toList());
Map<String,Object> map = new LinkedHashMap<>(); Map<String,Object> map = new LinkedHashMap<>();
map.put("用户名", userDTO.getUsername()); map.put("用户名", userDTO.getUsername());
map.put("头像", userDTO.getAvatar()); map.put("角色", roles);
map.put("部门", userDTO.getDept().getName());
map.put("岗位", userDTO.getJobs().stream().map(JobSmallDto::getName).toString());
map.put("邮箱", userDTO.getEmail()); map.put("邮箱", userDTO.getEmail());
map.put("状态", userDTO.getEnabled() ? "启用" : "禁用"); map.put("状态", userDTO.getEnabled() ? "启用" : "禁用");
map.put("手机号码", userDTO.getPhone()); map.put("手机号码", userDTO.getPhone());
map.put("角色", roles); map.put("修改密码的时间", userDTO.getPwdResetTime());
map.put("部门", userDTO.getDept().getName());
map.put("岗位", userDTO.getJob().getName());
map.put("最后修改密码的时间", userDTO.getLastPasswordResetTime());
map.put("创建日期", userDTO.getCreateTime()); map.put("创建日期", userDTO.getCreateTime());
list.add(map); list.add(map);
} }
......
package me.zhengjie.service.impl; /*
* 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.system.service.impl;
import cn.hutool.core.lang.Dict; import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.RandomUtil;
...@@ -6,82 +21,63 @@ import cn.hutool.extra.template.Template; ...@@ -6,82 +21,63 @@ import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig; import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine; import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil; import cn.hutool.extra.template.TemplateUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.domain.vo.EmailVo; import me.zhengjie.domain.vo.EmailVo;
import me.zhengjie.domain.VerificationCode;
import me.zhengjie.exception.BadRequestException; import me.zhengjie.exception.BadRequestException;
import me.zhengjie.repository.VerificationCodeRepository; import me.zhengjie.modules.system.service.VerifyService;
import me.zhengjie.service.VerificationCodeService; import me.zhengjie.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.Collections; import java.util.Collections;
import java.util.concurrent.*;
/** /**
* @author Zheng Jie * @author Zheng Jie
* @date 2018-12-26 * @date 2018-12-26
*/ */
@Service @Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class) @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class VerificationCodeServiceImpl implements VerificationCodeService { public class VerifyServiceImpl implements VerifyService {
private final VerificationCodeRepository verificationCodeRepository;
@Value("${code.expiration}") @Value("${code.expiration}")
private Integer expiration; private Long expiration;
private final RedisUtils redisUtils;
public VerificationCodeServiceImpl(VerificationCodeRepository verificationCodeRepository) {
this.verificationCodeRepository = verificationCodeRepository;
}
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public EmailVo sendEmail(VerificationCode code) { public EmailVo sendEmail(String email, String key) {
EmailVo emailVo; EmailVo emailVo;
String content; String content;
VerificationCode verificationCode = verificationCodeRepository.findByScenesAndTypeAndValueAndStatusIsTrue(code.getScenes(),code.getType(),code.getValue()); String redisKey = key + email;
// 如果不存在有效的验证码,就创建一个新的 // 如果不存在有效的验证码,就创建一个新的
TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
Template template = engine.getTemplate("email/email.ftl"); Template template = engine.getTemplate("email/email.ftl");
if(verificationCode == null){ Object oldCode = redisUtils.get(redisKey);
code.setCode(RandomUtil.randomNumbers (6)); if(oldCode == null){
content = template.render(Dict.create().set("code",code.getCode())); String code = RandomUtil.randomNumbers (6);
emailVo = new EmailVo(Collections.singletonList(code.getValue()),"eladmin后台管理系统",content); // 存入缓存
timedDestruction(verificationCodeRepository.save(code)); if(!redisUtils.set(redisKey, code, expiration)){
throw new BadRequestException("服务异常,请联系网站负责人");
}
content = template.render(Dict.create().set("code",code));
emailVo = new EmailVo(Collections.singletonList(email),"EL-ADMIN后台管理系统",content);
// 存在就再次发送原来的验证码 // 存在就再次发送原来的验证码
} else { } else {
content = template.render(Dict.create().set("code",verificationCode.getCode())); content = template.render(Dict.create().set("code",oldCode));
emailVo = new EmailVo(Collections.singletonList(verificationCode.getValue()),"eladmin后台管理系统",content); emailVo = new EmailVo(Collections.singletonList(email),"EL-ADMIN后台管理系统",content);
} }
return emailVo; return emailVo;
} }
@Override @Override
public void validated(VerificationCode code) { public void validated(String key, String code) {
VerificationCode verificationCode = verificationCodeRepository.findByScenesAndTypeAndValueAndStatusIsTrue(code.getScenes(),code.getType(),code.getValue()); Object value = redisUtils.get(key);
if(verificationCode == null || !verificationCode.getCode().equals(code.getCode())){ if(value == null || !value.toString().equals(code)){
throw new BadRequestException("无效验证码"); throw new BadRequestException("无效验证码");
} else { } else {
verificationCode.setStatus(false); redisUtils.del(key);
verificationCodeRepository.save(verificationCode);
}
}
/**
* 定时任务,指定分钟后改变验证码状态
* @param verifyCode 验证码
*/
private void timedDestruction(VerificationCode verifyCode) {
//以下示例为程序调用结束继续运行
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
try {
executorService.schedule(() -> {
verifyCode.setStatus(false);
verificationCodeRepository.save(verifyCode);
}, expiration * 60 * 1000L, TimeUnit.MILLISECONDS);
}catch (Exception e){
e.printStackTrace();
} }
} }
} }
/*
* 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.system.service.mapper; package me.zhengjie.modules.system.service.mapper;
import me.zhengjie.base.BaseMapper; import me.zhengjie.base.BaseMapper;
......
/*
* 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.system.service.mapper; package me.zhengjie.modules.system.service.mapper;
import me.zhengjie.base.BaseMapper; import me.zhengjie.base.BaseMapper;
......
/*
* 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.system.service.mapper; package me.zhengjie.modules.system.service.mapper;
import me.zhengjie.base.BaseMapper; import me.zhengjie.base.BaseMapper;
......
/*
* 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.system.service.mapper; package me.zhengjie.modules.system.service.mapper;
import me.zhengjie.base.BaseMapper; import me.zhengjie.base.BaseMapper;
......
/*
* 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.system.service.mapper; package me.zhengjie.modules.system.service.mapper;
import me.zhengjie.base.BaseMapper; import me.zhengjie.base.BaseMapper;
......
/*
* 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.system.service.mapper; package me.zhengjie.modules.system.service.mapper;
import me.zhengjie.base.BaseMapper; import me.zhengjie.base.BaseMapper;
import me.zhengjie.modules.system.domain.Job; import me.zhengjie.modules.system.domain.Job;
import me.zhengjie.modules.system.service.dto.JobDto; import me.zhengjie.modules.system.service.dto.JobDto;
import org.mapstruct.Mapper; import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.ReportingPolicy; import org.mapstruct.ReportingPolicy;
/** /**
...@@ -13,13 +27,4 @@ import org.mapstruct.ReportingPolicy; ...@@ -13,13 +27,4 @@ import org.mapstruct.ReportingPolicy;
*/ */
@Mapper(componentModel = "spring",uses = {DeptMapper.class},unmappedTargetPolicy = ReportingPolicy.IGNORE) @Mapper(componentModel = "spring",uses = {DeptMapper.class},unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface JobMapper extends BaseMapper<JobDto, Job> { public interface JobMapper extends BaseMapper<JobDto, Job> {
/**
* 转Dto
* @param job 原始数据
* @param deptSuperiorName /
* @return /
*/
@Mapping(source = "deptSuperiorName", target = "deptSuperiorName")
JobDto toDto(Job job, String deptSuperiorName);
} }
\ No newline at end of file
/*
* 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.system.service.mapper; package me.zhengjie.modules.system.service.mapper;
import me.zhengjie.base.BaseMapper; import me.zhengjie.base.BaseMapper;
......
/*
* 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.system.service.mapper; package me.zhengjie.modules.system.service.mapper;
import me.zhengjie.base.BaseMapper; import me.zhengjie.base.BaseMapper;
......
/*
* 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.system.service.mapper; package me.zhengjie.modules.system.service.mapper;
import me.zhengjie.base.BaseMapper; import me.zhengjie.base.BaseMapper;
......
/*
* 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.system.service.mapper; package me.zhengjie.modules.system.service.mapper;
import me.zhengjie.base.BaseMapper; import me.zhengjie.base.BaseMapper;
......
Supports Markdown
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