"""Generate explicit scanner controller routes from the backend operation registry.""" from pathlib import Path import re ROOT = Path(__file__).resolve().parents[1] SOURCE = ROOT / 'am-backend/yudao-module-cmvr/src/main/java/com/cmvr/scanner/ScannerOperation.java' TARGET = ROOT / 'am-backend/yudao-module-cmvr/src/main/java/com/cmvr/web/controller/scanner/ScannerController.java' def operations(): return re.findall(r'^ (\w+)\("(GET|POST)", "([^"]+)", "([^"]+)", (?:"([^"]+)"|null)\)', SOURCE.read_text(encoding='utf-8'), re.M) def replace_scanner_actions(source, action_lines): return re.sub(r' SCANNER_(?!SUPPLEMENT_)\w+\(.*?(?= SCANNER_SUPPLEMENT_PREPARE\(| MOTOR_\w+\()', action_lines, source, flags=re.S) def main(): enums = ROOT / 'am-backend/yudao-module-cmvr/src/main/java/com/cmvr/test/enums/ActionEnum.java' source = enums.read_text(encoding='utf-8') action_lines = ''.join(f' {action}("EDGE", "{action}", "{title}"),\n' for name, method, path, title, action in operations() if action) source = replace_scanner_actions(source, action_lines) enums.write_text(source, encoding='utf-8') methods=[] for name, method, path, title, action in operations(): suffix = '/metadata' if path == '/' else path.removeprefix('/api/v1') java_name = ('get' if method == 'GET' else 'post') + ''.join(p.title() for p in name.lower().split('_')) annotation = f' @ApiOperation("{title}")\n @{method.title()}Mapping("{suffix}")\n' if name == 'FRAMEWORK_UPLOAD': methods.append(annotation + ' @PreAuthorize("@ss.hasPermission(\'lab:execution:dispatch\')")\n' + ' public AjaxResult postFrameworkUpload(@RequestHeader("X-File-Name") String name, jakarta.servlet.http.HttpServletRequest request) throws java.io.IOException {\n' + ' return success(framework.upload(name, request.getContentType(), request.getContentLengthLong(), request.getInputStream()));\n }\n') elif method == 'POST': methods.append(annotation + ' @PreAuthorize("@ss.hasPermission(\'lab:execution:dispatch\')")\n' + f' public AjaxResult {java_name}(@RequestBody String body, @RequestHeader("X-Scanner-Command-Key") String commandKey) {{\n' + f' return success(access.submit(ScannerOperation.{name}, body, commandKey));\n }}\n') elif name in ('PREVIEW_IMAGE','PREVIEW_STREAM','FILE'): args='@PathVariable String fileId' if name=='FILE' else '' identity='fileId' if name=='FILE' else 'null' methods.append(annotation+f' public ResponseEntity {java_name}({args}) {{ return binary(ScannerOperation.{name}, {identity}); }}\n') else: args='@PathVariable String taskId' if name=='TASK' else '' identity='taskId' if name=='TASK' else 'null' methods.append(annotation+f' public AjaxResult {java_name}({args}) {{ return success(scanner.get(ScannerOperation.{name}, {identity})); }}\n') header='''package com.cmvr.web.controller.scanner; import com.cmvr.common.core.controller.BaseController; import com.cmvr.common.core.domain.AjaxResult; import com.cmvr.scanner.*; import io.swagger.annotations.*; import lombok.RequiredArgsConstructor; import org.springframework.http.*; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; import java.util.*; /** Explicit supplier routes. Generated by scripts/generate_scanner_routes.py. */ @Api(tags = "扫描仪接口") @RestController @RequestMapping("/admin-api/cmvr/scanner") @PreAuthorize("@ss.hasPermission('lab:resource:query')") @RequiredArgsConstructor public class ScannerController extends BaseController { private final ScannerService scanner; private final ScannerAccessService access; private final ScannerFrameworkService framework; @GetMapping("/configuration") public AjaxResult getConfiguration() { return success(scanner.configuration()); } @GetMapping("/commands/{commandKey}") public AjaxResult getCommand(@PathVariable String commandKey) { return success(scanner.command(commandKey)); } @PostMapping("/validate") public AjaxResult validateParameters(@RequestBody String source) { var input = ScannerRequestValidator.parse(source); ScannerOperation operation; try { operation = ScannerOperation.valueOf(input.path("operation").asText()); } catch (IllegalArgumentException error) { throw new ScannerException("invalid_operation", "扫描操作不存在", 400); } if (input.has("requestJson") && !input.get("requestJson").isTextual()) throw new ScannerException("invalid_request", "requestJson必须是JSON对象的字符串", 400); if(operation==ScannerOperation.FRAMEWORK_IMPORT && input.has("frameworkUrls")) framework.validateReferences(input.path("requestJson").asText("{}"),input.get("frameworkUrls")); else if(input.has("requestFieldDefinitions")) ScannerRequestComposer.validateApiDefinition(operation,input.path("requestJson").asText("{}"),input.get("requestFieldDefinitions")); else if(input.has("requestFieldNames")) ScannerRequestComposer.validateTemplate(operation,input.path("requestJson").asText("{}"),input.get("requestFieldNames")); else ScannerRequestValidator.validate(operation, ScannerRequestValidator.parse(input.path("requestJson").asText("{}"))); return success(true); } ''' tail=''' private ResponseEntity binary(ScannerOperation operation, String id) { var source = scanner.binary(operation, id); HttpHeaders headers = new HttpHeaders(); headers.setCacheControl("no-store"); source.headers().forEach((key, values) -> { if (key.equalsIgnoreCase("content-type") || key.equalsIgnoreCase("content-length") || key.equalsIgnoreCase("content-disposition") || key.toLowerCase(Locale.ROOT).startsWith("x-frame-")) { if (!values.isEmpty()) headers.put(key, values); } }); return ResponseEntity.ok().headers(headers).body(output -> { try (source) { byte[] buffer = new byte[16384]; int count; while ((count = source.stream().read(buffer)) != -1) { output.write(buffer, 0, count); if (operation == ScannerOperation.PREVIEW_STREAM) output.flush(); } } }); } @ExceptionHandler(ScannerException.class) public AjaxResult scannerError(ScannerException error) { AjaxResult result = AjaxResult.error(error.remoteStatus, error.getMessage()); result.put("scannerCode", error.scannerCode); return result; } } ''' TARGET.write_text(header+'\n'.join(methods)+'\n'+tail,encoding='utf-8') print(f'Generated {len(methods)} explicit supplier routes') if __name__ == '__main__': main()