MNT-24883 adding source file name to transform options

Added source file name to transform options if exist in nodeService. It will be used in ATS to maintain consistency in transform for filenames.
This commit is contained in:
bsayan2
2025-06-17 14:13:41 +05:30
committed by GitHub
parent b800c86a7c
commit 81c47c2b04
12 changed files with 706 additions and 494 deletions

View File

@@ -2,7 +2,7 @@
* #%L
* Alfresco Transform Core
* %%
* Copyright (C) 2005 - 2023 Alfresco Software Limited
* Copyright (C) 2005 - 2025 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* -
@@ -26,16 +26,16 @@
*/
package org.alfresco.transform.base.fs;
import org.alfresco.transform.base.logging.LogEntry;
import org.alfresco.transform.common.ExtensionService;
import org.alfresco.transform.exceptions.TransformException;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static org.springframework.http.HttpHeaders.CONTENT_DISPOSITION;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.INSUFFICIENT_STORAGE;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.util.StringUtils.getFilename;
import static org.alfresco.transform.common.ExtensionService.getExtensionForMimetype;
import jakarta.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@@ -43,14 +43,19 @@ import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Files;
import java.util.UUID;
import jakarta.servlet.http.HttpServletRequest;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static org.alfresco.transform.common.ExtensionService.getExtensionForMimetype;
import static org.springframework.http.HttpHeaders.CONTENT_DISPOSITION;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.INSUFFICIENT_STORAGE;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.util.StringUtils.getFilename;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;
import org.alfresco.transform.base.logging.LogEntry;
import org.alfresco.transform.common.ExtensionService;
import org.alfresco.transform.exceptions.TransformException;
public class FileManager
{
@@ -58,16 +63,19 @@ public class FileManager
public static final String TARGET_FILE = "targetFile";
private FileManager()
{
}
{}
public static File createSourceFile(HttpServletRequest request, InputStream inputStream, String sourceMimetype)
public static File createSourceFile(HttpServletRequest request, InputStream inputStream, String sourceMimetype, String sourceFileName)
{
try
{
String extension = "."+getExtensionForMimetype(sourceMimetype);
File file = TempFileProvider.createTempFile("source_", extension);
String extension = "." + getExtensionForMimetype(sourceMimetype);
File file = StringUtils.isEmpty(sourceFileName)
? TempFileProvider.createTempFile("source_", extension)
: TempFileProvider.createFileWithinUUIDTempDir(sourceFileName);
Files.copy(inputStream, file.toPath(), REPLACE_EXISTING);
if (request != null)
{
request.setAttribute(SOURCE_FILE, file);
@@ -85,7 +93,7 @@ public class FileManager
{
try
{
String extension = "."+ExtensionService.getExtensionForTargetMimetype(targetMimetype, sourceMimetype);
String extension = "." + ExtensionService.getExtensionForTargetMimetype(targetMimetype, sourceMimetype);
File file = TempFileProvider.createTempFile("target_", extension);
if (request != null)
{
@@ -120,20 +128,20 @@ public class FileManager
else
{
throw new TransformException(INTERNAL_SERVER_ERROR,
"Could not read the target file: " + file.getPath());
"Could not read the target file: " + file.getPath());
}
}
catch (MalformedURLException e)
{
throw new TransformException(INTERNAL_SERVER_ERROR,
"The target filename was malformed: " + file.getPath(), e);
"The target filename was malformed: " + file.getPath(), e);
}
}
public static InputStream getMultipartFileInputStream(MultipartFile sourceMultipartFile)
{
InputStream inputStream;
if (sourceMultipartFile == null)
if (sourceMultipartFile == null)
{
throw new TransformException(BAD_REQUEST, "Required request part 'file' is not present");
}
@@ -192,7 +200,7 @@ public class FileManager
// targetFilename should never be null (will be "transform."+<something>), so we should not worry about encodePath(null)
targetFilename = UriUtils.encodePath(getFilename(targetFilename), "UTF-8");
return ResponseEntity.ok().header(CONTENT_DISPOSITION,
"attachment; filename*=UTF-8''" + targetFilename).body(targetResource);
"attachment; filename*=UTF-8''" + targetFilename).body(targetResource);
}
/**
@@ -201,8 +209,7 @@ public class FileManager
public static class TempFileProvider
{
private TempFileProvider()
{
}
{}
public static File createTempFile(final String prefix, final String suffix)
{
@@ -214,11 +221,22 @@ public class FileManager
catch (IOException e)
{
throw new RuntimeException(
"Failed to created temp file: \n prefix: " + prefix +
"\n suffix: " + suffix + "\n directory: " + directory, e);
"Failed to created temp file: \n prefix: " + prefix +
"\n suffix: " + suffix + "\n directory: " + directory,
e);
}
}
public static File createFileWithinUUIDTempDir(String sourceFileName)
{
File tempDir = new File(getTempDir(), UUID.randomUUID().toString());
if (!tempDir.mkdirs() && !tempDir.exists())
{
throw new TransformException(INSUFFICIENT_STORAGE, "Failed to create temp directory: " + tempDir);
}
return new File(tempDir, sourceFileName);
}
private static File getTempDir()
{
final String dirName = "Alfresco";

View File

@@ -2,7 +2,7 @@
* #%L
* Alfresco Transform Core
* %%
* Copyright (C) 2022 - 2023 Alfresco Software Limited
* Copyright (C) 2022 - 2025 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* -
@@ -26,19 +26,12 @@
*/
package org.alfresco.transform.base.transform;
import org.alfresco.transform.base.CustomTransformer;
import org.alfresco.transform.base.TransformController;
import org.alfresco.transform.base.logging.LogEntry;
import org.alfresco.transform.base.probes.ProbeTransform;
import org.alfresco.transform.base.registry.CustomTransformers;
import org.alfresco.transform.client.model.TransformRequest;
import org.alfresco.transform.exceptions.TransformException;
import org.alfresco.transform.common.TransformerDebug;
import org.alfresco.transform.registry.TransformServiceRegistry;
import org.springframework.web.multipart.MultipartFile;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.http.HttpStatus.OK;
import static org.alfresco.transform.common.RequestParamMap.*;
import jakarta.jms.Destination;
import jakarta.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
@@ -46,30 +39,32 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import jakarta.jms.Destination;
import jakarta.servlet.http.HttpServletRequest;
import static org.alfresco.transform.common.RequestParamMap.DIRECT_ACCESS_URL;
import static org.alfresco.transform.common.RequestParamMap.SOURCE_EXTENSION;
import static org.alfresco.transform.common.RequestParamMap.SOURCE_MIMETYPE;
import static org.alfresco.transform.common.RequestParamMap.TARGET_EXTENSION;
import static org.alfresco.transform.common.RequestParamMap.TARGET_MIMETYPE;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.http.HttpStatus.OK;
import org.springframework.web.multipart.MultipartFile;
import org.alfresco.transform.base.CustomTransformer;
import org.alfresco.transform.base.TransformController;
import org.alfresco.transform.base.logging.LogEntry;
import org.alfresco.transform.base.probes.ProbeTransform;
import org.alfresco.transform.base.registry.CustomTransformers;
import org.alfresco.transform.client.model.TransformRequest;
import org.alfresco.transform.common.TransformerDebug;
import org.alfresco.transform.exceptions.TransformException;
import org.alfresco.transform.registry.TransformServiceRegistry;
/**
* Provides the transform logic common to http (upload/download), message and probe requests. See
* {@link TransformHandler#handleHttpRequest(HttpServletRequest, MultipartFile, String, String, Map, ProbeTransform)},
* {@link TransformHandler#handleMessageRequest(TransformRequest, Long, Destination, ProbeTransform)} and
* {@link TransformHandler#handleProbeRequest(String, String, Map, File, File, ProbeTransform)}. Note the handing of transform requests
* via a message queue is the same as via the {@link TransformController#transform(TransformRequest, Long, Destination)}.
* Provides the transform logic common to http (upload/download), message and probe requests. See {@link TransformHandler#handleHttpRequest(HttpServletRequest, MultipartFile, String, String, Map, ProbeTransform)}, {@link TransformHandler#handleMessageRequest(TransformRequest, Long, Destination, ProbeTransform)} and {@link TransformHandler#handleProbeRequest(String, String, Map, File, File, ProbeTransform)}. Note the handing of transform requests via a message queue is the same as via the {@link TransformController#transform(TransformRequest, Long, Destination)}.
*/
abstract class ProcessHandler extends FragmentHandler
{
private static final List<String> NON_TRANSFORM_OPTION_REQUEST_PARAMETERS = Arrays.asList(SOURCE_EXTENSION,
TARGET_EXTENSION, TARGET_MIMETYPE, SOURCE_MIMETYPE, DIRECT_ACCESS_URL);
TARGET_EXTENSION, TARGET_MIMETYPE, SOURCE_MIMETYPE, DIRECT_ACCESS_URL, SOURCE_FILENAME);
protected final String sourceMimetype;
protected final String targetMimetype;
protected final String sourceFileName;
private final Map<String, String> transformOptions;
protected String reference;
private final TransformServiceRegistry transformRegistry;
@@ -78,11 +73,12 @@ abstract class ProcessHandler extends FragmentHandler
private final CustomTransformers customTransformers;
ProcessHandler(String sourceMimetype, String targetMimetype, Map<String, String> transformOptions,
String reference, TransformServiceRegistry transformRegistry, TransformerDebug transformerDebug,
ProbeTransform probeTransform, CustomTransformers customTransformers)
String reference, TransformServiceRegistry transformRegistry, TransformerDebug transformerDebug,
ProbeTransform probeTransform, CustomTransformers customTransformers)
{
this.sourceMimetype = sourceMimetype;
this.targetMimetype = targetMimetype;
this.sourceFileName = transformOptions.getOrDefault(SOURCE_FILENAME, null);
this.transformOptions = cleanTransformOptions(transformOptions);
this.reference = reference;
@@ -107,7 +103,6 @@ abstract class ProcessHandler extends FragmentHandler
super.init();
}
public String getReference()
{
return reference;
@@ -118,6 +113,7 @@ abstract class ProcessHandler extends FragmentHandler
LogEntry.start();
transformManager.setSourceMimetype(sourceMimetype);
transformManager.setTargetMimetype(targetMimetype);
transformManager.setSourceFileName(sourceFileName);
probeTransform.incrementTransformerCount();
try
{
@@ -131,13 +127,13 @@ abstract class ProcessHandler extends FragmentHandler
}
catch (TransformException e)
{
transformerDebug.logFailure(reference, " Error: "+e.getMessage());
transformerDebug.logFailure(reference, " Error: " + e.getMessage());
LogEntry.setStatusCodeAndMessage(e.getStatus(), e.getMessage());
handleTransformException(e);
}
catch (Exception e)
{
transformerDebug.logFailure(reference, " Error: "+e.getMessage());
transformerDebug.logFailure(reference, " Error: " + e.getMessage());
LogEntry.setStatusCodeAndMessage(INTERNAL_SERVER_ERROR, e.getMessage());
handleException(e);
}
@@ -174,8 +170,7 @@ abstract class ProcessHandler extends FragmentHandler
}
protected void sendTransformResponse(TransformManagerImpl transformManager)
{
}
{}
protected void handleTransformException(TransformException e)
{
@@ -188,19 +183,19 @@ abstract class ProcessHandler extends FragmentHandler
}
private String getTransformerName(final String sourceMimetype, long sourceSizeInBytes, final String targetMimetype,
final Map<String, String> transformOptions)
final Map<String, String> transformOptions)
{
final String transformerName = transformRegistry.findTransformerName(sourceMimetype,
sourceSizeInBytes, targetMimetype, transformOptions, null);
sourceSizeInBytes, targetMimetype, transformOptions, null);
if (transformerName == null)
{
throw new TransformException(BAD_REQUEST, "No transforms for: "+
sourceMimetype+
(sourceSizeInBytes >= 0 ? " ("+TransformerDebug.fileSize(sourceSizeInBytes)+")" : "")+
" -> "+targetMimetype+
transformOptions.entrySet().stream()
.map(entry -> entry.getKey()+"="+entry.getValue())
.collect(Collectors.joining(", ", " ", "")));
throw new TransformException(BAD_REQUEST, "No transforms for: " +
sourceMimetype +
(sourceSizeInBytes >= 0 ? " (" + TransformerDebug.fileSize(sourceSizeInBytes) + ")" : "") +
" -> " + targetMimetype +
transformOptions.entrySet().stream()
.map(entry -> entry.getKey() + "=" + entry.getValue())
.collect(Collectors.joining(", ", " ", "")));
}
return transformerName;
}
@@ -210,7 +205,7 @@ abstract class ProcessHandler extends FragmentHandler
CustomTransformer customTransformer = customTransformers.get(transformName);
if (customTransformer == null)
{
throw new TransformException(INTERNAL_SERVER_ERROR, "Custom Transformer "+transformName+" not found");
throw new TransformException(INTERNAL_SERVER_ERROR, "Custom Transformer " + transformName + " not found");
}
return customTransformer;
}

