This commit is contained in:
Saturneric 2020-09-01 15:14:33 +08:00
parent 3942d547af
commit 4f6af49432
53 changed files with 6 additions and 3101 deletions

View File

@ -1,176 +0,0 @@
package com.codesdream.ase.component.activity;
import com.alibaba.fastjson.JSONObject;
import com.codesdream.ase.exception.innerservererror.DataInvalidFormatException;
import com.codesdream.ase.model.activity.Activity;
import com.codesdream.ase.model.activity.Attendance;
import com.codesdream.ase.model.activity.Period;
import com.codesdream.ase.model.permission.User;
import com.codesdream.ase.service.ActivityService;
import com.codesdream.ase.service.UserService;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
/**
* JSONObject-Activity转化类
*/
@Component
public class ActivityConverter {
@Resource
UserService userService;
@Resource
PeriodService periodService;
@Resource
AttendanceService attendanceService;
/**
* @param json 一个Optional的json对象用以转化为Activity对象此过程中进行值的合法校验
* @return 一个可以被直接存储在数据库中的合法的Activity对象
*/
public Activity convertToActivity(Optional<JSONObject> json) {
if (!json.isPresent()) {
throw new NullPointerException();
}
Activity activity = new Activity();
JSONObject jsonObject = json.get();
//设置活动创建人
int userId = (int) jsonObject.get("creator");
Optional<User> creator = userService.findUserById(userId);
activity.setCreator(creator.get());
//设置参与人员
List<Integer> participateGroupFromJson = (List<Integer>) jsonObject.get("participate-group");
Set<User> participateGroup = new HashSet<>();
for (int id : participateGroupFromJson) {
Optional<User> user = userService.findUserById(id);
participateGroup.add(user.get());
}
activity.setParticipateGroup(participateGroup);
//设置活动标题
String title = (String) jsonObject.get("title");
activity.setTitle(title);
//设置主要负责人
int chiefManagerId = (int) jsonObject.get("chief-manager");
Optional<User> chiefManager = userService.findUserById(chiefManagerId);
activity.setChiefManager(chiefManager.get());
//设置次要负责人
List<Integer> assistManagersFromJSON = (List<Integer>) jsonObject.get("assist-managers");
Set<User> assistManager = new HashSet<>();
for (int id : assistManagersFromJSON) {
Optional<User> user = userService.findUserById(id);
assistManager.add(user.get());
}
activity.setAssistManagers(assistManager);
//设置活动类型
String type = (String) jsonObject.get("type");
activity.setType(type);
//设置
String startTimeFromJSON = (String) jsonObject.get("start-time");
String endTimeFromJSON = (String) jsonObject.get("end-time");
LocalDateTime startTime = LocalDateTime.parse(startTimeFromJSON, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
LocalDateTime endTime = LocalDateTime.parse(endTimeFromJSON, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
Period period = new Period(startTime, endTime);
period.setEnabled(false);
period = periodService.save(period);
activity.setPlanPeriod(period);
String cycle = (String) jsonObject.get("cycle");
activity.setCycle(cycle);
String description = (String) jsonObject.get("description");
activity.setDescription(description);
List<Integer> signGroupFromJSON = (List<Integer>) jsonObject.get("sign-group");
Set<User> signGroup = new HashSet<>();
for (int id : signGroupFromJSON) {
Optional<User> user = userService.findUserById(id);
signGroup.add(user.get());
}
activity.setSignGroup(signGroup);
List<Integer> informGroupFromJSON = (List<Integer>) jsonObject.get("inform-group");
if (informGroupFromJSON == null) {
participateGroupFromJson.removeAll(signGroupFromJSON);
participateGroupFromJson.addAll(signGroupFromJSON);
informGroupFromJSON = participateGroupFromJson;
}
Set<User> informGroup = new HashSet<>();
for (int id : informGroupFromJSON) {
Optional<User> user = userService.findUserById(id);
informGroup.add(user.get());
}
activity.setInformGroup(informGroup);
List<Integer> visibleGroupFromJSON = (List<Integer>) jsonObject.get("visible-group");
Set<User> visibleGroup = new HashSet<>();
for (int id : visibleGroupFromJSON) {
Optional<User> user = userService.findUserById(id);
visibleGroup.add(user.get());
}
activity.setVisibleGroup(informGroup);
String remindTimeFromJSON = (String) jsonObject.get("remind-time");
String numStr = remindTimeFromJSON.substring(0, remindTimeFromJSON.length() - 1);
int num = Integer.parseInt(numStr);
char unit = remindTimeFromJSON.charAt(remindTimeFromJSON.length() - 1);
switch (unit) {
case 'w': {
activity.setRemindTime(activity.getPlanPeriod().getStartTime().minusWeeks(num));
break;
}
case 'd': {
activity.setRemindTime(activity.getPlanPeriod().getStartTime().minusDays(num));
break;
}
case 'm': {
activity.setRemindTime(activity.getPlanPeriod().getStartTime().minusMinutes(num));
break;
}
case 'h': {
activity.setRemindTime(activity.getPlanPeriod().getStartTime().minusHours(num));
break;
}
case 's': {
activity.setRemindTime(activity.getPlanPeriod().getStartTime().minusSeconds(num));
}
}
Set<Period> periods = new HashSet<>();
String[] attendanceTimes = (String[]) jsonObject.get("attendance");
boolean attendanceOnLine = (boolean) jsonObject.get("attendance-online");
if ((attendanceTimes.length & 1) == 1) {
throw new DataInvalidFormatException();
}
for (int i = 0; i < attendanceTimes.length; i += 2) {
LocalDateTime start = LocalDateTime.parse(attendanceTimes[i], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
LocalDateTime end = LocalDateTime.parse(attendanceTimes[i + 1], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
Period period1 = new Period(start, end);
periods.add(period1);
}
Attendance attendance = new Attendance();
attendance.setClockInPeriods(periods);
attendance.setOnline(attendanceOnLine);
attendance = attendanceService.save(attendance);
activity.setAttendance(attendance);
activity.setOn(false);
activity.setOff(false);
return activity;
}
}

View File

@ -1,26 +0,0 @@
package com.codesdream.ase.component.activity;
import com.codesdream.ase.component.ASESpringUtil;
import com.codesdream.ase.model.permission.User;
import com.codesdream.ase.repository.permission.UserRepository;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Optional;
//获取当前用户的用户名
@Component
public class CurrentUserGetter {
private Optional<User> user;
public Optional<User> getCurrentUser(HttpServletRequest request){
Principal principal = request.getUserPrincipal();
String username = principal.getName();
ASESpringUtil aseSpringUtil = new ASESpringUtil();
UserRepository userRepository = aseSpringUtil.getBean(UserRepository.class);
this.user = userRepository.findByUsername(username);
return this.user;
}
}

View File

@ -1,189 +0,0 @@
package com.codesdream.ase.component.activity;
import com.codesdream.ase.exception.conflict.FileNameConflict;
import com.codesdream.ase.exception.notfound.AppendixFileNotFoundException;
import com.codesdream.ase.model.activity.Activity;
import com.codesdream.ase.model.activity.AppendixFile;
import com.codesdream.ase.repository.activity.ActivityRepository;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.*;
import java.time.LocalDateTime;
import java.util.Optional;
@Component
public class FileSystem {
@Resource
private AppendixFileService appendixFileService;
public static final int FAILED = -1;
//默认文件系统根路径
private static final String rootDir = "d:/temp";
/**
* 用于创建文件条目的辅助函数
* @param fileName 文件名
* @return 文件在数据库中的条目
*/
private AppendixFile createFileTable(String fileName)
{
AppendixFile appendixFile = new AppendixFile();
appendixFile.setFileName(fileName);
appendixFile.setLastEditTime(LocalDateTime.now());
String[] temp = fileName.split("\\.",2);
for(String s : temp)
System.out.println(s);
if(temp.length == 1)
appendixFile.setType("");
else
appendixFile.setType(temp[temp.length-1]);
return appendixFile;
}
/**
* 向磁盘中添加一个文件并在数据库建立条目
* @param data 文件的数据
* @param fileName 文件名包括拓展名
* @return 成功时返回文件id失败时返回FileSystem.FAILED
*/
public int addFile(byte data[], String fileName) throws Exception
{
AppendixFile appendixFile = createFileTable(fileName);
appendixFile = appendixFileService.save(appendixFile);
File file = new File(rootDir,""+appendixFile.getId());
FileOutputStream outputStream;
if(file.exists())
throw new FileNameConflict(
"file name conflict,there is a file in the directory, and is not created by this program",
file.getName());
File parent = file.getParentFile();
if(!parent.exists())
parent.mkdirs();
try{
file.createNewFile();
outputStream = new FileOutputStream(file);
outputStream.write(data);
outputStream.close();
return appendixFile.getId();
}
catch (Exception e){
appendixFileService.delete(appendixFile);
e.printStackTrace();
throw new Exception(e);
}
}
/**
* 根据id获取一个磁盘中的文件
* @param id 文件的id
* @return 成功返回文件的InputStream失败返回null
*/
public InputStream getFile(int id)throws AppendixFileNotFoundException
{
Optional<AppendixFile> optionalAppendixFile = appendixFileService.findById(id);
if(!optionalAppendixFile.isPresent())
throw new AppendixFileNotFoundException(
"the required id does not exist in the database",id,
AppendixFileNotFoundException.ID_NOT_FOUND);
AppendixFile appendixFile = appendixFileService.findById(id).get();
File file = new File(rootDir,""+appendixFile.getId());
if(file.exists())
{
try {
InputStream inputStream = new FileInputStream(file);
return inputStream;
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new AppendixFileNotFoundException(
"the required id exists in the database, but the stream can not be opened",id,
AppendixFileNotFoundException.STREAM_FAILURE);
}
}
else
throw new AppendixFileNotFoundException(
"the required id exists in the database, but the file is missing",id,
AppendixFileNotFoundException.FILE_NOT_fOUND);
}
/**
* 删除一个文件如果该文件不存在则不会发生操作
* @param id 要删除文件的id
*/
public void deleteFile(int id)
{
Optional<AppendixFile> optionalAppendixFile = appendixFileService.findById(id);
if(!optionalAppendixFile.isPresent())
return;
AppendixFile appendixFile = appendixFileService.findById(id).get();
File file = new File(rootDir,""+appendixFile.getId());
if(file.exists()) {
file.delete();
appendixFileService.delete(appendixFile);
}
}
/**
* 根据id获取一个文件的条目其中包含文件信息
* @param id 要寻找条目的id
*/
public AppendixFile getFileData(int id)throws AppendixFileNotFoundException
{
Optional<AppendixFile> optionalAppendixFile = appendixFileService.findById(id);
if(!optionalAppendixFile.isPresent())
throw new AppendixFileNotFoundException(
"the required id does not exist in the database",id,
AppendixFileNotFoundException.ID_NOT_FOUND);
AppendixFile appendixFile = appendixFileService.findById(id).get();
return appendixFile;
}
/**
* 维护数据库删去所有文件已经缺失的条目仅用于在文件系统出现故障时的维护
*/
public void databaseRefresh()
{
for (AppendixFile appendixFile:
appendixFileService.findAll()) {
File file = new File(rootDir,""+appendixFile.getId());
if(!file.exists())
appendixFileService.delete(appendixFile);
}
}
/**
* 维护磁盘删除指定根目录下所有不在数据库中的文件仅用于文件系统出现故障时的维护
*/
public void diskRefresh()
{
File dir = new File(rootDir);
if (dir.exists()) {
if (null == dir.listFiles()) {
return;
}
for(File file : dir.listFiles())
{
int id;
try{
id = Integer.parseInt(file.getName());
if(!appendixFileService.findById(id).isPresent())
file.delete();
}
catch (Exception ex){
file.delete();
}
}
}
}
}

View File

@ -1,129 +0,0 @@
package com.codesdream.ase.component.activity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;
@Component
public class FileUtils {
/**
* 得到图片字节流 数组大小
*/
public static byte[] readStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
outStream.close();
inStream.close();
return outStream.toByteArray();
}
/**
* 将文件转换成Byte数组
*
* @param file
* @return
*/
public static byte[] getBytesByFile(File file) {
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
byte[] data = bos.toByteArray();
bos.close();
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* MultipartFile转File
*
* @param param
* @return
*/
public static File transfer(MultipartFile param) {
if (!param.isEmpty()) {
File file = null;
try {
InputStream in = param.getInputStream();
file = new File(param.getOriginalFilename());
OutputStream out = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
out.write(buffer, 0, bytesRead);
}
in.close();
out.close();
return file;
} catch (Exception e) {
e.printStackTrace();
return file;
}
}
return null;
}
/**
* 获取指定文件的输入流
*
* @param logoPath 文件的路径
* @return
*/
public static InputStream getResourceAsStream(String logoPath) {
return FileUtils.class.getResourceAsStream(logoPath);
}
/**
* 将InputStream写入到File中
*
* @param ins
* @param file
* @throws IOException
*/
public void inputStreamToFile(InputStream ins, File file) throws IOException {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
}
/**
* 将图片转化成输入流
*
* @param image 图片
* @return inputStream 图片转化之后的输入流
*/
public static InputStream getImageStream(BufferedImage image) {
InputStream inputStream = null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageOutputStream imageOutputStream;
try {
imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream);
ImageIO.write(image, "jpg", imageOutputStream);
inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
return inputStream;
}
}

View File

@ -1,12 +0,0 @@
package com.codesdream.ase.component.activity;
import lombok.Data;
import org.springframework.stereotype.Component;
import java.util.List;
@Data
@Component
public class NullValueAttributes {
private List<String> nullValueAttributes;
}

View File

@ -1,225 +0,0 @@
package com.codesdream.ase.component.activity;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Hashtable;
import java.util.Random;
/**
* 二维码生成工具类
*/
@Component
public class QrCodeUtils {
private static final String CHARSET = "utf-8";
public static final String FORMAT = "JPG";
// 二维码尺寸
private static final int QRCODE_SIZE = 300;
// LOGO宽度
private static final int LOGO_WIDTH = 60;
// LOGO高度
private static final int LOGO_HEIGHT = 60;
/**
* 生成二维码
*
* @param content 二维码内容
* @param logoPath logo地址
* @param needCompress 是否压缩logo
* @return 图片
* @throws Exception
*/
public static BufferedImage createImage(String content, String logoPath, boolean needCompress) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
if (logoPath == null || "".equals(logoPath)) {
return image;
}
// 插入图片
QrCodeUtils.insertImage(image, logoPath, needCompress);
return image;
}
/**
* 插入LOGO
*
* @param source 二维码图片
* @param logoPath LOGO图片地址
* @param needCompress 是否压缩
* @throws IOException
*/
private static void insertImage(BufferedImage source, String logoPath, boolean needCompress) throws IOException {
InputStream inputStream = null;
try {
inputStream = FileUtils.getResourceAsStream(logoPath);
Image src = ImageIO.read(inputStream);
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 压缩LOGO
if (width > LOGO_WIDTH) {
width = LOGO_WIDTH;
}
if (height > LOGO_HEIGHT) {
height = LOGO_HEIGHT;
}
Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
/**
* 生成二维码(内嵌LOGO)
* 二维码文件名随机文件名可能会有重复
*
* @param content 内容
* @param logoPath LOGO地址
* @param destPath 存放目录
* @param needCompress 是否压缩LOGO
* @throws Exception
*/
public static String encode(String content, String logoPath, String destPath, boolean needCompress) throws Exception {
BufferedImage image = QrCodeUtils.createImage(content, logoPath, needCompress);
mkdirs(destPath);
String fileName = new Random().nextInt(99999999) + "." + FORMAT.toLowerCase();
ImageIO.write(image, FORMAT, new File(destPath + "/" + fileName));
return fileName;
}
/**
* 生成二维码(内嵌LOGO)
* 调用者指定二维码文件名
*
* @param content 内容
* @param logoPath LOGO地址
* @param destPath 存放目录
* @param fileName 二维码文件名
* @param needCompress 是否压缩LOGO
* @throws Exception
*/
public static String encode(String content, String logoPath, String destPath, String fileName, boolean needCompress) throws Exception {
BufferedImage image = QrCodeUtils.createImage(content, logoPath, needCompress);
mkdirs(destPath);
fileName = fileName.substring(0, fileName.indexOf(".") > 0 ? fileName.indexOf(".") : fileName.length())
+ "." + FORMAT.toLowerCase();
ImageIO.write(image, FORMAT, new File(destPath + "/" + fileName));
return fileName;
}
/**
* 当文件夹不存在时mkdirs会自动创建多层目录区别于mkdir
* (mkdir如果父目录不存在则会抛出异常)
*
* @param destPath 存放目录
*/
public static void mkdirs(String destPath) {
File file = new File(destPath);
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content 内容
* @param logoPath LOGO地址
* @param destPath 存储地址
* @throws Exception
*/
public static String encode(String content, String logoPath, String destPath) throws Exception {
return QrCodeUtils.encode(content, logoPath, destPath, false);
}
/**
* 生成二维码
*
* @param content 内容
* @param destPath 存储地址
* @param needCompress 是否压缩LOGO
* @throws Exception
*/
public static String encode(String content, String destPath, boolean needCompress) throws Exception {
return QrCodeUtils.encode(content, null, destPath, needCompress);
}
/**
* 生成二维码
*
* @param content 内容
* @param destPath 存储地址
* @throws Exception
*/
public static String encode(String content, String destPath) throws Exception {
return QrCodeUtils.encode(content, null, destPath, false);
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content 内容
* @param logoPath LOGO地址
* @param output 输出流
* @param needCompress 是否压缩LOGO
* @throws Exception
*/
public static void encode(String content, String logoPath, OutputStream output, boolean needCompress)
throws Exception {
BufferedImage image = QrCodeUtils.createImage(content, logoPath, needCompress);
ImageIO.write(image, FORMAT, output);
}
/**
* 生成二维码
*
* @param content 内容
* @param output 输出流
* @throws Exception
*/
public static void encode(String content, OutputStream output) throws Exception {
QrCodeUtils.encode(content, null, output, false);
}
}

View File

@ -1,40 +1,23 @@
package com.codesdream.ase.component.auth;
import com.codesdream.ase.model.permission.Function;
import com.codesdream.ase.repository.permission.FunctionRepository;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
@Component
public class ASEInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
private HashMap<String, Collection<ConfigAttribute>> map = null;
@Resource
private FunctionRepository functionRepository;
private void loadFunctionDefine(){
map = new HashMap<>();
Iterable<Function> functions = functionRepository.findAll();
for(Function function : functions) {
Collection<ConfigAttribute> array = new ArrayList<>();
ConfigAttribute cfg = new SecurityConfig(function.getName());
array.add(cfg);
map.put(function.getUrl(), array);
}
//TODO 给HashMap添加URL
}
@Override

View File

@ -1,38 +0,0 @@
package com.codesdream.ase.component.json.model;
import com.codesdream.ase.model.permission.FunctionalPermissionContainer;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.NoArgsConstructor;
import springfox.documentation.spring.web.json.Json;
@Data
@NoArgsConstructor
@ApiModel("功能性权限容器")
public class JsonableFPC {
private Integer id;
private String name;
private String description;
private boolean enabled;
private boolean deleted;
public JsonableFPC(FunctionalPermissionContainer fpc){
this.id = fpc.getId();
this.name = fpc.getName();
this.description = fpc.getDescription();
this.enabled = fpc.isEnabled();
this.deleted = fpc.isDeleted();
}
public FunctionalPermissionContainer parseObject(FunctionalPermissionContainer fpc){
fpc.setName(this.name);
fpc.setDescription(this.description);
fpc.setEnabled(this.enabled);
fpc.setDeleted(this.deleted);
return fpc;
}
}

View File

@ -1,62 +0,0 @@
package com.codesdream.ase.component.json.model;
import com.codesdream.ase.exception.notfound.NotFoundException;
import com.codesdream.ase.model.permission.FunctionalPermissionContainer;
import com.codesdream.ase.model.permission.FunctionalScopeRelation;
import com.codesdream.ase.model.permission.ScopePermissionContainer;
import com.codesdream.ase.service.IPermissionService;
import com.codesdream.ase.service.PermissionService;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.bind.annotation.RequestParam;
import javax.annotation.Resource;
import java.util.Optional;
@Data
@NoArgsConstructor
@ApiModel("单项权力")
public class JsonableFSR {
private Integer id;
private String name;
private String description;
private Integer fpcId;
private Integer spcId;
@Resource
@ApiModelProperty(hidden = true)
private IPermissionService permissionService;
public JsonableFSR(FunctionalScopeRelation fsr){
this.id = fsr.getId();
this.name = fsr.getName();
this.description = fsr.getDescription();
this.fpcId = fsr.getFunctionalPermissionContainer().getId();
this.spcId = fsr.getScopePermissionContainer().getId();
}
public FunctionalScopeRelation parseObject(FunctionalScopeRelation fsr){
fsr.setName(this.name);
fsr.setDescription(this.description);
if(this.fpcId != null){
Optional<FunctionalPermissionContainer> fpc = permissionService.findFPC(this.fpcId);
if(!fpc.isPresent()) throw new NotFoundException(this.fpcId.toString());
fsr.setFunctionalPermissionContainer(fpc.get());
}
if(this.spcId != null){
Optional<ScopePermissionContainer> spc = permissionService.findSPC(this.spcId);
if(!spc.isPresent()) throw new NotFoundException(this.spcId.toString());
fsr.setScopePermissionContainer(spc.get());
}
return fsr;
}
}

View File

@ -1,60 +0,0 @@
package com.codesdream.ase.component.json.model;
import com.codesdream.ase.exception.notfound.NotFoundException;
import com.codesdream.ase.model.permission.Function;
import com.codesdream.ase.service.IPermissionService;
import com.codesdream.ase.service.PermissionService;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import lombok.Data;
import lombok.NoArgsConstructor;
import springfox.documentation.annotations.ApiIgnore;
import javax.annotation.Resource;
import java.util.Optional;
@Data
@NoArgsConstructor
@ApiModel("功能")
public class JsonableFunction {
private Integer id;
private String name;
private String description;
private Integer fatherId;
private String url;
@Resource
@ApiModelProperty(hidden = true)
private IPermissionService permissionService;
public JsonableFunction(Function function){
this.id = function.getId();
this.name = function.getName();
this.description = function.getDescription();
if(function.getFather() != null) {
this.fatherId = function.getFather().getId();
}
else this.fatherId = null;
this.url = function.getUrl();
}
public Function parseObject(Function function){
function.setName(this.name);
function.setDescription(this.description);
if(this.fatherId != null) {
Optional<Function> fatherFunction = permissionService.findFunction(this.fatherId);
if (!fatherFunction.isPresent()) throw new NotFoundException(fatherId.toString());
function.setFather(fatherFunction.get());
}
function.setUrl(this.url);
return function;
}
}

View File

@ -1,22 +0,0 @@
package com.codesdream.ase.component.json.model;
import com.codesdream.ase.model.permission.PermissionContainersCollection;
import com.codesdream.ase.model.permission.Tag;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
@ApiModel("权限容器集合列表")
public class JsonablePCCList {
List<Integer> pccIdList;
public JsonablePCCList(Tag tag){
for(PermissionContainersCollection pcc : tag.getPermissionContainersCollections()){
pccIdList.add(pcc.getId());
}
}
}

View File

@ -1,26 +0,0 @@
package com.codesdream.ase.component.json.model;
import com.codesdream.ase.model.permission.Function;
import com.codesdream.ase.model.permission.FunctionalPermissionContainer;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.HashSet;
import java.util.Set;
@Data
@NoArgsConstructor
@ApiModel("功能性权限容器所属角色集合")
public class JsonableRoleList {
private Integer id;
private Set<Integer> functions = new HashSet<>();
public JsonableRoleList(FunctionalPermissionContainer fpc){
this.id = fpc.getId();
if(fpc.getFunctions() != null) {
for(Function function : fpc.getFunctions())
this.functions.add(function.getId());
}
}
}

View File

@ -1,39 +0,0 @@
package com.codesdream.ase.component.json.model;
import com.codesdream.ase.model.permission.ScopePermissionContainer;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@ApiModel("范围性权限容器")
public class JsonableSPC {
private Integer id;
private String name;
private String description;
private boolean enabled;
private boolean deleted;
public JsonableSPC(ScopePermissionContainer spc){
this.id = spc.getId();
this.name = spc.getName();
this.description = spc.getDescription();
this.enabled = spc.isEnabled();
this.deleted = spc.isDeleted();
}
public ScopePermissionContainer parseObject(ScopePermissionContainer spc){
spc.setName(this.name);
spc.setDescription(this.description);
spc.setEnabled(this.enabled);
spc.setDeleted(this.deleted);
return spc;
}
}

View File

@ -1,48 +0,0 @@
package com.codesdream.ase.component.json.model;
import com.codesdream.ase.model.permission.Tag;
import com.codesdream.ase.model.permission.User;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import net.bytebuddy.implementation.bind.annotation.DefaultMethod;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Data
@NoArgsConstructor
@ApiModel("标签")
public class JsonableTag {
@ApiModelProperty(value = "标签id")
private Integer id = null;
@ApiModelProperty(value = "标签名", example = "系统管理员")
private String name;
@ApiModelProperty(value = "标签说明", example = "该系统的管理员")
private String description;
private boolean enabled;
private boolean deleted;
public JsonableTag(Tag tag){
this.id = tag.getId();
this.name = tag.getName();
this.description = tag.getDescription();
this.enabled = tag.isEnabled();
this.deleted = tag.isDeleted();
}
public Tag parseObject(Tag tag){
tag.setName(this.name);
tag.setDescription(this.description);
tag.setDeleted(this.deleted);
tag.setEnabled(this.enabled);
return tag;
}
}

View File

@ -5,15 +5,14 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
@Component
public class UserAuthoritiesGenerator {
@Resource
UserFunctionsListGenerator userFunctionsListGenerator;
public Collection<? extends GrantedAuthority> grantedAuthorities(User user){
return userFunctionsListGenerator.generateRoles(user);
return new ArrayList<>();
}
}

View File

@ -1,41 +0,0 @@
package com.codesdream.ase.component.permission;
import com.codesdream.ase.model.permission.*;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
/**
* 生成功能性权限容器列表
*/
@Component
public class UserFPCListGenerator {
@Resource
private UserFSRGenerator fsrListGenerator;
public Collection<FunctionalPermissionContainer> generateFPC(
Collection<FunctionalScopeRelation> functionalScopeRelations){
Collection<FunctionalPermissionContainer> functionalPermissionContainers
= new ArrayList<>();
for (FunctionalScopeRelation functionalScopeRelation : functionalScopeRelations){
functionalPermissionContainers.add(functionalScopeRelation.getFunctionalPermissionContainer());
}
return functionalPermissionContainers;
}
public Collection<FunctionalPermissionContainer> generateFPCs(User user){
return generateFPC(
fsrListGenerator.generateFSRs(user)
);
}
public Collection<FunctionalPermissionContainer> generateFPCs(String username){
return generateFPC(
fsrListGenerator.generateFSRs(username)
);
}
}

View File

@ -1,45 +0,0 @@
package com.codesdream.ase.component.permission;
import com.codesdream.ase.model.permission.FunctionalScopeRelation;
import com.codesdream.ase.model.permission.PermissionContainersCollection;
import com.codesdream.ase.model.permission.User;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
/**
* 生成功能性权限容器与范围性权限容器关联对列表
*/
@Component
public class UserFSRGenerator {
@Resource
private UserPCCListGenerator userPCCListGenerator;
public Collection<FunctionalScopeRelation> generateFSRs(
Collection<PermissionContainersCollection> pccs){
Collection<FunctionalScopeRelation> fsrs =
new ArrayList<>();
for(PermissionContainersCollection pcc : pccs){
fsrs.addAll(pcc.getFunctionalScopeRelations());
}
return fsrs;
}
public Collection<FunctionalScopeRelation> generateFSRs(
User user){
return generateFSRs(
userPCCListGenerator.generatePCCs(user));
}
public Collection<FunctionalScopeRelation> generateFSRs(
String username){
return generateFSRs(
userPCCListGenerator.generatePCCs(username));
}
}

View File

@ -1,45 +0,0 @@
package com.codesdream.ase.component.permission;
import com.codesdream.ase.model.permission.Function;
import com.codesdream.ase.model.permission.FunctionalPermissionContainer;
import com.codesdream.ase.model.permission.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
/**
* 生成用户访问权限角色列表
*/
@Component
public class UserFunctionsListGenerator {
@Resource
private UserFPCListGenerator fpcListGenerator;
public Collection<GrantedAuthority> generateRoles(
Collection<FunctionalPermissionContainer> fpcs){
Collection<GrantedAuthority> authorities = new ArrayList<>();
for(FunctionalPermissionContainer fpc :fpcs){
for(Function function :fpc.getFunctions()){
authorities.add(new SimpleGrantedAuthority(function.getName()));
}
}
return authorities;
}
public Collection<GrantedAuthority> generateRoles(String username){
return generateRoles(
fpcListGenerator.generateFPCs(username)
);
}
public Collection<GrantedAuthority> generateRoles(User user){
return generateRoles(
fpcListGenerator.generateFPCs(user)
);
}
}

View File

@ -1,39 +0,0 @@
package com.codesdream.ase.component.permission;
import com.codesdream.ase.model.permission.PermissionContainersCollection;
import com.codesdream.ase.model.permission.Tag;
import com.codesdream.ase.model.permission.User;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
/**
* 生成权限容器集合列表
*/
@Component
public class UserPCCListGenerator {
@Resource
private UserTagsListGenerator userTagsListGenerator;
public Collection<PermissionContainersCollection> generatePCCs(
Collection<Tag> tags){
Collection<PermissionContainersCollection> pccs =
new ArrayList<>();
for(Tag tag : tags){
pccs.addAll(tag.getPermissionContainersCollections());
}
return pccs;
}
public Collection<PermissionContainersCollection> generatePCCs(
User user) {
return generatePCCs(userTagsListGenerator.generateTags(user));
}
public Collection<PermissionContainersCollection> generatePCCs(
String username){
return generatePCCs(userTagsListGenerator.generateTags(username));
}
}

View File

@ -1,54 +0,0 @@
package com.codesdream.ase.component.permission;
import com.codesdream.ase.model.permission.ScopePermissionContainer;
import com.codesdream.ase.model.permission.Tag;
import com.codesdream.ase.model.permission.User;
import com.codesdream.ase.repository.permission.UserRepository;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;
/**
* 生成用户标签列表
*/
@Component
public class UserTagsListGenerator {
@Resource
UserRepository userRepository;
public Collection<Tag> generateTags(ScopePermissionContainer spc){
return new ArrayList<>(spc.getTags());
}
public Collection<Tag> generateTags(User user){
return new ArrayList<Tag>(user.getTags());
}
public Collection<Tag> generateTags(String username){
Optional<User> user = userRepository.findByUsername(username);
// 检查用户是否存在
if(!user.isPresent()) throw new RuntimeException("User Not Found");
return generateTags(user.get());
}
public Collection<String> generateTagsName(User user){
Collection<String> tagsName = new ArrayList<>();
Collection<Tag> tags = generateTags(user);
for(Tag tag : tags){
tagsName.add(tag.getName());
}
return tagsName;
}
public Collection<String> generateTagsName(String username){
Optional<User> user = userRepository.findByUsername(username);
if(!user.isPresent()) throw new RuntimeException("User Not Found");
return generateTagsName(user.get());
}
}

View File

@ -1,22 +0,0 @@
package com.codesdream.ase.component.permission;
import com.codesdream.ase.model.permission.Tag;
import com.codesdream.ase.model.permission.User;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Collection;
/**
* 生成用户列表
*/
@Component
public class UsersListGenerator {
public Collection<User> generateUsers(Collection<Tag> tags){
Collection<User> users = new ArrayList<>();
for(Tag tag : tags){
users.addAll(tag.getUsers());
}
return users;
}
}

View File

@ -1,169 +0,0 @@
package com.codesdream.ase.controller.permission;
import com.codesdream.ase.component.datamanager.JSONParameter;
import com.codesdream.ase.component.json.model.JsonableFPC;
import com.codesdream.ase.component.json.model.JsonableFunction;
import com.codesdream.ase.component.json.model.JsonableRoleList;
import com.codesdream.ase.component.json.model.JsonableUser;
import com.codesdream.ase.exception.badrequest.AlreadyExistException;
import com.codesdream.ase.exception.notfound.NotFoundException;
import com.codesdream.ase.model.permission.Function;
import com.codesdream.ase.model.permission.FunctionalPermissionContainer;
import com.codesdream.ase.model.permission.Tag;
import com.codesdream.ase.model.permission.User;
import com.codesdream.ase.service.PermissionService;
import com.github.fge.jsonpatch.JsonPatch;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@RestController
@RequestMapping(value = "pmt")
@Api(tags = "功能性权限容器接口")
public class FPCController {
@Resource
private PermissionService permissionService;
@Resource
private JSONParameter jsonParameter;
@GetMapping("fpc")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "查找功能性权限容器")
public JsonableFPC getFPC(@RequestParam(value = "id") Integer id){
Optional<FunctionalPermissionContainer> fpc = permissionService.findFPC(id);
if(!fpc.isPresent()) throw new NotFoundException(id.toString());
return new JsonableFPC(fpc.get());
}
@PostMapping("fpc")
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(value = "创建新的功能性权限容器")
public JsonableFPC createFPC(@RequestBody JsonableFPC fpc){
if(permissionService.findFPC(fpc.getName()).isPresent()) throw new AlreadyExistException(fpc.getName());
FunctionalPermissionContainer functionalPermissionContainer = new FunctionalPermissionContainer();
return new JsonableFPC(permissionService.save(fpc.parseObject(functionalPermissionContainer)));
}
@GetMapping("fpcs")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "获得所有功能性权限容器的信息")
public Set<JsonableFPC> listFPC(){
Iterable<FunctionalPermissionContainer> fpcs = permissionService.findAllFPC();
Set<JsonableFPC> jsonableFPCS = new HashSet<>();
for(FunctionalPermissionContainer fpc : fpcs){
jsonableFPCS.add(new JsonableFPC(fpc));
}
return jsonableFPCS;
}
@GetMapping("fpc/roles")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "获得功能性权限容器所属角色")
public JsonableRoleList getFPCRoleList(@RequestParam(value = "id") Integer id){
Optional<FunctionalPermissionContainer> functionalPermissionContainer =
permissionService.findFPC(id);
if(!functionalPermissionContainer.isPresent()) throw new NotFoundException(id.toString());
return new JsonableRoleList(functionalPermissionContainer.get());
}
@PatchMapping("fpc")
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(value = "更新标功能性权限容器内容")
public JsonableFPC patchFPC(@RequestParam(value = "id") Integer id, @RequestBody JsonPatch patch){
Optional<FunctionalPermissionContainer> fpc = permissionService.findFPC(id);
if(!fpc.isPresent()) throw new NotFoundException(id.toString());
JsonableFPC jsonableFPC = new JsonableFPC(fpc.get());
jsonableFPC = jsonParameter.parsePathToObject(patch, jsonableFPC);
return new JsonableFPC(permissionService.update(jsonableFPC.parseObject(fpc.get())));
}
@GetMapping("fpc/funcs")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "功能性权限容器所含功能集合")
public Set<JsonableFunction> getFunctionFPC(@RequestParam(value = "id") Integer id){
Optional<FunctionalPermissionContainer> fpc = permissionService.findFPC(id);
if(!fpc.isPresent()) throw new NotFoundException(id.toString());
Set<JsonableFunction> jsonableFunctions = new HashSet<>();
for(Function function : fpc.get().getFunctions()){
jsonableFunctions.add(new JsonableFunction(function));
}
return jsonableFunctions;
}
@PutMapping("fpc/funcs")
@ApiOperation("搜索单个功能性权限容器所属功能集合信息")
public Set<JsonableFunction> setFunctionFPC(@RequestParam(value = "id") Integer id,
@RequestBody List<Integer> functionIdList){
Optional<FunctionalPermissionContainer> fpc = permissionService.findFPC(id);
if(!fpc.isPresent()) throw new NotFoundException(id.toString());
Set<Integer> functionSet = new HashSet<>(functionIdList);
fpc.get().setFunctions(permissionService.findFunctions(functionSet));
Set<JsonableFunction> jsonableFunctions = new HashSet<>();
for(Function function : permissionService.update(fpc.get()).getFunctions()){
jsonableFunctions.add(new JsonableFunction(function));
}
return jsonableFunctions;
}
@PostMapping("fpc/funcs")
@ApiOperation("从单个功能性权限容器所属功能集合中添加一个或多个功能")
public Set<JsonableFunction> addFunctionFPC(@RequestParam(value = "id") Integer id,
@RequestBody List<Integer> functionIdList){
Optional<FunctionalPermissionContainer> fpc = permissionService.findFPC(id);
if(!fpc.isPresent()) throw new NotFoundException(id.toString());
Set<Function> newFunctionSet = permissionService.findFunctions(new HashSet<>(functionIdList));
Set<Function> functionSet = fpc.get().getFunctions();
functionSet.addAll(newFunctionSet);
fpc.get().setFunctions(functionSet);
Set<JsonableFunction> jsonableFunctions = new HashSet<>();
for(Function function : permissionService.update(fpc.get()).getFunctions()){
jsonableFunctions.add(new JsonableFunction(function));
}
return jsonableFunctions;
}
@DeleteMapping("fpc/funcs")
@ResponseStatus(HttpStatus.OK)
@ApiOperation("从单个功能性权限容器所属功能集合中删除一个或多个功能")
public Set<JsonableFunction> deleteUserTag(@RequestParam Integer id,
@RequestBody List<Integer> functionIdList){
Optional<FunctionalPermissionContainer> fpc = permissionService.findFPC(id);
if(!fpc.isPresent()) throw new NotFoundException(id.toString());
Set<Function> functionSet = fpc.get().getFunctions();
Set<Function> deleteFuncSet = permissionService.findFunctions(new HashSet<>(functionIdList));
functionSet.removeAll(deleteFuncSet);
fpc.get().setFunctions(functionSet);
Set<JsonableFunction> jsonableFunctions = new HashSet<>();
for(Function function : permissionService.update(fpc.get()).getFunctions()){
jsonableFunctions.add(new JsonableFunction(function));
}
return jsonableFunctions;
}
}

View File

@ -1,78 +0,0 @@
package com.codesdream.ase.controller.permission;
import com.codesdream.ase.component.datamanager.JSONParameter;
import com.codesdream.ase.component.json.model.JsonableFPC;
import com.codesdream.ase.component.json.model.JsonableFunction;
import com.codesdream.ase.component.json.model.JsonableRoleList;
import com.codesdream.ase.exception.badrequest.AlreadyExistException;
import com.codesdream.ase.exception.notfound.NotFoundException;
import com.codesdream.ase.model.permission.Function;
import com.codesdream.ase.model.permission.FunctionalPermissionContainer;
import com.codesdream.ase.service.PermissionService;
import com.github.fge.jsonpatch.JsonPatch;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
@RestController
@RequestMapping(value = "pmt")
@Api(tags = "功能接口")
public class FunctionController {
@Resource
private PermissionService permissionService;
@Resource
private JSONParameter jsonParameter;
@GetMapping("func")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "查找功能")
public JsonableFunction getFunction(@RequestParam(value = "id") Integer id){
Optional<Function> function = permissionService.findFunction(id);
if(!function.isPresent()) throw new NotFoundException(id.toString());
return new JsonableFunction(function.get());
}
@PostMapping("func")
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(value = "创建新的功能")
public JsonableFunction createFunction(@RequestBody JsonableFunction function){
if(permissionService.findFunction(function.getName()).isPresent())
throw new AlreadyExistException(function.getName());
return new JsonableFunction(permissionService.save(function.parseObject(new Function())));
}
@GetMapping("funcs")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "获得所有功能的信息")
public Set<JsonableFunction> listFunction(){
Iterable<Function> functions = permissionService.findAllFunction();
Set<JsonableFunction> jsonableFunctions = new HashSet<>();
for(Function function : functions){
jsonableFunctions.add(new JsonableFunction(function));
}
return jsonableFunctions;
}
@PatchMapping("func")
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(value = "更新标功能内容")
public JsonableFunction patchFunction(@RequestParam(value = "id") Integer id, @RequestBody JsonPatch patch){
Optional<Function> function = permissionService.findFunction(id);
if(!function.isPresent()) throw new NotFoundException(id.toString());
JsonableFunction jsonableFunction = new JsonableFunction(function.get());
jsonableFunction = jsonParameter.parsePathToObject(patch, jsonableFunction);
return new JsonableFunction(permissionService.update(jsonableFunction.parseObject(function.get())));
}
}

