ATS-531 : Reformat code

This commit is contained in:
Cezar.Leahu
2019-08-14 22:21:06 +03:00
committed by CezarLeahu
parent 70ab0241dd
commit 485347729b
58 changed files with 1310 additions and 1074 deletions

View File

@@ -26,7 +26,6 @@
*/
package org.alfresco.transformer;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
@@ -35,15 +34,18 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import io.micrometer.core.instrument.MeterRegistry;
@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class Application
{
@Value("${container.name}")
private String containerName;
@Bean
MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
MeterRegistryCustomizer<MeterRegistry> metricsCommonTags()
{
return registry -> registry.config().commonTags("containerName", containerName);
}

View File

@@ -66,11 +66,14 @@ public class MiscController extends AbstractTransformerController
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(
"--------------------------------------------------------------------------------------------------------------------------------------------------------------");
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(
"--------------------------------------------------------------------------------------------------------------------------------------------------------------");
}
@Override
@@ -91,8 +94,8 @@ public class MiscController extends AbstractTransformerController
// HtmlParserContentTransformer html -> text
// See the Javadoc on this method and Probes.md for the choice of these values.
return new ProbeTestTransform(this, "quick.html", "quick.txt",
119, 30, 150, 1024,
60*2+1,60*2)
119, 30, 150, 1024,
60 * 2 + 1, 60 * 2)
{
@Override
protected void executeTransformCommand(File sourceFile, File targetFile)
@@ -100,40 +103,47 @@ public class MiscController extends AbstractTransformerController
Map<String, String> parameters = new HashMap<>();
parameters.put(SOURCE_ENCODING, "UTF-8");
parameters.put(TARGET_ENCODING, "UTF-8");
transformer.transform(sourceFile, targetFile, MIMETYPE_HTML, MIMETYPE_TEXT_PLAIN, parameters);
transformer.transform(sourceFile, targetFile, MIMETYPE_HTML, MIMETYPE_TEXT_PLAIN,
parameters);
}
};
}
@Override
public void processTransform(File sourceFile, File targetFile, Map<String, String> transformOptions, Long timeout)
public void processTransform(File sourceFile, File targetFile,
Map<String, String> transformOptions, Long timeout)
{
if (logger.isDebugEnabled())
{
logger.debug("Processing request with: sourceFile '{}', targetFile '{}', transformOptions" +
" '{}', timeout {} ms", sourceFile, targetFile, transformOptions, timeout);
logger.debug(
"Processing request with: sourceFile '{}', targetFile '{}', transformOptions" +
" '{}', timeout {} ms", sourceFile, targetFile, transformOptions, timeout);
}
String sourceMimetype = transformOptions.get("sourceMimetype");
String targetMimetype = transformOptions.get("targetMimetype");
transformer.transform(sourceFile, targetFile, sourceMimetype, targetMimetype, transformOptions);
transformer.transform(sourceFile, targetFile, sourceMimetype, targetMimetype,
transformOptions);
}
@PostMapping(value = "/transform", consumes = MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Resource> transform(HttpServletRequest request,
@RequestParam("file") MultipartFile sourceMultipartFile,
@RequestParam(value = "targetExtension") String targetExtension,
@RequestParam(value = "targetMimetype") String targetMimetype,
@RequestParam(value = "sourceMimetype") String sourceMimetype,
@RequestParam(value = "testDelay", required = false) Long testDelay,
@RequestParam Map<String, String> parameters)
@RequestParam("file") MultipartFile sourceMultipartFile,
@RequestParam(value = "targetExtension") String targetExtension,
@RequestParam(value = "targetMimetype") String targetMimetype,
@RequestParam(value = "sourceMimetype") String sourceMimetype,
@RequestParam(value = "testDelay", required = false) Long testDelay,
@RequestParam Map<String, String> parameters)
{
if (logger.isDebugEnabled())
{
logger.debug("Processing request with: sourceMimetype '{}', targetMimetype '{}' , targetExtension '{}' " +
", parameters '{}'", sourceMimetype, targetMimetype, targetExtension, parameters);
logger.debug(
"Processing request with: sourceMimetype '{}', targetMimetype '{}' , targetExtension '{}' " +
", parameters '{}'", sourceMimetype, targetMimetype, targetExtension, parameters);
}
String targetFilename = createTargetFileName(sourceMultipartFile.getOriginalFilename(), targetExtension);
String targetFilename = createTargetFileName(sourceMultipartFile.getOriginalFilename(),
targetExtension);
getProbeTestTransform().incrementTransformerCount();
File sourceFile = createSourceFile(request, sourceMultipartFile);
File targetFile = createTargetFile(request, targetFilename);

View File

@@ -26,12 +26,9 @@
*/
package org.alfresco.transformer.transformers;
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.ZipArchiveInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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_PAGES;
import java.io.BufferedInputStream;
import java.io.File;
@@ -43,9 +40,12 @@ import java.util.Arrays;
import java.util.List;
import java.util.Map;
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_PAGES;
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.ZipArchiveInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Converts Apple iWorks files to JPEGs for thumbnailing & previewing.
@@ -60,23 +60,25 @@ import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_IWORK_PAGES;
*/
public class AppleIWorksContentTransformer implements SelectableTransformer
{
private static final Logger logger = LoggerFactory.getLogger(AppleIWorksContentTransformer.class);
private static final Logger logger = LoggerFactory.getLogger(
AppleIWorksContentTransformer.class);
// Apple's zip entry names for previews in iWorks have changed over time.
private static final List<String> PDF_PATHS = Arrays.asList(
"QuickLook/Preview.pdf"); // iWorks 2008/9
"QuickLook/Preview.pdf"); // iWorks 2008/9
private static final List<String> JPG_PATHS = Arrays.asList(
"QuickLook/Thumbnail.jpg", // iWorks 2008/9
"preview.jpg"); // iWorks 2013/14 (720 x 552) We use the best quality image. Others are:
// (225 x 173) preview-web.jpg
// (53 x 41) preview-micro.jpg
"QuickLook/Thumbnail.jpg", // iWorks 2008/9
"preview.jpg"); // iWorks 2013/14 (720 x 552) We use the best quality image. Others are:
// (225 x 173) preview-web.jpg
// (53 x 41) preview-micro.jpg
@Override
public boolean isTransformable(String sourceMimetype, String targetMimetype, Map<String, String> parameters)
public boolean isTransformable(String sourceMimetype, String targetMimetype,
Map<String, String> parameters)
{
boolean transformable = MIMETYPE_IWORK_KEYNOTE.equals(sourceMimetype)
|| MIMETYPE_IWORK_NUMBERS.equals(sourceMimetype)
|| MIMETYPE_IWORK_PAGES.equals(sourceMimetype);
boolean transformable = MIMETYPE_IWORK_KEYNOTE.equals(sourceMimetype)
|| MIMETYPE_IWORK_NUMBERS.equals(sourceMimetype)
|| MIMETYPE_IWORK_PAGES.equals(sourceMimetype);
return transformable;
}
@@ -86,20 +88,22 @@ public class AppleIWorksContentTransformer implements SelectableTransformer
final String sourceMimetype = parameters.get(SOURCE_MIMETYPE);
final String targetMimetype = parameters.get(TARGET_MIMETYPE);
if(logger.isDebugEnabled())
if (logger.isDebugEnabled())
{
logger.debug("Performing IWorks to jpeg transform with sourceMimetype=" + sourceMimetype
+ " targetMimetype=" + targetMimetype);
+ " targetMimetype=" + targetMimetype);
}
// iWorks files are zip (or package) files.
// If it's not a zip file, the resultant ZipException will be caught as an IOException below.
try (ZipArchiveInputStream iWorksZip = new ZipArchiveInputStream( new BufferedInputStream( new FileInputStream(sourceFile))))
try (ZipArchiveInputStream iWorksZip = new ZipArchiveInputStream(
new BufferedInputStream(new FileInputStream(sourceFile))))
{
// Look through the zip file entries for the preview/thumbnail.
List<String> paths = Mimetype.MIMETYPE_IMAGE_JPEG.equals(targetMimetype) ? JPG_PATHS : PDF_PATHS;
List<String> paths = Mimetype.MIMETYPE_IMAGE_JPEG.equals(
targetMimetype) ? JPG_PATHS : PDF_PATHS;
ZipArchiveEntry entry;
boolean found = false;
while ((entry=iWorksZip.getNextZipEntry()) != null)
while ((entry = iWorksZip.getNextZipEntry()) != null)
{
String name = entry.getName();
if (paths.contains(name))
@@ -110,14 +114,17 @@ public class AppleIWorksContentTransformer implements SelectableTransformer
}
}
if (! found)
if (!found)
{
throw new AlfrescoRuntimeException("The source " + sourceMimetype + " file did not contain a " + targetMimetype + " preview");
throw new AlfrescoRuntimeException(
"The source " + sourceMimetype + " file did not contain a " + targetMimetype + " preview");
}
}
catch (IOException e)
{
throw new AlfrescoRuntimeException("Unable to transform " + sourceMimetype + " file. It should have been a zip format file.", e);
throw new AlfrescoRuntimeException(
"Unable to transform " + sourceMimetype + " file. It should have been a zip format file.",
e);
}
}
}