View File

@@ -2,7 +2,7 @@
* #%L
* Alfresco Transform Core
* %%
* Copyright (C) 2005 - 2023 Alfresco Software Limited
* Copyright (C) 2005 - 2025 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* -
@@ -26,18 +26,21 @@
*/
package org.alfresco.transform.base.transform;
import org.alfresco.transform.base.TransformManager;
import org.alfresco.transform.base.fs.FileManager;
import org.alfresco.transform.base.util.OutputStreamLengthRecorder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import jakarta.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.alfresco.transform.base.TransformManager;
import org.alfresco.transform.base.fs.FileManager;
import org.alfresco.transform.base.util.OutputStreamLengthRecorder;
/**
* Manages the input and output streams and any temporary files that have been created.
@@ -60,6 +63,17 @@ public class TransformManagerImpl implements TransformManager
private boolean createTargetFileCalled;
private Boolean startedWithSourceFile;
private Boolean startedWithTargetFile;
private String sourceFileName;
public String getSourceFileName()
{
return sourceFileName;
}
public void setSourceFileName(String sourceFileName)
{
this.sourceFileName = sourceFileName;
}
public void setRequest(HttpServletRequest request)
{
@@ -71,7 +85,8 @@ public class TransformManagerImpl implements TransformManager
this.processHandler = processHandler;
}
@Override public String getRequestId()
@Override
public String getRequestId()
{
return processHandler.getReference();
}
@@ -149,7 +164,8 @@ public class TransformManagerImpl implements TransformManager
keepTargetFile = true;
}
@Override public File createSourceFile()
@Override
public File createSourceFile()
{
if (createSourceFileCalled)
{
@@ -159,12 +175,13 @@ public class TransformManagerImpl implements TransformManager
if (sourceFile == null)
{
sourceFile = FileManager.createSourceFile(request, inputStream, sourceMimetype);
sourceFile = FileManager.createSourceFile(request, inputStream, sourceMimetype, sourceFileName);
}
return sourceFile;
}
@Override public File createTargetFile()
@Override
public File createTargetFile()
{
if (createTargetFileCalled)
{
@@ -204,8 +221,19 @@ public class TransformManagerImpl implements TransformManager
{
logger.error("Failed to delete temporary source file {}", sourceFile.getPath());
}
if (sourceFile != null)
{
File parentDir = sourceFile.getParentFile();
if (parentDir != null
&& !StringUtils.equalsAny(parentDir.getName().toLowerCase(Locale.ROOT), "alfresco", "temp", "tmp")
&& !parentDir.delete())
{
logger.error("Failed to delete parent directory {}", parentDir.getPath());
}
}
outputStreamLengthRecorder = null;
sourceFile = null;
sourceFileName = null;
createSourceFileCalled = false;
startedWithSourceFile = null;
}

View File

@@ -10,6 +10,7 @@
<form method="POST" enctype="multipart/form-data" th:action="${proxyPathPrefix+'/test'}">
<table>
<tr><td><div style="text-align:right">file</div></td><td><input type="file" name="file" /></td></tr>
<tr><td><div style="text-align:right">sourceFilename</div></td><td><input type="text" name="sourceFilename"/></td></tr>
<tr><td><div style="text-align:right">directAccessUrl</div></td><td><input type="text" name="directAccessUrl"/></td></tr>
<tr><td><div style="text-align:right">sourceMimetype</div></td><td><input type="text" name="sourceMimetype" value="" /></td>
<td><select name="_sourceMimetype">

View File

@@ -26,25 +26,12 @@
*/
package org.alfresco.transform.base;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.alfresco.transform.base.fakes.FakeTransformEngineWithAllInOne;
import org.alfresco.transform.base.fakes.FakeTransformEngineWithOneCustomTransformer;
import org.alfresco.transform.base.fakes.FakeTransformEngineWithTwoCustomTransformers;
import org.alfresco.transform.base.fakes.FakeTransformerPdf2Jpg;
import org.alfresco.transform.base.fakes.FakeTransformerPdf2Png;
import org.alfresco.transform.base.fakes.FakeTransformerTxT2Pdf;
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.mock.web.MockMultipartFile;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.nio.charset.StandardCharsets;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.alfresco.transform.base.TransformControllerTest.assertConfig;
import static org.alfresco.transform.base.TransformControllerTest.getLogMessagesFor;
@@ -64,28 +51,42 @@ import static org.alfresco.transform.common.RequestParamMap.ENDPOINT_VERSION;
import static org.alfresco.transform.common.RequestParamMap.PAGE_REQUEST_PARAM;
import static org.alfresco.transform.common.RequestParamMap.SOURCE_MIMETYPE;
import static org.alfresco.transform.common.RequestParamMap.TARGET_MIMETYPE;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.nio.charset.StandardCharsets;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;
import com.fasterxml.jackson.databind.ObjectMapper;
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.mock.web.MockMultipartFile;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.alfresco.transform.base.fakes.FakeTransformEngineWithAllInOne;
import org.alfresco.transform.base.fakes.FakeTransformEngineWithOneCustomTransformer;
import org.alfresco.transform.base.fakes.FakeTransformEngineWithTwoCustomTransformers;
import org.alfresco.transform.base.fakes.FakeTransformerPdf2Jpg;
import org.alfresco.transform.base.fakes.FakeTransformerPdf2Png;
import org.alfresco.transform.base.fakes.FakeTransformerTxT2Pdf;
/**
* Testing TransformController functionality where there are multiple TransformEngines brought together
* in a single t-engine.
* Testing TransformController functionality where there are multiple TransformEngines brought together in a single t-engine.
*
* Repeats a set of tests from {@link TransformControllerTest}, which tests the single TransformEngine case.
*/
@AutoConfigureMockMvc
@SpringBootTest(classes={org.alfresco.transform.base.Application.class})
@SpringBootTest(classes = {org.alfresco.transform.base.Application.class})
@ContextConfiguration(classes = {
FakeTransformEngineWithAllInOne.class,
FakeTransformEngineWithTwoCustomTransformers.class,
FakeTransformerTxT2Pdf.class,
FakeTransformerPdf2Png.class,
FakeTransformEngineWithOneCustomTransformer.class,
FakeTransformerPdf2Jpg.class})
FakeTransformEngineWithAllInOne.class,
FakeTransformEngineWithTwoCustomTransformers.class,
FakeTransformerTxT2Pdf.class,
FakeTransformerPdf2Png.class,
FakeTransformEngineWithOneCustomTransformer.class,
FakeTransformerPdf2Jpg.class})
public class TransformControllerAllInOneTest
{
@Autowired
@@ -112,45 +113,45 @@ public class TransformControllerAllInOneTest
transformController.startup();
assertEquals(
"--------------------------------------------------------------------------------------------------------------------------------------------------------------\n"
+ "Startup 0000 AllInOne\n"
+ "Line 2 0000 AllInOne\n"
+ "Line 3\n"
+ "--------------------------------------------------------------------------------------------------------------------------------------------------------------\n"
+ "Starting application components... Done",
controllerLogMessages.toString());
"--------------------------------------------------------------------------------------------------------------------------------------------------------------\n"
+ "Startup 0000 AllInOne\n"
+ "Line 2 0000 AllInOne\n"
+ "Line 3\n"
+ "--------------------------------------------------------------------------------------------------------------------------------------------------------------\n"
+ "Starting application components... Done",
controllerLogMessages.toString());
}
@Test
public void testVersionEndpointIncludesAvailable() throws Exception
{
mockMvc.perform(MockMvcRequestBuilders.get(ENDPOINT_VERSION))
.andExpect(status().isOk())
.andExpect(content().string("AllInOne "+coreVersion));
.andExpect(status().isOk())
.andExpect(content().string("AllInOne " + coreVersion));
}
@Test
public void testRootEndpointReturnsTestPage() throws Exception
{
mockMvc.perform(MockMvcRequestBuilders.get(ENDPOINT_ROOT))
.andExpect(status().isOk())
.andExpect(content().string(containsString("AllInOne Test Page")));
.andExpect(status().isOk())
.andExpect(content().string(containsString("AllInOne Test Page")));
}
@Test
public void testErrorEndpointReturnsErrorPage() throws Exception
{
mockMvc.perform(MockMvcRequestBuilders.get(ENDPOINT_ERROR))
.andExpect(status().isOk())
.andExpect(content().string(containsString("AllInOne Error Page")));
.andExpect(status().isOk())
.andExpect(content().string(containsString("AllInOne Error Page")));
}
@Test
public void testLogEndpointReturnsLogPage() throws Exception
{
mockMvc.perform(MockMvcRequestBuilders.get(ENDPOINT_LOG))
.andExpect(status().isOk())
.andExpect(content().string(containsString("AllInOne Log Entries")));
.andExpect(status().isOk())
.andExpect(content().string(containsString("AllInOne Log Entries")));
}
@Test
@@ -158,8 +159,8 @@ public class TransformControllerAllInOneTest
{
resetProbeForTesting(transformController);
mockMvc.perform(MockMvcRequestBuilders.get(ENDPOINT_READY))
.andExpect(status().isOk())
.andExpect(content().string(containsString("Success - ")));
.andExpect(status().isOk())
.andExpect(content().string(containsString("Success - ")));
}
@Test
@@ -167,8 +168,8 @@ public class TransformControllerAllInOneTest
{
resetProbeForTesting(transformController);
mockMvc.perform(MockMvcRequestBuilders.get(ENDPOINT_LIVE))
.andExpect(status().isOk())
.andExpect(content().string(containsString("Success - ")));
.andExpect(status().isOk())
.andExpect(content().string(containsString("Success - ")));
}
@Test
@@ -176,57 +177,58 @@ public class TransformControllerAllInOneTest
{
// The transformer's options should not include directAccessUrl as this is the default version of config
assertConfig(ENDPOINT_TRANSFORM_CONFIG,
"Pdf2Jpg,null,imageOptions\n"
+ "Pdf2Png,null,imageOptions\n"
+ "TxT2Pdf,null,docOptions\n"
+ "Txt2JpgViaPdf,null,imageOptions\n"
+ "Txt2PngViaPdf,null,imageOptions",
"docOptions,imageOptions", mockMvc, objectMapper);
"Pdf2Jpg,null,imageOptions\n"
+ "Pdf2Png,null,imageOptions\n"
+ "TxT2Pdf,null,docOptions\n"
+ "Txt2JpgViaPdf,null,imageOptions\n"
+ "Txt2PngViaPdf,null,imageOptions",
"docOptions,imageOptions", mockMvc, objectMapper);
}
@Test
public void testConfigLatestEndpointReturnsCoreVersionAndDirectAccessUrlOption() throws Exception
{
assertConfig(ENDPOINT_TRANSFORM_CONFIG_LATEST,
"Pdf2Jpg,"+coreVersion+",directAccessUrl,imageOptions\n"
+ "Pdf2Png,"+coreVersion+",directAccessUrl,imageOptions\n"
+ "TxT2Pdf,"+coreVersion+",directAccessUrl,docOptions\n"
+ "Txt2JpgViaPdf,"+coreVersion+",directAccessUrl,imageOptions\n"
+ "Txt2PngViaPdf,"+coreVersion+",directAccessUrl,imageOptions",
"directAccessUrl,docOptions,imageOptions", mockMvc, objectMapper);
"Pdf2Jpg," + coreVersion + ",directAccessUrl,imageOptions,sourceFilename\n"
+ "Pdf2Png," + coreVersion + ",directAccessUrl,imageOptions,sourceFilename\n"
+ "TxT2Pdf," + coreVersion + ",directAccessUrl,docOptions,sourceFilename\n"
+ "Txt2JpgViaPdf," + coreVersion + ",directAccessUrl,imageOptions,sourceFilename\n"
+ "Txt2PngViaPdf," + coreVersion + ",directAccessUrl,imageOptions,sourceFilename",
"directAccessUrl,docOptions,imageOptions,sourceFilename", mockMvc, objectMapper);
}
@Test
public void testTransformEndpointUsingTransformEngineWithTwoCustomTransformers() throws Exception
{
await()
.atMost(10, TimeUnit.SECONDS)
.untilAsserted(() -> mockMvc.perform(
MockMvcRequestBuilders.multipart(ENDPOINT_TRANSFORM)
.file(new MockMultipartFile("file", null, MIMETYPE_TEXT_PLAIN,
"Start".getBytes(StandardCharsets.UTF_8)))
.param(SOURCE_MIMETYPE, MIMETYPE_TEXT_PLAIN)
.param(TARGET_MIMETYPE, MIMETYPE_PDF)
.param(PAGE_REQUEST_PARAM, "1"))
.andExpect(status().isOk())
.andExpect(header().string("Content-Disposition",
"attachment; filename*=UTF-8''transform.pdf"))
.andExpect(content().string("Start -> TxT2Pdf(page=1)")));
await()
.atMost(10, TimeUnit.SECONDS)
.untilAsserted(() -> mockMvc.perform(
MockMvcRequestBuilders.multipart(ENDPOINT_TRANSFORM)
.file(new MockMultipartFile("file", null, MIMETYPE_TEXT_PLAIN,
"Start".getBytes(StandardCharsets.UTF_8)))
.param(SOURCE_MIMETYPE, MIMETYPE_TEXT_PLAIN)
.param(TARGET_MIMETYPE, MIMETYPE_PDF)
.param(PAGE_REQUEST_PARAM, "1"))
.andExpect(status().isOk())
.andExpect(header().string("Content-Disposition",
"attachment; filename*=UTF-8''transform.pdf"))
.andExpect(content().string("Start -> TxT2Pdf(page=1)")));
}
@Test
public void testTransformEndpointUsingTransformEngineWithOneCustomTransformer() throws Exception {
await()
.atMost(10, TimeUnit.SECONDS)
.untilAsserted(() -> mockMvc.perform(
MockMvcRequestBuilders.multipart(ENDPOINT_TRANSFORM)
.file(new MockMultipartFile("file", null, MIMETYPE_PDF,
"Start".getBytes(StandardCharsets.UTF_8)))
.param(SOURCE_MIMETYPE, MIMETYPE_PDF)
.param(TARGET_MIMETYPE, MIMETYPE_IMAGE_JPEG))
.andExpect(status().isOk())
.andExpect(header().string("Content-Disposition",
"attachment; filename*=UTF-8''transform.jpeg"))
.andExpect(content().string("Start -> Pdf2Jpg()")));
}
@Test
public void testTransformEndpointUsingTransformEngineWithOneCustomTransformer() throws Exception
{
await()
.atMost(10, TimeUnit.SECONDS)
.untilAsserted(() -> mockMvc.perform(
MockMvcRequestBuilders.multipart(ENDPOINT_TRANSFORM)
.file(new MockMultipartFile("file", null, MIMETYPE_PDF,
"Start".getBytes(StandardCharsets.UTF_8)))
.param(SOURCE_MIMETYPE, MIMETYPE_PDF)
.param(TARGET_MIMETYPE, MIMETYPE_IMAGE_JPEG))
.andExpect(status().isOk())
.andExpect(header().string("Content-Disposition",
"attachment; filename*=UTF-8''transform.jpeg"))
.andExpect(content().string("Start -> Pdf2Jpg()")));
}
}

