ATS-532 : Code improvements (#89)

- move startup message from controllers to the Application classes (SpringBoot configuration beans)
- added static imports for most static variables and static methods
- simplified a few nested *if*s
- replaced Arrays.asList() with explicit immutable collections
- fixed a few IntelliJ code inspection warnings
This commit is contained in:
CezarLeahu 2019-08-18 18:45:14 +03:00 committed by GitHub
parent 485347729b
commit 22de0ce5df
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
40 changed files with 391 additions and 329 deletions

View File

@ -65,7 +65,6 @@
<artifactId>dom4j</artifactId> <artifactId>dom4j</artifactId>
<version>2.1.1</version> <version>2.1.1</version>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -30,11 +30,10 @@ import static org.alfresco.transformer.fs.FileManager.createAttachment;
import static org.alfresco.transformer.fs.FileManager.createSourceFile; import static org.alfresco.transformer.fs.FileManager.createSourceFile;
import static org.alfresco.transformer.fs.FileManager.createTargetFile; import static org.alfresco.transformer.fs.FileManager.createTargetFile;
import static org.alfresco.transformer.fs.FileManager.createTargetFileName; import static org.alfresco.transformer.fs.FileManager.createTargetFileName;
import static org.alfresco.transformer.logging.StandardMessages.LICENCE;
import static org.springframework.http.HttpStatus.OK; import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.Map; import java.util.Map;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -46,7 +45,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
@ -82,18 +80,6 @@ public class AlfrescoPdfRendererController extends AbstractTransformerController
@Autowired @Autowired
private PdfRendererCommandExecutor commandExecutor; private PdfRendererCommandExecutor commandExecutor;
@Autowired
public AlfrescoPdfRendererController()
{
logger.info(
"-----------------------------------------------------------------------------------------------------------------------------------------------------------");
Arrays.stream(LICENCE.split("\\n")).forEach(logger::info);
logger.info(
"alfresco-pdf-renderer uses the PDFium library from Google Inc. See the license at https://pdfium.googlesource.com/pdfium/+/master/LICENSE or in /pdfium.txt");
logger.info(
"-----------------------------------------------------------------------------------------------------------------------------------------------------------");
}
@Override @Override
public String getTransformerName() public String getTransformerName()
{ {
@ -141,7 +127,7 @@ public class AlfrescoPdfRendererController extends AbstractTransformerController
} }
@Deprecated @Deprecated
@PostMapping(value = "/transform", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @PostMapping(value = "/transform", consumes = MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Resource> transform(HttpServletRequest request, public ResponseEntity<Resource> transform(HttpServletRequest request,
@RequestParam("file") MultipartFile sourceMultipartFile, @RequestParam("file") MultipartFile sourceMultipartFile,
@RequestParam("targetExtension") String targetExtension, @RequestParam("targetExtension") String targetExtension,

View File

@ -26,13 +26,21 @@
*/ */
package org.alfresco.transformer; package org.alfresco.transformer;
import static org.alfresco.transformer.logging.StandardMessages.LICENCE;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer; import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;
import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.MeterRegistry;
@ -40,6 +48,8 @@ import io.micrometer.core.instrument.MeterRegistry;
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class}) @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class Application public class Application
{ {
private static final Logger logger = LoggerFactory.getLogger(Application.class);
@Value("${container.name}") @Value("${container.name}")
private String containerName; private String containerName;
@ -53,4 +63,15 @@ public class Application
{ {
SpringApplication.run(Application.class, args); SpringApplication.run(Application.class, args);
} }
@EventListener(ApplicationReadyEvent.class)
public void startup()
{
logger.info("-----------------------------------------------------------------------------------------------------------------------------------------------------------");
Arrays.stream(LICENCE.split("\\n")).forEach(logger::info);
logger.info("alfresco-pdf-renderer uses the PDFium library from Google Inc. See the license at https://pdfium.googlesource.com/pdfium/+/master/LICENSE or in /pdfium.txt");
logger.info("-----------------------------------------------------------------------------------------------------------------------------------------------------------");
logger.info("Starting application components... Done");
}
} }

View File

@ -44,9 +44,7 @@ final class OptionsBuilder
private Boolean allowPdfEnlargement; private Boolean allowPdfEnlargement;
private Boolean maintainPdfAspectRatio; private Boolean maintainPdfAspectRatio;
private OptionsBuilder() private OptionsBuilder() {}
{
}
public OptionsBuilder withPage(final String page) public OptionsBuilder withPage(final String page)
{ {

View File

@ -33,11 +33,19 @@ import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.springframework.http.HttpHeaders.ACCEPT;
import static org.springframework.http.HttpHeaders.CONTENT_DISPOSITION;
import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
import static org.springframework.http.HttpStatus.BAD_REQUEST; import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK; import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.http.MediaType.APPLICATION_PDF_VALUE;
import static org.springframework.http.MediaType.IMAGE_PNG_VALUE;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 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.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.util.StringUtils.getFilenameExtension;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -64,14 +72,11 @@ import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile; import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.util.StringUtils;
/** /**
* Test the AlfrescoPdfRendererController without a server. * Test the AlfrescoPdfRendererController without a server.
@ -129,7 +134,7 @@ public class AlfrescoPdfRendererControllerTest extends AbstractTransformerContro
String actualOptions = actualProperties.get("options"); String actualOptions = actualProperties.get("options");
String actualSource = actualProperties.get("source"); String actualSource = actualProperties.get("source");
String actualTarget = actualProperties.get("target"); String actualTarget = actualProperties.get("target");
String actualTargetExtension = StringUtils.getFilenameExtension(actualTarget); String actualTargetExtension = getFilenameExtension(actualTarget);
assertNotNull(actualSource); assertNotNull(actualSource);
assertNotNull(actualTarget); assertNotNull(actualTarget);
@ -234,8 +239,8 @@ public class AlfrescoPdfRendererControllerTest extends AbstractTransformerContro
{ {
transformRequest.setSourceExtension("pdf"); transformRequest.setSourceExtension("pdf");
transformRequest.setTargetExtension("png"); transformRequest.setTargetExtension("png");
transformRequest.setSourceMediaType(MediaType.APPLICATION_PDF_VALUE); transformRequest.setSourceMediaType(APPLICATION_PDF_VALUE);
transformRequest.setTargetMediaType(MediaType.IMAGE_PNG_VALUE); transformRequest.setTargetMediaType(IMAGE_PNG_VALUE);
} }
@Test @Test
@ -270,14 +275,13 @@ public class AlfrescoPdfRendererControllerTest extends AbstractTransformerContro
// HTTP Request // HTTP Request
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.CONTENT_DISPOSITION, headers.set(CONTENT_DISPOSITION, "attachment; filename=quick." + sourceExtension);
"attachment; filename=quick." + sourceExtension);
ResponseEntity<Resource> response = new ResponseEntity<>(new FileSystemResource( ResponseEntity<Resource> response = new ResponseEntity<>(new FileSystemResource(
sourceFile), headers, OK); sourceFile), headers, OK);
when(alfrescoSharedFileStoreClient.retrieveFile(sourceFileRef)).thenReturn(response); when(alfrescoSharedFileStoreClient.retrieveFile(sourceFileRef)).thenReturn(response);
when(alfrescoSharedFileStoreClient.saveFile(any())).thenReturn( when(alfrescoSharedFileStoreClient.saveFile(any()))
new FileRefResponse(new FileRefEntity(targetFileRef))); .thenReturn(new FileRefResponse(new FileRefEntity(targetFileRef)));
when(mockExecutionResult.getExitValue()).thenReturn(0); when(mockExecutionResult.getExitValue()).thenReturn(0);
// Update the Transformation Request with any specific params before sending it // Update the Transformation Request with any specific params before sending it
@ -288,9 +292,10 @@ public class AlfrescoPdfRendererControllerTest extends AbstractTransformerContro
String transformationReplyAsString = mockMvc String transformationReplyAsString = mockMvc
.perform(MockMvcRequestBuilders .perform(MockMvcRequestBuilders
.post("/transform") .post("/transform")
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) .header(ACCEPT, APPLICATION_JSON_VALUE)
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).content(tr)) .header(CONTENT_TYPE, APPLICATION_JSON_VALUE)
.andExpect(status().is(HttpStatus.CREATED.value())) .content(tr))
.andExpect(status().is(CREATED.value()))
.andReturn().getResponse().getContentAsString(); .andReturn().getResponse().getContentAsString();
TransformReply transformReply = objectMapper.readValue(transformationReplyAsString, TransformReply transformReply = objectMapper.readValue(transformationReplyAsString,

View File

@ -65,7 +65,6 @@
<artifactId>dom4j</artifactId> <artifactId>dom4j</artifactId>
<version>2.1.1</version> <version>2.1.1</version>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -26,13 +26,21 @@
*/ */
package org.alfresco.transformer; package org.alfresco.transformer;
import static org.alfresco.transformer.logging.StandardMessages.LICENCE;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer; import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;
import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.MeterRegistry;
@ -40,6 +48,8 @@ import io.micrometer.core.instrument.MeterRegistry;
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class}) @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class Application public class Application
{ {
private static final Logger logger = LoggerFactory.getLogger(Application.class);
@Value("${container.name}") @Value("${container.name}")
private String containerName; private String containerName;
@ -53,4 +63,15 @@ public class Application
{ {
SpringApplication.run(Application.class, args); SpringApplication.run(Application.class, args);
} }
@EventListener(ApplicationReadyEvent.class)
public void startup()
{
logger.info("--------------------------------------------------------------------------------------------------------------------------------------------------------------");
Arrays.stream(LICENCE.split("\\n")).forEach(logger::info);
logger.info("This transformer uses ImageMagick from ImageMagick Studio LLC. See the license at http://www.imagemagick.org/script/license.php or in /ImageMagick-license.txt");
logger.info("--------------------------------------------------------------------------------------------------------------------------------------------------------------");
logger.info("Starting application components... Done");
}
} }

View File

@ -30,12 +30,11 @@ import static org.alfresco.transformer.fs.FileManager.createAttachment;
import static org.alfresco.transformer.fs.FileManager.createSourceFile; import static org.alfresco.transformer.fs.FileManager.createSourceFile;
import static org.alfresco.transformer.fs.FileManager.createTargetFile; import static org.alfresco.transformer.fs.FileManager.createTargetFile;
import static org.alfresco.transformer.fs.FileManager.createTargetFileName; import static org.alfresco.transformer.fs.FileManager.createTargetFileName;
import static org.alfresco.transformer.logging.StandardMessages.LICENCE;
import static org.alfresco.transformer.util.Util.stringToInteger; import static org.alfresco.transformer.util.Util.stringToInteger;
import static org.springframework.http.HttpStatus.OK; import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.Map; import java.util.Map;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -47,7 +46,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
@ -84,18 +82,6 @@ public class ImageMagickController extends AbstractTransformerController
@Autowired @Autowired
private ImageMagickCommandExecutor commandExecutor; private ImageMagickCommandExecutor commandExecutor;
@Autowired
public ImageMagickController()
{
logger.info(
"--------------------------------------------------------------------------------------------------------------------------------------------------------------");
Arrays.stream(LICENCE.split("\\n")).forEach(logger::info);
logger.info(
"This transformer uses ImageMagick from ImageMagick Studio LLC. See the license at http://www.imagemagick.org/script/license.php or in /ImageMagick-license.txt");
logger.info(
"--------------------------------------------------------------------------------------------------------------------------------------------------------------");
}
@Override @Override
public String getTransformerName() public String getTransformerName()
{ {
@ -123,7 +109,7 @@ public class ImageMagickController extends AbstractTransformerController
}; };
} }
@PostMapping(value = "/transform", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @PostMapping(value = "/transform", consumes = MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Resource> transform(HttpServletRequest request, public ResponseEntity<Resource> transform(HttpServletRequest request,
@RequestParam("file") MultipartFile sourceMultipartFile, @RequestParam("file") MultipartFile sourceMultipartFile,
@RequestParam("targetExtension") String targetExtension, @RequestParam("targetExtension") String targetExtension,

View File

@ -26,7 +26,6 @@
*/ */
package org.alfresco.transformer; package org.alfresco.transformer;
import static java.util.Arrays.asList;
import static org.alfresco.transformer.util.Util.stringToBoolean; import static org.alfresco.transformer.util.Util.stringToBoolean;
import static org.alfresco.transformer.util.Util.stringToInteger; import static org.alfresco.transformer.util.Util.stringToInteger;
import static org.springframework.http.HttpStatus.BAD_REQUEST; import static org.springframework.http.HttpStatus.BAD_REQUEST;
@ -36,6 +35,8 @@ import java.util.StringJoiner;
import org.alfresco.transform.exceptions.TransformException; import org.alfresco.transform.exceptions.TransformException;
import com.google.common.collect.ImmutableList;
/** /**
* ImageMagick options builder. * ImageMagick options builder.
* *
@ -43,8 +44,8 @@ import org.alfresco.transform.exceptions.TransformException;
*/ */
final class OptionsBuilder final class OptionsBuilder
{ {
private static final List<String> GRAVITY_VALUES = asList("North", "NorthEast", "East", private static final List<String> GRAVITY_VALUES = ImmutableList.of("North", "NorthEast",
"SouthEast", "South", "SouthWest", "West", "NorthWest", "Center"); "East", "SouthEast", "South", "SouthWest", "West", "NorthWest", "Center");
private Integer startPage; private Integer startPage;
private Integer endPage; private Integer endPage;
@ -64,9 +65,7 @@ final class OptionsBuilder
private Boolean maintainAspectRatio; private Boolean maintainAspectRatio;
private String commandOptions; private String commandOptions;
private OptionsBuilder() private OptionsBuilder() {}
{
}
public OptionsBuilder withStartPage(final String startPage) public OptionsBuilder withStartPage(final String startPage)
{ {

View File

@ -33,11 +33,18 @@ import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.springframework.http.HttpHeaders.ACCEPT;
import static org.springframework.http.HttpHeaders.CONTENT_DISPOSITION;
import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
import static org.springframework.http.HttpStatus.BAD_REQUEST; import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK; import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.http.MediaType.IMAGE_PNG_VALUE;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 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.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.util.StringUtils.getFilenameExtension;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -63,14 +70,11 @@ import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile; import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.util.StringUtils;
/** /**
* Test the ImageMagickController without a server. * Test the ImageMagickController without a server.
@ -128,7 +132,7 @@ public class ImageMagickControllerTest extends AbstractTransformerControllerTest
String actualOptions = actualProperties.get("options"); String actualOptions = actualProperties.get("options");
String actualSource = actualProperties.get("source"); String actualSource = actualProperties.get("source");
String actualTarget = actualProperties.get("target"); String actualTarget = actualProperties.get("target");
String actualTargetExtension = StringUtils.getFilenameExtension(actualTarget); String actualTargetExtension = getFilenameExtension(actualTarget);
assertNotNull(actualSource); assertNotNull(actualSource);
assertNotNull(actualTarget); assertNotNull(actualTarget);
@ -312,8 +316,8 @@ public class ImageMagickControllerTest extends AbstractTransformerControllerTest
{ {
transformRequest.setSourceExtension("png"); transformRequest.setSourceExtension("png");
transformRequest.setTargetExtension("png"); transformRequest.setTargetExtension("png");
transformRequest.setSourceMediaType(MediaType.IMAGE_PNG_VALUE); transformRequest.setSourceMediaType(IMAGE_PNG_VALUE);
transformRequest.setTargetMediaType(MediaType.IMAGE_PNG_VALUE); transformRequest.setTargetMediaType(IMAGE_PNG_VALUE);
} }
@Test @Test
@ -348,14 +352,13 @@ public class ImageMagickControllerTest extends AbstractTransformerControllerTest
// HTTP Request // HTTP Request
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.CONTENT_DISPOSITION, headers.set(CONTENT_DISPOSITION, "attachment; filename=quick." + sourceExtension);
"attachment; filename=quick." + sourceExtension);
ResponseEntity<Resource> response = new ResponseEntity<>(new FileSystemResource( ResponseEntity<Resource> response = new ResponseEntity<>(new FileSystemResource(
sourceFile), headers, OK); sourceFile), headers, OK);
when(alfrescoSharedFileStoreClient.retrieveFile(sourceFileRef)).thenReturn(response); when(alfrescoSharedFileStoreClient.retrieveFile(sourceFileRef)).thenReturn(response);
when(alfrescoSharedFileStoreClient.saveFile(any())).thenReturn( when(alfrescoSharedFileStoreClient.saveFile(any()))
new FileRefResponse(new FileRefEntity(targetFileRef))); .thenReturn(new FileRefResponse(new FileRefEntity(targetFileRef)));
when(mockExecutionResult.getExitValue()).thenReturn(0); when(mockExecutionResult.getExitValue()).thenReturn(0);
// Update the Transformation Request with any specific params before sending it // Update the Transformation Request with any specific params before sending it
@ -366,10 +369,10 @@ public class ImageMagickControllerTest extends AbstractTransformerControllerTest
String transformationReplyAsString = mockMvc String transformationReplyAsString = mockMvc
.perform(MockMvcRequestBuilders .perform(MockMvcRequestBuilders
.post("/transform") .post("/transform")
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) .header(ACCEPT, APPLICATION_JSON_VALUE)
.header(HttpHeaders.CONTENT_TYPE, .header(CONTENT_TYPE, APPLICATION_JSON_VALUE)
MediaType.APPLICATION_JSON_VALUE).content(tr)) .content(tr))
.andExpect(status().is(HttpStatus.CREATED.value())) .andExpect(status().is(CREATED.value()))
.andReturn().getResponse().getContentAsString(); .andReturn().getResponse().getContentAsString();
TransformReply transformReply = objectMapper.readValue(transformationReplyAsString, TransformReply transformReply = objectMapper.readValue(transformationReplyAsString,

View File

@ -57,6 +57,7 @@ public class ImageMagickQueueTransformServiceIT extends AbstractQueueTransformSe
.withSchema(1) .withSchema(1)
.withClientData("ACS") .withClientData("ACS")
.withSourceReference(UUID.randomUUID().toString()) .withSourceReference(UUID.randomUUID().toString())
.withSourceSize(32L).build(); .withSourceSize(32L)
.build();
} }
} }

View File

@ -26,13 +26,21 @@
*/ */
package org.alfresco.transformer; package org.alfresco.transformer;
import static org.alfresco.transformer.logging.StandardMessages.LICENCE;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer; import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;
import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.MeterRegistry;
@ -40,6 +48,8 @@ import io.micrometer.core.instrument.MeterRegistry;
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class}) @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class Application public class Application
{ {
private static final Logger logger = LoggerFactory.getLogger(Application.class);
@Value("${container.name}") @Value("${container.name}")
private String containerName; private String containerName;
@ -53,4 +63,15 @@ public class Application
{ {
SpringApplication.run(Application.class, args); SpringApplication.run(Application.class, args);
} }
@EventListener(ApplicationReadyEvent.class)
public void startup()
{
logger.info("-------------------------------------------------------------------------------------------------------------------------------------------------------");
Arrays.stream(LICENCE.split("\\n")).forEach(logger::info);
logger.info("This transformer uses LibreOffice from The Document Foundation. See the license at https://www.libreoffice.org/download/license/ or in /libreoffice.txt");
logger.info("-------------------------------------------------------------------------------------------------------------------------------------------------------");
logger.info("Starting application components... Done");
}
} }

View File

@ -30,11 +30,10 @@ import static org.alfresco.transformer.fs.FileManager.createAttachment;
import static org.alfresco.transformer.fs.FileManager.createSourceFile; import static org.alfresco.transformer.fs.FileManager.createSourceFile;
import static org.alfresco.transformer.fs.FileManager.createTargetFile; import static org.alfresco.transformer.fs.FileManager.createTargetFile;
import static org.alfresco.transformer.fs.FileManager.createTargetFileName; import static org.alfresco.transformer.fs.FileManager.createTargetFileName;
import static org.alfresco.transformer.logging.StandardMessages.LICENCE;
import static org.springframework.http.HttpStatus.OK; import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.Map; import java.util.Map;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -46,7 +45,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
@ -82,18 +80,6 @@ public class LibreOfficeController extends AbstractTransformerController
@Autowired @Autowired
private LibreOfficeJavaExecutor javaExecutor; private LibreOfficeJavaExecutor javaExecutor;
@Autowired
public LibreOfficeController()
{
logger.info(
"-------------------------------------------------------------------------------------------------------------------------------------------------------");
Arrays.stream(LICENCE.split("\\n")).forEach(logger::info);
logger.info(
"This transformer uses LibreOffice from The Document Foundation. See the license at https://www.libreoffice.org/download/license/ or in /libreoffice.txt");
logger.info(
"-------------------------------------------------------------------------------------------------------------------------------------------------------");
}
@Override @Override
public String getTransformerName() public String getTransformerName()
{ {
@ -122,7 +108,7 @@ public class LibreOfficeController extends AbstractTransformerController
} }
//todo: the "timeout" request parameter is ignored; the timeout is preset at JodConverter creation //todo: the "timeout" request parameter is ignored; the timeout is preset at JodConverter creation
@PostMapping(value = "/transform", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @PostMapping(value = "/transform", consumes = MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Resource> transform(HttpServletRequest request, public ResponseEntity<Resource> transform(HttpServletRequest request,
@RequestParam("file") MultipartFile sourceMultipartFile, @RequestParam("file") MultipartFile sourceMultipartFile,
@RequestParam("targetExtension") String targetExtension, @RequestParam("targetExtension") String targetExtension,

View File

@ -34,7 +34,15 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.springframework.http.HttpHeaders.ACCEPT;
import static org.springframework.http.HttpHeaders.CONTENT_DISPOSITION;
import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.http.MediaType.IMAGE_PNG_VALUE;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.util.StringUtils.getFilenameExtension;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -59,13 +67,10 @@ import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile; import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.util.StringUtils;
/** /**
* Test the LibreOfficeController without a server. * Test the LibreOfficeController without a server.
@ -105,8 +110,7 @@ public class LibreOfficeControllerTest extends AbstractTransformerControllerTest
{ {
File sourceFile = invocation.getArgument(0); File sourceFile = invocation.getArgument(0);
File targetFile = invocation.getArgument(1); File targetFile = invocation.getArgument(1);
String actualTargetExtension = StringUtils.getFilenameExtension( String actualTargetExtension = getFilenameExtension(targetFile.getAbsolutePath());
targetFile.getAbsolutePath());
assertNotNull(sourceFile); assertNotNull(sourceFile);
assertNotNull(targetFile); assertNotNull(targetFile);
@ -164,7 +168,7 @@ public class LibreOfficeControllerTest extends AbstractTransformerControllerTest
transformRequest.setSourceExtension("doc"); transformRequest.setSourceExtension("doc");
transformRequest.setTargetExtension("pdf"); transformRequest.setTargetExtension("pdf");
transformRequest.setSourceMediaType("application/msword"); transformRequest.setSourceMediaType("application/msword");
transformRequest.setTargetMediaType(MediaType.IMAGE_PNG_VALUE); transformRequest.setTargetMediaType(IMAGE_PNG_VALUE);
} }
@Test @Test
@ -188,14 +192,13 @@ public class LibreOfficeControllerTest extends AbstractTransformerControllerTest
// HTTP Request // HTTP Request
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.CONTENT_DISPOSITION, headers.set(CONTENT_DISPOSITION, "attachment; filename=quick." + sourceExtension);
"attachment; filename=quick." + sourceExtension);
ResponseEntity<Resource> response = new ResponseEntity<>(new FileSystemResource( ResponseEntity<Resource> response = new ResponseEntity<>(new FileSystemResource(
sourceFile), headers, HttpStatus.OK); sourceFile), headers, OK);
when(alfrescoSharedFileStoreClient.retrieveFile(sourceFileRef)).thenReturn(response); when(alfrescoSharedFileStoreClient.retrieveFile(sourceFileRef)).thenReturn(response);
when(alfrescoSharedFileStoreClient.saveFile(any())).thenReturn( when(alfrescoSharedFileStoreClient.saveFile(any()))
new FileRefResponse(new FileRefEntity(targetFileRef))); .thenReturn(new FileRefResponse(new FileRefEntity(targetFileRef)));
when(mockExecutionResult.getExitValue()).thenReturn(0); when(mockExecutionResult.getExitValue()).thenReturn(0);
// Update the Transformation Request with any specific params before sending it // Update the Transformation Request with any specific params before sending it
@ -203,13 +206,13 @@ public class LibreOfficeControllerTest extends AbstractTransformerControllerTest
// Serialize and call the transformer // Serialize and call the transformer
String tr = objectMapper.writeValueAsString(transformRequest); String tr = objectMapper.writeValueAsString(transformRequest);
String transformationReplyAsString = mockMvc.perform( String transformationReplyAsString = mockMvc
MockMvcRequestBuilders.post("/transform") .perform(MockMvcRequestBuilders
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) .post("/transform")
.header(HttpHeaders.CONTENT_TYPE, .header(ACCEPT, APPLICATION_JSON_VALUE)
MediaType.APPLICATION_JSON_VALUE).content(tr)) .header(CONTENT_TYPE, APPLICATION_JSON_VALUE)
.andExpect( .content(tr))
status().is(HttpStatus.CREATED.value())) .andExpect(status().is(CREATED.value()))
.andReturn().getResponse().getContentAsString(); .andReturn().getResponse().getContentAsString();
TransformReply transformReply = objectMapper.readValue(transformationReplyAsString, TransformReply transformReply = objectMapper.readValue(transformationReplyAsString,

View File

@ -56,6 +56,7 @@ public class LibreOfficeQueueTransformServiceIT extends AbstractQueueTransformSe
.withSchema(1) .withSchema(1)
.withClientData("ACS") .withClientData("ACS")
.withSourceReference(UUID.randomUUID().toString()) .withSourceReference(UUID.randomUUID().toString())
.withSourceSize(32L).build(); .withSourceSize(32L)
.build();
} }
} }

View File

@ -26,13 +26,21 @@
*/ */
package org.alfresco.transformer; package org.alfresco.transformer;
import static org.alfresco.transformer.logging.StandardMessages.LICENCE;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer; import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;
import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.MeterRegistry;
@ -40,6 +48,8 @@ import io.micrometer.core.instrument.MeterRegistry;
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class}) @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class Application public class Application
{ {
private static final Logger logger = LoggerFactory.getLogger(Application.class);
@Value("${container.name}") @Value("${container.name}")
private String containerName; private String containerName;
@ -53,4 +63,15 @@ public class Application
{ {
SpringApplication.run(Application.class, args); SpringApplication.run(Application.class, args);
} }
@EventListener(ApplicationReadyEvent.class)
public void startup()
{
logger.info("--------------------------------------------------------------------------------------------------------------------------------------------------------------");
Arrays.stream(LICENCE.split("\\n")).forEach(logger::info);
logger.info("Tika is from Apache. See the license at http://www.apache.org/licenses/LICENSE-2.0. or in /Apache\\ 2.0.txt");
logger.info("--------------------------------------------------------------------------------------------------------------------------------------------------------------");
logger.info("Starting application components... Done");
}
} }

View File

@ -37,13 +37,12 @@ import static org.alfresco.transformer.fs.FileManager.createAttachment;
import static org.alfresco.transformer.fs.FileManager.createSourceFile; import static org.alfresco.transformer.fs.FileManager.createSourceFile;
import static org.alfresco.transformer.fs.FileManager.createTargetFile; import static org.alfresco.transformer.fs.FileManager.createTargetFile;
import static org.alfresco.transformer.fs.FileManager.createTargetFileName; import static org.alfresco.transformer.fs.FileManager.createTargetFileName;
import static org.alfresco.transformer.logging.StandardMessages.LICENCE;
import static org.alfresco.transformer.util.Util.stringToBoolean; import static org.alfresco.transformer.util.Util.stringToBoolean;
import static org.springframework.http.HttpStatus.BAD_REQUEST; import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.OK; import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE;
import java.io.File; import java.io.File;
import java.util.Arrays;
import java.util.Map; import java.util.Map;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -56,7 +55,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
@ -69,9 +67,9 @@ import org.springframework.web.multipart.MultipartFile;
* Status Codes: * Status Codes:
* *
* 200 Success * 200 Success
* 400 Bad Request: Invalid target mimetype &lt;mimetype> * 400 Bad Request: Invalid target mimetype <mimetype>
* 400 Bad Request: Request parameter &lt;name> is missing (missing mandatory parameter) * 400 Bad Request: Request parameter <name> is missing (missing mandatory parameter)
* 400 Bad Request: Request parameter &lt;name> is of the wrong type * 400 Bad Request: Request parameter <name> is of the wrong type
* 400 Bad Request: Transformer exit code was not 0 (possible problem with the source file) * 400 Bad Request: Transformer exit code was not 0 (possible problem with the source file)
* 400 Bad Request: The source filename was not supplied * 400 Bad Request: The source filename was not supplied
* 500 Internal Server Error: (no message with low level IO problems) * 500 Internal Server Error: (no message with low level IO problems)
@ -92,18 +90,6 @@ public class TikaController extends AbstractTransformerController
@Autowired @Autowired
private TikaJavaExecutor javaExecutor; private TikaJavaExecutor javaExecutor;
@Autowired
public TikaController()
{
logger.info(
"--------------------------------------------------------------------------------------------------------------------------------------------------------------");
Arrays.stream(LICENCE.split("\\n")).forEach(logger::info);
logger.info(
"Tika is from Apache. See the license at http://www.apache.org/licenses/LICENSE-2.0. or in /Apache\\ 2.0.txt");
logger.info(
"--------------------------------------------------------------------------------------------------------------------------------------------------------------");
}
@Override @Override
public String getTransformerName() public String getTransformerName()
{ {
@ -133,7 +119,7 @@ public class TikaController extends AbstractTransformerController
}; };
} }
@PostMapping(value = "/transform", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @PostMapping(value = "/transform", consumes = MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Resource> transform(HttpServletRequest request, public ResponseEntity<Resource> transform(HttpServletRequest request,
@RequestParam("file") MultipartFile sourceMultipartFile, @RequestParam("file") MultipartFile sourceMultipartFile,
@RequestParam("targetExtension") String targetExtension, @RequestParam("targetExtension") String targetExtension,

View File

@ -26,7 +26,6 @@
*/ */
package org.alfresco.transformer.executors; package org.alfresco.transformer.executors;
import static java.util.Arrays.asList;
import static org.alfresco.repo.content.MimetypeMap.MIMETYPE_HTML; import static org.alfresco.repo.content.MimetypeMap.MIMETYPE_HTML;
import static org.alfresco.repo.content.MimetypeMap.MIMETYPE_IMAGE_JPEG; import static org.alfresco.repo.content.MimetypeMap.MIMETYPE_IMAGE_JPEG;
import static org.alfresco.repo.content.MimetypeMap.MIMETYPE_IMAGE_PNG; import static org.alfresco.repo.content.MimetypeMap.MIMETYPE_IMAGE_PNG;
@ -74,6 +73,8 @@ import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler; import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import com.google.common.collect.ImmutableList;
/** /**
* Stripped down command line Tika transformers. Not actually run as a separate process, but the code fits the patten * Stripped down command line Tika transformers. Not actually run as a separate process, but the code fits the patten
* used by transformers that do. * used by transformers that do.
@ -455,7 +456,7 @@ public class Tika
public static final String TIKA_AUTO = "TikaAuto"; public static final String TIKA_AUTO = "TikaAuto";
public static final String TEXT_MINING = "TextMining"; public static final String TEXT_MINING = "TextMining";
public static final List<String> TRANSFORM_NAMES = asList( public static final List<String> TRANSFORM_NAMES = ImmutableList.of(
ARCHIVE, OUTLOOK_MSG, PDF_BOX, POI_OFFICE, POI, POI_OO_XML, TIKA_AUTO, TEXT_MINING); ARCHIVE, OUTLOOK_MSG, PDF_BOX, POI_OFFICE, POI, POI_OO_XML, TIKA_AUTO, TEXT_MINING);
public static final String TARGET_MIMETYPE = "--targetMimetype="; public static final String TARGET_MIMETYPE = "--targetMimetype=";
@ -484,9 +485,9 @@ public class Tika
private final Parser tikaOfficeDetectParser = new TikaOfficeDetectParser(); private final Parser tikaOfficeDetectParser = new TikaOfficeDetectParser();
private final PDFParserConfig pdfParserConfig = new PDFParserConfig(); private final PDFParserConfig pdfParserConfig = new PDFParserConfig();
private DocumentSelector pdfBoxEmbededDocumentSelector = new DocumentSelector() private final DocumentSelector pdfBoxEmbededDocumentSelector = new DocumentSelector()
{ {
private final List<String> disabledMediaTypes = asList(MIMETYPE_IMAGE_JPEG, private final List<String> disabledMediaTypes = ImmutableList.of(MIMETYPE_IMAGE_JPEG,
MIMETYPE_IMAGE_TIFF, MIMETYPE_IMAGE_PNG); MIMETYPE_IMAGE_TIFF, MIMETYPE_IMAGE_PNG);
@Override @Override

View File

@ -64,10 +64,18 @@ import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.springframework.http.HttpHeaders.ACCEPT;
import static org.springframework.http.HttpHeaders.CONTENT_DISPOSITION;
import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.http.HttpStatus.OK; import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.http.MediaType.APPLICATION_PDF_VALUE;
import static org.springframework.http.MediaType.TEXT_PLAIN_VALUE;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.util.StringUtils.getFilenameExtension;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -93,15 +101,12 @@ import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile; import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.util.StringUtils;
/** /**
* Test the TikaController without a server. * Test the TikaController without a server.
@ -169,7 +174,7 @@ public class TikaControllerTest extends AbstractTransformerControllerTest
String actualOptions = actualProperties.get("options"); String actualOptions = actualProperties.get("options");
String actualSource = actualProperties.get("source"); String actualSource = actualProperties.get("source");
String actualTarget = actualProperties.get("target"); String actualTarget = actualProperties.get("target");
String actualTargetExtension = StringUtils.getFilenameExtension(actualTarget); String actualTargetExtension = getFilenameExtension(actualTarget);
assertNotNull(actualSource); assertNotNull(actualSource);
assertNotNull(actualTarget); assertNotNull(actualTarget);
@ -533,11 +538,10 @@ public class TikaControllerTest extends AbstractTransformerControllerTest
{ {
transformRequest.setSourceExtension(sourceExtension); transformRequest.setSourceExtension(sourceExtension);
transformRequest.setTargetExtension(targetExtension); transformRequest.setTargetExtension(targetExtension);
transformRequest.setSourceMediaType(MediaType.APPLICATION_PDF_VALUE); transformRequest.setSourceMediaType(APPLICATION_PDF_VALUE);
transformRequest.setTargetMediaType(MediaType.TEXT_PLAIN_VALUE); transformRequest.setTargetMediaType(TEXT_PLAIN_VALUE);
transformRequest.getTransformRequestOptions().put("transform", "PdfBox"); transformRequest.getTransformRequestOptions().put("transform", "PdfBox");
transformRequest.getTransformRequestOptions().put("targetMimetype", transformRequest.getTransformRequestOptions().put("targetMimetype", TEXT_PLAIN_VALUE);
MediaType.TEXT_PLAIN_VALUE);
transformRequest.getTransformRequestOptions().put("targetEncoding", "UTF-8"); transformRequest.getTransformRequestOptions().put("targetEncoding", "UTF-8");
} }
@ -562,14 +566,13 @@ public class TikaControllerTest extends AbstractTransformerControllerTest
// HTTP Request // HTTP Request
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.CONTENT_DISPOSITION, headers.set(CONTENT_DISPOSITION, "attachment; filename=quick." + sourceExtension);
"attachment; filename=quick." + sourceExtension);
ResponseEntity<Resource> response = new ResponseEntity<>(new FileSystemResource( ResponseEntity<Resource> response = new ResponseEntity<>(new FileSystemResource(
sourceFile), headers, OK); sourceFile), headers, OK);
when(alfrescoSharedFileStoreClient.retrieveFile(sourceFileRef)).thenReturn(response); when(alfrescoSharedFileStoreClient.retrieveFile(sourceFileRef)).thenReturn(response);
when(alfrescoSharedFileStoreClient.saveFile(any())).thenReturn( when(alfrescoSharedFileStoreClient.saveFile(any()))
new FileRefResponse(new FileRefEntity(targetFileRef))); .thenReturn(new FileRefResponse(new FileRefEntity(targetFileRef)));
when(mockExecutionResult.getExitValue()).thenReturn(0); when(mockExecutionResult.getExitValue()).thenReturn(0);
// Update the Transformation Request with any specific params before sending it // Update the Transformation Request with any specific params before sending it
@ -577,13 +580,13 @@ public class TikaControllerTest extends AbstractTransformerControllerTest
// Serialize and call the transformer // Serialize and call the transformer
String tr = objectMapper.writeValueAsString(transformRequest); String tr = objectMapper.writeValueAsString(transformRequest);
String transformationReplyAsString = mockMvc.perform( String transformationReplyAsString = mockMvc
MockMvcRequestBuilders.post("/transform") .perform(MockMvcRequestBuilders
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) .post("/transform")
.header(HttpHeaders.CONTENT_TYPE, .header(ACCEPT, APPLICATION_JSON_VALUE)
MediaType.APPLICATION_JSON_VALUE).content(tr)) .header(CONTENT_TYPE, APPLICATION_JSON_VALUE)
.andExpect( .content(tr))
status().is(HttpStatus.CREATED.value())) .andExpect(status().is(CREATED.value()))
.andReturn().getResponse().getContentAsString(); .andReturn().getResponse().getContentAsString();
TransformReply transformReply = objectMapper.readValue(transformationReplyAsString, TransformReply transformReply = objectMapper.readValue(transformationReplyAsString,

View File

@ -26,13 +26,17 @@
*/ */
package org.alfresco.transformer; package org.alfresco.transformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer; import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;
import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.MeterRegistry;
@ -40,6 +44,8 @@ import io.micrometer.core.instrument.MeterRegistry;
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class}) @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class Application public class Application
{ {
private static final Logger logger = LoggerFactory.getLogger(Application.class);
@Value("${container.name}") @Value("${container.name}")
private String containerName; private String containerName;
@ -53,4 +59,16 @@ public class Application
{ {
SpringApplication.run(Application.class, args); SpringApplication.run(Application.class, args);
} }
@EventListener(ApplicationReadyEvent.class)
public void startup()
{
logger.info("--------------------------------------------------------------------------------------------------------------------------------------------------------------");
logger.info("The transformers in this project use libraries from Apache. See the license at http://www.apache.org/licenses/LICENSE-2.0. or in /Apache\\\\ 2.0.txt");
logger.info("Additional libraries used:");
logger.info("* htmlparser http://htmlparser.sourceforge.net/license.html");
logger.info("--------------------------------------------------------------------------------------------------------------------------------------------------------------");
logger.info("Starting application components... Done");
}
} }

View File

@ -64,18 +64,6 @@ public class MiscController extends AbstractTransformerController
@Autowired @Autowired
private SelectingTransformer transformer; private SelectingTransformer transformer;
public MiscController()
{
logger.info(
"--------------------------------------------------------------------------------------------------------------------------------------------------------------");
logger.info(
"The transformers in this project use libraries from Apache. See the license at http://www.apache.org/licenses/LICENSE-2.0. or in /Apache\\\\ 2.0.txt");
logger.info("Additional libraries used:");
logger.info("* htmlparser http://htmlparser.sourceforge.net/license.html");
logger.info(
"--------------------------------------------------------------------------------------------------------------------------------------------------------------");
}
@Override @Override
public String getTransformerName() public String getTransformerName()
{ {

View File

@ -26,6 +26,7 @@
*/ */
package org.alfresco.transformer.transformers; package org.alfresco.transformer.transformers;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_IMAGE_JPEG;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_IWORK_KEYNOTE; import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_IWORK_KEYNOTE;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_IWORK_NUMBERS; import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_IWORK_NUMBERS;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_IWORK_PAGES; import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_IWORK_PAGES;
@ -36,17 +37,17 @@ import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.StandardCopyOption; import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.alfresco.error.AlfrescoRuntimeException; import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.transform.client.model.Mimetype;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableList;
/** /**
* Converts Apple iWorks files to JPEGs for thumbnailing & previewing. * Converts Apple iWorks files to JPEGs for thumbnailing & previewing.
* The transformer will only work for iWorks 2013/14 files. Support for iWorks 2008/9 has been dropped as we cannot * The transformer will only work for iWorks 2013/14 files. Support for iWorks 2008/9 has been dropped as we cannot
@ -64,9 +65,9 @@ public class AppleIWorksContentTransformer implements SelectableTransformer
AppleIWorksContentTransformer.class); AppleIWorksContentTransformer.class);
// Apple's zip entry names for previews in iWorks have changed over time. // Apple's zip entry names for previews in iWorks have changed over time.
private static final List<String> PDF_PATHS = Arrays.asList( private static final List<String> PDF_PATHS = ImmutableList.of(
"QuickLook/Preview.pdf"); // iWorks 2008/9 "QuickLook/Preview.pdf"); // iWorks 2008/9
private static final List<String> JPG_PATHS = Arrays.asList( private static final List<String> JPG_PATHS = ImmutableList.of(
"QuickLook/Thumbnail.jpg", // iWorks 2008/9 "QuickLook/Thumbnail.jpg", // iWorks 2008/9
"preview.jpg"); // iWorks 2013/14 (720 x 552) We use the best quality image. Others are: "preview.jpg"); // iWorks 2013/14 (720 x 552) We use the best quality image. Others are:
// (225 x 173) preview-web.jpg // (225 x 173) preview-web.jpg
@ -76,10 +77,9 @@ public class AppleIWorksContentTransformer implements SelectableTransformer
public boolean isTransformable(String sourceMimetype, String targetMimetype, public boolean isTransformable(String sourceMimetype, String targetMimetype,
Map<String, String> parameters) Map<String, String> parameters)
{ {
boolean transformable = MIMETYPE_IWORK_KEYNOTE.equals(sourceMimetype) return MIMETYPE_IWORK_KEYNOTE.equals(sourceMimetype) ||
|| MIMETYPE_IWORK_NUMBERS.equals(sourceMimetype) MIMETYPE_IWORK_NUMBERS.equals(sourceMimetype) ||
|| MIMETYPE_IWORK_PAGES.equals(sourceMimetype); MIMETYPE_IWORK_PAGES.equals(sourceMimetype);
return transformable;
} }
@Override @Override
@ -88,19 +88,16 @@ public class AppleIWorksContentTransformer implements SelectableTransformer
final String sourceMimetype = parameters.get(SOURCE_MIMETYPE); final String sourceMimetype = parameters.get(SOURCE_MIMETYPE);
final String targetMimetype = parameters.get(TARGET_MIMETYPE); final String targetMimetype = parameters.get(TARGET_MIMETYPE);
if (logger.isDebugEnabled()) logger.debug("Performing IWorks to jpeg transform with sourceMimetype={} targetMimetype={}",
{ sourceMimetype, targetMimetype);
logger.debug("Performing IWorks to jpeg transform with sourceMimetype=" + sourceMimetype
+ " targetMimetype=" + targetMimetype);
}
// iWorks files are zip (or package) files. // iWorks files are zip (or package) files.
// If it's not a zip file, the resultant ZipException will be caught as an IOException below. // If it's not a zip file, the resultant ZipException will be caught as an IOException below.
try (ZipArchiveInputStream iWorksZip = new ZipArchiveInputStream( try (ZipArchiveInputStream iWorksZip = new ZipArchiveInputStream(
new BufferedInputStream(new FileInputStream(sourceFile)))) new BufferedInputStream(new FileInputStream(sourceFile))))
{ {
// Look through the zip file entries for the preview/thumbnail. // Look through the zip file entries for the preview/thumbnail.
List<String> paths = Mimetype.MIMETYPE_IMAGE_JPEG.equals( List<String> paths = MIMETYPE_IMAGE_JPEG.equals(targetMimetype) ? JPG_PATHS : PDF_PATHS;
targetMimetype) ? JPG_PATHS : PDF_PATHS;
ZipArchiveEntry entry; ZipArchiveEntry entry;
boolean found = false; boolean found = false;
while ((entry = iWorksZip.getNextZipEntry()) != null) while ((entry = iWorksZip.getNextZipEntry()) != null)

View File

@ -85,8 +85,8 @@ public class HtmlParserContentTransformer implements SelectableTransformer
} }
@Override @Override
public void transform(File sourceFile, File targetFile, Map<String, String> parameters) throws public void transform(File sourceFile, File targetFile, Map<String, String> parameters)
Exception throws Exception
{ {
String sourceEncoding = parameters.get(SOURCE_ENCODING); String sourceEncoding = parameters.get(SOURCE_ENCODING);
checkEncodingParameter(sourceEncoding, SOURCE_ENCODING); checkEncodingParameter(sourceEncoding, SOURCE_ENCODING);
@ -113,20 +113,20 @@ public class HtmlParserContentTransformer implements SelectableTransformer
} }
} }
private void checkEncodingParameter(String encoding, String paramterName) private void checkEncodingParameter(String encoding, String parameterName)
{ {
try try
{ {
if (encoding != null && !Charset.isSupported(encoding)) if (encoding != null && !Charset.isSupported(encoding))
{ {
throw new IllegalArgumentException( throw new IllegalArgumentException(
paramterName + "=" + encoding + " is not supported by the JVM."); parameterName + "=" + encoding + " is not supported by the JVM.");
} }
} }
catch (IllegalCharsetNameException e) catch (IllegalCharsetNameException e)
{ {
throw new IllegalArgumentException( throw new IllegalArgumentException(
paramterName + "=" + encoding + " is not a valid encoding."); parameterName + "=" + encoding + " is not a valid encoding.");
} }
} }
@ -159,7 +159,7 @@ public class HtmlParserContentTransformer implements SelectableTransformer
String previousURL = getURL(); String previousURL = getURL();
String newURL = file.getAbsolutePath(); String newURL = file.getAbsolutePath();
if ((previousURL == null) || (!newURL.equals(previousURL))) if (previousURL == null || !newURL.equals(previousURL))
{ {
try try
{ {

View File

@ -26,17 +26,36 @@
*/ */
package org.alfresco.transformer.transformers; package org.alfresco.transformer.transformers;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_IMAGE_JPEG;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_OPENXML_PRESENTATION;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_OPENXML_PRESENTATION_ADDIN;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_OPENXML_PRESENTATION_MACRO;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_OPENXML_PRESENTATION_SLIDE;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_OPENXML_PRESENTATION_SLIDESHOW;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_OPENXML_PRESENTATION_SLIDESHOW_MACRO;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_OPENXML_PRESENTATION_SLIDE_MACRO;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_OPENXML_PRESENTATION_TEMPLATE;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_OPENXML_PRESENTATION_TEMPLATE_MACRO;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_OPENXML_SPREADSHEET;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_OPENXML_SPREADSHEET_ADDIN_MACRO;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_OPENXML_SPREADSHEET_BINARY_MACRO;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_OPENXML_SPREADSHEET_MACRO;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_OPENXML_SPREADSHEET_TEMPLATE;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_OPENXML_SPREADSHEET_TEMPLATE_MACRO;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_OPENXML_WORDPROCESSING;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_OPENXML_WORDPROCESSING_MACRO;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_OPENXML_WORD_TEMPLATE;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_OPENXML_WORD_TEMPLATE_MACRO;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.StandardCopyOption; import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.alfresco.error.AlfrescoRuntimeException; import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.transform.client.model.Mimetype;
import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.openxml4j.opc.PackageRelationship;
@ -45,6 +64,8 @@ import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableList;
/** /**
* Extracts out Thumbnail JPEGs from OOXML files for thumbnailing & previewing. * Extracts out Thumbnail JPEGs from OOXML files for thumbnailing & previewing.
* This transformer will only work for OOXML files where thumbnailing was enabled, * This transformer will only work for OOXML files where thumbnailing was enabled,
@ -58,38 +79,39 @@ public class OOXMLThumbnailContentTransformer implements SelectableTransformer
private static final Logger logger = LoggerFactory.getLogger( private static final Logger logger = LoggerFactory.getLogger(
OOXMLThumbnailContentTransformer.class); OOXMLThumbnailContentTransformer.class);
private static final List<String> OOXML_MIMETYPES = Arrays.asList(Mimetype.MIMETYPE_OPENXML_WORDPROCESSING, private static final List<String> OOXML_MIMETYPES = ImmutableList.of(
Mimetype.MIMETYPE_OPENXML_WORDPROCESSING_MACRO, MIMETYPE_OPENXML_WORDPROCESSING,
Mimetype.MIMETYPE_OPENXML_WORD_TEMPLATE, MIMETYPE_OPENXML_WORDPROCESSING_MACRO,
Mimetype.MIMETYPE_OPENXML_WORD_TEMPLATE_MACRO, MIMETYPE_OPENXML_WORD_TEMPLATE,
Mimetype.MIMETYPE_OPENXML_PRESENTATION, MIMETYPE_OPENXML_WORD_TEMPLATE_MACRO,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_MACRO, MIMETYPE_OPENXML_PRESENTATION,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_SLIDESHOW, MIMETYPE_OPENXML_PRESENTATION_MACRO,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_SLIDESHOW_MACRO, MIMETYPE_OPENXML_PRESENTATION_SLIDESHOW,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_TEMPLATE, MIMETYPE_OPENXML_PRESENTATION_SLIDESHOW_MACRO,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_TEMPLATE_MACRO, MIMETYPE_OPENXML_PRESENTATION_TEMPLATE,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_ADDIN, MIMETYPE_OPENXML_PRESENTATION_TEMPLATE_MACRO,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_SLIDE, MIMETYPE_OPENXML_PRESENTATION_ADDIN,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_SLIDE_MACRO, MIMETYPE_OPENXML_PRESENTATION_SLIDE,
Mimetype.MIMETYPE_OPENXML_SPREADSHEET, MIMETYPE_OPENXML_PRESENTATION_SLIDE_MACRO,
Mimetype.MIMETYPE_OPENXML_SPREADSHEET_TEMPLATE, MIMETYPE_OPENXML_SPREADSHEET,
Mimetype.MIMETYPE_OPENXML_SPREADSHEET_MACRO, MIMETYPE_OPENXML_SPREADSHEET_TEMPLATE,
Mimetype.MIMETYPE_OPENXML_SPREADSHEET_TEMPLATE_MACRO, MIMETYPE_OPENXML_SPREADSHEET_MACRO,
Mimetype.MIMETYPE_OPENXML_SPREADSHEET_ADDIN_MACRO, MIMETYPE_OPENXML_SPREADSHEET_TEMPLATE_MACRO,
Mimetype.MIMETYPE_OPENXML_SPREADSHEET_BINARY_MACRO); MIMETYPE_OPENXML_SPREADSHEET_ADDIN_MACRO,
MIMETYPE_OPENXML_SPREADSHEET_BINARY_MACRO);
@Override @Override
public boolean isTransformable(String sourceMimetype, String targetMimetype, public boolean isTransformable(String sourceMimetype, String targetMimetype,
Map<String, String> parameters) Map<String, String> parameters)
{ {
// only support [OOXML] -> JPEG // only support [OOXML] -> JPEG
return Mimetype.MIMETYPE_IMAGE_JPEG.equals(targetMimetype) && OOXML_MIMETYPES.contains( return MIMETYPE_IMAGE_JPEG.equals(targetMimetype) &&
sourceMimetype); OOXML_MIMETYPES.contains(sourceMimetype);
} }
@Override @Override
public void transform(File sourceFile, File targetFile, Map<String, String> parameters) throws public void transform(File sourceFile, File targetFile, Map<String, String> parameters)
Exception throws Exception
{ {
final String sourceMimetype = parameters.get(SOURCE_MIMETYPE); final String sourceMimetype = parameters.get(SOURCE_MIMETYPE);
final String targetMimetype = parameters.get(TARGET_MIMETYPE); final String targetMimetype = parameters.get(TARGET_MIMETYPE);

View File

@ -49,8 +49,8 @@ public interface SelectableTransformer
* @param parameters * @param parameters
* @throws Exception * @throws Exception
*/ */
void transform(File sourceFile, File targetFile, Map<String, String> parameters) throws void transform(File sourceFile, File targetFile, Map<String, String> parameters)
Exception; throws Exception;
/** /**
* Determine whether this transformer is applicable for the given MIME types. * Determine whether this transformer is applicable for the given MIME types.

View File

@ -30,7 +30,6 @@ import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import java.io.File; import java.io.File;
import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.StringJoiner; import java.util.StringJoiner;
@ -42,6 +41,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import com.google.common.collect.ImmutableList;
/** /**
* The SelectingTransformer selects a registered {@link SelectableTransformer} * The SelectingTransformer selects a registered {@link SelectableTransformer}
* and delegates the transformation to its implementation. * and delegates the transformation to its implementation.
@ -53,15 +54,17 @@ public class SelectingTransformer
{ {
private static final Logger logger = LoggerFactory.getLogger(SelectingTransformer.class); private static final Logger logger = LoggerFactory.getLogger(SelectingTransformer.class);
private List<SelectableTransformer> transformers = new LinkedList<>(); private final List<SelectableTransformer> transformers;
public SelectingTransformer() public SelectingTransformer()
{ {
transformers.add(new AppleIWorksContentTransformer()); transformers = ImmutableList.of(
transformers.add(new HtmlParserContentTransformer()); new AppleIWorksContentTransformer(),
transformers.add(new StringExtractingContentTransformer()); new HtmlParserContentTransformer(),
transformers.add(new TextToPdfContentTransformer()); new StringExtractingContentTransformer(),
// transformers.add(new OOXMLThumbnailContentTransformer()); // Doesn't work with java 11, transformer and test disabled new TextToPdfContentTransformer()
// new OOXMLThumbnailContentTransformer()); // Doesn't work with java 11, transformer and test disabled
);
} }
/** /**
@ -77,8 +80,8 @@ public class SelectingTransformer
{ {
try try
{ {
SelectableTransformer transformer = selectTransformer(sourceMimetype, targetMimetype, final SelectableTransformer transformer = selectTransformer(sourceMimetype,
parameters); targetMimetype, parameters);
logOptions(sourceFile, targetFile, parameters); logOptions(sourceFile, targetFile, parameters);
transformer.transform(sourceFile, targetFile, parameters); transformer.transform(sourceFile, targetFile, parameters);
} }
@ -109,11 +112,8 @@ public class SelectingTransformer
{ {
if (transformer.isTransformable(sourceMimetype, targetMimetype, parameters)) if (transformer.isTransformable(sourceMimetype, targetMimetype, parameters))
{ {
if (logger.isDebugEnabled()) logger.debug("Using {} to transform from {} to {}",
{ transformer.getClass().getName(), sourceMimetype, targetMimetype);
logger.debug("Using " + transformer.getClass().getName()
+ " to transform from " + sourceMimetype + " to " + targetMimetype);
}
return transformer; return transformer;
} }
} }
@ -139,9 +139,8 @@ public class SelectingTransformer
private String getExtension(File file) private String getExtension(File file)
{ {
String name = file.getName(); final String name = file.getName();
int i = name.lastIndexOf('.'); int i = name.lastIndexOf('.');
String ext = i == -1 ? "???" : name.substring(i + 1); return i == -1 ? "???" : name.substring(i + 1);
return ext;
} }
} }

View File

@ -68,11 +68,10 @@ public class StringExtractingContentTransformer implements SelectableTransformer
public boolean isTransformable(String sourceMimetype, String targetMimetype, public boolean isTransformable(String sourceMimetype, String targetMimetype,
Map<String, String> parameters) Map<String, String> parameters)
{ {
boolean transformable = (sourceMimetype.startsWith("text/") return (sourceMimetype.startsWith("text/")
|| MIMETYPE_JAVASCRIPT.equals(sourceMimetype) || MIMETYPE_JAVASCRIPT.equals(sourceMimetype)
|| MIMETYPE_DITA.equals(sourceMimetype)) || MIMETYPE_DITA.equals(sourceMimetype))
&& MIMETYPE_TEXT_PLAIN.equals(targetMimetype); && MIMETYPE_TEXT_PLAIN.equals(targetMimetype);
return transformable;
} }
/** /**
@ -84,8 +83,8 @@ public class StringExtractingContentTransformer implements SelectableTransformer
* be unformatted but valid. * be unformatted but valid.
*/ */
@Override @Override
public void transform(File sourceFile, File targetFile, Map<String, String> parameters) throws public void transform(File sourceFile, File targetFile, Map<String, String> parameters)
Exception throws Exception
{ {
String sourceEncoding = parameters.get(SOURCE_ENCODING); String sourceEncoding = parameters.get(SOURCE_ENCODING);

View File

@ -71,7 +71,7 @@ public class TextToPdfContentTransformer implements SelectableTransformer
public static final String PAGE_LIMIT = "pageLimit"; public static final String PAGE_LIMIT = "pageLimit";
private PagedTextToPDF transformer; private final PagedTextToPDF transformer;
public TextToPdfContentTransformer() public TextToPdfContentTransformer()
{ {
@ -108,18 +108,16 @@ public class TextToPdfContentTransformer implements SelectableTransformer
public boolean isTransformable(String sourceMimetype, String targetMimetype, public boolean isTransformable(String sourceMimetype, String targetMimetype,
Map<String, String> parameters) Map<String, String> parameters)
{ {
boolean transformable = ((MIMETYPE_TEXT_PLAIN.equals(sourceMimetype) return (MIMETYPE_TEXT_PLAIN.equals(sourceMimetype) ||
|| MIMETYPE_TEXT_CSV.equals(sourceMimetype) MIMETYPE_TEXT_CSV.equals(sourceMimetype) ||
|| MIMETYPE_DITA.equals(sourceMimetype) MIMETYPE_DITA.equals(sourceMimetype) ||
|| MIMETYPE_XML.equals(sourceMimetype)) MIMETYPE_XML.equals(sourceMimetype)) &&
&& MIMETYPE_PDF.equals(targetMimetype)); MIMETYPE_PDF.equals(targetMimetype);
return transformable;
} }
@Override @Override
public void transform(File sourceFile, File targetFile, Map<String, String> parameters) throws public void transform(File sourceFile, File targetFile, Map<String, String> parameters)
Exception throws Exception
{ {
String sourceEncoding = parameters.get(SOURCE_ENCODING); String sourceEncoding = parameters.get(SOURCE_ENCODING);
String stringPageLimit = parameters.get(PAGE_LIMIT); String stringPageLimit = parameters.get(PAGE_LIMIT);
@ -184,7 +182,7 @@ public class TextToPdfContentTransformer implements SelectableTransformer
return STANDARD_14.get(name); return STANDARD_14.get(name);
} }
private static final Map<String, PDType1Font> STANDARD_14 = new HashMap<String, PDType1Font>(); private static final Map<String, PDType1Font> STANDARD_14 = new HashMap<>();
static static
{ {
@ -227,7 +225,7 @@ public class TextToPdfContentTransformer implements SelectableTransformer
height = height * getFontSize() * 1.05f; height = height * getFontSize() * 1.05f;
doc = new PDDocument(); doc = new PDDocument();
BufferedReader data = new BufferedReader(text); BufferedReader data = new BufferedReader(text);
String nextLine = null; String nextLine;
PDPage page = new PDPage(); PDPage page = new PDPage();
PDPageContentStream contentStream = null; PDPageContentStream contentStream = null;
float y = -1; float y = -1;
@ -249,7 +247,7 @@ public class TextToPdfContentTransformer implements SelectableTransformer
int lineIndex = 0; int lineIndex = 0;
while (lineIndex < lineWords.length) while (lineIndex < lineWords.length)
{ {
StringBuffer nextLineToDraw = new StringBuffer(); final StringBuilder nextLineToDraw = new StringBuilder();
float lengthIfUsingNextWord = 0; float lengthIfUsingNextWord = 0;
do do
{ {
@ -289,8 +287,7 @@ public class TextToPdfContentTransformer implements SelectableTransformer
contentStream.setFont(getFont(), getFontSize()); contentStream.setFont(getFont(), getFontSize());
contentStream.beginText(); contentStream.beginText();
y = page.getMediaBox().getHeight() - margin + height; y = page.getMediaBox().getHeight() - margin + height;
contentStream.moveTextPositionByAmount( contentStream.moveTextPositionByAmount(margin, y);
margin, y);
} }
//System.out.println( "Drawing string at " + x + "," + y ); //System.out.println( "Drawing string at " + x + "," + y );

View File

@ -66,13 +66,12 @@ import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilde
@Import({SelectingTransformer.class}) @Import({SelectingTransformer.class})
public class MiscControllerTest extends AbstractTransformerControllerTest public class MiscControllerTest extends AbstractTransformerControllerTest
{ {
@Autowired @Autowired
private MiscController controller; private MiscController controller;
private String sourceEncoding = "UTF-8"; private final String sourceEncoding = "UTF-8";
private String targetEncoding = "UTF-8"; private final String targetEncoding = "UTF-8";
private String targetMimetype = MIMETYPE_TEXT_PLAIN; private final String targetMimetype = MIMETYPE_TEXT_PLAIN;
@Before @Before
public void before() throws Exception public void before() throws Exception
@ -157,8 +156,8 @@ public class MiscControllerTest extends AbstractTransformerControllerTest
@Test @Test
public void testStringToString() throws Exception public void testStringToString() throws Exception
{ {
String expected = null; String expected;
byte[] content = null; byte[] content;
try try
{ {
content = "azAz10!<21>$%^&*()\t\r\n".getBytes(UTF_8); content = "azAz10!<21>$%^&*()\t\r\n".getBytes(UTF_8);
@ -204,14 +203,13 @@ public class MiscControllerTest extends AbstractTransformerControllerTest
public void textToPdf() throws Exception public void textToPdf() throws Exception
{ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
String expected = null;
for (int i = 1; i <= 5; i++) for (int i = 1; i <= 5; i++)
{ {
sb.append(i); sb.append(i);
sb.append(" I must not talk in class or feed my homework to my cat.\n"); sb.append(" I must not talk in class or feed my homework to my cat.\n");
} }
sb.append("\nBart\n"); sb.append("\nBart\n");
expected = sb.toString(); String expected = sb.toString();
MvcResult result = sendText("txt", MvcResult result = sendText("txt",
"UTF-8", "UTF-8",
@ -301,13 +299,12 @@ public class MiscControllerTest extends AbstractTransformerControllerTest
.param("sourceEncoding", sourceEncoding) .param("sourceEncoding", sourceEncoding)
.param("sourceMimetype", sourceMimetype); .param("sourceMimetype", sourceMimetype);
MvcResult result = mockMvc return mockMvc
.perform(requestBuilder) .perform(requestBuilder)
.andExpect(status().is(OK.value())) .andExpect(status().is(OK.value()))
.andExpect(header().string("Content-Disposition", .andExpect(header().string("Content-Disposition",
"attachment; filename*= " + targetEncoding + "''test_file." + targetExtension)) "attachment; filename*= " + targetEncoding + "''test_file." + targetExtension))
.andReturn(); .andReturn();
return result;
} }
private String clean(String text) private String clean(String text)

View File

@ -159,10 +159,8 @@ public class HtmlParserContentTransformerTest
} }
} }
private String readFromFile(File file, String encoding) throws Exception private String readFromFile(File file, final String encoding) throws Exception
{ {
String content = "wrong content"; return new String(Files.readAllBytes(file.toPath()), encoding);
content = new String(Files.readAllBytes(file.toPath()), encoding);
return content;
} }
} }

View File

@ -33,9 +33,11 @@ import static org.alfresco.transformer.fs.FileManager.deleteFile;
import static org.alfresco.transformer.fs.FileManager.getFilenameFromContentDisposition; import static org.alfresco.transformer.fs.FileManager.getFilenameFromContentDisposition;
import static org.alfresco.transformer.fs.FileManager.save; import static org.alfresco.transformer.fs.FileManager.save;
import static org.springframework.http.HttpStatus.BAD_REQUEST; import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.http.HttpStatus.OK; import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.util.StringUtils.getFilenameExtension;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -59,7 +61,6 @@ import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.DirectFieldBindingResult; import org.springframework.validation.DirectFieldBindingResult;
import org.springframework.validation.Errors; import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@ -162,7 +163,7 @@ public abstract class AbstractTransformerController implements TransformControll
final Errors errors = validateTransformRequest(request); final Errors errors = validateTransformRequest(request);
if (!errors.getAllErrors().isEmpty()) if (!errors.getAllErrors().isEmpty())
{ {
reply.setStatus(HttpStatus.BAD_REQUEST.value()); reply.setStatus(BAD_REQUEST.value());
reply.setErrorDetails(errors reply.setErrorDetails(errors
.getAllErrors() .getAllErrors()
.stream() .stream()
@ -251,8 +252,8 @@ public abstract class AbstractTransformerController implements TransformControll
reply.setStatus(e.getStatusCode().value()); reply.setStatus(e.getStatusCode().value());
reply.setErrorDetails(messageWithCause("Failed at writing the transformed file. ", e)); reply.setErrorDetails(messageWithCause("Failed at writing the transformed file. ", e));
logger.error("Failed to save target file (HttpClientErrorException), sending " + logger.error("Failed to save target file (HttpClientErrorException), sending " + reply,
reply, e); e);
return new ResponseEntity<>(reply, HttpStatus.valueOf(reply.getStatus())); return new ResponseEntity<>(reply, HttpStatus.valueOf(reply.getStatus()));
} }
catch (Exception e) catch (Exception e)
@ -283,9 +284,9 @@ public abstract class AbstractTransformerController implements TransformControll
} }
reply.setTargetReference(targetRef.getEntry().getFileRef()); reply.setTargetReference(targetRef.getEntry().getFileRef());
reply.setStatus(HttpStatus.CREATED.value()); reply.setStatus(CREATED.value());
logger.info("Sending successful {}, timeout {} ms", reply); logger.info("Sending successful {}, timeout {} ms", reply, timeout);
return new ResponseEntity<>(reply, HttpStatus.valueOf(reply.getStatus())); return new ResponseEntity<>(reply, HttpStatus.valueOf(reply.getStatus()));
} }
@ -302,7 +303,7 @@ public abstract class AbstractTransformerController implements TransformControll
* @param sourceReference reference to the file in Alfresco Shared File Store * @param sourceReference reference to the file in Alfresco Shared File Store
* @return the file containing the source content for the transformation * @return the file containing the source content for the transformation
*/ */
private File loadSourceFile(final String sourceReference) throws Exception private File loadSourceFile(final String sourceReference)
{ {
ResponseEntity<Resource> responseEntity = alfrescoSharedFileStoreClient ResponseEntity<Resource> responseEntity = alfrescoSharedFileStoreClient
.retrieveFile(sourceReference); .retrieveFile(sourceReference);
@ -311,7 +312,7 @@ public abstract class AbstractTransformerController implements TransformControll
HttpHeaders headers = responseEntity.getHeaders(); HttpHeaders headers = responseEntity.getHeaders();
String filename = getFilenameFromContentDisposition(headers); String filename = getFilenameFromContentDisposition(headers);
String extension = StringUtils.getFilenameExtension(filename); String extension = getFilenameExtension(filename);
MediaType contentType = headers.getContentType(); MediaType contentType = headers.getContentType();
long size = headers.getContentLength(); long size = headers.getContentLength();

View File

@ -26,6 +26,9 @@
*/ */
package org.alfresco.transformer; package org.alfresco.transformer;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import java.util.Optional; import java.util.Optional;
import javax.jms.Destination; import javax.jms.Destination;
@ -152,14 +155,14 @@ public class QueueTransformService
String message = String message =
"MessageConversionException during T-Request deserialization of message with correlationID " "MessageConversionException during T-Request deserialization of message with correlationID "
+ correlationId + ": "; + correlationId + ": ";
throw new TransformException(HttpStatus.BAD_REQUEST.value(), message + e.getMessage()); throw new TransformException(BAD_REQUEST.value(), message + e.getMessage());
} }
catch (JMSException e) catch (JMSException e)
{ {
String message = String message =
"JMSException during T-Request deserialization of message with correlationID " "JMSException during T-Request deserialization of message with correlationID "
+ correlationId + ": "; + correlationId + ": ";
throw new TransformException(HttpStatus.INTERNAL_SERVER_ERROR.value(), throw new TransformException(INTERNAL_SERVER_ERROR.value(),
message + e.getMessage()); message + e.getMessage());
} }
catch (Exception e) catch (Exception e)
@ -167,7 +170,7 @@ public class QueueTransformService
String message = String message =
"Exception during T-Request deserialization of message with correlationID " "Exception during T-Request deserialization of message with correlationID "
+ correlationId + ": "; + correlationId + ": ";
throw new TransformException(HttpStatus.INTERNAL_SERVER_ERROR.value(), throw new TransformException(INTERNAL_SERVER_ERROR.value(),
message + e.getMessage()); message + e.getMessage());
} }
} }
@ -175,7 +178,7 @@ public class QueueTransformService
private void replyWithInternalSvErr(final Destination destination, final String msg, private void replyWithInternalSvErr(final Destination destination, final String msg,
final String correlationId) final String correlationId)
{ {
replyWithError(destination, HttpStatus.INTERNAL_SERVER_ERROR, msg, correlationId); replyWithError(destination, INTERNAL_SERVER_ERROR, msg, correlationId);
} }
private void replyWithError(final Destination destination, final HttpStatus status, private void replyWithError(final Destination destination, final HttpStatus status,

View File

@ -26,6 +26,9 @@
*/ */
package org.alfresco.transformer.clients; package org.alfresco.transformer.clients;
import static org.springframework.http.HttpMethod.POST;
import static org.springframework.http.MediaType.MULTIPART_FORM_DATA;
import java.io.File; import java.io.File;
import org.alfresco.transform.exceptions.TransformException; import org.alfresco.transform.exceptions.TransformException;
@ -36,8 +39,6 @@ import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity; import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.HttpClientErrorException;
@ -87,11 +88,11 @@ public class AlfrescoSharedFileStoreClient
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", value); map.add("file", value);
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA); headers.setContentType(MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map,
headers); headers);
ResponseEntity<FileRefResponse> responseEntity = restTemplate ResponseEntity<FileRefResponse> responseEntity = restTemplate
.exchange(fileStoreUrl, HttpMethod.POST, requestEntity, FileRefResponse.class); .exchange(fileStoreUrl, POST, requestEntity, FileRefResponse.class);
return responseEntity.getBody(); return responseEntity.getBody();
} }
catch (HttpClientErrorException e) catch (HttpClientErrorException e)

View File

@ -26,9 +26,12 @@
*/ */
package org.alfresco.transformer.fs; package org.alfresco.transformer.fs;
import static org.springframework.http.HttpHeaders.CONTENT_DISPOSITION;
import static org.springframework.http.HttpStatus.BAD_REQUEST; import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.INSUFFICIENT_STORAGE; import static org.springframework.http.HttpStatus.INSUFFICIENT_STORAGE;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.util.StringUtils.getFilename;
import static org.springframework.util.StringUtils.getFilenameExtension;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -46,7 +49,6 @@ import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource; import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils; import org.springframework.web.util.UriUtils;
@ -99,7 +101,7 @@ public class FileManager
*/ */
private static String checkFilename(boolean source, String filename) private static String checkFilename(boolean source, String filename)
{ {
filename = StringUtils.getFilename(filename); filename = getFilename(filename);
if (filename == null || filename.isEmpty()) if (filename == null || filename.isEmpty())
{ {
String sourceOrTarget = source ? "source" : "target"; String sourceOrTarget = source ? "source" : "target";
@ -162,7 +164,7 @@ public class FileManager
public static String getFilenameFromContentDisposition(HttpHeaders headers) public static String getFilenameFromContentDisposition(HttpHeaders headers)
{ {
String filename = ""; String filename = "";
String contentDisposition = headers.getFirst(HttpHeaders.CONTENT_DISPOSITION); String contentDisposition = headers.getFirst(CONTENT_DISPOSITION);
if (contentDisposition != null) if (contentDisposition != null)
{ {
String[] strings = contentDisposition.split("; *"); String[] strings = contentDisposition.split("; *");
@ -184,14 +186,14 @@ public class FileManager
*/ */
public static String createTargetFileName(final String fileName, final String targetExtension) public static String createTargetFileName(final String fileName, final String targetExtension)
{ {
final String sourceFilename = StringUtils.getFilename(fileName); final String sourceFilename = getFilename(fileName);
if (sourceFilename == null || sourceFilename.isEmpty()) if (sourceFilename == null || sourceFilename.isEmpty())
{ {
return null; return null;
} }
final String ext = StringUtils.getFilenameExtension(sourceFilename); final String ext = getFilenameExtension(sourceFilename);
if (ext == null || ext.isEmpty()) if (ext == null || ext.isEmpty())
{ {
@ -235,9 +237,8 @@ public class FileManager
targetFile) targetFile)
{ {
Resource targetResource = load(targetFile); Resource targetResource = load(targetFile);
targetFilename = UriUtils.encodePath(StringUtils.getFilename(targetFilename), "UTF-8"); targetFilename = UriUtils.encodePath(getFilename(targetFilename), "UTF-8");
return ResponseEntity.ok().header(HttpHeaders return ResponseEntity.ok().header(CONTENT_DISPOSITION,
.CONTENT_DISPOSITION,
"attachment; filename*= UTF-8''" + targetFilename).body(targetResource); "attachment; filename*= UTF-8''" + targetFilename).body(targetResource);
} }
} }

View File

@ -54,25 +54,13 @@ public class FileRefEntity
return fileRef; return fileRef;
} }
@Override
public String toString()
{
return fileRef;
}
@Override @Override
public boolean equals(Object o) public boolean equals(Object o)
{ {
if (this == o) if (this == o) return true;
{ if (o == null || getClass() != o.getClass()) return false;
return true; FileRefEntity that = (FileRefEntity) o;
} return Objects.equals(fileRef, that.fileRef);
if (o == null || getClass() != o.getClass())
{
return false;
}
FileRefEntity fileRef = (FileRefEntity) o;
return Objects.equals(this.fileRef, fileRef.fileRef);
} }
@Override @Override
@ -80,4 +68,10 @@ public class FileRefEntity
{ {
return Objects.hash(fileRef); return Objects.hash(fileRef);
} }
@Override
public String toString()
{
return fileRef;
}
} }

View File

@ -35,9 +35,7 @@ public class FileRefResponse
{ {
private FileRefEntity entry; private FileRefEntity entry;
public FileRefResponse() public FileRefResponse() {}
{
}
public FileRefResponse(FileRefEntity entry) public FileRefResponse(FileRefEntity entry)
{ {

View File

@ -27,6 +27,8 @@
package org.alfresco.transformer; package org.alfresco.transformer;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.springframework.http.HttpMethod.POST;
import static org.springframework.http.MediaType.MULTIPART_FORM_DATA;
import static org.springframework.test.util.AssertionErrors.assertTrue; import static org.springframework.test.util.AssertionErrors.assertTrue;
import org.junit.Test; import org.junit.Test;
@ -35,8 +37,6 @@ import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort; import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpEntity; import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.LinkedMultiValueMap;
@ -115,11 +115,11 @@ public abstract class AbstractHttpRequestTest
new org.springframework.core.io.ClassPathResource("quick." + getSourceExtension())); new org.springframework.core.io.ClassPathResource("quick." + getSourceExtension()));
} }
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA); headers.setContentType(MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> entity = new HttpEntity<>(parameters, HttpEntity<LinkedMultiValueMap<String, Object>> entity = new HttpEntity<>(parameters,
headers); headers);
ResponseEntity<String> response = restTemplate.exchange("/transform", HttpMethod.POST, ResponseEntity<String> response = restTemplate.exchange("/transform", POST, entity,
entity, String.class, ""); String.class, "");
assertEquals(errorMessage, getErrorMessage(response.getBody())); assertEquals(errorMessage, getErrorMessage(response.getBody()));
} }

View File

@ -30,11 +30,13 @@ import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.springframework.http.HttpHeaders.ACCEPT;
import static org.springframework.http.HttpHeaders.CONTENT_TYPE; import static org.springframework.http.HttpHeaders.CONTENT_TYPE;
import static org.springframework.http.HttpStatus.BAD_REQUEST; import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.http.HttpStatus.OK; import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 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.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ -64,8 +66,6 @@ import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile; import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MockMvc;
@ -314,8 +314,8 @@ public abstract class AbstractTransformerControllerTest
String transformationReplyAsString = mockMvc String transformationReplyAsString = mockMvc
.perform(MockMvcRequestBuilders .perform(MockMvcRequestBuilders
.post("/transform") .post("/transform")
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) .header(ACCEPT, APPLICATION_JSON_VALUE)
.header(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header(CONTENT_TYPE, APPLICATION_JSON_VALUE)
.content(tr)) .content(tr))
.andExpect(status().is(BAD_REQUEST.value())) .andExpect(status().is(BAD_REQUEST.value()))
.andReturn().getResponse().getContentAsString(); .andReturn().getResponse().getContentAsString();
@ -383,9 +383,10 @@ public abstract class AbstractTransformerControllerTest
ReflectionTestUtils.setField(AbstractTransformerController.class, "ENGINE_CONFIG", ReflectionTestUtils.setField(AbstractTransformerController.class, "ENGINE_CONFIG",
"engine_config_incomplete.json"); "engine_config_incomplete.json");
String response = mockMvc.perform(MockMvcRequestBuilders.get("/transform/config")) String response = mockMvc
.andExpect(status().is(OK.value())).andExpect( .perform(MockMvcRequestBuilders.get("/transform/config"))
header().string(CONTENT_TYPE, APPLICATION_JSON_UTF8_VALUE)) .andExpect(status().is(OK.value()))
.andExpect(header().string(CONTENT_TYPE, APPLICATION_JSON_UTF8_VALUE))
.andReturn().getResponse().getContentAsString(); .andReturn().getResponse().getContentAsString();
TransformConfig transformConfig = objectMapper.readValue(response, TransformConfig.class); TransformConfig transformConfig = objectMapper.readValue(response, TransformConfig.class);

View File

@ -32,6 +32,9 @@ import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import javax.jms.Destination; import javax.jms.Destination;
import javax.jms.JMSException; import javax.jms.JMSException;
@ -100,7 +103,7 @@ public class QueueTransformServiceTest
TransformReply reply = TransformReply TransformReply reply = TransformReply
.builder() .builder()
.withStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()) .withStatus(INTERNAL_SERVER_ERROR.value())
.withErrorDetails( .withErrorDetails(
"JMS exception during T-Request deserialization of message with correlationID " "JMS exception during T-Request deserialization of message with correlationID "
+ msg.getCorrelationId() + ": null") + msg.getCorrelationId() + ": null")
@ -127,7 +130,7 @@ public class QueueTransformServiceTest
TransformReply reply = TransformReply TransformReply reply = TransformReply
.builder() .builder()
.withStatus(HttpStatus.BAD_REQUEST.value()) .withStatus(BAD_REQUEST.value())
.withErrorDetails( .withErrorDetails(
"Message conversion exception during T-Request deserialization of message with correlationID" "Message conversion exception during T-Request deserialization of message with correlationID"
+ msg.getCorrelationId() + ": null") + msg.getCorrelationId() + ": null")
@ -154,9 +157,10 @@ public class QueueTransformServiceTest
TransformReply reply = TransformReply TransformReply reply = TransformReply
.builder() .builder()
.withStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()).withErrorDetails( .withStatus(INTERNAL_SERVER_ERROR.value())
"JMSException during T-Request deserialization of message with correlationID " + msg .withErrorDetails(
.getCorrelationId() + ": null") "JMSException during T-Request deserialization of message with correlationID " +
msg.getCorrelationId() + ": null")
.build(); .build();
doThrow(JMSException.class).when(transformMessageConverter).fromMessage(msg); doThrow(JMSException.class).when(transformMessageConverter).fromMessage(msg);
@ -179,7 +183,7 @@ public class QueueTransformServiceTest
TransformRequest request = new TransformRequest(); TransformRequest request = new TransformRequest();
TransformReply reply = TransformReply TransformReply reply = TransformReply
.builder() .builder()
.withStatus(HttpStatus.CREATED.value()) .withStatus(CREATED.value())
.build(); .build();
doReturn(request).when(transformMessageConverter).fromMessage(msg); doReturn(request).when(transformMessageConverter).fromMessage(msg);
@ -218,8 +222,9 @@ public class QueueTransformServiceTest
doReturn(destination).when(msg).getJMSReplyTo(); doReturn(destination).when(msg).getJMSReplyTo();
TransformRequest request = new TransformRequest(); TransformRequest request = new TransformRequest();
TransformReply reply = TransformReply.builder() TransformReply reply = TransformReply
.withStatus(HttpStatus.CREATED.value()) .builder()
.withStatus(CREATED.value())
.build(); .build();
doReturn(request).when(transformMessageConverter).fromMessage(msg); doReturn(request).when(transformMessageConverter).fromMessage(msg);

View File

@ -15,7 +15,10 @@
<packaging>pom</packaging> <packaging>pom</packaging>
<properties> <properties>
<java.version>1.8</java.version> <java.version>11</java.version>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<image.tag>latest</image.tag> <image.tag>latest</image.tag>
<dependency.pdfbox.version>2.0.16</dependency.pdfbox.version> <dependency.pdfbox.version>2.0.16</dependency.pdfbox.version>
<dependency.alfresco-core.version>7.17</dependency.alfresco-core.version> <dependency.alfresco-core.version>7.17</dependency.alfresco-core.version>