View File

@@ -26,16 +26,12 @@
*/
package org.alfresco.transformer.transformers;
import org.htmlparser.Parser;
import org.htmlparser.beans.StringBean;
import org.htmlparser.util.ParserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_HTML;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_TEXT_PLAIN;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URLConnection;
@@ -43,8 +39,11 @@ import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.util.Map;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_HTML;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_TEXT_PLAIN;
import org.htmlparser.Parser;
import org.htmlparser.beans.StringBean;
import org.htmlparser.util.ParserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Content transformer which wraps the HTML Parser library for
@@ -63,34 +62,36 @@ import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_TEXT_PLAIN;
*
* <p>
* Tika Note - could be converted to use the Tika HTML parser,
* but we'd potentially need a custom text handler to replicate
* the current settings around links and non-breaking spaces.
* but we'd potentially need a custom text handler to replicate
* the current settings around links and non-breaking spaces.
* </p>
*
* @see <a href="http://htmlparser.sourceforge.net/">http://htmlparser.sourceforge.net</a>
* @see org.htmlparser.beans.StringBean
* @see <a href="http://sourceforge.net/tracker/?func=detail&aid=1644504&group_id=24399&atid=381401">HTML Parser</a>
*
* @author Derek Hulley
* @author eknizat
* @see <a href="http://htmlparser.sourceforge.net/">http://htmlparser.sourceforge.net</a>
* @see org.htmlparser.beans.StringBean
* @see <a href="http://sourceforge.net/tracker/?func=detail&aid=1644504&group_id=24399&atid=381401">HTML Parser</a>
*/
public class HtmlParserContentTransformer implements SelectableTransformer
{
private static final Logger logger = LoggerFactory.getLogger(HtmlParserContentTransformer.class);
private static final Logger logger = LoggerFactory.getLogger(
HtmlParserContentTransformer.class);
@Override
public boolean isTransformable(String sourceMimetype, String targetMimetype, Map<String, String> parameters)
public boolean isTransformable(String sourceMimetype, String targetMimetype,
Map<String, String> parameters)
{
return MIMETYPE_HTML.equals(sourceMimetype) && MIMETYPE_TEXT_PLAIN.equals(targetMimetype);
}
@Override
public void transform(File sourceFile, File targetFile, Map<String, String> parameters) throws Exception
public void transform(File sourceFile, File targetFile, Map<String, String> parameters) throws
Exception
{
String sourceEncoding = parameters.get(SOURCE_ENCODING);
checkEncodingParameter(sourceEncoding, SOURCE_ENCODING);
if(logger.isDebugEnabled())
if (logger.isDebugEnabled())
{
logger.debug("Performing HTML to text transform with sourceEncoding=" + sourceEncoding);
}
@@ -105,7 +106,8 @@ public class HtmlParserContentTransformer implements SelectableTransformer
String text = extractor.getStrings();
// write it to the writer
try ( Writer writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(targetFile))))
try (Writer writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(targetFile))))
{
writer.write(text);
}
@@ -117,30 +119,29 @@ public class HtmlParserContentTransformer implements SelectableTransformer
{
if (encoding != null && !Charset.isSupported(encoding))
{
throw new IllegalArgumentException(paramterName + "=" + encoding + " is not supported by the JVM.");
throw new IllegalArgumentException(
paramterName + "=" + encoding + " is not supported by the JVM.");
}
}
catch (IllegalCharsetNameException e)
{
throw new IllegalArgumentException(paramterName + "=" + encoding + " is not a valid encoding.");
throw new IllegalArgumentException(
paramterName + "=" + encoding + " is not a valid encoding.");
}
}
/**
*
* <p>
* This code is based on a class of the same name, originally implemented in alfresco-repository.
* </p>
* <p>
* This code is based on a class of the same name, originally implemented in alfresco-repository.
* </p>
*
* A version of {@link StringBean} which allows control of the
* encoding in the underlying HTML Parser.
* encoding in the underlying HTML Parser.
* Unfortunately, StringBean doesn't allow easy over-riding of
* this, so we have to duplicate some code to control this.
* this, so we have to duplicate some code to control this.
* This allows us to correctly handle HTML files where the encoding
* is specified against the content property (rather than in the
* HTML Head Meta), see ALF-10466 for details.
*
*
* is specified against the content property (rather than in the
* HTML Head Meta), see ALF-10466 for details.
*/
private class EncodingAwareStringBean extends StringBean
{
@@ -148,9 +149,9 @@ public class HtmlParserContentTransformer implements SelectableTransformer
/**
* Sets the File to extract strings from, and the encoding
* it's in (if known to Alfresco)
* it's in (if known to Alfresco)
*
* @param file The File that text should be fetched from.
* @param file The File that text should be fetched from.
* @param encoding The encoding of the input
*/
public void setURL(File file, String encoding)
@@ -158,7 +159,7 @@ public class HtmlParserContentTransformer implements SelectableTransformer
String previousURL = getURL();
String newURL = file.getAbsolutePath();
if ( (previousURL == null) || (!newURL.equals(previousURL)) )
if ((previousURL == null) || (!newURL.equals(previousURL)))
{
try
{
@@ -178,8 +179,10 @@ public class HtmlParserContentTransformer implements SelectableTransformer
mParser.setEncoding(encoding);
}
mPropertySupport.firePropertyChange(StringBean.PROP_URL_PROPERTY, previousURL, getURL());
mPropertySupport.firePropertyChange(StringBean.PROP_CONNECTION_PROPERTY, conn, mParser.getConnection());
mPropertySupport.firePropertyChange(StringBean.PROP_URL_PROPERTY, previousURL,
getURL());
mPropertySupport.firePropertyChange(StringBean.PROP_CONNECTION_PROPERTY, conn,
mParser.getConnection());
setStrings();
}
catch (ParserException pe)
@@ -189,7 +192,8 @@ public class HtmlParserContentTransformer implements SelectableTransformer
}
}
public String getEncoding(){
public String getEncoding()
{
return mParser.getEncoding();
}
}