View File

@@ -114,11 +114,11 @@ import org.alfresco.transform.config.TransformConfig;
* Also see {@link TransformControllerAllInOneTest}.
*/
@AutoConfigureMockMvc
@SpringBootTest(classes={org.alfresco.transform.base.Application.class})
@SpringBootTest(classes = {org.alfresco.transform.base.Application.class})
@ContextConfiguration(classes = {
FakeTransformEngineWithTwoCustomTransformers.class,
FakeTransformerTxT2Pdf.class,
FakeTransformerPdf2Png.class})
FakeTransformEngineWithTwoCustomTransformers.class,
FakeTransformerTxT2Pdf.class,
FakeTransformerPdf2Png.class})
public class TransformControllerTest
{
@Autowired
@@ -154,28 +154,27 @@ public class TransformControllerTest
transformController.startup();
assertEquals(
"--------------------------------------------------------------------------------------------------------------------------------------------------------------\n"
+ "Startup 0000 TwoCustomTransformers\n"
+ "Line 2 0000 TwoCustomTransformers\n"
+ "Line 3\n"
+ "--------------------------------------------------------------------------------------------------------------------------------------------------------------\n"
+ "Starting application components... Done",
controllerLogMessages.toString());
"--------------------------------------------------------------------------------------------------------------------------------------------------------------\n"
+ "Startup 0000 TwoCustomTransformers\n"
+ "Line 2 0000 TwoCustomTransformers\n"
+ "Line 3\n"
+ "--------------------------------------------------------------------------------------------------------------------------------------------------------------\n"
+ "Starting application components... Done",
controllerLogMessages.toString());
}
public static StringJoiner getLogMessagesFor(Class classBeingLogged)
{
StringJoiner logMessages = new StringJoiner("\n");
Logger logger = (Logger) LoggerFactory.getLogger(classBeingLogged);
AppenderBase<ILoggingEvent> logAppender = new AppenderBase<>()
{
AppenderBase<ILoggingEvent> logAppender = new AppenderBase<>() {
@Override
protected void append(ILoggingEvent iLoggingEvent)
{
logMessages.add(iLoggingEvent.getMessage());
}
};
logAppender.setContext((LoggerContext)LoggerFactory.getILoggerFactory());
logAppender.setContext((LoggerContext) LoggerFactory.getILoggerFactory());
logger.setLevel(Level.DEBUG);
logger.addAppender(logAppender);
logAppender.start();
@@ -183,7 +182,6 @@ public class TransformControllerTest
return logMessages;
}
private void testPageWithOrWithoutIngresPrefix(String url, boolean behindIngres, String... expected) throws Exception
{
boolean origBehindIngres = (boolean) ReflectionTestUtils.getField(transformController, "behindIngres");
@@ -192,13 +190,13 @@ public class TransformControllerTest
ReflectionTestUtils.setField(transformController, "behindIngres", behindIngres);
mockMvc.perform(MockMvcRequestBuilders.get(url))
.andExpect(status().isOk())
.andExpect(content().string(containsString(expected[0])))
.andExpect(content().string(containsString(expected[1])))
.andExpect(content().string(containsString(expected[2])))
.andExpect(content().string(containsString(expected[3])))
.andExpect(content().string(containsString(expected[4])))
.andExpect(content().string(containsString(expected[5])));
.andExpect(status().isOk())
.andExpect(content().string(containsString(expected[0])))
.andExpect(content().string(containsString(expected[1])))
.andExpect(content().string(containsString(expected[2])))
.andExpect(content().string(containsString(expected[3])))
.andExpect(content().string(containsString(expected[4])))
.andExpect(content().string(containsString(expected[5])));
}
finally
{
@@ -210,79 +208,80 @@ public class TransformControllerTest
public void testVersionEndpointIncludesAvailable() throws Exception
{
mockMvc.perform(MockMvcRequestBuilders.get(ENDPOINT_VERSION))
.andExpect(status().isOk())
.andExpect(content().string("TwoCustomTransformers "+coreVersion));
.andExpect(status().isOk())
.andExpect(content().string("TwoCustomTransformers " + coreVersion));
}
@Test
public void testRootEndpointReturnsTestPage() throws Exception
{
testPageWithOrWithoutIngresPrefix(ENDPOINT_ROOT, false,
"TwoCustomTransformers Test Page",
"action=\"/test\"",
"<a href=\"/log\">Log</a>",
"<a href=\"/ready\">Ready</a>",
"<a href=\"/live\">Live</a>",
"<a href=\"/transform/config?configVersion=9999\">Config</a>");
"TwoCustomTransformers Test Page",
"action=\"/test\"",
"<a href=\"/log\">Log</a>",
"<a href=\"/ready\">Ready</a>",
"<a href=\"/live\">Live</a>",
"<a href=\"/transform/config?configVersion=9999\">Config</a>");
}
@Test
public void testRootEndpointReturnsTestPageWithIngres() throws Exception
{
testPageWithOrWithoutIngresPrefix(ENDPOINT_ROOT, true,
"TwoCustomTransformers Test Page",
"action=\"/twocustomtransformers/test\"",
"href=\"/twocustomtransformers/log\"",
"<a href=\"/twocustomtransformers/ready\">Ready</a>",
"<a href=\"/twocustomtransformers/live\">Live</a>",
"<a href=\"/twocustomtransformers/transform/config?configVersion=9999\">Config</a>");
"TwoCustomTransformers Test Page",
"action=\"/twocustomtransformers/test\"",
"href=\"/twocustomtransformers/log\"",
"<a href=\"/twocustomtransformers/ready\">Ready</a>",
"<a href=\"/twocustomtransformers/live\">Live</a>",
"<a href=\"/twocustomtransformers/transform/config?configVersion=9999\">Config</a>");
}
@Test
public void testErrorEndpointReturnsErrorPage() throws Exception
{
testPageWithOrWithoutIngresPrefix(ENDPOINT_ERROR, false,
"TwoCustomTransformers Error Page",
"<a href=\"/\">Test</a>",
"<a href=\"/log\">Log</a>",
"<a href=\"/ready\">Ready</a>",
"<a href=\"/live\">Live</a>",
"<a href=\"/transform/config?configVersion=9999\">Config</a>"); }
"TwoCustomTransformers Error Page",
"<a href=\"/\">Test</a>",
"<a href=\"/log\">Log</a>",
"<a href=\"/ready\">Ready</a>",
"<a href=\"/live\">Live</a>",
"<a href=\"/transform/config?configVersion=9999\">Config</a>");
}
@Test
public void testErrorEndpointReturnsErrorPageWithIngres() throws Exception
{
testPageWithOrWithoutIngresPrefix(ENDPOINT_ERROR, true,
"TwoCustomTransformers Error Page",
"href=\"/twocustomtransformers/\"",
"href=\"/twocustomtransformers/log\"",
"<a href=\"/twocustomtransformers/ready\">Ready</a>",
"<a href=\"/twocustomtransformers/live\">Live</a>",
"<a href=\"/twocustomtransformers/transform/config?configVersion=9999\">Config</a>");
"TwoCustomTransformers Error Page",
"href=\"/twocustomtransformers/\"",
"href=\"/twocustomtransformers/log\"",
"<a href=\"/twocustomtransformers/ready\">Ready</a>",
"<a href=\"/twocustomtransformers/live\">Live</a>",
"<a href=\"/twocustomtransformers/transform/config?configVersion=9999\">Config</a>");
}
@Test
public void testLogEndpointReturnsLogPage() throws Exception
{
testPageWithOrWithoutIngresPrefix(ENDPOINT_LOG, false,
"TwoCustomTransformers Log Entries",
"<a href=\"/\">Test</a>",
"Log",
"<a href=\"/ready\">Ready</a>",
"<a href=\"/live\">Live</a>",
"<a href=\"/transform/config?configVersion=9999\">Config</a>");
"TwoCustomTransformers Log Entries",
"<a href=\"/\">Test</a>",
"Log",
"<a href=\"/ready\">Ready</a>",
"<a href=\"/live\">Live</a>",
"<a href=\"/transform/config?configVersion=9999\">Config</a>");
}
@Test
public void testLogEndpointReturnsLogPageWithIngres() throws Exception
{
testPageWithOrWithoutIngresPrefix(ENDPOINT_LOG, true,
"TwoCustomTransformers Log Entries",
"href=\"/twocustomtransformers/\"",
"Log",
"<a href=\"/twocustomtransformers/ready\">Ready</a>",
"<a href=\"/twocustomtransformers/live\">Live</a>",
"<a href=\"/twocustomtransformers/transform/config?configVersion=9999\">Config</a>");
"TwoCustomTransformers Log Entries",
"href=\"/twocustomtransformers/\"",
"Log",
"<a href=\"/twocustomtransformers/ready\">Ready</a>",
"<a href=\"/twocustomtransformers/live\">Live</a>",
"<a href=\"/twocustomtransformers/transform/config?configVersion=9999\">Config</a>");
}
@Test
@@ -290,8 +289,8 @@ public class TransformControllerTest
{
resetProbeForTesting(transformController);
mockMvc.perform(MockMvcRequestBuilders.get(ENDPOINT_READY))
.andExpect(status().isOk())
.andExpect(content().string(containsString("Success - ")));
.andExpect(status().isOk())
.andExpect(content().string(containsString("Success - ")));
}
@Test
@@ -321,59 +320,60 @@ public class TransformControllerTest
// coreValue is not set as this is the default version of config
// The transformer's options should not include directAccessUrl as this is the default version of config
assertConfig(ENDPOINT_TRANSFORM_CONFIG,
"Pdf2Png,null,imageOptions\n"
+ "TxT2Pdf,null,docOptions\n"
+ "Txt2JpgViaPdf,null,imageOptions\n"
+ "Txt2PngViaPdf,null,imageOptions",
"docOptions,imageOptions", mockMvc, objectMapper);
"Pdf2Png,null,imageOptions\n"
+ "TxT2Pdf,null,docOptions\n"
+ "Txt2JpgViaPdf,null,imageOptions\n"
+ "Txt2PngViaPdf,null,imageOptions",
"docOptions,imageOptions", mockMvc, objectMapper);
}
@Test
public void testConfigLatestEndpointReturnsCoreVersionAndDirectAccessUrlOption() throws Exception
{
assertConfig(ENDPOINT_TRANSFORM_CONFIG_LATEST,
"Pdf2Png,"+coreVersion+",directAccessUrl,imageOptions\n"
+ "TxT2Pdf,"+coreVersion+",directAccessUrl,docOptions\n"
+ "Txt2JpgViaPdf,null,imageOptions\n"
+ "Txt2PngViaPdf,"+coreVersion+",directAccessUrl,imageOptions",
"directAccessUrl,docOptions,imageOptions", mockMvc, objectMapper);
"Pdf2Png," + coreVersion + ",directAccessUrl,imageOptions,sourceFilename\n"
+ "TxT2Pdf," + coreVersion + ",directAccessUrl,docOptions,sourceFilename\n"
+ "Txt2JpgViaPdf,null,imageOptions\n"
+ "Txt2PngViaPdf," + coreVersion + ",directAccessUrl,imageOptions,sourceFilename",
"directAccessUrl,docOptions,imageOptions,sourceFilename", mockMvc, objectMapper);
}
static void assertConfig(String url, String expectedTransformers, String expectedOptions,
MockMvc mockMvc, ObjectMapper objectMapper) throws Exception
MockMvc mockMvc, ObjectMapper objectMapper) throws Exception
{
TransformConfig config = objectMapper.readValue(
mockMvc.perform(MockMvcRequestBuilders.get(url))
.andExpect(status().isOk())
.andExpect(header().string(CONTENT_TYPE, APPLICATION_JSON_VALUE))
.andReturn()
.getResponse()
.getContentAsString(), TransformConfig.class);
mockMvc.perform(MockMvcRequestBuilders.get(url))
.andExpect(status().isOk())
.andExpect(header().string(CONTENT_TYPE, APPLICATION_JSON_VALUE))
.andReturn()
.getResponse()
.getContentAsString(),
TransformConfig.class);
// Gets a list of transformerNames,coreVersion,optionNames
assertEquals(expectedTransformers,
config.getTransformers().stream()
.map(t -> t.getTransformerName()+","
+t.getCoreVersion()+","
+t.getTransformOptions().stream().sorted().collect(Collectors.joining(",")))
.sorted()
.collect(Collectors.joining("\n")));
config.getTransformers().stream()
.map(t -> t.getTransformerName() + ","
+ t.getCoreVersion() + ","
+ t.getTransformOptions().stream().sorted().collect(Collectors.joining(",")))
.sorted()
.collect(Collectors.joining("\n")));
assertEquals(expectedOptions,
config.getTransformOptions().keySet().stream()
.sorted()
.collect(Collectors.joining(",")));
config.getTransformOptions().keySet().stream()
.sorted()
.collect(Collectors.joining(",")));
}
@Test
public void testTransformEndpointThatUsesTransformRequests() throws Exception
{
final Map<String,File> sfsRef2File = new HashMap<>();
final Map<String, File> sfsRef2File = new HashMap<>();
when(fakeSfsClient.saveFile(any())).thenAnswer((Answer) invocation -> {
File originalFile = (File) invocation.getArguments()[0];
// Make a copy as the original might get deleted
File fileCopy = new File(tempDir, originalFile.getName()+"copy");
File fileCopy = new File(tempDir, originalFile.getName() + "copy");
FileUtils.copyFile(originalFile, fileCopy);
String fileRef = UUID.randomUUID().toString();
@@ -381,9 +381,8 @@ public class TransformControllerTest
return new FileRefResponse(new FileRefEntity(fileRef));
});
when(fakeSfsClient.retrieveFile(any())).thenAnswer((Answer) invocation ->
ResponseEntity.ok().header(CONTENT_DISPOSITION,"attachment; filename*=UTF-8''transform.tmp")
.body((Resource) new UrlResource(sfsRef2File.get(invocation.getArguments()[0]).toURI())));
when(fakeSfsClient.retrieveFile(any())).thenAnswer((Answer) invocation -> ResponseEntity.ok().header(CONTENT_DISPOSITION, "attachment; filename*=UTF-8''transform.tmp")
.body((Resource) new UrlResource(sfsRef2File.get(invocation.getArguments()[0]).toURI())));
File sourceFile = getTestFile("original.txt", true, tempDir);
String sourceFileRef = fakeSfsClient.saveFile(sourceFile).getEntry().getFileRef();
@@ -392,7 +391,7 @@ public class TransformControllerTest
.withRequestId("1")
.withSchema(1)
.withClientData("Alfresco Digital Business Platform")
// .withTransformRequestOptions(ImmutableMap.of(DIRECT_ACCESS_URL, "file://"+sourceFile.toPath()))
// .withTransformRequestOptions(ImmutableMap.of(DIRECT_ACCESS_URL, "file://"+sourceFile.toPath()))
.withSourceReference(sourceFileRef)
.withSourceMediaType(MIMETYPE_TEXT_PLAIN)
.withSourceSize(sourceFile.length())
@@ -423,16 +422,16 @@ public class TransformControllerTest
public void testTransformEndpointThatUploadsAndDownloadsContent() throws Exception
{
mockMvc.perform(
MockMvcRequestBuilders.multipart(ENDPOINT_TRANSFORM)
.file(new MockMultipartFile("file", null, MIMETYPE_TEXT_PLAIN,
"Start".getBytes(StandardCharsets.UTF_8)))
.param(SOURCE_MIMETYPE, MIMETYPE_TEXT_PLAIN)
.param(TARGET_MIMETYPE, MIMETYPE_PDF)
.param(PAGE_REQUEST_PARAM, "1"))
.andExpect(status().isOk())
.andExpect(header().string("Content-Disposition",
"attachment; filename*=UTF-8''transform.pdf"))
.andExpect(content().string("Start -> TxT2Pdf(page=1)"));
MockMvcRequestBuilders.multipart(ENDPOINT_TRANSFORM)
.file(new MockMultipartFile("file", null, MIMETYPE_TEXT_PLAIN,
"Start".getBytes(StandardCharsets.UTF_8)))
.param(SOURCE_MIMETYPE, MIMETYPE_TEXT_PLAIN)
.param(TARGET_MIMETYPE, MIMETYPE_PDF)
.param(PAGE_REQUEST_PARAM, "1"))
.andExpect(status().isOk())
.andExpect(header().string("Content-Disposition",
"attachment; filename*=UTF-8''transform.pdf"))
.andExpect(content().string("Start -> TxT2Pdf(page=1)"));
}
@Test
@@ -445,24 +444,25 @@ public class TransformControllerTest
transformController.transformHandler = transformHandlerSpy;
mockMvc.perform(
MockMvcRequestBuilders.multipart(ENDPOINT_TEST)
.file(new MockMultipartFile("file", null, MIMETYPE_TEXT_PLAIN,
"Start".getBytes(StandardCharsets.UTF_8)))
.param(SOURCE_MIMETYPE, MIMETYPE_IMAGE_BMP)
.param("_"+SOURCE_MIMETYPE, MIMETYPE_TEXT_PLAIN)
.param(TARGET_MIMETYPE, MIMETYPE_PDF)
.param("_"+TARGET_MIMETYPE, "")
.param(PAGE_REQUEST_PARAM, "replaced")
.param("name1", "hasNoValueSoRemoved").param("value1", "")
.param("name2", PAGE_REQUEST_PARAM).param("value2", "1")
.param("name3", SOURCE_ENCODING).param("value3", "UTF-8"));
MockMvcRequestBuilders.multipart(ENDPOINT_TEST)
.file(new MockMultipartFile("file", null, MIMETYPE_TEXT_PLAIN,
"Start".getBytes(StandardCharsets.UTF_8)))
.param(SOURCE_MIMETYPE, MIMETYPE_IMAGE_BMP)
.param("_" + SOURCE_MIMETYPE, MIMETYPE_TEXT_PLAIN)
.param(TARGET_MIMETYPE, MIMETYPE_PDF)
.param("_" + TARGET_MIMETYPE, "")
.param(PAGE_REQUEST_PARAM, "replaced")
.param("name1", "hasNoValueSoRemoved").param("value1", "")
.param("name2", PAGE_REQUEST_PARAM).param("value2", "1")
.param("name3", SOURCE_ENCODING).param("value3", "UTF-8"));
verify(transformHandlerSpy).handleHttpRequest(any(), any(), eq(MIMETYPE_TEXT_PLAIN), eq(MIMETYPE_PDF),
eq(ImmutableMap.of(
SOURCE_MIMETYPE, MIMETYPE_TEXT_PLAIN,
TARGET_MIMETYPE, MIMETYPE_PDF,
PAGE_REQUEST_PARAM, "1",
SOURCE_ENCODING, "UTF-8")), any());
eq(ImmutableMap.of(
SOURCE_MIMETYPE, MIMETYPE_TEXT_PLAIN,
TARGET_MIMETYPE, MIMETYPE_PDF,
PAGE_REQUEST_PARAM, "1",
SOURCE_ENCODING, "UTF-8")),
any());
}
finally
{
@@ -474,25 +474,25 @@ public class TransformControllerTest
public void testInterceptOfMissingServletRequestParameterException() throws Exception
{
mockMvc.perform(
MockMvcRequestBuilders.multipart(ENDPOINT_TRANSFORM)
.file(new MockMultipartFile("file", null, MIMETYPE_TEXT_PLAIN,
"Start".getBytes(StandardCharsets.UTF_8))))
.andExpect(status().isBadRequest())
.andExpect(status().reason(containsString("Request parameter '"+SOURCE_MIMETYPE+"' is missing")));
MockMvcRequestBuilders.multipart(ENDPOINT_TRANSFORM)
.file(new MockMultipartFile("file", null, MIMETYPE_TEXT_PLAIN,
"Start".getBytes(StandardCharsets.UTF_8))))
.andExpect(status().isBadRequest())
.andExpect(status().reason(containsString("Request parameter '" + SOURCE_MIMETYPE + "' is missing")));
}
@Test
public void testInterceptOfTransformException_noTransformers() throws Exception
{
mockMvc.perform(
MockMvcRequestBuilders.multipart(ENDPOINT_TRANSFORM)
.file(new MockMultipartFile("file", null, MIMETYPE_TEXT_PLAIN,
"Start".getBytes(StandardCharsets.UTF_8)))
.param(SOURCE_MIMETYPE, MIMETYPE_TEXT_PLAIN)
.param(TARGET_MIMETYPE, MIMETYPE_PDF)
.param("unknown", "1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(containsString("TwoCustomTransformers Error Page")))
.andExpect(content().string(containsString("No transforms for: text/plain (5 bytes) -&gt; application/pdf unknown=1")));
MockMvcRequestBuilders.multipart(ENDPOINT_TRANSFORM)
.file(new MockMultipartFile("file", null, MIMETYPE_TEXT_PLAIN,
"Start".getBytes(StandardCharsets.UTF_8)))
.param(SOURCE_MIMETYPE, MIMETYPE_TEXT_PLAIN)
.param(TARGET_MIMETYPE, MIMETYPE_PDF)
.param("unknown", "1"))
.andExpect(status().isBadRequest())
.andExpect(content().string(containsString("TwoCustomTransformers Error Page")))
.andExpect(content().string(containsString("No transforms for: text/plain (5 bytes) -&gt; application/pdf unknown=1")));
}
}