View File

@ -1,92 +0,0 @@
package com.codesdream.ase.controller.permission;
import com.codesdream.ase.component.datamanager.JSONParameter;
import com.codesdream.ase.component.json.model.JsonableSPC;
import com.codesdream.ase.component.json.model.JsonableTag;
import com.codesdream.ase.exception.badrequest.AlreadyExistException;
import com.codesdream.ase.exception.notfound.NotFoundException;
import com.codesdream.ase.model.permission.ScopePermissionContainer;
import com.codesdream.ase.model.permission.Tag;
import com.codesdream.ase.service.PermissionService;
import com.github.fge.jsonpatch.JsonPatch;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
@RestController
@RequestMapping(value = "pmt")
@Api(tags = "范围性权限容器接口")
public class SPCController {
@Resource
private PermissionService permissionService;
@Resource
private JSONParameter jsonParameter;
@GetMapping(value = "spc")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "获得范围性权限容器信息")
public JsonableSPC getSPC(@RequestParam(value = "id") Integer id){
Optional<ScopePermissionContainer> spc = permissionService.findSPC(id);
if(!spc.isPresent()) throw new NotFoundException(id.toString());
return new JsonableSPC(spc.get());
}
@GetMapping(value = "spcs")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "获得所有的范围性权限容器信息")
public Set<JsonableSPC> listSPC(){
Iterable<ScopePermissionContainer> spcs = permissionService.findALLSPC();
Set<JsonableSPC> jsonableSPCS = new HashSet<>();
for(ScopePermissionContainer spc : spcs){
jsonableSPCS.add(new JsonableSPC(spc));
}
return jsonableSPCS;
}
@GetMapping(value = "spc/tags")
@ResponseStatus(HttpStatus.OK)
@ApiOperation(value = "查询范围性权限容器下的所有标签集合")
public Set<JsonableTag> listSPCTag(@RequestParam(value = "id") Integer id){
Optional<ScopePermissionContainer> spc = permissionService.findSPC(id);
if(!spc.isPresent()) throw new NotFoundException(id.toString());
Set<JsonableTag> tags = new HashSet<>();
for(Tag tag : spc.get().getTags()){
tags.add(new JsonableTag(tag));
}
return tags;
}
@PostMapping(value = "spc")
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(value = "创建范围性权限容器")
public JsonableSPC createSPC(@RequestBody JsonableSPC spc) {
if(permissionService.findSPC(spc.getName()).isPresent()) throw new AlreadyExistException(spc.getName());
return new JsonableSPC(permissionService.save(spc.parseObject(permissionService.getDefaultSPC(spc.getName()))));
}
@PatchMapping(value = "spc")
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(value = "更新范围性权限容器信息")
public JsonableSPC updateSPC(@RequestParam(value = "id") Integer id, @RequestBody JsonPatch patch){
Optional<ScopePermissionContainer> spc = permissionService.findSPC(id);
if(!spc.isPresent()) throw new NotFoundException(id.toString());
JsonableSPC jsonableSPC = jsonParameter.parsePathToObject(patch, new JsonableSPC(spc.get()));
return new JsonableSPC(permissionService.update(jsonableSPC.parseObject(spc.get())));
}
}