View File

@@ -26,6 +26,15 @@
*/
package org.alfresco.transformer.transformers;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.transform.client.model.Mimetype;
import org.apache.poi.openxml4j.opc.OPCPackage;
@@ -36,74 +45,67 @@ import org.apache.poi.openxml4j.opc.PackageRelationshipTypes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* Extracts out Thumbnail JPEGs from OOXML files for thumbnailing & previewing.
* This transformer will only work for OOXML files where thumbnailing was enabled,
* which isn't on by default on Windows, but is more common on Mac.
* which isn't on by default on Windows, but is more common on Mac.
*
* @author Nick Burch
* @author eknizat
*
*/
public class OOXMLThumbnailContentTransformer implements SelectableTransformer
{
private static final Logger logger = LoggerFactory.getLogger(OOXMLThumbnailContentTransformer.class);
private static final Logger logger = LoggerFactory.getLogger(
OOXMLThumbnailContentTransformer.class);
private static final List<String> OOXML_MIMETYPES = Arrays.asList(new String[]{
Mimetype.MIMETYPE_OPENXML_WORDPROCESSING,
Mimetype.MIMETYPE_OPENXML_WORDPROCESSING_MACRO,
Mimetype.MIMETYPE_OPENXML_WORD_TEMPLATE,
Mimetype.MIMETYPE_OPENXML_WORD_TEMPLATE_MACRO,
Mimetype.MIMETYPE_OPENXML_PRESENTATION,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_MACRO,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_SLIDESHOW,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_SLIDESHOW_MACRO,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_TEMPLATE,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_TEMPLATE_MACRO,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_ADDIN,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_SLIDE,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_SLIDE_MACRO,
Mimetype.MIMETYPE_OPENXML_SPREADSHEET,
Mimetype.MIMETYPE_OPENXML_SPREADSHEET_TEMPLATE,
Mimetype.MIMETYPE_OPENXML_SPREADSHEET_MACRO,
Mimetype.MIMETYPE_OPENXML_SPREADSHEET_TEMPLATE_MACRO,
Mimetype.MIMETYPE_OPENXML_SPREADSHEET_ADDIN_MACRO,
Mimetype.MIMETYPE_OPENXML_SPREADSHEET_BINARY_MACRO});
private static final List<String> OOXML_MIMETYPES = Arrays.asList(Mimetype.MIMETYPE_OPENXML_WORDPROCESSING,
Mimetype.MIMETYPE_OPENXML_WORDPROCESSING_MACRO,
Mimetype.MIMETYPE_OPENXML_WORD_TEMPLATE,
Mimetype.MIMETYPE_OPENXML_WORD_TEMPLATE_MACRO,
Mimetype.MIMETYPE_OPENXML_PRESENTATION,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_MACRO,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_SLIDESHOW,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_SLIDESHOW_MACRO,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_TEMPLATE,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_TEMPLATE_MACRO,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_ADDIN,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_SLIDE,
Mimetype.MIMETYPE_OPENXML_PRESENTATION_SLIDE_MACRO,
Mimetype.MIMETYPE_OPENXML_SPREADSHEET,
Mimetype.MIMETYPE_OPENXML_SPREADSHEET_TEMPLATE,
Mimetype.MIMETYPE_OPENXML_SPREADSHEET_MACRO,
Mimetype.MIMETYPE_OPENXML_SPREADSHEET_TEMPLATE_MACRO,
Mimetype.MIMETYPE_OPENXML_SPREADSHEET_ADDIN_MACRO,
Mimetype.MIMETYPE_OPENXML_SPREADSHEET_BINARY_MACRO);
@Override
public boolean isTransformable(String sourceMimetype, String targetMimetype, Map<String, String> parameters)
public boolean isTransformable(String sourceMimetype, String targetMimetype,
Map<String, String> parameters)
{
// only support [OOXML] -> JPEG
return Mimetype.MIMETYPE_IMAGE_JPEG.equals(targetMimetype) && OOXML_MIMETYPES.contains(sourceMimetype);
return Mimetype.MIMETYPE_IMAGE_JPEG.equals(targetMimetype) && OOXML_MIMETYPES.contains(
sourceMimetype);
}
@Override
public void transform(File sourceFile, File targetFile, Map<String, String> parameters) throws Exception
public void transform(File sourceFile, File targetFile, Map<String, String> parameters) throws
Exception
{
final String sourceMimetype = parameters.get(SOURCE_MIMETYPE);
final String targetMimetype = parameters.get(TARGET_MIMETYPE);
if(logger.isDebugEnabled())
if (logger.isDebugEnabled())
{
logger.debug("Performing OOXML to jpeg transform with sourceMimetype=" + sourceMimetype
+ " targetMimetype=" + targetMimetype);
+ " targetMimetype=" + targetMimetype);
}
try (OPCPackage pkg = OPCPackage.open(sourceFile.getPath()))
{
// Does it have a thumbnail?
PackageRelationshipCollection rels = pkg.getRelationshipsByType(PackageRelationshipTypes.THUMBNAIL);
PackageRelationshipCollection rels = pkg.getRelationshipsByType(
PackageRelationshipTypes.THUMBNAIL);
if (rels.size() > 0)
{
// Get the thumbnail part
@@ -118,7 +120,8 @@ public class OOXMLThumbnailContentTransformer implements SelectableTransformer
else
{
logger.debug("No thumbnail present in file.");
throw new Exception("No thumbnail present in file, unable to generate " + targetMimetype);
throw new Exception(
"No thumbnail present in file, unable to generate " + targetMimetype);
}
}
catch (IOException e)

View File

@@ -26,15 +26,10 @@
*/
package org.alfresco.transformer.transformers;
import org.alfresco.transformer.logging.LogEntry;
import java.io.File;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;
/**
*
* Implemented by transformers used by {@link SelectingTransformer}.
*
* @author eknizat
@@ -48,21 +43,23 @@ public interface SelectableTransformer
/**
* Implementation of the actual transformation.
*
* @param sourceFile
* @param targetFile
* @param parameters
* @throws Exception
*/
public void transform(File sourceFile, File targetFile, Map<String, String> parameters) throws Exception;
void transform(File sourceFile, File targetFile, Map<String, String> parameters) throws
Exception;
/**
* Determine whether this transformer is applicable for the given MIME types.
*
* @param sourceMimetype
* @param targetMimetype
* @param parameters
* @return
*/
public boolean isTransformable(String sourceMimetype, String targetMimetype, Map<String, String> parameters);
boolean isTransformable(String sourceMimetype, String targetMimetype,
Map<String, String> parameters);
}

View File

@@ -26,12 +26,8 @@
*/
package org.alfresco.transformer.transformers;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.transform.exceptions.TransformException;
import org.alfresco.transformer.logging.LogEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import java.io.File;
import java.util.LinkedList;
@@ -39,16 +35,18 @@ import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.transform.exceptions.TransformException;
import org.alfresco.transformer.logging.LogEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
*
* The SelectingTransformer selects a registered {@link SelectableTransformer}
* and delegates the transformation to its implementation.
*
* @author eknizat
*
*/
@Component
public class SelectingTransformer
@@ -68,17 +66,19 @@ public class SelectingTransformer
/**
* Performs a transform using a transformer selected based on the provided sourceMimetype and targetMimetype
* @param sourceFile File to transform from
* @param targetFile File to transform to
*
* @param sourceFile File to transform from
* @param targetFile File to transform to
* @param sourceMimetype Mimetype of the source file
* @throws TransformException
*/
public void transform(File sourceFile, File targetFile, String sourceMimetype, String targetMimetype,
Map<String, String> parameters) throws TransformException
public void transform(File sourceFile, File targetFile, String sourceMimetype,
String targetMimetype, Map<String, String> parameters) throws TransformException
{
try
{
SelectableTransformer transformer = selectTransformer(sourceMimetype, targetMimetype, parameters);
SelectableTransformer transformer = selectTransformer(sourceMimetype, targetMimetype,
parameters);
logOptions(sourceFile, targetFile, parameters);
transformer.transform(sourceFile, targetFile, parameters);
}
@@ -93,17 +93,17 @@ public class SelectingTransformer
if (!targetFile.exists())
{
throw new TransformException(INTERNAL_SERVER_ERROR.value(),
"Transformer failed to create an output file. Target file does not exist.");
"Transformer failed to create an output file. Target file does not exist.");
}
if (sourceFile.length() > 0 && targetFile.length() == 0)
{
throw new TransformException(INTERNAL_SERVER_ERROR.value(),
"Transformer failed to create an output file. Target file is empty but source file was not empty.");
"Transformer failed to create an output file. Target file is empty but source file was not empty.");
}
}
private SelectableTransformer selectTransformer(String sourceMimetype, String targetMimetype,
Map<String, String> parameters)
Map<String, String> parameters)
{
for (SelectableTransformer transformer : transformers)
{
@@ -112,13 +112,14 @@ public class SelectingTransformer
if (logger.isDebugEnabled())
{
logger.debug("Using " + transformer.getClass().getName()
+ " to transform from " + sourceMimetype + " to " + targetMimetype );
+ " to transform from " + sourceMimetype + " to " + targetMimetype);
}
return transformer;
}
}
throw new AlfrescoRuntimeException( "Could not select a transformer for sourceMimetype=" + sourceMimetype
+ " targetMimetype=" + targetMimetype);
throw new AlfrescoRuntimeException(
"Could not select a transformer for sourceMimetype=" + sourceMimetype
+ " targetMimetype=" + targetMimetype);
}
private static String getMessage(Exception e)
@@ -129,7 +130,8 @@ public class SelectingTransformer
private void logOptions(File sourceFile, File targetFile, Map<String, String> parameters)
{
StringJoiner sj = new StringJoiner(" ");
parameters.forEach( (k, v) -> sj.add("--" + k + "=" + v)); // keeping the existing style used in other T-Engines
parameters.forEach((k, v) -> sj.add(
"--" + k + "=" + v)); // keeping the existing style used in other T-Engines
sj.add(getExtension(sourceFile));
sj.add(getExtension(targetFile));
LogEntry.setOptions(sj.toString());

View File

@@ -26,29 +26,25 @@
*/
package org.alfresco.transformer.transformers;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_DITA;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_JAVASCRIPT;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_TEXT_PLAIN;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.util.Map;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_DITA;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_JAVASCRIPT;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_TEXT_PLAIN;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Converts any textual format to plain text.
@@ -60,7 +56,6 @@ import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_TEXT_PLAIN;
* This code is based on a class of the same name originally implemented in alfresco-repository.
* </p>
*
*
* @author Derek Hulley
* @author eknizat
*/
@@ -70,12 +65,13 @@ public class StringExtractingContentTransformer implements SelectableTransformer
private static final Log logger = LogFactory.getLog(StringExtractingContentTransformer.class);
@Override
public boolean isTransformable(String sourceMimetype, String targetMimetype, Map<String, String> parameters)
public boolean isTransformable(String sourceMimetype, String targetMimetype,
Map<String, String> parameters)
{
boolean transformable = (sourceMimetype.startsWith("text/")
|| MIMETYPE_JAVASCRIPT.equals(sourceMimetype)
|| MIMETYPE_DITA.equals(sourceMimetype))
&& MIMETYPE_TEXT_PLAIN.equals(targetMimetype);
boolean transformable = (sourceMimetype.startsWith("text/")
|| MIMETYPE_JAVASCRIPT.equals(sourceMimetype)
|| MIMETYPE_DITA.equals(sourceMimetype))
&& MIMETYPE_TEXT_PLAIN.equals(targetMimetype);
return transformable;
}
@@ -88,16 +84,17 @@ public class StringExtractingContentTransformer implements SelectableTransformer
* be unformatted but valid.
*/
@Override
public void transform(File sourceFile, File targetFile, Map<String, String> parameters) throws Exception
public void transform(File sourceFile, File targetFile, Map<String, String> parameters) throws
Exception
{
String sourceEncoding = parameters.get(SOURCE_ENCODING);
String targetEncoding = parameters.get(TARGET_ENCODING);
if(logger.isDebugEnabled())
if (logger.isDebugEnabled())
{
logger.debug("Performing text to text transform with sourceEncoding=" + sourceEncoding
+ " targetEncoding=" + targetEncoding);
+ " targetEncoding=" + targetEncoding);
}
Reader charReader = null;
@@ -107,23 +104,27 @@ public class StringExtractingContentTransformer implements SelectableTransformer
// Build reader
if (sourceEncoding == null)
{
charReader = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile)));
charReader = new BufferedReader(
new InputStreamReader(new FileInputStream(sourceFile)));
}
else
{
checkEncodingParameter(sourceEncoding, SOURCE_ENCODING);
charReader = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile), sourceEncoding));
charReader = new BufferedReader(
new InputStreamReader(new FileInputStream(sourceFile), sourceEncoding));
}
// Build writer
if (targetEncoding == null)
{
charWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile)));
charWriter = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(targetFile)));
}
else
{
checkEncodingParameter( targetEncoding, TARGET_ENCODING);
charWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), targetEncoding));
checkEncodingParameter(targetEncoding, TARGET_ENCODING);
charWriter = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(targetFile), targetEncoding));
}
// copy from the one to the other
@@ -157,12 +158,14 @@ public class StringExtractingContentTransformer implements SelectableTransformer
{
if (!Charset.isSupported(encoding))
{
throw new IllegalArgumentException(paramterName + "=" + encoding + " is not supported by the JVM.");
throw new IllegalArgumentException(
paramterName + "=" + encoding + " is not supported by the JVM.");
}
}
catch (IllegalCharsetNameException e)
{
throw new IllegalArgumentException(paramterName + "=" + encoding + " is not a valid encoding.");
throw new IllegalArgumentException(
paramterName + "=" + encoding + " is not a valid encoding.");
}
}
}

