后台管理初始化
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
package com.linkerbot.cadworld;
|
||||
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||
|
||||
@SpringBootApplication
|
||||
@ConfigurationPropertiesScan("com.linkerbot.cadworld.config")
|
||||
@MapperScan("com.linkerbot.cadworld.mapper")
|
||||
public class AdminApiApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(AdminApiApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.linkerbot.cadworld.audit;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface AuditOperation {
|
||||
String module();
|
||||
String action();
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.linkerbot.cadworld.audit;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||
import com.linkerbot.cadworld.dto.component.ComponentResponse;
|
||||
import com.linkerbot.cadworld.dto.component.CompleteCoverImageUploadResponse;
|
||||
import com.linkerbot.cadworld.dto.component.CompleteUrdfUploadResponse;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlResponse;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareCoverImageUploadSessionResponse;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareUrdfUploadSessionResponse;
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.server.ServerHttpRequest;
|
||||
import org.springframework.http.server.ServerHttpResponse;
|
||||
import org.springframework.http.server.ServletServerHttpRequest;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
|
||||
|
||||
/** Only reads known identifiers from responses; tokens and request bodies are never retained. */
|
||||
@RestControllerAdvice
|
||||
public class AuditResponseAdvice implements ResponseBodyAdvice<Object> {
|
||||
@Override
|
||||
public boolean supports(MethodParameter parameter, Class<? extends HttpMessageConverter<?>> converter) { return true; }
|
||||
|
||||
@Override
|
||||
public Object beforeBodyWrite(Object body, MethodParameter parameter, MediaType type,
|
||||
Class<? extends HttpMessageConverter<?>> converter, ServerHttpRequest request, ServerHttpResponse response) {
|
||||
if (request instanceof ServletServerHttpRequest servlet && body instanceof ApiResponse<?> envelope
|
||||
&& servlet.getServletRequest().getAttribute(OperationAuditInterceptor.CONTEXT) instanceof OperationAuditInterceptor.Context context) {
|
||||
Object data = envelope.getData();
|
||||
String id = switch (data) {
|
||||
case ComponentResponse component -> String.valueOf(component.id());
|
||||
case JsonNode json when json.hasNonNull("id") -> json.get("id").asText();
|
||||
case PrepareCoverImageUploadSessionResponse session -> session.keyPrefix();
|
||||
case PrepareUrdfUploadSessionResponse session -> session.keyPrefix();
|
||||
case PrepareObjectUploadUrlResponse upload -> upload.objectKey();
|
||||
case CompleteCoverImageUploadResponse upload -> upload.coverImageKey();
|
||||
case CompleteUrdfUploadResponse upload -> upload.source();
|
||||
case null, default -> null;
|
||||
};
|
||||
if (id != null && context.event().getTargetId() == null) context.event().setTargetId(OperationAuditInterceptor.limit(id, 512));
|
||||
}
|
||||
return body;
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.linkerbot.cadworld.audit;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
|
||||
|
||||
/** Multipart size failures can occur before an MVC interceptor is invoked. */
|
||||
@Slf4j
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
|
||||
public class EarlyFailureAuditFilter extends OncePerRequestFilter {
|
||||
private final RequestMappingHandlerMapping mappings;
|
||||
private final OperationAuditInterceptor audit;
|
||||
|
||||
public EarlyFailureAuditFilter(@Qualifier("requestMappingHandlerMapping") RequestMappingHandlerMapping mappings,
|
||||
OperationAuditInterceptor audit) {
|
||||
this.mappings = mappings;
|
||||
this.audit = audit;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
long started = System.nanoTime();
|
||||
try {
|
||||
chain.doFilter(request, response);
|
||||
} finally {
|
||||
if (response.getStatus() >= 400 && request.getAttribute(OperationAuditInterceptor.CONTEXT) == null
|
||||
&& request.getRequestURI().startsWith("/admin-api/")) {
|
||||
try {
|
||||
// DispatcherServlet clears its parsed path before returning to filters.
|
||||
org.springframework.web.util.ServletRequestPathUtils.parseAndCache(request);
|
||||
var handler = mappings.getHandler(request);
|
||||
if (handler != null) {
|
||||
audit.preHandle(request, response, handler.getHandler());
|
||||
if (request.getAttribute(OperationAuditInterceptor.CONTEXT) instanceof OperationAuditInterceptor.Context context) {
|
||||
request.setAttribute(OperationAuditInterceptor.CONTEXT, new OperationAuditInterceptor.Context(context.event(), started));
|
||||
audit.afterCompletion(request, response, handler.getHandler(), null);
|
||||
}
|
||||
}
|
||||
} catch (Exception failure) {
|
||||
log.error("Failed to resolve early operation failure at {} {}", request.getMethod(), request.getRequestURI(), failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package com.linkerbot.cadworld.audit;
|
||||
|
||||
import com.linkerbot.cadworld.common.api.RequestIdHolder;
|
||||
import com.linkerbot.cadworld.entity.OperationLog;
|
||||
import com.linkerbot.cadworld.service.AdminOperatorProvider;
|
||||
import com.linkerbot.cadworld.service.OperationLogService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Map;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
import org.springframework.web.servlet.HandlerMapping;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class OperationAuditInterceptor implements HandlerInterceptor {
|
||||
static final String CONTEXT = "cadworld.auditContext";
|
||||
private final OperationLogService service;
|
||||
private final AdminOperatorProvider operator;
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
|
||||
if (!(handler instanceof HandlerMethod method)) return true;
|
||||
AuditOperation annotation = method.getMethodAnnotation(AuditOperation.class);
|
||||
if (annotation == null) return true;
|
||||
OperationLog event = new OperationLog();
|
||||
event.setModule(annotation.module());
|
||||
event.setAction(annotation.action());
|
||||
event.setOperatorId(operator.userId());
|
||||
event.setOperatorName(operator.name());
|
||||
event.setRequestPath(limit(request.getRequestURI(), 512));
|
||||
event.setRequestMethod(request.getMethod());
|
||||
event.setClientIp(limit(request.getRemoteAddr(), 64));
|
||||
event.setRequestId(limit(RequestIdHolder.get(), 64));
|
||||
event.setOperatedAt(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
|
||||
Object variables = request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
|
||||
if (variables instanceof Map<?, ?> values && values.get("id") != null) {
|
||||
event.setTargetId(limit(values.get("id").toString(), 512));
|
||||
} else if ("UPLOAD".equals(annotation.action())) {
|
||||
event.setTargetId(limit(request.getParameter("objectKey"), 512));
|
||||
}
|
||||
request.setAttribute(CONTEXT, new Context(event, System.nanoTime()));
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
|
||||
if (!(request.getAttribute(CONTEXT) instanceof Context context)) return;
|
||||
OperationLog event = context.event();
|
||||
Object error = request.getAttribute("cadworld.operationError");
|
||||
boolean success = response.getStatus() < 400 && exception == null && error == null;
|
||||
event.setSuccess(success);
|
||||
event.setHttpStatus(response.getStatus());
|
||||
event.setDurationMs((System.nanoTime() - context.started()) / 1_000_000);
|
||||
if (!success) event.setErrorSummary(limit(error == null ? "请求失败,HTTP " + response.getStatus() : error.toString(), 1000));
|
||||
try {
|
||||
service.record(event);
|
||||
} catch (Exception failure) {
|
||||
log.error("Failed to persist operation log. requestId={}, module={}, action={}",
|
||||
event.getRequestId(), event.getModule(), event.getAction(), failure);
|
||||
}
|
||||
}
|
||||
|
||||
static String limit(String value, int length) {
|
||||
return value == null ? null : value.substring(0, Math.min(length, value.length()));
|
||||
}
|
||||
|
||||
record Context(OperationLog event, long started) { }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.linkerbot.cadworld.config;
|
||||
|
||||
import com.linkerbot.cadworld.audit.OperationAuditInterceptor;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
@RequiredArgsConstructor
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
private final OperationAuditInterceptor audit;
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(audit).addPathPatterns("/admin-api/**"); }
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package com.linkerbot.cadworld.controller;
|
||||
|
||||
import com.linkerbot.cadworld.audit.AuditOperation;
|
||||
|
||||
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
|
||||
import com.linkerbot.cadworld.service.impl.ComponentUploadSupport;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.util.UriUtils;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin-api/component-assets")
|
||||
@RequiredArgsConstructor
|
||||
public class ComponentAssetController {
|
||||
|
||||
private final com.linkerbot.cadworld.service.AdminOperatorProvider operatorProvider;
|
||||
|
||||
private static final String ASSET_PATH_PREFIX = "/admin-api/component-assets/";
|
||||
|
||||
private final ComponentUploadSupport componentUploadSupport;
|
||||
private final ObjectStorageClient objectStorageClient;
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "UPLOAD")
|
||||
@PutMapping("/upload")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void upload(
|
||||
@RequestParam String objectKey,
|
||||
@RequestHeader(value = HttpHeaders.CONTENT_TYPE, required = false) String contentType,
|
||||
HttpServletRequest request
|
||||
) throws IOException {
|
||||
componentUploadSupport.uploadObject(
|
||||
operatorProvider.userId(),
|
||||
objectKey,
|
||||
contentType,
|
||||
request.getInputStream(),
|
||||
request.getContentLengthLong()
|
||||
);
|
||||
}
|
||||
|
||||
@GetMapping("/**")
|
||||
public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
String requestUri = request.getRequestURI();
|
||||
int prefixIndex = requestUri.indexOf(ASSET_PATH_PREFIX);
|
||||
if (prefixIndex < 0) {
|
||||
response.sendError(HttpStatus.NOT_FOUND.value());
|
||||
return;
|
||||
}
|
||||
String encodedKey = requestUri.substring(prefixIndex + ASSET_PATH_PREFIX.length());
|
||||
String objectKey = UriUtils.decode(encodedKey, StandardCharsets.UTF_8);
|
||||
ObjectStorageClient.StoredObject object = objectStorageClient.statObject(objectKey);
|
||||
|
||||
response.setStatus(HttpStatus.OK.value());
|
||||
response.setContentType(object.contentType() == null || object.contentType().isBlank()
|
||||
? MediaType.APPLICATION_OCTET_STREAM_VALUE
|
||||
: object.contentType());
|
||||
if (object.contentLength() >= 0) {
|
||||
response.setContentLengthLong(object.contentLength());
|
||||
}
|
||||
response.setHeader(HttpHeaders.CACHE_CONTROL, "public, max-age=3600");
|
||||
objectStorageClient.writeObjectTo(objectKey, response.getOutputStream());
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
package com.linkerbot.cadworld.controller;
|
||||
|
||||
import com.linkerbot.cadworld.audit.AuditOperation;
|
||||
|
||||
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||
import com.linkerbot.cadworld.common.api.PageResponse;
|
||||
import com.linkerbot.cadworld.dto.component.CompleteCoverImageUploadRequest;
|
||||
import com.linkerbot.cadworld.dto.component.CompleteCoverImageUploadResponse;
|
||||
import com.linkerbot.cadworld.dto.component.CompleteUrdfUploadRequest;
|
||||
import com.linkerbot.cadworld.dto.component.CompleteUrdfUploadResponse;
|
||||
import com.linkerbot.cadworld.dto.common.SuccessResponse;
|
||||
import com.linkerbot.cadworld.dto.component.ComponentListItemResponse;
|
||||
import com.linkerbot.cadworld.dto.component.ComponentResponse;
|
||||
import com.linkerbot.cadworld.dto.component.CreateComponentRequest;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlRequest;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareObjectUploadUrlResponse;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareCoverImageUploadSessionResponse;
|
||||
import com.linkerbot.cadworld.dto.component.PrepareUrdfUploadSessionResponse;
|
||||
import com.linkerbot.cadworld.dto.component.UpdateComponentRequest;
|
||||
import com.linkerbot.cadworld.service.ComponentCoverImageUploadService;
|
||||
import com.linkerbot.cadworld.service.ComponentService;
|
||||
import com.linkerbot.cadworld.service.ComponentUrdfUploadService;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin-api/components")
|
||||
@RequiredArgsConstructor
|
||||
public class ComponentController {
|
||||
|
||||
private final com.linkerbot.cadworld.service.AdminOperatorProvider operatorProvider;
|
||||
|
||||
private final ComponentService componentService;
|
||||
private final ComponentCoverImageUploadService componentCoverImageUploadService;
|
||||
private final ComponentUrdfUploadService componentUrdfUploadService;
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "CREATE")
|
||||
@PostMapping
|
||||
public ApiResponse<ComponentResponse> create(
|
||||
@Valid @RequestBody CreateComponentRequest request
|
||||
) {
|
||||
return ApiResponse.success(componentService.createComponent(operatorProvider.userId(), request));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "PREPARE_UPLOAD")
|
||||
@PostMapping("/cover-image-upload-sessions")
|
||||
public ApiResponse<PrepareCoverImageUploadSessionResponse> prepareCoverImageUploadSession(
|
||||
) {
|
||||
return ApiResponse.success(componentCoverImageUploadService.prepareUploadSession(operatorProvider.userId()));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "PREPARE_UPLOAD_URL")
|
||||
@PostMapping("/cover-image-upload-sessions/upload-url")
|
||||
public ApiResponse<PrepareObjectUploadUrlResponse> prepareCoverImageObjectUploadUrl(
|
||||
@Valid @RequestBody PrepareObjectUploadUrlRequest request
|
||||
) {
|
||||
return ApiResponse.success(componentCoverImageUploadService.prepareObjectUploadUrl(operatorProvider.userId(), request));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "COMPLETE_UPLOAD")
|
||||
@PostMapping("/cover-image-upload-sessions/complete")
|
||||
public ApiResponse<CompleteCoverImageUploadResponse> completeCoverImageUploadSession(
|
||||
@Valid @RequestBody CompleteCoverImageUploadRequest request
|
||||
) {
|
||||
return ApiResponse.success(componentCoverImageUploadService.completeUploadSession(operatorProvider.userId(), request));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "PREPARE_UPLOAD")
|
||||
@PostMapping("/urdf-upload-sessions")
|
||||
public ApiResponse<PrepareUrdfUploadSessionResponse> prepareUrdfUploadSession(
|
||||
) {
|
||||
return ApiResponse.success(componentUrdfUploadService.prepareUploadSession(operatorProvider.userId()));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "PREPARE_UPLOAD_URL")
|
||||
@PostMapping("/urdf-upload-sessions/upload-url")
|
||||
public ApiResponse<PrepareObjectUploadUrlResponse> prepareUrdfObjectUploadUrl(
|
||||
@Valid @RequestBody PrepareObjectUploadUrlRequest request
|
||||
) {
|
||||
return ApiResponse.success(componentUrdfUploadService.prepareObjectUploadUrl(operatorProvider.userId(), request));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "COMPLETE_UPLOAD")
|
||||
@PostMapping("/urdf-upload-sessions/complete")
|
||||
public ApiResponse<CompleteUrdfUploadResponse> completeUrdfUploadSession(
|
||||
@Valid @RequestBody CompleteUrdfUploadRequest request
|
||||
) {
|
||||
return ApiResponse.success(componentUrdfUploadService.completeUploadSession(operatorProvider.userId(), request));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<PageResponse<ComponentListItemResponse>> list(
|
||||
@RequestParam(defaultValue = "1") long page,
|
||||
@RequestParam(defaultValue = "20") long size,
|
||||
@RequestParam(required = false) String keyword
|
||||
) {
|
||||
return ApiResponse.success(componentService.listComponents(page, Math.min(size, 100), keyword));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ApiResponse<ComponentResponse> detail(@PathVariable Long id) {
|
||||
return ApiResponse.success(componentService.getComponent(id));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "UPDATE")
|
||||
@PutMapping("/{id}")
|
||||
public ApiResponse<ComponentResponse> update(
|
||||
@PathVariable Long id,
|
||||
@Valid @RequestBody UpdateComponentRequest request
|
||||
) {
|
||||
return ApiResponse.success(componentService.updateComponent(operatorProvider.userId(), id, request));
|
||||
}
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "DELETE")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResponse<SuccessResponse> delete(
|
||||
@PathVariable Long id
|
||||
) {
|
||||
componentService.deleteComponent(operatorProvider.userId(), id);
|
||||
return ApiResponse.success(SuccessResponse.ok());
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.linkerbot.cadworld.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||
import com.linkerbot.cadworld.service.InterfaceBrepService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestPart;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin-api/interface-brep")
|
||||
@RequiredArgsConstructor
|
||||
public class InterfaceBrepController {
|
||||
private final InterfaceBrepService service;
|
||||
|
||||
@PostMapping(value = "/analyze", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
public ApiResponse<JsonNode> analyze(@RequestPart("file") MultipartFile file) {
|
||||
return ApiResponse.success(service.analyze(file));
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.linkerbot.cadworld.controller;
|
||||
|
||||
import com.linkerbot.cadworld.audit.AuditOperation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||
import com.linkerbot.cadworld.common.api.PageResponse;
|
||||
import com.linkerbot.cadworld.dto.common.SuccessResponse;
|
||||
import com.linkerbot.cadworld.service.InterfaceDefinitionService;
|
||||
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
|
||||
import java.io.IOException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import org.springframework.web.bind.annotation.RequestPart;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin-api/interfaces")
|
||||
@RequiredArgsConstructor
|
||||
public class InterfaceDefinitionController {
|
||||
private final InterfaceDefinitionService service;
|
||||
private final ObjectStorageClient objectStorageClient;
|
||||
@GetMapping public ApiResponse<List<JsonNode>> list(@RequestParam(required = false) String keyword) { return ApiResponse.success(service.list(keyword)); }
|
||||
@GetMapping("/{id}") public ApiResponse<JsonNode> get(@PathVariable String id) { return ApiResponse.success(service.get(id)); }
|
||||
@AuditOperation(module = "INTERFACE", action = "CREATE")
|
||||
@PostMapping public ApiResponse<JsonNode> create(@RequestBody JsonNode request) { return ApiResponse.success(service.create(request)); }
|
||||
@AuditOperation(module = "INTERFACE", action = "UPDATE")
|
||||
@PutMapping("/{id}") public ApiResponse<JsonNode> update(@PathVariable String id, @RequestBody JsonNode request) { return ApiResponse.success(service.update(id, request)); }
|
||||
@AuditOperation(module = "INTERFACE", action = "DELETE")
|
||||
@DeleteMapping("/{id}") public ApiResponse<SuccessResponse> delete(@PathVariable String id) { service.delete(id); return ApiResponse.success(SuccessResponse.ok()); }
|
||||
|
||||
@AuditOperation(module = "INTERFACE", action = "UPLOAD")
|
||||
@PostMapping("/{id}/assets")
|
||||
public ApiResponse<String> uploadAsset(@PathVariable String id,
|
||||
@RequestParam int geometryRevision,
|
||||
@RequestPart("file") MultipartFile file) throws IOException {
|
||||
if (file == null || file.isEmpty()) throw new IllegalArgumentException("接口源文件不能为空");
|
||||
String name = file.getOriginalFilename() == null ? "source.step" : file.getOriginalFilename().replace('\\', '/');
|
||||
name = name.substring(name.lastIndexOf('/') + 1).replaceAll("[^A-Za-z0-9._-]", "_");
|
||||
if(service.get(id).path("geometryRevision").asInt()!=geometryRevision)throw new IllegalArgumentException("接口已修订,请刷新");
|
||||
String key;
|
||||
{
|
||||
try {
|
||||
byte[] bytes = file.getBytes();
|
||||
String hash = java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
key = "interfaces/" + java.util.HexFormat.of().formatHex(id.getBytes(java.nio.charset.StandardCharsets.UTF_8)) + "/" + geometryRevision + "/" + hash + "/" + name;
|
||||
objectStorageClient.putObject(key, file.getContentType(), new java.io.ByteArrayInputStream(bytes), bytes.length);
|
||||
service.attachAsset(id, geometryRevision, key, "sha256:" + hash);
|
||||
} catch (NoSuchAlgorithmException exception) {
|
||||
throw new IllegalStateException("SHA-256 不可用", exception);
|
||||
}
|
||||
}
|
||||
return ApiResponse.success(key);
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.linkerbot.cadworld.controller;
|
||||
|
||||
import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
|
||||
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||
import com.linkerbot.cadworld.mechanicalinterface.MechanicalInterfaceSolver;
|
||||
import com.linkerbot.cadworld.service.InterfaceDefinitionService;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController @RequiredArgsConstructor
|
||||
@RequestMapping("/admin-api/interfaces/{id}")
|
||||
public class InterfacePoseController {
|
||||
private final InterfaceDefinitionService definitions;
|
||||
private final MechanicalInterfaceSolver solver;
|
||||
private final ObjectMapper objectMapper;
|
||||
@PostMapping("/pose-candidates")
|
||||
public ApiResponse<CandidateSet> candidates(@PathVariable String id,@RequestBody JsonNode body){
|
||||
PoseRequest request=read(body,PoseRequest.class);
|
||||
return ApiResponse.success(solver.enumeratePortPoses(definitions.geometryDefinition(id,request.definitionRevision()),request));
|
||||
}
|
||||
@PostMapping("/confirm-port")
|
||||
public ApiResponse<Port> confirm(@PathVariable String id,@RequestBody JsonNode body){
|
||||
Port request=read(body,Port.class);
|
||||
if(!id.equals(request.definitionId()))throw new IllegalArgumentException("URL 与端口定义不一致");
|
||||
return ApiResponse.success(solver.confirmPortPose(definitions.geometryDefinition(id,request.definitionRevision()),request));
|
||||
}
|
||||
private <T> T read(JsonNode body,Class<T> type){
|
||||
try{return objectMapper.readerFor(type).with(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).readValue(normalizePortBody(body));}
|
||||
catch(java.io.IOException | IllegalArgumentException e){throw new IllegalArgumentException("不支持的接口数据结构:"+rootMessage(e),e);}
|
||||
}
|
||||
private JsonNode normalizePortBody(JsonNode body){
|
||||
if(body==null||!body.isObject())return body;
|
||||
ObjectNode copy=body.deepCopy();JsonNode targets=copy.get("connectableTargets");
|
||||
if(targets!=null&&!targets.isNull()){
|
||||
ArrayNode normalized=objectMapper.createArrayNode();flattenTargets(targets,normalized);copy.set("connectableTargets",normalized);
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
private void flattenTargets(JsonNode node,ArrayNode output){
|
||||
if(node==null||node.isNull())return;
|
||||
if(node.isArray()){
|
||||
boolean path=true;StringBuilder joined=new StringBuilder();
|
||||
for(JsonNode child:node){if(!child.isTextual()){path=false;break;}if(joined.length()>0)joined.append('/');joined.append(child.asText());}
|
||||
if(path){String value=joined.toString().trim();if(!value.isEmpty()&&!containsTarget(output,value))output.add(value);return;}
|
||||
node.forEach(child->flattenTargets(child,output));return;
|
||||
}
|
||||
String value=node.asText("").trim();if(!value.isEmpty()&&!containsTarget(output,value))output.add(value);
|
||||
}
|
||||
private boolean containsTarget(ArrayNode output,String value){for(JsonNode item:output)if(value.equals(item.asText()))return true;return false;}
|
||||
private String rootMessage(Throwable error){Throwable current=error;while(current.getCause()!=null)current=current.getCause();return current.getMessage()==null?"字段格式错误":current.getMessage();}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.linkerbot.cadworld.controller;
|
||||
|
||||
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||
import com.linkerbot.cadworld.common.api.PageResponse;
|
||||
import com.linkerbot.cadworld.entity.OperationLog;
|
||||
import com.linkerbot.cadworld.service.OperationLogService;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import java.time.LocalDateTime;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin-api/operation-logs")
|
||||
@RequiredArgsConstructor
|
||||
@Validated
|
||||
public class OperationLogController {
|
||||
private final OperationLogService service;
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<PageResponse<OperationLog>> list(
|
||||
@RequestParam(defaultValue = "1") @Min(1) long page,
|
||||
@RequestParam(defaultValue = "20") @Min(1) long size,
|
||||
@RequestParam(required = false) String module,
|
||||
@RequestParam(required = false) String action,
|
||||
@RequestParam(required = false) Boolean success,
|
||||
@RequestParam(required = false) Long operatorId,
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime from,
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime to) {
|
||||
return ApiResponse.success(service.list(page, Math.min(size, 100), module, action, success, operatorId, from, to));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ApiResponse<OperationLog> get(@PathVariable Long id) { return ApiResponse.success(service.get(id)); }
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.linkerbot.cadworld.controller;
|
||||
|
||||
import com.linkerbot.cadworld.common.api.ApiResponse;
|
||||
import com.linkerbot.cadworld.common.api.PageResponse;
|
||||
import com.linkerbot.cadworld.dto.common.SuccessResponse;
|
||||
import com.linkerbot.cadworld.dto.user.SaveUserRequest;
|
||||
import com.linkerbot.cadworld.dto.user.UserResponse;
|
||||
import com.linkerbot.cadworld.enums.UserStatus;
|
||||
import com.linkerbot.cadworld.enums.UserType;
|
||||
import com.linkerbot.cadworld.service.UserManagementService;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/admin-api/users")
|
||||
@RequiredArgsConstructor
|
||||
@Validated
|
||||
public class UserManagementController {
|
||||
private final UserManagementService service;
|
||||
|
||||
@GetMapping
|
||||
public ApiResponse<PageResponse<UserResponse>> list(
|
||||
@RequestParam(defaultValue = "1") @Min(1) long page,
|
||||
@RequestParam(defaultValue = "20") @Min(1) long size,
|
||||
@RequestParam(required = false) String keyword,
|
||||
@RequestParam(required = false) UserType userType,
|
||||
@RequestParam(required = false) UserStatus status) {
|
||||
return ApiResponse.success(service.list(page, Math.min(size, 100), keyword, userType, status));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ApiResponse<UserResponse> get(@PathVariable Long id) { return ApiResponse.success(service.get(id)); }
|
||||
|
||||
@PostMapping
|
||||
public ApiResponse<UserResponse> create(@Valid @RequestBody SaveUserRequest request) { return ApiResponse.success(service.create(request)); }
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ApiResponse<UserResponse> update(@PathVariable Long id, @Valid @RequestBody SaveUserRequest request) { return ApiResponse.success(service.update(id, request)); }
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResponse<SuccessResponse> delete(@PathVariable Long id) {
|
||||
service.delete(id);
|
||||
return ApiResponse.success(SuccessResponse.ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: ${APP_DB_URL}
|
||||
username: ${APP_DB_USERNAME}
|
||||
password: ${APP_DB_PASSWORD}
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
hikari:
|
||||
maximum-pool-size: 20
|
||||
|
||||
springdoc:
|
||||
api-docs:
|
||||
enabled: false
|
||||
swagger-ui:
|
||||
enabled: false
|
||||
@@ -0,0 +1,21 @@
|
||||
spring:
|
||||
datasource:
|
||||
url: ${APP_DB_URL:jdbc:mysql://39.105.93.138:3306/cadworld?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai}
|
||||
username: ${APP_DB_USERNAME:}
|
||||
password: ${APP_DB_PASSWORD:}
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
hikari:
|
||||
pool-name: CadworldAdminHikariCP
|
||||
minimum-idle: 1
|
||||
maximum-pool-size: 10
|
||||
connection-timeout: 5000
|
||||
|
||||
springdoc:
|
||||
api-docs:
|
||||
enabled: true
|
||||
swagger-ui:
|
||||
enabled: true
|
||||
|
||||
logging:
|
||||
level:
|
||||
com.linkerbot.cadworld: DEBUG
|
||||
@@ -0,0 +1,71 @@
|
||||
spring:
|
||||
application:
|
||||
name: cadworld-adminapi
|
||||
profiles:
|
||||
default: test
|
||||
sql:
|
||||
init:
|
||||
mode: never
|
||||
servlet:
|
||||
multipart:
|
||||
max-file-size: 100MB
|
||||
max-request-size: 100MB
|
||||
jackson:
|
||||
default-property-inclusion: non_null
|
||||
time-zone: Asia/Shanghai
|
||||
lifecycle:
|
||||
timeout-per-shutdown-phase: 30s
|
||||
|
||||
server:
|
||||
port: ${SERVER_PORT:8992}
|
||||
shutdown: graceful
|
||||
compression:
|
||||
enabled: true
|
||||
min-response-size: 2KB
|
||||
|
||||
mybatis-plus:
|
||||
configuration:
|
||||
map-underscore-to-camel-case: true
|
||||
|
||||
springdoc:
|
||||
api-docs:
|
||||
path: /api-docs
|
||||
swagger-ui:
|
||||
path: /swagger-ui.html
|
||||
|
||||
app:
|
||||
admin:
|
||||
operator:
|
||||
id: ${APP_ADMIN_OPERATOR_ID:0}
|
||||
name: ${APP_ADMIN_OPERATOR_NAME:TEST_OPERATOR}
|
||||
upload-session:
|
||||
issuer: cadworld-upload
|
||||
# Empty means a random, process-local signing key. Set a stable key for restarts/multiple instances.
|
||||
secret: ${APP_UPLOAD_SESSION_SECRET:}
|
||||
storage:
|
||||
provider: ${APP_STORAGE_PROVIDER:minio}
|
||||
urdf-prefix: components/urdf
|
||||
cover-image-prefix: components/cover-images
|
||||
public-api-base-url: ${APP_STORAGE_PUBLIC_API_BASE_URL:http://127.0.0.1:${SERVER_PORT:8992}}
|
||||
public-base-url: ${APP_STORAGE_PUBLIC_BASE_URL:http://127.0.0.1:${SERVER_PORT:8992}/admin-api/component-assets}
|
||||
local-root: ${APP_STORAGE_LOCAL_ROOT:./data/assets}
|
||||
upload-session-ttl: PT30M
|
||||
minio:
|
||||
endpoint: ${APP_MINIO_ENDPOINT:}
|
||||
access-key: ${APP_MINIO_ACCESS_KEY:}
|
||||
secret-key: ${APP_MINIO_SECRET_KEY:}
|
||||
bucket: ${APP_MINIO_BUCKET:}
|
||||
interface-brep:
|
||||
python: ${APP_INTERFACE_BREP_PYTHON:python3}
|
||||
script: ${APP_INTERFACE_BREP_SCRIPT:classpath:scripts/step_brep_topology.py}
|
||||
timeout-seconds: ${APP_INTERFACE_BREP_TIMEOUT_SECONDS:120}
|
||||
max-upload-bytes: ${APP_INTERFACE_BREP_MAX_UPLOAD_BYTES:104857600}
|
||||
max-output-bytes: ${APP_INTERFACE_BREP_MAX_OUTPUT_BYTES:104857600}
|
||||
|
||||
logging:
|
||||
file:
|
||||
path: ${LOG_PATH:logs}
|
||||
level:
|
||||
root: INFO
|
||||
com.linkerbot.cadworld: INFO
|
||||
org.springframework.web: INFO
|
||||
@@ -0,0 +1,183 @@
|
||||
package com.linkerbot.cadworld;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.cadworld.entity.OperationLog;
|
||||
import com.linkerbot.cadworld.service.OperationLogService;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
@SpringBootTest(properties = {
|
||||
"spring.datasource.url=jdbc:h2:mem:admin;MODE=MySQL;DB_CLOSE_DELAY=-1",
|
||||
"spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.username=sa", "spring.datasource.password=",
|
||||
"spring.sql.init.mode=always", "spring.sql.init.schema-locations=classpath:test-schema.sql",
|
||||
"app.storage.provider=local", "app.storage.local-root=target/test-assets", "logging.file.path=target/test-logs"
|
||||
})
|
||||
@ActiveProfiles("verification")
|
||||
@AutoConfigureMockMvc
|
||||
class AdminApiTest {
|
||||
@Autowired MockMvc mvc;
|
||||
@Autowired ObjectMapper json;
|
||||
@Autowired JdbcTemplate jdbc;
|
||||
@Autowired OperationLogService logs;
|
||||
@Autowired TransactionTemplate transactions;
|
||||
|
||||
@BeforeEach
|
||||
void clean() {
|
||||
for (String table : new String[]{"component_asset", "component", "interface_definition_revision", "interface_definition_v2", "sys_user", "sys_operation_log"}) {
|
||||
jdbc.update("DELETE FROM " + table);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void userCrudFiltersAndLogicalDeletionKeepPhoneReserved() throws Exception {
|
||||
JsonNode created = send("/admin-api/users", Map.of("phone", "13812345678", "nickname", "测试用户"));
|
||||
long id = created.path("data").path("id").asLong();
|
||||
assertThat(created.path("data").path("status").asText()).isEqualTo("ACTIVE");
|
||||
assertThat(created.path("data").path("userType").asText()).isEqualTo("NORMAL");
|
||||
mvc.perform(put("/admin-api/users/{id}", id).contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"phone\":\"13812345678\",\"nickname\":\"管理员\",\"status\":\"DISABLED\",\"userType\":\"ADMIN\"}"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.data.userType").value("ADMIN"));
|
||||
mvc.perform(get("/admin-api/users").param("keyword", "管理员").param("userType", "ADMIN").param("status", "DISABLED"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.data.total").value(1));
|
||||
mvc.perform(get("/admin-api/users/{id}", id)).andExpect(status().isOk());
|
||||
mvc.perform(delete("/admin-api/users/{id}", id)).andExpect(status().isOk());
|
||||
mvc.perform(get("/admin-api/users/{id}", id)).andExpect(status().isNotFound());
|
||||
mvc.perform(get("/admin-api/users")).andExpect(jsonPath("$.data.total").value(0));
|
||||
assertThat(jdbc.queryForObject("SELECT deleted FROM sys_user WHERE id=?", Integer.class, id)).isEqualTo(1);
|
||||
mvc.perform(post("/admin-api/users").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"phone\":\"13812345678\",\"nickname\":\"新用户\"}"))
|
||||
.andExpect(status().isConflict()).andExpect(jsonPath("$.code").value("USER_PHONE_DUPLICATE"));
|
||||
assertThat(logCount()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidUserFieldsEnumsAndPaginationAreRejected() throws Exception {
|
||||
for (String body : new String[]{
|
||||
"{\"phone\":\"123\",\"nickname\":\"x\"}",
|
||||
"{\"phone\":\"13812345678\",\"nickname\":\" \"}",
|
||||
"{\"phone\":\"13812345678\",\"nickname\":\"x\",\"status\":\"INVALID\"}",
|
||||
"{\"phone\":\"13812345678\",\"nickname\":\"x\",\"userType\":\"ROOT\"}"}) {
|
||||
mvc.perform(post("/admin-api/users").contentType(MediaType.APPLICATION_JSON).content(body)).andExpect(status().isUnprocessableEntity());
|
||||
}
|
||||
mvc.perform(get("/admin-api/users").param("page", "0")).andExpect(status().isUnprocessableEntity());
|
||||
mvc.perform(get("/admin-api/users").param("size", "0")).andExpect(status().isUnprocessableEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void componentCrudAndEveryFailureAreAuditedButReadsAreExcluded() throws Exception {
|
||||
JsonNode result = send("/admin-api/components", component("sample"));
|
||||
long id = result.path("data").path("id").asLong();
|
||||
assertThat(result.path("data").path("sourceUrl").asText()).contains("/admin-api/component-assets/");
|
||||
mvc.perform(put("/admin-api/components/{id}", id).contentType(MediaType.APPLICATION_JSON).content(json.writeValueAsString(component("renamed"))))
|
||||
.andExpect(status().isOk());
|
||||
mvc.perform(get("/admin-api/components")).andExpect(status().isOk());
|
||||
mvc.perform(get("/admin-api/components/{id}", id)).andExpect(status().isOk());
|
||||
mvc.perform(delete("/admin-api/components/{id}", id)).andExpect(status().isOk());
|
||||
mvc.perform(delete("/admin-api/components/{id}", id)).andExpect(status().isNotFound());
|
||||
mvc.perform(post("/admin-api/components").contentType(MediaType.APPLICATION_JSON).content("{}"))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
mvc.perform(post("/admin-api/components").contentType(MediaType.APPLICATION_JSON).content("{invalid"))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
assertThat(logCount()).isEqualTo(6);
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_operation_log WHERE success=FALSE", Long.class)).isEqualTo(3);
|
||||
mvc.perform(get("/admin-api/operation-logs").param("module", "COMPONENT").param("success", "false").param("operatorId", "0"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.data.total").value(3));
|
||||
Long logId = jdbc.queryForObject("SELECT MIN(id) FROM sys_operation_log", Long.class);
|
||||
mvc.perform(get("/admin-api/operation-logs/{id}", logId)).andExpect(status().isOk()).andExpect(jsonPath("$.data.operatorName").value("TEST_OPERATOR"));
|
||||
assertThat(logCount()).isEqualTo(6);
|
||||
}
|
||||
|
||||
@Test
|
||||
void interfaceRevisionsAndRejectedStaleEditsAreAudited() throws Exception {
|
||||
JsonNode request = json.readTree("""
|
||||
{"id":"mount","name":"安装接口","geometry":{"plane":{"pointM":[0,0,0],"outwardNormal":[0,0,1]},
|
||||
"holes":[{"id":"a","pointOnPlaneM":[-0.02,0,0],"axis":[0,0,1],"diameterM":0.004},
|
||||
{"id":"b","pointOnPlaneM":[0.02,0,0],"axis":[0,0,1],"diameterM":0.004}]},
|
||||
"tolerances":{"positionM":0.0002,"axisAngleRad":0.0174533,"planeAngleRad":0.0174533}}
|
||||
""");
|
||||
JsonNode created = send("/admin-api/interfaces", request).path("data");
|
||||
((com.fasterxml.jackson.databind.node.ObjectNode) created).put("name", "新版");
|
||||
mvc.perform(put("/admin-api/interfaces/mount").contentType(MediaType.APPLICATION_JSON).content(created.toString()))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.data.geometryRevision").value(2));
|
||||
mvc.perform(put("/admin-api/interfaces/mount").contentType(MediaType.APPLICATION_JSON).content(created.toString()))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM interface_definition_revision", Long.class)).isEqualTo(2);
|
||||
mvc.perform(get("/admin-api/interfaces")).andExpect(status().isOk());
|
||||
mvc.perform(delete("/admin-api/interfaces/mount")).andExpect(status().isOk());
|
||||
assertThat(logCount()).isEqualTo(4);
|
||||
// Historical revisions survive deletion and still prohibit ID reuse.
|
||||
mvc.perform(post("/admin-api/interfaces").contentType(MediaType.APPLICATION_JSON).content(request.toString()))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadWorkflowUsesAdminUrlsAndDoesNotStoreToken() throws Exception {
|
||||
JsonNode session = send("/admin-api/components/cover-image-upload-sessions", null).path("data");
|
||||
String token = session.path("uploadSessionToken").asText();
|
||||
JsonNode upload = send("/admin-api/components/cover-image-upload-sessions/upload-url",
|
||||
Map.of("uploadSessionToken", token, "objectPath", "cover.png", "contentType", "image/png")).path("data");
|
||||
assertThat(upload.path("uploadUrl").asText()).contains("/admin-api/component-assets/upload");
|
||||
String key = upload.path("objectKey").asText();
|
||||
mvc.perform(put("/admin-api/component-assets/upload").param("objectKey", key).contentType("image/png").content(new byte[]{1, 2, 3}))
|
||||
.andExpect(status().isNoContent());
|
||||
send("/admin-api/components/cover-image-upload-sessions/complete", Map.of("uploadSessionToken", token, "objectKeys", new String[]{key}));
|
||||
mvc.perform(get("/admin-api/component-assets/" + key)).andExpect(status().isOk()).andExpect(content().bytes(new byte[]{1, 2, 3}));
|
||||
assertThat(logCount()).isEqualTo(4);
|
||||
assertThat(jdbc.queryForList("SELECT * FROM sys_operation_log").toString()).doesNotContain(token);
|
||||
}
|
||||
|
||||
@Test
|
||||
void requiresNewLogSurvivesOuterRollbackAndOldRoutesAreAbsent() throws Exception {
|
||||
transactions.executeWithoutResult(tx -> {
|
||||
jdbc.update("INSERT INTO sys_user(phone,nickname,status,user_type,deleted) VALUES ('13912345678','rollback','ACTIVE','NORMAL',0)");
|
||||
OperationLog event = new OperationLog();
|
||||
event.setModule("COMPONENT"); event.setAction("CREATE"); event.setOperatorId(0L); event.setOperatorName("TEST_OPERATOR");
|
||||
event.setRequestPath("/admin-api/components"); event.setRequestMethod("POST"); event.setOperatedAt(java.time.LocalDateTime.now());
|
||||
event.setDurationMs(1L); event.setSuccess(false); event.setHttpStatus(422);
|
||||
logs.record(event);
|
||||
tx.setRollbackOnly();
|
||||
});
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_user", Long.class)).isZero();
|
||||
assertThat(logCount()).isEqualTo(1);
|
||||
for (String path : new String[]{"/api/interfaces", "/api/components", "/api/component-assets/a", "/api/auth/me", "/api/projects"}) {
|
||||
mvc.perform(get(path)).andExpect(status().isNotFound());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void analysisAndPoseCalculationsAreExcludedFromAudit() throws Exception {
|
||||
mvc.perform(multipart("/admin-api/interface-brep/analyze")
|
||||
.file(new org.springframework.mock.web.MockMultipartFile("file", "bad.stl", "application/octet-stream", new byte[]{1})))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
mvc.perform(post("/admin-api/interfaces/missing/pose-candidates").contentType(MediaType.APPLICATION_JSON).content("{}"))
|
||||
.andExpect(status().isUnprocessableEntity());
|
||||
assertThat(logCount()).isZero();
|
||||
}
|
||||
|
||||
private JsonNode send(String path, Object body) throws Exception {
|
||||
var request = post(path);
|
||||
if (body != null) request.contentType(MediaType.APPLICATION_JSON).content(json.writeValueAsString(body));
|
||||
return json.readTree(mvc.perform(request).andExpect(status().isOk()).andReturn().getResponse().getContentAsString());
|
||||
}
|
||||
|
||||
private Map<String, Object> component(String name) {
|
||||
return Map.of("componentName", name, "robotType", "humanoid", "company", "test", "model", "m1", "source", "components/sample.rfs",
|
||||
"componentJson", Map.of("interfaces", new Object[0]), "assemblyMetadata", Map.of("tags", new String[]{"test"}, "capabilities", new Object[0], "dimensions", Map.of()));
|
||||
}
|
||||
|
||||
private long logCount() { return jdbc.queryForObject("SELECT COUNT(*) FROM sys_operation_log", Long.class); }
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.linkerbot.cadworld;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.sql.DriverManager;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.jdbc.datasource.init.ScriptUtils;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
/** Opt-in integration profile: dedicated disposable MySQL schema and MinIO bucket only. */
|
||||
@SpringBootTest(properties = {
|
||||
"spring.datasource.url=${cadworld.it.db-url:jdbc:mysql://127.0.0.1:13306/cadworld_verification?serverTimezone=Asia/Shanghai}",
|
||||
"spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver",
|
||||
"spring.datasource.username=${cadworld.it.db-user:root}", "spring.datasource.password=${cadworld.it.db-password:}",
|
||||
"spring.sql.init.mode=never", "app.storage.provider=minio",
|
||||
"app.minio.endpoint=${cadworld.it.minio-endpoint:http://127.0.0.1:19000}",
|
||||
"app.minio.access-key=${cadworld.it.minio-user:cadworld-test}", "app.minio.secret-key=${cadworld.it.minio-password:cadworld-test-secret}",
|
||||
"app.minio.bucket=cadworld-verification", "logging.file.path=target/integration-logs"
|
||||
})
|
||||
class ExternalServicesIT extends AdminApiTest {
|
||||
@BeforeAll
|
||||
static void prepareAndVerifySql() throws Exception {
|
||||
String url = System.getProperty("cadworld.it.db-url", "jdbc:mysql://127.0.0.1:13306/cadworld_verification?serverTimezone=Asia/Shanghai");
|
||||
// Refuse accidental execution against the shared cadworld database.
|
||||
if (!url.matches("jdbc:mysql://[^/]+/cadworld_verification(?:\\?.*)?")) {
|
||||
throw new IllegalArgumentException("Integration database must be named cadworld_verification");
|
||||
}
|
||||
Path db = Path.of(System.getProperty("cadworld.project-root", "..")).resolve("db");
|
||||
try (var connection = DriverManager.getConnection(url, System.getProperty("cadworld.it.db-user", "root"), System.getProperty("cadworld.it.db-password", ""));
|
||||
var statement = connection.createStatement()) {
|
||||
statement.execute("DROP TABLE IF EXISTS component_asset, component, interface_definition_revision, interface_definition_v2, sys_operation_log, sys_user");
|
||||
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("init.sql")));
|
||||
statement.executeUpdate("INSERT INTO sys_user(phone,nickname,status,user_type) VALUES ('13800000000','sentinel','ACTIVE','NORMAL')");
|
||||
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("init.sql")));
|
||||
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("upgrade.sql")));
|
||||
try (var result = statement.executeQuery("SELECT COUNT(*) FROM sys_user WHERE nickname='sentinel' AND deleted=0")) {
|
||||
result.next(); assertThat(result.getInt(1)).isEqualTo(1);
|
||||
}
|
||||
// Simulate precisely the supplied pre-upgrade tables while retaining a real user row.
|
||||
statement.execute("DROP TABLE component_asset, interface_definition_revision, interface_definition_v2, sys_operation_log");
|
||||
statement.execute("ALTER TABLE sys_user DROP COLUMN deleted");
|
||||
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("upgrade.sql")));
|
||||
ScriptUtils.executeSqlScript(connection, new FileSystemResource(db.resolve("upgrade.sql")));
|
||||
try (var result = statement.executeQuery("SELECT COUNT(*) FROM sys_user WHERE nickname='sentinel' AND deleted=0")) {
|
||||
result.next(); assertThat(result.getInt(1)).isEqualTo(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.linkerbot.cadworld;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.client.TestRestTemplate;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.util.LinkedMultiValueMap;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, properties = {
|
||||
"spring.datasource.url=jdbc:h2:mem:upload-http;MODE=MySQL;DB_CLOSE_DELAY=-1",
|
||||
"spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.username=sa", "spring.datasource.password=",
|
||||
"spring.sql.init.mode=always", "spring.sql.init.schema-locations=classpath:test-schema.sql",
|
||||
"spring.servlet.multipart.max-file-size=1KB", "spring.servlet.multipart.max-request-size=2KB",
|
||||
"app.storage.provider=local", "app.storage.local-root=target/test-http-assets", "logging.file.path=target/test-logs"
|
||||
})
|
||||
@ActiveProfiles("verification")
|
||||
class UploadHttpTest {
|
||||
@Autowired TestRestTemplate http;
|
||||
@Autowired JdbcTemplate jdbc;
|
||||
|
||||
@Test
|
||||
void realServletMultipartSizeFailureReturns413AndPersistsAudit() {
|
||||
var body = new LinkedMultiValueMap<String, Object>();
|
||||
body.add("file", new ByteArrayResource(new byte[4096]) {
|
||||
@Override public String getFilename() { return "oversize.step"; }
|
||||
});
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
|
||||
var response = http.postForEntity("/admin-api/interfaces/missing/assets?geometryRevision=1", new HttpEntity<>(body, headers), String.class);
|
||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.PAYLOAD_TOO_LARGE);
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM sys_operation_log WHERE module='INTERFACE' AND action='UPLOAD' AND http_status=413 AND success=FALSE AND target_id='missing'", Long.class))
|
||||
.isEqualTo(1);
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package com.linkerbot.cadworld.audit;
|
||||
|
||||
import com.linkerbot.cadworld.config.AdminOperatorProperties;
|
||||
import com.linkerbot.cadworld.service.AdminOperatorProvider;
|
||||
import com.linkerbot.cadworld.service.OperationLogService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class OperationAuditInterceptorTest {
|
||||
@Test
|
||||
void multipartFailureBeforeMvcIsAuditedOnce() throws Exception {
|
||||
OperationLogService service = mock(OperationLogService.class);
|
||||
OperationAuditInterceptor audit = new OperationAuditInterceptor(service, new AdminOperatorProvider(new AdminOperatorProperties(0, "TEST_OPERATOR")));
|
||||
var mappings = mock(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.class);
|
||||
var request = new MockHttpServletRequest("POST", "/admin-api/components");
|
||||
var response = new MockHttpServletResponse();
|
||||
var handler = new HandlerMethod(this, getClass().getDeclaredMethod("operation"));
|
||||
when(mappings.getHandler(request)).thenReturn(new org.springframework.web.servlet.HandlerExecutionChain(handler));
|
||||
var filter = new EarlyFailureAuditFilter(mappings, audit);
|
||||
filter.doFilter(request, response, (req, res) -> ((jakarta.servlet.http.HttpServletResponse) res).setStatus(413));
|
||||
var captured = org.mockito.ArgumentCaptor.forClass(com.linkerbot.cadworld.entity.OperationLog.class);
|
||||
verify(service).record(captured.capture());
|
||||
assertThat(captured.getValue().getSuccess()).isFalse();
|
||||
assertThat(captured.getValue().getHttpStatus()).isEqualTo(413);
|
||||
}
|
||||
|
||||
@Test
|
||||
void logFailureDoesNotChangeTheBusinessResponse() throws Exception {
|
||||
OperationLogService service = mock(OperationLogService.class);
|
||||
doThrow(new IllegalStateException("database unavailable")).when(service).record(any());
|
||||
OperationAuditInterceptor audit = new OperationAuditInterceptor(service, new AdminOperatorProvider(new AdminOperatorProperties(0, "TEST_OPERATOR")));
|
||||
var request = new MockHttpServletRequest("POST", "/admin-api/components");
|
||||
var response = new MockHttpServletResponse();
|
||||
var handler = new HandlerMethod(this, getClass().getDeclaredMethod("operation"));
|
||||
audit.preHandle(request, response, handler);
|
||||
audit.afterCompletion(request, response, handler, null);
|
||||
verify(service).record(any());
|
||||
assertThat(response.getStatus()).isEqualTo(200);
|
||||
}
|
||||
|
||||
@AuditOperation(module = "COMPONENT", action = "CREATE")
|
||||
void operation() { }
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.linkerbot.cadworld.mechanicalinterface;
|
||||
|
||||
import static com.linkerbot.cadworld.mechanicalinterface.InterfaceGeometry.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.linkerbot.cadworld.controller.InterfacePoseController;
|
||||
import com.linkerbot.cadworld.service.InterfaceDefinitionService;
|
||||
import com.linkerbot.cadworld.service.client.ObjectStorageClient;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class InterfaceBoundaryTest {
|
||||
final ObjectMapper mapper=new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
|
||||
final MechanicalInterfaceSolver solver=new MechanicalInterfaceSolver();
|
||||
final MountGeometry geometry=new MountGeometry(new Plane(new double[3],new double[]{0,0,1}),List.of(
|
||||
new Hole("a",new double[]{-.02,0,0},new double[]{0,0,1},.004),
|
||||
new Hole("b",new double[]{.02,0,0},new double[]{0,0,1},.004)));
|
||||
final Definition definition=new Definition("two",1,"two",geometry,Tolerances.defaults());
|
||||
|
||||
@Test void endpointsRejectUnknownRotationEvenWhenGlobalJacksonIgnoresUnknownFields(){
|
||||
InterfaceDefinitionService definitions=mock(InterfaceDefinitionService.class);
|
||||
InterfacePoseController controller=new InterfacePoseController(definitions,solver,mapper);
|
||||
ObjectNode request=mapper.valueToTree(new PoseRequest(1,"base",geometry,"sha"));
|
||||
request.put("mountRotationRpy",0);
|
||||
assertThatThrownBy(()->controller.candidates("two",request)).hasMessageContaining("不支持");
|
||||
verifyNoInteractions(definitions);
|
||||
}
|
||||
@Test void confirmationRecomputesTransformAndMappingFromCandidateId(){
|
||||
PoseCandidate chosen=solver.enumeratePortPoses(definition,new PoseRequest(1,"base",geometry,"sha")).candidates().get(0);
|
||||
Port submitted=new Port("port","base","two",1,geometry,
|
||||
new SelectedPose(chosen.id(),new RigidPose(new double[]{99,99,99},new double[4]),List.of(),chosen.orientationDirectionInLink()),"sha",SOLVER_VERSION);
|
||||
Port confirmed=solver.confirmPortPose(definition,submitted);
|
||||
assertThat(confirmed.selectedPose().templateInLink().positionM()).containsExactly(chosen.templateInLink().positionM());
|
||||
assertThat(confirmed.selectedPose().holeMapping()).isEqualTo(chosen.holeMapping());
|
||||
InterfaceDefinitionService definitions=mock(InterfaceDefinitionService.class);
|
||||
assertThatThrownBy(()->new InterfacePoseController(definitions,solver,mapper).confirm("another",mapper.valueToTree(submitted)))
|
||||
.hasMessageContaining("不一致");
|
||||
}
|
||||
@Test void confirmFlattensCascaderPathTargetsBeforeStrictPortBinding(){
|
||||
PoseCandidate chosen=solver.enumeratePortPoses(definition,new PoseRequest(1,"base",geometry,"sha")).candidates().get(0);
|
||||
ObjectNode request=mapper.valueToTree(new Port("port","base","two",1,geometry,
|
||||
new SelectedPose(chosen.id(),chosen.templateInLink(),chosen.holeMapping(),chosen.orientationDirectionInLink()),"sha",SOLVER_VERSION,
|
||||
List.of("humanoid/left_arm")));
|
||||
request.set("connectableTargets",mapper.createArrayNode().add(mapper.createArrayNode().add("humanoid").add("left_arm")));
|
||||
InterfaceDefinitionService definitions=mock(InterfaceDefinitionService.class);
|
||||
when(definitions.geometryDefinition("two",1)).thenReturn(definition);
|
||||
Port confirmed=new InterfacePoseController(definitions,solver,mapper).confirm("two",request).getData();
|
||||
assertThat(confirmed.connectableTargets()).containsExactly("humanoid/left_arm");
|
||||
}
|
||||
@Test void storedBytesAreVerifiedAndUnsafeStorageKeysNeverFetched() throws Exception {
|
||||
byte[] bytes="real mesh bytes".getBytes(StandardCharsets.UTF_8);
|
||||
String hash=HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
ObjectStorageClient storage=mock(ObjectStorageClient.class);
|
||||
doAnswer(invocation->{invocation.<OutputStream>getArgument(1).write(bytes);return null;}).when(storage).writeObjectTo(eq("objects/mesh"),any());
|
||||
UrdfAssetVerifier verifier=new UrdfAssetVerifier(storage);
|
||||
ObjectNode source=mapper.createObjectNode();source.putArray("resources").addObject().put("reference","a.stl").put("sourceKey","objects/mesh").put("sha256",hash);
|
||||
verifier.verify(source);
|
||||
((ObjectNode)source.path("resources").get(0)).put("sha256","tampered");
|
||||
assertThatThrownBy(()->verifier.verify(source)).hasMessageContaining("已变化");
|
||||
clearInvocations(storage);
|
||||
for(String key:List.of("https://remote.test/a","/etc/passwd","objects/../secret","objects\\secret")) {
|
||||
((ObjectNode)source.path("resources").get(0)).put("sourceKey",key);
|
||||
assertThatThrownBy(()->verifier.verify(source)).hasMessageContaining("存储对象");
|
||||
}
|
||||
verifyNoInteractions(storage);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
-- Run against a selected empty cadworld database. No database is created or selected here.
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `sys_user` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`phone` varchar(32) NOT NULL,
|
||||
`nickname` varchar(64) NOT NULL,
|
||||
`status` varchar(32) NOT NULL DEFAULT 'ACTIVE',
|
||||
`deleted` tinyint NOT NULL DEFAULT 0,
|
||||
`user_type` varchar(32) NOT NULL DEFAULT 'NORMAL',
|
||||
`created_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
`updated_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_sys_user_phone` (`phone`)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `component` (
|
||||
`id` bigint NOT NULL AUTO_INCREMENT,
|
||||
`component_name` varchar(64) NOT NULL DEFAULT '',
|
||||
`category` varchar(64) NOT NULL,
|
||||
`robot_type` varchar(32) NOT NULL DEFAULT 'humanoid',
|
||||
`company` varchar(64) NOT NULL DEFAULT '',
|
||||
`model` varchar(64) NOT NULL DEFAULT '',
|
||||
`source` varchar(255) NOT NULL DEFAULT '',
|
||||
`cover_image_key` varchar(512) NOT NULL DEFAULT '',
|
||||
`description` text NOT NULL,
|
||||
`component_json` LONGTEXT NOT NULL,
|
||||
`assembly_metadata` LONGTEXT NOT NULL,
|
||||
`created_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
`updated_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_component_type_company` (`category`,`company`),
|
||||
KEY `idx_component_type_model` (`category`,`model`),
|
||||
KEY `idx_component_robot_type_component_type` (`robot_type`,`category`)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS interface_definition_v2 (
|
||||
id VARCHAR(64) NOT NULL PRIMARY KEY,
|
||||
name VARCHAR(128) NOT NULL,
|
||||
description VARCHAR(500) NULL,
|
||||
geometry_revision INT NOT NULL,
|
||||
geometry_json LONGTEXT NOT NULL,
|
||||
tolerances_json LONGTEXT NOT NULL,
|
||||
connectable_targets_json LONGTEXT NULL,
|
||||
display_forward_json LONGTEXT NULL,
|
||||
source_asset_key VARCHAR(512) NULL,
|
||||
source_geometry_hash VARCHAR(128) NULL,
|
||||
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS interface_definition_revision (
|
||||
id VARCHAR(96) NOT NULL PRIMARY KEY,
|
||||
definition_id VARCHAR(64) NOT NULL,
|
||||
geometry_revision INT NOT NULL,
|
||||
definition_json LONGTEXT NOT NULL,
|
||||
UNIQUE KEY uk_interface_geometry_revision (definition_id, geometry_revision)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS component_asset (
|
||||
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
component_id BIGINT NOT NULL,
|
||||
object_key VARCHAR(512) NOT NULL,
|
||||
relative_path VARCHAR(512) NOT NULL,
|
||||
asset_kind VARCHAR(32) NOT NULL,
|
||||
content_type VARCHAR(128) NULL,
|
||||
size BIGINT NOT NULL DEFAULT 0,
|
||||
sha256 VARCHAR(128) NULL,
|
||||
is_primary TINYINT NOT NULL DEFAULT 0,
|
||||
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
|
||||
CONSTRAINT fk_component_asset_component FOREIGN KEY (component_id) REFERENCES component(id) ON DELETE CASCADE,
|
||||
UNIQUE KEY uk_component_asset_object_key (object_key),
|
||||
KEY idx_component_asset_component (component_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sys_operation_log (
|
||||
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
module VARCHAR(32) NOT NULL,
|
||||
action VARCHAR(32) NOT NULL,
|
||||
target_id VARCHAR(512) NULL,
|
||||
operator_id BIGINT NOT NULL,
|
||||
operator_name VARCHAR(64) NOT NULL,
|
||||
request_path VARCHAR(512) NOT NULL,
|
||||
request_method VARCHAR(16) NOT NULL,
|
||||
client_ip VARCHAR(64) NULL,
|
||||
request_id VARCHAR(64) NULL,
|
||||
operated_at DATETIME(3) NOT NULL,
|
||||
duration_ms BIGINT NOT NULL,
|
||||
success TINYINT NOT NULL,
|
||||
http_status INT NOT NULL,
|
||||
error_summary VARCHAR(1000) NULL,
|
||||
KEY idx_operation_module_time (module, operated_at),
|
||||
KEY idx_operation_operator_time (operator_id, operated_at),
|
||||
KEY idx_operation_result_time (success, operated_at)
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user