View File

@ -1,222 +0,0 @@
package com.codesdream.ase.controller.permission;
import com.codesdream.ase.component.datamanager.JSONParameter;
import com.codesdream.ase.component.json.model.JsonablePCCList;
import com.codesdream.ase.component.json.model.JsonableTag;
import com.codesdream.ase.component.json.model.JsonableUser;
import com.codesdream.ase.exception.badrequest.AlreadyExistException;
import com.codesdream.ase.exception.conflict.RelatedObjectsExistException;
import com.codesdream.ase.exception.notfound.NotFoundException;
import com.codesdream.ase.model.permission.PermissionContainersCollection;
import com.codesdream.ase.model.permission.Tag;
import com.codesdream.ase.model.permission.User;
import com.codesdream.ase.service.IUserService;
import com.codesdream.ase.service.PermissionService;
import com.github.fge.jsonpatch.JsonPatch;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@RestController
@RequestMapping("pmt")
@Api(tags = "标签管理接口")
public class TagController {
@Resource
private PermissionService permissionService;
@Resource
private IUserService userService;
@Resource
private JSONParameter jsonParameter;
// 根据名字创建新的标签
@PostMapping("tag")
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(value = "创建新的标签", notes = "创建标签时其ID自动分配指定ID无效")
public JsonableTag createTag(@RequestBody JsonableTag tag){
String tagName = tag.getName();
Optional<Tag> tagOptional = permissionService.findTag(tagName);
if(tagOptional.isPresent()) throw new AlreadyExistException(tagName);
return new JsonableTag(permissionService.save(tag.parseObject(permissionService.getDefaultTag(tag.getName()))));
}
// 根据名字搜索标签的简要信息
@GetMapping("tag")
@ResponseStatus(HttpStatus.OK)
@ApiOperation("搜索标签信息")
public JsonableTag checkTag(@RequestParam(value = "id") Integer id){
Optional<Tag> tagOptional = permissionService.findTag(id);
if(tagOptional.isPresent()){
return new JsonableTag(tagOptional.get());
}
else throw new NotFoundException(id.toString());
}
// 根据名字搜索标签的简要信息
@GetMapping("tags")
@ResponseStatus(HttpStatus.OK)
@ApiOperation("列出所有的标签信息")
public Set<JsonableTag> listTag(){
Iterable<Tag> tagIterable = permissionService.findAllTag();
Set<JsonableTag> jsonableTagSet = new HashSet<>();
for(Tag tag : tagIterable){
jsonableTagSet.add(new JsonableTag(tag));
}
return jsonableTagSet;
}
// 根据名字搜索标签的简要信息
@DeleteMapping("tag")
@ResponseStatus(HttpStatus.NO_CONTENT)
@ApiOperation("删除标签")
public void deleteTag(@RequestParam(value = "id") Integer id){
Optional<Tag> tag = permissionService.findTag(id);
if(!tag.isPresent()) throw new NotFoundException(id.toString());
// 检查外键关联
if(tag.get().getUsers().size() > 0) throw new RelatedObjectsExistException();
if(tag.get().getPermissionContainersCollections().size() > 0) throw new RelatedObjectsExistException();
permissionService.delete(tag.get());
}
// 根据名字搜索标签的简要信息
@PatchMapping(path = "tag")
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation("修改标签属性")
public JsonableTag updateTag(@RequestParam(value = "id") Integer id, @RequestBody JsonPatch patch){
Optional<Tag> tag = permissionService.findTag(id);
if(!tag.isPresent()) throw new NotFoundException(id.toString());
JsonableTag jsonableTag = new JsonableTag(tag.get());
jsonableTag = jsonParameter.parsePathToObject(patch, jsonableTag);
return new JsonableTag(permissionService.update(jsonableTag.parseObject(tag.get())));
}
@GetMapping("tag/users")
@ResponseStatus(HttpStatus.OK)
@ApiOperation("搜索单个标签所属用户集合信息")
public Set<JsonableUser> getUserTag(@RequestParam(value = "id") Integer id){
Optional<Tag> tag = permissionService.findTag(id);
if(!tag.isPresent()) throw new NotFoundException(id.toString());
Set<JsonableUser> jsonableUsers = new HashSet<>();
for(User user : tag.get().getUsers()){
jsonableUsers.add(new JsonableUser(user));
}
return jsonableUsers;
}
@PutMapping("tag/users")
@ApiOperation("搜索单个标签所属用户集合信息")
public Set<JsonableUser> setUserTag(@RequestParam(value = "id") Integer id,
@RequestBody List<Integer> userIdList){
Optional<Tag> tag = permissionService.findTag(id);
if(!tag.isPresent()) throw new NotFoundException(id.toString());
Set<Integer> userSet = new HashSet<>(userIdList);
tag.get().setUsers(userService.findUsersById(userSet));
Set<JsonableUser> jsonableUsers = new HashSet<>();
for(User user : permissionService.update(tag.get()).getUsers()){
jsonableUsers.add(new JsonableUser(user));
}
return jsonableUsers;
}
@PostMapping("tag/users")
@ApiOperation("从单个标签所属用户集合中添加一个或多个用户")
public Set<JsonableUser> addUserTag(@RequestParam(value = "id") Integer id,
@RequestBody List<Integer> userIdList){
Optional<Tag> tag = permissionService.findTag(id);
if(!tag.isPresent()) throw new NotFoundException(id.toString());
Set<User> newUserSet = userService.findUsersById(new HashSet<>(userIdList));
Set<User> userSet = tag.get().getUsers();
userSet.addAll(newUserSet);
tag.get().setUsers(userSet);
Set<JsonableUser> jsonableUsers = new HashSet<>();
for(User user : permissionService.update(tag.get()).getUsers()){
jsonableUsers.add(new JsonableUser(user));
}
return jsonableUsers;
}
@DeleteMapping("tag/users")
@ResponseStatus(HttpStatus.OK)
@ApiOperation("从单个标签所属用户集合中删除一个或多个用户")
public Set<JsonableUser> deleteUserTag(@RequestParam Integer id,
@RequestBody List<Integer> userIdList){
Optional<Tag> tag = permissionService.findTag(id);
if(!tag.isPresent()) throw new NotFoundException(id.toString());
Set<User> userSet = tag.get().getUsers();
Set<User> deleteUserSet = userService.findUsersById(new HashSet<>(userIdList));
userSet.removeAll(deleteUserSet);
tag.get().setUsers(userSet);
Set<JsonableUser> jsonableUsers = new HashSet<>();
for(User user : permissionService.update(tag.get()).getUsers()){
jsonableUsers.add(new JsonableUser(user));
}
return jsonableUsers;
}
@GetMapping("tags/users")
@ResponseStatus(HttpStatus.OK)
@ApiOperation("搜索多个标签所属用户集合信息")
public Set<JsonableUser> getUserTags(@RequestParam(value = "id") List<Integer> ids){
Set<Tag> tagSet = permissionService.findTags(ids);
Set<User> userSet = new HashSet<>();
Set<JsonableUser> jsonableUsers = new HashSet<>();
for(Tag tag : tagSet){
userSet.addAll(tag.getUsers());
}
for(User user : userSet){
jsonableUsers.add(new JsonableUser(user));
}
return jsonableUsers;
}
@GetMapping("tag/pcc")
@ResponseStatus(HttpStatus.OK)
@ApiOperation("获取标签所含权力列表")
public JsonablePCCList getPCCTag(@RequestParam(value = "id") Integer id){
Optional<Tag> tagOptional = permissionService.findTag(id);
if(!tagOptional.isPresent()) throw new NotFoundException(id.toString());
return new JsonablePCCList(tagOptional.get());
}
@PostMapping("tag/pcc")
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation("在指定标签的权限列表中添加一个或多个权限容器")
public JsonablePCCList addPCCTag(@RequestParam(value = "id") Integer id, JsonablePCCList jsonablePCCList){
Optional<Tag> tagOptional = permissionService.findTag(id);
if(!tagOptional.isPresent()) throw new NotFoundException(id.toString());
Set<PermissionContainersCollection> pccs = tagOptional.get().getPermissionContainersCollections();
pccs.addAll(permissionService.findPCCs(new HashSet<>(jsonablePCCList.getPccIdList())));
tagOptional.get().setPermissionContainersCollections(pccs);
return new JsonablePCCList(permissionService.save(tagOptional.get()));
}
}