View File

@@ -26,14 +26,11 @@
*/
package org.alfresco.transformer.transformers;
import org.alfresco.error.AlfrescoRuntimeException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.tools.TextToPDF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_DITA;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_PDF;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_TEXT_CSV;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_TEXT_PLAIN;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_XML;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
@@ -49,14 +46,16 @@ import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_DITA;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_PDF;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_TEXT_CSV;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_TEXT_PLAIN;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_XML;
import org.alfresco.error.AlfrescoRuntimeException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.tools.TextToPDF;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* <p>
* This code is based on a class of the same name originally implemented in alfresco-repository.
* </p>
@@ -65,7 +64,7 @@ import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_XML;
*
* @author Derek Hulley
* @author eknizat
*/
*/
public class TextToPdfContentTransformer implements SelectableTransformer
{
private static final Logger logger = LoggerFactory.getLogger(TextToPdfContentTransformer.class);
@@ -83,11 +82,12 @@ public class TextToPdfContentTransformer implements SelectableTransformer
{
try
{
transformer.setFont(transformer.getStandardFont(fontName));
transformer.setFont(PagedTextToPDF.getStandardFont(fontName));
}
catch (Throwable e)
{
throw new AlfrescoRuntimeException("Unable to set Standard Font for PDF generation: " + fontName, e);
throw new AlfrescoRuntimeException(
"Unable to set Standard Font for PDF generation: " + fontName, e);
}
}
@@ -99,29 +99,32 @@ public class TextToPdfContentTransformer implements SelectableTransformer
}
catch (Throwable e)
{
throw new AlfrescoRuntimeException("Unable to set Font Size for PDF generation: " + fontSize);
throw new AlfrescoRuntimeException(
"Unable to set Font Size for PDF generation: " + fontSize);
}
}
@Override
public boolean isTransformable(String sourceMimetype, String targetMimetype, Map<String, String> parameters)
public boolean isTransformable(String sourceMimetype, String targetMimetype,
Map<String, String> parameters)
{
boolean transformable = ( (MIMETYPE_TEXT_PLAIN.equals(sourceMimetype)
|| MIMETYPE_TEXT_CSV.equals(sourceMimetype)
|| MIMETYPE_DITA.equals(sourceMimetype)
|| MIMETYPE_XML.equals(sourceMimetype) )
&& MIMETYPE_PDF.equals(targetMimetype));
boolean transformable = ((MIMETYPE_TEXT_PLAIN.equals(sourceMimetype)
|| MIMETYPE_TEXT_CSV.equals(sourceMimetype)
|| MIMETYPE_DITA.equals(sourceMimetype)
|| MIMETYPE_XML.equals(sourceMimetype))
&& MIMETYPE_PDF.equals(targetMimetype));
return transformable;
}
@Override
public void transform(File sourceFile, File targetFile, Map<String, String> parameters) throws Exception
public void transform(File sourceFile, File targetFile, Map<String, String> parameters) throws
Exception
{
String sourceEncoding = parameters.get(SOURCE_ENCODING);
String stringPageLimit = parameters.get(PAGE_LIMIT);
int pageLimit = -1;
if ( stringPageLimit != null)
if (stringPageLimit != null)
{
pageLimit = parseInt(stringPageLimit, PAGE_LIMIT);
}
@@ -148,18 +151,19 @@ public class TextToPdfContentTransformer implements SelectableTransformer
protected InputStreamReader buildReader(InputStream is, String encoding)
{
// If they gave an encoding, try to use it
if(encoding != null)
if (encoding != null)
{
Charset charset = null;
try
{
charset = Charset.forName(encoding);
} catch(Exception e)
}
catch (Exception e)
{
logger.warn("JVM doesn't understand encoding '" + encoding +
"' when transforming text to pdf");
"' when transforming text to pdf");
}
if(charset != null)
if (charset != null)
{
logger.debug("Processing plain text in encoding " + charset.displayName());
return new InputStreamReader(is, charset);
@@ -175,24 +179,31 @@ public class TextToPdfContentTransformer implements SelectableTransformer
{
// REPO-1066: duplicating the following lines from org.apache.pdfbox.tools.TextToPDF because they made them private
// before the upgrade to pdfbox 2.0.8, in pdfbox 1.8, this piece of code was public in org.apache.pdfbox.pdmodel.font.PDType1Font
static PDType1Font getStandardFont(String name) {
return (PDType1Font)STANDARD_14.get(name);
static PDType1Font getStandardFont(String name)
{
return STANDARD_14.get(name);
}
private static final Map<String, PDType1Font> STANDARD_14 = new HashMap<String, PDType1Font>();
static
{
STANDARD_14.put(PDType1Font.TIMES_ROMAN.getBaseFont(), PDType1Font.TIMES_ROMAN);
STANDARD_14.put(PDType1Font.TIMES_BOLD.getBaseFont(), PDType1Font.TIMES_BOLD);
STANDARD_14.put(PDType1Font.TIMES_ITALIC.getBaseFont(), PDType1Font.TIMES_ITALIC);
STANDARD_14.put(PDType1Font.TIMES_BOLD_ITALIC.getBaseFont(), PDType1Font.TIMES_BOLD_ITALIC);
STANDARD_14.put(PDType1Font.TIMES_BOLD_ITALIC.getBaseFont(),
PDType1Font.TIMES_BOLD_ITALIC);
STANDARD_14.put(PDType1Font.HELVETICA.getBaseFont(), PDType1Font.HELVETICA);
STANDARD_14.put(PDType1Font.HELVETICA_BOLD.getBaseFont(), PDType1Font.HELVETICA_BOLD);
STANDARD_14.put(PDType1Font.HELVETICA_OBLIQUE.getBaseFont(), PDType1Font.HELVETICA_OBLIQUE);
STANDARD_14.put(PDType1Font.HELVETICA_BOLD_OBLIQUE.getBaseFont(), PDType1Font.HELVETICA_BOLD_OBLIQUE);
STANDARD_14.put(PDType1Font.HELVETICA_OBLIQUE.getBaseFont(),
PDType1Font.HELVETICA_OBLIQUE);
STANDARD_14.put(PDType1Font.HELVETICA_BOLD_OBLIQUE.getBaseFont(),
PDType1Font.HELVETICA_BOLD_OBLIQUE);
STANDARD_14.put(PDType1Font.COURIER.getBaseFont(), PDType1Font.COURIER);
STANDARD_14.put(PDType1Font.COURIER_BOLD.getBaseFont(), PDType1Font.COURIER_BOLD);
STANDARD_14.put(PDType1Font.COURIER_OBLIQUE.getBaseFont(), PDType1Font.COURIER_OBLIQUE);
STANDARD_14.put(PDType1Font.COURIER_BOLD_OBLIQUE.getBaseFont(), PDType1Font.COURIER_BOLD_OBLIQUE);
STANDARD_14.put(PDType1Font.COURIER_BOLD_OBLIQUE.getBaseFont(),
PDType1Font.COURIER_BOLD_OBLIQUE);
STANDARD_14.put(PDType1Font.SYMBOL.getBaseFont(), PDType1Font.SYMBOL);
STANDARD_14.put(PDType1Font.ZAPF_DINGBATS.getBaseFont(), PDType1Font.ZAPF_DINGBATS);
}
@@ -202,7 +213,7 @@ public class TextToPdfContentTransformer implements SelectableTransformer
// checks for page limits.
// The calling code must close the PDDocument once finished with it.
public PDDocument createPDFFromText(Reader text, int pageLimit)
throws IOException
throws IOException
{
//int pageLimit = (int)pageLimits.getValue();
PDDocument doc = null;
@@ -210,23 +221,23 @@ public class TextToPdfContentTransformer implements SelectableTransformer
try
{
final int margin = 40;
float height = getFont().getFontDescriptor().getFontBoundingBox().getHeight()/1000;
float height = getFont().getFontDescriptor().getFontBoundingBox().getHeight() / 1000;
//calculate font height and increase by 5 percent.
height = height*getFontSize()*1.05f;
height = height * getFontSize() * 1.05f;
doc = new PDDocument();
BufferedReader data = new BufferedReader( text );
BufferedReader data = new BufferedReader(text);
String nextLine = null;
PDPage page = new PDPage();
PDPageContentStream contentStream = null;
float y = -1;
float maxStringLength = page.getMediaBox().getWidth() - 2*margin;
float maxStringLength = page.getMediaBox().getWidth() - 2 * margin;
// There is a special case of creating a PDF document from an empty string.
boolean textIsEmpty = true;
outer:
while( (nextLine = data.readLine()) != null )
while ((nextLine = data.readLine()) != null)
{
// The input text is nonEmpty. New pages will be created and added
@@ -234,29 +245,30 @@ public class TextToPdfContentTransformer implements SelectableTransformer
// the text.
textIsEmpty = false;
String[] lineWords = nextLine.trim().split( " " );
String[] lineWords = nextLine.trim().split(" ");
int lineIndex = 0;
while( lineIndex < lineWords.length )
while (lineIndex < lineWords.length)
{
StringBuffer nextLineToDraw = new StringBuffer();
float lengthIfUsingNextWord = 0;
do
{
nextLineToDraw.append( lineWords[lineIndex] );
nextLineToDraw.append( " " );
nextLineToDraw.append(lineWords[lineIndex]);
nextLineToDraw.append(" ");
lineIndex++;
if( lineIndex < lineWords.length )
if (lineIndex < lineWords.length)
{
String lineWithNextWord = nextLineToDraw.toString() + lineWords[lineIndex];
lengthIfUsingNextWord =
(getFont().getStringWidth( lineWithNextWord )/1000) * getFontSize();
(getFont().getStringWidth(
lineWithNextWord) / 1000) * getFontSize();
}
}
while( lineIndex < lineWords.length &&
lengthIfUsingNextWord < maxStringLength );
if( y < margin )
while (lineIndex < lineWords.length &&
lengthIfUsingNextWord < maxStringLength);
if (y < margin)
{
int test = pageCount +1;
int test = pageCount + 1;
if (pageLimit > 0 && (pageCount++ >= pageLimit))
{
// pageLimits.getAction().throwIOExceptionIfRequired("Page limit ("+pageLimit+
@@ -267,8 +279,8 @@ public class TextToPdfContentTransformer implements SelectableTransformer
// We have crossed the end-of-page boundary and need to extend the
// document by another page.
page = new PDPage();
doc.addPage( page );
if( contentStream != null )
doc.addPage(page);
if (contentStream != null)
{
contentStream.endText();
contentStream.close();
@@ -278,17 +290,17 @@ public class TextToPdfContentTransformer implements SelectableTransformer
contentStream.beginText();
y = page.getMediaBox().getHeight() - margin + height;
contentStream.moveTextPositionByAmount(
margin, y );
margin, y);
}
//System.out.println( "Drawing string at " + x + "," + y );
if( contentStream == null )
if (contentStream == null)
{
throw new IOException( "Error:Expected non-null content stream." );
throw new IOException("Error:Expected non-null content stream.");
}
contentStream.moveTextPositionByAmount( 0, -height);
contentStream.moveTextPositionByAmount(0, -height);
y -= height;
contentStream.drawString( nextLineToDraw.toString() );
contentStream.drawString(nextLineToDraw.toString());
}
}
@@ -300,15 +312,15 @@ public class TextToPdfContentTransformer implements SelectableTransformer
doc.addPage(page);
}
if( contentStream != null )
if (contentStream != null)
{
contentStream.endText();
contentStream.close();
}
}
catch( IOException io )
catch (IOException io)
{
if( doc != null )
if (doc != null)
{
doc.close();
}

View File

@@ -26,30 +26,7 @@
*/
package org.alfresco.transformer;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.transform.client.model.TransformRequest;
import org.alfresco.transformer.transformers.AppleIWorksContentTransformer;
import org.alfresco.transformer.transformers.HtmlParserContentTransformer;
import org.alfresco.transformer.transformers.SelectingTransformer;
import org.alfresco.transformer.transformers.StringExtractingContentTransformer;
import org.alfresco.transformer.transformers.TextToPdfContentTransformer;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_HTML;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_IMAGE_JPEG;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_IWORK_KEYNOTE;
@@ -64,6 +41,26 @@ import static org.springframework.http.HttpStatus.OK;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.transform.client.model.TransformRequest;
import org.alfresco.transformer.transformers.SelectingTransformer;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.Import;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
@RunWith(SpringRunner.class)
@WebMvcTest(MiscController.class)
@Import({SelectingTransformer.class})
@@ -88,12 +85,13 @@ public class MiscControllerTest extends AbstractTransformerControllerTest
expectedSourceFileBytes = readTestFile(sourceExtension);
expectedTargetFileBytes = readTestFile(targetExtension);
//expectedTargetFileBytes = null;
sourceFile = new MockMultipartFile("file", "quick." + sourceExtension, sourceMimetype, expectedSourceFileBytes);
sourceFile = new MockMultipartFile("file", "quick." + sourceExtension, sourceMimetype,
expectedSourceFileBytes);
}
@Override
protected void mockTransformCommand(String sourceExtension, String targetExtension, String sourceMimetype, boolean readTargetFileBytes) throws IOException
protected void mockTransformCommand(String sourceExtension, String targetExtension,
String sourceMimetype, boolean readTargetFileBytes) throws IOException
{
}
@@ -110,13 +108,14 @@ public class MiscControllerTest extends AbstractTransformerControllerTest
@Override
// Add extra required parameters to the request.
protected MockHttpServletRequestBuilder mockMvcRequest(String url, MockMultipartFile sourceFile, String... params)
protected MockHttpServletRequestBuilder mockMvcRequest(String url, MockMultipartFile sourceFile,
String... params)
{
return super.mockMvcRequest(url, sourceFile, params)
.param("targetEncoding", targetEncoding)
.param("sourceEncoding", sourceEncoding)
.param("targetMimetype", targetMimetype)
.param("sourceMimetype", sourceMimetype);
.param("targetEncoding", targetEncoding)
.param("sourceEncoding", sourceEncoding)
.param("targetMimetype", targetMimetype)
.param("sourceMimetype", sourceMimetype);
}
@Test
@@ -130,28 +129,29 @@ public class MiscControllerTest extends AbstractTransformerControllerTest
@Test
public void testHTMLtoString() throws Exception
{
final String NEWLINE = System.getProperty ("line.separator");
final String NEWLINE = System.getProperty("line.separator");
final String TITLE = "Testing!";
final String TEXT_P1 = "This is some text in English";
final String TEXT_P2 = "This is more text in English";
final String TEXT_P3 = "C'est en Fran\u00e7ais et Espa\u00f1ol";
String partA = "<html><head><title>" + TITLE + "</title></head>" + NEWLINE;
String partB = "<body><p>" + TEXT_P1 + "</p>" + NEWLINE +
"<p>" + TEXT_P2 + "</p>" + NEWLINE +
"<p>" + TEXT_P3 + "</p>" + NEWLINE;
"<p>" + TEXT_P2 + "</p>" + NEWLINE +
"<p>" + TEXT_P3 + "</p>" + NEWLINE;
String partC = "</body></html>";
final String expected = TITLE + NEWLINE + TEXT_P1 + NEWLINE + TEXT_P2 + NEWLINE + TEXT_P3 + NEWLINE;
MvcResult result = sendText("html",
"UTF-8",
MIMETYPE_HTML,
"txt",
MIMETYPE_TEXT_PLAIN,
"UTF-8",
expected.getBytes());
"UTF-8",
MIMETYPE_HTML,
"txt",
MIMETYPE_TEXT_PLAIN,
"UTF-8",
expected.getBytes());
String contentResult = new String(result.getResponse().getContentAsByteArray(), targetEncoding);
assertTrue("The content did not include \""+expected, contentResult.contains(expected));
String contentResult = new String(result.getResponse().getContentAsByteArray(),
targetEncoding);
assertTrue("The content did not include \"" + expected, contentResult.contains(expected));
}
@Test
@@ -161,7 +161,7 @@ public class MiscControllerTest extends AbstractTransformerControllerTest
byte[] content = null;
try
{
content = "azAz10!<21>$%^&*()\t\r\n".getBytes("UTF-8");
content = "azAz10!<21>$%^&*()\t\r\n".getBytes(UTF_8);
expected = new String(content, "MacDingbat");
}
catch (UnsupportedEncodingException e)
@@ -170,32 +170,34 @@ public class MiscControllerTest extends AbstractTransformerControllerTest
}
MvcResult result = sendText("txt",
"MacDingbat",
MIMETYPE_TEXT_PLAIN,
"txt",
MIMETYPE_TEXT_PLAIN,
"UTF-8",
content);
"MacDingbat",
MIMETYPE_TEXT_PLAIN,
"txt",
MIMETYPE_TEXT_PLAIN,
"UTF-8",
content);
String contentResult = new String(result.getResponse().getContentAsByteArray(), targetEncoding);
assertTrue("The content did not include \""+expected, contentResult.contains(expected));
String contentResult = new String(result.getResponse().getContentAsByteArray(),
targetEncoding);
assertTrue("The content did not include \"" + expected, contentResult.contains(expected));
}
@Test
public void testEmptyTextFileReturnsEmptyFile() throws Exception
{
// Use empty content to create an empty source file
byte[] content = new byte[0];
byte[] content = new byte[0];
MvcResult result = sendText("txt",
"UTF-8",
MIMETYPE_TEXT_PLAIN,
"txt",
MIMETYPE_TEXT_PLAIN,
"UTF-8",
content);
"UTF-8",
MIMETYPE_TEXT_PLAIN,
"txt",
MIMETYPE_TEXT_PLAIN,
"UTF-8",
content);
assertEquals("Returned content should be empty for an empty source file", 0, result.getResponse().getContentLength());
assertEquals("Returned content should be empty for an empty source file", 0,
result.getResponse().getContentLength());
}
@Test
@@ -203,7 +205,7 @@ public class MiscControllerTest extends AbstractTransformerControllerTest
{
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 must not talk in class or feed my homework to my cat.\n");
@@ -212,12 +214,12 @@ public class MiscControllerTest extends AbstractTransformerControllerTest
expected = sb.toString();
MvcResult result = sendText("txt",
"UTF-8",
MIMETYPE_TEXT_PLAIN,
"pdf",
MIMETYPE_PDF,
"UTF-8",
expected.getBytes());
"UTF-8",
MIMETYPE_TEXT_PLAIN,
"pdf",
MIMETYPE_PDF,
"UTF-8",
expected.getBytes());
// Read back in the PDF and check it
PDDocument doc = PDDocument.load(result.getResponse().getContentAsByteArray());
@@ -257,45 +259,54 @@ public class MiscControllerTest extends AbstractTransformerControllerTest
imageBasedTransform("docx", MIMETYPE_OPENXML_WORDPROCESSING, MIMETYPE_IMAGE_JPEG, "jpeg");
}
private void imageBasedTransform(String sourceExtension, String sourceMimetype, String targetMimetype, String targetExtension) throws Exception
private void imageBasedTransform(String sourceExtension, String sourceMimetype,
String targetMimetype, String targetExtension) throws Exception
{
MockMultipartFile sourceFilex = new MockMultipartFile("file", "test_file." + sourceExtension, sourceMimetype, readTestFile(sourceExtension));
MockMultipartFile sourceFilex = new MockMultipartFile("file",
"test_file." + sourceExtension, sourceMimetype, readTestFile(sourceExtension));
MockHttpServletRequestBuilder requestBuilder = super.mockMvcRequest("/transform", sourceFilex)
.param("targetExtension", "jpeg")
.param("targetMimetype", targetMimetype)
.param("sourceMimetype", sourceMimetype);
MockHttpServletRequestBuilder requestBuilder = super
.mockMvcRequest("/transform", sourceFilex)
.param("targetExtension", "jpeg")
.param("targetMimetype", targetMimetype)
.param("sourceMimetype",
sourceMimetype);
MvcResult result = mockMvc.perform(requestBuilder)
.andExpect(status().is(OK.value()))
.andExpect(header().string("Content-Disposition", "attachment; filename*= UTF-8''test_file." + targetExtension))
.andReturn();
assertTrue("Expected image content but content is empty.",result.getResponse().getContentLengthLong() > 0L);
MvcResult result = mockMvc
.perform(requestBuilder)
.andExpect(status().is(OK.value()))
.andExpect(header().string("Content-Disposition",
"attachment; filename*= UTF-8''test_file." + targetExtension))
.andReturn();
assertTrue("Expected image content but content is empty.",
result.getResponse().getContentLengthLong() > 0L);
}
private MvcResult sendText(String sourceExtension,
String sourceEncoding,
String sourceMimetype,
String targetExtension,
String targetMimetype,
String targetEncoding,
byte[] content) throws Exception
String sourceEncoding,
String sourceMimetype,
String targetExtension,
String targetMimetype,
String targetEncoding,
byte[] content) throws Exception
{
MockMultipartFile sourceFilex = new MockMultipartFile("file", "test_file." + sourceExtension, sourceMimetype, content);
MockMultipartFile sourceFilex = new MockMultipartFile("file",
"test_file." + sourceExtension, sourceMimetype, content);
MockHttpServletRequestBuilder requestBuilder = super.mockMvcRequest("/transform", sourceFilex)
.param("targetExtension", targetExtension)
.param("targetEncoding", targetEncoding)
.param("targetMimetype", targetMimetype)
.param("sourceEncoding", sourceEncoding)
.param("sourceMimetype", sourceMimetype);
MockHttpServletRequestBuilder requestBuilder = super
.mockMvcRequest("/transform", sourceFilex)
.param("targetExtension", targetExtension)
.param("targetEncoding", targetEncoding)
.param("targetMimetype", targetMimetype)
.param("sourceEncoding", sourceEncoding)
.param("sourceMimetype", sourceMimetype);
MvcResult result = mockMvc.perform(requestBuilder)
.andExpect(status().is(OK.value()))
.andExpect(header().string("Content-Disposition", "attachment; filename*= "+targetEncoding+"''test_file." + targetExtension)).
andReturn();
MvcResult result = mockMvc
.perform(requestBuilder)
.andExpect(status().is(OK.value()))
.andExpect(header().string("Content-Disposition",
"attachment; filename*= " + targetEncoding + "''test_file." + targetExtension))
.andReturn();
return result;
}
@@ -307,5 +318,4 @@ public class MiscControllerTest extends AbstractTransformerControllerTest
text = text.replaceAll("\\n", "");
return text;
}
}