View File

@@ -2,7 +2,7 @@
* #%L
* Alfresco Transform Core
* %%
* Copyright (C) 2022 - 2022 Alfresco Software Limited
* Copyright (C) 2022 - 2025 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* -
@@ -26,9 +26,9 @@
*/
package org.alfresco.transform.base.transform;
import org.alfresco.transform.base.CustomTransformer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
@@ -43,19 +43,20 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.alfresco.transform.base.CustomTransformer;
/**
* Tests {@link StreamHandler}, {@link TransformManagerImpl#createSourceFile()} and
* {@link TransformManagerImpl#createTargetFile()} methods.
* Tests {@link StreamHandler}, {@link TransformManagerImpl#createSourceFile()} and {@link TransformManagerImpl#createTargetFile()} methods.
*/
@SuppressWarnings("PMD.TooManyMethods")
public class StreamHandlerTest
{
public static final String ORIGINAL = "Original";
public static final String CHANGE = " plus some change";
public static final String EXPECTED = ORIGINAL+ CHANGE;
public static final String EXPECTED = ORIGINAL + CHANGE;
TransformManagerImpl transformManager = new TransformManagerImpl();
@TempDir
@@ -132,12 +133,12 @@ public class StreamHandlerTest
public void testStartWithInputStream() throws Exception
{
try (InputStream inputStream = getSourceInputStreamFromBytes();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream())
ByteArrayOutputStream outputStream = new ByteArrayOutputStream())
{
transformManager.setInputStream(inputStream);
OutputStream outputStreamLengthRecorder = transformManager.setOutputStream(outputStream);
write(outputStreamLengthRecorder, read(inputStream)+CHANGE);
write(outputStreamLengthRecorder, read(inputStream) + CHANGE);
transformManager.copyTargetFileToOutputStream();
transformManager.getOutputStream().close();
@@ -155,14 +156,14 @@ public class StreamHandlerTest
public void testStartWithInputStreamAndCallCreateSourceFile() throws Exception
{
try (InputStream inputStream = getSourceInputStreamFromBytes();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream())
ByteArrayOutputStream outputStream = new ByteArrayOutputStream())
{
transformManager.setInputStream(inputStream);
OutputStream outputStreamLengthRecorder = transformManager.setOutputStream(outputStream);
File sourceFileCreatedByTransform = transformManager.createSourceFile();
assertTrue(sourceFileCreatedByTransform.exists());
write(outputStreamLengthRecorder, read(sourceFileCreatedByTransform)+CHANGE);
write(outputStreamLengthRecorder, read(sourceFileCreatedByTransform) + CHANGE);
transformManager.copyTargetFileToOutputStream();
transformManager.getOutputStream().close();
@@ -185,12 +186,12 @@ public class StreamHandlerTest
transformManager.setSourceFile(sourceFile);
try (InputStream inputStream = new BufferedInputStream(new FileInputStream(sourceFile));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream())
ByteArrayOutputStream outputStream = new ByteArrayOutputStream())
{
transformManager.setInputStream(inputStream);
OutputStream outputStreamLengthRecorder = transformManager.setOutputStream(outputStream);
write(outputStreamLengthRecorder, read(inputStream)+CHANGE);
write(outputStreamLengthRecorder, read(inputStream) + CHANGE);
transformManager.copyTargetFileToOutputStream();
closeInputStreamWithoutException(inputStream);
@@ -213,14 +214,14 @@ public class StreamHandlerTest
transformManager.setSourceFile(sourceFile);
try (InputStream inputStream = new BufferedInputStream(new FileInputStream(sourceFile));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream())
ByteArrayOutputStream outputStream = new ByteArrayOutputStream())
{
transformManager.setInputStream(inputStream);
OutputStream outputStreamLengthRecorder = transformManager.setOutputStream(outputStream);
File sourceFileCreatedByTransform = transformManager.createSourceFile();
assertEquals(sourceFile, sourceFileCreatedByTransform);
write(outputStreamLengthRecorder, read(sourceFileCreatedByTransform)+CHANGE);
write(outputStreamLengthRecorder, read(sourceFileCreatedByTransform) + CHANGE);
transformManager.copyTargetFileToOutputStream();
closeInputStreamWithoutException(inputStream);
@@ -247,14 +248,14 @@ public class StreamHandlerTest
public void testStartWithOutputStreamAndCallCreateTargetFile() throws Exception
{
try (InputStream inputStream = getSourceInputStreamFromBytes();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream())
ByteArrayOutputStream outputStream = new ByteArrayOutputStream())
{
transformManager.setInputStream(inputStream);
transformManager.setOutputStream(outputStream);
File targetFileCreatedByTransform = transformManager.createTargetFile();
assertTrue(targetFileCreatedByTransform.exists());
write(targetFileCreatedByTransform, read(inputStream)+CHANGE);
write(targetFileCreatedByTransform, read(inputStream) + CHANGE);
transformManager.copyTargetFileToOutputStream();
transformManager.getOutputStream().close();
@@ -276,12 +277,12 @@ public class StreamHandlerTest
transformManager.setTargetFile(targetFile);
try (InputStream inputStream = getSourceInputStreamFromBytes();
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)))
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)))
{
transformManager.setInputStream(inputStream);
OutputStream outputStreamLengthRecorder = transformManager.setOutputStream(outputStream);
write(outputStreamLengthRecorder, read(inputStream)+CHANGE);
write(outputStreamLengthRecorder, read(inputStream) + CHANGE);
transformManager.copyTargetFileToOutputStream();
transformManager.getOutputStream().close();
@@ -304,14 +305,14 @@ public class StreamHandlerTest
transformManager.setTargetFile(targetFile);
try (InputStream inputStream = getSourceInputStreamFromBytes();
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)))
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)))
{
transformManager.setInputStream(inputStream);
transformManager.setOutputStream(outputStream);
File targetFileCreatedByTransform = transformManager.createTargetFile();
assertEquals(targetFile, targetFileCreatedByTransform);
write(targetFileCreatedByTransform, read(inputStream)+CHANGE);
write(targetFileCreatedByTransform, read(inputStream) + CHANGE);
transformManager.copyTargetFileToOutputStream();
transformManager.getOutputStream().close();
@@ -344,12 +345,12 @@ public class StreamHandlerTest
transformManager.keepTargetFile();
try (InputStream inputStream = new BufferedInputStream(new FileInputStream(sourceFile));
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)))
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)))
{
transformManager.setInputStream(inputStream);
OutputStream outputStreamLengthRecorder = transformManager.setOutputStream(outputStream);
write(outputStreamLengthRecorder, read(inputStream)+CHANGE);
write(outputStreamLengthRecorder, read(inputStream) + CHANGE);
transformManager.copyTargetFileToOutputStream();
closeInputStreamWithoutException(inputStream);
@@ -375,12 +376,12 @@ public class StreamHandlerTest
transformManager.setTargetFile(targetFile);
try (InputStream inputStream = new BufferedInputStream(new FileInputStream(sourceFile));
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)))
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)))
{
transformManager.setInputStream(inputStream);
OutputStream outputStreamLengthRecorder = transformManager.setOutputStream(outputStream);
write(outputStreamLengthRecorder, read(inputStream)+CHANGE);
write(outputStreamLengthRecorder, read(inputStream) + CHANGE);
transformManager.copyTargetFileToOutputStream();
closeInputStreamWithoutException(inputStream);
@@ -404,12 +405,12 @@ public class StreamHandlerTest
transformManager.setTargetFile(targetFile);
try (InputStream inputStream = getSourceInputStreamFromBytes();
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)))
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)))
{
transformManager.setInputStream(inputStream);
OutputStream outputStreamLengthRecorder = transformManager.setOutputStream(outputStream);
write(outputStreamLengthRecorder, read(inputStream)+CHANGE);
write(outputStreamLengthRecorder, read(inputStream) + CHANGE);
transformManager.copyTargetFileToOutputStream();
closeInputStreamWithoutException(inputStream);
@@ -437,7 +438,7 @@ public class StreamHandlerTest
@Override
protected void transform(CustomTransformer customTransformer) throws Exception
{
write(outputStream, read(inputStream)+CHANGE);
write(outputStream, read(inputStream) + CHANGE);
}
}
@@ -448,8 +449,7 @@ public class StreamHandlerTest
try (ByteArrayOutputStream os = new ByteArrayOutputStream())
{
new FakeStreamHandler()
{
new FakeStreamHandler() {
@Override
protected void init() throws IOException
{
@@ -480,8 +480,7 @@ public class StreamHandlerTest
File sourceFile = tempFile();
write(sourceFile, ORIGINAL);
new FakeStreamHandler()
{
new FakeStreamHandler() {
@Override
protected void init() throws IOException
{
@@ -512,8 +511,7 @@ public class StreamHandlerTest
File sourceFile = tempFile();
write(sourceFile, ORIGINAL);
new FakeStreamHandler()
{
new FakeStreamHandler() {
@Override
protected InputStream getInputStream() throws IOException
{
@@ -533,8 +531,7 @@ public class StreamHandlerTest
{
File targetFile = tempFile();
new FakeStreamHandler()
{
new FakeStreamHandler() {
@Override
protected InputStream getInputStream()
{
@@ -543,7 +540,7 @@ public class StreamHandlerTest
@Override
protected OutputStream getOutputStream()
throws FileNotFoundException
throws FileNotFoundException
{
return getOutputStreamToFile(targetFile);
}
@@ -560,8 +557,7 @@ public class StreamHandlerTest
{
try (ByteArrayOutputStream os = new ByteArrayOutputStream())
{
new FakeStreamHandler()
{
new FakeStreamHandler() {
@Override
protected InputStream getInputStream()
{
@@ -576,4 +572,34 @@ public class StreamHandlerTest
}.handleTransformRequest();
}
}
@Test
public void testStartWithInputStreamAndCallCreateSourceFileWithSourceFileName() throws Exception
{
try (
InputStream in = getSourceInputStreamFromBytes();
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream rec = transformManager.setOutputStream(out))
{
String testFilename = "test.docx";
transformManager.setSourceFileName(testFilename);
transformManager.setInputStream(in);
File src = transformManager.createSourceFile();
assertTrue(src.exists());
write(rec, read(src) + CHANGE);
assertEquals(testFilename, src.getName());
transformManager.copyTargetFileToOutputStream();
transformManager.getOutputStream().close();
closeInputStreamWithoutException(in);
Long outputLength = transformManager.getOutputLength();
transformManager.deleteSourceFile();
transformManager.deleteTargetFile();
assertEquals(EXPECTED, read(out));
assertEquals(EXPECTED.length(), outputLength);
assertFalse(src.exists());
}
}
}