View File

@ -1,13 +1,9 @@
package com.codesdream.ase.controller.permission;
import com.codesdream.ase.component.datamanager.JSONParameter;
import com.codesdream.ase.component.json.model.JsonableFunction;
import com.codesdream.ase.component.json.model.JsonableUser;
import com.codesdream.ase.exception.badrequest.AlreadyExistException;
import com.codesdream.ase.exception.notfound.NotFoundException;
import com.codesdream.ase.model.permission.Function;
import com.codesdream.ase.model.permission.User;
import com.codesdream.ase.service.PermissionService;
import com.codesdream.ase.service.UserService;
import com.github.fge.jsonpatch.JsonPatch;
import io.swagger.annotations.Api;

View File

@ -1,7 +1,5 @@
package com.codesdream.ase.exception.notfound;
import com.codesdream.ase.model.activity.AppendixFile;
import java.io.IOException;
public class AppendixFileNotFoundException extends IOException {

View File

@ -1,31 +0,0 @@
package com.codesdream.ase.model.permission;
import io.swagger.models.auth.In;
import lombok.Data;
import org.hibernate.annotations.GeneratorType;
import javax.persistence.*;
/**
* 功能
*/
@Data
@Entity
@Table(name = "function")
public class Function {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
// 功能名称
private String name;
// 功能描述
private String description;
@ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
private Function father = null;
// 授权url
private String url;
}

View File

@ -1,51 +0,0 @@
package com.codesdream.ase.model.permission;
import lombok.Data;
import javax.persistence.*;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* 功能性权限容器
*/
@Data
@Entity
@Table(name = "functional_permit_container")
public class FunctionalPermissionContainer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
// 功能性权限容器名
@Column(unique = true)
private String name = "";
// 功能性权限容器解释
private String description = "";
// 对应访问控制角色列表W
@ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
@Column(nullable = false)
private Set<Function> functions = new HashSet<>();
// 是否启用
@Column(nullable = false)
private boolean enabled = true;
// 是否删除
@Column(nullable = false)
private boolean deleted = false;
public FunctionalPermissionContainer(String name) {
this.name = name;
}
public FunctionalPermissionContainer(){
}
}