View File

@@ -26,16 +26,16 @@
*/
package org.alfresco.transformer;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_HTML;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_TEXT_PLAIN;
import java.util.UUID;
import org.alfresco.transform.client.model.TransformRequest;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.UUID;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_HTML;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_TEXT_PLAIN;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = {"activemq.url=nio://localhost:61616"})
@@ -44,14 +44,15 @@ public class MiscQueueTransformServiceIT extends AbstractQueueTransformServiceIT
@Override
protected TransformRequest buildRequest()
{
return TransformRequest.builder()
.withRequestId(UUID.randomUUID().toString())
.withSourceMediaType(MIMETYPE_HTML)
.withTargetMediaType(MIMETYPE_TEXT_PLAIN)
.withTargetExtension("txt")
.withSchema(1)
.withClientData("ACS")
.withSourceReference(UUID.randomUUID().toString())
.withSourceSize(32L).build();
return TransformRequest
.builder()
.withRequestId(UUID.randomUUID().toString())
.withSourceMediaType(MIMETYPE_HTML)
.withTargetMediaType(MIMETYPE_TEXT_PLAIN)
.withTargetExtension("txt")
.withSchema(1)
.withClientData("ACS")
.withSourceReference(UUID.randomUUID().toString())
.withSourceSize(32L).build();
}
}

