style(web): 优化代码缩进
This commit is contained in:
@@ -29,24 +29,24 @@ import org.springframework.scheduling.annotation.EnableAsync;
|
||||
@EnableConfigurationProperties
|
||||
@EnableEncryptableProperties
|
||||
public class WebApplication implements ApplicationRunner {
|
||||
private final UserService userService;
|
||||
private final UserService userService;
|
||||
|
||||
public WebApplication(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
public WebApplication(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(WebApplication.class, args);
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(WebApplication.class, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) throws Exception {
|
||||
// 初始化系统管理员
|
||||
userService.initial();
|
||||
}
|
||||
@Override
|
||||
public void run(ApplicationArguments args) throws Exception {
|
||||
// 初始化系统管理员
|
||||
userService.initial();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuditorAware<User> auditorAware(UserService userService) {
|
||||
return userService::currentLoginUserOptional;
|
||||
}
|
||||
@Bean
|
||||
public AuditorAware<User> auditorAware(UserService userService) {
|
||||
return userService::currentLoginUserOptional;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,12 +16,12 @@ import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
*/
|
||||
@RestControllerAdvice
|
||||
public class ErrorController {
|
||||
private static final Logger logger = LoggerFactory.getLogger(ErrorController.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(ErrorController.class);
|
||||
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
@ExceptionHandler(Throwable.class)
|
||||
public AmisResponse<Object> errorHandler(Throwable throwable) {
|
||||
logger.error("Error", throwable);
|
||||
return AmisResponse.responseError(throwable.getMessage());
|
||||
}
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
@ExceptionHandler(Throwable.class)
|
||||
public AmisResponse<Object> errorHandler(Throwable throwable) {
|
||||
logger.error("Error", throwable);
|
||||
return AmisResponse.responseError(throwable.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,5 +12,5 @@ import org.springframework.context.annotation.Configuration;
|
||||
@ConfigurationProperties(prefix = "gringotts.host")
|
||||
@Configuration
|
||||
public class HostConfiguration {
|
||||
private String prefix = "http://127.0.0.1:20080";
|
||||
private String prefix = "http://127.0.0.1:20080";
|
||||
}
|
||||
|
||||
@@ -12,33 +12,33 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
* web配置
|
||||
*
|
||||
* @author wn
|
||||
* @since 2024-11-14
|
||||
* @since 2024-11-14
|
||||
*/
|
||||
@Slf4j
|
||||
@Configuration
|
||||
public class SaTokenConfiguration implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry
|
||||
.addInterceptor(
|
||||
new SaInterceptor(handler -> {
|
||||
SaRouter
|
||||
.match("/**")
|
||||
.notMatch("/")
|
||||
.notMatch("/index.html")
|
||||
.notMatch("/assets/**")
|
||||
.notMatch("/pages/**")
|
||||
.notMatch("/user/**")
|
||||
.notMatch("/upload/download/**")
|
||||
.check(r -> {
|
||||
try {
|
||||
StpUtil.checkLogin();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("账号未登陆", e);
|
||||
}
|
||||
});
|
||||
})
|
||||
)
|
||||
.addPathPatterns("/**");
|
||||
}
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
registry
|
||||
.addInterceptor(
|
||||
new SaInterceptor(handler -> {
|
||||
SaRouter
|
||||
.match("/**")
|
||||
.notMatch("/")
|
||||
.notMatch("/index.html")
|
||||
.notMatch("/assets/**")
|
||||
.notMatch("/pages/**")
|
||||
.notMatch("/user/**")
|
||||
.notMatch("/upload/download/**")
|
||||
.check(r -> {
|
||||
try {
|
||||
StpUtil.checkLogin();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("账号未登陆", e);
|
||||
}
|
||||
});
|
||||
})
|
||||
)
|
||||
.addPathPatterns("/**");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,80 +14,80 @@ import org.slf4j.LoggerFactory;
|
||||
* @date 2024-11-14
|
||||
*/
|
||||
public class SnowflakeIdGenerator implements IdentifierGenerator {
|
||||
private static final Logger logger = LoggerFactory.getLogger(SnowflakeIdGenerator.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(SnowflakeIdGenerator.class);
|
||||
|
||||
@Override
|
||||
public Serializable generate(SharedSessionContractImplementor session, Object object) {
|
||||
try {
|
||||
return Snowflake.next();
|
||||
} catch (Exception e) {
|
||||
logger.error("Generate snowflake id failed", e);
|
||||
throw new RuntimeException(e);
|
||||
@Override
|
||||
public Serializable generate(SharedSessionContractImplementor session, Object object) {
|
||||
try {
|
||||
return Snowflake.next();
|
||||
} catch (Exception e) {
|
||||
logger.error("Generate snowflake id failed", e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static class Snowflake {
|
||||
/**
|
||||
* 起始的时间戳
|
||||
*/
|
||||
private final static long START_TIMESTAMP = 1;
|
||||
|
||||
/**
|
||||
* 序列号占用的位数
|
||||
*/
|
||||
private final static long SEQUENCE_BIT = 11;
|
||||
|
||||
/**
|
||||
* 序列号最大值
|
||||
*/
|
||||
private final static long MAX_SEQUENCE_BIT = ~(-1 << SEQUENCE_BIT);
|
||||
|
||||
/**
|
||||
* 时间戳值向左位移
|
||||
*/
|
||||
private final static long TIMESTAMP_OFFSET = SEQUENCE_BIT;
|
||||
|
||||
/**
|
||||
* 序列号
|
||||
*/
|
||||
private static long sequence = 0;
|
||||
/**
|
||||
* 上一次时间戳
|
||||
*/
|
||||
private static long lastTimestamp = -1;
|
||||
|
||||
public static synchronized long next() {
|
||||
long currentTimestamp = nowTimestamp();
|
||||
if (currentTimestamp < lastTimestamp) {
|
||||
throw new RuntimeException("Clock have moved backwards.");
|
||||
}
|
||||
|
||||
if (currentTimestamp == lastTimestamp) {
|
||||
// 相同毫秒内, 序列号自增
|
||||
sequence = (sequence + 1) & MAX_SEQUENCE_BIT;
|
||||
// 同一毫秒的序列数已经达到最大
|
||||
if (sequence == 0) {
|
||||
currentTimestamp = nextTimestamp();
|
||||
}
|
||||
} else {
|
||||
// 不同毫秒内, 序列号置为0
|
||||
sequence = 0;
|
||||
}
|
||||
|
||||
lastTimestamp = currentTimestamp;
|
||||
return (currentTimestamp - START_TIMESTAMP) << TIMESTAMP_OFFSET | sequence;
|
||||
}
|
||||
|
||||
private static class Snowflake {
|
||||
/**
|
||||
* 起始的时间戳
|
||||
*/
|
||||
private final static long START_TIMESTAMP = 1;
|
||||
|
||||
/**
|
||||
* 序列号占用的位数
|
||||
*/
|
||||
private final static long SEQUENCE_BIT = 11;
|
||||
|
||||
/**
|
||||
* 序列号最大值
|
||||
*/
|
||||
private final static long MAX_SEQUENCE_BIT = ~(-1 << SEQUENCE_BIT);
|
||||
|
||||
/**
|
||||
* 时间戳值向左位移
|
||||
*/
|
||||
private final static long TIMESTAMP_OFFSET = SEQUENCE_BIT;
|
||||
|
||||
/**
|
||||
* 序列号
|
||||
*/
|
||||
private static long sequence = 0;
|
||||
/**
|
||||
* 上一次时间戳
|
||||
*/
|
||||
private static long lastTimestamp = -1;
|
||||
|
||||
public static synchronized long next() {
|
||||
long currentTimestamp = nowTimestamp();
|
||||
if (currentTimestamp < lastTimestamp) {
|
||||
throw new RuntimeException("Clock have moved backwards.");
|
||||
}
|
||||
|
||||
if (currentTimestamp == lastTimestamp) {
|
||||
// 相同毫秒内, 序列号自增
|
||||
sequence = (sequence + 1) & MAX_SEQUENCE_BIT;
|
||||
// 同一毫秒的序列数已经达到最大
|
||||
if (sequence == 0) {
|
||||
currentTimestamp = nextTimestamp();
|
||||
}
|
||||
} else {
|
||||
// 不同毫秒内, 序列号置为0
|
||||
sequence = 0;
|
||||
}
|
||||
|
||||
lastTimestamp = currentTimestamp;
|
||||
return (currentTimestamp - START_TIMESTAMP) << TIMESTAMP_OFFSET | sequence;
|
||||
}
|
||||
|
||||
private static long nextTimestamp() {
|
||||
long milli = nowTimestamp();
|
||||
while (milli <= lastTimestamp) {
|
||||
milli = nowTimestamp();
|
||||
}
|
||||
return milli;
|
||||
}
|
||||
|
||||
private static long nowTimestamp() {
|
||||
return Instant.now().toEpochMilli();
|
||||
}
|
||||
private static long nextTimestamp() {
|
||||
long milli = nowTimestamp();
|
||||
while (milli <= lastTimestamp) {
|
||||
milli = nowTimestamp();
|
||||
}
|
||||
return milli;
|
||||
}
|
||||
|
||||
private static long nowTimestamp() {
|
||||
return Instant.now().toEpochMilli();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,5 +14,5 @@ import org.springframework.context.annotation.Configuration;
|
||||
@ConfigurationProperties(prefix = "gringotts.upload")
|
||||
@Configuration
|
||||
public class UploadConfiguration {
|
||||
private String uploadPath = "./upload";
|
||||
private String uploadPath = "./upload";
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ package com.eshore.gringotts.web.configuration.amis;
|
||||
* @date 2023-07-06
|
||||
*/
|
||||
public class AmisItemResponse extends AmisMapResponse {
|
||||
public void setDetail(Object detail) {
|
||||
getData().put("item", detail);
|
||||
}
|
||||
public void setDetail(Object detail) {
|
||||
getData().put("item", detail);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,24 +7,24 @@ package com.eshore.gringotts.web.configuration.amis;
|
||||
* @date 2023-07-06
|
||||
*/
|
||||
public class AmisListResponse extends AmisMapResponse {
|
||||
public void setData(Iterable<?> list) {
|
||||
getData().put("items", list);
|
||||
}
|
||||
public void setData(Iterable<?> list) {
|
||||
getData().put("items", list);
|
||||
}
|
||||
|
||||
public void setTotal(Long total) {
|
||||
getData().put("total", total);
|
||||
}
|
||||
public void setTotal(Long total) {
|
||||
getData().put("total", total);
|
||||
}
|
||||
|
||||
public void setTotal(Integer total) {
|
||||
setTotal(total.longValue());
|
||||
}
|
||||
public void setTotal(Integer total) {
|
||||
setTotal(total.longValue());
|
||||
}
|
||||
|
||||
public void setData(Iterable<?> list, Long total) {
|
||||
setData(list);
|
||||
setTotal(total);
|
||||
}
|
||||
public void setData(Iterable<?> list, Long total) {
|
||||
setData(list);
|
||||
setTotal(total);
|
||||
}
|
||||
|
||||
public void setData(Iterable<?> list, Integer total) {
|
||||
setData(list, total.longValue());
|
||||
}
|
||||
public void setData(Iterable<?> list, Integer total) {
|
||||
setData(list, total.longValue());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,12 +10,12 @@ import java.util.Map;
|
||||
* @date 2023-07-06
|
||||
*/
|
||||
public class AmisMapResponse extends AmisResponse<Map<String, Object>> {
|
||||
public AmisMapResponse() {
|
||||
setData(new HashMap<>());
|
||||
}
|
||||
public AmisMapResponse() {
|
||||
setData(new HashMap<>());
|
||||
}
|
||||
|
||||
public AmisMapResponse setData(String key, Object value) {
|
||||
getData().put(key, value);
|
||||
return this;
|
||||
}
|
||||
public AmisMapResponse setData(String key, Object value) {
|
||||
getData().put(key, value);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,91 +16,91 @@ import lombok.ToString;
|
||||
@Getter
|
||||
@Setter
|
||||
public class AmisResponse<T> {
|
||||
private static final int SUCCESS_STATUS = 0;
|
||||
private static final int ERROR_STATUS = 500;
|
||||
private static final String SUCCESS_MESSAGE = "成功";
|
||||
private static final String ERROR_MESSAGE = "错误";
|
||||
private Integer status;
|
||||
@JsonProperty("msg")
|
||||
private String message;
|
||||
private T data;
|
||||
private static final int SUCCESS_STATUS = 0;
|
||||
private static final int ERROR_STATUS = 500;
|
||||
private static final String SUCCESS_MESSAGE = "成功";
|
||||
private static final String ERROR_MESSAGE = "错误";
|
||||
private Integer status;
|
||||
@JsonProperty("msg")
|
||||
private String message;
|
||||
private T data;
|
||||
|
||||
public static AmisResponse<Object> responseError() {
|
||||
return responseError(ERROR_MESSAGE);
|
||||
}
|
||||
public static AmisResponse<Object> responseError() {
|
||||
return responseError(ERROR_MESSAGE);
|
||||
}
|
||||
|
||||
public static AmisResponse<Object> responseError(String message) {
|
||||
AmisResponse<Object> response = new AmisResponse<>();
|
||||
response.setStatus(ERROR_STATUS);
|
||||
response.setMessage(message);
|
||||
return response;
|
||||
}
|
||||
public static AmisResponse<Object> responseError(String message) {
|
||||
AmisResponse<Object> response = new AmisResponse<>();
|
||||
response.setStatus(ERROR_STATUS);
|
||||
response.setMessage(message);
|
||||
return response;
|
||||
}
|
||||
|
||||
public static AmisResponse<Object> responseSuccess() {
|
||||
return responseSuccess(SUCCESS_MESSAGE);
|
||||
}
|
||||
public static AmisResponse<Object> responseSuccess() {
|
||||
return responseSuccess(SUCCESS_MESSAGE);
|
||||
}
|
||||
|
||||
public static AmisResponse<Object> responseSuccess(String message) {
|
||||
AmisResponse<Object> response = new AmisResponse<>();
|
||||
response.setStatus(SUCCESS_STATUS);
|
||||
response.setMessage(message);
|
||||
return response;
|
||||
}
|
||||
public static AmisResponse<Object> responseSuccess(String message) {
|
||||
AmisResponse<Object> response = new AmisResponse<>();
|
||||
response.setStatus(SUCCESS_STATUS);
|
||||
response.setMessage(message);
|
||||
return response;
|
||||
}
|
||||
|
||||
public static <E> AmisResponse<E> responseSuccess(String message, E data) {
|
||||
AmisResponse<E> response = new AmisResponse<>();
|
||||
response.setStatus(SUCCESS_STATUS);
|
||||
response.setMessage(message);
|
||||
response.setData(data);
|
||||
return response;
|
||||
}
|
||||
public static <E> AmisResponse<E> responseSuccess(String message, E data) {
|
||||
AmisResponse<E> response = new AmisResponse<>();
|
||||
response.setStatus(SUCCESS_STATUS);
|
||||
response.setMessage(message);
|
||||
response.setData(data);
|
||||
return response;
|
||||
}
|
||||
|
||||
public static <E> AmisResponse<E> responseSuccess(E data) {
|
||||
return responseSuccess(SUCCESS_MESSAGE, data);
|
||||
}
|
||||
public static <E> AmisResponse<E> responseSuccess(E data) {
|
||||
return responseSuccess(SUCCESS_MESSAGE, data);
|
||||
}
|
||||
|
||||
public static AmisMapResponse responseMapData() {
|
||||
AmisMapResponse response = new AmisMapResponse();
|
||||
response.setStatus(SUCCESS_STATUS);
|
||||
response.setMessage(SUCCESS_MESSAGE);
|
||||
return response;
|
||||
}
|
||||
public static AmisMapResponse responseMapData() {
|
||||
AmisMapResponse response = new AmisMapResponse();
|
||||
response.setStatus(SUCCESS_STATUS);
|
||||
response.setMessage(SUCCESS_MESSAGE);
|
||||
return response;
|
||||
}
|
||||
|
||||
public static AmisMapResponse responseMapData(Map<String, Object> data) {
|
||||
AmisMapResponse response = responseMapData();
|
||||
response.setData(data);
|
||||
return response;
|
||||
}
|
||||
public static AmisMapResponse responseMapData(Map<String, Object> data) {
|
||||
AmisMapResponse response = responseMapData();
|
||||
response.setData(data);
|
||||
return response;
|
||||
}
|
||||
|
||||
public static AmisMapResponse responseMapData(String key, Object value) {
|
||||
AmisMapResponse response = responseMapData();
|
||||
response.setData(key, value);
|
||||
return response;
|
||||
}
|
||||
public static AmisMapResponse responseMapData(String key, Object value) {
|
||||
AmisMapResponse response = responseMapData();
|
||||
response.setData(key, value);
|
||||
return response;
|
||||
}
|
||||
|
||||
public static AmisListResponse responseListData(Iterable<?> data) {
|
||||
AmisListResponse response = new AmisListResponse();
|
||||
response.setStatus(SUCCESS_STATUS);
|
||||
response.setMessage(SUCCESS_MESSAGE);
|
||||
response.setData(data);
|
||||
return response;
|
||||
}
|
||||
public static AmisListResponse responseListData(Iterable<?> data) {
|
||||
AmisListResponse response = new AmisListResponse();
|
||||
response.setStatus(SUCCESS_STATUS);
|
||||
response.setMessage(SUCCESS_MESSAGE);
|
||||
response.setData(data);
|
||||
return response;
|
||||
}
|
||||
|
||||
public static AmisListResponse responseListData(Iterable<?> data, Integer total) {
|
||||
AmisListResponse response = responseListData(data);
|
||||
response.setTotal(total);
|
||||
return response;
|
||||
}
|
||||
public static AmisListResponse responseListData(Iterable<?> data, Integer total) {
|
||||
AmisListResponse response = responseListData(data);
|
||||
response.setTotal(total);
|
||||
return response;
|
||||
}
|
||||
|
||||
public static AmisListResponse responseListData(Iterable<?> data, Long total) {
|
||||
AmisListResponse response = responseListData(data);
|
||||
response.setTotal(total);
|
||||
return response;
|
||||
}
|
||||
public static AmisListResponse responseListData(Iterable<?> data, Long total) {
|
||||
AmisListResponse response = responseListData(data);
|
||||
response.setTotal(total);
|
||||
return response;
|
||||
}
|
||||
|
||||
public static AmisItemResponse responseItemData(Object detail) {
|
||||
AmisItemResponse response = new AmisItemResponse();
|
||||
response.setDetail(detail);
|
||||
return response;
|
||||
}
|
||||
public static AmisItemResponse responseItemData(Object detail) {
|
||||
AmisItemResponse response = new AmisItemResponse();
|
||||
response.setDetail(detail);
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,5 +7,5 @@ import com.eshore.gringotts.web.configuration.amis.AmisResponse;
|
||||
* @date 2024-11-28
|
||||
*/
|
||||
public interface DetailController<DETAIL_ITEM> {
|
||||
AmisResponse<DETAIL_ITEM> detail(Long id) throws Exception;
|
||||
AmisResponse<DETAIL_ITEM> detail(Long id) throws Exception;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import org.eclipse.collections.api.list.ImmutableList;
|
||||
* @date 2024-11-28
|
||||
*/
|
||||
public interface ListController<LIST_ITEM> {
|
||||
AmisResponse<ImmutableList<LIST_ITEM>> list() throws Exception;
|
||||
AmisResponse<ImmutableList<LIST_ITEM>> list() throws Exception;
|
||||
|
||||
AmisResponse<ImmutableList<LIST_ITEM>> list(Query query) throws Exception;
|
||||
AmisResponse<ImmutableList<LIST_ITEM>> list(Query query) throws Exception;
|
||||
}
|
||||
|
||||
@@ -7,5 +7,5 @@ import com.eshore.gringotts.web.configuration.amis.AmisResponse;
|
||||
* @date 2024-11-28
|
||||
*/
|
||||
public interface RemoveController {
|
||||
AmisResponse<Object> remove(Long id) throws Exception;
|
||||
AmisResponse<Object> remove(Long id) throws Exception;
|
||||
}
|
||||
|
||||
@@ -7,5 +7,5 @@ import com.eshore.gringotts.web.configuration.amis.AmisResponse;
|
||||
* @date 2024-11-28
|
||||
*/
|
||||
public interface SaveController<SAVE_ITEM> {
|
||||
AmisResponse<Long> save(SAVE_ITEM item) throws Exception;
|
||||
AmisResponse<Long> save(SAVE_ITEM item) throws Exception;
|
||||
}
|
||||
|
||||
@@ -19,66 +19,66 @@ import org.springframework.web.bind.annotation.RequestBody;
|
||||
*/
|
||||
@Slf4j
|
||||
public abstract class SimpleControllerSupport<ENTITY extends SimpleEntity, SAVE_ITEM, LIST_ITEM, DETAIL_ITEM> implements SimpleController<SAVE_ITEM, LIST_ITEM, DETAIL_ITEM> {
|
||||
protected static final String SAVE = "/save";
|
||||
protected static final String LIST = "/list";
|
||||
protected static final String DETAIL = "/detail/{id}";
|
||||
protected static final String REMOVE = "/remove/{id}";
|
||||
protected static final String SAVE = "/save";
|
||||
protected static final String LIST = "/list";
|
||||
protected static final String DETAIL = "/detail/{id}";
|
||||
protected static final String REMOVE = "/remove/{id}";
|
||||
|
||||
private final SimpleServiceSupport<ENTITY> service;
|
||||
private final SimpleServiceSupport<ENTITY> service;
|
||||
|
||||
public SimpleControllerSupport(SimpleServiceSupport<ENTITY> service) {
|
||||
this.service = service;
|
||||
public SimpleControllerSupport(SimpleServiceSupport<ENTITY> service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@PostMapping(SAVE)
|
||||
@Override
|
||||
public AmisResponse<Long> save(@RequestBody SAVE_ITEM item) throws Exception {
|
||||
return AmisResponse.responseSuccess(service.save(fromSaveItem(item)));
|
||||
}
|
||||
|
||||
@GetMapping(LIST)
|
||||
@Override
|
||||
public AmisResponse<ImmutableList<LIST_ITEM>> list() throws Exception {
|
||||
return AmisResponse.responseSuccess(service.list().collect(entity -> {
|
||||
try {
|
||||
return toListItem(entity);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@PostMapping(LIST)
|
||||
@Override
|
||||
public AmisResponse<ImmutableList<LIST_ITEM>> list(@RequestBody Query query) throws Exception {
|
||||
if (ObjectUtil.isNull(query)) {
|
||||
return AmisResponse.responseSuccess(Lists.immutable.empty());
|
||||
}
|
||||
return AmisResponse.responseSuccess(service.list(query).collect(entity -> {
|
||||
try {
|
||||
return toListItem(entity);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@PostMapping(SAVE)
|
||||
@Override
|
||||
public AmisResponse<Long> save(@RequestBody SAVE_ITEM item) throws Exception {
|
||||
return AmisResponse.responseSuccess(service.save(fromSaveItem(item)));
|
||||
}
|
||||
@GetMapping(DETAIL)
|
||||
@Override
|
||||
public AmisResponse<DETAIL_ITEM> detail(@PathVariable Long id) throws Exception {
|
||||
return AmisResponse.responseSuccess(toDetailItem(service.detailOrThrow(id)));
|
||||
}
|
||||
|
||||
@GetMapping(LIST)
|
||||
@Override
|
||||
public AmisResponse<ImmutableList<LIST_ITEM>> list() throws Exception {
|
||||
return AmisResponse.responseSuccess(service.list().collect(entity -> {
|
||||
try {
|
||||
return toListItem(entity);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}));
|
||||
}
|
||||
@GetMapping(REMOVE)
|
||||
@Override
|
||||
public AmisResponse<Object> remove(@PathVariable Long id) {
|
||||
service.remove(id);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@PostMapping(LIST)
|
||||
@Override
|
||||
public AmisResponse<ImmutableList<LIST_ITEM>> list(@RequestBody Query query) throws Exception {
|
||||
if (ObjectUtil.isNull(query)) {
|
||||
return AmisResponse.responseSuccess(Lists.immutable.empty());
|
||||
}
|
||||
return AmisResponse.responseSuccess(service.list(query).collect(entity -> {
|
||||
try {
|
||||
return toListItem(entity);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}));
|
||||
}
|
||||
protected abstract ENTITY fromSaveItem(SAVE_ITEM item) throws Exception;
|
||||
|
||||
@GetMapping(DETAIL)
|
||||
@Override
|
||||
public AmisResponse<DETAIL_ITEM> detail(@PathVariable Long id) throws Exception {
|
||||
return AmisResponse.responseSuccess(toDetailItem(service.detailOrThrow(id)));
|
||||
}
|
||||
protected abstract LIST_ITEM toListItem(ENTITY entity) throws Exception;
|
||||
|
||||
@GetMapping(REMOVE)
|
||||
@Override
|
||||
public AmisResponse<Object> remove(@PathVariable Long id) {
|
||||
service.remove(id);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
protected abstract ENTITY fromSaveItem(SAVE_ITEM item) throws Exception;
|
||||
|
||||
protected abstract LIST_ITEM toListItem(ENTITY entity) throws Exception;
|
||||
|
||||
protected abstract DETAIL_ITEM toDetailItem(ENTITY entity) throws Exception;
|
||||
protected abstract DETAIL_ITEM toDetailItem(ENTITY entity) throws Exception;
|
||||
}
|
||||
|
||||
@@ -12,50 +12,50 @@ import org.eclipse.collections.api.map.ImmutableMap;
|
||||
*/
|
||||
@Data
|
||||
public class Query {
|
||||
private Queryable query;
|
||||
private ImmutableList<Sortable> sort;
|
||||
private Pageable page;
|
||||
private Queryable query;
|
||||
private ImmutableList<Sortable> sort;
|
||||
private Pageable page;
|
||||
|
||||
@Data
|
||||
public static class Queryable {
|
||||
private ImmutableList<String> nullEqual;
|
||||
private ImmutableList<String> notNullEqual;
|
||||
private ImmutableList<String> empty;
|
||||
private ImmutableList<String> notEmpty;
|
||||
private ImmutableMap<String, ?> equal;
|
||||
private ImmutableMap<String, ?> notEqual;
|
||||
private ImmutableMap<String, String> like;
|
||||
private ImmutableMap<String, String> notLike;
|
||||
private ImmutableMap<String, ?> great;
|
||||
private ImmutableMap<String, ?> less;
|
||||
private ImmutableMap<String, ?> greatEqual;
|
||||
private ImmutableMap<String, ?> lessEqual;
|
||||
private ImmutableMap<String, ImmutableList<?>> in;
|
||||
private ImmutableMap<String, ImmutableList<?>> notIn;
|
||||
private ImmutableMap<String, Between> between;
|
||||
private ImmutableMap<String, Between> notBetween;
|
||||
|
||||
@Data
|
||||
public static class Queryable {
|
||||
private ImmutableList<String> nullEqual;
|
||||
private ImmutableList<String> notNullEqual;
|
||||
private ImmutableList<String> empty;
|
||||
private ImmutableList<String> notEmpty;
|
||||
private ImmutableMap<String, ?> equal;
|
||||
private ImmutableMap<String, ?> notEqual;
|
||||
private ImmutableMap<String, String> like;
|
||||
private ImmutableMap<String, String> notLike;
|
||||
private ImmutableMap<String, ?> great;
|
||||
private ImmutableMap<String, ?> less;
|
||||
private ImmutableMap<String, ?> greatEqual;
|
||||
private ImmutableMap<String, ?> lessEqual;
|
||||
private ImmutableMap<String, ImmutableList<?>> in;
|
||||
private ImmutableMap<String, ImmutableList<?>> notIn;
|
||||
private ImmutableMap<String, Between> between;
|
||||
private ImmutableMap<String, Between> notBetween;
|
||||
|
||||
@Data
|
||||
public static class Between {
|
||||
private String start;
|
||||
private String end;
|
||||
}
|
||||
public static class Between {
|
||||
private String start;
|
||||
private String end;
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Sortable {
|
||||
private String column;
|
||||
private Direction direction;
|
||||
@Data
|
||||
public static class Sortable {
|
||||
private String column;
|
||||
private Direction direction;
|
||||
|
||||
public enum Direction {
|
||||
ASC,
|
||||
DESC,
|
||||
}
|
||||
public enum Direction {
|
||||
ASC,
|
||||
DESC,
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Pageable {
|
||||
private Integer page;
|
||||
private Integer size;
|
||||
}
|
||||
@Data
|
||||
public static class Pageable {
|
||||
private Integer page;
|
||||
private Integer size;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,40 +20,40 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
@MappedSuperclass
|
||||
@EntityListeners(AuditingEntityListener.class)
|
||||
public class CheckingNeededEntity extends LogicDeleteEntity {
|
||||
private String description;
|
||||
private String description;
|
||||
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private State state = State.DRAFT;
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private State state = State.DRAFT;
|
||||
|
||||
@OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
|
||||
@ToString.Exclude
|
||||
private CheckOrder order;
|
||||
@OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
|
||||
@ToString.Exclude
|
||||
private CheckOrder order;
|
||||
|
||||
public enum State {
|
||||
/**
|
||||
* 无确权
|
||||
*/
|
||||
NONE,
|
||||
/**
|
||||
* 草稿
|
||||
*/
|
||||
DRAFT,
|
||||
/**
|
||||
* 审查中
|
||||
*/
|
||||
CHECKING,
|
||||
/**
|
||||
* 用户审核
|
||||
*/
|
||||
OWNER_CHECKING,
|
||||
/**
|
||||
* 正常
|
||||
*/
|
||||
NORMAL,
|
||||
/**
|
||||
* 驳回
|
||||
*/
|
||||
REJECT,
|
||||
}
|
||||
public enum State {
|
||||
/**
|
||||
* 无确权
|
||||
*/
|
||||
NONE,
|
||||
/**
|
||||
* 草稿
|
||||
*/
|
||||
DRAFT,
|
||||
/**
|
||||
* 审查中
|
||||
*/
|
||||
CHECKING,
|
||||
/**
|
||||
* 用户审核
|
||||
*/
|
||||
OWNER_CHECKING,
|
||||
/**
|
||||
* 正常
|
||||
*/
|
||||
NORMAL,
|
||||
/**
|
||||
* 驳回
|
||||
*/
|
||||
REJECT,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,35 +17,35 @@ import lombok.NoArgsConstructor;
|
||||
@AllArgsConstructor
|
||||
@JsonDeserialize(using = FileInfo.FileInfoDeserializer.class)
|
||||
public final class FileInfo {
|
||||
private String id;
|
||||
private String name;
|
||||
private String filename;
|
||||
private Long value;
|
||||
private String state;
|
||||
private String id;
|
||||
private String name;
|
||||
private String filename;
|
||||
private Long value;
|
||||
private String state;
|
||||
|
||||
public FileInfo(DataFile dataFile) {
|
||||
this.id = dataFile.getId().toString();
|
||||
this.name = dataFile.getFilename();
|
||||
this.filename = dataFile.getFilename();
|
||||
this.value = dataFile.getId();
|
||||
this.state = "uploaded";
|
||||
}
|
||||
public FileInfo(DataFile dataFile) {
|
||||
this.id = dataFile.getId().toString();
|
||||
this.name = dataFile.getFilename();
|
||||
this.filename = dataFile.getFilename();
|
||||
this.value = dataFile.getId();
|
||||
this.state = "uploaded";
|
||||
}
|
||||
|
||||
public static final class FileInfoDeserializer extends JsonDeserializer<FileInfo> {
|
||||
@Override
|
||||
public FileInfo deserialize(JsonParser parser, DeserializationContext context) throws IOException {
|
||||
TreeNode root = parser.readValueAsTree();
|
||||
if (root instanceof ObjectNode) {
|
||||
ObjectNode node = (ObjectNode) root;
|
||||
return new FileInfo(
|
||||
node.get("id").asText(),
|
||||
node.get("name").asText(),
|
||||
node.get("filename").asText(),
|
||||
node.get("value").asLong(),
|
||||
node.get("state").asText()
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public static final class FileInfoDeserializer extends JsonDeserializer<FileInfo> {
|
||||
@Override
|
||||
public FileInfo deserialize(JsonParser parser, DeserializationContext context) throws IOException {
|
||||
TreeNode root = parser.readValueAsTree();
|
||||
if (root instanceof ObjectNode) {
|
||||
ObjectNode node = (ObjectNode) root;
|
||||
return new FileInfo(
|
||||
node.get("id").asText(),
|
||||
node.get("name").asText(),
|
||||
node.get("filename").asText(),
|
||||
node.get("value").asLong(),
|
||||
node.get("state").asText()
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,24 +22,24 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
@MappedSuperclass
|
||||
@EntityListeners(AuditingEntityListener.class)
|
||||
public class IdOnlyEntity {
|
||||
@Id
|
||||
@GeneratedValue(generator = "snowflake")
|
||||
@GenericGenerator(name = "snowflake", strategy = "com.eshore.gringotts.web.configuration.SnowflakeIdGenerator")
|
||||
private Long id;
|
||||
@Id
|
||||
@GeneratedValue(generator = "snowflake")
|
||||
@GenericGenerator(name = "snowflake", strategy = "com.eshore.gringotts.web.configuration.SnowflakeIdGenerator")
|
||||
private Long id;
|
||||
|
||||
@Override
|
||||
public final boolean equals(Object object) {
|
||||
if (this == object)
|
||||
return true;
|
||||
if (!(object instanceof IdOnlyEntity))
|
||||
return false;
|
||||
@Override
|
||||
public final boolean equals(Object object) {
|
||||
if (this == object)
|
||||
return true;
|
||||
if (!(object instanceof IdOnlyEntity))
|
||||
return false;
|
||||
|
||||
IdOnlyEntity that = (IdOnlyEntity) object;
|
||||
return id.equals(that.id);
|
||||
}
|
||||
IdOnlyEntity that = (IdOnlyEntity) object;
|
||||
return id.equals(that.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return id.hashCode();
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return id.hashCode();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,8 +20,8 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
@MappedSuperclass
|
||||
@EntityListeners(AuditingEntityListener.class)
|
||||
public class LogicDeleteEntity extends SimpleEntity {
|
||||
public static final String LOGIC_DELETE_CLAUSE = "deleted = false";
|
||||
public static final String LOGIC_DELETE_CLAUSE = "deleted = false";
|
||||
|
||||
@Column(nullable = false)
|
||||
private Boolean deleted = false;
|
||||
@Column(nullable = false)
|
||||
private Boolean deleted = false;
|
||||
}
|
||||
|
||||
@@ -20,8 +20,8 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
@MappedSuperclass
|
||||
@EntityListeners(AuditingEntityListener.class)
|
||||
public class LogicDeleteIdOnlyEntity extends IdOnlyEntity {
|
||||
public static final String LOGIC_DELETE_CLAUSE = "deleted = false";
|
||||
public static final String LOGIC_DELETE_CLAUSE = "deleted = false";
|
||||
|
||||
@Column(nullable = false)
|
||||
private Boolean deleted = false;
|
||||
@Column(nullable = false)
|
||||
private Boolean deleted = false;
|
||||
}
|
||||
|
||||
@@ -10,5 +10,5 @@ import lombok.Data;
|
||||
*/
|
||||
@Data
|
||||
public abstract class SimpleDetailItem<ENTITY> {
|
||||
private Long id;
|
||||
private Long id;
|
||||
}
|
||||
|
||||
@@ -30,18 +30,18 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
@MappedSuperclass
|
||||
@EntityListeners(AuditingEntityListener.class)
|
||||
public class SimpleEntity extends IdOnlyEntity {
|
||||
@CreatedDate
|
||||
private LocalDateTime createdTime;
|
||||
@OneToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
@CreatedBy
|
||||
private User createdUser;
|
||||
@LastModifiedDate
|
||||
private LocalDateTime modifiedTime;
|
||||
@OneToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
@LastModifiedBy
|
||||
private User modifiedUser;
|
||||
@CreatedDate
|
||||
private LocalDateTime createdTime;
|
||||
@OneToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
@CreatedBy
|
||||
private User createdUser;
|
||||
@LastModifiedDate
|
||||
private LocalDateTime modifiedTime;
|
||||
@OneToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
@LastModifiedBy
|
||||
private User modifiedUser;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import lombok.Data;
|
||||
*/
|
||||
@Data
|
||||
public abstract class SimpleListItem<ENTITY> {
|
||||
private Long id;
|
||||
private String createdUsername;
|
||||
private LocalDateTime createdTime;
|
||||
private Long id;
|
||||
private String createdUsername;
|
||||
private LocalDateTime createdTime;
|
||||
}
|
||||
|
||||
@@ -10,5 +10,5 @@ import lombok.Data;
|
||||
*/
|
||||
@Data
|
||||
public abstract class SimpleSaveItem<ENTITY> {
|
||||
private Long id;
|
||||
private Long id;
|
||||
}
|
||||
|
||||
@@ -10,5 +10,5 @@ import org.eclipse.collections.api.map.ImmutableMap;
|
||||
* @date 2024-11-28
|
||||
*/
|
||||
public interface CheckingService {
|
||||
void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap<String, Object> parameters);
|
||||
void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap<String, Object> parameters);
|
||||
}
|
||||
|
||||
@@ -21,24 +21,24 @@ import org.eclipse.collections.api.list.ImmutableList;
|
||||
*/
|
||||
@Slf4j
|
||||
public abstract class LogicDeleteService<ENTITY extends LogicDeleteEntity> extends SimpleServiceSupport<ENTITY> {
|
||||
private final EntityManager manager;
|
||||
private final EntityManager manager;
|
||||
|
||||
public LogicDeleteService(SimpleRepository<ENTITY, Long> repository, UserService userService, EntityManager manager) {
|
||||
super(repository, userService);
|
||||
this.manager = manager;
|
||||
}
|
||||
public LogicDeleteService(SimpleRepository<ENTITY, Long> repository, UserService userService, EntityManager manager) {
|
||||
super(repository, userService);
|
||||
this.manager = manager;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ImmutableList<Predicate> listPredicate(Root<ENTITY> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
return super.listPredicate(root, query, builder).newWith(builder.equal(root.get("deleted"), false));
|
||||
}
|
||||
@Override
|
||||
protected ImmutableList<Predicate> listPredicate(Root<ENTITY> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
return super.listPredicate(root, query, builder).newWith(builder.equal(root.get("deleted"), false));
|
||||
}
|
||||
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
@Override
|
||||
public void remove(Long id) {
|
||||
String entityName = ClassUtil.getTypeArgument(this.getClass()).getSimpleName();
|
||||
Query query = manager.createQuery(StrUtil.format("update {} entity set deleted=true where id=?1", entityName));
|
||||
query.setParameter(1, id);
|
||||
query.executeUpdate();
|
||||
}
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
@Override
|
||||
public void remove(Long id) {
|
||||
String entityName = ClassUtil.getTypeArgument(this.getClass()).getSimpleName();
|
||||
Query query = manager.createQuery(StrUtil.format("update {} entity set deleted=true where id=?1", entityName));
|
||||
query.setParameter(1, id);
|
||||
query.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,21 +11,21 @@ import org.eclipse.collections.api.set.ImmutableSet;
|
||||
* @date 2024-11-28
|
||||
*/
|
||||
public interface SimpleService<ENTITY extends SimpleEntity> {
|
||||
Long save(ENTITY entity) throws Exception;
|
||||
Long save(ENTITY entity) throws Exception;
|
||||
|
||||
ImmutableList<ENTITY> list() throws Exception;
|
||||
ImmutableList<ENTITY> list() throws Exception;
|
||||
|
||||
ImmutableList<ENTITY> list(ImmutableSet<Long> ids) throws Exception;
|
||||
ImmutableList<ENTITY> list(ImmutableSet<Long> ids) throws Exception;
|
||||
|
||||
ImmutableList<ENTITY> list(Query query) throws Exception;
|
||||
ImmutableList<ENTITY> list(Query query) throws Exception;
|
||||
|
||||
Optional<ENTITY> detailOptional(Long id) throws Exception;
|
||||
Optional<ENTITY> detailOptional(Long id) throws Exception;
|
||||
|
||||
ENTITY detail(Long id) throws Exception;
|
||||
ENTITY detail(Long id) throws Exception;
|
||||
|
||||
ENTITY detailOrThrow(Long id) throws Exception;
|
||||
ENTITY detailOrThrow(Long id) throws Exception;
|
||||
|
||||
ENTITY detailOrNull(Long id) throws Exception;
|
||||
ENTITY detailOrNull(Long id) throws Exception;
|
||||
|
||||
void remove(Long id) throws Exception;
|
||||
void remove(Long id) throws Exception;
|
||||
}
|
||||
|
||||
@@ -32,206 +32,206 @@ import org.springframework.data.domain.Sort;
|
||||
*/
|
||||
@Slf4j
|
||||
public abstract class SimpleServiceSupport<ENTITY extends SimpleEntity> implements SimpleService<ENTITY> {
|
||||
protected final SimpleRepository<ENTITY, Long> repository;
|
||||
protected final UserService userService;
|
||||
protected final SimpleRepository<ENTITY, Long> repository;
|
||||
protected final UserService userService;
|
||||
|
||||
public SimpleServiceSupport(SimpleRepository<ENTITY, Long> repository, UserService userService) {
|
||||
this.repository = repository;
|
||||
this.userService = userService;
|
||||
public SimpleServiceSupport(SimpleRepository<ENTITY, Long> repository, UserService userService) {
|
||||
this.repository = repository;
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
@Override
|
||||
public Long save(ENTITY entity) {
|
||||
if (ObjectUtil.isNotNull(entity.getId())) {
|
||||
Long id = entity.getId();
|
||||
ENTITY targetEntity = repository.findById(entity.getId()).orElseThrow(() -> new IdNotFoundException(id));
|
||||
BeanUtil.copyProperties(
|
||||
entity,
|
||||
targetEntity,
|
||||
CopyOptions.create()
|
||||
.setIgnoreProperties(
|
||||
IdOnlyEntity_.ID,
|
||||
SimpleEntity_.CREATED_USER,
|
||||
SimpleEntity_.CREATED_TIME,
|
||||
SimpleEntity_.MODIFIED_USER,
|
||||
SimpleEntity_.MODIFIED_TIME
|
||||
)
|
||||
);
|
||||
entity = targetEntity;
|
||||
}
|
||||
entity = repository.save(entity);
|
||||
return entity.getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ImmutableList<ENTITY> list() throws Exception {
|
||||
return Lists.immutable.ofAll(repository.findAll(
|
||||
(root, query, builder) ->
|
||||
builder.and(
|
||||
listPredicate(root, query, builder)
|
||||
.reject(ObjectUtil::isNull)
|
||||
.toArray(new Predicate[]{})
|
||||
)
|
||||
));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ImmutableList<ENTITY> list(ImmutableSet<Long> ids) throws Exception {
|
||||
return Lists.immutable.ofAll(repository.findAll(
|
||||
(root, query, builder) -> {
|
||||
MutableList<Predicate> predicates = Lists.mutable.ofAll(listPredicate(root, query, builder));
|
||||
predicates.add(builder.in(root.get("id")).value(ids));
|
||||
return builder.and(predicates.reject(ObjectUtil::isNull).toArray(new Predicate[predicates.size()]));
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
private <Y> Path<Y> column(Root<ENTITY> root, String column) {
|
||||
String[] columns = StrUtil.splitToArray(column, "/");
|
||||
Path<Y> path = root.get(columns[0]);
|
||||
for (int i = 1; i < columns.length; i++) {
|
||||
path = path.get(columns[i]);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
private <Y> Object value(Path<Y> column, Object value) {
|
||||
Class<?> javaType = column.getJavaType();
|
||||
if (EnumUtil.isEnum(javaType)) {
|
||||
return EnumUtil.fromString((Class<Enum>) javaType, (String) value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private ImmutableList<Predicate> queryPredicates(Query.Queryable queryable, Root<ENTITY> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
MutableList<Predicate> predicates = Lists.mutable.empty();
|
||||
if (ObjectUtil.isEmpty(queryable)) {
|
||||
return predicates.toImmutable();
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getNullEqual())) {
|
||||
queryable.getNullEqual().forEach(column -> predicates.add(builder.isNull(column(root, column))));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getNotNullEqual())) {
|
||||
queryable.getNotNullEqual().forEach(column -> predicates.add(builder.isNull(column(root, column))));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getEmpty())) {
|
||||
queryable.getEmpty().forEach(column -> predicates.add(builder.isEmpty(column(root, column))));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getNotEmpty())) {
|
||||
queryable.getNotEmpty().forEach(column -> predicates.add(builder.isNotEmpty(column(root, column))));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getEqual())) {
|
||||
queryable.getEqual().forEachKeyValue((column, value) -> {
|
||||
Path<Object> path = column(root, column);
|
||||
predicates.add(builder.equal(path, value(path, value)));
|
||||
});
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getNotEqual())) {
|
||||
queryable.getEqual().forEachKeyValue((column, value) -> {
|
||||
Path<Object> path = column(root, column);
|
||||
predicates.add(builder.notEqual(path, value(path, value)));
|
||||
});
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getLike())) {
|
||||
queryable.getLike().forEachKeyValue((column, value) -> predicates.add(builder.like(column(root, column), value)));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getNotLike())) {
|
||||
queryable.getNotLike().forEachKeyValue((column, value) -> predicates.add(builder.notLike(column(root, column), value)));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getGreat())) {
|
||||
queryable.getGreat().forEachKeyValue((column, value) -> predicates.add(builder.greaterThan(column(root, column), (Comparable<Object>) value)));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getLess())) {
|
||||
queryable.getLess().forEachKeyValue((column, value) -> predicates.add(builder.lessThan(column(root, column), (Comparable<Object>) value)));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getGreatEqual())) {
|
||||
queryable.getGreatEqual().forEachKeyValue((column, value) -> predicates.add(builder.greaterThanOrEqualTo(column(root, column), (Comparable<Object>) value)));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getLessEqual())) {
|
||||
queryable.getLessEqual().forEachKeyValue((column, value) -> predicates.add(builder.lessThanOrEqualTo(column(root, column), (Comparable<Object>) value)));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getIn())) {
|
||||
queryable.getIn().forEachKeyValue((column, value) -> predicates.add(builder.in(column(root, column)).value(value)));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getNotIn())) {
|
||||
queryable.getNotIn().forEachKeyValue((column, value) -> predicates.add(builder.in(column(root, column)).value(value).not()));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getBetween())) {
|
||||
queryable.getBetween().forEachKeyValue((column, value) -> predicates.add(builder.between(column(root, column), value.getStart(), value.getEnd())));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getNotBetween())) {
|
||||
queryable.getNotBetween().forEachKeyValue((column, value) -> predicates.add(builder.between(column(root, column), value.getStart(), value.getEnd())));
|
||||
}
|
||||
return predicates.toImmutable();
|
||||
}
|
||||
|
||||
protected ImmutableList<Predicate> listPredicate(Root<ENTITY> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
User user = userService.currentLoginUser();
|
||||
if (User.isNotAdministrator(user)) {
|
||||
return Lists.immutable.of(builder.equal(root.get(SimpleEntity_.createdUser), user));
|
||||
}
|
||||
return Lists.immutable.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ImmutableList<ENTITY> list(Query listQuery) throws Exception {
|
||||
return Lists.immutable.ofAll(repository.findAll(
|
||||
(root, query, builder) -> {
|
||||
MutableList<Predicate> predicates = Lists.mutable.ofAll(listPredicate(root, query, builder));
|
||||
predicates.addAllIterable(queryPredicates(listQuery.getQuery(), root, query, builder));
|
||||
return builder.and(predicates.reject(ObjectUtil::isNull).toArray(new Predicate[predicates.size()]));
|
||||
},
|
||||
Sort.by(SimpleEntity_.CREATED_TIME).descending()
|
||||
));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ENTITY> detailOptional(Long id) {
|
||||
if (ObjectUtil.isNull(id)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return repository.findOne(
|
||||
(root, query, builder) -> {
|
||||
MutableList<Predicate> predicates = Lists.mutable.ofAll(listPredicate(root, query, builder));
|
||||
predicates.add(builder.equal(root.get(IdOnlyEntity_.id), id));
|
||||
return builder.and(predicates.reject(ObjectUtil::isNull).toArray(new Predicate[predicates.size()]));
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ENTITY detail(Long id) {
|
||||
return detailOrNull(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ENTITY detailOrThrow(Long id) {
|
||||
return detailOptional(id).orElseThrow(() -> new IdNotFoundException(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ENTITY detailOrNull(Long id) {
|
||||
return detailOptional(id).orElse(null);
|
||||
}
|
||||
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
@Override
|
||||
public void remove(Long id) {
|
||||
if (ObjectUtil.isNotNull(id)) {
|
||||
repository.deleteById(id);
|
||||
}
|
||||
}
|
||||
|
||||
public static final class IdNotFoundException extends RuntimeException {
|
||||
public IdNotFoundException() {
|
||||
super("资源不存在");
|
||||
}
|
||||
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
@Override
|
||||
public Long save(ENTITY entity) {
|
||||
if (ObjectUtil.isNotNull(entity.getId())) {
|
||||
Long id = entity.getId();
|
||||
ENTITY targetEntity = repository.findById(entity.getId()).orElseThrow(() -> new IdNotFoundException(id));
|
||||
BeanUtil.copyProperties(
|
||||
entity,
|
||||
targetEntity,
|
||||
CopyOptions.create()
|
||||
.setIgnoreProperties(
|
||||
IdOnlyEntity_.ID,
|
||||
SimpleEntity_.CREATED_USER,
|
||||
SimpleEntity_.CREATED_TIME,
|
||||
SimpleEntity_.MODIFIED_USER,
|
||||
SimpleEntity_.MODIFIED_TIME
|
||||
)
|
||||
);
|
||||
entity = targetEntity;
|
||||
}
|
||||
entity = repository.save(entity);
|
||||
return entity.getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ImmutableList<ENTITY> list() throws Exception {
|
||||
return Lists.immutable.ofAll(repository.findAll(
|
||||
(root, query, builder) ->
|
||||
builder.and(
|
||||
listPredicate(root, query, builder)
|
||||
.reject(ObjectUtil::isNull)
|
||||
.toArray(new Predicate[]{})
|
||||
)
|
||||
));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ImmutableList<ENTITY> list(ImmutableSet<Long> ids) throws Exception {
|
||||
return Lists.immutable.ofAll(repository.findAll(
|
||||
(root, query, builder) -> {
|
||||
MutableList<Predicate> predicates = Lists.mutable.ofAll(listPredicate(root, query, builder));
|
||||
predicates.add(builder.in(root.get("id")).value(ids));
|
||||
return builder.and(predicates.reject(ObjectUtil::isNull).toArray(new Predicate[predicates.size()]));
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
private <Y> Path<Y> column(Root<ENTITY> root, String column) {
|
||||
String[] columns = StrUtil.splitToArray(column, "/");
|
||||
Path<Y> path = root.get(columns[0]);
|
||||
for (int i = 1; i < columns.length; i++) {
|
||||
path = path.get(columns[i]);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
private <Y> Object value(Path<Y> column, Object value) {
|
||||
Class<?> javaType = column.getJavaType();
|
||||
if (EnumUtil.isEnum(javaType)) {
|
||||
return EnumUtil.fromString((Class<Enum>) javaType, (String) value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private ImmutableList<Predicate> queryPredicates(Query.Queryable queryable, Root<ENTITY> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
MutableList<Predicate> predicates = Lists.mutable.empty();
|
||||
if (ObjectUtil.isEmpty(queryable)) {
|
||||
return predicates.toImmutable();
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getNullEqual())) {
|
||||
queryable.getNullEqual().forEach(column -> predicates.add(builder.isNull(column(root, column))));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getNotNullEqual())) {
|
||||
queryable.getNotNullEqual().forEach(column -> predicates.add(builder.isNull(column(root, column))));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getEmpty())) {
|
||||
queryable.getEmpty().forEach(column -> predicates.add(builder.isEmpty(column(root, column))));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getNotEmpty())) {
|
||||
queryable.getNotEmpty().forEach(column -> predicates.add(builder.isNotEmpty(column(root, column))));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getEqual())) {
|
||||
queryable.getEqual().forEachKeyValue((column, value) -> {
|
||||
Path<Object> path = column(root, column);
|
||||
predicates.add(builder.equal(path, value(path, value)));
|
||||
});
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getNotEqual())) {
|
||||
queryable.getEqual().forEachKeyValue((column, value) -> {
|
||||
Path<Object> path = column(root, column);
|
||||
predicates.add(builder.notEqual(path, value(path, value)));
|
||||
});
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getLike())) {
|
||||
queryable.getLike().forEachKeyValue((column, value) -> predicates.add(builder.like(column(root, column), value)));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getNotLike())) {
|
||||
queryable.getNotLike().forEachKeyValue((column, value) -> predicates.add(builder.notLike(column(root, column), value)));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getGreat())) {
|
||||
queryable.getGreat().forEachKeyValue((column, value) -> predicates.add(builder.greaterThan(column(root, column), (Comparable<Object>) value)));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getLess())) {
|
||||
queryable.getLess().forEachKeyValue((column, value) -> predicates.add(builder.lessThan(column(root, column), (Comparable<Object>) value)));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getGreatEqual())) {
|
||||
queryable.getGreatEqual().forEachKeyValue((column, value) -> predicates.add(builder.greaterThanOrEqualTo(column(root, column), (Comparable<Object>) value)));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getLessEqual())) {
|
||||
queryable.getLessEqual().forEachKeyValue((column, value) -> predicates.add(builder.lessThanOrEqualTo(column(root, column), (Comparable<Object>) value)));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getIn())) {
|
||||
queryable.getIn().forEachKeyValue((column, value) -> predicates.add(builder.in(column(root, column)).value(value)));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getNotIn())) {
|
||||
queryable.getNotIn().forEachKeyValue((column, value) -> predicates.add(builder.in(column(root, column)).value(value).not()));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getBetween())) {
|
||||
queryable.getBetween().forEachKeyValue((column, value) -> predicates.add(builder.between(column(root, column), value.getStart(), value.getEnd())));
|
||||
}
|
||||
if (ObjectUtil.isNotEmpty(queryable.getNotBetween())) {
|
||||
queryable.getNotBetween().forEachKeyValue((column, value) -> predicates.add(builder.between(column(root, column), value.getStart(), value.getEnd())));
|
||||
}
|
||||
return predicates.toImmutable();
|
||||
}
|
||||
|
||||
protected ImmutableList<Predicate> listPredicate(Root<ENTITY> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
User user = userService.currentLoginUser();
|
||||
if (User.isNotAdministrator(user)) {
|
||||
return Lists.immutable.of(builder.equal(root.get(SimpleEntity_.createdUser), user));
|
||||
}
|
||||
return Lists.immutable.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ImmutableList<ENTITY> list(Query listQuery) throws Exception {
|
||||
return Lists.immutable.ofAll(repository.findAll(
|
||||
(root, query, builder) -> {
|
||||
MutableList<Predicate> predicates = Lists.mutable.ofAll(listPredicate(root, query, builder));
|
||||
predicates.addAllIterable(queryPredicates(listQuery.getQuery(), root, query, builder));
|
||||
return builder.and(predicates.reject(ObjectUtil::isNull).toArray(new Predicate[predicates.size()]));
|
||||
},
|
||||
Sort.by(SimpleEntity_.CREATED_TIME).descending()
|
||||
));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ENTITY> detailOptional(Long id) {
|
||||
if (ObjectUtil.isNull(id)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return repository.findOne(
|
||||
(root, query, builder) -> {
|
||||
MutableList<Predicate> predicates = Lists.mutable.ofAll(listPredicate(root, query, builder));
|
||||
predicates.add(builder.equal(root.get(IdOnlyEntity_.id), id));
|
||||
return builder.and(predicates.reject(ObjectUtil::isNull).toArray(new Predicate[predicates.size()]));
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ENTITY detail(Long id) {
|
||||
return detailOrNull(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ENTITY detailOrThrow(Long id) {
|
||||
return detailOptional(id).orElseThrow(() -> new IdNotFoundException(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public ENTITY detailOrNull(Long id) {
|
||||
return detailOptional(id).orElse(null);
|
||||
}
|
||||
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
@Override
|
||||
public void remove(Long id) {
|
||||
if (ObjectUtil.isNotNull(id)) {
|
||||
repository.deleteById(id);
|
||||
}
|
||||
}
|
||||
|
||||
public static final class IdNotFoundException extends RuntimeException {
|
||||
public IdNotFoundException() {
|
||||
super("资源不存在");
|
||||
}
|
||||
|
||||
public IdNotFoundException(Long id) {
|
||||
super(StrUtil.format("ID为{}的资源不存在", id));
|
||||
}
|
||||
public IdNotFoundException(Long id) {
|
||||
super(StrUtil.format("ID为{}的资源不存在", id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,101 +30,101 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
@RestController
|
||||
@RequestMapping("authentication")
|
||||
public class AuthenticationController extends SimpleControllerSupport<Authentication, AuthenticationController.SaveItem, AuthenticationController.ListItem, AuthenticationController.DetailItem> {
|
||||
private final AuthenticationService authenticationService;
|
||||
private final DataResourceService dataResourceService;
|
||||
private final DataFileService dataFileService;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final DataResourceService dataResourceService;
|
||||
private final DataFileService dataFileService;
|
||||
|
||||
public AuthenticationController(AuthenticationService service, DataResourceService dataResourceService, DataFileService dataFileService) {
|
||||
super(service);
|
||||
this.authenticationService = service;
|
||||
this.dataResourceService = dataResourceService;
|
||||
this.dataFileService = dataFileService;
|
||||
public AuthenticationController(AuthenticationService service, DataResourceService dataResourceService, DataFileService dataFileService) {
|
||||
super(service);
|
||||
this.authenticationService = service;
|
||||
this.dataResourceService = dataResourceService;
|
||||
this.dataFileService = dataFileService;
|
||||
}
|
||||
|
||||
@GetMapping("/submit/{id}")
|
||||
public AmisResponse<Object> submit(@PathVariable Long id) throws JsonProcessingException {
|
||||
authenticationService.submit(id);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@GetMapping("/retract/{id}")
|
||||
public AmisResponse<Object> retract(@PathVariable Long id) {
|
||||
authenticationService.retract(id);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Authentication fromSaveItem(SaveItem item) throws Exception {
|
||||
Authentication authentication = new Authentication();
|
||||
authentication.setId(item.getId());
|
||||
authentication.setDescription(item.getDescription());
|
||||
authentication.setTarget(dataResourceService.detailOrThrow(item.getTargetId()));
|
||||
authentication.setEvidences(dataFileService.list(item.getEvidenceFiles().collect(FileInfo::getValue)).toSet());
|
||||
authentication.setActiveTime(item.getActiveTime());
|
||||
authentication.setExpiredTime(item.getExpiredTime());
|
||||
return authentication;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ListItem toListItem(Authentication entity) {
|
||||
return new ListItem(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DetailItem toDetailItem(Authentication entity) {
|
||||
return new DetailItem(entity);
|
||||
}
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static class SaveItem extends SimpleSaveItem<Authentication> {
|
||||
private Long targetId;
|
||||
private String description;
|
||||
private ImmutableSet<FileInfo> evidenceFiles;
|
||||
private LocalDateTime activeTime;
|
||||
private LocalDateTime expiredTime;
|
||||
}
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static final class ListItem extends SimpleListItem<Authentication> {
|
||||
private String name;
|
||||
private String description;
|
||||
private String state;
|
||||
|
||||
public ListItem(Authentication authentication) {
|
||||
this.setId(authentication.getId());
|
||||
this.setName(authentication.getTarget().getName());
|
||||
this.setDescription(authentication.getDescription());
|
||||
this.setState(authentication.getState().name());
|
||||
this.setCreatedUsername(authentication.getCreatedUser().getUsername());
|
||||
this.setCreatedTime(authentication.getCreatedTime());
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/submit/{id}")
|
||||
public AmisResponse<Object> submit(@PathVariable Long id) throws JsonProcessingException {
|
||||
authenticationService.submit(id);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@GetMapping("/retract/{id}")
|
||||
public AmisResponse<Object> retract(@PathVariable Long id) {
|
||||
authenticationService.retract(id);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Authentication fromSaveItem(SaveItem item) throws Exception {
|
||||
Authentication authentication = new Authentication();
|
||||
authentication.setId(item.getId());
|
||||
authentication.setDescription(item.getDescription());
|
||||
authentication.setTarget(dataResourceService.detailOrThrow(item.getTargetId()));
|
||||
authentication.setEvidences(dataFileService.list(item.getEvidenceFiles().collect(FileInfo::getValue)).toSet());
|
||||
authentication.setActiveTime(item.getActiveTime());
|
||||
authentication.setExpiredTime(item.getExpiredTime());
|
||||
return authentication;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ListItem toListItem(Authentication entity) {
|
||||
return new ListItem(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DetailItem toDetailItem(Authentication entity) {
|
||||
return new DetailItem(entity);
|
||||
}
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static class SaveItem extends SimpleSaveItem<Authentication> {
|
||||
private Long targetId;
|
||||
private String description;
|
||||
private ImmutableSet<FileInfo> evidenceFiles;
|
||||
private LocalDateTime activeTime;
|
||||
private LocalDateTime expiredTime;
|
||||
}
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static final class ListItem extends SimpleListItem<Authentication> {
|
||||
private String name;
|
||||
private String description;
|
||||
private String state;
|
||||
|
||||
public ListItem(Authentication authentication) {
|
||||
this.setId(authentication.getId());
|
||||
this.setName(authentication.getTarget().getName());
|
||||
this.setDescription(authentication.getDescription());
|
||||
this.setState(authentication.getState().name());
|
||||
this.setCreatedUsername(authentication.getCreatedUser().getUsername());
|
||||
this.setCreatedTime(authentication.getCreatedTime());
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static final class DetailItem extends SaveItem {
|
||||
private String targetName;
|
||||
private LocalDateTime createdTime;
|
||||
private String createdUsername;
|
||||
private LocalDateTime modifiedTime;
|
||||
private String modifiedUsername;
|
||||
|
||||
public DetailItem(Authentication authentication) {
|
||||
this.setId(authentication.getId());
|
||||
this.setTargetId(authentication.getTarget().getId());
|
||||
this.setTargetName(authentication.getTarget().getName());
|
||||
this.setDescription(authentication.getDescription());
|
||||
this.setEvidenceFiles(Sets.immutable.ofAll(authentication.getEvidences()).collect(FileInfo::new));
|
||||
this.setActiveTime(authentication.getActiveTime());
|
||||
this.setExpiredTime(authentication.getExpiredTime());
|
||||
this.setCreatedTime(authentication.getCreatedTime());
|
||||
this.setCreatedUsername(authentication.getCreatedUser().getUsername());
|
||||
this.setModifiedTime(authentication.getModifiedTime());
|
||||
this.setModifiedUsername(authentication.getModifiedUser().getUsername());
|
||||
}
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static final class DetailItem extends SaveItem {
|
||||
private String targetName;
|
||||
private LocalDateTime createdTime;
|
||||
private String createdUsername;
|
||||
private LocalDateTime modifiedTime;
|
||||
private String modifiedUsername;
|
||||
|
||||
public DetailItem(Authentication authentication) {
|
||||
this.setId(authentication.getId());
|
||||
this.setTargetId(authentication.getTarget().getId());
|
||||
this.setTargetName(authentication.getTarget().getName());
|
||||
this.setDescription(authentication.getDescription());
|
||||
this.setEvidenceFiles(Sets.immutable.ofAll(authentication.getEvidences()).collect(FileInfo::new));
|
||||
this.setActiveTime(authentication.getActiveTime());
|
||||
this.setExpiredTime(authentication.getExpiredTime());
|
||||
this.setCreatedTime(authentication.getCreatedTime());
|
||||
this.setCreatedUsername(authentication.getCreatedUser().getUsername());
|
||||
this.setModifiedTime(authentication.getModifiedTime());
|
||||
this.setModifiedUsername(authentication.getModifiedUser().getUsername());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,58 +32,58 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
@RestController
|
||||
@RequestMapping("check_order")
|
||||
public class CheckOrderController implements ListController<CheckOrderController.ListItem> {
|
||||
private final CheckOrderService checkOrderService;
|
||||
private final ObjectMapper mapper;
|
||||
private final CheckOrderService checkOrderService;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
public CheckOrderController(CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) {
|
||||
this.checkOrderService = checkOrderService;
|
||||
this.mapper = builder.build();
|
||||
}
|
||||
public CheckOrderController(CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) {
|
||||
this.checkOrderService = checkOrderService;
|
||||
this.mapper = builder.build();
|
||||
}
|
||||
|
||||
@GetMapping("/list")
|
||||
@Override
|
||||
public AmisResponse<ImmutableList<CheckOrderController.ListItem>> list() throws Exception {
|
||||
return AmisResponse.responseSuccess(checkOrderService.list().collect(this::toListItem));
|
||||
}
|
||||
@GetMapping("/list")
|
||||
@Override
|
||||
public AmisResponse<ImmutableList<CheckOrderController.ListItem>> list() throws Exception {
|
||||
return AmisResponse.responseSuccess(checkOrderService.list().collect(this::toListItem));
|
||||
}
|
||||
|
||||
@PostMapping("/list")
|
||||
@Override
|
||||
public AmisResponse<ImmutableList<ListItem>> list(@RequestBody Query query) throws Exception {
|
||||
return AmisResponse.responseSuccess(checkOrderService.list().collect(this::toListItem));
|
||||
}
|
||||
@PostMapping("/list")
|
||||
@Override
|
||||
public AmisResponse<ImmutableList<ListItem>> list(@RequestBody Query query) throws Exception {
|
||||
return AmisResponse.responseSuccess(checkOrderService.list().collect(this::toListItem));
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
private ListItem toListItem(CheckOrder order) {
|
||||
ListItem item = new ListItem();
|
||||
item.setCheckOrderId(order.getId());
|
||||
item.setDescription(order.getDescription());
|
||||
item.setType(order.getType());
|
||||
item.setParameters(mapper.readValue(order.getParameters(), new TypeReference<>() {}));
|
||||
item.setState(order.getState());
|
||||
item.setCreatedUsername(order.getCreatedUser().getUsername());
|
||||
item.setCreatedTime(order.getCreatedTime());
|
||||
item.setModifiedUsername(order.getModifiedUser().getUsername());
|
||||
item.setModifiedTime(order.getModifiedTime());
|
||||
return item;
|
||||
}
|
||||
@SneakyThrows
|
||||
private ListItem toListItem(CheckOrder order) {
|
||||
ListItem item = new ListItem();
|
||||
item.setCheckOrderId(order.getId());
|
||||
item.setDescription(order.getDescription());
|
||||
item.setType(order.getType());
|
||||
item.setParameters(mapper.readValue(order.getParameters(), new TypeReference<>() {}));
|
||||
item.setState(order.getState());
|
||||
item.setCreatedUsername(order.getCreatedUser().getUsername());
|
||||
item.setCreatedTime(order.getCreatedTime());
|
||||
item.setModifiedUsername(order.getModifiedUser().getUsername());
|
||||
item.setModifiedTime(order.getModifiedTime());
|
||||
return item;
|
||||
}
|
||||
|
||||
@GetMapping("/operation/{id}/{operation}")
|
||||
public AmisResponse<Object> operation(@PathVariable Long id, @PathVariable CheckOrder.Operation operation) throws JsonProcessingException {
|
||||
log.info("id:{}, operation:{}", id, operation);
|
||||
checkOrderService.operation(id, operation);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
@GetMapping("/operation/{id}/{operation}")
|
||||
public AmisResponse<Object> operation(@PathVariable Long id, @PathVariable CheckOrder.Operation operation) throws JsonProcessingException {
|
||||
log.info("id:{}, operation:{}", id, operation);
|
||||
checkOrderService.operation(id, operation);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@Data
|
||||
public static final class ListItem {
|
||||
private Long checkOrderId;
|
||||
private String description;
|
||||
private CheckOrder.Type type;
|
||||
private ImmutableMap<String, Object> parameters;
|
||||
private CheckOrder.State state;
|
||||
private LocalDateTime createdTime;
|
||||
private String createdUsername;
|
||||
private LocalDateTime modifiedTime;
|
||||
private String modifiedUsername;
|
||||
}
|
||||
@Data
|
||||
public static final class ListItem {
|
||||
private Long checkOrderId;
|
||||
private String description;
|
||||
private CheckOrder.Type type;
|
||||
private ImmutableMap<String, Object> parameters;
|
||||
private CheckOrder.State state;
|
||||
private LocalDateTime createdTime;
|
||||
private String createdUsername;
|
||||
private LocalDateTime modifiedTime;
|
||||
private String modifiedUsername;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,93 +29,93 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
@RestController
|
||||
@RequestMapping("confirmation")
|
||||
public class ConfirmationController extends SimpleControllerSupport<Confirmation, ConfirmationController.SaveItem, ConfirmationController.ListItem, ConfirmationController.DetailItem> {
|
||||
private final ConfirmationService confirmationService;
|
||||
private final DataResourceService dataResourceService;
|
||||
private final DataFileService dataFileService;
|
||||
private final ConfirmationService confirmationService;
|
||||
private final DataResourceService dataResourceService;
|
||||
private final DataFileService dataFileService;
|
||||
|
||||
public ConfirmationController(ConfirmationService service, ConfirmationService confirmationService, DataResourceService dataResourceService, DataFileService dataFileService) {
|
||||
super(service);
|
||||
this.confirmationService = confirmationService;
|
||||
this.dataResourceService = dataResourceService;
|
||||
this.dataFileService = dataFileService;
|
||||
public ConfirmationController(ConfirmationService service, ConfirmationService confirmationService, DataResourceService dataResourceService, DataFileService dataFileService) {
|
||||
super(service);
|
||||
this.confirmationService = confirmationService;
|
||||
this.dataResourceService = dataResourceService;
|
||||
this.dataFileService = dataFileService;
|
||||
}
|
||||
|
||||
@GetMapping("/submit/{id}")
|
||||
public AmisResponse<Object> submit(@PathVariable Long id) throws JsonProcessingException {
|
||||
confirmationService.submit(id);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@GetMapping("/retract/{id}")
|
||||
public AmisResponse<Object> retract(@PathVariable Long id) {
|
||||
confirmationService.retract(id);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Confirmation fromSaveItem(SaveItem item) throws Exception {
|
||||
Confirmation confirmation = new Confirmation();
|
||||
confirmation.setId(item.getId());
|
||||
confirmation.setDescription(item.getDescription());
|
||||
confirmation.setTarget(dataResourceService.detailOrThrow(item.getTargetId()));
|
||||
confirmation.setEvidences(dataFileService.list(item.getEvidenceFiles().collect(FileInfo::getValue)).toSet());
|
||||
return confirmation;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ListItem toListItem(Confirmation entity) {
|
||||
return new ListItem(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DetailItem toDetailItem(Confirmation entity) {
|
||||
return new DetailItem(entity);
|
||||
}
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static class SaveItem extends SimpleSaveItem<Confirmation> {
|
||||
private Long targetId;
|
||||
private String description;
|
||||
private ImmutableSet<FileInfo> evidenceFiles;
|
||||
}
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static final class ListItem extends SimpleListItem<Confirmation> {
|
||||
private String name;
|
||||
private String description;
|
||||
private String state;
|
||||
|
||||
public ListItem(Confirmation confirmation) {
|
||||
this.setId(confirmation.getId());
|
||||
this.setName(confirmation.getTarget().getName());
|
||||
this.setDescription(confirmation.getDescription());
|
||||
this.setState(confirmation.getState().name());
|
||||
this.setCreatedUsername(confirmation.getCreatedUser().getUsername());
|
||||
this.setCreatedTime(confirmation.getCreatedTime());
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/submit/{id}")
|
||||
public AmisResponse<Object> submit(@PathVariable Long id) throws JsonProcessingException {
|
||||
confirmationService.submit(id);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@GetMapping("/retract/{id}")
|
||||
public AmisResponse<Object> retract(@PathVariable Long id) {
|
||||
confirmationService.retract(id);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Confirmation fromSaveItem(SaveItem item) throws Exception {
|
||||
Confirmation confirmation = new Confirmation();
|
||||
confirmation.setId(item.getId());
|
||||
confirmation.setDescription(item.getDescription());
|
||||
confirmation.setTarget(dataResourceService.detailOrThrow(item.getTargetId()));
|
||||
confirmation.setEvidences(dataFileService.list(item.getEvidenceFiles().collect(FileInfo::getValue)).toSet());
|
||||
return confirmation;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ListItem toListItem(Confirmation entity) {
|
||||
return new ListItem(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DetailItem toDetailItem(Confirmation entity) {
|
||||
return new DetailItem(entity);
|
||||
}
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static class SaveItem extends SimpleSaveItem<Confirmation> {
|
||||
private Long targetId;
|
||||
private String description;
|
||||
private ImmutableSet<FileInfo> evidenceFiles;
|
||||
}
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static final class ListItem extends SimpleListItem<Confirmation> {
|
||||
private String name;
|
||||
private String description;
|
||||
private String state;
|
||||
|
||||
public ListItem(Confirmation confirmation) {
|
||||
this.setId(confirmation.getId());
|
||||
this.setName(confirmation.getTarget().getName());
|
||||
this.setDescription(confirmation.getDescription());
|
||||
this.setState(confirmation.getState().name());
|
||||
this.setCreatedUsername(confirmation.getCreatedUser().getUsername());
|
||||
this.setCreatedTime(confirmation.getCreatedTime());
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static final class DetailItem extends SaveItem {
|
||||
private String targetName;
|
||||
private LocalDateTime createdTime;
|
||||
private String createdUsername;
|
||||
private LocalDateTime modifiedTime;
|
||||
private String modifiedUsername;
|
||||
|
||||
public DetailItem(Confirmation confirmation) {
|
||||
this.setId(confirmation.getId());
|
||||
this.setTargetId(confirmation.getTarget().getId());
|
||||
this.setTargetName(confirmation.getTarget().getName());
|
||||
this.setDescription(confirmation.getDescription());
|
||||
this.setEvidenceFiles(Sets.immutable.ofAll(confirmation.getEvidences()).collect(FileInfo::new));
|
||||
this.setCreatedTime(confirmation.getCreatedTime());
|
||||
this.setCreatedUsername(confirmation.getCreatedUser().getUsername());
|
||||
this.setModifiedTime(confirmation.getModifiedTime());
|
||||
this.setModifiedUsername(confirmation.getModifiedUser().getUsername());
|
||||
}
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static final class DetailItem extends SaveItem {
|
||||
private String targetName;
|
||||
private LocalDateTime createdTime;
|
||||
private String createdUsername;
|
||||
private LocalDateTime modifiedTime;
|
||||
private String modifiedUsername;
|
||||
|
||||
public DetailItem(Confirmation confirmation) {
|
||||
this.setId(confirmation.getId());
|
||||
this.setTargetId(confirmation.getTarget().getId());
|
||||
this.setTargetName(confirmation.getTarget().getName());
|
||||
this.setDescription(confirmation.getDescription());
|
||||
this.setEvidenceFiles(Sets.immutable.ofAll(confirmation.getEvidences()).collect(FileInfo::new));
|
||||
this.setCreatedTime(confirmation.getCreatedTime());
|
||||
this.setCreatedUsername(confirmation.getCreatedUser().getUsername());
|
||||
this.setModifiedTime(confirmation.getModifiedTime());
|
||||
this.setModifiedUsername(confirmation.getModifiedUser().getUsername());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,179 +41,179 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
@RestController
|
||||
@RequestMapping("/upload")
|
||||
public class DataFileController {
|
||||
private final HostConfiguration hostConfiguration;
|
||||
private final DataFileService dataFileService;
|
||||
private final String uploadFolderPath;
|
||||
private final String cacheFolderPath;
|
||||
private final String sliceFolderPath;
|
||||
private final HostConfiguration hostConfiguration;
|
||||
private final DataFileService dataFileService;
|
||||
private final String uploadFolderPath;
|
||||
private final String cacheFolderPath;
|
||||
private final String sliceFolderPath;
|
||||
|
||||
public DataFileController(HostConfiguration hostConfiguration, UploadConfiguration uploadConfiguration, DataFileService dataFileService) {
|
||||
this.hostConfiguration = hostConfiguration;
|
||||
this.dataFileService = dataFileService;
|
||||
public DataFileController(HostConfiguration hostConfiguration, UploadConfiguration uploadConfiguration, DataFileService dataFileService) {
|
||||
this.hostConfiguration = hostConfiguration;
|
||||
this.dataFileService = dataFileService;
|
||||
|
||||
this.uploadFolderPath = uploadConfiguration.getUploadPath();
|
||||
this.cacheFolderPath = StrUtil.format("{}/cache", uploadFolderPath);
|
||||
this.sliceFolderPath = StrUtil.format("{}/slice", uploadFolderPath);
|
||||
this.uploadFolderPath = uploadConfiguration.getUploadPath();
|
||||
this.cacheFolderPath = StrUtil.format("{}/cache", uploadFolderPath);
|
||||
this.sliceFolderPath = StrUtil.format("{}/slice", uploadFolderPath);
|
||||
}
|
||||
|
||||
@PostMapping("")
|
||||
public AmisResponse<FinishResponse> upload(@RequestParam("file") MultipartFile file) throws IOException {
|
||||
String filename = file.getOriginalFilename();
|
||||
Long id = dataFileService.initialDataFile(filename);
|
||||
String url = StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), id);
|
||||
byte[] bytes = file.getBytes();
|
||||
String originMd5 = SecureUtil.md5(new ByteArrayInputStream(bytes));
|
||||
File targetFile = new File(StrUtil.format("{}/{}", uploadFolderPath, originMd5));
|
||||
if (targetFile.exists()) {
|
||||
dataFileService.updateDataFile(id, FileUtil.getAbsolutePath(targetFile), FileUtil.size(targetFile), originMd5, file.getContentType());
|
||||
return AmisResponse.responseSuccess(new FinishResponse(id, filename, url, url));
|
||||
}
|
||||
|
||||
@PostMapping("")
|
||||
public AmisResponse<FinishResponse> upload(@RequestParam("file") MultipartFile file) throws IOException {
|
||||
String filename = file.getOriginalFilename();
|
||||
Long id = dataFileService.initialDataFile(filename);
|
||||
String url = StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), id);
|
||||
byte[] bytes = file.getBytes();
|
||||
String originMd5 = SecureUtil.md5(new ByteArrayInputStream(bytes));
|
||||
File targetFile = new File(StrUtil.format("{}/{}", uploadFolderPath, originMd5));
|
||||
if (targetFile.exists()) {
|
||||
dataFileService.updateDataFile(id, FileUtil.getAbsolutePath(targetFile), FileUtil.size(targetFile), originMd5, file.getContentType());
|
||||
return AmisResponse.responseSuccess(new FinishResponse(id, filename, url, url));
|
||||
}
|
||||
File cacheFile = new File(StrUtil.format("{}/{}", cacheFolderPath, id));
|
||||
cacheFile = FileUtil.writeBytes(bytes, cacheFile);
|
||||
String targetMd5 = SecureUtil.md5(cacheFile);
|
||||
if (!StrUtil.equals(originMd5, targetMd5)) {
|
||||
throw new RuntimeException("文件上传失败,校验不匹配");
|
||||
}
|
||||
FileUtil.move(cacheFile, targetFile, true);
|
||||
dataFileService.updateDataFile(id, FileUtil.getAbsolutePath(targetFile), FileUtil.size(targetFile), targetMd5, file.getContentType());
|
||||
return AmisResponse.responseSuccess(new FinishResponse(id, filename, url, url));
|
||||
File cacheFile = new File(StrUtil.format("{}/{}", cacheFolderPath, id));
|
||||
cacheFile = FileUtil.writeBytes(bytes, cacheFile);
|
||||
String targetMd5 = SecureUtil.md5(cacheFile);
|
||||
if (!StrUtil.equals(originMd5, targetMd5)) {
|
||||
throw new RuntimeException("文件上传失败,校验不匹配");
|
||||
}
|
||||
FileUtil.move(cacheFile, targetFile, true);
|
||||
dataFileService.updateDataFile(id, FileUtil.getAbsolutePath(targetFile), FileUtil.size(targetFile), targetMd5, file.getContentType());
|
||||
return AmisResponse.responseSuccess(new FinishResponse(id, filename, url, url));
|
||||
}
|
||||
|
||||
@GetMapping("/download/{id}")
|
||||
public void download(@PathVariable Long id, HttpServletResponse response) throws IOException {
|
||||
DataFile dataFile = dataFileService.downloadFile(id);
|
||||
File targetFile = new File(dataFile.getPath());
|
||||
response.setHeader("Access-Control-Expose-Headers", "Content-Type");
|
||||
response.setHeader("Content-Type", dataFile.getType());
|
||||
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
|
||||
response.setHeader("Content-Disposition", StrUtil.format("attachment; filename={}", dataFile.getFilename()));
|
||||
IoUtil.copy(new FileInputStream(targetFile), response.getOutputStream());
|
||||
@GetMapping("/download/{id}")
|
||||
public void download(@PathVariable Long id, HttpServletResponse response) throws IOException {
|
||||
DataFile dataFile = dataFileService.downloadFile(id);
|
||||
File targetFile = new File(dataFile.getPath());
|
||||
response.setHeader("Access-Control-Expose-Headers", "Content-Type");
|
||||
response.setHeader("Content-Type", dataFile.getType());
|
||||
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
|
||||
response.setHeader("Content-Disposition", StrUtil.format("attachment; filename={}", dataFile.getFilename()));
|
||||
IoUtil.copy(new FileInputStream(targetFile), response.getOutputStream());
|
||||
}
|
||||
|
||||
@PostMapping("/start")
|
||||
public AmisResponse<StartResponse> start(@RequestBody StartRequest request) {
|
||||
log.info("Request: {}", request);
|
||||
Long id = dataFileService.initialDataFile(request.filename);
|
||||
return AmisResponse.responseSuccess(new StartResponse(id.toString()));
|
||||
}
|
||||
|
||||
@PostMapping("/slice")
|
||||
public AmisResponse<SliceResponse> slice(
|
||||
@RequestParam("uploadId")
|
||||
Long uploadId,
|
||||
@RequestParam("partNumber")
|
||||
Integer sequence,
|
||||
@RequestParam("partSize")
|
||||
Long size,
|
||||
@RequestParam("file")
|
||||
MultipartFile file
|
||||
) throws IOException {
|
||||
byte[] bytes = file.getBytes();
|
||||
String md5 = SecureUtil.md5(new ByteArrayInputStream(bytes));
|
||||
String targetFilename = StrUtil.format("{}-{}", sequence, md5);
|
||||
String targetFilePath = sliceFilePath(uploadId, targetFilename);
|
||||
FileUtil.mkParentDirs(targetFilePath);
|
||||
FileUtil.writeBytes(bytes, targetFilePath);
|
||||
return AmisResponse.responseSuccess(new SliceResponse(targetFilename));
|
||||
}
|
||||
|
||||
private String sliceFilePath(Long uploadId, String sliceFilename) {
|
||||
return StrUtil.format("{}/{}/{}", sliceFolderPath, uploadId, sliceFilename);
|
||||
}
|
||||
|
||||
@PostMapping("finish")
|
||||
public AmisResponse<FinishResponse> finish(@RequestBody FinishRequest request) {
|
||||
if (request.partList.anySatisfy(part -> !FileUtil.exist(sliceFilePath(request.uploadId, part.eTag)))) {
|
||||
throw new RuntimeException("文件校验失败,请重新上传");
|
||||
}
|
||||
|
||||
@PostMapping("/start")
|
||||
public AmisResponse<StartResponse> start(@RequestBody StartRequest request) {
|
||||
log.info("Request: {}", request);
|
||||
Long id = dataFileService.initialDataFile(request.filename);
|
||||
return AmisResponse.responseSuccess(new StartResponse(id.toString()));
|
||||
}
|
||||
|
||||
@PostMapping("/slice")
|
||||
public AmisResponse<SliceResponse> slice(
|
||||
@RequestParam("uploadId")
|
||||
Long uploadId,
|
||||
@RequestParam("partNumber")
|
||||
Integer sequence,
|
||||
@RequestParam("partSize")
|
||||
Long size,
|
||||
@RequestParam("file")
|
||||
MultipartFile file
|
||||
) throws IOException {
|
||||
byte[] bytes = file.getBytes();
|
||||
String md5 = SecureUtil.md5(new ByteArrayInputStream(bytes));
|
||||
String targetFilename = StrUtil.format("{}-{}", sequence, md5);
|
||||
String targetFilePath = sliceFilePath(uploadId, targetFilename);
|
||||
FileUtil.mkParentDirs(targetFilePath);
|
||||
FileUtil.writeBytes(bytes, targetFilePath);
|
||||
return AmisResponse.responseSuccess(new SliceResponse(targetFilename));
|
||||
}
|
||||
|
||||
private String sliceFilePath(Long uploadId, String sliceFilename) {
|
||||
return StrUtil.format("{}/{}/{}", sliceFolderPath, uploadId, sliceFilename);
|
||||
}
|
||||
|
||||
@PostMapping("finish")
|
||||
public AmisResponse<FinishResponse> finish(@RequestBody FinishRequest request) {
|
||||
if (request.partList.anySatisfy(part -> !FileUtil.exist(sliceFilePath(request.uploadId, part.eTag)))) {
|
||||
throw new RuntimeException("文件校验失败,请重新上传");
|
||||
}
|
||||
try {
|
||||
File cacheFile = new File(StrUtil.format("{}/{}", cacheFolderPath, request.uploadId));
|
||||
FileUtil.mkParentDirs(cacheFile);
|
||||
if (cacheFile.createNewFile()) {
|
||||
try (FileOutputStream fos = new FileOutputStream(cacheFile)) {
|
||||
try (FileChannel fosChannel = fos.getChannel()) {
|
||||
for (FinishRequest.Part part : request.partList) {
|
||||
File sliceFile = new File(sliceFilePath(request.uploadId, part.eTag));
|
||||
try (FileInputStream fis = new FileInputStream(sliceFile)) {
|
||||
try (FileChannel fisChannel = fis.getChannel()) {
|
||||
fisChannel.transferTo(0, fisChannel.size(), fosChannel);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
File cacheFile = new File(StrUtil.format("{}/{}", cacheFolderPath, request.uploadId));
|
||||
FileUtil.mkParentDirs(cacheFile);
|
||||
if (cacheFile.createNewFile()) {
|
||||
try (FileOutputStream fos = new FileOutputStream(cacheFile)) {
|
||||
try (FileChannel fosChannel = fos.getChannel()) {
|
||||
for (FinishRequest.Part part : request.partList) {
|
||||
File sliceFile = new File(sliceFilePath(request.uploadId, part.eTag));
|
||||
try (FileInputStream fis = new FileInputStream(sliceFile)) {
|
||||
try (FileChannel fisChannel = fis.getChannel()) {
|
||||
fisChannel.transferTo(0, fisChannel.size(), fosChannel);
|
||||
}
|
||||
String md5 = SecureUtil.md5(cacheFile);
|
||||
File targetFile = new File(StrUtil.format("{}/{}", uploadFolderPath, md5));
|
||||
if (!targetFile.exists()) {
|
||||
FileUtil.move(cacheFile, targetFile, true);
|
||||
}
|
||||
String absolutePath = FileUtil.getAbsolutePath(targetFile);
|
||||
dataFileService.updateDataFile(
|
||||
request.uploadId,
|
||||
absolutePath,
|
||||
FileUtil.size(targetFile),
|
||||
SecureUtil.md5(targetFile),
|
||||
FileUtil.getMimeType(absolutePath)
|
||||
);
|
||||
return AmisResponse.responseSuccess(new FinishResponse(
|
||||
request.uploadId,
|
||||
request.filename,
|
||||
request.uploadId.toString(),
|
||||
StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), request.uploadId)
|
||||
));
|
||||
} else {
|
||||
throw new RuntimeException("合并文件失败");
|
||||
}
|
||||
}
|
||||
} catch (Throwable throwable) {
|
||||
throw new RuntimeException(throwable);
|
||||
} finally {
|
||||
FileUtil.del(StrUtil.format("{}/{}", cacheFolderPath, request.uploadId));
|
||||
FileUtil.del(StrUtil.format("{}/{}", sliceFolderPath, request.uploadId));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
public static final class StartRequest {
|
||||
private String name;
|
||||
private String filename;
|
||||
}
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static final class StartResponse {
|
||||
private String uploadId;
|
||||
}
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static final class SliceResponse {
|
||||
@JsonProperty("eTag")
|
||||
private String eTag;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static final class FinishRequest {
|
||||
private String filename;
|
||||
private Long uploadId;
|
||||
private ImmutableList<Part> partList;
|
||||
|
||||
@Data
|
||||
public static final class Part {
|
||||
private Integer partNumber;
|
||||
@JsonProperty("eTag")
|
||||
private String eTag;
|
||||
String md5 = SecureUtil.md5(cacheFile);
|
||||
File targetFile = new File(StrUtil.format("{}/{}", uploadFolderPath, md5));
|
||||
if (!targetFile.exists()) {
|
||||
FileUtil.move(cacheFile, targetFile, true);
|
||||
}
|
||||
String absolutePath = FileUtil.getAbsolutePath(targetFile);
|
||||
dataFileService.updateDataFile(
|
||||
request.uploadId,
|
||||
absolutePath,
|
||||
FileUtil.size(targetFile),
|
||||
SecureUtil.md5(targetFile),
|
||||
FileUtil.getMimeType(absolutePath)
|
||||
);
|
||||
return AmisResponse.responseSuccess(new FinishResponse(
|
||||
request.uploadId,
|
||||
request.filename,
|
||||
request.uploadId.toString(),
|
||||
StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), request.uploadId)
|
||||
));
|
||||
} else {
|
||||
throw new RuntimeException("合并文件失败");
|
||||
}
|
||||
} catch (Throwable throwable) {
|
||||
throw new RuntimeException(throwable);
|
||||
} finally {
|
||||
FileUtil.del(StrUtil.format("{}/{}", cacheFolderPath, request.uploadId));
|
||||
FileUtil.del(StrUtil.format("{}/{}", sliceFolderPath, request.uploadId));
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
public static final class StartRequest {
|
||||
private String name;
|
||||
private String filename;
|
||||
}
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static final class StartResponse {
|
||||
private String uploadId;
|
||||
}
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static final class SliceResponse {
|
||||
@JsonProperty("eTag")
|
||||
private String eTag;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static final class FinishRequest {
|
||||
private String filename;
|
||||
private Long uploadId;
|
||||
private ImmutableList<Part> partList;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static final class FinishResponse {
|
||||
private Long id;
|
||||
private String filename;
|
||||
private String value;
|
||||
private String url;
|
||||
public static final class Part {
|
||||
private Integer partNumber;
|
||||
@JsonProperty("eTag")
|
||||
private String eTag;
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static final class FinishResponse {
|
||||
private Long id;
|
||||
private String filename;
|
||||
private String value;
|
||||
private String url;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,262 +47,262 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
@RestController
|
||||
@RequestMapping("/data_resource")
|
||||
public class DataResourceController extends SimpleControllerSupport<DataResource, DataResourceController.SaveItem, DataResourceController.ListItem, DataResourceController.DetailItem> {
|
||||
private final ObjectMapper mapper;
|
||||
private final DataResourceService dataResourceService;
|
||||
private final DataFileService dataFileService;
|
||||
private final ObjectMapper mapper;
|
||||
private final DataResourceService dataResourceService;
|
||||
private final DataFileService dataFileService;
|
||||
|
||||
public DataResourceController(DataResourceService dataResourceService, DataFileService dataFileService, Jackson2ObjectMapperBuilder builder) {
|
||||
super(dataResourceService);
|
||||
this.dataResourceService = dataResourceService;
|
||||
this.dataFileService = dataFileService;
|
||||
this.mapper = builder.build();
|
||||
}
|
||||
public DataResourceController(DataResourceService dataResourceService, DataFileService dataFileService, Jackson2ObjectMapperBuilder builder) {
|
||||
super(dataResourceService);
|
||||
this.dataResourceService = dataResourceService;
|
||||
this.dataFileService = dataFileService;
|
||||
this.mapper = builder.build();
|
||||
}
|
||||
|
||||
@GetMapping(LIST + "_no_confirmation")
|
||||
public AmisResponse<ImmutableList<ListItem>> listNoConfirmation() {
|
||||
return AmisResponse.responseSuccess(dataResourceService.listNoConfirmation().collect(entity -> {
|
||||
try {
|
||||
return toListItem(entity);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}));
|
||||
}
|
||||
@GetMapping(LIST + "_no_confirmation")
|
||||
public AmisResponse<ImmutableList<ListItem>> listNoConfirmation() {
|
||||
return AmisResponse.responseSuccess(dataResourceService.listNoConfirmation().collect(entity -> {
|
||||
try {
|
||||
return toListItem(entity);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@GetMapping(LIST + "_no_authentication")
|
||||
public AmisResponse<ImmutableList<ListItem>> listNoAuthentication() {
|
||||
return AmisResponse.responseSuccess(dataResourceService.listNoAuthentication().collect(entity -> {
|
||||
try {
|
||||
return toListItem(entity);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}));
|
||||
}
|
||||
@GetMapping(LIST + "_no_authentication")
|
||||
public AmisResponse<ImmutableList<ListItem>> listNoAuthentication() {
|
||||
return AmisResponse.responseSuccess(dataResourceService.listNoAuthentication().collect(entity -> {
|
||||
try {
|
||||
return toListItem(entity);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@GetMapping(LIST + "_no_ware")
|
||||
public AmisResponse<ImmutableList<ListItem>> listNoWare() {
|
||||
return AmisResponse.responseSuccess(dataResourceService.listNoWare().collect(entity -> {
|
||||
try {
|
||||
return toListItem(entity);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}));
|
||||
}
|
||||
@GetMapping(LIST + "_no_ware")
|
||||
public AmisResponse<ImmutableList<ListItem>> listNoWare() {
|
||||
return AmisResponse.responseSuccess(dataResourceService.listNoWare().collect(entity -> {
|
||||
try {
|
||||
return toListItem(entity);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DataResource fromSaveItem(SaveItem item) throws JsonProcessingException {
|
||||
ResourceType type = generateResourceType(item);
|
||||
ResourceFormat format = generateResourceFormat(item);
|
||||
DataResource dataResource = new DataResource();
|
||||
dataResource.setId(item.getId());
|
||||
dataResource.setName(item.getName());
|
||||
dataResource.setDescription(item.getDescription());
|
||||
dataResource.setType(type);
|
||||
dataResource.setFormat(format);
|
||||
if (ObjectUtil.isNotNull(item.getExampleFile())) {
|
||||
dataResource.setExample(dataFileService.detail(item.getExampleFile().getValue()));
|
||||
}
|
||||
return dataResource;
|
||||
@Override
|
||||
protected DataResource fromSaveItem(SaveItem item) throws JsonProcessingException {
|
||||
ResourceType type = generateResourceType(item);
|
||||
ResourceFormat format = generateResourceFormat(item);
|
||||
DataResource dataResource = new DataResource();
|
||||
dataResource.setId(item.getId());
|
||||
dataResource.setName(item.getName());
|
||||
dataResource.setDescription(item.getDescription());
|
||||
dataResource.setType(type);
|
||||
dataResource.setFormat(format);
|
||||
if (ObjectUtil.isNotNull(item.getExampleFile())) {
|
||||
dataResource.setExample(dataFileService.detail(item.getExampleFile().getValue()));
|
||||
}
|
||||
return dataResource;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ListItem toListItem(DataResource dataResource) {
|
||||
ListItem item = new ListItem();
|
||||
item.setId(dataResource.getId());
|
||||
item.setName(dataResource.getName());
|
||||
item.setDescription(dataResource.getDescription());
|
||||
item.setType(dataResource.getType().getResourceType().name());
|
||||
item.setFormat(dataResource.getFormat().getFormatType().name());
|
||||
if (ObjectUtil.isNotNull(dataResource.getConfirmation())) {
|
||||
item.setConfirmationId(dataResource.getConfirmation().getId());
|
||||
item.setConfirmationState(dataResource.getConfirmation().getState());
|
||||
} else {
|
||||
item.setConfirmationState(Confirmation.State.NONE);
|
||||
}
|
||||
item.setCreatedUser(dataResource.getCreatedUser().getUsername());
|
||||
item.setCreatedTime(dataResource.getCreatedTime());
|
||||
return item;
|
||||
@Override
|
||||
protected ListItem toListItem(DataResource dataResource) {
|
||||
ListItem item = new ListItem();
|
||||
item.setId(dataResource.getId());
|
||||
item.setName(dataResource.getName());
|
||||
item.setDescription(dataResource.getDescription());
|
||||
item.setType(dataResource.getType().getResourceType().name());
|
||||
item.setFormat(dataResource.getFormat().getFormatType().name());
|
||||
if (ObjectUtil.isNotNull(dataResource.getConfirmation())) {
|
||||
item.setConfirmationId(dataResource.getConfirmation().getId());
|
||||
item.setConfirmationState(dataResource.getConfirmation().getState());
|
||||
} else {
|
||||
item.setConfirmationState(Confirmation.State.NONE);
|
||||
}
|
||||
item.setCreatedUser(dataResource.getCreatedUser().getUsername());
|
||||
item.setCreatedTime(dataResource.getCreatedTime());
|
||||
return item;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DetailItem toDetailItem(DataResource dataResource) throws Exception {
|
||||
DetailItem item = new DetailItem();
|
||||
item.setId(dataResource.getId());
|
||||
item.setResourceTypeId(dataResource.getType().getId());
|
||||
item.setResourceFormatId(dataResource.getFormat().getId());
|
||||
item.setName(dataResource.getName());
|
||||
item.setDescription(dataResource.getDescription());
|
||||
item.setResourceType(dataResource.getType().getResourceType());
|
||||
switch (dataResource.getType().getResourceType()) {
|
||||
case API:
|
||||
ApiResourceType apiType = (ApiResourceType) dataResource.getType();
|
||||
item.setApiUrl(apiType.getUrl());
|
||||
item.setApiUsername(apiType.getUsername());
|
||||
item.setApiPassword(apiType.getPassword());
|
||||
break;
|
||||
case FILE:
|
||||
FileResourceType fileType = (FileResourceType) dataResource.getType();
|
||||
item.setFile(new FileInfo(fileType.getFile()));
|
||||
break;
|
||||
case DATABASE:
|
||||
DatabaseResourceType databaseType = (DatabaseResourceType) dataResource.getType();
|
||||
item.setDatabaseType(databaseType.getDatabaseType().name());
|
||||
item.setDatabaseJdbc(databaseType.getJdbc());
|
||||
item.setDatabaseUsername(databaseType.getUsername());
|
||||
item.setDatabasePassword(databaseType.getPassword());
|
||||
break;
|
||||
case HDFS:
|
||||
HDFSResourceType hdfsType = (HDFSResourceType) dataResource.getType();
|
||||
item.setCoreSiteFile(new FileInfo(hdfsType.getCoreSite()));
|
||||
item.setHdfsSiteFile(new FileInfo(hdfsType.getHdfsSite()));
|
||||
break;
|
||||
case FTP:
|
||||
FtpResourceType ftpType = (FtpResourceType) dataResource.getType();
|
||||
item.setFtpUrl(ftpType.getUrl());
|
||||
item.setFtpUsername(ftpType.getUsername());
|
||||
item.setFtpPassword(ftpType.getPassword());
|
||||
item.setFtpPath(ftpType.getPath());
|
||||
item.setFtpRegexFilter(ftpType.getRegexFilter());
|
||||
break;
|
||||
}
|
||||
item.setFormatType(dataResource.getFormat().getFormatType());
|
||||
switch (dataResource.getFormat().getFormatType()) {
|
||||
case NONE:
|
||||
case LINE:
|
||||
break;
|
||||
case JSON:
|
||||
JsonResourceFormat jsonFormat = (JsonResourceFormat) dataResource.getFormat();
|
||||
item.setJsonSchemaText(jsonFormat.getSchema());
|
||||
item.setJsonSchema(mapper.readValue(jsonFormat.getSchema(), Map.class));
|
||||
break;
|
||||
case JSON_LINE:
|
||||
JsonLineResourceFormat jsonLineFormat = (JsonLineResourceFormat) dataResource.getFormat();
|
||||
item.setJsonLineSchemaText(jsonLineFormat.getSchema());
|
||||
item.setJsonLineSchema(mapper.readValue(jsonLineFormat.getSchema(), Map.class));
|
||||
break;
|
||||
case CSV:
|
||||
CsvResourceFormat csvFormat = (CsvResourceFormat) dataResource.getFormat();
|
||||
item.setCsvSchemaText(csvFormat.getSchema());
|
||||
item.setCsvSchema(mapper.readValue(csvFormat.getSchema(), Map.class));
|
||||
break;
|
||||
}
|
||||
if (ObjectUtil.isNotNull(dataResource.getExample())) {
|
||||
item.setExampleFile(new FileInfo(dataResource.getExample()));
|
||||
}
|
||||
item.setCreatedUsername(dataResource.getCreatedUser().getUsername());
|
||||
item.setCreatedTime(dataResource.getCreatedTime());
|
||||
item.setModifiedUsername(dataResource.getModifiedUser().getUsername());
|
||||
item.setModifiedTime(dataResource.getModifiedTime());
|
||||
return item;
|
||||
@Override
|
||||
protected DetailItem toDetailItem(DataResource dataResource) throws Exception {
|
||||
DetailItem item = new DetailItem();
|
||||
item.setId(dataResource.getId());
|
||||
item.setResourceTypeId(dataResource.getType().getId());
|
||||
item.setResourceFormatId(dataResource.getFormat().getId());
|
||||
item.setName(dataResource.getName());
|
||||
item.setDescription(dataResource.getDescription());
|
||||
item.setResourceType(dataResource.getType().getResourceType());
|
||||
switch (dataResource.getType().getResourceType()) {
|
||||
case API:
|
||||
ApiResourceType apiType = (ApiResourceType) dataResource.getType();
|
||||
item.setApiUrl(apiType.getUrl());
|
||||
item.setApiUsername(apiType.getUsername());
|
||||
item.setApiPassword(apiType.getPassword());
|
||||
break;
|
||||
case FILE:
|
||||
FileResourceType fileType = (FileResourceType) dataResource.getType();
|
||||
item.setFile(new FileInfo(fileType.getFile()));
|
||||
break;
|
||||
case DATABASE:
|
||||
DatabaseResourceType databaseType = (DatabaseResourceType) dataResource.getType();
|
||||
item.setDatabaseType(databaseType.getDatabaseType().name());
|
||||
item.setDatabaseJdbc(databaseType.getJdbc());
|
||||
item.setDatabaseUsername(databaseType.getUsername());
|
||||
item.setDatabasePassword(databaseType.getPassword());
|
||||
break;
|
||||
case HDFS:
|
||||
HDFSResourceType hdfsType = (HDFSResourceType) dataResource.getType();
|
||||
item.setCoreSiteFile(new FileInfo(hdfsType.getCoreSite()));
|
||||
item.setHdfsSiteFile(new FileInfo(hdfsType.getHdfsSite()));
|
||||
break;
|
||||
case FTP:
|
||||
FtpResourceType ftpType = (FtpResourceType) dataResource.getType();
|
||||
item.setFtpUrl(ftpType.getUrl());
|
||||
item.setFtpUsername(ftpType.getUsername());
|
||||
item.setFtpPassword(ftpType.getPassword());
|
||||
item.setFtpPath(ftpType.getPath());
|
||||
item.setFtpRegexFilter(ftpType.getRegexFilter());
|
||||
break;
|
||||
}
|
||||
item.setFormatType(dataResource.getFormat().getFormatType());
|
||||
switch (dataResource.getFormat().getFormatType()) {
|
||||
case NONE:
|
||||
case LINE:
|
||||
break;
|
||||
case JSON:
|
||||
JsonResourceFormat jsonFormat = (JsonResourceFormat) dataResource.getFormat();
|
||||
item.setJsonSchemaText(jsonFormat.getSchema());
|
||||
item.setJsonSchema(mapper.readValue(jsonFormat.getSchema(), Map.class));
|
||||
break;
|
||||
case JSON_LINE:
|
||||
JsonLineResourceFormat jsonLineFormat = (JsonLineResourceFormat) dataResource.getFormat();
|
||||
item.setJsonLineSchemaText(jsonLineFormat.getSchema());
|
||||
item.setJsonLineSchema(mapper.readValue(jsonLineFormat.getSchema(), Map.class));
|
||||
break;
|
||||
case CSV:
|
||||
CsvResourceFormat csvFormat = (CsvResourceFormat) dataResource.getFormat();
|
||||
item.setCsvSchemaText(csvFormat.getSchema());
|
||||
item.setCsvSchema(mapper.readValue(csvFormat.getSchema(), Map.class));
|
||||
break;
|
||||
}
|
||||
if (ObjectUtil.isNotNull(dataResource.getExample())) {
|
||||
item.setExampleFile(new FileInfo(dataResource.getExample()));
|
||||
}
|
||||
item.setCreatedUsername(dataResource.getCreatedUser().getUsername());
|
||||
item.setCreatedTime(dataResource.getCreatedTime());
|
||||
item.setModifiedUsername(dataResource.getModifiedUser().getUsername());
|
||||
item.setModifiedTime(dataResource.getModifiedTime());
|
||||
return item;
|
||||
}
|
||||
|
||||
private ResourceType generateResourceType(SaveItem item) {
|
||||
ResourceType type = null;
|
||||
switch (item.getResourceType()) {
|
||||
case API:
|
||||
type = new ApiResourceType(item.getApiUrl(), item.getApiUsername(), item.getApiPassword());
|
||||
break;
|
||||
case FILE:
|
||||
DataFile dataFile = dataFileService.detail(item.getFile().getValue());
|
||||
type = new FileResourceType(dataFile);
|
||||
break;
|
||||
case DATABASE:
|
||||
type = new DatabaseResourceType(
|
||||
item.getDatabaseJdbc(),
|
||||
item.getDatabaseUsername(),
|
||||
item.getDatabasePassword(),
|
||||
EnumUtil.fromString(DatabaseResourceType.DatabaseType.class, item.getDatabaseType())
|
||||
);
|
||||
break;
|
||||
case HDFS:
|
||||
type = new HDFSResourceType(dataFileService.detail(item.getCoreSiteFile().getValue()), dataFileService.detail(item.getHdfsSiteFile().getValue()));
|
||||
break;
|
||||
case FTP:
|
||||
type = new FtpResourceType(item.getFtpUrl(), item.getFtpUsername(), item.getFtpPassword(), item.getFtpPath(), item.getFtpRegexFilter());
|
||||
break;
|
||||
}
|
||||
type.setId(item.getResourceTypeId());
|
||||
return type;
|
||||
private ResourceType generateResourceType(SaveItem item) {
|
||||
ResourceType type = null;
|
||||
switch (item.getResourceType()) {
|
||||
case API:
|
||||
type = new ApiResourceType(item.getApiUrl(), item.getApiUsername(), item.getApiPassword());
|
||||
break;
|
||||
case FILE:
|
||||
DataFile dataFile = dataFileService.detail(item.getFile().getValue());
|
||||
type = new FileResourceType(dataFile);
|
||||
break;
|
||||
case DATABASE:
|
||||
type = new DatabaseResourceType(
|
||||
item.getDatabaseJdbc(),
|
||||
item.getDatabaseUsername(),
|
||||
item.getDatabasePassword(),
|
||||
EnumUtil.fromString(DatabaseResourceType.DatabaseType.class, item.getDatabaseType())
|
||||
);
|
||||
break;
|
||||
case HDFS:
|
||||
type = new HDFSResourceType(dataFileService.detail(item.getCoreSiteFile().getValue()), dataFileService.detail(item.getHdfsSiteFile().getValue()));
|
||||
break;
|
||||
case FTP:
|
||||
type = new FtpResourceType(item.getFtpUrl(), item.getFtpUsername(), item.getFtpPassword(), item.getFtpPath(), item.getFtpRegexFilter());
|
||||
break;
|
||||
}
|
||||
type.setId(item.getResourceTypeId());
|
||||
return type;
|
||||
}
|
||||
|
||||
private ResourceFormat generateResourceFormat(SaveItem item) throws JsonProcessingException {
|
||||
ResourceFormat format = null;
|
||||
switch (item.getFormatType()) {
|
||||
case NONE:
|
||||
format = new NoneResourceFormat();
|
||||
break;
|
||||
case LINE:
|
||||
format = new LineResourceFormat();
|
||||
break;
|
||||
case JSON:
|
||||
format = new JsonResourceFormat(mapper.writeValueAsString(item.getJsonSchema()));
|
||||
break;
|
||||
case JSON_LINE:
|
||||
format = new JsonLineResourceFormat(mapper.writeValueAsString(item.getJsonLineSchema()));
|
||||
break;
|
||||
case CSV:
|
||||
format = new CsvResourceFormat(mapper.writeValueAsString(item.getCsvSchema()));
|
||||
break;
|
||||
}
|
||||
format.setId(item.getResourceFormatId());
|
||||
return format;
|
||||
private ResourceFormat generateResourceFormat(SaveItem item) throws JsonProcessingException {
|
||||
ResourceFormat format = null;
|
||||
switch (item.getFormatType()) {
|
||||
case NONE:
|
||||
format = new NoneResourceFormat();
|
||||
break;
|
||||
case LINE:
|
||||
format = new LineResourceFormat();
|
||||
break;
|
||||
case JSON:
|
||||
format = new JsonResourceFormat(mapper.writeValueAsString(item.getJsonSchema()));
|
||||
break;
|
||||
case JSON_LINE:
|
||||
format = new JsonLineResourceFormat(mapper.writeValueAsString(item.getJsonLineSchema()));
|
||||
break;
|
||||
case CSV:
|
||||
format = new CsvResourceFormat(mapper.writeValueAsString(item.getCsvSchema()));
|
||||
break;
|
||||
}
|
||||
format.setId(item.getResourceFormatId());
|
||||
return format;
|
||||
}
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static class SaveItem extends SimpleSaveItem<DataResource> {
|
||||
private String name;
|
||||
private String description;
|
||||
private Long resourceTypeId;
|
||||
private ResourceType.Type resourceType;
|
||||
private String apiUrl;
|
||||
private String apiUsername;
|
||||
private String apiPassword;
|
||||
private FileInfo file;
|
||||
private String databaseType;
|
||||
private String databaseJdbc;
|
||||
private String databaseUsername;
|
||||
private String databasePassword;
|
||||
private FileInfo coreSiteFile;
|
||||
private FileInfo hdfsSiteFile;
|
||||
private String ftpUrl;
|
||||
private String ftpUsername;
|
||||
private String ftpPassword;
|
||||
private String ftpPath;
|
||||
private String ftpRegexFilter;
|
||||
private Long resourceFormatId;
|
||||
private ResourceFormat.Type formatType;
|
||||
private Map<?, ?> jsonSchema;
|
||||
private String jsonSchemaText;
|
||||
private Map<?, ?> jsonLineSchema;
|
||||
private String jsonLineSchemaText;
|
||||
private Map<?, ?> csvSchema;
|
||||
private String csvSchemaText;
|
||||
private FileInfo exampleFile;
|
||||
}
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static class SaveItem extends SimpleSaveItem<DataResource> {
|
||||
private String name;
|
||||
private String description;
|
||||
private Long resourceTypeId;
|
||||
private ResourceType.Type resourceType;
|
||||
private String apiUrl;
|
||||
private String apiUsername;
|
||||
private String apiPassword;
|
||||
private FileInfo file;
|
||||
private String databaseType;
|
||||
private String databaseJdbc;
|
||||
private String databaseUsername;
|
||||
private String databasePassword;
|
||||
private FileInfo coreSiteFile;
|
||||
private FileInfo hdfsSiteFile;
|
||||
private String ftpUrl;
|
||||
private String ftpUsername;
|
||||
private String ftpPassword;
|
||||
private String ftpPath;
|
||||
private String ftpRegexFilter;
|
||||
private Long resourceFormatId;
|
||||
private ResourceFormat.Type formatType;
|
||||
private Map<?, ?> jsonSchema;
|
||||
private String jsonSchemaText;
|
||||
private Map<?, ?> jsonLineSchema;
|
||||
private String jsonLineSchemaText;
|
||||
private Map<?, ?> csvSchema;
|
||||
private String csvSchemaText;
|
||||
private FileInfo exampleFile;
|
||||
}
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static final class ListItem extends SimpleListItem<DataResource> {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String description;
|
||||
private String type;
|
||||
private String format;
|
||||
private Long confirmationId;
|
||||
private Confirmation.State confirmationState;
|
||||
private String createdUser;
|
||||
private LocalDateTime createdTime;
|
||||
}
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static final class ListItem extends SimpleListItem<DataResource> {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String description;
|
||||
private String type;
|
||||
private String format;
|
||||
private Long confirmationId;
|
||||
private Confirmation.State confirmationState;
|
||||
private String createdUser;
|
||||
private LocalDateTime createdTime;
|
||||
}
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static final class DetailItem extends SaveItem {
|
||||
private LocalDateTime createdTime;
|
||||
private String createdUsername;
|
||||
private LocalDateTime modifiedTime;
|
||||
private String modifiedUsername;
|
||||
}
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static final class DetailItem extends SaveItem {
|
||||
private LocalDateTime createdTime;
|
||||
private String createdUsername;
|
||||
private LocalDateTime modifiedTime;
|
||||
private String modifiedUsername;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,54 +23,54 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
@RestController
|
||||
@RequestMapping("/user")
|
||||
public class UserController {
|
||||
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
|
||||
|
||||
private final UserService userService;
|
||||
private final UserService userService;
|
||||
|
||||
public UserController(UserService userService) {
|
||||
this.userService = userService;
|
||||
public UserController(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@GetMapping("/state")
|
||||
public AmisResponse<UserService.UserInformation> state() {
|
||||
return AmisResponse.responseSuccess(userService.state());
|
||||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
public void register(@RequestBody RegisterRequest request) {
|
||||
logger.info("Register request: {}", request);
|
||||
userService.register(request.username, request.password, request.role);
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public AmisResponse<UserService.UserInformation> login(@RequestBody LoginRequest request) {
|
||||
logger.info("Login request: {}", request);
|
||||
return AmisResponse.responseSuccess(userService.login(request.username, request.password));
|
||||
}
|
||||
|
||||
@GetMapping("/logout")
|
||||
public void logout() {
|
||||
userService.logout();
|
||||
}
|
||||
|
||||
@GetMapping("/exists_username/{username}")
|
||||
public void existsUsername(@PathVariable("username") String username) {
|
||||
if (userService.exitsUsername(username)) {
|
||||
throw new RuntimeException(StrUtil.format("{} 已存在", username));
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/state")
|
||||
public AmisResponse<UserService.UserInformation> state() {
|
||||
return AmisResponse.responseSuccess(userService.state());
|
||||
}
|
||||
@Data
|
||||
public static final class LoginRequest {
|
||||
private String username;
|
||||
private String password;
|
||||
private String checkCode;
|
||||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
public void register(@RequestBody RegisterRequest request) {
|
||||
logger.info("Register request: {}", request);
|
||||
userService.register(request.username, request.password, request.role);
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public AmisResponse<UserService.UserInformation> login(@RequestBody LoginRequest request) {
|
||||
logger.info("Login request: {}", request);
|
||||
return AmisResponse.responseSuccess(userService.login(request.username, request.password));
|
||||
}
|
||||
|
||||
@GetMapping("/logout")
|
||||
public void logout() {
|
||||
userService.logout();
|
||||
}
|
||||
|
||||
@GetMapping("/exists_username/{username}")
|
||||
public void existsUsername(@PathVariable("username") String username) {
|
||||
if (userService.exitsUsername(username)) {
|
||||
throw new RuntimeException(StrUtil.format("{} 已存在", username));
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
public static final class LoginRequest {
|
||||
private String username;
|
||||
private String password;
|
||||
private String checkCode;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static final class RegisterRequest {
|
||||
private String username;
|
||||
private String password;
|
||||
private User.Role role;
|
||||
}
|
||||
@Data
|
||||
public static final class RegisterRequest {
|
||||
private String username;
|
||||
private String password;
|
||||
private User.Role role;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,112 +25,112 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
@RestController
|
||||
@RequestMapping("/user_management")
|
||||
public class UserManagementController {
|
||||
private static final Logger logger = LoggerFactory.getLogger(UserManagementController.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(UserManagementController.class);
|
||||
|
||||
private final UserService userService;
|
||||
private final UserService userService;
|
||||
|
||||
public UserManagementController(UserService userService) {
|
||||
this.userService = userService;
|
||||
public UserManagementController(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@GetMapping("/list")
|
||||
public AmisListResponse list() {
|
||||
return AmisListResponse.responseListData(userService.list().collect(UserListItem::new));
|
||||
}
|
||||
|
||||
@GetMapping("/detail/{username}")
|
||||
public AmisResponse<UserDetail> detail(@PathVariable String username) {
|
||||
return AmisResponse.responseSuccess(new UserDetail(userService.detail(username)));
|
||||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
public void register(@RequestBody RegisterRequest request) {
|
||||
logger.info("Register request: {}", request);
|
||||
userService.registerFromAdministrator(request.username, request.password, request.role);
|
||||
}
|
||||
|
||||
@PostMapping("/change_password")
|
||||
public AmisResponse<Object> changePassword(@RequestBody ChangePasswordRequest request) {
|
||||
userService.changePassword(request.oldPassword, request.newPassword);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@GetMapping("/disable/{username}")
|
||||
public AmisResponse<Object> disable(@PathVariable String username) {
|
||||
userService.disable(username);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@GetMapping("/enable/{username}")
|
||||
public AmisResponse<Object> enable(@PathVariable String username) {
|
||||
userService.enable(username);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@GetMapping("/check/{username}")
|
||||
public AmisResponse<Object> check(@PathVariable String username) {
|
||||
userService.check(username);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@Data
|
||||
public static final class ChangePasswordRequest {
|
||||
private String oldPassword;
|
||||
private String newPassword;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static final class RegisterRequest {
|
||||
private String username;
|
||||
private String password;
|
||||
private User.Role role;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static final class UserListItem {
|
||||
private Long id;
|
||||
private String username;
|
||||
private User.Role role;
|
||||
private User.State state;
|
||||
private LocalDateTime lastLoginTime;
|
||||
private LocalDateTime createdTime;
|
||||
|
||||
public UserListItem(User user) {
|
||||
this.id = user.getId();
|
||||
this.username = user.getUsername();
|
||||
this.role = user.getRole();
|
||||
this.state = user.getState();
|
||||
this.lastLoginTime = user.getLastLoginTime();
|
||||
this.createdTime = user.getCreatedTime();
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/list")
|
||||
public AmisListResponse list() {
|
||||
return AmisListResponse.responseListData(userService.list().collect(UserListItem::new));
|
||||
}
|
||||
|
||||
@GetMapping("/detail/{username}")
|
||||
public AmisResponse<UserDetail> detail(@PathVariable String username) {
|
||||
return AmisResponse.responseSuccess(new UserDetail(userService.detail(username)));
|
||||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
public void register(@RequestBody RegisterRequest request) {
|
||||
logger.info("Register request: {}", request);
|
||||
userService.registerFromAdministrator(request.username, request.password, request.role);
|
||||
}
|
||||
|
||||
@PostMapping("/change_password")
|
||||
public AmisResponse<Object> changePassword(@RequestBody ChangePasswordRequest request) {
|
||||
userService.changePassword(request.oldPassword, request.newPassword);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@GetMapping("/disable/{username}")
|
||||
public AmisResponse<Object> disable(@PathVariable String username) {
|
||||
userService.disable(username);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@GetMapping("/enable/{username}")
|
||||
public AmisResponse<Object> enable(@PathVariable String username) {
|
||||
userService.enable(username);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@GetMapping("/check/{username}")
|
||||
public AmisResponse<Object> check(@PathVariable String username) {
|
||||
userService.check(username);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@Data
|
||||
public static final class ChangePasswordRequest {
|
||||
private String oldPassword;
|
||||
private String newPassword;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static final class RegisterRequest {
|
||||
private String username;
|
||||
private String password;
|
||||
private User.Role role;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static final class UserListItem {
|
||||
private Long id;
|
||||
private String username;
|
||||
private User.Role role;
|
||||
private User.State state;
|
||||
private LocalDateTime lastLoginTime;
|
||||
private LocalDateTime createdTime;
|
||||
|
||||
public UserListItem(User user) {
|
||||
this.id = user.getId();
|
||||
this.username = user.getUsername();
|
||||
this.role = user.getRole();
|
||||
this.state = user.getState();
|
||||
this.lastLoginTime = user.getLastLoginTime();
|
||||
this.createdTime = user.getCreatedTime();
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
public static final class UserDetail {
|
||||
private String username;
|
||||
private User.Role role;
|
||||
private User.State state;
|
||||
private LocalDateTime lastLoginTime;
|
||||
private LocalDateTime createdTime;
|
||||
private String createdUsername;
|
||||
private LocalDateTime modifiedTime;
|
||||
private String modifiedUsername;
|
||||
private LocalDateTime checkedTime;
|
||||
private String checkedUsername;
|
||||
|
||||
public UserDetail(User user) {
|
||||
this.username = user.getUsername();
|
||||
this.role = user.getRole();
|
||||
this.state = user.getState();
|
||||
this.lastLoginTime = user.getLastLoginTime();
|
||||
this.createdTime = user.getCreatedTime();
|
||||
this.createdUsername = user.getCreatedUser().getUsername();
|
||||
this.modifiedTime = user.getModifiedTime();
|
||||
this.modifiedUsername = user.getModifiedUser().getUsername();
|
||||
if (ObjectUtil.isNotNull(user.getCheckedUser())) {
|
||||
this.checkedTime = user.getCheckedTime();
|
||||
this.checkedUsername = user.getCheckedUser().getUsername();
|
||||
}
|
||||
}
|
||||
@Data
|
||||
public static final class UserDetail {
|
||||
private String username;
|
||||
private User.Role role;
|
||||
private User.State state;
|
||||
private LocalDateTime lastLoginTime;
|
||||
private LocalDateTime createdTime;
|
||||
private String createdUsername;
|
||||
private LocalDateTime modifiedTime;
|
||||
private String modifiedUsername;
|
||||
private LocalDateTime checkedTime;
|
||||
private String checkedUsername;
|
||||
|
||||
public UserDetail(User user) {
|
||||
this.username = user.getUsername();
|
||||
this.role = user.getRole();
|
||||
this.state = user.getState();
|
||||
this.lastLoginTime = user.getLastLoginTime();
|
||||
this.createdTime = user.getCreatedTime();
|
||||
this.createdUsername = user.getCreatedUser().getUsername();
|
||||
this.modifiedTime = user.getModifiedTime();
|
||||
this.modifiedUsername = user.getModifiedUser().getUsername();
|
||||
if (ObjectUtil.isNotNull(user.getCheckedUser())) {
|
||||
this.checkedTime = user.getCheckedTime();
|
||||
this.checkedUsername = user.getCheckedUser().getUsername();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,108 +29,108 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
@RestController
|
||||
@RequestMapping("ware")
|
||||
public class WareController extends SimpleControllerSupport<Ware, WareController.SaveItem, WareController.ListItem, WareController.DetailItem> {
|
||||
private final HostConfiguration hostConfiguration;
|
||||
private final WareService wareService;
|
||||
private final DataResourceService dataResourceService;
|
||||
private final DataFileService dataFileService;
|
||||
private final HostConfiguration hostConfiguration;
|
||||
private final WareService wareService;
|
||||
private final DataResourceService dataResourceService;
|
||||
private final DataFileService dataFileService;
|
||||
|
||||
public WareController(HostConfiguration hostConfiguration, WareService service, DataResourceService dataResourceService, DataFileService dataFileService) {
|
||||
super(service);
|
||||
this.hostConfiguration = hostConfiguration;
|
||||
this.wareService = service;
|
||||
this.dataResourceService = dataResourceService;
|
||||
this.dataFileService = dataFileService;
|
||||
}
|
||||
public WareController(HostConfiguration hostConfiguration, WareService service, DataResourceService dataResourceService, DataFileService dataFileService) {
|
||||
super(service);
|
||||
this.hostConfiguration = hostConfiguration;
|
||||
this.wareService = service;
|
||||
this.dataResourceService = dataResourceService;
|
||||
this.dataFileService = dataFileService;
|
||||
}
|
||||
|
||||
@GetMapping(LIST + "_public")
|
||||
public AmisResponse<ImmutableList<ListItem>> listPublic() {
|
||||
return AmisResponse.responseSuccess(wareService.listPublic().collect(this::toListItem));
|
||||
}
|
||||
@GetMapping(LIST + "_public")
|
||||
public AmisResponse<ImmutableList<ListItem>> listPublic() {
|
||||
return AmisResponse.responseSuccess(wareService.listPublic().collect(this::toListItem));
|
||||
}
|
||||
|
||||
@GetMapping("/submit/{id}")
|
||||
public AmisResponse<Object> submit(@PathVariable Long id) throws JsonProcessingException {
|
||||
wareService.submit(id);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
@GetMapping("/submit/{id}")
|
||||
public AmisResponse<Object> submit(@PathVariable Long id) throws JsonProcessingException {
|
||||
wareService.submit(id);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@GetMapping("/retract/{id}")
|
||||
public AmisResponse<Object> retract(@PathVariable Long id) {
|
||||
wareService.retract(id);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
@GetMapping("/retract/{id}")
|
||||
public AmisResponse<Object> retract(@PathVariable Long id) {
|
||||
wareService.retract(id);
|
||||
return AmisResponse.responseSuccess();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Ware fromSaveItem(SaveItem saveItem) {
|
||||
Ware ware = new Ware();
|
||||
ware.setId(saveItem.getId());
|
||||
ware.setResource(dataResourceService.detailOrThrow(saveItem.getResourceId()));
|
||||
ware.setName(saveItem.getName());
|
||||
ware.setDescription(saveItem.getDescription());
|
||||
ware.setIcon(dataFileService.detailOrThrow(saveItem.getIconId()));
|
||||
ware.setContent(saveItem.getContent());
|
||||
return ware;
|
||||
}
|
||||
@Override
|
||||
protected Ware fromSaveItem(SaveItem saveItem) {
|
||||
Ware ware = new Ware();
|
||||
ware.setId(saveItem.getId());
|
||||
ware.setResource(dataResourceService.detailOrThrow(saveItem.getResourceId()));
|
||||
ware.setName(saveItem.getName());
|
||||
ware.setDescription(saveItem.getDescription());
|
||||
ware.setIcon(dataFileService.detailOrThrow(saveItem.getIconId()));
|
||||
ware.setContent(saveItem.getContent());
|
||||
return ware;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ListItem toListItem(Ware entity) {
|
||||
ListItem item = new ListItem();
|
||||
item.setId(entity.getId());
|
||||
item.setName(entity.getName());
|
||||
item.setDescription(entity.getDescription());
|
||||
item.setIcon(StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), entity.getIcon().getId()));
|
||||
item.setState(entity.getState().name());
|
||||
item.setResourceId(entity.getResource().getId());
|
||||
item.setCreatedTime(entity.getCreatedTime());
|
||||
item.setCreatedUsername(entity.getCreatedUser().getUsername());
|
||||
return item;
|
||||
}
|
||||
@Override
|
||||
protected ListItem toListItem(Ware entity) {
|
||||
ListItem item = new ListItem();
|
||||
item.setId(entity.getId());
|
||||
item.setName(entity.getName());
|
||||
item.setDescription(entity.getDescription());
|
||||
item.setIcon(StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), entity.getIcon().getId()));
|
||||
item.setState(entity.getState().name());
|
||||
item.setResourceId(entity.getResource().getId());
|
||||
item.setCreatedTime(entity.getCreatedTime());
|
||||
item.setCreatedUsername(entity.getCreatedUser().getUsername());
|
||||
return item;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DetailItem toDetailItem(Ware entity) {
|
||||
DetailItem item = new DetailItem();
|
||||
item.setId(entity.getId());
|
||||
item.setResourceId(entity.getResource().getId());
|
||||
item.setResourceName(entity.getResource().getName());
|
||||
item.setName(entity.getName());
|
||||
item.setDescription(entity.getDescription());
|
||||
item.setIconId(entity.getIcon().getId());
|
||||
item.setContent(entity.getContent());
|
||||
item.setIcon(StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), entity.getIcon().getId()));
|
||||
item.setCreatedTime(entity.getCreatedTime());
|
||||
item.setCreatedUsername(entity.getCreatedUser().getUsername());
|
||||
item.setModifiedTime(entity.getModifiedTime());
|
||||
item.setModifiedUsername(entity.getModifiedUser().getUsername());
|
||||
return item;
|
||||
}
|
||||
@Override
|
||||
protected DetailItem toDetailItem(Ware entity) {
|
||||
DetailItem item = new DetailItem();
|
||||
item.setId(entity.getId());
|
||||
item.setResourceId(entity.getResource().getId());
|
||||
item.setResourceName(entity.getResource().getName());
|
||||
item.setName(entity.getName());
|
||||
item.setDescription(entity.getDescription());
|
||||
item.setIconId(entity.getIcon().getId());
|
||||
item.setContent(entity.getContent());
|
||||
item.setIcon(StrUtil.format("{}/upload/download/{}", hostConfiguration.getPrefix(), entity.getIcon().getId()));
|
||||
item.setCreatedTime(entity.getCreatedTime());
|
||||
item.setCreatedUsername(entity.getCreatedUser().getUsername());
|
||||
item.setModifiedTime(entity.getModifiedTime());
|
||||
item.setModifiedUsername(entity.getModifiedUser().getUsername());
|
||||
return item;
|
||||
}
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static class SaveItem extends SimpleSaveItem<Ware> {
|
||||
private Long resourceId;
|
||||
private String name;
|
||||
private String description;
|
||||
private Long iconId;
|
||||
private String content;
|
||||
}
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static class SaveItem extends SimpleSaveItem<Ware> {
|
||||
private Long resourceId;
|
||||
private String name;
|
||||
private String description;
|
||||
private Long iconId;
|
||||
private String content;
|
||||
}
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static class ListItem extends SimpleListItem<Ware> {
|
||||
private String name;
|
||||
private String description;
|
||||
private String state;
|
||||
private String icon;
|
||||
private Long resourceId;
|
||||
}
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static class ListItem extends SimpleListItem<Ware> {
|
||||
private String name;
|
||||
private String description;
|
||||
private String state;
|
||||
private String icon;
|
||||
private Long resourceId;
|
||||
}
|
||||
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static class DetailItem extends SaveItem {
|
||||
private String icon;
|
||||
private String resourceName;
|
||||
private LocalDateTime createdTime;
|
||||
private String createdUsername;
|
||||
private LocalDateTime modifiedTime;
|
||||
private String modifiedUsername;
|
||||
}
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
public static class DetailItem extends SaveItem {
|
||||
private String icon;
|
||||
private String resourceName;
|
||||
private LocalDateTime createdTime;
|
||||
private String createdUsername;
|
||||
private LocalDateTime modifiedTime;
|
||||
private String modifiedUsername;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,33 +41,33 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
@EntityListeners(AuditingEntityListener.class)
|
||||
@Table(name = Constants.TABLE_PREFIX + "authentication")
|
||||
@NamedEntityGraph(name = "authentication.list", attributeNodes = {
|
||||
@NamedAttributeNode(value = "target"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
@NamedAttributeNode(value = "target"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
})
|
||||
@NamedEntityGraph(name = "authentication.detail", attributeNodes = {
|
||||
@NamedAttributeNode(value = "target"),
|
||||
@NamedAttributeNode(value = "evidences"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
@NamedAttributeNode(value = "modifiedUser"),
|
||||
@NamedAttributeNode(value = "target"),
|
||||
@NamedAttributeNode(value = "evidences"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
@NamedAttributeNode(value = "modifiedUser"),
|
||||
})
|
||||
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "authentication" + " set deleted = true where id = ?")
|
||||
@Where(clause = LogicDeleteEntity.LOGIC_DELETE_CLAUSE)
|
||||
public class Authentication extends CheckingNeededEntity {
|
||||
@ManyToOne(fetch = FetchType.EAGER)
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
private DataResource target;
|
||||
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
|
||||
@JoinTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
private Set<DataFile> evidences;
|
||||
/**
|
||||
* 生效时间
|
||||
*/
|
||||
@Column(nullable = false)
|
||||
private LocalDateTime activeTime = LocalDateTime.now();
|
||||
/**
|
||||
* 过期时间
|
||||
*/
|
||||
@Column(nullable = false)
|
||||
private LocalDateTime expiredTime = LocalDateTime.now().plusDays(1);
|
||||
@ManyToOne(fetch = FetchType.EAGER)
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
private DataResource target;
|
||||
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
|
||||
@JoinTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
private Set<DataFile> evidences;
|
||||
/**
|
||||
* 生效时间
|
||||
*/
|
||||
@Column(nullable = false)
|
||||
private LocalDateTime activeTime = LocalDateTime.now();
|
||||
/**
|
||||
* 过期时间
|
||||
*/
|
||||
@Column(nullable = false)
|
||||
private LocalDateTime expiredTime = LocalDateTime.now().plusDays(1);
|
||||
}
|
||||
|
||||
@@ -34,97 +34,97 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
@EntityListeners(AuditingEntityListener.class)
|
||||
@Table(name = Constants.TABLE_PREFIX + "check_order")
|
||||
@NamedEntityGraph(name = "check_order.list", attributeNodes = {
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
@NamedAttributeNode(value = "modifiedUser"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
@NamedAttributeNode(value = "modifiedUser"),
|
||||
})
|
||||
@NamedEntityGraph(name = "check_order.detail", attributeNodes = {
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
@NamedAttributeNode(value = "modifiedUser"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
@NamedAttributeNode(value = "modifiedUser"),
|
||||
})
|
||||
@NoArgsConstructor
|
||||
public class CheckOrder extends SimpleEntity {
|
||||
@Column(nullable = false)
|
||||
private String keyword;
|
||||
@Column(nullable = false)
|
||||
private String description;
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private Type type;
|
||||
/**
|
||||
* JSON 结构 Map<String, Object>
|
||||
*/
|
||||
@Column(nullable = false)
|
||||
private String parameters;
|
||||
@Column(nullable = false)
|
||||
private String keyword;
|
||||
@Column(nullable = false)
|
||||
private String description;
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private Type type;
|
||||
/**
|
||||
* JSON 结构 Map<String, Object>
|
||||
*/
|
||||
@Column(nullable = false)
|
||||
private String parameters;
|
||||
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private Target target;
|
||||
@Column(nullable = false)
|
||||
private String targetClass;
|
||||
@OneToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
private User targetUser;
|
||||
@Enumerated(EnumType.STRING)
|
||||
private User.Role targetRole;
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private Target target;
|
||||
@Column(nullable = false)
|
||||
private String targetClass;
|
||||
@OneToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
private User targetUser;
|
||||
@Enumerated(EnumType.STRING)
|
||||
private User.Role targetRole;
|
||||
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private State state = State.CHECKING;
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private State state = State.CHECKING;
|
||||
|
||||
public CheckOrder(
|
||||
String keyword,
|
||||
String description,
|
||||
Type type,
|
||||
String parameters,
|
||||
String targetClass,
|
||||
User targetUser
|
||||
) {
|
||||
this.keyword = keyword;
|
||||
this.description = description;
|
||||
this.type = type;
|
||||
this.parameters = parameters;
|
||||
this.target = Target.USER;
|
||||
this.targetClass = targetClass;
|
||||
this.targetUser = targetUser;
|
||||
}
|
||||
public CheckOrder(
|
||||
String keyword,
|
||||
String description,
|
||||
Type type,
|
||||
String parameters,
|
||||
String targetClass,
|
||||
User targetUser
|
||||
) {
|
||||
this.keyword = keyword;
|
||||
this.description = description;
|
||||
this.type = type;
|
||||
this.parameters = parameters;
|
||||
this.target = Target.USER;
|
||||
this.targetClass = targetClass;
|
||||
this.targetUser = targetUser;
|
||||
}
|
||||
|
||||
public CheckOrder(
|
||||
String keyword,
|
||||
String description,
|
||||
Type type,
|
||||
String parameters,
|
||||
String targetClass,
|
||||
User.Role targetRole
|
||||
) {
|
||||
this.keyword = keyword;
|
||||
this.description = description;
|
||||
this.type = type;
|
||||
this.parameters = parameters;
|
||||
this.target = Target.ROLE;
|
||||
this.targetClass = targetClass;
|
||||
this.targetRole = targetRole;
|
||||
}
|
||||
public CheckOrder(
|
||||
String keyword,
|
||||
String description,
|
||||
Type type,
|
||||
String parameters,
|
||||
String targetClass,
|
||||
User.Role targetRole
|
||||
) {
|
||||
this.keyword = keyword;
|
||||
this.description = description;
|
||||
this.type = type;
|
||||
this.parameters = parameters;
|
||||
this.target = Target.ROLE;
|
||||
this.targetClass = targetClass;
|
||||
this.targetRole = targetRole;
|
||||
}
|
||||
|
||||
public enum Operation {
|
||||
APPLY,
|
||||
REJECT,
|
||||
}
|
||||
public enum Operation {
|
||||
APPLY,
|
||||
REJECT,
|
||||
}
|
||||
|
||||
public enum Type {
|
||||
CONFIRMATION,
|
||||
AUTHENTICATION,
|
||||
MARKET,
|
||||
}
|
||||
public enum Type {
|
||||
CONFIRMATION,
|
||||
AUTHENTICATION,
|
||||
MARKET,
|
||||
}
|
||||
|
||||
public enum Target {
|
||||
USER,
|
||||
ROLE,
|
||||
}
|
||||
public enum Target {
|
||||
USER,
|
||||
ROLE,
|
||||
}
|
||||
|
||||
public enum State {
|
||||
CHECKING,
|
||||
RETRACT,
|
||||
OVER,
|
||||
}
|
||||
public enum State {
|
||||
CHECKING,
|
||||
RETRACT,
|
||||
OVER,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,23 +39,23 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
@EntityListeners(AuditingEntityListener.class)
|
||||
@Table(name = Constants.TABLE_PREFIX + "confirmation")
|
||||
@NamedEntityGraph(name = "confirmation.list", attributeNodes = {
|
||||
@NamedAttributeNode(value = "target"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
@NamedAttributeNode(value = "target"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
})
|
||||
@NamedEntityGraph(name = "confirmation.detail", attributeNodes = {
|
||||
@NamedAttributeNode(value = "target"),
|
||||
@NamedAttributeNode(value = "evidences"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
@NamedAttributeNode(value = "modifiedUser"),
|
||||
@NamedAttributeNode(value = "target"),
|
||||
@NamedAttributeNode(value = "evidences"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
@NamedAttributeNode(value = "modifiedUser"),
|
||||
})
|
||||
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "confirmation" + " set deleted = true where id = ?")
|
||||
@Where(clause = LogicDeleteEntity.LOGIC_DELETE_CLAUSE)
|
||||
public class Confirmation extends CheckingNeededEntity {
|
||||
@OneToOne(fetch = FetchType.EAGER)
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
private DataResource target;
|
||||
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
|
||||
@JoinTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
private Set<DataFile> evidences;
|
||||
@OneToOne(fetch = FetchType.EAGER)
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
private DataResource target;
|
||||
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
|
||||
@JoinTable(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT), inverseForeignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
private Set<DataFile> evidences;
|
||||
}
|
||||
|
||||
@@ -26,9 +26,9 @@ import org.hibernate.annotations.Where;
|
||||
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "data_file" + " set deleted = true where id = ?")
|
||||
@Where(clause = LogicDeleteEntity.LOGIC_DELETE_CLAUSE)
|
||||
public class DataFile extends LogicDeleteEntity {
|
||||
private String filename;
|
||||
private Long size;
|
||||
private String md5;
|
||||
private String path;
|
||||
private String type;
|
||||
private String filename;
|
||||
private Long size;
|
||||
private String md5;
|
||||
private String path;
|
||||
private String type;
|
||||
}
|
||||
|
||||
@@ -34,44 +34,44 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
@DynamicUpdate
|
||||
@Table(name = Constants.TABLE_PREFIX + "data_resource")
|
||||
@NamedEntityGraph(name = "data_resource.list", attributeNodes = {
|
||||
@NamedAttributeNode(value = "type"),
|
||||
@NamedAttributeNode(value = "format"),
|
||||
@NamedAttributeNode(value = "confirmation"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
@NamedAttributeNode(value = "type"),
|
||||
@NamedAttributeNode(value = "format"),
|
||||
@NamedAttributeNode(value = "confirmation"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
})
|
||||
@NamedEntityGraph(name = "data_resource.detail", attributeNodes = {
|
||||
@NamedAttributeNode(value = "type"),
|
||||
@NamedAttributeNode(value = "format"),
|
||||
@NamedAttributeNode(value = "example"),
|
||||
@NamedAttributeNode(value = "confirmation"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
@NamedAttributeNode(value = "modifiedUser"),
|
||||
@NamedAttributeNode(value = "type"),
|
||||
@NamedAttributeNode(value = "format"),
|
||||
@NamedAttributeNode(value = "example"),
|
||||
@NamedAttributeNode(value = "confirmation"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
@NamedAttributeNode(value = "modifiedUser"),
|
||||
})
|
||||
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "data_resource" + " set deleted = true where id = ?")
|
||||
@Where(clause = LogicDeleteEntity.LOGIC_DELETE_CLAUSE)
|
||||
public class DataResource extends LogicDeleteEntity {
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
private String description;
|
||||
@OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
private ResourceType type;
|
||||
@OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
private ResourceFormat format;
|
||||
@OneToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
private DataFile example;
|
||||
@OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "target")
|
||||
@ToString.Exclude
|
||||
private Confirmation confirmation;
|
||||
@OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "target")
|
||||
@ToString.Exclude
|
||||
private Set<Authentication> authentications;
|
||||
@OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "resource")
|
||||
@ToString.Exclude
|
||||
private Ware ware;
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
private String description;
|
||||
@OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
private ResourceType type;
|
||||
@OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
private ResourceFormat format;
|
||||
@OneToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
private DataFile example;
|
||||
@OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "target")
|
||||
@ToString.Exclude
|
||||
private Confirmation confirmation;
|
||||
@OneToMany(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "target")
|
||||
@ToString.Exclude
|
||||
private Set<Authentication> authentications;
|
||||
@OneToOne(cascade = CascadeType.REMOVE, fetch = FetchType.EAGER, mappedBy = "resource")
|
||||
@ToString.Exclude
|
||||
private Ware ware;
|
||||
}
|
||||
|
||||
@@ -33,98 +33,98 @@ import org.hibernate.annotations.DynamicUpdate;
|
||||
@DynamicUpdate
|
||||
@Table(name = Constants.TABLE_PREFIX + "user")
|
||||
@NamedEntityGraph(name = "user.list", attributeNodes = {
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
})
|
||||
@NamedEntityGraph(name = "user.detail", attributeNodes = {
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
@NamedAttributeNode(value = "modifiedUser"),
|
||||
@NamedAttributeNode(value = "checkedUser"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
@NamedAttributeNode(value = "modifiedUser"),
|
||||
@NamedAttributeNode(value = "checkedUser"),
|
||||
})
|
||||
public class User extends SimpleEntity {
|
||||
@Column(unique = true, nullable = false)
|
||||
private String username;
|
||||
@Column(nullable = false)
|
||||
private String password;
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private Role role;
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private State state = State.CHECKING;
|
||||
private LocalDateTime lastLoginTime;
|
||||
private LocalDateTime checkedTime;
|
||||
@OneToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
private User checkedUser;
|
||||
@Column(unique = true, nullable = false)
|
||||
private String username;
|
||||
@Column(nullable = false)
|
||||
private String password;
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private Role role;
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private State state = State.CHECKING;
|
||||
private LocalDateTime lastLoginTime;
|
||||
private LocalDateTime checkedTime;
|
||||
@OneToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
private User checkedUser;
|
||||
|
||||
public static boolean isAdministrator(User user) {
|
||||
return Role.ADMINISTRATOR.equals(user.role);
|
||||
}
|
||||
public static boolean isAdministrator(User user) {
|
||||
return Role.ADMINISTRATOR.equals(user.role);
|
||||
}
|
||||
|
||||
public static boolean isNotAdministrator(User user) {
|
||||
return !isAdministrator(user);
|
||||
}
|
||||
public static boolean isNotAdministrator(User user) {
|
||||
return !isAdministrator(user);
|
||||
}
|
||||
|
||||
public static boolean isChecker(User user) {
|
||||
return Role.CHECKER.equals(user.role);
|
||||
}
|
||||
public static boolean isChecker(User user) {
|
||||
return Role.CHECKER.equals(user.role);
|
||||
}
|
||||
|
||||
public static boolean isNotChecker(User user) {
|
||||
return !isChecker(user);
|
||||
}
|
||||
public static boolean isNotChecker(User user) {
|
||||
return !isChecker(user);
|
||||
}
|
||||
|
||||
public static boolean isProvider(User user) {
|
||||
return Role.PROVIDER.equals(user.role);
|
||||
}
|
||||
public static boolean isProvider(User user) {
|
||||
return Role.PROVIDER.equals(user.role);
|
||||
}
|
||||
|
||||
public static boolean isNotProvider(User user) {
|
||||
return !isProvider(user);
|
||||
}
|
||||
public static boolean isNotProvider(User user) {
|
||||
return !isProvider(user);
|
||||
}
|
||||
|
||||
public static boolean isCustomer(User user) {
|
||||
return Role.CUSTOMER.equals(user.role);
|
||||
}
|
||||
public static boolean isCustomer(User user) {
|
||||
return Role.CUSTOMER.equals(user.role);
|
||||
}
|
||||
|
||||
public static boolean isNotCustomer(User user) {
|
||||
return !isCustomer(user);
|
||||
}
|
||||
public static boolean isNotCustomer(User user) {
|
||||
return !isCustomer(user);
|
||||
}
|
||||
|
||||
public static boolean isUser(User user) {
|
||||
return isProvider(user) || isCustomer(user);
|
||||
}
|
||||
public static boolean isUser(User user) {
|
||||
return isProvider(user) || isCustomer(user);
|
||||
}
|
||||
|
||||
public enum State {
|
||||
/**
|
||||
* 审查中
|
||||
*/
|
||||
CHECKING,
|
||||
/**
|
||||
* 正常
|
||||
*/
|
||||
NORMAL,
|
||||
/**
|
||||
* 禁用
|
||||
*/
|
||||
DISABLED,
|
||||
}
|
||||
public enum State {
|
||||
/**
|
||||
* 审查中
|
||||
*/
|
||||
CHECKING,
|
||||
/**
|
||||
* 正常
|
||||
*/
|
||||
NORMAL,
|
||||
/**
|
||||
* 禁用
|
||||
*/
|
||||
DISABLED,
|
||||
}
|
||||
|
||||
public enum Role {
|
||||
/**
|
||||
* 数据提供方
|
||||
*/
|
||||
PROVIDER,
|
||||
/**
|
||||
* 数据使用方
|
||||
*/
|
||||
CUSTOMER,
|
||||
/**
|
||||
* 数据监管方
|
||||
*/
|
||||
CHECKER,
|
||||
/**
|
||||
* 系统管理员
|
||||
*/
|
||||
ADMINISTRATOR,
|
||||
}
|
||||
public enum Role {
|
||||
/**
|
||||
* 数据提供方
|
||||
*/
|
||||
PROVIDER,
|
||||
/**
|
||||
* 数据使用方
|
||||
*/
|
||||
CUSTOMER,
|
||||
/**
|
||||
* 数据监管方
|
||||
*/
|
||||
CHECKER,
|
||||
/**
|
||||
* 系统管理员
|
||||
*/
|
||||
ADMINISTRATOR,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,33 +39,33 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
|
||||
@DynamicUpdate
|
||||
@Table(name = Constants.TABLE_PREFIX + "ware")
|
||||
@NamedEntityGraph(name = "ware.list", attributeNodes = {
|
||||
@NamedAttributeNode(value = "icon"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
@NamedAttributeNode(value = "icon"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
})
|
||||
@NamedEntityGraph(name = "ware.detail", attributeNodes = {
|
||||
@NamedAttributeNode(value = "icon"),
|
||||
@NamedAttributeNode(value = "content"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
@NamedAttributeNode(value = "modifiedUser"),
|
||||
@NamedAttributeNode(value = "icon"),
|
||||
@NamedAttributeNode(value = "content"),
|
||||
@NamedAttributeNode(value = "createdUser"),
|
||||
@NamedAttributeNode(value = "modifiedUser"),
|
||||
})
|
||||
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "ware" + " set deleted = true where id = ?")
|
||||
@Where(clause = LogicDeleteEntity.LOGIC_DELETE_CLAUSE)
|
||||
public class Ware extends CheckingNeededEntity {
|
||||
@OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.EAGER)
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
private DataResource resource;
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
@Column(nullable = false)
|
||||
private String description;
|
||||
@OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
private DataFile icon;
|
||||
@Lob
|
||||
@Basic(fetch = FetchType.LAZY)
|
||||
@ToString.Exclude
|
||||
@Column(nullable = false)
|
||||
private String content;
|
||||
@OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.EAGER)
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
private DataResource resource;
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
@Column(nullable = false)
|
||||
private String description;
|
||||
@OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.LAZY)
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
@ToString.Exclude
|
||||
private DataFile icon;
|
||||
@Lob
|
||||
@Basic(fetch = FetchType.LAZY)
|
||||
@ToString.Exclude
|
||||
@Column(nullable = false)
|
||||
private String content;
|
||||
}
|
||||
|
||||
@@ -28,10 +28,10 @@ import org.hibernate.annotations.Where;
|
||||
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_format" + " set deleted = true where id = ?")
|
||||
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
|
||||
public class CsvResourceFormat extends ResourceFormat {
|
||||
private String schema;
|
||||
private String schema;
|
||||
|
||||
@Override
|
||||
public Type getFormatType() {
|
||||
return Type.CSV;
|
||||
}
|
||||
@Override
|
||||
public Type getFormatType() {
|
||||
return Type.CSV;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,10 +28,10 @@ import org.hibernate.annotations.Where;
|
||||
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_format" + " set deleted = true where id = ?")
|
||||
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
|
||||
public class JsonLineResourceFormat extends ResourceFormat {
|
||||
private String schema;
|
||||
private String schema;
|
||||
|
||||
@Override
|
||||
public Type getFormatType() {
|
||||
return Type.JSON_LINE;
|
||||
}
|
||||
@Override
|
||||
public Type getFormatType() {
|
||||
return Type.JSON_LINE;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,10 +28,10 @@ import org.hibernate.annotations.Where;
|
||||
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_format" + " set deleted = true where id = ?")
|
||||
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
|
||||
public class JsonResourceFormat extends ResourceFormat {
|
||||
private String schema;
|
||||
private String schema;
|
||||
|
||||
@Override
|
||||
public Type getFormatType() {
|
||||
return Type.JSON;
|
||||
}
|
||||
@Override
|
||||
public Type getFormatType() {
|
||||
return Type.JSON;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,8 +24,8 @@ import org.hibernate.annotations.Where;
|
||||
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_format" + " set deleted = true where id = ?")
|
||||
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
|
||||
public class LineResourceFormat extends ResourceFormat {
|
||||
@Override
|
||||
public Type getFormatType() {
|
||||
return Type.LINE;
|
||||
}
|
||||
@Override
|
||||
public Type getFormatType() {
|
||||
return Type.LINE;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,8 +24,8 @@ import org.hibernate.annotations.Where;
|
||||
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_format" + " set deleted = true where id = ?")
|
||||
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
|
||||
public class NoneResourceFormat extends ResourceFormat {
|
||||
@Override
|
||||
public Type getFormatType() {
|
||||
return Type.NONE;
|
||||
}
|
||||
@Override
|
||||
public Type getFormatType() {
|
||||
return Type.NONE;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,13 +27,13 @@ import org.hibernate.annotations.Where;
|
||||
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_format" + " set deleted = true where id = ?")
|
||||
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
|
||||
public abstract class ResourceFormat extends LogicDeleteIdOnlyEntity {
|
||||
public abstract Type getFormatType();
|
||||
public abstract Type getFormatType();
|
||||
|
||||
public enum Type {
|
||||
NONE,
|
||||
LINE,
|
||||
JSON,
|
||||
JSON_LINE,
|
||||
CSV,
|
||||
}
|
||||
public enum Type {
|
||||
NONE,
|
||||
LINE,
|
||||
JSON,
|
||||
JSON_LINE,
|
||||
CSV,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,13 +23,13 @@ import org.hibernate.annotations.Where;
|
||||
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_type_api" + " set deleted = true where id = ?")
|
||||
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
|
||||
public class ApiResourceType extends ResourceType {
|
||||
@Column(nullable = false)
|
||||
private String url;
|
||||
private String username;
|
||||
private String password;
|
||||
@Column(nullable = false)
|
||||
private String url;
|
||||
private String username;
|
||||
private String password;
|
||||
|
||||
@Override
|
||||
public Type getResourceType() {
|
||||
return Type.API;
|
||||
}
|
||||
@Override
|
||||
public Type getResourceType() {
|
||||
return Type.API;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,22 +25,22 @@ import org.hibernate.annotations.Where;
|
||||
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_type_database" + " set deleted = true where id = ?")
|
||||
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
|
||||
public class DatabaseResourceType extends ResourceType {
|
||||
@Column(nullable = false)
|
||||
private String jdbc;
|
||||
private String username;
|
||||
private String password;
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private DatabaseType databaseType;
|
||||
@Column(nullable = false)
|
||||
private String jdbc;
|
||||
private String username;
|
||||
private String password;
|
||||
@Column(nullable = false)
|
||||
@Enumerated(EnumType.STRING)
|
||||
private DatabaseType databaseType;
|
||||
|
||||
@Override
|
||||
public Type getResourceType() {
|
||||
return Type.DATABASE;
|
||||
}
|
||||
@Override
|
||||
public Type getResourceType() {
|
||||
return Type.DATABASE;
|
||||
}
|
||||
|
||||
public enum DatabaseType {
|
||||
MYSQL,
|
||||
POSTGRESQL,
|
||||
ORACLE,
|
||||
}
|
||||
public enum DatabaseType {
|
||||
MYSQL,
|
||||
POSTGRESQL,
|
||||
ORACLE,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,12 +27,12 @@ import org.hibernate.annotations.Where;
|
||||
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_type_file" + " set deleted = true where id = ?")
|
||||
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
|
||||
public class FileResourceType extends ResourceType {
|
||||
@OneToOne
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
private DataFile file;
|
||||
@OneToOne
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
private DataFile file;
|
||||
|
||||
@Override
|
||||
public Type getResourceType() {
|
||||
return Type.FILE;
|
||||
}
|
||||
@Override
|
||||
public Type getResourceType() {
|
||||
return Type.FILE;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,15 +23,15 @@ import org.hibernate.annotations.Where;
|
||||
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_type_ftp" + " set deleted = true where id = ?")
|
||||
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
|
||||
public class FtpResourceType extends ResourceType {
|
||||
@Column(nullable = false)
|
||||
private String url;
|
||||
private String username;
|
||||
private String password;
|
||||
private String path;
|
||||
private String regexFilter;
|
||||
@Column(nullable = false)
|
||||
private String url;
|
||||
private String username;
|
||||
private String password;
|
||||
private String path;
|
||||
private String regexFilter;
|
||||
|
||||
@Override
|
||||
public Type getResourceType() {
|
||||
return Type.FTP;
|
||||
}
|
||||
@Override
|
||||
public Type getResourceType() {
|
||||
return Type.FTP;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,15 +27,15 @@ import org.hibernate.annotations.Where;
|
||||
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_type_hdfs" + " set deleted = true where id = ?")
|
||||
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
|
||||
public class HDFSResourceType extends ResourceType {
|
||||
@OneToOne
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
private DataFile coreSite;
|
||||
@OneToOne
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
private DataFile hdfsSite;
|
||||
@OneToOne
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
private DataFile coreSite;
|
||||
@OneToOne
|
||||
@JoinColumn(nullable = false, foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
|
||||
private DataFile hdfsSite;
|
||||
|
||||
@Override
|
||||
public Type getResourceType() {
|
||||
return Type.HDFS;
|
||||
}
|
||||
@Override
|
||||
public Type getResourceType() {
|
||||
return Type.HDFS;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,13 +27,13 @@ import org.hibernate.annotations.Where;
|
||||
@SQLDelete(sql = "update " + Constants.TABLE_PREFIX + "resource_type" + " set deleted = true where id = ?")
|
||||
@Where(clause = LogicDeleteIdOnlyEntity.LOGIC_DELETE_CLAUSE)
|
||||
public abstract class ResourceType extends LogicDeleteIdOnlyEntity {
|
||||
public abstract Type getResourceType();
|
||||
public abstract Type getResourceType();
|
||||
|
||||
public enum Type {
|
||||
API,
|
||||
DATABASE,
|
||||
FILE,
|
||||
FTP,
|
||||
HDFS,
|
||||
}
|
||||
public enum Type {
|
||||
API,
|
||||
DATABASE,
|
||||
FILE,
|
||||
FTP,
|
||||
HDFS,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,15 +16,15 @@ import org.springframework.stereotype.Repository;
|
||||
@SuppressWarnings("NullableProblems")
|
||||
@Repository
|
||||
public interface AuthenticationRepository extends SimpleRepository<Authentication, Long> {
|
||||
@Override
|
||||
@EntityGraph(value = "authentication.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<Authentication> findAll(Specification<Authentication> specification);
|
||||
@Override
|
||||
@EntityGraph(value = "authentication.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<Authentication> findAll(Specification<Authentication> specification);
|
||||
|
||||
@Override
|
||||
@EntityGraph(value = "authentication.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<Authentication> findAll(Specification<Authentication> specification, Sort sort);
|
||||
@Override
|
||||
@EntityGraph(value = "authentication.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<Authentication> findAll(Specification<Authentication> specification, Sort sort);
|
||||
|
||||
@Override
|
||||
@EntityGraph(value = "authentication.detail", type = EntityGraph.EntityGraphType.FETCH)
|
||||
Optional<Authentication> findOne(Specification<Authentication> specification);
|
||||
@Override
|
||||
@EntityGraph(value = "authentication.detail", type = EntityGraph.EntityGraphType.FETCH)
|
||||
Optional<Authentication> findOne(Specification<Authentication> specification);
|
||||
}
|
||||
|
||||
@@ -20,20 +20,20 @@ import org.springframework.stereotype.Repository;
|
||||
@SuppressWarnings("NullableProblems")
|
||||
@Repository
|
||||
public interface CheckOrderRepository extends SimpleRepository<CheckOrder, Long> {
|
||||
@Override
|
||||
@EntityGraph(value = "check_order.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<CheckOrder> findAll(Specification<CheckOrder> specification);
|
||||
@Override
|
||||
@EntityGraph(value = "check_order.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<CheckOrder> findAll(Specification<CheckOrder> specification);
|
||||
|
||||
@Override
|
||||
@EntityGraph(value = "check_order.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<CheckOrder> findAll(Specification<CheckOrder> specification, Sort sort);
|
||||
@Override
|
||||
@EntityGraph(value = "check_order.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<CheckOrder> findAll(Specification<CheckOrder> specification, Sort sort);
|
||||
|
||||
@Override
|
||||
@EntityGraph(value = "check_order.detail", type = EntityGraph.EntityGraphType.FETCH)
|
||||
Optional<CheckOrder> findOne(Specification<CheckOrder> specification);
|
||||
@Override
|
||||
@EntityGraph(value = "check_order.detail", type = EntityGraph.EntityGraphType.FETCH)
|
||||
Optional<CheckOrder> findOne(Specification<CheckOrder> specification);
|
||||
|
||||
@Transactional
|
||||
@Modifying
|
||||
@Query("update CheckOrder check set check.state = ?2, check.modifiedUser = ?3, check.modifiedTime = current_timestamp where check.id = ?1")
|
||||
void overById(Long id, CheckOrder.State state, User modifiedUser);
|
||||
@Transactional
|
||||
@Modifying
|
||||
@Query("update CheckOrder check set check.state = ?2, check.modifiedUser = ?3, check.modifiedTime = current_timestamp where check.id = ?1")
|
||||
void overById(Long id, CheckOrder.State state, User modifiedUser);
|
||||
}
|
||||
|
||||
@@ -16,17 +16,17 @@ import org.springframework.stereotype.Repository;
|
||||
@SuppressWarnings("NullableProblems")
|
||||
@Repository
|
||||
public interface ConfirmationRepository extends SimpleRepository<Confirmation, Long> {
|
||||
@Override
|
||||
@EntityGraph(value = "confirmation.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<Confirmation> findAll(Specification<Confirmation> specification);
|
||||
@Override
|
||||
@EntityGraph(value = "confirmation.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<Confirmation> findAll(Specification<Confirmation> specification);
|
||||
|
||||
@Override
|
||||
@EntityGraph(value = "confirmation.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<Confirmation> findAll(Specification<Confirmation> specification, Sort sort);
|
||||
@Override
|
||||
@EntityGraph(value = "confirmation.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<Confirmation> findAll(Specification<Confirmation> specification, Sort sort);
|
||||
|
||||
@Override
|
||||
@EntityGraph(value = "confirmation.detail", type = EntityGraph.EntityGraphType.FETCH)
|
||||
Optional<Confirmation> findOne(Specification<Confirmation> specification);
|
||||
@Override
|
||||
@EntityGraph(value = "confirmation.detail", type = EntityGraph.EntityGraphType.FETCH)
|
||||
Optional<Confirmation> findOne(Specification<Confirmation> specification);
|
||||
|
||||
Boolean existsByTarget_Id(Long id);
|
||||
Boolean existsByTarget_Id(Long id);
|
||||
}
|
||||
|
||||
@@ -12,18 +12,18 @@ import org.springframework.stereotype.Repository;
|
||||
@SuppressWarnings("NullableProblems")
|
||||
@Repository
|
||||
public interface DataResourceRepository extends SimpleRepository<DataResource, Long> {
|
||||
@Override
|
||||
@EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<DataResource> findAll(Specification<DataResource> specification);
|
||||
@Override
|
||||
@EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<DataResource> findAll(Specification<DataResource> specification);
|
||||
|
||||
@Override
|
||||
@EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<DataResource> findAll(Specification<DataResource> specification, Sort sort);
|
||||
@Override
|
||||
@EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<DataResource> findAll(Specification<DataResource> specification, Sort sort);
|
||||
|
||||
@EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<DataResource> findAllByConfirmationIsNull();
|
||||
@EntityGraph(value = "data_resource.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<DataResource> findAllByConfirmationIsNull();
|
||||
|
||||
@Override
|
||||
@EntityGraph(value = "data_resource.detail", type = EntityGraph.EntityGraphType.FETCH)
|
||||
Optional<DataResource> findOne(Specification<DataResource> specification);
|
||||
@Override
|
||||
@EntityGraph(value = "data_resource.detail", type = EntityGraph.EntityGraphType.FETCH)
|
||||
Optional<DataResource> findOne(Specification<DataResource> specification);
|
||||
}
|
||||
|
||||
@@ -16,12 +16,12 @@ import org.springframework.stereotype.Repository;
|
||||
@SuppressWarnings("NullableProblems")
|
||||
@Repository
|
||||
public interface UserRepository extends SimpleRepository<User, Long> {
|
||||
@Override
|
||||
@EntityGraph(value = "user.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<User> findAll();
|
||||
@Override
|
||||
@EntityGraph(value = "user.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<User> findAll();
|
||||
|
||||
Boolean existsByUsername(String username);
|
||||
Boolean existsByUsername(String username);
|
||||
|
||||
@EntityGraph(value = "user.detail", type = EntityGraph.EntityGraphType.FETCH)
|
||||
Optional<User> findByUsername(String username);
|
||||
@EntityGraph(value = "user.detail", type = EntityGraph.EntityGraphType.FETCH)
|
||||
Optional<User> findByUsername(String username);
|
||||
}
|
||||
|
||||
@@ -12,15 +12,15 @@ import org.springframework.stereotype.Repository;
|
||||
@SuppressWarnings("NullableProblems")
|
||||
@Repository
|
||||
public interface WareRepository extends SimpleRepository<Ware, Long> {
|
||||
@Override
|
||||
@EntityGraph(value = "ware.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<Ware> findAll(Specification<Ware> specification);
|
||||
@Override
|
||||
@EntityGraph(value = "ware.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<Ware> findAll(Specification<Ware> specification);
|
||||
|
||||
@Override
|
||||
@EntityGraph(value = "ware.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<Ware> findAll(Specification<Ware> specification, Sort sort);
|
||||
@Override
|
||||
@EntityGraph(value = "ware.list", type = EntityGraph.EntityGraphType.FETCH)
|
||||
List<Ware> findAll(Specification<Ware> specification, Sort sort);
|
||||
|
||||
@Override
|
||||
@EntityGraph(value = "ware.detail", type = EntityGraph.EntityGraphType.FETCH)
|
||||
Optional<Ware> findOne(Specification<Ware> specification);
|
||||
@Override
|
||||
@EntityGraph(value = "ware.detail", type = EntityGraph.EntityGraphType.FETCH)
|
||||
Optional<Ware> findOne(Specification<Ware> specification);
|
||||
}
|
||||
@@ -34,120 +34,120 @@ import org.springframework.stereotype.Service;
|
||||
@Slf4j
|
||||
@Service("com.eshore.gringotts.web.domain.service.AuthenticationService")
|
||||
public class AuthenticationService extends LogicDeleteService<Authentication> implements CheckingService {
|
||||
private final AuthenticationRepository authenticationRepository;
|
||||
private final UserService userService;
|
||||
private final CheckOrderService checkOrderService;
|
||||
private final ObjectMapper mapper;
|
||||
private final AuthenticationRepository authenticationRepository;
|
||||
private final UserService userService;
|
||||
private final CheckOrderService checkOrderService;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
public AuthenticationService(AuthenticationRepository repository, UserService userService, EntityManager manager, CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) {
|
||||
super(repository, userService, manager);
|
||||
this.authenticationRepository = repository;
|
||||
this.userService = userService;
|
||||
this.checkOrderService = checkOrderService;
|
||||
this.mapper = builder.build();
|
||||
public AuthenticationService(AuthenticationRepository repository, UserService userService, EntityManager manager, CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) {
|
||||
super(repository, userService, manager);
|
||||
this.authenticationRepository = repository;
|
||||
this.userService = userService;
|
||||
this.checkOrderService = checkOrderService;
|
||||
this.mapper = builder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ImmutableList<Predicate> listPredicate(Root<Authentication> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
User loginUser = userService.currentLoginUser();
|
||||
if (User.isAdministrator(loginUser)) {
|
||||
return Lists.immutable.empty();
|
||||
}
|
||||
return Lists.immutable.of(builder.or(
|
||||
builder.equal(root.get(Authentication_.createdUser), loginUser),
|
||||
builder.and(
|
||||
builder.equal(root.get(Authentication_.order).get(CheckOrder_.target), CheckOrder.Target.ROLE),
|
||||
builder.equal(root.get(Authentication_.order).get(CheckOrder_.targetRole), loginUser.getRole())
|
||||
),
|
||||
builder.and(
|
||||
builder.equal(root.get(Authentication_.order).get(CheckOrder_.target), CheckOrder.Target.USER),
|
||||
builder.equal(root.get(Authentication_.order).get(CheckOrder_.targetUser), loginUser)
|
||||
)
|
||||
));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ImmutableList<Predicate> listPredicate(Root<Authentication> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
User loginUser = userService.currentLoginUser();
|
||||
if (User.isAdministrator(loginUser)) {
|
||||
return Lists.immutable.empty();
|
||||
@Override
|
||||
public Long save(Authentication entity) {
|
||||
if (ObjectUtil.isNull(entity.getId()) && authenticationRepository.findOne(
|
||||
(root, query, criteriaBuilder) -> {
|
||||
// TODO 同一个资源的授权时间是否重合
|
||||
// 查询是否存在createdUser为当前登陆用户并且绑定的数据资源是同一个的授权申请
|
||||
return criteriaBuilder.and(
|
||||
criteriaBuilder.equal(root.get("createdUser"), userService.currentLoginUser()),
|
||||
criteriaBuilder.equal(root.get("target"), entity.getTarget())
|
||||
);
|
||||
}
|
||||
return Lists.immutable.of(builder.or(
|
||||
builder.equal(root.get(Authentication_.createdUser), loginUser),
|
||||
builder.and(
|
||||
builder.equal(root.get(Authentication_.order).get(CheckOrder_.target), CheckOrder.Target.ROLE),
|
||||
builder.equal(root.get(Authentication_.order).get(CheckOrder_.targetRole), loginUser.getRole())
|
||||
),
|
||||
builder.and(
|
||||
builder.equal(root.get(Authentication_.order).get(CheckOrder_.target), CheckOrder.Target.USER),
|
||||
builder.equal(root.get(Authentication_.order).get(CheckOrder_.targetUser), loginUser)
|
||||
)
|
||||
));
|
||||
).isPresent()) {
|
||||
throw new AuthenticationDuplicatedException();
|
||||
}
|
||||
return super.save(entity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long save(Authentication entity) {
|
||||
if (ObjectUtil.isNull(entity.getId()) && authenticationRepository.findOne(
|
||||
(root, query, criteriaBuilder) -> {
|
||||
// TODO 同一个资源的授权时间是否重合
|
||||
// 查询是否存在createdUser为当前登陆用户并且绑定的数据资源是同一个的授权申请
|
||||
return criteriaBuilder.and(
|
||||
criteriaBuilder.equal(root.get("createdUser"), userService.currentLoginUser()),
|
||||
criteriaBuilder.equal(root.get("target"), entity.getTarget())
|
||||
);
|
||||
}
|
||||
).isPresent()) {
|
||||
throw new AuthenticationDuplicatedException();
|
||||
}
|
||||
return super.save(entity);
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
public void submit(Long id) throws JsonProcessingException {
|
||||
Authentication authentication = detailOrThrow(id);
|
||||
authentication.setState(CheckingNeededEntity.State.OWNER_CHECKING);
|
||||
Long orderId = checkOrderService.save(new CheckOrder(
|
||||
"authentication_owner_check",
|
||||
StrUtil.format("数据资源「{}」的授权申请", authentication.getTarget().getName()),
|
||||
CheckOrder.Type.AUTHENTICATION,
|
||||
mapper.writeValueAsString(Maps.immutable.of("authenticationId", authentication.getId())),
|
||||
"com.eshore.gringotts.web.domain.service.AuthenticationService",
|
||||
authentication.getCreatedUser()
|
||||
));
|
||||
CheckOrder order = checkOrderService.detailOrThrow(orderId);
|
||||
authentication.setOrder(order);
|
||||
save(authentication);
|
||||
}
|
||||
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
public void retract(Long id) {
|
||||
Authentication authentication = detailOrThrow(id);
|
||||
authentication.setState(Authentication.State.DRAFT);
|
||||
save(authentication);
|
||||
|
||||
CheckOrder order = authentication.getOrder();
|
||||
order.setState(CheckOrder.State.RETRACT);
|
||||
checkOrderService.save(order);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
public void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap<String, Object> parameters) {
|
||||
Long id = (Long) parameters.get("authenticationId");
|
||||
Authentication authentication = detailOrThrow(id);
|
||||
if (StrUtil.equals(order.getKeyword(), "authentication_owner_check")) {
|
||||
switch (operation) {
|
||||
case APPLY:
|
||||
authentication.setState(Authentication.State.CHECKING);
|
||||
order.setKeyword("authentication_checker_check");
|
||||
order.setTarget(CheckOrder.Target.ROLE);
|
||||
order.setTargetRole(User.Role.CHECKER);
|
||||
break;
|
||||
case REJECT:
|
||||
authentication.setState(Authentication.State.DRAFT);
|
||||
order.setState(CheckOrder.State.OVER);
|
||||
break;
|
||||
}
|
||||
} else if (StrUtil.equals(order.getKeyword(), "authentication_checker_check")) {
|
||||
switch (operation) {
|
||||
case APPLY:
|
||||
authentication.setState(Authentication.State.NORMAL);
|
||||
order.setState(CheckOrder.State.OVER);
|
||||
break;
|
||||
case REJECT:
|
||||
authentication.setState(Authentication.State.DRAFT);
|
||||
order.setState(CheckOrder.State.OVER);
|
||||
break;
|
||||
}
|
||||
}
|
||||
save(authentication);
|
||||
checkOrderService.save(order);
|
||||
}
|
||||
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
public void submit(Long id) throws JsonProcessingException {
|
||||
Authentication authentication = detailOrThrow(id);
|
||||
authentication.setState(CheckingNeededEntity.State.OWNER_CHECKING);
|
||||
Long orderId = checkOrderService.save(new CheckOrder(
|
||||
"authentication_owner_check",
|
||||
StrUtil.format("数据资源「{}」的授权申请", authentication.getTarget().getName()),
|
||||
CheckOrder.Type.AUTHENTICATION,
|
||||
mapper.writeValueAsString(Maps.immutable.of("authenticationId", authentication.getId())),
|
||||
"com.eshore.gringotts.web.domain.service.AuthenticationService",
|
||||
authentication.getCreatedUser()
|
||||
));
|
||||
CheckOrder order = checkOrderService.detailOrThrow(orderId);
|
||||
authentication.setOrder(order);
|
||||
save(authentication);
|
||||
}
|
||||
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
public void retract(Long id) {
|
||||
Authentication authentication = detailOrThrow(id);
|
||||
authentication.setState(Authentication.State.DRAFT);
|
||||
save(authentication);
|
||||
|
||||
CheckOrder order = authentication.getOrder();
|
||||
order.setState(CheckOrder.State.RETRACT);
|
||||
checkOrderService.save(order);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
public void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap<String, Object> parameters) {
|
||||
Long id = (Long) parameters.get("authenticationId");
|
||||
Authentication authentication = detailOrThrow(id);
|
||||
if (StrUtil.equals(order.getKeyword(), "authentication_owner_check")) {
|
||||
switch (operation) {
|
||||
case APPLY:
|
||||
authentication.setState(Authentication.State.CHECKING);
|
||||
order.setKeyword("authentication_checker_check");
|
||||
order.setTarget(CheckOrder.Target.ROLE);
|
||||
order.setTargetRole(User.Role.CHECKER);
|
||||
break;
|
||||
case REJECT:
|
||||
authentication.setState(Authentication.State.DRAFT);
|
||||
order.setState(CheckOrder.State.OVER);
|
||||
break;
|
||||
}
|
||||
} else if (StrUtil.equals(order.getKeyword(), "authentication_checker_check")) {
|
||||
switch (operation) {
|
||||
case APPLY:
|
||||
authentication.setState(Authentication.State.NORMAL);
|
||||
order.setState(CheckOrder.State.OVER);
|
||||
break;
|
||||
case REJECT:
|
||||
authentication.setState(Authentication.State.DRAFT);
|
||||
order.setState(CheckOrder.State.OVER);
|
||||
break;
|
||||
}
|
||||
}
|
||||
save(authentication);
|
||||
checkOrderService.save(order);
|
||||
}
|
||||
|
||||
public static final class AuthenticationDuplicatedException extends RuntimeException {
|
||||
public AuthenticationDuplicatedException() {
|
||||
super("数据资源已绑定该账号的授权申请,无法再次申请");
|
||||
}
|
||||
public static final class AuthenticationDuplicatedException extends RuntimeException {
|
||||
public AuthenticationDuplicatedException() {
|
||||
super("数据资源已绑定该账号的授权申请,无法再次申请");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,53 +30,53 @@ import org.springframework.stereotype.Service;
|
||||
@Slf4j
|
||||
@Service
|
||||
public class CheckOrderService extends SimpleServiceSupport<CheckOrder> {
|
||||
private final ApplicationContext applicationContext;
|
||||
private final ObjectMapper mapper;
|
||||
private final CheckOrderRepository checkOrderRepository;
|
||||
private final UserService userService;
|
||||
private final ApplicationContext applicationContext;
|
||||
private final ObjectMapper mapper;
|
||||
private final CheckOrderRepository checkOrderRepository;
|
||||
private final UserService userService;
|
||||
|
||||
public CheckOrderService(CheckOrderRepository repository, UserService userService, ApplicationContext applicationContext, Jackson2ObjectMapperBuilder builder) {
|
||||
super(repository, userService);
|
||||
this.applicationContext = applicationContext;
|
||||
this.mapper = builder.build();
|
||||
this.checkOrderRepository = repository;
|
||||
this.userService = userService;
|
||||
}
|
||||
public CheckOrderService(CheckOrderRepository repository, UserService userService, ApplicationContext applicationContext, Jackson2ObjectMapperBuilder builder) {
|
||||
super(repository, userService);
|
||||
this.applicationContext = applicationContext;
|
||||
this.mapper = builder.build();
|
||||
this.checkOrderRepository = repository;
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ImmutableList<Predicate> listPredicate(Root<CheckOrder> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
User user = userService.currentLoginUser();
|
||||
if (User.isAdministrator(user)) {
|
||||
return Lists.immutable.empty();
|
||||
}
|
||||
return Lists.immutable.of(builder.or(
|
||||
builder.equal(root.get(CheckOrder_.createdUser), user),
|
||||
builder.and(
|
||||
builder.equal(root.get(CheckOrder_.target), CheckOrder.Target.USER),
|
||||
builder.equal(root.get(CheckOrder_.targetUser), user)
|
||||
),
|
||||
builder.and(
|
||||
builder.equal(root.get(CheckOrder_.target), CheckOrder.Target.ROLE),
|
||||
builder.equal(root.get(CheckOrder_.targetRole), user.getRole())
|
||||
)
|
||||
));
|
||||
@Override
|
||||
protected ImmutableList<Predicate> listPredicate(Root<CheckOrder> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
User user = userService.currentLoginUser();
|
||||
if (User.isAdministrator(user)) {
|
||||
return Lists.immutable.empty();
|
||||
}
|
||||
return Lists.immutable.of(builder.or(
|
||||
builder.equal(root.get(CheckOrder_.createdUser), user),
|
||||
builder.and(
|
||||
builder.equal(root.get(CheckOrder_.target), CheckOrder.Target.USER),
|
||||
builder.equal(root.get(CheckOrder_.targetUser), user)
|
||||
),
|
||||
builder.and(
|
||||
builder.equal(root.get(CheckOrder_.target), CheckOrder.Target.ROLE),
|
||||
builder.equal(root.get(CheckOrder_.targetRole), user.getRole())
|
||||
)
|
||||
));
|
||||
}
|
||||
|
||||
public void operation(Long id, CheckOrder.Operation operation) throws JsonProcessingException {
|
||||
CheckOrder order = detailOrThrow(id);
|
||||
CheckingService service = applicationContext.getBean(order.getTargetClass(), CheckingService.class);
|
||||
if (ObjectUtil.isNull(service)) {
|
||||
throw new RuntimeException(StrUtil.format("名为「{}」的服务未找到", order.getTargetClass()));
|
||||
}
|
||||
ImmutableMap<String, Object> parameters = mapper.readValue(order.getParameters(), new TypeReference<>() {});
|
||||
service.onChecked(order, operation, parameters);
|
||||
public void operation(Long id, CheckOrder.Operation operation) throws JsonProcessingException {
|
||||
CheckOrder order = detailOrThrow(id);
|
||||
CheckingService service = applicationContext.getBean(order.getTargetClass(), CheckingService.class);
|
||||
if (ObjectUtil.isNull(service)) {
|
||||
throw new RuntimeException(StrUtil.format("名为「{}」的服务未找到", order.getTargetClass()));
|
||||
}
|
||||
ImmutableMap<String, Object> parameters = mapper.readValue(order.getParameters(), new TypeReference<>() {});
|
||||
service.onChecked(order, operation, parameters);
|
||||
}
|
||||
|
||||
public void retract(Long id) {
|
||||
checkOrderRepository.overById(id, CheckOrder.State.RETRACT, userService.currentLoginUser());
|
||||
}
|
||||
public void retract(Long id) {
|
||||
checkOrderRepository.overById(id, CheckOrder.State.RETRACT, userService.currentLoginUser());
|
||||
}
|
||||
|
||||
public void over(Long id) {
|
||||
checkOrderRepository.overById(id, CheckOrder.State.OVER, userService.currentLoginUser());
|
||||
}
|
||||
public void over(Long id) {
|
||||
checkOrderRepository.overById(id, CheckOrder.State.OVER, userService.currentLoginUser());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,102 +35,102 @@ import org.springframework.stereotype.Service;
|
||||
@Slf4j
|
||||
@Service("com.eshore.gringotts.web.domain.service.ConfirmationService")
|
||||
public class ConfirmationService extends SimpleServiceSupport<Confirmation> implements CheckingService {
|
||||
private final ConfirmationRepository confirmationRepository;
|
||||
private final CheckOrderService checkOrderService;
|
||||
private final ObjectMapper mapper;
|
||||
private final ConfirmationRepository confirmationRepository;
|
||||
private final CheckOrderService checkOrderService;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
public ConfirmationService(ConfirmationRepository confirmationRepository, UserService userService, CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) {
|
||||
super(confirmationRepository, userService);
|
||||
this.confirmationRepository = confirmationRepository;
|
||||
this.checkOrderService = checkOrderService;
|
||||
this.mapper = builder.build();
|
||||
public ConfirmationService(ConfirmationRepository confirmationRepository, UserService userService, CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) {
|
||||
super(confirmationRepository, userService);
|
||||
this.confirmationRepository = confirmationRepository;
|
||||
this.checkOrderService = checkOrderService;
|
||||
this.mapper = builder.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ImmutableList<Predicate> listPredicate(Root<Confirmation> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
User loginUser = userService.currentLoginUser();
|
||||
if (User.isAdministrator(loginUser)) {
|
||||
return Lists.immutable.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ImmutableList<Predicate> listPredicate(Root<Confirmation> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
User loginUser = userService.currentLoginUser();
|
||||
if (User.isAdministrator(loginUser)) {
|
||||
return Lists.immutable.empty();
|
||||
}
|
||||
Join<Confirmation, CheckOrder> orderJoin = root.join(Confirmation_.order, JoinType.LEFT);
|
||||
return Lists.immutable.of(builder.or(
|
||||
builder.equal(root.get(Confirmation_.createdUser), loginUser),
|
||||
Join<Confirmation, CheckOrder> orderJoin = root.join(Confirmation_.order, JoinType.LEFT);
|
||||
return Lists.immutable.of(builder.or(
|
||||
builder.equal(root.get(Confirmation_.createdUser), loginUser),
|
||||
builder.and(
|
||||
builder.isNotNull(orderJoin),
|
||||
builder.or(
|
||||
builder.and(
|
||||
builder.isNotNull(orderJoin),
|
||||
builder.or(
|
||||
builder.and(
|
||||
builder.equal(orderJoin.get(CheckOrder_.target), CheckOrder.Target.ROLE),
|
||||
builder.equal(orderJoin.get(CheckOrder_.targetRole), loginUser.getRole())
|
||||
),
|
||||
builder.and(
|
||||
builder.equal(orderJoin.get(CheckOrder_.target), CheckOrder.Target.USER),
|
||||
builder.equal(orderJoin.get(CheckOrder_.targetUser), loginUser)
|
||||
)
|
||||
)
|
||||
builder.equal(orderJoin.get(CheckOrder_.target), CheckOrder.Target.ROLE),
|
||||
builder.equal(orderJoin.get(CheckOrder_.targetRole), loginUser.getRole())
|
||||
),
|
||||
builder.and(
|
||||
builder.equal(orderJoin.get(CheckOrder_.target), CheckOrder.Target.USER),
|
||||
builder.equal(orderJoin.get(CheckOrder_.targetUser), loginUser)
|
||||
)
|
||||
));
|
||||
}
|
||||
)
|
||||
)
|
||||
));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long save(Confirmation entity) {
|
||||
if (ObjectUtil.isNull(entity.getId()) && confirmationRepository.existsByTarget_Id(entity.getTarget().getId())) {
|
||||
throw new ConfirmationDuplicatedException();
|
||||
}
|
||||
return super.save(entity);
|
||||
@Override
|
||||
public Long save(Confirmation entity) {
|
||||
if (ObjectUtil.isNull(entity.getId()) && confirmationRepository.existsByTarget_Id(entity.getTarget().getId())) {
|
||||
throw new ConfirmationDuplicatedException();
|
||||
}
|
||||
return super.save(entity);
|
||||
}
|
||||
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
public void submit(Long id) throws JsonProcessingException {
|
||||
Confirmation confirmation = detailOrThrow(id);
|
||||
confirmation.setState(Confirmation.State.CHECKING);
|
||||
Long orderId = checkOrderService.save(new CheckOrder(
|
||||
"confirmation_check",
|
||||
StrUtil.format("数据资源「{}」的确权申请", confirmation.getTarget().getName()),
|
||||
CheckOrder.Type.CONFIRMATION,
|
||||
mapper.writeValueAsString(Maps.immutable.of("confirmationId", confirmation.getId())),
|
||||
"com.eshore.gringotts.web.domain.service.ConfirmationService",
|
||||
User.Role.CHECKER
|
||||
));
|
||||
CheckOrder order = checkOrderService.detailOrThrow(orderId);
|
||||
confirmation.setOrder(order);
|
||||
save(confirmation);
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
public void submit(Long id) throws JsonProcessingException {
|
||||
Confirmation confirmation = detailOrThrow(id);
|
||||
confirmation.setState(Confirmation.State.CHECKING);
|
||||
Long orderId = checkOrderService.save(new CheckOrder(
|
||||
"confirmation_check",
|
||||
StrUtil.format("数据资源「{}」的确权申请", confirmation.getTarget().getName()),
|
||||
CheckOrder.Type.CONFIRMATION,
|
||||
mapper.writeValueAsString(Maps.immutable.of("confirmationId", confirmation.getId())),
|
||||
"com.eshore.gringotts.web.domain.service.ConfirmationService",
|
||||
User.Role.CHECKER
|
||||
));
|
||||
CheckOrder order = checkOrderService.detailOrThrow(orderId);
|
||||
confirmation.setOrder(order);
|
||||
save(confirmation);
|
||||
}
|
||||
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
public void retract(Long id) {
|
||||
Confirmation confirmation = detailOrThrow(id);
|
||||
confirmation.setState(CheckingNeededEntity.State.DRAFT);
|
||||
save(confirmation);
|
||||
|
||||
CheckOrder order = confirmation.getOrder();
|
||||
order.setState(CheckOrder.State.RETRACT);
|
||||
checkOrderService.save(order);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
public void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap<String, Object> parameters) {
|
||||
if (StrUtil.equals(order.getKeyword(), "confirmation_check")) {
|
||||
Long id = (Long) parameters.get("confirmationId");
|
||||
Confirmation confirmation = detailOrThrow(id);
|
||||
switch (operation) {
|
||||
case APPLY:
|
||||
confirmation.setState(Confirmation.State.NORMAL);
|
||||
order.setState(CheckOrder.State.OVER);
|
||||
break;
|
||||
case REJECT:
|
||||
confirmation.setState(Confirmation.State.DRAFT);
|
||||
order.setState(CheckOrder.State.OVER);
|
||||
break;
|
||||
}
|
||||
save(confirmation);
|
||||
checkOrderService.save(order);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
public void retract(Long id) {
|
||||
Confirmation confirmation = detailOrThrow(id);
|
||||
confirmation.setState(CheckingNeededEntity.State.DRAFT);
|
||||
save(confirmation);
|
||||
|
||||
CheckOrder order = confirmation.getOrder();
|
||||
order.setState(CheckOrder.State.RETRACT);
|
||||
checkOrderService.save(order);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
public void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap<String, Object> parameters) {
|
||||
if (StrUtil.equals(order.getKeyword(), "confirmation_check")) {
|
||||
Long id = (Long) parameters.get("confirmationId");
|
||||
Confirmation confirmation = detailOrThrow(id);
|
||||
switch (operation) {
|
||||
case APPLY:
|
||||
confirmation.setState(Confirmation.State.NORMAL);
|
||||
order.setState(CheckOrder.State.OVER);
|
||||
break;
|
||||
case REJECT:
|
||||
confirmation.setState(Confirmation.State.DRAFT);
|
||||
order.setState(CheckOrder.State.OVER);
|
||||
break;
|
||||
}
|
||||
save(confirmation);
|
||||
checkOrderService.save(order);
|
||||
}
|
||||
}
|
||||
|
||||
public static final class ConfirmationDuplicatedException extends RuntimeException {
|
||||
public ConfirmationDuplicatedException() {
|
||||
super("数据资源已绑定确权申请,无法再次申请");
|
||||
}
|
||||
public static final class ConfirmationDuplicatedException extends RuntimeException {
|
||||
public ConfirmationDuplicatedException() {
|
||||
super("数据资源已绑定确权申请,无法再次申请");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,75 +29,75 @@ import org.springframework.stereotype.Service;
|
||||
@Slf4j
|
||||
@Service
|
||||
public class DataFileService extends SimpleServiceSupport<DataFile> {
|
||||
private final DataFileRepository dataFileRepository;
|
||||
private final UserService userService;
|
||||
private final DataFileRepository dataFileRepository;
|
||||
private final UserService userService;
|
||||
|
||||
public DataFileService(DataFileRepository dataFileRepository, UserService userService) {
|
||||
super(dataFileRepository, userService);
|
||||
this.dataFileRepository = dataFileRepository;
|
||||
this.userService = userService;
|
||||
public DataFileService(DataFileRepository dataFileRepository, UserService userService) {
|
||||
super(dataFileRepository, userService);
|
||||
this.dataFileRepository = dataFileRepository;
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ImmutableList<Predicate> listPredicate(Root<DataFile> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
User loginUser = userService.currentLoginUser();
|
||||
if (User.isAdministrator(loginUser)) {
|
||||
return Lists.immutable.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ImmutableList<Predicate> listPredicate(Root<DataFile> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
User loginUser = userService.currentLoginUser();
|
||||
if (User.isAdministrator(loginUser)) {
|
||||
return Lists.immutable.empty();
|
||||
}
|
||||
Subquery<Confirmation> confirmationSubquery = query.subquery(Confirmation.class);
|
||||
Root<Confirmation> confirmationRoot = confirmationSubquery.from(Confirmation.class);
|
||||
confirmationSubquery.select(confirmationRoot)
|
||||
.where(
|
||||
builder.isMember(root, confirmationRoot.get(Confirmation_.evidences)),
|
||||
EntityHelper.checkNeededEntityPrediction(confirmationRoot, builder, loginUser)
|
||||
);
|
||||
|
||||
Subquery<Confirmation> confirmationSubquery = query.subquery(Confirmation.class);
|
||||
Root<Confirmation> confirmationRoot = confirmationSubquery.from(Confirmation.class);
|
||||
confirmationSubquery.select(confirmationRoot)
|
||||
.where(
|
||||
builder.isMember(root, confirmationRoot.get(Confirmation_.evidences)),
|
||||
EntityHelper.checkNeededEntityPrediction(confirmationRoot, builder, loginUser)
|
||||
);
|
||||
Subquery<Authentication> authenticationSubquery = query.subquery(Authentication.class);
|
||||
Root<Authentication> authenticationRoot = authenticationSubquery.from(Authentication.class);
|
||||
authenticationSubquery.select(authenticationRoot)
|
||||
.where(
|
||||
builder.isMember(root, authenticationRoot.get(Authentication_.evidences)),
|
||||
EntityHelper.checkNeededEntityPrediction(authenticationRoot, builder, loginUser)
|
||||
);
|
||||
|
||||
Subquery<Authentication> authenticationSubquery = query.subquery(Authentication.class);
|
||||
Root<Authentication> authenticationRoot = authenticationSubquery.from(Authentication.class);
|
||||
authenticationSubquery.select(authenticationRoot)
|
||||
.where(
|
||||
builder.isMember(root, authenticationRoot.get(Authentication_.evidences)),
|
||||
EntityHelper.checkNeededEntityPrediction(authenticationRoot, builder, loginUser)
|
||||
);
|
||||
return Lists.immutable.of(builder.or(
|
||||
builder.equal(root.get(DataFile_.createdUser), loginUser),
|
||||
builder.exists(confirmationSubquery),
|
||||
builder.exists(authenticationSubquery)
|
||||
));
|
||||
}
|
||||
|
||||
return Lists.immutable.of(builder.or(
|
||||
builder.equal(root.get(DataFile_.createdUser), loginUser),
|
||||
builder.exists(confirmationSubquery),
|
||||
builder.exists(authenticationSubquery)
|
||||
));
|
||||
public DataFile downloadFile(Long id) {
|
||||
return dataFileRepository.findOne((root, query, builder) -> builder.equal(root.get(DataFile_.id), id)).orElseThrow(DataFileNotFoundException::new);
|
||||
}
|
||||
|
||||
public Long initialDataFile(String filename) {
|
||||
DataFile dataFile = new DataFile();
|
||||
dataFile.setFilename(filename);
|
||||
return dataFileRepository.save(dataFile).getId();
|
||||
}
|
||||
|
||||
public void updateDataFile(Long id, String path, Long size, String md5, String type) {
|
||||
DataFile dataFile = dataFileRepository.findById(id).orElseThrow(UpdateDataFileFailedException::new);
|
||||
dataFile.setSize(size);
|
||||
dataFile.setMd5(md5);
|
||||
dataFile.setPath(path);
|
||||
dataFile.setType(type);
|
||||
User loginUser = userService.currentLoginUser();
|
||||
dataFile.setModifiedUser(loginUser);
|
||||
dataFileRepository.save(dataFile);
|
||||
}
|
||||
|
||||
public static final class DataFileNotFoundException extends RuntimeException {
|
||||
public DataFileNotFoundException() {
|
||||
super("文件未找到,请重新上传");
|
||||
}
|
||||
}
|
||||
|
||||
public DataFile downloadFile(Long id) {
|
||||
return dataFileRepository.findOne((root, query, builder) -> builder.equal(root.get(DataFile_.id), id)).orElseThrow(DataFileNotFoundException::new);
|
||||
}
|
||||
|
||||
public Long initialDataFile(String filename) {
|
||||
DataFile dataFile = new DataFile();
|
||||
dataFile.setFilename(filename);
|
||||
return dataFileRepository.save(dataFile).getId();
|
||||
}
|
||||
|
||||
public void updateDataFile(Long id, String path, Long size, String md5, String type) {
|
||||
DataFile dataFile = dataFileRepository.findById(id).orElseThrow(UpdateDataFileFailedException::new);
|
||||
dataFile.setSize(size);
|
||||
dataFile.setMd5(md5);
|
||||
dataFile.setPath(path);
|
||||
dataFile.setType(type);
|
||||
User loginUser = userService.currentLoginUser();
|
||||
dataFile.setModifiedUser(loginUser);
|
||||
dataFileRepository.save(dataFile);
|
||||
}
|
||||
|
||||
public static final class DataFileNotFoundException extends RuntimeException {
|
||||
public DataFileNotFoundException() {
|
||||
super("文件未找到,请重新上传");
|
||||
}
|
||||
}
|
||||
|
||||
public static final class UpdateDataFileFailedException extends RuntimeException {
|
||||
public UpdateDataFileFailedException() {
|
||||
super("更新文件信息失败,请重新上传");
|
||||
}
|
||||
public static final class UpdateDataFileFailedException extends RuntimeException {
|
||||
public UpdateDataFileFailedException() {
|
||||
super("更新文件信息失败,请重新上传");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,103 +35,103 @@ import org.springframework.stereotype.Service;
|
||||
@Slf4j
|
||||
@Service
|
||||
public class DataResourceService extends SimpleServiceSupport<DataResource> {
|
||||
private final DataResourceRepository dataResourceRepository;
|
||||
private final ResourceTypeRepository resourceTypeRepository;
|
||||
private final ResourceFormatRepository resourceFormatRepository;
|
||||
private final UserService userService;
|
||||
private final DataResourceRepository dataResourceRepository;
|
||||
private final ResourceTypeRepository resourceTypeRepository;
|
||||
private final ResourceFormatRepository resourceFormatRepository;
|
||||
private final UserService userService;
|
||||
|
||||
public DataResourceService(DataResourceRepository repository, ResourceTypeRepository resourceTypeRepository, ResourceFormatRepository resourceFormatRepository, UserService userService) {
|
||||
super(repository, userService);
|
||||
this.dataResourceRepository = repository;
|
||||
this.resourceTypeRepository = resourceTypeRepository;
|
||||
this.resourceFormatRepository = resourceFormatRepository;
|
||||
this.userService = userService;
|
||||
public DataResourceService(DataResourceRepository repository, ResourceTypeRepository resourceTypeRepository, ResourceFormatRepository resourceFormatRepository, UserService userService) {
|
||||
super(repository, userService);
|
||||
this.dataResourceRepository = repository;
|
||||
this.resourceTypeRepository = resourceTypeRepository;
|
||||
this.resourceFormatRepository = resourceFormatRepository;
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ImmutableList<Predicate> listPredicate(Root<DataResource> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
User loginUser = userService.currentLoginUser();
|
||||
if (User.isAdministrator(loginUser)) {
|
||||
return Lists.immutable.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ImmutableList<Predicate> listPredicate(Root<DataResource> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
|
||||
User loginUser = userService.currentLoginUser();
|
||||
if (User.isAdministrator(loginUser)) {
|
||||
return Lists.immutable.empty();
|
||||
Subquery<Confirmation> confirmationSubquery = query.subquery(Confirmation.class);
|
||||
Root<Confirmation> confirmationRoot = confirmationSubquery.from(Confirmation.class);
|
||||
confirmationSubquery.select(confirmationRoot)
|
||||
.where(
|
||||
builder.equal(confirmationRoot.get(Confirmation_.target), root),
|
||||
EntityHelper.checkNeededEntityPrediction(confirmationRoot, builder, loginUser)
|
||||
);
|
||||
|
||||
Subquery<Authentication> authenticationSubquery = query.subquery(Authentication.class);
|
||||
Root<Authentication> authenticationRoot = authenticationSubquery.from(Authentication.class);
|
||||
authenticationSubquery.select(authenticationRoot)
|
||||
.where(
|
||||
builder.equal(authenticationRoot.get(Authentication_.target), root),
|
||||
EntityHelper.checkNeededEntityPrediction(authenticationRoot, builder, loginUser)
|
||||
);
|
||||
|
||||
return Lists.immutable.of(builder.or(
|
||||
builder.equal(root.get(DataResource_.createdUser), loginUser),
|
||||
builder.exists(confirmationSubquery),
|
||||
builder.exists(authenticationSubquery)
|
||||
));
|
||||
}
|
||||
|
||||
public ImmutableList<DataResource> listNoConfirmation() {
|
||||
return Lists.immutable.ofAll(dataResourceRepository.findAll(
|
||||
(root, query, builder) -> {
|
||||
Join<DataResource, Confirmation> confirmationJoin = root.join(DataResource_.confirmation, JoinType.LEFT);
|
||||
return builder.and(
|
||||
builder.isNull(confirmationJoin.get(Confirmation_.id)),
|
||||
builder.equal(root.get(DataResource_.createdUser), userService.currentLoginUser())
|
||||
);
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
Subquery<Confirmation> confirmationSubquery = query.subquery(Confirmation.class);
|
||||
Root<Confirmation> confirmationRoot = confirmationSubquery.from(Confirmation.class);
|
||||
confirmationSubquery.select(confirmationRoot)
|
||||
.where(
|
||||
builder.equal(confirmationRoot.get(Confirmation_.target), root),
|
||||
EntityHelper.checkNeededEntityPrediction(confirmationRoot, builder, loginUser)
|
||||
);
|
||||
public ImmutableList<DataResource> listNoAuthentication() {
|
||||
return Lists.immutable.ofAll(dataResourceRepository.findAll(
|
||||
(root, query, builder) -> {
|
||||
Join<DataResource, Confirmation> confirmationJoin = root.join(DataResource_.confirmation, JoinType.LEFT);
|
||||
confirmationJoin.on(builder.equal(confirmationJoin.get(Confirmation_.state), Confirmation.State.NORMAL));
|
||||
|
||||
Subquery<Authentication> authenticationSubquery = query.subquery(Authentication.class);
|
||||
Root<Authentication> authenticationRoot = authenticationSubquery.from(Authentication.class);
|
||||
authenticationSubquery.select(authenticationRoot)
|
||||
.where(
|
||||
builder.equal(authenticationRoot.get(Authentication_.target), root),
|
||||
EntityHelper.checkNeededEntityPrediction(authenticationRoot, builder, loginUser)
|
||||
);
|
||||
Subquery<Authentication> authenticationSubquery = query.subquery(Authentication.class);
|
||||
Root<Authentication> authenticationRoot = authenticationSubquery.from(Authentication.class);
|
||||
authenticationSubquery.select(authenticationRoot)
|
||||
.where(
|
||||
builder.equal(authenticationRoot.get(Authentication_.target), root),
|
||||
builder.equal(authenticationRoot.get(Authentication_.createdUser), userService.currentLoginUser())
|
||||
);
|
||||
return builder.and(
|
||||
builder.exists(authenticationSubquery).not(),
|
||||
builder.equal(root.get(DataResource_.createdUser), userService.currentLoginUser())
|
||||
);
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
return Lists.immutable.of(builder.or(
|
||||
builder.equal(root.get(DataResource_.createdUser), loginUser),
|
||||
builder.exists(confirmationSubquery),
|
||||
builder.exists(authenticationSubquery)
|
||||
));
|
||||
}
|
||||
public ImmutableList<DataResource> listNoWare() {
|
||||
return Lists.immutable.ofAll(dataResourceRepository.findAll(
|
||||
(root, query, builder) -> {
|
||||
Join<DataResource, Confirmation> confirmationJoin = root.join(DataResource_.confirmation, JoinType.LEFT);
|
||||
Join<DataResource, Ware> wareJoin = root.join(DataResource_.ware, JoinType.LEFT);
|
||||
return builder.and(
|
||||
builder.isNotNull(confirmationJoin),
|
||||
builder.equal(confirmationJoin.get(Confirmation_.state), Confirmation.State.NORMAL),
|
||||
builder.isNull(wareJoin),
|
||||
builder.equal(root.get(DataResource_.createdUser), userService.currentLoginUser())
|
||||
);
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
public ImmutableList<DataResource> listNoConfirmation() {
|
||||
return Lists.immutable.ofAll(dataResourceRepository.findAll(
|
||||
(root, query, builder) -> {
|
||||
Join<DataResource, Confirmation> confirmationJoin = root.join(DataResource_.confirmation, JoinType.LEFT);
|
||||
return builder.and(
|
||||
builder.isNull(confirmationJoin.get(Confirmation_.id)),
|
||||
builder.equal(root.get(DataResource_.createdUser), userService.currentLoginUser())
|
||||
);
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
public ImmutableList<DataResource> listNoAuthentication() {
|
||||
return Lists.immutable.ofAll(dataResourceRepository.findAll(
|
||||
(root, query, builder) -> {
|
||||
Join<DataResource, Confirmation> confirmationJoin = root.join(DataResource_.confirmation, JoinType.LEFT);
|
||||
confirmationJoin.on(builder.equal(confirmationJoin.get(Confirmation_.state), Confirmation.State.NORMAL));
|
||||
|
||||
Subquery<Authentication> authenticationSubquery = query.subquery(Authentication.class);
|
||||
Root<Authentication> authenticationRoot = authenticationSubquery.from(Authentication.class);
|
||||
authenticationSubquery.select(authenticationRoot)
|
||||
.where(
|
||||
builder.equal(authenticationRoot.get(Authentication_.target), root),
|
||||
builder.equal(authenticationRoot.get(Authentication_.createdUser), userService.currentLoginUser())
|
||||
);
|
||||
return builder.and(
|
||||
builder.exists(authenticationSubquery).not(),
|
||||
builder.equal(root.get(DataResource_.createdUser), userService.currentLoginUser())
|
||||
);
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
public ImmutableList<DataResource> listNoWare() {
|
||||
return Lists.immutable.ofAll(dataResourceRepository.findAll(
|
||||
(root, query, builder) -> {
|
||||
Join<DataResource, Confirmation> confirmationJoin = root.join(DataResource_.confirmation, JoinType.LEFT);
|
||||
Join<DataResource, Ware> wareJoin = root.join(DataResource_.ware, JoinType.LEFT);
|
||||
return builder.and(
|
||||
builder.isNotNull(confirmationJoin),
|
||||
builder.equal(confirmationJoin.get(Confirmation_.state), Confirmation.State.NORMAL),
|
||||
builder.isNull(wareJoin),
|
||||
builder.equal(root.get(DataResource_.createdUser), userService.currentLoginUser())
|
||||
);
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long save(DataResource entity) {
|
||||
ResourceType type = resourceTypeRepository.save(entity.getType());
|
||||
ResourceFormat format = resourceFormatRepository.save(entity.getFormat());
|
||||
entity.setType(type);
|
||||
entity.setFormat(format);
|
||||
return super.save(entity);
|
||||
}
|
||||
@Override
|
||||
public Long save(DataResource entity) {
|
||||
ResourceType type = resourceTypeRepository.save(entity.getType());
|
||||
ResourceFormat format = resourceFormatRepository.save(entity.getFormat());
|
||||
entity.setType(type);
|
||||
entity.setFormat(format);
|
||||
return super.save(entity);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,252 +25,252 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
*/
|
||||
@Service
|
||||
public class UserService {
|
||||
private static final Logger logger = LoggerFactory.getLogger(UserService.class);
|
||||
private static final Logger logger = LoggerFactory.getLogger(UserService.class);
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final UserRepository userRepository;
|
||||
|
||||
public UserService(UserRepository userRepository) {
|
||||
this.userRepository = userRepository;
|
||||
public UserService(UserRepository userRepository) {
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
private static String encryptPassword(String password) {
|
||||
String salt = "tY2gNdkt7x%%HcCAFc";
|
||||
return SecureUtil.sha256(StrUtil.format("{}{}", salt, password));
|
||||
}
|
||||
|
||||
/**
|
||||
* 当数据库里没有用户的时候,增加一个默认的系统管理员
|
||||
*/
|
||||
public void initial() {
|
||||
if (userRepository.count() == 0) {
|
||||
User user = new User();
|
||||
user.setUsername("administrator@eshore.com");
|
||||
user.setPassword(encryptPassword("administrator"));
|
||||
user.setRole(User.Role.ADMINISTRATOR);
|
||||
user.setState(User.State.NORMAL);
|
||||
user.setCheckedUser(user);
|
||||
user.setCheckedTime(LocalDateTime.now());
|
||||
user.setCreatedUser(user);
|
||||
user.setModifiedUser(user);
|
||||
userRepository.save(user);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登陆账号状态
|
||||
*/
|
||||
public UserInformation state() {
|
||||
try {
|
||||
long id = StpUtil.getLoginIdAsLong();
|
||||
User user = userRepository.findById(id).orElseThrow(LoginNotFoundException::new);
|
||||
// User user = userRepository.findByUsername("administrator@eshore.com").orElseThrow(LoginNotFoundException::new);
|
||||
StpUtil.login(user.getId());
|
||||
return new UserInformation(user, StpUtil.getTokenInfo());
|
||||
} catch (NotLoginException e) {
|
||||
throw new LoginNotFoundException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public User currentLoginUser() {
|
||||
return currentLoginUserOptional().orElseThrow(LoginNotFoundException::new);
|
||||
}
|
||||
|
||||
public Optional<User> currentLoginUserOptional() {
|
||||
try {
|
||||
return userRepository.findById(StpUtil.getLoginIdAsLong());
|
||||
} catch (Throwable throwable) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private User findUserByUsername(String username) {
|
||||
return userRepository.findByUsername(username).orElseThrow(UserNotFoundException::new);
|
||||
}
|
||||
|
||||
/**
|
||||
* 登陆操作
|
||||
*/
|
||||
public UserInformation login(String username, String password) {
|
||||
User user = userRepository.findByUsername(username).orElseThrow(LoginFailureException::new);
|
||||
if (user.getState() == User.State.CHECKING) {
|
||||
throw new LoginFailureByCheckingException();
|
||||
} else if (user.getState() == User.State.DISABLED) {
|
||||
throw new LoginFailureByDisabledException();
|
||||
} else if (!StrUtil.equals(encryptPassword(password), user.getPassword())) {
|
||||
throw new LoginFailureException();
|
||||
} else {
|
||||
StpUtil.login(user.getId());
|
||||
user.setLastLoginTime(LocalDateTime.now());
|
||||
userRepository.save(user);
|
||||
return new UserInformation(user, StpUtil.getTokenInfo());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 登出操作
|
||||
*/
|
||||
public void logout() {
|
||||
StpUtil.logout();
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册操作
|
||||
*/
|
||||
public void register(String username, String password, User.Role role) {
|
||||
// 不允许通过这个入口注册管理员
|
||||
if (User.Role.ADMINISTRATOR.equals(role)) {
|
||||
throw new RegisterFailureException();
|
||||
}
|
||||
User user = new User();
|
||||
user.setUsername(username);
|
||||
user.setPassword(encryptPassword(password));
|
||||
user.setRole(role);
|
||||
user.setCreatedUser(user);
|
||||
user.setModifiedUser(user);
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员注册操作
|
||||
* 直接成功
|
||||
*/
|
||||
public void registerFromAdministrator(String username, String password, User.Role role) {
|
||||
User loginUser = currentLoginUser();
|
||||
User user = new User();
|
||||
user.setUsername(username);
|
||||
user.setPassword(encryptPassword(password));
|
||||
user.setRole(role);
|
||||
user.setState(User.State.NORMAL);
|
||||
user.setCheckedUser(loginUser);
|
||||
user.setCheckedTime(LocalDateTime.now());
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否存在用户名
|
||||
*/
|
||||
public boolean exitsUsername(String username) {
|
||||
return userRepository.existsByUsername(username);
|
||||
}
|
||||
|
||||
/**
|
||||
* 禁用账号
|
||||
*/
|
||||
@Transactional
|
||||
public void disable(String username) {
|
||||
User loginUser = currentLoginUser();
|
||||
User user = findUserByUsername(username);
|
||||
user.setState(User.State.DISABLED);
|
||||
user.setModifiedUser(loginUser);
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 启用账号
|
||||
*/
|
||||
@Transactional
|
||||
public void enable(String username) {
|
||||
User loginUser = currentLoginUser();
|
||||
User user = findUserByUsername(username);
|
||||
user.setState(User.State.NORMAL);
|
||||
user.setModifiedUser(loginUser);
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void check(String username) {
|
||||
User loginUser = currentLoginUser();
|
||||
User user = findUserByUsername(username);
|
||||
user.setState(User.State.NORMAL);
|
||||
user.setCheckedUser(loginUser);
|
||||
user.setCheckedTime(LocalDateTime.now());
|
||||
user.setModifiedUser(loginUser);
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
public ImmutableList<User> list() {
|
||||
return Lists.immutable.ofAll(userRepository.findAll());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void changePassword(String oldPassword, String newPassword) {
|
||||
long id = StpUtil.getLoginIdAsLong();
|
||||
User user = userRepository.findById(id).orElseThrow(LoginNotFoundException::new);
|
||||
if (StrUtil.equals(encryptPassword(oldPassword), user.getPassword())) {
|
||||
user.setPassword(encryptPassword(newPassword));
|
||||
user.setModifiedUser(user);
|
||||
userRepository.save(user);
|
||||
} else {
|
||||
throw new ChangePasswordFailureException();
|
||||
}
|
||||
}
|
||||
|
||||
public User detail(String username) {
|
||||
return userRepository.findByUsername(username).orElseThrow(UserNotFoundException::new);
|
||||
}
|
||||
|
||||
public static class UserNotFoundException extends RuntimeException {
|
||||
public UserNotFoundException() {
|
||||
super("账号不存在");
|
||||
}
|
||||
}
|
||||
|
||||
public static class RegisterFailureException extends RuntimeException {
|
||||
public RegisterFailureException() {
|
||||
super("不允许注册的用户类型");
|
||||
}
|
||||
}
|
||||
|
||||
public static class LoginFailureException extends RuntimeException {
|
||||
public LoginFailureException() {
|
||||
super("邮箱或密码错误");
|
||||
}
|
||||
}
|
||||
|
||||
public static class LoginFailureByCheckingException extends RuntimeException {
|
||||
public LoginFailureByCheckingException() {
|
||||
super("账号正在审查中");
|
||||
}
|
||||
}
|
||||
|
||||
public static class LoginFailureByDisabledException extends RuntimeException {
|
||||
public LoginFailureByDisabledException() {
|
||||
super("账号已被禁用");
|
||||
}
|
||||
}
|
||||
|
||||
public static class LogoutFailureException extends RuntimeException {
|
||||
public LogoutFailureException() {
|
||||
super("账号登出失败");
|
||||
}
|
||||
}
|
||||
|
||||
public static class LoginNotFoundException extends RuntimeException {
|
||||
public LoginNotFoundException() {
|
||||
super("账号未登陆");
|
||||
}
|
||||
|
||||
private static String encryptPassword(String password) {
|
||||
String salt = "tY2gNdkt7x%%HcCAFc";
|
||||
return SecureUtil.sha256(StrUtil.format("{}{}", salt, password));
|
||||
public LoginNotFoundException(Exception exception) {
|
||||
super("账号未登陆", exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 当数据库里没有用户的时候,增加一个默认的系统管理员
|
||||
*/
|
||||
public void initial() {
|
||||
if (userRepository.count() == 0) {
|
||||
User user = new User();
|
||||
user.setUsername("administrator@eshore.com");
|
||||
user.setPassword(encryptPassword("administrator"));
|
||||
user.setRole(User.Role.ADMINISTRATOR);
|
||||
user.setState(User.State.NORMAL);
|
||||
user.setCheckedUser(user);
|
||||
user.setCheckedTime(LocalDateTime.now());
|
||||
user.setCreatedUser(user);
|
||||
user.setModifiedUser(user);
|
||||
userRepository.save(user);
|
||||
}
|
||||
public static class ChangePasswordFailureException extends RuntimeException {
|
||||
public ChangePasswordFailureException() {
|
||||
super("原密码不正确");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前登陆账号状态
|
||||
*/
|
||||
public UserInformation state() {
|
||||
try {
|
||||
long id = StpUtil.getLoginIdAsLong();
|
||||
User user = userRepository.findById(id).orElseThrow(LoginNotFoundException::new);
|
||||
// User user = userRepository.findByUsername("administrator@eshore.com").orElseThrow(LoginNotFoundException::new);
|
||||
StpUtil.login(user.getId());
|
||||
return new UserInformation(user, StpUtil.getTokenInfo());
|
||||
} catch (NotLoginException e) {
|
||||
throw new LoginNotFoundException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public User currentLoginUser() {
|
||||
return currentLoginUserOptional().orElseThrow(LoginNotFoundException::new);
|
||||
}
|
||||
|
||||
public Optional<User> currentLoginUserOptional() {
|
||||
try {
|
||||
return userRepository.findById(StpUtil.getLoginIdAsLong());
|
||||
} catch (Throwable throwable) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private User findUserByUsername(String username) {
|
||||
return userRepository.findByUsername(username).orElseThrow(UserNotFoundException::new);
|
||||
}
|
||||
|
||||
/**
|
||||
* 登陆操作
|
||||
*/
|
||||
public UserInformation login(String username, String password) {
|
||||
User user = userRepository.findByUsername(username).orElseThrow(LoginFailureException::new);
|
||||
if (user.getState() == User.State.CHECKING) {
|
||||
throw new LoginFailureByCheckingException();
|
||||
} else if (user.getState() == User.State.DISABLED) {
|
||||
throw new LoginFailureByDisabledException();
|
||||
} else if (!StrUtil.equals(encryptPassword(password), user.getPassword())) {
|
||||
throw new LoginFailureException();
|
||||
} else {
|
||||
StpUtil.login(user.getId());
|
||||
user.setLastLoginTime(LocalDateTime.now());
|
||||
userRepository.save(user);
|
||||
return new UserInformation(user, StpUtil.getTokenInfo());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 登出操作
|
||||
*/
|
||||
public void logout() {
|
||||
StpUtil.logout();
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册操作
|
||||
*/
|
||||
public void register(String username, String password, User.Role role) {
|
||||
// 不允许通过这个入口注册管理员
|
||||
if (User.Role.ADMINISTRATOR.equals(role)) {
|
||||
throw new RegisterFailureException();
|
||||
}
|
||||
User user = new User();
|
||||
user.setUsername(username);
|
||||
user.setPassword(encryptPassword(password));
|
||||
user.setRole(role);
|
||||
user.setCreatedUser(user);
|
||||
user.setModifiedUser(user);
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员注册操作
|
||||
* 直接成功
|
||||
*/
|
||||
public void registerFromAdministrator(String username, String password, User.Role role) {
|
||||
User loginUser = currentLoginUser();
|
||||
User user = new User();
|
||||
user.setUsername(username);
|
||||
user.setPassword(encryptPassword(password));
|
||||
user.setRole(role);
|
||||
user.setState(User.State.NORMAL);
|
||||
user.setCheckedUser(loginUser);
|
||||
user.setCheckedTime(LocalDateTime.now());
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否存在用户名
|
||||
*/
|
||||
public boolean exitsUsername(String username) {
|
||||
return userRepository.existsByUsername(username);
|
||||
}
|
||||
|
||||
/**
|
||||
* 禁用账号
|
||||
*/
|
||||
@Transactional
|
||||
public void disable(String username) {
|
||||
User loginUser = currentLoginUser();
|
||||
User user = findUserByUsername(username);
|
||||
user.setState(User.State.DISABLED);
|
||||
user.setModifiedUser(loginUser);
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 启用账号
|
||||
*/
|
||||
@Transactional
|
||||
public void enable(String username) {
|
||||
User loginUser = currentLoginUser();
|
||||
User user = findUserByUsername(username);
|
||||
user.setState(User.State.NORMAL);
|
||||
user.setModifiedUser(loginUser);
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void check(String username) {
|
||||
User loginUser = currentLoginUser();
|
||||
User user = findUserByUsername(username);
|
||||
user.setState(User.State.NORMAL);
|
||||
user.setCheckedUser(loginUser);
|
||||
user.setCheckedTime(LocalDateTime.now());
|
||||
user.setModifiedUser(loginUser);
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
public ImmutableList<User> list() {
|
||||
return Lists.immutable.ofAll(userRepository.findAll());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void changePassword(String oldPassword, String newPassword) {
|
||||
long id = StpUtil.getLoginIdAsLong();
|
||||
User user = userRepository.findById(id).orElseThrow(LoginNotFoundException::new);
|
||||
if (StrUtil.equals(encryptPassword(oldPassword), user.getPassword())) {
|
||||
user.setPassword(encryptPassword(newPassword));
|
||||
user.setModifiedUser(user);
|
||||
userRepository.save(user);
|
||||
} else {
|
||||
throw new ChangePasswordFailureException();
|
||||
}
|
||||
}
|
||||
|
||||
public User detail(String username) {
|
||||
return userRepository.findByUsername(username).orElseThrow(UserNotFoundException::new);
|
||||
}
|
||||
|
||||
public static class UserNotFoundException extends RuntimeException {
|
||||
public UserNotFoundException() {
|
||||
super("账号不存在");
|
||||
}
|
||||
}
|
||||
|
||||
public static class RegisterFailureException extends RuntimeException {
|
||||
public RegisterFailureException() {
|
||||
super("不允许注册的用户类型");
|
||||
}
|
||||
}
|
||||
|
||||
public static class LoginFailureException extends RuntimeException {
|
||||
public LoginFailureException() {
|
||||
super("邮箱或密码错误");
|
||||
}
|
||||
}
|
||||
|
||||
public static class LoginFailureByCheckingException extends RuntimeException {
|
||||
public LoginFailureByCheckingException() {
|
||||
super("账号正在审查中");
|
||||
}
|
||||
}
|
||||
|
||||
public static class LoginFailureByDisabledException extends RuntimeException {
|
||||
public LoginFailureByDisabledException() {
|
||||
super("账号已被禁用");
|
||||
}
|
||||
}
|
||||
|
||||
public static class LogoutFailureException extends RuntimeException {
|
||||
public LogoutFailureException() {
|
||||
super("账号登出失败");
|
||||
}
|
||||
}
|
||||
|
||||
public static class LoginNotFoundException extends RuntimeException {
|
||||
public LoginNotFoundException() {
|
||||
super("账号未登陆");
|
||||
}
|
||||
|
||||
public LoginNotFoundException(Exception exception) {
|
||||
super("账号未登陆", exception);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ChangePasswordFailureException extends RuntimeException {
|
||||
public ChangePasswordFailureException() {
|
||||
super("原密码不正确");
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class UserInformation {
|
||||
private String username;
|
||||
private User.Role role;
|
||||
private String token;
|
||||
|
||||
public UserInformation(User user, SaTokenInfo token) {
|
||||
this.username = user.getUsername();
|
||||
this.role = user.getRole();
|
||||
this.token = token.getTokenValue();
|
||||
}
|
||||
@Data
|
||||
public static class UserInformation {
|
||||
private String username;
|
||||
private User.Role role;
|
||||
private String token;
|
||||
|
||||
public UserInformation(User user, SaTokenInfo token) {
|
||||
this.username = user.getUsername();
|
||||
this.role = user.getRole();
|
||||
this.token = token.getTokenValue();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,69 +25,69 @@ import org.springframework.stereotype.Service;
|
||||
@Slf4j
|
||||
@Service("com.eshore.gringotts.web.domain.service.WareService")
|
||||
public class WareService extends SimpleServiceSupport<Ware> implements CheckingService {
|
||||
private final WareRepository wareRepository;
|
||||
private final CheckOrderService checkOrderService;
|
||||
private final ObjectMapper mapper;
|
||||
private final WareRepository wareRepository;
|
||||
private final CheckOrderService checkOrderService;
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
public WareService(WareRepository repository, UserService userService, CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) {
|
||||
super(repository, userService);
|
||||
this.wareRepository = repository;
|
||||
this.checkOrderService = checkOrderService;
|
||||
this.mapper = builder.build();
|
||||
public WareService(WareRepository repository, UserService userService, CheckOrderService checkOrderService, Jackson2ObjectMapperBuilder builder) {
|
||||
super(repository, userService);
|
||||
this.wareRepository = repository;
|
||||
this.checkOrderService = checkOrderService;
|
||||
this.mapper = builder.build();
|
||||
}
|
||||
|
||||
public ImmutableList<Ware> listPublic() {
|
||||
return Lists.immutable.ofAll(
|
||||
wareRepository.findAll((root, query, builder) -> builder.equal(root.get("state"), Ware.State.NORMAL))
|
||||
);
|
||||
}
|
||||
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
@Override
|
||||
public void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap<String, Object> parameters) {
|
||||
if (StrUtil.equals(order.getKeyword(), "ware_check")) {
|
||||
Long wareId = (Long) parameters.get("wareId");
|
||||
Ware ware = detailOrThrow(wareId);
|
||||
switch (operation) {
|
||||
case APPLY:
|
||||
ware.setState(Ware.State.NORMAL);
|
||||
order.setState(CheckOrder.State.OVER);
|
||||
break;
|
||||
case REJECT:
|
||||
ware.setState(Ware.State.DRAFT);
|
||||
order.setState(CheckOrder.State.OVER);
|
||||
break;
|
||||
}
|
||||
save(ware);
|
||||
checkOrderService.save(order);
|
||||
}
|
||||
}
|
||||
|
||||
public ImmutableList<Ware> listPublic() {
|
||||
return Lists.immutable.ofAll(
|
||||
wareRepository.findAll((root, query, builder) -> builder.equal(root.get("state"), Ware.State.NORMAL))
|
||||
);
|
||||
}
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
public void submit(Long id) throws JsonProcessingException {
|
||||
Ware ware = detailOrThrow(id);
|
||||
ware.setState(Ware.State.CHECKING);
|
||||
Long orderId = checkOrderService.save(new CheckOrder(
|
||||
"ware_check",
|
||||
StrUtil.format("数据资源「{}」的上架申请", ware.getName()),
|
||||
CheckOrder.Type.MARKET,
|
||||
mapper.writeValueAsString(Maps.immutable.of("wareId", ware.getId())),
|
||||
"com.eshore.gringotts.web.domain.service.WareService",
|
||||
User.Role.CHECKER
|
||||
));
|
||||
CheckOrder order = checkOrderService.detailOrThrow(orderId);
|
||||
ware.setOrder(order);
|
||||
save(ware);
|
||||
}
|
||||
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
@Override
|
||||
public void onChecked(CheckOrder order, CheckOrder.Operation operation, ImmutableMap<String, Object> parameters) {
|
||||
if (StrUtil.equals(order.getKeyword(), "ware_check")) {
|
||||
Long wareId = (Long) parameters.get("wareId");
|
||||
Ware ware = detailOrThrow(wareId);
|
||||
switch (operation) {
|
||||
case APPLY:
|
||||
ware.setState(Ware.State.NORMAL);
|
||||
order.setState(CheckOrder.State.OVER);
|
||||
break;
|
||||
case REJECT:
|
||||
ware.setState(Ware.State.DRAFT);
|
||||
order.setState(CheckOrder.State.OVER);
|
||||
break;
|
||||
}
|
||||
save(ware);
|
||||
checkOrderService.save(order);
|
||||
}
|
||||
}
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
public void retract(Long id) {
|
||||
Ware ware = detailOrThrow(id);
|
||||
ware.setState(Ware.State.DRAFT);
|
||||
save(ware);
|
||||
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
public void submit(Long id) throws JsonProcessingException {
|
||||
Ware ware = detailOrThrow(id);
|
||||
ware.setState(Ware.State.CHECKING);
|
||||
Long orderId = checkOrderService.save(new CheckOrder(
|
||||
"ware_check",
|
||||
StrUtil.format("数据资源「{}」的上架申请", ware.getName()),
|
||||
CheckOrder.Type.MARKET,
|
||||
mapper.writeValueAsString(Maps.immutable.of("wareId", ware.getId())),
|
||||
"com.eshore.gringotts.web.domain.service.WareService",
|
||||
User.Role.CHECKER
|
||||
));
|
||||
CheckOrder order = checkOrderService.detailOrThrow(orderId);
|
||||
ware.setOrder(order);
|
||||
save(ware);
|
||||
}
|
||||
|
||||
@Transactional(rollbackOn = Throwable.class)
|
||||
public void retract(Long id) {
|
||||
Ware ware = detailOrThrow(id);
|
||||
ware.setState(Ware.State.DRAFT);
|
||||
save(ware);
|
||||
|
||||
CheckOrder order = ware.getOrder();
|
||||
order.setState(CheckOrder.State.RETRACT);
|
||||
checkOrderService.save(order);
|
||||
}
|
||||
CheckOrder order = ware.getOrder();
|
||||
order.setState(CheckOrder.State.RETRACT);
|
||||
checkOrderService.save(order);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,23 +19,23 @@ import org.springframework.data.jpa.repository.JpaRepository;
|
||||
* @date 2024-11-25
|
||||
*/
|
||||
public class EntityHelper {
|
||||
public static <E, ID> void deleteIfUpdateNeeded(JpaRepository<E, ID> repository, Supplier<E> getter, E target) {
|
||||
E old = getter.get();
|
||||
if (ObjectUtil.notEqual(old, target)) {
|
||||
repository.delete(old);
|
||||
}
|
||||
public static <E, ID> void deleteIfUpdateNeeded(JpaRepository<E, ID> repository, Supplier<E> getter, E target) {
|
||||
E old = getter.get();
|
||||
if (ObjectUtil.notEqual(old, target)) {
|
||||
repository.delete(old);
|
||||
}
|
||||
}
|
||||
|
||||
public static Predicate checkNeededEntityPrediction(Root<? extends CheckingNeededEntity> root, CriteriaBuilder builder, User loginUser) {
|
||||
return builder.or(
|
||||
builder.and(
|
||||
builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.target), CheckOrder.Target.ROLE),
|
||||
builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.targetRole), loginUser.getRole())
|
||||
),
|
||||
builder.and(
|
||||
builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.target), CheckOrder.Target.USER),
|
||||
builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.targetUser), loginUser)
|
||||
)
|
||||
);
|
||||
}
|
||||
public static Predicate checkNeededEntityPrediction(Root<? extends CheckingNeededEntity> root, CriteriaBuilder builder, User loginUser) {
|
||||
return builder.or(
|
||||
builder.and(
|
||||
builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.target), CheckOrder.Target.ROLE),
|
||||
builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.targetRole), loginUser.getRole())
|
||||
),
|
||||
builder.and(
|
||||
builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.target), CheckOrder.Target.USER),
|
||||
builder.equal(root.get(CheckingNeededEntity_.order).get(CheckOrder_.targetUser), loginUser)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,58 +11,58 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
* @date 2024-12-03
|
||||
*/
|
||||
public class TestQueryParse {
|
||||
public static void main(String[] args) throws JsonProcessingException {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.registerModule(new EclipseCollectionsModule());
|
||||
mapper.registerModule(new JavaTimeModule());
|
||||
// language=JSON
|
||||
System.out.println(mapper.readValue("{}", Query.class));
|
||||
// language=JSON
|
||||
System.out.println(mapper.readValue("{\n" +
|
||||
" \"query\": {\n" +
|
||||
" \"equal\": {\n" +
|
||||
" \"name\": \"lanyuanxiaoyao\"\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
"}", Query.class));
|
||||
// language=JSON
|
||||
System.out.println(mapper.readValue("{\n" +
|
||||
" \"query\": {\n" +
|
||||
" \"equal\": {\n" +
|
||||
" \"name\": \"lanyuanxiaoyao\"\n" +
|
||||
" },\n" +
|
||||
" \"notEqual\": {\n" +
|
||||
" \"username\": \"lanyuanxiaoyao@qq.com\",\n" +
|
||||
" \"password\": \"mingland87\"\n" +
|
||||
" },\n" +
|
||||
" \"great\": {\n" +
|
||||
" \"age\": 12,\n" +
|
||||
" \"createTime\": \"2020-10-12 00:00:00\"\n" +
|
||||
" },\n" +
|
||||
" \"in\": {\n" +
|
||||
" \"age\": [\n" +
|
||||
" 15,\n" +
|
||||
" 18,\n" +
|
||||
" 20\n" +
|
||||
" ]\n" +
|
||||
" },\n" +
|
||||
" \"between\": {\n" +
|
||||
" \"createTime\": {\n" +
|
||||
" \"start\": \"2024-12-03 00:00:00\",\n" +
|
||||
" \"end\": \"2024-12-03 00:00:00\"\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
" },\n" +
|
||||
" \"sort\": [\n" +
|
||||
" {\n" +
|
||||
" \"column\": \"createTime\",\n" +
|
||||
" \"direction\": \"ASC\"\n" +
|
||||
" }\n" +
|
||||
" ],\n" +
|
||||
" \"page\": {\n" +
|
||||
" \"size\": 10,\n" +
|
||||
" \"page\": 1\n" +
|
||||
" }\n" +
|
||||
"}", Query.class));
|
||||
}
|
||||
public static void main(String[] args) throws JsonProcessingException {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.registerModule(new EclipseCollectionsModule());
|
||||
mapper.registerModule(new JavaTimeModule());
|
||||
// language=JSON
|
||||
System.out.println(mapper.readValue("{}", Query.class));
|
||||
// language=JSON
|
||||
System.out.println(mapper.readValue("{\n" +
|
||||
" \"query\": {\n" +
|
||||
" \"equal\": {\n" +
|
||||
" \"name\": \"lanyuanxiaoyao\"\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
"}", Query.class));
|
||||
// language=JSON
|
||||
System.out.println(mapper.readValue("{\n" +
|
||||
" \"query\": {\n" +
|
||||
" \"equal\": {\n" +
|
||||
" \"name\": \"lanyuanxiaoyao\"\n" +
|
||||
" },\n" +
|
||||
" \"notEqual\": {\n" +
|
||||
" \"username\": \"lanyuanxiaoyao@qq.com\",\n" +
|
||||
" \"password\": \"mingland87\"\n" +
|
||||
" },\n" +
|
||||
" \"great\": {\n" +
|
||||
" \"age\": 12,\n" +
|
||||
" \"createTime\": \"2020-10-12 00:00:00\"\n" +
|
||||
" },\n" +
|
||||
" \"in\": {\n" +
|
||||
" \"age\": [\n" +
|
||||
" 15,\n" +
|
||||
" 18,\n" +
|
||||
" 20\n" +
|
||||
" ]\n" +
|
||||
" },\n" +
|
||||
" \"between\": {\n" +
|
||||
" \"createTime\": {\n" +
|
||||
" \"start\": \"2024-12-03 00:00:00\",\n" +
|
||||
" \"end\": \"2024-12-03 00:00:00\"\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
" },\n" +
|
||||
" \"sort\": [\n" +
|
||||
" {\n" +
|
||||
" \"column\": \"createTime\",\n" +
|
||||
" \"direction\": \"ASC\"\n" +
|
||||
" }\n" +
|
||||
" ],\n" +
|
||||
" \"page\": {\n" +
|
||||
" \"size\": 10,\n" +
|
||||
" \"page\": 1\n" +
|
||||
" }\n" +
|
||||
"}", Query.class));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user