View File

@ -1,31 +0,0 @@
package com.codesdream.ase.model.permission;
import lombok.Data;
import javax.persistence.*;
/**
* 功能性权限容器与范围性权限容器关联对 (单项权力)
*/
@Data
@Entity
@Table(name = "functional_scope_relation")
public class FunctionalScopeRelation {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String description;
// 对应功能性权限容器
@OneToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
private FunctionalPermissionContainer functionalPermissionContainer;
// 对应范围性权限容器
@OneToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
private ScopePermissionContainer scopePermissionContainer;
}

View File

@ -1,37 +0,0 @@
package com.codesdream.ase.model.permission;
import lombok.Data;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
/**
* 权限容器集合多项权力
*/
@Data
@Entity
@Table(name = "permission_container_collection")
public class PermissionContainersCollection {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
// 权限容器集合名称
@Column(unique = true)
private String name = "";
// 权限容器集合概述
private String description = "";
// 对应功能性权限容器与范围性权限容器关联对
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<FunctionalScopeRelation> functionalScopeRelations = new HashSet<>();
public PermissionContainersCollection(String name){
this.name = name;
}
public PermissionContainersCollection(){
}
}

View File

@ -1,39 +0,0 @@
package com.codesdream.ase.model.permission;
import lombok.Data;
import javax.persistence.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
@Data
@Entity
@Table(name = "scope_permit_container")
public class ScopePermissionContainer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(unique = true)
private String name = "";
private String description = "";
@OneToMany(cascade = {CascadeType.MERGE, CascadeType.DETACH}, fetch = FetchType.LAZY)
private List<Tag> tags = new LinkedList<>();
@Column(nullable = false)
private boolean enabled = true;
@Column(nullable = false)
private boolean deleted = false;
public ScopePermissionContainer(String name){
this.name = name;
}
public ScopePermissionContainer(){
}
}