View File

@@ -26,13 +26,8 @@
*/
package org.alfresco.transformer.transformers;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import static org.alfresco.transformer.transformers.StringExtractingContentTransformer.SOURCE_ENCODING;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FileOutputStream;
@@ -41,9 +36,11 @@ import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
import static org.alfresco.transformer.transformers.StringExtractingContentTransformer.SOURCE_ENCODING;
import static org.alfresco.transformer.transformers.StringExtractingContentTransformer.TARGET_ENCODING;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@Import(HtmlParserContentTransformer.class)
@@ -54,24 +51,24 @@ public class HtmlParserContentTransformerTest
/**
* Checks that we correctly handle text in different encodings,
* no matter if the encoding is specified on the Content Property
* or in a meta tag within the HTML itself. (ALF-10466)
* no matter if the encoding is specified on the Content Property
* or in a meta tag within the HTML itself. (ALF-10466)
*
* On Windows, org.htmlparser.beans.StringBean.carriageReturn() appends a new system dependent new line
* so we must be careful when checking the returned text
* On Windows, org.htmlparser.beans.StringBean.carriageReturn() appends a new system dependent new line
* so we must be careful when checking the returned text
*/
@Test
public void testEncodingHandling() throws Exception
{
final String NEWLINE = System.getProperty ("line.separator");
final String NEWLINE = System.getProperty("line.separator");
final String TITLE = "Testing!";
final String TEXT_P1 = "This is some text in English";
final String TEXT_P2 = "This is more text in English";
final String TEXT_P3 = "C'est en Fran\u00e7ais et Espa\u00f1ol";
String partA = "<html><head><title>" + TITLE + "</title></head>" + NEWLINE;
String partB = "<body><p>" + TEXT_P1 + "</p>" + NEWLINE +
"<p>" + TEXT_P2 + "</p>" + NEWLINE +
"<p>" + TEXT_P3 + "</p>" + NEWLINE;
"<p>" + TEXT_P2 + "</p>" + NEWLINE +
"<p>" + TEXT_P3 + "</p>" + NEWLINE;
String partC = "</body></html>";
final String expected = TITLE + NEWLINE + TEXT_P1 + NEWLINE + TEXT_P2 + NEWLINE + TEXT_P3 + NEWLINE;
@@ -82,7 +79,7 @@ public class HtmlParserContentTransformerTest
{
// Content set to ISO 8859-1
tmpS = File.createTempFile("AlfrescoTestSource_", ".html");
writeToFile(tmpS, partA+partB+partC, "ISO-8859-1");
writeToFile(tmpS, partA + partB + partC, "ISO-8859-1");
tmpD = File.createTempFile("AlfrescoTestTarget_", ".txt");
@@ -96,7 +93,7 @@ public class HtmlParserContentTransformerTest
// Content set to UTF-8
tmpS = File.createTempFile("AlfrescoTestSource_", ".html");
writeToFile(tmpS, partA+partB+partC, "UTF-8");
writeToFile(tmpS, partA + partB + partC, "UTF-8");
tmpD = File.createTempFile("AlfrescoTestTarget_", ".txt");
parameters = new HashMap<>();
@@ -106,10 +103,9 @@ public class HtmlParserContentTransformerTest
tmpS.delete();
tmpD.delete();
// Content set to UTF-16
tmpS = File.createTempFile("AlfrescoTestSource_", ".html");
writeToFile(tmpS, partA+partB+partC, "UTF-16");
writeToFile(tmpS, partA + partB + partC, "UTF-16");
tmpD = File.createTempFile("AlfrescoTestTarget_", ".txt");
parameters = new HashMap<>();
@@ -129,9 +125,9 @@ public class HtmlParserContentTransformerTest
// Content set to ISO 8859-1, meta set to UTF-8
tmpS = File.createTempFile("AlfrescoTestSource_", ".html");
String str = partA+
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" +
partB+partC;
String str = partA +
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" +
partB + partC;
writeToFile(tmpS, str, "UTF-8");
@@ -144,7 +140,6 @@ public class HtmlParserContentTransformerTest
tmpS.delete();
tmpD.delete();
// Note - we can't test UTF-16 with only a meta encoding,
// because without that the parser won't know about the
// 2 byte format so won't be able to identify the meta tag
@@ -166,7 +161,7 @@ public class HtmlParserContentTransformerTest
private String readFromFile(File file, String encoding) throws Exception
{
String content = "wrong content";
String content = "wrong content";
content = new String(Files.readAllBytes(file.toPath()), encoding);
return content;
}

View File

@@ -26,15 +26,8 @@
*/
package org.alfresco.transformer.transformers;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import static org.alfresco.transformer.transformers.TextToPdfContentTransformer.PAGE_LIMIT;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.FileOutputStream;
@@ -43,8 +36,14 @@ import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import static org.alfresco.transformer.transformers.TextToPdfContentTransformer.PAGE_LIMIT;
import static org.junit.Assert.*;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@Import(TextToPdfContentTransformer.class)
@@ -60,7 +59,6 @@ public class TextToPdfContentTransformerTest
transformer.setFontSize(20);
}
@Test
public void testUnlimitedPages() throws Exception
{
@@ -88,11 +86,11 @@ public class TextToPdfContentTransformerTest
private void transformTextAndCheckPageLength(int pageLimit) throws Exception
{
int pageLength = 32;
int lines = (pageLength+10) * ((pageLimit > 0) ? pageLimit : 1);
int lines = (pageLength + 10) * ((pageLimit > 0) ? pageLimit : 1);
StringBuilder sb = new StringBuilder();
String checkText = null;
int cutoff = pageLimit * pageLength;
for (int i=1; i<=lines; i++)
for (int i = 1; i <= lines; i++)
{
sb.append(i);
sb.append(" I must not talk in class or feed my homework to my cat.\n");
@@ -105,12 +103,12 @@ public class TextToPdfContentTransformerTest
transformTextAndCheck(text, "UTF-8", checkText, String.valueOf(pageLimit));
}
private void transformTextAndCheck(String text, String encoding, String checkText, String pageLimit) throws Exception
private void transformTextAndCheck(String text, String encoding, String checkText,
String pageLimit) throws Exception
{
// Get a reader for the text
File sourceFile = File.createTempFile("AlfrescoTestSource_", ".txt");
writeToFile(sourceFile,text, encoding);
writeToFile(sourceFile, text, encoding);
// And a temp writer
File targetFile = File.createTempFile("AlfrescoTestTarget_", ".pdf");
@@ -130,8 +128,8 @@ public class TextToPdfContentTransformerTest
String roundTrip = clean(textWriter.toString());
assertEquals(
"Incorrect text in PDF when starting from text in " + encoding,
checkText, roundTrip
"Incorrect text in PDF when starting from text in " + encoding,
checkText, roundTrip
);
sourceFile.delete();