This commit is contained in:
Anthony Stirling 2023-12-31 13:34:35 +00:00
parent d83bd1ae94
commit 39045df785
5 changed files with 201 additions and 194 deletions

View file

@ -102,8 +102,9 @@ public class SecurityConfiguration {
|| trimmedUri.startsWith("/images/") || trimmedUri.startsWith("/images/")
|| trimmedUri.startsWith("/public/") || trimmedUri.startsWith("/public/")
|| trimmedUri.startsWith("/css/") || trimmedUri.startsWith("/css/")
|| trimmedUri.startsWith("/js/") || || trimmedUri.startsWith("/js/")
trimmedUri.startsWith("/api/v1/info/status"); || trimmedUri.startsWith(
"/api/v1/info/status");
}) })
.permitAll() .permitAll()
.anyRequest() .anyRequest()

View file

@ -95,16 +95,16 @@ public class UserAuthenticationFilter extends OncePerRequestFilter {
String uri = request.getRequestURI(); String uri = request.getRequestURI();
String contextPath = request.getContextPath(); String contextPath = request.getContextPath();
String[] permitAllPatterns = { String[] permitAllPatterns = {
contextPath + "/login", contextPath + "/login",
contextPath + "/register", contextPath + "/register",
contextPath + "/error", contextPath + "/error",
contextPath + "/images/", contextPath + "/images/",
contextPath + "/public/", contextPath + "/public/",
contextPath + "/css/", contextPath + "/css/",
contextPath + "/js/", contextPath + "/js/",
contextPath + "/pdfjs/", contextPath + "/pdfjs/",
contextPath + "/api/v1/info/status", contextPath + "/api/v1/info/status",
contextPath + "/site.webmanifest" contextPath + "/site.webmanifest"
}; };
for (String pattern : permitAllPatterns) { for (String pattern : permitAllPatterns) {

View file

@ -49,145 +49,153 @@ public class PipelineProcessor {
@Autowired(required = false) @Autowired(required = false)
private UserServiceInterface userService; private UserServiceInterface userService;
@Autowired @Autowired private ServletContext servletContext;
private ServletContext servletContext;
private String getApiKeyForUser() {
if (userService == null) return "";
return userService.getApiKeyForUser(Role.INTERNAL_API_USER.getRoleId());
}
private String getBaseUrl() {
String contextPath = servletContext.getContextPath();
String port = SPdfApplication.getPort();
private String getApiKeyForUser() { return "http://localhost:" + port + contextPath + "/";
if (userService == null) }
return "";
return userService.getApiKeyForUser(Role.INTERNAL_API_USER.getRoleId());
}
List<Resource> runPipelineAgainstFiles(List<Resource> outputFiles, PipelineConfig config)
throws Exception {
private String getBaseUrl() { ByteArrayOutputStream logStream = new ByteArrayOutputStream();
String contextPath = servletContext.getContextPath(); PrintStream logPrintStream = new PrintStream(logStream);
String port = SPdfApplication.getPort();
return "http://localhost:" + port + contextPath + "/"; boolean hasErrors = false;
}
for (PipelineOperation pipelineOperation : config.getOperations()) {
String operation = pipelineOperation.getOperation();
List<Resource> runPipelineAgainstFiles(List<Resource> outputFiles, PipelineConfig config) throws Exception { boolean isMultiInputOperation = apiDocService.isMultiInput(operation);
ByteArrayOutputStream logStream = new ByteArrayOutputStream(); logger.info(
PrintStream logPrintStream = new PrintStream(logStream); "Running operation: {} isMultiInputOperation {}",
operation,
isMultiInputOperation);
Map<String, Object> parameters = pipelineOperation.getParameters();
String inputFileExtension = "";
boolean hasErrors = false; // TODO
// if (operationNode.has("inputFileType")) {
// inputFileExtension = operationNode.get("inputFileType").asText();
// } else {
inputFileExtension = ".pdf";
// }
final String finalInputFileExtension = inputFileExtension;
for (PipelineOperation pipelineOperation : config.getOperations()) { String url = getBaseUrl() + operation;
String operation = pipelineOperation.getOperation();
boolean isMultiInputOperation = apiDocService.isMultiInput(operation);
logger.info("Running operation: {} isMultiInputOperation {}", operation, isMultiInputOperation); List<Resource> newOutputFiles = new ArrayList<>();
Map<String, Object> parameters = pipelineOperation.getParameters(); if (!isMultiInputOperation) {
String inputFileExtension = ""; for (Resource file : outputFiles) {
boolean hasInputFileType = false;
//TODO if (file.getFilename().endsWith(inputFileExtension)) {
//if (operationNode.has("inputFileType")) { hasInputFileType = true;
// inputFileExtension = operationNode.get("inputFileType").asText(); MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
//} else { body.add("fileInput", file);
inputFileExtension = ".pdf";
//}
final String finalInputFileExtension = inputFileExtension;
String url = getBaseUrl() + operation;
List<Resource> newOutputFiles = new ArrayList<>();
if (!isMultiInputOperation) {
for (Resource file : outputFiles) {
boolean hasInputFileType = false;
if (file.getFilename().endsWith(inputFileExtension)) {
hasInputFileType = true;
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
body.add("fileInput", file);
for (Entry<String, Object> entry : parameters.entrySet()) {
for(Entry<String, Object> entry : parameters.entrySet()) { body.add(entry.getKey(), entry.getValue());
body.add(entry.getKey(), entry.getValue()); }
}
ResponseEntity<byte[]> response = sendWebRequest(url, body); ResponseEntity<byte[]> response = sendWebRequest(url, body);
// If the operation is filter and the response body is null or empty, skip this // If the operation is filter and the response body is null or empty, skip
// file // this
if (operation.startsWith("filter-") // file
&& (response.getBody() == null || response.getBody().length == 0)) { if (operation.startsWith("filter-")
logger.info("Skipping file due to failing {}", operation); && (response.getBody() == null || response.getBody().length == 0)) {
continue; logger.info("Skipping file due to failing {}", operation);
} continue;
}
if (!response.getStatusCode().equals(HttpStatus.OK)) { if (!response.getStatusCode().equals(HttpStatus.OK)) {
logPrintStream.println("Error: " + response.getBody()); logPrintStream.println("Error: " + response.getBody());
hasErrors = true; hasErrors = true;
continue; continue;
} }
processOutputFiles(operation, file.getFilename(), response, newOutputFiles); processOutputFiles(operation, file.getFilename(), response, newOutputFiles);
}
}
if (!hasInputFileType) { if (!hasInputFileType) {
logPrintStream.println( logPrintStream.println(
"No files with extension " + inputFileExtension + " found for operation " + operation); "No files with extension "
hasErrors = true; + inputFileExtension
} + " found for operation "
+ operation);
hasErrors = true;
}
}
} else {
} // Filter and collect all files that match the inputFileExtension
List<Resource> matchingFiles =
outputFiles.stream()
.filter(
file ->
file.getFilename()
.endsWith(finalInputFileExtension))
.collect(Collectors.toList());
} else { // Check if there are matching files
// Filter and collect all files that match the inputFileExtension if (!matchingFiles.isEmpty()) {
List<Resource> matchingFiles = outputFiles.stream() // Create a new MultiValueMap for the request body
.filter(file -> file.getFilename().endsWith(finalInputFileExtension)) MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
.collect(Collectors.toList());
// Check if there are matching files // Add all matching files to the body
if (!matchingFiles.isEmpty()) { for (Resource file : matchingFiles) {
// Create a new MultiValueMap for the request body body.add("fileInput", file);
MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(); }
// Add all matching files to the body for (Entry<String, Object> entry : parameters.entrySet()) {
for (Resource file : matchingFiles) { body.add(entry.getKey(), entry.getValue());
body.add("fileInput", file); }
}
for(Entry<String, Object> entry : parameters.entrySet()) { ResponseEntity<byte[]> response = sendWebRequest(url, body);
body.add(entry.getKey(), entry.getValue());
}
ResponseEntity<byte[]> response = sendWebRequest(url, body);
// Handle the response // Handle the response
if (response.getStatusCode().equals(HttpStatus.OK)) { if (response.getStatusCode().equals(HttpStatus.OK)) {
processOutputFiles(operation, matchingFiles.get(0).getFilename(), response, newOutputFiles); processOutputFiles(
} else { operation,
// Log error if the response status is not OK matchingFiles.get(0).getFilename(),
logPrintStream.println("Error in multi-input operation: " + response.getBody()); response,
hasErrors = true; newOutputFiles);
} } else {
} else { // Log error if the response status is not OK
logPrintStream.println("No files with extension " + inputFileExtension + " found for multi-input operation " + operation); logPrintStream.println(
hasErrors = true; "Error in multi-input operation: " + response.getBody());
} hasErrors = true;
} }
logPrintStream.close(); } else {
outputFiles = newOutputFiles; logPrintStream.println(
"No files with extension "
+ inputFileExtension
+ " found for multi-input operation "
+ operation);
hasErrors = true;
}
}
logPrintStream.close();
outputFiles = newOutputFiles;
}
if (hasErrors) {
logger.error("Errors occurred during processing. Log: {}", logStream.toString());
}
} return outputFiles;
if (hasErrors) { }
logger.error("Errors occurred during processing. Log: {}", logStream.toString());
}
return outputFiles;
}
private ResponseEntity<byte[]> sendWebRequest(String url, MultiValueMap<String, Object> body ){ private ResponseEntity<byte[]> sendWebRequest(String url, MultiValueMap<String, Object> body) {
RestTemplate restTemplate = new RestTemplate(); RestTemplate restTemplate = new RestTemplate();
// Set up headers, including API key // Set up headers, including API key
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
String apiKey = getApiKeyForUser(); String apiKey = getApiKeyForUser();

View file

@ -33,67 +33,66 @@ import io.swagger.v3.oas.annotations.tags.Tag;
@Tag(name = "General", description = "General APIs") @Tag(name = "General", description = "General APIs")
public class GeneralWebController { public class GeneralWebController {
@GetMapping("/pipeline")
@GetMapping("/pipeline") @Hidden
@Hidden public String pipelineForm(Model model) {
public String pipelineForm(Model model) { model.addAttribute("currentPage", "pipeline");
model.addAttribute("currentPage", "pipeline");
List<String> pipelineConfigs = new ArrayList<>(); List<String> pipelineConfigs = new ArrayList<>();
List<Map<String, String>> pipelineConfigsWithNames = new ArrayList<>(); List<Map<String, String>> pipelineConfigsWithNames = new ArrayList<>();
if(new File("./pipeline/defaultWebUIConfigs/").exists()) {
try (Stream<Path> paths = Files.walk(Paths.get("./pipeline/defaultWebUIConfigs/"))) {
List<Path> jsonFiles = paths
.filter(Files::isRegularFile)
.filter(p -> p.toString().endsWith(".json"))
.collect(Collectors.toList());
for (Path jsonFile : jsonFiles) {
String content = Files.readString(jsonFile, StandardCharsets.UTF_8);
pipelineConfigs.add(content);
}
for (String config : pipelineConfigs) {
Map<String, Object> jsonContent = new ObjectMapper().readValue(config, new TypeReference<Map<String, Object>>(){});
String name = (String) jsonContent.get("name");
if(name == null || name.length() < 1) {
String filename = jsonFiles.get(pipelineConfigs.indexOf(config)).getFileName().toString();
name = filename.substring(0, filename.lastIndexOf('.'));
}
Map<String, String> configWithName = new HashMap<>();
System.out.println("json" + config);
System.out.println("name" + name);
configWithName.put("json", config);
configWithName.put("name", name);
pipelineConfigsWithNames.add(configWithName);
}
} catch (IOException e) {
e.printStackTrace();
}
}
if(pipelineConfigsWithNames.size() == 0) {
Map<String, String> configWithName = new HashMap<>();
configWithName.put("json", "");
configWithName.put("name", "No preloaded configs found");
pipelineConfigsWithNames.add(configWithName);
}
model.addAttribute("pipelineConfigsWithNames", pipelineConfigsWithNames);
model.addAttribute("pipelineConfigs", pipelineConfigs); if (new File("./pipeline/defaultWebUIConfigs/").exists()) {
try (Stream<Path> paths = Files.walk(Paths.get("./pipeline/defaultWebUIConfigs/"))) {
List<Path> jsonFiles =
paths.filter(Files::isRegularFile)
.filter(p -> p.toString().endsWith(".json"))
.collect(Collectors.toList());
return "pipeline"; for (Path jsonFile : jsonFiles) {
} String content = Files.readString(jsonFile, StandardCharsets.UTF_8);
pipelineConfigs.add(content);
}
for (String config : pipelineConfigs) {
Map<String, Object> jsonContent =
new ObjectMapper()
.readValue(config, new TypeReference<Map<String, Object>>() {});
String name = (String) jsonContent.get("name");
if (name == null || name.length() < 1) {
String filename =
jsonFiles
.get(pipelineConfigs.indexOf(config))
.getFileName()
.toString();
name = filename.substring(0, filename.lastIndexOf('.'));
}
Map<String, String> configWithName = new HashMap<>();
System.out.println("json" + config);
System.out.println("name" + name);
configWithName.put("json", config);
configWithName.put("name", name);
pipelineConfigsWithNames.add(configWithName);
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (pipelineConfigsWithNames.size() == 0) {
Map<String, String> configWithName = new HashMap<>();
configWithName.put("json", "");
configWithName.put("name", "No preloaded configs found");
pipelineConfigsWithNames.add(configWithName);
}
model.addAttribute("pipelineConfigsWithNames", pipelineConfigsWithNames);
model.addAttribute("pipelineConfigs", pipelineConfigs);
return "pipeline";
}
@GetMapping("/merge-pdfs") @GetMapping("/merge-pdfs")
@Hidden @Hidden
public String mergePdfForm(Model model) { public String mergePdfForm(Model model) {

View file

@ -2,15 +2,14 @@ package stirling.software.SPDF.utils;
public class RequestUriUtils { public class RequestUriUtils {
public static boolean isStaticResource(String requestURI) { public static boolean isStaticResource(String requestURI) {
return requestURI.startsWith("/css/") return requestURI.startsWith("/css/")
|| requestURI.startsWith("/js/") || requestURI.startsWith("/js/")
|| requestURI.startsWith("/images/") || requestURI.startsWith("/images/")
|| requestURI.startsWith("/public/") || requestURI.startsWith("/public/")
|| requestURI.startsWith("/pdfjs/") || requestURI.startsWith("/pdfjs/")
|| requestURI.endsWith(".svg") || requestURI.endsWith(".svg")
|| requestURI.startsWith("/api/v1/info/status"); || requestURI.startsWith("/api/v1/info/status");
} }
} }