View File

@ -1,52 +0,0 @@
package com.codesdream.ase.model.permission;
import lombok.Data;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
/**
* 标签
*/
@Data
@Entity
@Table(name = "tag")
public class Tag {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
// 标签名
@Column(unique = true)
private String name = "";
// 标签解释
private String description = "";
// 标签关联用户
@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.DETACH}, fetch = FetchType.LAZY)
private Set<User> users = new HashSet<>();
// 启用标志
@Column(nullable = false)
private boolean enabled = true;
// 删除标志
@Column(nullable = false)
private boolean deleted = false;
// 对应权限容器集合
@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.DETACH}, fetch = FetchType.LAZY)
private Set<PermissionContainersCollection> permissionContainersCollections = new HashSet<>();
public Tag(String name) {
this.name = name;
}
public Tag(){
}
}

View File

@ -1,6 +1,5 @@
package com.codesdream.ase.model.permission;
import com.codesdream.ase.model.activity.UserActivity;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
@ -46,17 +45,10 @@ public class User implements UserDetails {
// 访问控制角色(不在数据表中) Spring Security
private transient Collection<?extends GrantedAuthority> authorities;
// 用户关联标签
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Tag> tags;
// 用户详细信息
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private UserDetail userDetail;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private UserActivity userActivity;
// 用户认证表
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private UserAuth userAuth;
@ -84,7 +76,6 @@ public class User implements UserDetails {
this.credentialsNonExpired = true;
this.deleted = false;
this.enabled = true;
this.tags = new HashSet<>();
this.userDetail = new UserDetail();
this.userAuth = new UserAuth();
this.authorities = new ArrayList<>();

View File

@ -1,5 +1,4 @@
package com.codesdream.ase.repository.leaves;
import com.codesdream.ase.model.activity.Report;
import com.codesdream.ase.model.leaves.Leave;
import org.springframework.data.repository.CrudRepository;

View File

@ -1,12 +0,0 @@
package com.codesdream.ase.repository.permission;
import com.codesdream.ase.model.permission.Function;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface FunctionRepository extends CrudRepository<Function, Integer> {
Optional<Function> findByName(String name);
}

View File

@ -1,12 +0,0 @@
package com.codesdream.ase.repository.permission;
import com.codesdream.ase.model.permission.FunctionalPermissionContainer;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface FunctionalPermissionContainerRepository extends CrudRepository<FunctionalPermissionContainer, Integer> {
Optional<FunctionalPermissionContainer> findByName(String name);
}

View File

@ -1,13 +0,0 @@
package com.codesdream.ase.repository.permission;
import com.codesdream.ase.model.permission.PermissionContainersCollection;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface PermissionContainersCollectionRepository
extends CrudRepository<PermissionContainersCollection, Integer> {
Optional<PermissionContainersCollection> findByName(String name);
}

View File

@ -1,10 +0,0 @@
package com.codesdream.ase.repository.permission;
import com.codesdream.ase.model.permission.ScopePermissionContainer;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
public interface ScopePermissionContainerRepository extends CrudRepository<ScopePermissionContainer, Integer> {
Optional<ScopePermissionContainer> findByName(String name);
}

View File

@ -1,14 +0,0 @@
package com.codesdream.ase.repository.permission;
import com.codesdream.ase.model.permission.FunctionalPermissionContainer;
import com.codesdream.ase.model.permission.Tag;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
import java.util.Set;
@Repository
public interface TagRepository extends CrudRepository<Tag, Integer> {
Optional<Tag> findByName(String name);
}

View File

@ -1,6 +1,5 @@
package com.codesdream.ase.repository.permission;
import com.codesdream.ase.model.permission.Tag;
import com.codesdream.ase.model.permission.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

View File

@ -1,140 +0,0 @@
package com.codesdream.ase.service;
import com.codesdream.ase.model.permission.*;
import javafx.util.Pair;
import java.util.*;
public interface IPermissionService {
FunctionalPermissionContainer getDefaultFPC(String name);
ScopePermissionContainer getDefaultSPC(String name);
PermissionContainersCollection getDefaultPCC(String name);
Tag getDefaultTag(String name);
// 查找用户标签
Optional<Tag> findTag(String name);
// 查找用户标签
Optional<Tag> findTag(Integer id);
// 列出所有的标签
Iterable<Tag> findAllTag();
Set<Tag> findTags(List<Integer> ids);
// 查找功能性权限容器
Optional<FunctionalPermissionContainer> findFPC(String name);
Iterable<FunctionalPermissionContainer> findAllFPC();
// 查找范围性权限容器
Optional<ScopePermissionContainer> findSPC(String name);
// 根据id查找功能性权限容器
Optional<FunctionalPermissionContainer> findFPC(int id);
Iterable<ScopePermissionContainer> findALLSPC();
// 根据id查找范围性权限容器
Optional<ScopePermissionContainer> findSPC(int id);
// 标签下所有的获得权限容器集合列表
Collection<PermissionContainersCollection> getPCCs(Tag tag);
Set<PermissionContainersCollection> findPCCs(Set<Integer> pccs);
Optional<PermissionContainersCollection> findPCC(Integer id);
// 查找功能
Optional<Function> findFunction(Integer id);
// 查找功能
Optional<Function> findFunction(String name);
// 根据序号列表寻找功能
Set<Function> findFunctions(Set<Integer> funcs);
Iterable<Function> findAllFunction();
// 获得范围性权限容器下的所有标签列表
Collection<Tag> getTagsFromSPC(
ScopePermissionContainer spc);
// 查找用户下的所有标签列表
Collection<Tag> getTagsFromUser(User user);
// 查找功能性权限容器下的所有范围性权限容器列表
Collection<FunctionalPermissionContainer> getFPCs(
PermissionContainersCollection pcc);
// 查找标签下的所有用户
Set<User> getUsersFromTag(Tag tag);
// 指定一对功能性权限容器与对应的范围性权限容器并添加到指定权限容器集合中
PermissionContainersCollection addRelationItemToPCC(
PermissionContainersCollection pcc,
FunctionalPermissionContainer fpc,
ScopePermissionContainer spc);
// 指定多对功能性权限容器与对应的范围性权限容器并添加到指定权限容器集合中
PermissionContainersCollection addRelationItemsToPCC(
PermissionContainersCollection pcc,
Collection<Pair<FunctionalPermissionContainer, ScopePermissionContainer>>
fspcPairs);
// 添加一个用户到指定标签中
Tag addUserToTag(Tag tag, User user);
// 添加多个用户到指定标签中
Tag addUsersToTag(Tag tag, Collection<User> users);
// 为功能性权限容器添加一个访问控制角色
FunctionalPermissionContainer addRoleToFPC(
FunctionalPermissionContainer fpc,
Function function);
// 为功能性权限容器添加多个访问控制角色
FunctionalPermissionContainer addRolesToFPC(
FunctionalPermissionContainer fpc,
Collection<Function> functions);
// 为范围性权限容器添加一个标签
ScopePermissionContainer addTagToSPC(ScopePermissionContainer spc, Tag tag);
// 为范围性权限容器添加多个标签
ScopePermissionContainer addTagsToSPC(ScopePermissionContainer spc, Collection<Tag> tags);
// 将一个权限容器集合添加到标签中
Tag addPCCToTag(Tag tag, PermissionContainersCollection pcc);
// 将多个权限容器集合添加到标签中
Tag addPCCsToTag(Tag tag, Collection<PermissionContainersCollection> pccs);
Tag save(Tag tag);
Function save(Function tag);
void delete(Tag tag);
FunctionalPermissionContainer save(FunctionalPermissionContainer fpc);
ScopePermissionContainer save(ScopePermissionContainer spc);
PermissionContainersCollection save(PermissionContainersCollection pcc);
Tag update(Tag tag);
Function update(Function function);
FunctionalPermissionContainer update(FunctionalPermissionContainer fpc);
ScopePermissionContainer update(ScopePermissionContainer spc);
PermissionContainersCollection update(PermissionContainersCollection pcc);
}

View File

@ -1,19 +0,0 @@
package com.codesdream.ase.service;
import com.codesdream.ase.model.activity.Activity;
import com.codesdream.ase.model.activity.Report;
import java.util.Optional;
public interface IReportService {
Optional<Report> findByTitle(String title);
Optional<Report> findByCreator(String creatorName);
Report save(Activity activity, Report report);
void delete(Report report);
Report update (Report report);
}

View File

@ -1,361 +0,0 @@
package com.codesdream.ase.service;
import com.codesdream.ase.component.permission.UserFPCListGenerator;
import com.codesdream.ase.component.permission.UserFSRGenerator;
import com.codesdream.ase.exception.badrequest.AlreadyExistException;
import com.codesdream.ase.exception.notfound.NotFoundException;
import com.codesdream.ase.model.permission.*;
import com.codesdream.ase.repository.permission.*;
import javafx.util.Pair;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.*;
@Service
public class PermissionService implements IPermissionService {
@Resource
private TagRepository tagRepository;
@Resource
private FunctionalPermissionContainerRepository fpcRepository;
@Resource
private ScopePermissionContainerRepository spcRepository;
@Resource
private PermissionContainersCollectionRepository pccRepository;
@Resource
private IUserService userService;
@Resource
private UserFPCListGenerator userFPCListGenerator;
@Resource
private UserFSRGenerator userFSRGenerator;
@Resource
private FunctionRepository functionRepository;
@Override
public FunctionalPermissionContainer getDefaultFPC(String name) {
return new FunctionalPermissionContainer(name);
}
@Override
public ScopePermissionContainer getDefaultSPC(String name) {
return new ScopePermissionContainer(name);
}
@Override
public PermissionContainersCollection getDefaultPCC(String name) {
return new PermissionContainersCollection(name);
}
@Override
public Tag getDefaultTag(String name) {
return new Tag(name);
}
@Override
public Optional<Tag> findTag(String name) {
return tagRepository.findByName(name);
}
@Override
public Optional<Tag> findTag(Integer id) {
return tagRepository.findById(id);
}
@Override
public Iterable<Tag> findAllTag() {
return tagRepository.findAll();
}
@Override
public Set<Tag> findTags(List<Integer> ids) {
Set<Tag> tagSet = new HashSet<>();
for(Integer id : ids){
Optional<Tag> tag = findTag(id);
if(!tag.isPresent()) throw new NotFoundException(id.toString());
tagSet.add(tag.get());
}
return tagSet;
}
@Override
public Optional<FunctionalPermissionContainer> findFPC(String name) {
return fpcRepository.findByName(name);
}
public Iterable<FunctionalPermissionContainer> findAllFPC() {
return fpcRepository.findAll();
}
@Override
public Optional<ScopePermissionContainer> findSPC(String name) {
return spcRepository.findByName(name);
}
@Override
public Optional<FunctionalPermissionContainer> findFPC(int id) {
return fpcRepository.findById(id);
}
@Override
public Iterable<ScopePermissionContainer> findALLSPC() {
return spcRepository.findAll();
}
@Override
public Optional<ScopePermissionContainer> findSPC(int id) {
return spcRepository.findById(id);
}
@Override
public Collection<PermissionContainersCollection> getPCCs(Tag tag) {
return new ArrayList<>(tag.getPermissionContainersCollections());
}
@Override
public Set<PermissionContainersCollection> findPCCs(Set<Integer> pccs) {
Set<PermissionContainersCollection> set = new HashSet<>();
for(Integer id : pccs){
Optional<PermissionContainersCollection> pcc = findPCC(id);
if(!pcc.isPresent()) throw new NotFoundException(String.format("PCCId: %d",id));
set.add(pcc.get());
}
return set;
}
@Override
public Optional<PermissionContainersCollection> findPCC(Integer id) {
return pccRepository.findById(id);
}
@Override
public Optional<Function> findFunction(Integer id) {
return functionRepository.findById(id);
}
@Override
public Optional<Function> findFunction(String name) {
return functionRepository.findByName(name);
}
@Override
public Set<Function> findFunctions(Set<Integer> funcs) {
Set<Function> set = new HashSet<>();
for(Integer id : funcs){
Optional<Function> function = findFunction(id);
if(!function.isPresent()) throw new NotFoundException(id.toString());
set.add(function.get());
}
return set;
}
@Override
public Iterable<Function> findAllFunction() {
return functionRepository.findAll();
}
@Override
public Collection<Tag> getTagsFromSPC(ScopePermissionContainer spc) {
return new ArrayList<>(spc.getTags());
}
@Override
public Collection<Tag> getTagsFromUser(User user) {
return new ArrayList<>(user.getTags());
}
@Override
public Collection<FunctionalPermissionContainer> getFPCs(
PermissionContainersCollection pcc)
{
Collection<PermissionContainersCollection> pccCollections =
new ArrayList<PermissionContainersCollection>(){{
add(pcc);
}};
// 生成功能性与范围性权限容器关联对
Collection<FunctionalScopeRelation> fsr =
userFSRGenerator.generateFSRs(pccCollections);
return userFPCListGenerator.generateFPC(fsr);
}
@Override
public Set<User> getUsersFromTag(Tag tag) {
return new HashSet<>(tag.getUsers());
}
@Override
public PermissionContainersCollection addRelationItemToPCC(PermissionContainersCollection pcc,
FunctionalPermissionContainer fpc,
ScopePermissionContainer spc)
{
if(!findFPC(fpc.getId()).isPresent()){
throw new RuntimeException("FPC NOT In Database");
}
if(!findSPC(spc.getId()).isPresent()){
throw new RuntimeException("SPC NOT In Database");
}
FunctionalScopeRelation relation = new FunctionalScopeRelation();
relation.setFunctionalPermissionContainer(fpc);
relation.setScopePermissionContainer(spc);
pcc.getFunctionalScopeRelations().add(relation);
return update(pcc);
}
@Override
public PermissionContainersCollection addRelationItemsToPCC(PermissionContainersCollection pcc,
Collection<Pair<FunctionalPermissionContainer, ScopePermissionContainer>> fspcPairs)
{
for(Pair<FunctionalPermissionContainer, ScopePermissionContainer> fspc :fspcPairs){
pcc = addRelationItemToPCC(pcc, fspc.getKey(), fspc.getValue());
}
return pcc;
}
@Override
public Tag addUserToTag(Tag tag, User user) {
// 检查用户是否存在
if(!userService.checkIfUserExists(user.getUsername()).getKey())
throw new RuntimeException("User Not Exist");
tag.getUsers().add(user);
return update(tag);
}
@Override
public Tag addUsersToTag(Tag tag, Collection<User> users) {
for(User user :users){
tag = addUserToTag(tag, user);
}
return tag;
}
@Override
public FunctionalPermissionContainer addRoleToFPC(FunctionalPermissionContainer fpc, Function function) {
fpc.getFunctions().add(function);
return update(fpc);
}
@Override
public FunctionalPermissionContainer addRolesToFPC(FunctionalPermissionContainer fpc, Collection<Function> functions) {
for(Function function : functions){
fpc = addRoleToFPC(fpc, function);
}
return fpc;
}
@Override
public ScopePermissionContainer addTagToSPC(ScopePermissionContainer spc, Tag tag) {
if(!tagRepository.findByName(tag.getName()).isPresent())
throw new RuntimeException("Tag Not Exist");
spc.getTags().add(tag);
return update(spc);
}
@Override
public ScopePermissionContainer addTagsToSPC(ScopePermissionContainer spc, Collection<Tag> tags) {
for(Tag tag :tags){
spc = addTagToSPC(spc, tag);
}
return spc;
}
@Override
public Tag addPCCToTag(Tag tag, PermissionContainersCollection pcc) {
if(!pccRepository.findByName(pcc.getName()).isPresent())
throw new RuntimeException("PCC Not Exist");
tag.getPermissionContainersCollections().add(pcc);
return update(tag);
}
@Override
public Tag addPCCsToTag(Tag tag, Collection<PermissionContainersCollection> pccs) {
for(PermissionContainersCollection pcc : pccs) {
tag = addPCCToTag(tag, pcc);
}
return tag;
}
@Override
public Tag save(Tag tag) {
if(tagRepository.findByName(tag.getName()).isPresent())
throw new AlreadyExistException(tag.getName());
return tagRepository.save(tag);
}
@Override
public Function save(Function function) {
if(functionRepository.findByName(function.getName()).isPresent())
throw new AlreadyExistException(function.getName());
return functionRepository.save(function);
}
@Override
public void delete(Tag tag) {
tagRepository.delete(tag);
}
@Override
public FunctionalPermissionContainer save(FunctionalPermissionContainer fpc) {
if(fpcRepository.findByName(fpc.getName()).isPresent())
throw new AlreadyExistException(fpc.getName());
return fpcRepository.save(fpc);
}
@Override
public ScopePermissionContainer save(ScopePermissionContainer spc) {
if(spcRepository.findByName(spc.getName()).isPresent())
throw new AlreadyExistException(spc.getName());
return spcRepository.save(spc);
}
@Override
public PermissionContainersCollection save(PermissionContainersCollection pcc) {
if(pccRepository.findByName(pcc.getName()).isPresent())
throw new RuntimeException(pcc.getName());
return pccRepository.save(pcc);
}
@Override
public Tag update(Tag tag) {
if(!tagRepository.findByName(tag.getName()).isPresent())
throw new NotFoundException(tag.getName());
return tagRepository.save(tag);
}
@Override
public Function update(Function function) {
if(!functionRepository.findByName(function.getName()).isPresent())
throw new NotFoundException(function.getName());
return functionRepository.save(function);
}
@Override
public FunctionalPermissionContainer update(FunctionalPermissionContainer fpc) {
if(!fpcRepository.findByName(fpc.getName()).isPresent())
throw new NotFoundException(fpc.getName());
return fpcRepository.save(fpc);
}
@Override
public ScopePermissionContainer update(ScopePermissionContainer spc) {
if(!spcRepository.findByName(spc.getName()).isPresent())
throw new NotFoundException(spc.getName());
return spcRepository.save(spc);
}
@Override
public PermissionContainersCollection update(PermissionContainersCollection pcc) {
if(!pccRepository.findByName(pcc.getName()).isPresent())
throw new NotFoundException(pcc.getName());
return pccRepository.save(pcc);
}
}

View File

@ -2,7 +2,6 @@ package com.codesdream.ase.service;
import com.codesdream.ase.component.auth.ASEPasswordEncoder;
import com.codesdream.ase.component.auth.ASEUsernameEncoder;
import com.codesdream.ase.component.permission.UserFunctionsListGenerator;
import com.codesdream.ase.exception.badrequest.UserInformationIllegalException;
import com.codesdream.ase.exception.notfound.UserNotFoundException;
import com.codesdream.ase.exception.badrequest.UsernameAlreadyExistException;
@ -19,8 +18,6 @@ import java.util.*;
@Service
public class UserService implements IUserService {
@Resource
private UserFunctionsListGenerator userFunctionsListGenerator;
@Resource
private UserRepository userRepository;
@ -56,7 +53,7 @@ public class UserService implements IUserService {
@Override
public Collection<? extends GrantedAuthority> getUserAuthorities(User user) {
return userFunctionsListGenerator.generateRoles(user);
return new ArrayList<>();
}
@Override

View File

@ -1,20 +0,0 @@
package com.codesdream.ase.validator;
import com.alibaba.fastjson.JSONObject;
import com.codesdream.ase.model.activity.Activity;
import org.springframework.stereotype.Component;
import java.nio.file.OpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
//检查当前活动各属性值是否合法存在
@Component
public class ActivityValidator {
public String[] check(Optional<JSONObject> json) {
return null;
}
}

View File

@ -1,76 +0,0 @@
package com.codesdream.ase.validator;
import com.codesdream.ase.model.activity.Attendance;
import com.codesdream.ase.model.activity.Period;
import com.codesdream.ase.model.activity.Report;
import com.codesdream.ase.model.permission.User;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
@Component
public class NullValueValidator {
/**
* 传入一个对象利用Java的反射机制判断各个属性的值是否为空并返回空值列表
* @param object 传入的对象
* @return 一个字符串列表维护值为空的属性的名字
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public List<String> checkNullValues (Object object) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Field[] fields = object.getClass().getDeclaredFields();
List<String> result = new ArrayList<>();
for (Field field : fields){
String name = field.getName();
String type = field.getGenericType().toString();
Method method = object.getClass().getMethod("get" + name);
name = field.getName();
if(type.equals("class java.lang.String")){
String str = (String) method.invoke(object);
if(str.isEmpty()) result.add(name);
}
else if(type.equals("class com.codesdream.ase.model.permission.User")){
User user = (User) method.invoke(object);
if(user == null) result.add(name);
}
else if(type.equals("java.util.Set<com.codesdream.ase.model.permission.User>")){
Set<User> users = (Set<User>) method.invoke(object);
if(users.isEmpty()) result.add(name);
}
else if(type.equals("class com.codesdream.ase.model.activity.Period")){
Period period = (Period) method.invoke(object);
if(period == null) result.add(name);
}
else if(type.equals(("class java.time.LocalDateTime"))){
LocalDateTime date = (LocalDateTime) method.invoke(object);
if(date == null) result.add(name);
}
else if(type.equals("java.util.List<java.lang.String>")){
List<String> strings = (List<String>) method.invoke(object);
if(strings.isEmpty()) result.add(name);
}
else if(type.equals("boolean")){
boolean a = (boolean) method.invoke(object);
if(!a) result.add(name);
}
else if(type.equals("class com.codesdream.ase.model.activity.Attendance")){
Attendance attendance = (Attendance) method.invoke(object);
if(attendance == null) result.add(name);
}
else if(type.equals("class com.codesdream.ase.model.activity.Report")){
Report report = (Report) method.invoke(object);
if(report == null) result.add(name);
}
}
return result;
}
}

View File

@ -1,27 +0,0 @@
package com.codesdream.ase.validator;
import com.codesdream.ase.model.activity.Activity;
import javafx.beans.binding.ObjectExpression;
import java.lang.reflect.Field;
public class TestNullValueValidator {
public static void main(String[] args){
Activity activity = new Activity();
TestNullValueValidator.run(activity);
}
static void run(Object object){
Field[] fields = object.getClass().getDeclaredFields();
for (Field field : fields){
String name = field.getName();
name = name.substring(0,1).toUpperCase()+name.substring(1);
String type = field.getGenericType().toString();
System.out.println("name: " + name);
System.out.println("Type: " + type);
System.out.println();
}
}
}

View File

@ -1,26 +0,0 @@
package com.codesdream.ase.test;
import com.codesdream.ase.model.activity.Activity;
import com.codesdream.ase.model.activity.Report;
import com.codesdream.ase.service.ActivityService;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
/**
* 成绩管理子系统单元测试
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
public class AchievementServiceTest {
@Resource
private AchievementService achievementService;
}

View File

@ -1,56 +0,0 @@
package com.codesdream.ase.test;
import com.codesdream.ase.model.activity.Activity;
import com.codesdream.ase.model.activity.Report;
import com.codesdream.ase.model.permission.User;
import com.codesdream.ase.service.ActivityService;
import com.codesdream.ase.service.UserService;
import javafx.util.Pair;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@SpringBootTest
@RunWith(SpringRunner.class)
public class ActivityServiceTest {
@Resource
ActivityService activityService;
@Resource
UserService userService;
//Activity model的增删改查
@Test
public void baseFuncTest(){
User creator = new User();
creator.setUsername("Tom");
creator.setPassword("123456");
creator.getUserAuth().setStudentID("2018303026");
creator.getUserAuth().setMail("937447984@qq.com");
creator.getUserAuth().setUserQuestion("Your favourite animal?");
creator.getUserAuth().setUserAnswer("Cat");
creator.getUserDetail().setAtSchool(true);
creator.getUserDetail().setRealName("张三");
Pair<Boolean, User> checker = userService.checkIfUserExists("Tom");
if(checker.getKey()){
userService.delete(checker.getValue());
}
creator = userService.save(creator);
Activity activity = new Activity();
activity.setTitle("活动1");
activity.setCreator(creator);
activity.setType("lo");
activity.setChiefManager(creator);
Report report = new Report();
report.setTitle("活动1的报告");
activity = activityService.save(activity);
activity = activityService.addReport(activity, report);
//activityService.delete();
//Activity activity1 = new Activity("活动2");
}
}

View File

@ -1,108 +0,0 @@
package com.codesdream.ase.test;
import com.codesdream.ase.component.activity.FileSystem;
import com.codesdream.ase.exception.notfound.AppendixFileNotFoundException;
import com.codesdream.ase.model.activity.AppendixFile;
import com.codesdream.ase.repository.activity.AppendixFileRespository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.io.InputStream;
import java.util.Scanner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class FileSystemTest {
@Resource
FileSystem fileSystem;
@Resource
AppendixFileService appendixFileService;
@Test
public void getPresentFilesTest()
{
Iterable<AppendixFile> appendixFiles = appendixFileService.findAll();
for (AppendixFile appendixFile:
appendixFiles) {
System.out.println(appendixFile.getFileName()+" "+appendixFile.getId()+" "+appendixFile.getType()+
" "+appendixFile.getLastEditTime().toString());
}
}
@Test
public void DeleteAllFilesTest()
{
Iterable<AppendixFile> appendixFiles = appendixFileService.findAll();
for (AppendixFile appendixFile:
appendixFiles) {
fileSystem.deleteFile(appendixFile.getId());
}
}
@Test
public void wrongIDTest()
{
int id = 1;
try {
InputStream inputStream = fileSystem.getFile(id);
} catch (AppendixFileNotFoundException e) {
System.out.println(e.getLocalizedMessage());
}
}
@Test
public void fileNotExistErrorTest()
{
int id = 268;
try {
InputStream inputStream = fileSystem.getFile(id);
} catch (AppendixFileNotFoundException e) {
System.out.println(e.getLocalizedMessage());
}
}
@Test
public void refreshDataBaseTest()
{
fileSystem.databaseRefresh();
}
@Test
public void refreshDiskTest()
{
fileSystem.diskRefresh();
}
@Test
public void createFile()
{
int id1 = 0;
try {
id1 = fileSystem.addFile("asfasefasgasgasg".getBytes(),"test1.txt");
} catch (Exception e) {
e.printStackTrace();
}
try {
int id2 = fileSystem.addFile("aspgjparjgpoarjgpjpeg".getBytes(),"test2.jpeg");
} catch (Exception e) {
e.printStackTrace();
}
InputStream inputStream = null;
try {
inputStream = fileSystem.getFile(id1);
} catch (AppendixFileNotFoundException e) {
e.printStackTrace();
}
Scanner scanner = new Scanner(inputStream, "UTF-8");
String text = scanner.useDelimiter("\\A").next();
System.out.println(text);
}
}

View File

@ -1,63 +0,0 @@
package com.codesdream.ase.test;
import com.codesdream.ase.model.permission.FunctionalPermissionContainer;
import com.codesdream.ase.model.permission.PermissionContainersCollection;
import com.codesdream.ase.model.permission.ScopePermissionContainer;
import com.codesdream.ase.model.permission.Tag;
import com.codesdream.ase.service.IPermissionService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@SpringBootTest
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
public class PermissionServiceTest {
@Resource
private IPermissionService permissionService;
@Test
public void PermissionServiceBaseTest(){
FunctionalPermissionContainer fpc = permissionService.getDefaultFPC("活动管理权");
fpc = permissionService.save(fpc);
Tag tag1 = permissionService.getDefaultTag("九班班长"),
tag2 = permissionService.getDefaultTag("九班班委"),
tag3 = permissionService.getDefaultTag("九班普通学生");
tag1 = permissionService.save(tag1);
tag2 = permissionService.save(tag2);
tag3 = permissionService.save(tag3);
ScopePermissionContainer spc = permissionService.getDefaultSPC("九班全体学生");
spc = permissionService.save(spc);
PermissionContainersCollection pcc = permissionService.getDefaultPCC("九班班长权限容器集合");
pcc = permissionService.save(pcc);
// 给活动管理权赋予添加/参与/管理的权力
/* fpc = permissionService.addRoleToFPC(fpc, "activity_create");
fpc = permissionService.addRoleToFPC(fpc, "activity_participate");
fpc = permissionService.addRoleToFPC(fpc, "activity_manage");*/
// 把九班班委加入到九班全体学生中
spc = permissionService.addTagToSPC(spc, tag2);
// 将九班普通学生加入到九班全体学生中
spc = permissionService.addTagToSPC(spc, tag3);
// 把活动管理权赋予范围九班全体学生,加入到九班班长权限容器集合中
pcc = permissionService.addRelationItemToPCC(pcc, fpc, spc);
// 将设置好的权限容器集合赋予九班班长
tag1 = permissionService.addPCCToTag(tag1, pcc);
}
@Test
public void PermissionServiceBaseTest2() {
}
}