REPO-5203 Remove legacy transformers (#181)

Now that the T-Engines provide parity with in process legacy transforms and metadata extract, the legacy transform code is now being removed. This will allow the documentation to be greatly simplified and a number of libraries to be removed.

Custom legacy transforms need to be moved to T-Engines. ACS 6 still provides a version where both may be run in parallel. New versions of the document transform engine (DTE) and media management (MM) are planned for ACS 7.
This commit is contained in:
Alan Davis
2021-01-03 13:20:22 +00:00
committed by GitHub
parent affccc1b4d
commit 5d2c83c14b
229 changed files with 351 additions and 42025 deletions

View File

@@ -88,9 +88,6 @@ import org.junit.runners.Suite;
org.alfresco.repo.module.ModuleComponentHelperTest.class,
org.alfresco.repo.node.getchildren.GetChildrenCannedQueryTest.class,
// the following test fails locally - on windows
org.alfresco.repo.content.transform.DifferrentMimeTypeTest.class,
org.alfresco.repo.attributes.PropTablesCleanupJobIntegrationTest.class,
org.alfresco.service.ServiceRegistryTest.class,

View File

@@ -54,11 +54,7 @@ import org.junit.runners.Suite;
org.alfresco.repo.rendition2.RenditionService2IntegrationTest.class,
org.alfresco.repo.rendition2.LocalTransformServiceRegistryIntegrationTest.class,
org.alfresco.repo.rendition2.LocalTransformClientIntegrationTest.class,
org.alfresco.repo.rendition2.LegacyTransformServiceRegistryIntegrationTest.class,
org.alfresco.repo.rendition2.LegacyTransformClientIntegrationTest.class,
org.alfresco.repo.rendition2.LocalRenditionTest.class,
org.alfresco.repo.rendition2.LegacyRenditionTest.class,
org.alfresco.repo.rendition2.LegacyLocalRenditionTest.class,
org.alfresco.repo.rendition2.NoneRenditionTest.class,
org.alfresco.repo.solr.SOLRTrackingComponentTest.class,

View File

@@ -46,32 +46,6 @@ import org.springframework.context.ApplicationContext;
// Minimum context [classpath:alfresco/minimal-context.xml]
// ----------------------------------------------------------------------
// Limits
org.alfresco.repo.content.transform.AbstractContentTransformerLimitsTest.class,
// Transform tests
org.alfresco.repo.content.transform.BinaryPassThroughContentTransformerTest.class,
org.alfresco.repo.content.transform.ComplexContentTransformerTest.class,
org.alfresco.repo.content.transform.ContentTransformerRegistryTest.class,
org.alfresco.repo.content.transform.HtmlParserContentTransformerTest.class,
org.alfresco.repo.content.transform.MailContentTransformerTest.class,
org.alfresco.repo.content.transform.EMLTransformerTest.class,
org.alfresco.repo.content.transform.MediaWikiContentTransformerTest.class,
org.alfresco.repo.content.transform.OpenOfficeContentTransformerTest.class,
// Requires a transformer to be installed in the system
//org.alfresco.repo.content.transform.PdfBoxContentTransformerTest.class,
org.alfresco.repo.content.transform.PoiContentTransformerTest.class,
org.alfresco.repo.content.transform.PoiHssfContentTransformerTest.class,
org.alfresco.repo.content.transform.PoiOOXMLContentTransformerTest.class,
org.alfresco.repo.content.transform.RuntimeExecutableContentTransformerTest.class,
org.alfresco.repo.content.transform.StringExtractingContentTransformerTest.class,
org.alfresco.repo.content.transform.TextMiningContentTransformerTest.class,
org.alfresco.repo.content.transform.TextToPdfContentTransformerTest.class,
org.alfresco.repo.content.transform.TikaAutoContentTransformerTest.class,
org.alfresco.repo.content.transform.magick.ImageMagickContentTransformerTest.class,
org.alfresco.repo.content.transform.AppleIWorksContentTransformerTest.class,
org.alfresco.repo.content.transform.ArchiveContentTransformerTest.class,
// Metadata tests - replaced with simplified tests in LocalRenditionTest and ServiceRenditionTest
org.alfresco.repo.content.metadata.RFC822MetadataExtracterTest.class,
org.alfresco.repo.content.metadata.MappingMetadataExtracterTest.class,

View File

@@ -72,7 +72,6 @@ import org.alfresco.util.ApplicationContextHelper;
import org.alfresco.util.GUID;
import org.alfresco.util.testing.category.LuceneTests;
import org.alfresco.util.testing.category.RedundantTests;
import org.apache.tika.metadata.Metadata;
import org.junit.experimental.categories.Category;
import org.springframework.context.ConfigurableApplicationContext;
@@ -306,8 +305,8 @@ public class ContentMetadataExtracterTagMappingTest extends TestCase
super(Sets.newHashSet(MimetypeMap.MIMETYPE_IMAGE_JPEG));
Properties mappingProperties = new Properties();
// TODO move to new keyword once tika is upgraded
mappingProperties.put(Metadata.KEYWORDS, ContentModel.PROP_TAGS.toString());
mappingProperties.put(Metadata.DESCRIPTION, ContentModel.PROP_DESCRIPTION.toString());
mappingProperties.put("Keywords", ContentModel.PROP_TAGS.toString());
mappingProperties.put("description", ContentModel.PROP_DESCRIPTION.toString());
setMappingProperties(mappingProperties);
}
@@ -336,7 +335,7 @@ public class ContentMetadataExtracterTagMappingTest extends TestCase
// Add some test keywords to those actually extracted from the file including a nodeRef
List<String> keywords = new ArrayList<String>(Arrays.asList(
new String[] { existingTagNodeRef, TAG_2, TAG_3, TAG_NONEXISTENT_NODEREF }));
Serializable extractedKeywords = rawMap.get(Metadata.KEYWORDS);
Serializable extractedKeywords = rawMap.get("Keywords");
if (extractedKeywords != null && extractedKeywords instanceof String)
{
keywords.add((String) extractedKeywords);
@@ -345,7 +344,7 @@ public class ContentMetadataExtracterTagMappingTest extends TestCase
{
keywords.addAll((Collection<? extends String>) extractedKeywords);
}
putRawValue(Metadata.KEYWORDS, (Serializable) keywords, rawMap);
putRawValue("Keywords", (Serializable) keywords, rawMap);
return rawMap;
}
}

View File

@@ -76,8 +76,7 @@ import java.util.Properties;
import java.util.Set;
/**
* Test of the ActionExecuter for extracting metadata. Note: This test makes
* assumptions about the PDF test data for PdfBoxExtracter.
* Test of the ActionExecuter for extracting metadata.
*
* @author Jesper Steen Møller
*/

View File

@@ -1,229 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2017 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content;
import java.io.File;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.transform.AbstractContentTransformerTest;
import org.alfresco.repo.content.transform.ContentTransformer;
import org.alfresco.repo.management.subsystems.ChildApplicationContextFactory;
import org.alfresco.repo.model.Repository;
import org.alfresco.repo.rendition2.SynchronousTransformClient;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.alfresco.service.cmr.thumbnail.ThumbnailService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.ApplicationContextHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.springframework.context.ApplicationContext;
/**
* @deprecated The JodConverterMetadataExtracter has not been in use since 6.0.1 and the transformer is also deprecated.
*
* @author Neil McErlean
* @since 3.3
*/
@Ignore("This is an abstract class so don't instaniate it or run it in Junit")
@Deprecated
public abstract class AbstractJodConverterBasedTest
{
private static Log log = LogFactory.getLog(AbstractJodConverterBasedTest.class);
protected static ApplicationContext ctx = ApplicationContextHelper.getApplicationContext();
protected static ServiceRegistry serviceRegistry;
protected static TransactionService transactionService;
protected static NodeService nodeService;
protected static ContentService contentService;
protected static ThumbnailService thumbnailService;
private static Repository repositoryHelper;
private static ChildApplicationContextFactory oooJodcSubsystem;
protected NodeRef contentNodeRef;
protected LinkedList<NodeRef> nodesToDeleteAfterTest = new LinkedList<NodeRef>();
/**
* This test relies upon customised OpenOffice.org subsystems being available.
* The OOoDirect subsystem (usually enabled by default) is disabled and the
* OOoJodconverter subsystem (usually disabled by default) is enabled.
* @throws Exception
*/
@BeforeClass
public static void initServicesAndRestartOOoSubsystems() throws Exception
{
if (log.isDebugEnabled())
{
log.debug("initServicesAndRestartOOoSubsystems");
}
repositoryHelper = (Repository) ctx.getBean("repositoryHelper");
serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
contentService = serviceRegistry.getContentService();
nodeService = serviceRegistry.getNodeService();
thumbnailService = serviceRegistry.getThumbnailService();
transactionService = serviceRegistry.getTransactionService();
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
oooJodcSubsystem = (ChildApplicationContextFactory) ctx.getBean("OOoJodconverter");
// Stop the OOoJodconverter subsystem and restart it with test settings i.e. enabled.
// Also a pool of 3 JodConverter instances, just for fun.
if (log.isDebugEnabled())
{
log.debug("Enabling OOoJodconverter");
}
oooJodcSubsystem.stop();
oooJodcSubsystem.setProperty("jodconverter.enabled", "true");
oooJodcSubsystem.setProperty("jodconverter.portNumbers", "2022, 2023, 2024");
oooJodcSubsystem.start();
}
/**
* Returns <code>true</code> if OpenOffice-based transformations are currently known to
* be available, else <code>false</code>.
*/
protected boolean isOpenOfficeAvailable()
{
SynchronousTransformClient synchronousTransformClient = serviceRegistry.getSynchronousTransformClient();
return synchronousTransformClient.isSupported(MimetypeMap.MIMETYPE_WORD, -1, null,
MimetypeMap.MIMETYPE_PDF, Collections.emptyMap(), null, null);
}
@Before
public void createTemporaryNodeRefs() throws Exception
{
// Create a content node which will serve as test data for our transformations.
RetryingTransactionCallback<NodeRef> makeNodeCallback = new RetryingTransactionCallback<NodeRef>()
{
public NodeRef execute() throws Throwable
{
if (log.isDebugEnabled())
{
log.debug("Creating temporary NodeRefs for testing.");
}
final NodeRef companyHome = repositoryHelper.getCompanyHome();
// Create a folder
Map<QName, Serializable> folderProps = new HashMap<QName, Serializable>();
folderProps.put(ContentModel.PROP_NAME, this.getClass().getSimpleName() + System.currentTimeMillis());
NodeRef folderNodeRef = nodeService.createNode(companyHome, ContentModel.ASSOC_CONTAINS,
ContentModel.ASSOC_CONTAINS, ContentModel.TYPE_FOLDER, folderProps).getChildRef();
nodesToDeleteAfterTest.add(folderNodeRef);
// Add some content.
File origFile = AbstractContentTransformerTest.loadQuickTestFile("doc");
Map<QName, Serializable> props = new HashMap<QName, Serializable>();
props.put(ContentModel.PROP_NAME, "original." + "doc");
NodeRef node = nodeService.createNode(
folderNodeRef,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "original.doc"),
ContentModel.TYPE_CONTENT,
props).getChildRef();
ContentWriter writer = contentService.getWriter(node, ContentModel.PROP_CONTENT, true);
writer.setMimetype(MimetypeMap.MIMETYPE_WORD);
writer.setEncoding("UTF-8");
writer.putContent(origFile);
return node;
}
};
contentNodeRef = transactionService.getRetryingTransactionHelper().doInTransaction(makeNodeCallback);
this.nodesToDeleteAfterTest.add(contentNodeRef);
}
@After
public void deleteTemporaryNodeRefs()
{
// Tidy up the test nodes we created
RetryingTransactionCallback<Void> deleteNodeCallback = new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
// Delete them in reverse order.
for (Iterator<NodeRef> iter = nodesToDeleteAfterTest.descendingIterator(); iter.hasNext(); )
{
NodeRef nextNodeToDelete = iter.next();
if (nodeService.exists(nextNodeToDelete))
{
if (log.isDebugEnabled())
{
log.debug("Deleting temporary node " + nextNodeToDelete);
}
nodeService.deleteNode(nextNodeToDelete);
}
}
return null;
}
};
transactionService.getRetryingTransactionHelper().doInTransaction(deleteNodeCallback);
}
@AfterClass
public static void stopOOoSubsystems() throws Exception
{
// Put the OOoJodconverter subsystem back to its install settings (disabled).
if (log.isDebugEnabled())
{
log.debug("Disabling OOoJodconverter");
}
oooJodcSubsystem.stop();
oooJodcSubsystem.setProperty("jodconverter.enabled", "false");
oooJodcSubsystem.start();
oooJodcSubsystem.stop();
}
}

View File

@@ -1,244 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2017 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
import java.io.File;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
/**
* Tests methods added to JodConverterSharedInstance that try to use the replaced oooDirect settings.
* @author Alan Davis
*/
public class JodConverterSharedInstanceTest
{
public static final String LIBREOFFICE = "libreoffice";
public static final String PROGRAM = "program";
public static final String ELSEWHERE = "elsewhere";
public static final String SOFFICE_BIN = "soffice.bin";
public static final String SOFFICE_EXE = "soffice.exe";
private static final File OFFICE_HOME_DIR = new File(LIBREOFFICE);
private static final File PROGRAM_DIR = new File(OFFICE_HOME_DIR, PROGRAM);
private static final File ELSEWHERE_DIR = new File(OFFICE_HOME_DIR, ELSEWHERE);
private static final String OFFICE_HOME = OFFICE_HOME_DIR.getPath();
private static final String PROGRAM_BIN = new File( PROGRAM_DIR, SOFFICE_BIN).getPath();
private static final String PROGRAM_EXE = new File( PROGRAM_DIR, SOFFICE_EXE).getPath();
private static final String ELSEWHERE_BIN = new File( ELSEWHERE_DIR, SOFFICE_BIN).getPath();
private static final String NO_OFFICE_HOME_BIN = new File(new File(PROGRAM), SOFFICE_BIN).getPath();
private static final String JUST_SOFFICE_BIN = new File( SOFFICE_BIN).getPath();
private JodConverterSharedInstance instance;
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
instance = new JodConverterSharedInstance();
}
@Test
public void setupTest()
{
String SLASH = File.separator;
assertEquals(LIBREOFFICE, OFFICE_HOME);
assertEquals(LIBREOFFICE + SLASH + PROGRAM + SLASH + SOFFICE_EXE, PROGRAM_EXE);
assertEquals(LIBREOFFICE + SLASH + PROGRAM + SLASH + SOFFICE_BIN, PROGRAM_BIN);
assertEquals(LIBREOFFICE + SLASH + ELSEWHERE + SLASH + SOFFICE_BIN, ELSEWHERE_BIN);
assertEquals( PROGRAM + SLASH + SOFFICE_BIN, NO_OFFICE_HOME_BIN);
assertEquals( SOFFICE_BIN, JUST_SOFFICE_BIN);
assertNotEquals(PROGRAM_BIN, PROGRAM_EXE);
}
@Test
public void officeHomeTest()
{
// Only jodconverter.officehome
instance.setOfficeHome(OFFICE_HOME);
instance.setDeprecatedOooExe(null);
assertEquals(OFFICE_HOME, instance.getOfficeHome());
// Use ooo.exe
instance.setOfficeHome(null);
instance.setDeprecatedOooExe(PROGRAM_BIN);
assertEquals(OFFICE_HOME, instance.getOfficeHome());
// jodconverter.officehome wins
instance.setOfficeHome(OFFICE_HOME);
instance.setDeprecatedOooExe(PROGRAM_EXE);
assertEquals(OFFICE_HOME, instance.getOfficeHome());
// ooo.exe has no parent
instance.setOfficeHome(null);
instance.setDeprecatedOooExe(JUST_SOFFICE_BIN);
assertEquals("", instance.getOfficeHome());
// ooo.exe parent is not "program"
instance.setOfficeHome(null);
instance.setDeprecatedOooExe(ELSEWHERE_BIN);
assertEquals("", instance.getOfficeHome());
// ooo.exe has a parent "program" directory but no grandparent
instance.setOfficeHome(null);
instance.setDeprecatedOooExe(NO_OFFICE_HOME_BIN);
assertEquals("", instance.getOfficeHome());
}
@Test
public void enabledTest()
{
// If ooo.enabled is true the JodConverter will be enabled, otherwise the jodconverter.enabled value is used.
// Community set properties via alfresco-global.properties.
// Enterprise may do the same but may also reset jodconverter.enabled them via the Admin console.
// In the case of Enterprise it is very unlikely that ooo.enabled will be set to true.
// Only jodconverter.enabled
instance = new JodConverterSharedInstance();
instance.setEnabled("true");
instance.setDeprecatedOooEnabled(null);
assertTrue(instance.isEnabled());
instance = new JodConverterSharedInstance();
instance.setEnabled("true");
assertTrue(instance.isEnabled());
instance = new JodConverterSharedInstance();
instance.setEnabled("false");
instance.setDeprecatedOooEnabled(null);
assertFalse(instance.isEnabled());
instance = new JodConverterSharedInstance();
instance.setEnabled("false");
assertFalse(instance.isEnabled());
instance = new JodConverterSharedInstance();
instance.setEnabled("any value other than true");
instance.setDeprecatedOooEnabled(null);
assertFalse(instance.isEnabled());
instance = new JodConverterSharedInstance();
instance.setEnabled("");
instance.setDeprecatedOooEnabled(null);
assertFalse(instance.isEnabled());
instance = new JodConverterSharedInstance();
instance.setEnabled(null);
instance.setDeprecatedOooEnabled(null);
assertFalse(instance.isEnabled());
// Use ooo.enabled
instance = new JodConverterSharedInstance();
instance.setEnabled(null);
instance.setDeprecatedOooEnabled("true");
assertTrue(instance.isEnabled());
instance = new JodConverterSharedInstance();
instance.setEnabled(null);
instance.setDeprecatedOooEnabled("false");
assertFalse(instance.isEnabled());
instance = new JodConverterSharedInstance();
instance.setDeprecatedOooEnabled("true");
assertTrue(instance.isEnabled());
instance = new JodConverterSharedInstance();
instance.setDeprecatedOooEnabled("false");
assertFalse(instance.isEnabled());
// Check jodconverter.enabled is used if ooo.enabled is false - Original Enterprise setup
instance = new JodConverterSharedInstance();
instance.setEnabled("true");
instance.setDeprecatedOooEnabled("false");
assertTrue(instance.isEnabled());
instance = new JodConverterSharedInstance();
instance.setEnabled("false");
instance.setDeprecatedOooEnabled("false");
assertFalse(instance.isEnabled());
// Check jodconverter.enabled is ignored if ooo.enabled is true - Original Community setup
instance = new JodConverterSharedInstance();
instance.setEnabled("true");
instance.setDeprecatedOooEnabled("true");
assertTrue(instance.isEnabled());
instance = new JodConverterSharedInstance();
instance.setEnabled("false");
instance.setDeprecatedOooEnabled("true");
assertTrue(instance.isEnabled());
// Check reset of jodconverter.enabled turns off isAvailable
instance = new JodConverterSharedInstance();
instance.setEnabled("true");
instance.isAvailable = true; // Normally set to true after running afterPropertiesSet()
instance.setEnabled("true");
assertTrue(instance.isAvailable);
instance.setEnabled("false");
assertFalse(instance.isAvailable);
instance = new JodConverterSharedInstance();
instance.setEnabled("true");
instance.setDeprecatedOooEnabled("false"); // Extra line compare with previous
instance.isAvailable = true;
instance.setEnabled("true");
assertTrue(instance.isAvailable);
instance.setEnabled("false");
assertFalse(instance.isAvailable);
}
@Test
public void portNumbersTest()
{
// ooo.port or jodconverter.portNumber is used depending on the setting of enabled properties.
// If jodconverter.enabled is true jodconverter.portNumber is used.
// If jodconverter.enabled is false and ooo.enabled is true ooo.port is used.
// If jodconverter.enabled is false and ooo.enabled is true ooo.port is used.
// jodconverter.enabled=true use jodconverter.portNumber
instance.setEnabled("true");
instance.setPortNumbers("8001,8002,8003");
instance.setDeprecatedOooPort("8001");
assertArrayEquals(new int[] {8001, 8002, 8003}, instance.getPortNumbers());
// jodconverter.enabled=true and ooo.enabled=true use jodconverter.portNumber
instance.setDeprecatedOooEnabled("true");
assertArrayEquals(new int[] {8001, 8002, 8003}, instance.getPortNumbers());
// jodconverter.enabled=false and ooo.enabled=true use ooo.port
instance.setEnabled("false");
assertArrayEquals(new int[] {8001}, instance.getPortNumbers());
}
}

View File

@@ -1,574 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.HashMap;
import java.util.Map;
import org.alfresco.MiscContextTestSuite;
import org.alfresco.repo.content.AbstractContentReader;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ContentIOException;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.alfresco.service.cmr.repository.TransformationOptionLimits;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
/**
* Test methods that control limits in {@link AbstractContentTransformerLimits}
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class AbstractContentTransformerLimitsTest
{
private static final String A = MimetypeMap.MIMETYPE_XML;
private static final String B = MimetypeMap.MIMETYPE_HTML;
private static final String C = MimetypeMap.MIMETYPE_PDF;
private AbstractContentTransformerLimits transformer;
private TransformationOptionLimits limits;
private Map<String, Map<String, TransformationOptionLimits>> mimetypeLimits;
private TransformationOptions options;
@Before
public void setUp() throws Exception
{
ApplicationContext ctx = MiscContextTestSuite.getMinimalContext();
ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
MimetypeService mimetypeService = serviceRegistry.getMimetypeService();
TransformerDebug transformerDebug = (TransformerDebug) ctx.getBean("transformerDebug");
TransformerConfig transformerConfig = (TransformerConfig) ctx.getBean("transformerConfig");
transformer = new AbstractContentTransformer2()
{
@Override
public boolean isTransformableMimetype(String sourceMimetype, String targetMimetype,
TransformationOptions options)
{
return false;
}
@Override
protected void transformInternal(ContentReader reader, ContentWriter writer,
TransformationOptions options) throws Exception
{
}
};
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
transformer.setBeanName("transformer.test"+System.currentTimeMillis()%100000);
limits = new TransformationOptionLimits();
options = new TransformationOptions();
}
private void addMimetypeLimits(String source, String target, TransformationOptionLimits limits)
{
if (mimetypeLimits == null)
{
mimetypeLimits = new HashMap<String, Map<String, TransformationOptionLimits>>();
}
Map<String, TransformationOptionLimits> targetLimits = mimetypeLimits.get(source);
if (targetLimits == null)
{
targetLimits = new HashMap<String, TransformationOptionLimits>();
mimetypeLimits.put(source, targetLimits);
}
targetLimits.put(target, limits);
}
@Test
public void testTimeoutMs() throws Exception
{
long value = 1234;
transformer.setTimeoutMs(value);
transformer.register();
long actual = transformer.getTimeoutMs();
assertEquals("Getter did not return set value", value, actual);
}
@Test
public void testReadLimitTimeMs() throws Exception
{
long value = 1234;
transformer.setReadLimitTimeMs(value);
transformer.register();
long actual = transformer.getReadLimitTimeMs();
assertEquals("Getter did not return set value", value, actual);
}
@Test
public void testMaxSourceSizeKBytes() throws Exception
{
long value = 1234;
transformer.setMaxSourceSizeKBytes(value);
transformer.register();
long actual = transformer.getMaxSourceSizeKBytes();
assertEquals("Getter did not return set value", value, actual);
}
@Test
public void testReadLimitKBytes() throws Exception
{
long value = 1234;
transformer.setReadLimitKBytes(value);
transformer.register();
long actual = transformer.getReadLimitKBytes();
assertEquals("Getter did not return set value", value, actual);
}
@Test
public void testMaxPages() throws Exception
{
int value = 1234;
transformer.setMaxPages(value);
transformer.register();
int actual = transformer.getMaxPages();
assertEquals("Getter did not return set value", value, actual);
}
@Test
public void testPageLimit() throws Exception
{
int value = 1234;
transformer.setPageLimit(value);
transformer.register();
int actual = transformer.getPageLimit();
assertEquals("Getter did not return set value", value, actual);
}
@Test
public void testMimetypeLimit() throws Exception
{
long value = 1234;
limits.setMaxSourceSizeKBytes(value);
addMimetypeLimits(A, B, limits);
transformer.setMimetypeLimits(mimetypeLimits);
transformer.register();
long actual = transformer.getLimits(A, B, options).getMaxSourceSizeKBytes();
assertEquals("Getter did not return set value", value, actual);
actual = transformer.getLimits(A, C, options).getMaxSourceSizeKBytes();
assertEquals("Other values should not be set", -1, actual);
}
@Test
public void testMimetypeLimitTargetWildcard() throws Exception
{
long value = 1234;
limits.setMaxSourceSizeKBytes(value);
addMimetypeLimits(A, "*", limits);
transformer.setMimetypeLimits(mimetypeLimits);
transformer.register();
long actual = transformer.getLimits(A, B, options).getMaxSourceSizeKBytes();
assertEquals("Getter did not return set value", value, actual);
actual = transformer.getLimits(B, A, options).getMaxSourceSizeKBytes();
assertEquals("Other values should not be set", -1, actual);
}
@Test
public void testMimetypeLimitSourceWildcard() throws Exception
{
long value = 1234;
limits.setMaxSourceSizeKBytes(value);
addMimetypeLimits("*", B, limits);
transformer.setMimetypeLimits(mimetypeLimits);
transformer.register();
long actual = transformer.getLimits(A, B, options).getMaxSourceSizeKBytes();
assertEquals("Getter did not return set value", value, actual);
actual = transformer.getLimits(B, A, options).getMaxSourceSizeKBytes();
assertEquals("Other values should not be set", -1, actual);
}
@Test
public void testPassedInOptions() throws Exception
{
long value = 1234;
limits.setMaxSourceSizeKBytes(value+1);
addMimetypeLimits(A, B, limits);
transformer.setMimetypeLimits(mimetypeLimits);
transformer.register();
long actual = transformer.getLimits(A, B, options).getMaxSourceSizeKBytes();
assertEquals("Getter did not return set value", value+1, actual);
options.setMaxSourceSizeKBytes(value);
actual = transformer.getLimits(A, B, options).getMaxSourceSizeKBytes();
assertEquals("Getter did not return set value", value, actual);
}
@Test
public void testGetMaxSourceSizeKBytes() throws Exception
{
long kValue = 12;
long byteValue = kValue*1024;
// Not set mimetype limits yet
assertTrue("No limits so should have been ok",
transformer.isTransformableSize(A, byteValue+1, B, options));
// Set limit for A to B mimetypes and test
limits.setMaxSourceSizeKBytes(kValue);
addMimetypeLimits(A, B, limits);
transformer.setMimetypeLimits(mimetypeLimits);
transformer.register();
assertEquals("Expected to have set value returned", kValue,
transformer.getMaxSourceSizeKBytes(A, B, options));
// With a mimetype that does not have any specific limits
assertEquals("Expected to have -1 (unlimited) returned", -1,
transformer.getMaxSourceSizeKBytes(C, B, options));
}
@Test
// Combination using just transformer limit to start with
public void testGetMaxSourceSizeKBytesCombination() throws Exception
{
long kValue = 12;
long byteValue = kValue*1024;
// Not set mimetype limits yet
assertTrue("No limits so should have been ok",
transformer.isTransformableSize(A, byteValue+1, B, options));
// Check for combinations with transformer limits
transformer.setMaxSourceSizeKBytes(kValue);
transformer.register();
assertEquals("Expected to have transformer set value returned", kValue,
transformer.getMaxSourceSizeKBytes(A, B, options));
}
@Test
// Combination where mimetype limit is used
public void testGetMaxSourceSizeKBytesCombinationMimetypeUsed() throws Exception
{
long kValue = 12;
long byteValue = kValue*1024;
// Not set mimetype limits yet
assertTrue("No limits so should have been ok",
transformer.isTransformableSize(A, byteValue+1, B, options));
transformer.setMaxSourceSizeKBytes(kValue+1);
limits.setMaxSourceSizeKBytes(kValue);
addMimetypeLimits(A, B, limits);
transformer.setMimetypeLimits(mimetypeLimits);
transformer.register();
assertEquals("Expected to have transformer set value returned", kValue,
transformer.getMaxSourceSizeKBytes(A, B, options));
}
@Test
// Check no limit when page limit set on a transformer that does not support page limit
// maxSourceSizeKbytes value should be ignored if a page limit is in use
public void testGetMaxSourceSizeKBytesPageSupportsNot() throws Exception
{
long kValue = 12;
long byteValue = kValue*1024;
// Not set mimetype limits yet
assertTrue("No limits so should have been ok",
transformer.isTransformableSize(A, byteValue+1, B, options));
transformer.setPageLimitsSupported(false);
transformer.setMaxSourceSizeKBytes(kValue);
limits.setMaxSourceSizeKBytes(kValue+1);
limits.setPageLimit(1);
addMimetypeLimits(A, B, limits);
transformer.setMimetypeLimits(mimetypeLimits);
transformer.register();
assertEquals("Expected to ignore the page limit as the transformer does not support it", kValue+1,
transformer.getMaxSourceSizeKBytes(A, B, options));
}
@Test
// Check no limit when page limit set on a transformer that does support page limit
// maxSourceSizeKbytes value should be ignored if a page limit is in use
public void testGetMaxSourceSizeKBytesPageSupports() throws Exception
{
long kValue = 12;
long byteValue = kValue*1024;
// Not set mimetype limits yet
assertTrue("No limits so should have been ok",
transformer.isTransformableSize(A, byteValue+1, B, options));
transformer.setPageLimitsSupported(true);
transformer.setMaxSourceSizeKBytes(kValue);
limits.setMaxSourceSizeKBytes(kValue+1);
limits.setPageLimit(1);
addMimetypeLimits(A, B, limits);
transformer.setMimetypeLimits(mimetypeLimits);
transformer.register();
assertEquals("Expected to have -1 (unlimited) returned when there are page limits", -1,
transformer.getMaxSourceSizeKBytes(A, B, options));
}
@Test
// Using limit on a mimetype
public void testIsTransformableSizeMimetype() throws Exception
{
long kValue = 12;
long byteValue = kValue*1024;
// Not set mimetype limits yet
assertTrue("No limits so should have been ok",
transformer.isTransformableSize(A, byteValue+1, B, options));
// Set limit for A to B mimetypes and test
limits.setMaxSourceSizeKBytes(kValue);
addMimetypeLimits(A, B, limits);
transformer.setMimetypeLimits(mimetypeLimits);
transformer.register();
assertTrue("Size is less than limit so should have been ok",
transformer.isTransformableSize(A, byteValue-1, B, options));
assertTrue("Size is equal to limit so should have been ok",
transformer.isTransformableSize(A, byteValue, B, options));
assertFalse("Size is greater than limit so should have failed",
transformer.isTransformableSize(A, byteValue+1, B, options));
// With a mimetype that does not have any specific limits
assertTrue("No limits so should have been ok",
transformer.isTransformableSize(C, byteValue+1, B, options));
assertTrue("No limits so should have been ok",
transformer.isTransformableSize(A, byteValue+1, C, options));
assertTrue("No limits so should have been ok",
transformer.isTransformableSize(C, byteValue+1, C, options));
}
@Test
// Using limit on transformer as a whole
public void testIsTransformableSizeTrans() throws Exception
{
long kValue = 12;
long byteValue = kValue*1024;
// Not set mimetype limits yet
assertTrue("No limits so should have been ok",
transformer.isTransformableSize(A, byteValue+1, B, options));
transformer.setMaxSourceSizeKBytes(kValue);
transformer.register();
assertTrue("Size is equal to limit so should have been ok",
transformer.isTransformableSize(A, byteValue, B, options));
assertFalse("Size is greater than limit so should have failed",
transformer.isTransformableSize(A, byteValue+1, B, options));
}
@Test
// Combination where mimetype limit is used
public void testIsTransformableSizeCombinationMimetypeUsed() throws Exception
{
long kValue = 12;
long byteValue = kValue*1024;
// Not set mimetype limits yet
assertTrue("No limits so should have been ok",
transformer.isTransformableSize(A, byteValue+1, B, options));
transformer.setMaxSourceSizeKBytes(kValue+1);
limits.setMaxSourceSizeKBytes(kValue);
addMimetypeLimits(A, B, limits);
transformer.setMimetypeLimits(mimetypeLimits);
transformer.register();
assertTrue("Size is equal to limit so should have been ok",
transformer.isTransformableSize(A, byteValue, B, options));
assertFalse("Size is greater than limit so should have failed",
transformer.isTransformableSize(A, byteValue+1, B, options));
}
@Test
public void testIsTransformableSizeWithPageLimit() throws Exception
{
long kValue = 12;
long byteValue = kValue*1024;
transformer.setMaxSourceSizeKBytes(kValue);
transformer.setPageLimitsSupported(true);
transformer.register();
// Test works as normal before setting the pageLimit
assertTrue("Size is less than limit so should have been ok",
transformer.isTransformableSize(A, byteValue-1, B, options));
assertTrue("Size is equal to limit so should have been ok",
transformer.isTransformableSize(A, byteValue, B, options));
assertFalse("Size is greater than limit so should not have failed",
transformer.isTransformableSize(A, byteValue+1, B, options));
// test with pageLimit set
options.getLimits().setPageLimit(1);
assertTrue("Size is greater than limit BUT pageLimit is set so should have been ok",
transformer.isTransformableSize(A, byteValue+1, B, options));
}
@Test
public void testSetReaderLimits() throws Exception
{
AbstractContentReader reader = new DummyAbstractContentReader(0, 0);
long value = 1234;
transformer.setTimeoutMs(value);
transformer.register();
assertEquals("Limit should not have been set in the reader", null, reader.getLimits());
transformer.setReaderLimits(reader, null, options);
assertEquals("Limit should have been set in the reader", value, reader.getLimits().getTimeoutMs());
options.setTimeoutMs(--value);
transformer.setReaderLimits(reader, null, options);
assertEquals("Limit should have been set in the reader", value, reader.getLimits().getTimeoutMs());
}
/**
* A dummy AbstractContentReader that returns a given number of bytes
* (all 'a') very slowly. There is a configurable delay returning each byte.
* Used to test timeouts and read limits.
*/
private static class DummyAbstractContentReader extends AbstractContentReader
{
final long size;
final long msPerByte;
/**
* @param size of the dummy data
* @param msPerByte milliseconds between byte reads
*/
public DummyAbstractContentReader(long size, long msPerByte)
{
super("a");
this.size = size;
this.msPerByte = msPerByte;
}
/**
* @return Returns an instance of the this class
*/
@Override
protected ContentReader createReader() throws ContentIOException
{
return new DummyAbstractContentReader(size, msPerByte);
}
@Override
protected ReadableByteChannel getDirectReadableChannel() throws ContentIOException
{
InputStream is = new InputStream()
{
long read = 0;
long start = 0;
@Override
public int read() throws IOException
{
if (read >= size)
return -1;
read++;
if (msPerByte > 0)
{
long elapse = System.currentTimeMillis() - start;
if (read == 1)
{
start = elapse;
}
else
{
// On Windows it is possible to just wait 1 ms per byte but this
// does not work on linux hence (end up with a full read taking
// 40 seconds rather than 5) the need to wait if elapse time
// is too fast.
long delay = (read * msPerByte) - elapse;
if (delay > 0)
{
try
{
Thread.sleep(delay);
}
catch (InterruptedException e)
{
// ignore
}
}
}
}
return 'a';
}
// Just a way to tell AbstractContentReader not to wrap the ChannelInputStream
// in a BufferedInputStream
@Override
public boolean markSupported()
{
return true;
}
};
return Channels.newChannel(is);
}
public boolean exists()
{
return true;
}
public long getLastModified()
{
return 0L;
}
public long getSize()
{
return size;
}
};
}

View File

@@ -2,7 +2,7 @@
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* Copyright (C) 2005 - 2019 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
@@ -25,42 +25,19 @@
*/
package org.alfresco.repo.content.transform;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import junit.framework.TestCase;
import org.alfresco.MiscContextTestSuite;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.filestore.FileContentReader;
import org.alfresco.repo.content.filestore.FileContentWriter;
import org.alfresco.repo.management.subsystems.ChildApplicationContextFactory;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.alfresco.util.ApplicationContextHelper;
import org.alfresco.util.TempFileProvider;
import org.alfresco.util.exec.RuntimeExec;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ResourceUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/**
* Provides a base set of tests for testing
* {@link org.alfresco.repo.content.transform.ContentTransformer}
* implementations.
* Now only contains methods to load quick files
*
* @author Derek Hulley
*
@@ -69,67 +46,7 @@ import org.springframework.util.ResourceUtils;
@Deprecated
public abstract class AbstractContentTransformerTest extends TestCase
{
protected static String QUICK_CONTENT = "The quick brown fox jumps over the lazy dog";
private static String[] QUICK_WORDS = new String[] {
"quick", "brown", "fox", "jumps", "lazy", "dog"};
private static Log logger = LogFactory.getLog(AbstractContentTransformerTest.class);
/**
* This context will be fetched each time, but almost always
* will have been cached by {@link ApplicationContextHelper}
*/
protected ApplicationContext ctx;
protected ServiceRegistry serviceRegistry;
protected MimetypeService mimetypeService;
protected TransformerDebug transformerDebug;
protected TransformerConfig transformerConfig;
/**
* Fetches a transformer to test for a given transformation. The transformer
* does not <b>have</b> to be reliable for the given format - if it isn't
* then it will be ignored.
*
* @param sourceMimetype the sourceMimetype to be tested
* @param targetMimetype the targetMimetype to be tested
* @return Returns the <tt>ContentTranslators</tt> that will be tested by
* the methods implemented in this class. A null return value is
* acceptable if the source and target mimetypes are not of interest.
*/
protected abstract ContentTransformer getTransformer(String sourceMimetype, String targetMimetype);
/**
* Ensures that the temp locations are cleaned out before the tests start
*/
@Override
protected void setUp() throws Exception
{
// Grab a suitably configured context
ctx = MiscContextTestSuite.getMinimalContext();
// Grab other useful beans
serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
mimetypeService = serviceRegistry.getMimetypeService();
transformerDebug = (TransformerDebug) ctx.getBean("transformerDebug");
transformerConfig = (TransformerConfig) ctx.getBean("transformerConfig");
// perform a little cleaning up
long now = System.currentTimeMillis();
TempFileProvider.TempFileCleanerJob.removeFiles(now);
}
/**
* Check that all objects are present
*/
public void testSetUp() throws Exception
{
assertNotNull("MimetypeMap not present", mimetypeService);
// check that the quick resources are available
File sourceFile = AbstractContentTransformerTest.loadQuickTestFile("txt");
assertNotNull(sourceFile);
}
/**
* Helper method to load one of the "The quick brown fox" files from the
* classpath.
@@ -180,281 +97,4 @@ public abstract class AbstractContentTransformerTest extends TestCase
{
return loadNamedQuickTestFile("quick."+extension);
}
/**
* For the given mime type, returns one or more quick*
* files to be tested.
* By default this is just quick + the default extension.
* However, you can override this if you need special
* rules, eg quickOld.foo, quickMid.foo and quickNew.foo
* for differing versions of the file format.
*/
protected String[] getQuickFilenames(String sourceMimetype) {
String sourceExtension = mimetypeService.getExtension(sourceMimetype);
return new String[] {
"quick." + sourceExtension
};
}
/**
* Writes the supplied text out to a temporary file, and opens
* a content reader onto it.
*/
protected static ContentReader buildContentReader(String text, Charset encoding)
throws IOException
{
File tmpFile = TempFileProvider.createTempFile("AlfrescoTest_", ".txt");
FileOutputStream out = new FileOutputStream(tmpFile);
OutputStreamWriter wout = new OutputStreamWriter(out, encoding);
wout.write(text);
wout.close();
out.close();
ContentReader reader = new FileContentReader(tmpFile);
reader.setEncoding(encoding.displayName());
reader.setMimetype("text/plain");
return reader;
}
/**
* Tests the full range of transformations available on the
* {@link #getTransformer(String, String) transformer} subject to the
* {@link org.alfresco.util.test.QuickFileTest available test files}
* and the {@link ContentTransformer#getReliability(String, String) reliability} of
* the {@link #getTransformer(String, String) transformer} itself.
* <p>
* Each transformation is repeated several times, with a transformer being
* {@link #getTransformer(String, String) requested} for each transformation. In the
* case where optimizations are being done around the selection of the most
* appropriate transformer, different transformers could be used during the iteration
* process.
* <p>
* Results for the transformations are dumped to a temporary file named
* <b>AbstractContentTransformerTest-results-1234.txt</b>.
*/
public void testAllConversions() throws Exception
{
StringBuilder sb = new StringBuilder(2048);
sb.append("Mimetype Conversion Tests \n")
.append("========================= \n")
.append(" Date: ").append(new Date()).append("\n")
.append("\n");
// get all mimetypes
Set<String> mimetypes = new TreeSet<String>(mimetypeService.getMimetypes());
for (String sourceMimetype : mimetypes)
{
// attempt to get a source file for each mimetype
String[] quickFiles = getQuickFilenames(sourceMimetype);
sb.append(" Source Files: ");
for (String quickFile: quickFiles)
{
sb.append(quickFile);
sb.append(' ');
}
sb.append("\n");
for (String quickFile : quickFiles)
{
String sourceExtension = quickFile.substring(quickFile.lastIndexOf('.')+1);
// attempt to convert to every other mimetype
for (String targetMimetype : mimetypes)
{
if (sourceMimetype.equals(targetMimetype))
{
// Don't test like-to-like transformations
continue;
}
if (!doTestTransformation(quickFile, sourceMimetype, targetMimetype))
{
continue;
}
ContentWriter targetWriter = null;
// construct a reader onto the source file
String targetExtension = mimetypeService.getExtension(targetMimetype);
// must we test the transformation?
ContentTransformer transformer = getTransformer(sourceMimetype, targetMimetype);
if (transformer == null || transformer.isTransformable(sourceMimetype, -1, targetMimetype, null) == false)
{
// no transformer
continue;
}
if (isTransformationExcluded(sourceExtension, targetExtension))
{
continue;
}
// dump
sb.append(" Target Extension: ").append(targetExtension);
sb.append(" <").append(transformer.getClass().getSimpleName()).append(">");
// is there a test file for this conversion?
File sourceFile = AbstractContentTransformerTest.loadNamedQuickTestFile(quickFile);
if (sourceFile == null)
{
sb.append(" <no source test file>\n");
continue; // no test file available for that extension
}
ContentReader sourceReader = new FileContentReader(sourceFile);
// perform the transformation several times so that we get a good idea of performance
int count = 0;
long before = System.currentTimeMillis();
Set<String> transformerClasses = new HashSet<String>(2);
for (int i = 0; i < 5; i++)
{
// get the transformer repeatedly as it might be different each time around
transformer = getTransformer(sourceMimetype, targetMimetype);
// must we report on this class?
if (!transformerClasses.contains(transformer.getClass().getName()))
{
transformerClasses.add(transformer.getClass().getName());
sb.append(" <").append(transformer.getClass().getSimpleName()).append(">");
}
// make a writer for the target file
File targetFile = TempFileProvider.createTempFile(
getClass().getSimpleName() + "_" + getName() + "_" + sourceExtension + "_",
"." + targetExtension);
targetWriter = new FileContentWriter(targetFile);
// do the transformation
sourceReader.setMimetype(sourceMimetype);
targetWriter.setMimetype(targetMimetype);
transformer.transform(sourceReader.getReader(), targetWriter);
// if the target format is any type of text, then it must contain the 'quick' phrase
if (isQuickPhraseExpected(targetMimetype))
{
ContentReader targetReader = targetWriter.getReader();
String checkContent = targetReader.getContentString();
assertTrue("Quick phrase not present in document converted to text: \n" +
" transformer: " + transformer + "\n" +
" source: " + sourceReader + "\n" +
" target: " + targetWriter,
checkContent.contains(QUICK_CONTENT));
// Let subclasses do extra checks if they want
additionalContentCheck(sourceMimetype, targetMimetype, checkContent);
}
else if (isQuickWordsExpected(targetMimetype))
{
ContentReader targetReader = targetWriter.getReader();
String checkContent = targetReader.getContentString();
// essentially check that FTS indexing can use the conversion properly
for (int word = 0; word < QUICK_WORDS.length; word++)
{
assertTrue("Quick phrase word not present in document converted to text: \n" +
" transformer: " + transformer + "\n" +
" source: " + sourceReader + "\n" +
" target: " + targetWriter + "\n" +
" word: " + word,
checkContent.contains(QUICK_WORDS[word]));
}
}
// increment count
count++;
}
long after = System.currentTimeMillis();
double average = (double) (after - before) / (double) count;
// dump
sb.append(String.format(" average %10.0f ms", average)).append("\n");
if (logger.isDebugEnabled())
{
logger.debug("Transformation performed " + count + " time: " +
sourceMimetype + " --> " + targetMimetype + "\n" +
" source: " + sourceReader + "\n" +
" target: " + targetWriter + "\n" +
" transformer: " + getTransformer(sourceMimetype, targetMimetype));
}
}
}
}
// dump to file
File outputFile = TempFileProvider.createTempFile("AbstractContentTransformerTest-results-", ".txt");
ContentWriter outputWriter = new FileContentWriter(outputFile);
outputWriter.setEncoding("UTF8");
outputWriter.putContent(sb.toString());
}
/**
* Allows a subclass to skip selected transformations.
* @param quickFile name
* @param sourceMimetype of the quickFile
* @param targetMimetype of the transformation
* @return false to skip the transformation.
*/
protected boolean doTestTransformation(String quickFile, String sourceMimetype, String targetMimetype)
{
return false;
}
/**
* Allows implementations to do some extra checks on the
* results of the content as found by
* {@link #testAllConversions()}
*/
protected void additionalContentCheck(String sourceMimetype, String targetMimetype, String contents) {}
/**
* This method is an extension point for enabling/disabling an assertion that the "quick brown fox"
* phrase is present in the transformed content.
* By default, the phrase is expected in all text/plain outputs.
*
* @param targetMimetype mimetype of the target of the transformation
* @return <code>true</code> if phrase is expected else <code>false</code>.
*/
protected boolean isQuickPhraseExpected(String targetMimetype)
{
return targetMimetype.equals(MimetypeMap.MIMETYPE_TEXT_PLAIN);
}
/**
* This method is an extension point for enabling/disabling an assertion that the "quick brown fox"
* words are <i>each</i> present in the transformed content.
* By default, the words in the phrase are expected in all text/* outputs.
*
* @param targetMimetype mimetype of the target of the transformation
* @return <code>true</code> if each word is expected else <code>false</code>.
*/
protected boolean isQuickWordsExpected(String targetMimetype)
{
return targetMimetype.startsWith(StringExtractingContentTransformer.PREFIX_TEXT);
}
/**
* This method is an extension point for excluding certain transformations in a subclass.
* The default implementation returns <code>false</code> for all mime type pairs.
*
* @param sourceExtension String
* @param targetExtension String
* @return boolean
*/
protected boolean isTransformationExcluded(String sourceExtension, String targetExtension)
{
return false;
}
// TODO externalise ? Review as part of "fast & reliable tests" (and also testing a "reference deployment" that includes LibreOffice/OpenOffice)
private boolean failTestIfOOWorkerUnavailable = false;
/**
* This method is currently used to skip certain tests if LibreOffice/OpenOffice is not available (eg. on build machines).
*
* @return
* @throws InterruptedException
*/
protected boolean isOpenOfficeWorkerAvailable() throws InterruptedException
{
ChildApplicationContextFactory jodconverterSubsystem = (ChildApplicationContextFactory) ctx.getBean("OOoJodconverter");
JodContentTransformer jodContentTransformer = (JodContentTransformer)jodconverterSubsystem.getApplicationContext().getBean("transformer.worker.JodConverter");
return jodContentTransformer.isAvailable();
}
}

View File

@@ -1,69 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2017 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.service.cmr.repository.TransformationOptions;
/**
* Test case for {@link AppleIWorksContentTransformer} content transformer.
*
* @author Neil Mc Erlean
* @since 4.0
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class AppleIWorksContentTransformerTest extends AbstractContentTransformerTest
{
private AppleIWorksContentTransformer transformer;
@Override
public void setUp() throws Exception
{
super.setUp();
transformer = new AppleIWorksContentTransformer();
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
transformer.afterPropertiesSet();
}
@Override
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
public void testIsTransformable() throws Exception
{
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_IWORK_KEYNOTE, MimetypeMap.MIMETYPE_IMAGE_JPEG, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_IWORK_NUMBERS, MimetypeMap.MIMETYPE_IMAGE_JPEG, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_IWORK_PAGES, MimetypeMap.MIMETYPE_IMAGE_JPEG, new TransformationOptions()));
}
}

View File

@@ -1,248 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2019 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.filestore.FileContentReader;
import org.alfresco.repo.content.filestore.FileContentWriter;
import org.alfresco.repo.management.subsystems.ChildApplicationContextFactory;
import org.alfresco.repo.rendition2.SynchronousTransformClient;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.alfresco.util.TempFileProvider;
/**
* Test class for ArchiveContentTransformer.
*
* @see org.alfresco.repo.content.transform.ArchiveContentTransformer
*
* @author Neil McErlean
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class ArchiveContentTransformerTest extends AbstractContentTransformerTest
{
private ArchiveContentTransformer transformer;
private ContentTransformerRegistry registry;
@Override
public void setUp() throws Exception
{
super.setUp();
transformer = new ArchiveContentTransformer();
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
transformer.afterPropertiesSet();
registry = (ContentTransformerRegistry) ctx.getBean("contentTransformerRegistry");
}
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
public void testIsTransformable() throws Exception
{
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_ZIP, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
assertTrue(transformer.isTransformable("application/x-tar", -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
// TODO should this work ?
//assertTrue(transformer.isTransformable("application/x-gtar", -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
}
@Override
protected boolean isQuickPhraseExpected(String targetMimetype)
{
// The Zip transformer produces names of the entries, not their contents.
return false;
}
@Override
protected boolean isQuickWordsExpected(String targetMimetype)
{
// The Zip transformer produces names of the entries, not their contents.
return false;
}
public void testRecursing() throws Exception
{
ContentWriter writer;
String contents;
// Bean off, no options
transformer.setIncludeContents("FALSE");
writer = getTestWriter();
transformer.transform(getTestReader(), writer);
contents = writer.getReader().getContentString();
testHasFiles(contents);
testNested(contents, false);
// Bean on, no options
transformer.setIncludeContents("TRUE");
writer = getTestWriter();
transformer.transform(getTestReader(), writer);
contents = writer.getReader().getContentString();
testHasFiles(contents);
testNested(contents, true);
// Bean off, Transformation Options off
TransformationOptions options = new TransformationOptions();
transformer.setIncludeContents("FALSE");
writer = getTestWriter();
transformer.transform(getTestReader(), writer, options);
contents = writer.getReader().getContentString();
testHasFiles(contents);
testNested(contents, false);
// Bean on, Transformation Options off
transformer.setIncludeContents("T");
writer = getTestWriter();
transformer.transform(getTestReader(), writer, options);
contents = writer.getReader().getContentString();
testHasFiles(contents);
testNested(contents, true);
// Bean off, Transformation Options on - options win
options.setIncludeEmbedded(true);
transformer.setIncludeContents("FALSE");
writer = getTestWriter();
transformer.transform(getTestReader(), writer, options);
contents = writer.getReader().getContentString();
testHasFiles(contents);
testNested(contents, true);
// Bean on, Transformation Options on
transformer.setIncludeContents("YeS");
writer = getTestWriter();
transformer.transform(getTestReader(), writer, options);
contents = writer.getReader().getContentString();
testHasFiles(contents);
testNested(contents, true);
}
private ContentReader getTestReader() throws IOException {
ContentReader sourceReader = new FileContentReader(
loadQuickTestFile("zip")
);
sourceReader.setMimetype(MimetypeMap.MIMETYPE_ZIP);
return sourceReader;
}
private ContentWriter getTestWriter() throws IOException {
ContentWriter writer = new FileContentWriter(TempFileProvider.createTempFile("test", ".txt"));
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
return writer;
}
private void testHasFiles(String contents)
{
assertTrue("Files not found in " + contents,
contents.contains("quick.txt"));
assertTrue("Files not found in " + contents,
contents.contains("quick.doc"));
assertTrue("Files not found in " + contents,
contents.contains("subfolder/quick.jpg"));
}
private void testNested(String contents, boolean shouldHaveRecursed)
{
assertEquals(
"Recursion was " + shouldHaveRecursed +
" but content was " + contents,
shouldHaveRecursed,
contents.contains("The quick brown fox jumps over the lazy dog")
);
assertEquals(
"Recursion was " + shouldHaveRecursed +
" but content was " + contents,
shouldHaveRecursed,
contents.contains("Le renard brun rapide saute par-dessus le chien paresseux")
);
}
public void testArchiveToPdf() throws Exception
{
String sourceMimetype = MimetypeMap.MIMETYPE_ZIP;
String targetMimetype = MimetypeMap.MIMETYPE_PDF;
// force Transformers subsystem to start (this will also load the ContentTransformerRegistry - including complex/dynamic pipelines)
// note: a call to contentService.getTransformer would also do this .. even if transformer cannot be found (returned as null)
ChildApplicationContextFactory transformersSubsystem = (ChildApplicationContextFactory) ctx.getBean("Transformers");
transformersSubsystem.start();
assertNotNull(registry.getTransformer("transformer.complex.ArchiveToPdf"));
// note: txt -> pdf currently uses OpenOffice/LibreOffice
if (! isOpenOfficeWorkerAvailable())
{
// no connection
System.err.println("ooWorker not available - skipping testArchiveToPdf !!");
return;
}
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
ContentTransformer transformer = serviceRegistry.getContentService().getTransformer(sourceMimetype, targetMimetype);
assertNotNull(transformer);
String sourceExtension = mimetypeService.getExtension(sourceMimetype);
String targetExtension = mimetypeService.getExtension(targetMimetype);
File zipSourceFile = loadQuickTestFile("zip");
ContentReader sourceReader = new FileContentReader(zipSourceFile);
// make a writer for the target file
File targetFile = TempFileProvider.createTempFile(getClass().getSimpleName() + "_"
+ getName() + "_" + sourceExtension + "_", "." + targetExtension);
ContentWriter targetWriter = new FileContentWriter(targetFile);
// do the transformation
sourceReader.setMimetype(sourceMimetype);
targetWriter.setMimetype(targetMimetype);
transformer.transform(sourceReader.getReader(), targetWriter);
ContentReader targetReader = new FileContentReader(targetFile);
assertTrue(targetReader.getSize() > 0);
}
}

View File

@@ -1,76 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.service.cmr.repository.TransformationOptions;
/**
* @see org.alfresco.repo.content.transform.BinaryPassThroughContentTransformer
*
* @author Derek Hulley
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class BinaryPassThroughContentTransformerTest extends AbstractContentTransformerTest
{
private BinaryPassThroughContentTransformer transformer;
@Override
public void setUp() throws Exception
{
super.setUp();
transformer = new BinaryPassThroughContentTransformer();
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
}
/**
* @return Returns the same transformer regardless - it is allowed
*/
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
public void testIsTransformable() throws Exception
{
TransformationOptions options = new TransformationOptions();
boolean reliability = false;
reliability = transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, options);
assertFalse("Mimetype should not be supported", reliability);
reliability = transformer.isTransformable(MimetypeMap.MIMETYPE_XML, -1, MimetypeMap.MIMETYPE_XML, options);
assertFalse("Mimetype should not be supported", reliability);
reliability = transformer.isTransformable(MimetypeMap.MIMETYPE_WORD, -1, MimetypeMap.MIMETYPE_WORD, options);
assertTrue("Mimetype should be supported", reliability);
reliability = transformer.isTransformable(MimetypeMap.MIMETYPE_EXCEL, -1, MimetypeMap.MIMETYPE_EXCEL, options);
assertTrue("Mimetype should be supported", reliability);
}
}

View File

@@ -1,106 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.service.cmr.repository.TransformationOptions;
/**
* Tests a transformation from Powerpoint->PDF->Text.
*
* @see org.alfresco.repo.content.transform.ComplexContentTransformer
*
* @author Derek Hulley
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class ComplexContentTransformerTest extends AbstractContentTransformerTest
{
private ComplexContentTransformer transformer;
private boolean isAvailable;
@Override
public void setUp() throws Exception
{
super.setUp();
ContentTransformer unoTransformer = (ContentTransformer) ctx.getBean("transformer.JodConverter");
ContentTransformer pdfBoxTransformer = (ContentTransformer) ctx.getBean("transformer.PdfBox");
// make sure that they are working for this test
if (unoTransformer.isTransformable(MimetypeMap.MIMETYPE_PPT, -1, MimetypeMap.MIMETYPE_PDF, new TransformationOptions()) == false)
{
isAvailable = false;
return;
}
else if (pdfBoxTransformer.isTransformable(MimetypeMap.MIMETYPE_PDF, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()) == false)
{
isAvailable = false;
return;
}
else
{
isAvailable = true;
}
transformer = new ComplexContentTransformer();
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
// set the transformer list
List<ContentTransformer> transformers = new ArrayList<ContentTransformer>(2);
transformers.add(unoTransformer);
transformers.add(pdfBoxTransformer);
transformer.setTransformers(transformers);
// set the intermediate mimetypes
List<String> intermediateMimetypes = Collections.singletonList(MimetypeMap.MIMETYPE_PDF);
transformer.setIntermediateMimetypes(intermediateMimetypes);
}
/**
* @return Returns the same transformer regardless - it is allowed
*/
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
public void testReliability() throws Exception
{
if (!isAvailable)
{
return;
}
boolean reliability = transformer.isTransformable(MimetypeMap.MIMETYPE_PPT, -1, MimetypeMap.MIMETYPE_PDF, new TransformationOptions());
assertEquals("Mimetype should not be supported", false, reliability);
reliability = transformer.isTransformable(MimetypeMap.MIMETYPE_PPT, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions());
assertEquals("Mimetype should be supported", true, reliability);
}
}

View File

@@ -1,353 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2018 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.filestore.FileContentReader;
import org.alfresco.repo.content.filestore.FileContentWriter;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.alfresco.util.TempFileProvider;
import org.junit.Assert;
import java.util.Collections;
import java.util.List;
import static org.alfresco.repo.content.MimetypeMap.MIMETYPE_TEXT_PLAIN;
/**
* @see org.alfresco.repo.content.transform.ContentTransformerRegistry
*
* @author Derek Hulley
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class ContentTransformerRegistryTest extends AbstractContentTransformerTest
{
private static final String A = MIMETYPE_TEXT_PLAIN;
private static final String B = MimetypeMap.MIMETYPE_XML;
private static final String C = MimetypeMap.MIMETYPE_WORD;
private static final String D = MimetypeMap.MIMETYPE_HTML;
private static final TransformationOptions OPTIONS = new TransformationOptions();
/** a real registry with real transformers */
private ContentTransformerRegistry registry;
/** a fake registry with fake transformers */
private ContentTransformerRegistry dummyRegistry;
private ContentReader reader;
private ContentWriter writer;
private DummyTransformer ad20;
private DummyTransformer ad30;
private DummyTransformer ad10;
private DummyTransformer ad25a;
private DummyTransformer ad25b;
@Override
public void setUp() throws Exception
{
super.setUp();
registry = (ContentTransformerRegistry) ctx.getBean("contentTransformerRegistry");
reader = new FileContentReader(TempFileProvider.createTempFile(getName(), ".txt"));
reader.setMimetype(A);
writer = new FileContentWriter(TempFileProvider.createTempFile(getName(), ".txt"));
writer.setMimetype(D);
byte[] bytes = new byte[256];
for (int i = 0; i < 256; i++)
{
bytes[i] = (byte)i;
}
// create the dummyRegistry
TransformerSelectorImpl transformerSelector = new TransformerSelectorImpl();
transformerSelector.setTransformerConfig(transformerConfig);
transformerSelector.setContentTransformerRegistry(dummyRegistry);
dummyRegistry = new ContentTransformerRegistry(transformerSelector);
transformerSelector.setContentTransformerRegistry(dummyRegistry);
dummyRegistry.setTransformerDebug(transformerDebug);
// create some dummy transformers for reliability tests
new DummyTransformer(mimetypeService, "transformer.testAB10a", transformerDebug, transformerConfig, dummyRegistry, A, B, 10L);
new DummyTransformer(mimetypeService, "transformer.testAB10b", transformerDebug, transformerConfig, dummyRegistry, A, B, 10L);
new DummyTransformer(mimetypeService, "transformer.testAC10a", transformerDebug, transformerConfig, dummyRegistry, A, C, 10L);
new DummyTransformer(mimetypeService, "transformer.testAC10b", transformerDebug, transformerConfig, dummyRegistry, A, C, 10L);
new DummyTransformer(mimetypeService, "transformer.testBC10", transformerDebug, transformerConfig, dummyRegistry, B, C, 10L);
// create some dummy transformers for speed tests
ad20 = new DummyTransformer(mimetypeService, "transformer.testAD20", transformerDebug, transformerConfig, dummyRegistry, A, D, 20L);
ad30 = new DummyTransformer(mimetypeService, "transformer.testAD30", transformerDebug, transformerConfig, dummyRegistry, A, D, 30L);
ad10 = new DummyTransformer(mimetypeService, "transformer.testAD10", transformerDebug, transformerConfig, dummyRegistry, A, D, 10L); // the fast one
ad25a = new DummyTransformer(mimetypeService, "transformer.testAD25a", transformerDebug, transformerConfig, dummyRegistry, A, D, 25L);
ad25b = new DummyTransformer(mimetypeService, "transformer.testAD25b", transformerDebug, transformerConfig, dummyRegistry, A, D, 25L);
}
/**
* Checks that required objects are present
*/
public void testSetUp() throws Exception
{
super.testSetUp();
assertNotNull(registry);
}
/**
* @return Returns the transformer provided by the <b>real</b> registry
*/
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype, TransformationOptions options)
{
return registry.getTransformer(sourceMimetype, -1, targetMimetype, options);
}
public void testGetTransformerEnabledDisabled() throws Exception
{
TransformationOptions options = new TransformationOptions();
Assert.assertNotNull(registry.getTransformer(MIMETYPE_TEXT_PLAIN, -1, MIMETYPE_TEXT_PLAIN, options));
try
{
registry.setEnabled(false);
Assert.assertNull(registry.getTransformer(MIMETYPE_TEXT_PLAIN, -1, MIMETYPE_TEXT_PLAIN, options));
}
finally
{
registry.setEnabled(true);
}
Assert.assertNotNull(registry.getTransformer(MIMETYPE_TEXT_PLAIN, -1, MIMETYPE_TEXT_PLAIN, options));
}
public void testGetActiveTransformersEnabledDisabled() throws Exception
{
TransformationOptions options = new TransformationOptions();
Assert.assertFalse(registry.getActiveTransformers(MIMETYPE_TEXT_PLAIN, -1, MIMETYPE_TEXT_PLAIN, options).isEmpty());
try
{
registry.setEnabled(false);
Assert.assertTrue(registry.getActiveTransformers(MIMETYPE_TEXT_PLAIN, -1, MIMETYPE_TEXT_PLAIN, options).isEmpty());
}
finally
{
registry.setEnabled(true);
}
Assert.assertFalse(registry.getActiveTransformers(MIMETYPE_TEXT_PLAIN, -1, MIMETYPE_TEXT_PLAIN, options).isEmpty());
}
public void testNullRetrieval() throws Exception
{
ContentTransformer transformer = null;
transformer = dummyRegistry.getTransformer(C, -1, B, OPTIONS);
assertNull("No transformer expected", transformer);
transformer = dummyRegistry.getTransformer(C, -1, A, OPTIONS);
assertNull("No transformer expected", transformer);
transformer = dummyRegistry.getTransformer(B, -1, A, OPTIONS);
assertNull("No transformer expected", transformer);
}
public void testSimpleRetrieval() throws Exception
{
ContentTransformer transformer = null;
// B -> C expect true
transformer = dummyRegistry.getTransformer(B, -1, C, OPTIONS);
//transformer = dummyRegistry.getTransformer(B, C, OPTIONS);
assertNotNull("No transformer found", transformer);
assertTrue("Incorrect reliability", transformer.isTransformable(B, -1, C, OPTIONS));
assertFalse("Incorrect reliability", transformer.isTransformable(C, -1, B, OPTIONS));
}
/**
* Force some equally reliant transformers to do some work and develop
* different average transformation times. Check that the registry
* copes with the new averages after a reset.
*/
public void testPerformanceRetrieval() throws Exception
{
// Until the threshold (3) is reached by each transformer with the same priority it will
// be tried that many times in the order defined. 20, 30, 10, 25a, 25b
for (int i=1; i<=3; i++)
{
long expectedTime = i == 1 ? 0L : 20L;
ContentTransformer transformer1 = dummyRegistry.getTransformer(A, -1, D, OPTIONS);
assertEquals(i+" incorrect transformation time", expectedTime, transformer1.getTransformationTime(A, D));
ad20.transformInternal(null, null, null);
expectedTime = i == 1 ? 0L : 30L;
transformer1 = dummyRegistry.getTransformer(A, -1, D, OPTIONS);
assertEquals(i+" incorrect transformation time", expectedTime, transformer1.getTransformationTime(A, D));
ad30.transformInternal(null, null, null);
ad10.transformInternal(null, null, null);
ad25a.transformInternal(null, null, null);
ad25b.transformInternal(null, null, null);
}
// Now the average times are set up, it should find the fastest one
// A -> D expect 1.0, 10ms
ContentTransformer transformer1 = dummyRegistry.getTransformer(A, -1, D, OPTIONS);
assertTrue("Incorrect reliability", transformer1.isTransformable(A, -1, D, OPTIONS));
assertFalse("Incorrect reliability", transformer1.isTransformable(D, -1, A, OPTIONS));
assertEquals("Incorrect transformation time", 10L, transformer1.getTransformationTime(A, D));
// A -> D has 10, 20, 25, 25, 30
List<ContentTransformer> activeTransformers = dummyRegistry.getActiveTransformers(A, -1, D, OPTIONS);
assertEquals("Not all found", 5, activeTransformers.size());
assertEquals("Incorrect order", 10L, activeTransformers.get(0).getTransformationTime(A, D));
assertEquals("Incorrect order", 20L, activeTransformers.get(1).getTransformationTime(A, D));
assertEquals("Incorrect order", 25L, activeTransformers.get(2).getTransformationTime(A, D));
assertEquals("Incorrect order", 25L, activeTransformers.get(3).getTransformationTime(A, D));
assertEquals("Incorrect order", 30L, activeTransformers.get(4).getTransformationTime(A, D));
// Disable two of them, and re-test
((DummyTransformer)activeTransformers.get(2)).disable();
((DummyTransformer)activeTransformers.get(4)).disable();
activeTransformers = dummyRegistry.getActiveTransformers(A, -1, D, OPTIONS);
assertEquals("Not all found", 3, activeTransformers.size());
assertEquals("Incorrect order", 10L, activeTransformers.get(0).getTransformationTime(A, D));
assertEquals("Incorrect order", 20L, activeTransformers.get(1).getTransformationTime(A, D));
assertEquals("Incorrect order", 25L, activeTransformers.get(2).getTransformationTime(A, D));
}
public void testScoredRetrieval() throws Exception
{
ContentTransformer transformer = null;
// A -> B expect 0.6
transformer = dummyRegistry.getTransformer(A, -1, B, OPTIONS);
assertNotNull("No transformer found", transformer);
assertTrue("Incorrect reliability", transformer.isTransformable(A, -1, B, OPTIONS));
assertFalse("Incorrect reliability", transformer.isTransformable(B, -1, A, OPTIONS));
// A -> C expect 1.0
transformer = dummyRegistry.getTransformer(A, -1, C, OPTIONS);
assertNotNull("No transformer found", transformer);
assertTrue("Incorrect reliability", transformer.isTransformable(A, -1, C, OPTIONS));
assertFalse("Incorrect reliability", transformer.isTransformable(C, -1, A, OPTIONS));
}
/**
* Set an explicit, and bizarre, transformation. Check that it is used.
*
*/
public void testExplicitTransformation()
{
AbstractContentTransformer2 dummyTransformer = new DummyTransformer(
mimetypeService,
"transformer.testExplicit",
transformerDebug, transformerConfig,
dummyRegistry, MimetypeMap.MIMETYPE_FLASH, MimetypeMap.MIMETYPE_EXCEL, 12345);
// set an explicit transformation
ExplictTransformationDetails key =
new ExplictTransformationDetails(
MimetypeMap.MIMETYPE_FLASH,
MimetypeMap.MIMETYPE_EXCEL);
dummyTransformer.setExplicitTransformations(Collections.singletonList(key));
// register again
dummyTransformer.register();
// get the appropriate transformer for the bizarre mapping
ContentTransformer checkTransformer = dummyRegistry.getTransformer(MimetypeMap.MIMETYPE_FLASH, -1, MimetypeMap.MIMETYPE_EXCEL, OPTIONS);
assertNotNull("No explicit transformer found", checkTransformer);
assertTrue("Expected explicit transformer", dummyTransformer == checkTransformer);
}
/**
* Dummy transformer that does no transformation and scores exactly as it is
* told to in the constructor. It enables the tests to be sure of what to expect.
*/
private static class DummyTransformer extends AbstractContentTransformer2
{
private String sourceMimetype;
private String targetMimetype;
private long transformationTime;
private boolean disable = false;
public DummyTransformer(
MimetypeService mimetypeService,
String name,
TransformerDebug transformerDebug, TransformerConfig transformerConfig,
ContentTransformerRegistry registry, String sourceMimetype, String targetMimetype, long transformationTime)
{
super.setMimetypeService(mimetypeService);
super.setTransformerDebug(transformerDebug);
super.setTransformerConfig(transformerConfig);
super.setRegistry(registry);
this.sourceMimetype = sourceMimetype;
this.targetMimetype = targetMimetype;
this.transformationTime = transformationTime;
setRegisterTransformer(true);
setBeanName(name+'.'+System.currentTimeMillis()%100000);
// register
register();
}
protected void disable()
{
disable = true;
}
public boolean isTransformableMimetype(String sourceMimetype, String targetMimetype, TransformationOptions options)
{
if (disable) {
return false;
}
if (this.sourceMimetype.equals(sourceMimetype)
&& this.targetMimetype.equals(targetMimetype))
{
return true;
}
else
{
return false;
}
}
/**
* Just notches up some average times
*/
public void transformInternal(
ContentReader reader,
ContentWriter writer,
TransformationOptions options) throws Exception
{
// just update the transformation time
super.recordTime(sourceMimetype, targetMimetype, transformationTime);
}
}
@Override
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
// TODO Auto-generated method stub
return null;
}
}

View File

@@ -1,517 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.filestore.FileContentReader;
import org.alfresco.repo.content.filestore.FileContentWriter;
import org.alfresco.repo.model.Repository;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.ContentIOException;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.ApplicationContextHelper;
import org.alfresco.util.TempFileProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Before;
import org.springframework.context.ApplicationContext;
import junit.framework.TestCase;
/**
* Tests that ContentTransformers only correctly process source nodes if the
* mimetype of the node matches the content. This is the opposite of what this
* test class was originally written to prove for MNT-11015. The current version
* was reworked for MNT-16381.
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class DifferrentMimeTypeTest extends TestCase
{
private static Log log = LogFactory.getLog(DifferrentMimeTypeTest.class);
private AbstractContentTransformer2 contentTransformer;
private TransformationOptions options;
private ServiceRegistry serviceRegistry;
private MimetypeService mimetypeService;
private TransformerDebug transformerDebug;
private TransformerConfig transformerConfig;
private ContentTransformerRegistry registry;
private static Repository repositoryHelper;
private File testFile;
private TransactionService transactionService;
private NodeRef contentNodeRef;
private NodeService nodeService;
private LinkedList<NodeRef> nodesToDeleteAfterTest = new LinkedList<>();
private ContentService contentService;
private int NEITHER = 0;
private int RETRY = 1;
private int STRICT = 2;
private static boolean SUCCESS = true;
private static boolean FAILURE = false;
@Before
public void setUp() throws Exception
{
ApplicationContext ctx = ApplicationContextHelper.getApplicationContext();
serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
mimetypeService = serviceRegistry.getMimetypeService();
transformerDebug = (TransformerDebug) ctx.getBean("transformerDebug");
transformerConfig = (TransformerConfig) ctx.getBean("transformerConfig");
registry = (ContentTransformerRegistry) ctx.getBean("contentTransformerRegistry");
transactionService = serviceRegistry.getTransactionService();
repositoryHelper = (Repository) ctx.getBean("repositoryHelper");
nodeService = serviceRegistry.getNodeService();
contentService = serviceRegistry.getContentService();
assertNotNull("MimetypeMap not present", this.mimetypeService);
assertNotNull("ServiceRegistry not present", serviceRegistry);
assertNotNull("TransformerDebug not present", transformerDebug);
assertNotNull("TransformerConfig not present", transformerConfig);
assertNotNull("transactionService not present", transactionService);
assertNotNull("repositoryHelper not present", repositoryHelper);
assertNotNull("nodeService not present", nodeService);
assertNotNull("contentService not present", contentService);
}
// The file has the correct declared and detected mimetypes,
// so can be processed by all approaches
public void testMimetypesCorrects() throws IOException
{
testTransformToJPeg("quick.gif",
MimetypeMap.MIMETYPE_IMAGE_GIF,
MimetypeMap.MIMETYPE_IMAGE_GIF,
MimetypeMap.MIMETYPE_IMAGE_GIF,
NEITHER, SUCCESS);
}
public void testMimetypesCorrectsRetry() throws IOException
{
testTransformToJPeg("quick.gif",
MimetypeMap.MIMETYPE_IMAGE_GIF,
MimetypeMap.MIMETYPE_IMAGE_GIF,
MimetypeMap.MIMETYPE_IMAGE_GIF,
RETRY, SUCCESS);
}
public void testMimetypesCorrectsStrict() throws IOException
{
testTransformToJPeg("quick.gif",
MimetypeMap.MIMETYPE_IMAGE_GIF,
MimetypeMap.MIMETYPE_IMAGE_GIF,
MimetypeMap.MIMETYPE_IMAGE_GIF,
STRICT, SUCCESS);
}
public void testMimetypesCorrectsRetryStrict() throws IOException
{
testTransformToJPeg("quick.gif",
MimetypeMap.MIMETYPE_IMAGE_GIF,
MimetypeMap.MIMETYPE_IMAGE_GIF,
MimetypeMap.MIMETYPE_IMAGE_GIF,
RETRY|STRICT, SUCCESS);
}
// The file has the wrong extension (it is a .png rather than .docx)
// so can only be processed by the RETRY approach. If strict the transform
// should have been discarded before a retry could be tried.
public void testWrongExtension() throws IOException
{
testTransformToJPeg("quick-differentMimetype.docx",
MimetypeMap.MIMETYPE_OPENXML_WORDPROCESSING,
MimetypeMap.MIMETYPE_OPENXML_WORDPROCESSING,
MimetypeMap.MIMETYPE_IMAGE_PNG,
NEITHER, FAILURE);
}
public void testWrongExtensionRetry() throws IOException
{
testTransformToJPeg("quick-differentMimetype.docx",
MimetypeMap.MIMETYPE_OPENXML_WORDPROCESSING,
MimetypeMap.MIMETYPE_OPENXML_WORDPROCESSING,
MimetypeMap.MIMETYPE_IMAGE_PNG,
RETRY, SUCCESS);
}
public void testWrongExtensionStrict() throws IOException
{
testTransformToJPeg("quick-differentMimetype.docx",
MimetypeMap.MIMETYPE_OPENXML_WORDPROCESSING,
MimetypeMap.MIMETYPE_OPENXML_WORDPROCESSING,
MimetypeMap.MIMETYPE_IMAGE_PNG,
STRICT, FAILURE);
}
public void testWrongExtensionStrictRetry() throws IOException
{
testTransformToJPeg("quick-differentMimetype.docx",
MimetypeMap.MIMETYPE_OPENXML_WORDPROCESSING,
MimetypeMap.MIMETYPE_OPENXML_WORDPROCESSING,
MimetypeMap.MIMETYPE_IMAGE_PNG,
RETRY|STRICT, FAILURE);
}
// The file has the correct extension and content, but the content is incorrectly detected
// as .pdf. As .ai to .pdf is in the white list and has the same format as pdf all 3 can
// only process the file.
public void testDetectedInWhiteList() throws IOException
{
// The transformer can read the file as a pdf and does not know the node had the wrong mimetype.
testTransformToJPeg("quickCS5.ai",
MimetypeMap.MIMETYPE_APPLICATION_ILLUSTRATOR,
MimetypeMap.MIMETYPE_APPLICATION_ILLUSTRATOR,
MimetypeMap.MIMETYPE_PDF,
NEITHER, SUCCESS);
}
public void testDetectedInWhiteListRetry() throws IOException
{
// Same as testDetectedInWhiteList, so did not use the retry
testTransformToJPeg("quickCS5.ai",
MimetypeMap.MIMETYPE_APPLICATION_ILLUSTRATOR,
MimetypeMap.MIMETYPE_APPLICATION_ILLUSTRATOR,
MimetypeMap.MIMETYPE_PDF,
RETRY, SUCCESS);
}
public void testDetectedInWhiteListStrict() throws IOException
{
// Works because ai to pdf is in the white list, so we pass it to the transformer and it can read pdf.
testTransformToJPeg("quickCS5.ai",
MimetypeMap.MIMETYPE_APPLICATION_ILLUSTRATOR,
MimetypeMap.MIMETYPE_APPLICATION_ILLUSTRATOR,
MimetypeMap.MIMETYPE_PDF,
STRICT, SUCCESS);
}
public void testDetectedInWhiteListRetryStrict() throws IOException
{
// Works in the same way as testDetectedInWhiteListStrict.
testTransformToJPeg("quickCS5.ai",
MimetypeMap.MIMETYPE_APPLICATION_ILLUSTRATOR,
MimetypeMap.MIMETYPE_APPLICATION_ILLUSTRATOR,
MimetypeMap.MIMETYPE_PDF,
RETRY|STRICT, SUCCESS);
}
// The file has the correct extension and content, but has the wrong declared mimetype.
// As .ai to .doc is not in the white list a strict check will fail.
public void testDetectedNotInWhiteList() throws IOException
{
// The transformer for .ai to .jpg can do nothing with .doc files, so fails
testTransformToJPeg("quick.doc",
MimetypeMap.MIMETYPE_WORD,
MimetypeMap.MIMETYPE_APPLICATION_ILLUSTRATOR,
MimetypeMap.MIMETYPE_WORD,
NEITHER, FAILURE);
}
public void testDetectedNotInWhiteListRetry() throws IOException
{
// The retry fails without soffice (which is not available on Bamboo)
testTransformToJPeg("quick.doc",
MimetypeMap.MIMETYPE_WORD,
MimetypeMap.MIMETYPE_APPLICATION_ILLUSTRATOR,
MimetypeMap.MIMETYPE_WORD,
RETRY, FAILURE);
}
public void testDetectedNotInWhiteListStrict() throws IOException
{
// ai to doc not in white list
testTransformToJPeg("quick.doc",
MimetypeMap.MIMETYPE_WORD,
MimetypeMap.MIMETYPE_APPLICATION_ILLUSTRATOR,
MimetypeMap.MIMETYPE_WORD,
STRICT, FAILURE);
}
public void testDetectedNotInWhiteListRetryStrict() throws IOException
{
// ai to doc not in white list
testTransformToJPeg("quick.doc",
MimetypeMap.MIMETYPE_WORD,
MimetypeMap.MIMETYPE_APPLICATION_ILLUSTRATOR,
MimetypeMap.MIMETYPE_WORD,
RETRY|STRICT, FAILURE);
}
/**
* Method tries to transform a quick file to a JPeg, setting the declared source Mimetype.
* @param quickname name of the quickfile.
* @param extensionMimetype the expected mimetype of the quick file from the extension
* (this might be wrong - checked).
* @param declaredMimetype source mimetype to be set on the node
* (this may be wrong - simply used).
* @param detectedMimetype the expected mimetype detected from the content
* (this might be wrong - checked).
* @param approach indicates that the initial transform should be using
* STRICT mimetype checking,
* RETRY with another transformer if the declared and derived mimetypes
* don't match, or
* NEITHER if it should uses the original approach with no
* retries and no strict checking.
* @param expectSuccess indicates if the transform is expected to work.
* @throws IOException if the quick file cannot be loaded.
*/
private void testTransformToJPeg(String quickname, String extensionMimetype,
String declaredMimetype, String detectedMimetype, int approach,
boolean expectSuccess) throws IOException
{
boolean retry = (approach&RETRY) != 0;
boolean strict = (approach&STRICT) != 0;
testFile = AbstractContentTransformerTest.loadNamedQuickTestFile(quickname);
options = new TransformationOptions();
createContentNodeRef();
String fileName = testFile.getName();
String actualExtensionMimetype = mimetypeService.guessMimetype(fileName);
assertEquals("The "+quickname+" extension indicates a mimetype of "+actualExtensionMimetype+
" rather than "+extensionMimetype, extensionMimetype, actualExtensionMimetype);
String targetMimeType = MimetypeMap.MIMETYPE_IMAGE_JPEG;
String outputFileExtension = mimetypeService.getExtension(targetMimeType);
AuthenticationUtil.RunAsWork<ContentReader> createTargetWork = new AuthenticationUtil.RunAsWork<ContentReader>()
{
@Override
public ContentReader doWork() throws Exception
{
return contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
}
};
ContentReader contentReader = AuthenticationUtil.runAs(createTargetWork, AuthenticationUtil.getSystemUserName());
contentReader.setMimetype(declaredMimetype);
String actualDetectedMimetype = mimetypeService.getMimetypeIfNotMatches(contentReader);
if (actualDetectedMimetype != null)
{
assertEquals("The mimetype detected from the content was "+actualDetectedMimetype+
" rather than "+detectedMimetype, detectedMimetype, actualDetectedMimetype);
}
long size = contentReader.getSize();
contentTransformer = (AbstractContentTransformer2)registry.getTransformer(declaredMimetype, size, targetMimeType, options);
assertNotNull("Transformer not found", contentTransformer);
boolean originalRetry = (Boolean)contentTransformer.getRetryTransformOnDifferentMimeType();
boolean originalStrict = contentTransformer.getStrictMimeTypeCheck();
assertTrue("Content Transformations should be 'retry' by default", originalRetry);
assertTrue("Content Transformations should be 'strict' by default", originalStrict);
contentTransformer.setRetryTransformOnDifferentMimeType(retry);
contentTransformer.setStrictMimeTypeCheck(strict);
File outputFile = createATempFileForTheDifferentMimeTypeTest(outputFileExtension);
try
{
ContentWriter outputWriter = new FileContentWriter(outputFile);
outputWriter.setMimetype(targetMimeType);
contentTransformer.transform(contentReader.getReader(), outputWriter, options);
if (!expectSuccess)
{
if (strict)
{
fail("The contentTransformer should have failed with an UnsupportedTransformationException");
}
else
{
fail("The contentTransformer should have failed with a ContentIOException");
}
}
// After successful transformation image size should be grater than 0
assertTrue("File transformation failed. Output file size is '0'", outputWriter.getSize() > 0);
}
catch (ContentIOException e)
{
if (expectSuccess)
{
fail("The contentTransformer should NOT have failed with an ContentIOException "+e);
e.printStackTrace();
}
}
catch (UnsupportedTransformationException e)
{
if (expectSuccess)
{
fail("The contentTransformer should NOT have failed with an UnsupportedTransformationException "+e);
e.printStackTrace();
}
if (strict)
{
validateErrorMessage(fileName, declaredMimetype, detectedMimetype, e);
}
}
finally
{
contentTransformer.setRetryTransformOnDifferentMimeType(originalRetry);
contentTransformer.setStrictMimeTypeCheck(originalStrict);
outputFile.deleteOnExit();
}
}
private void validateErrorMessage(String fileName, String declaredMimetype, String detectedMimetype,
UnsupportedTransformationException e)
{
String message = e.getMessage();
assertTrue("Message should contain the original filename (" + fileName + ")", message.contains(fileName));
assertTrue("Message should contain the declared source mimetype (" + declaredMimetype + ")",
message.contains(declaredMimetype));
assertTrue("Message should contain the detected source mimetype (" + detectedMimetype + ")",
message.contains(detectedMimetype));
}
private File createATempFileForTheDifferentMimeTypeTest(String outputFileExtension)
{
return TempFileProvider.createTempFile("DifferentMimeTypeTest-results-", "." + outputFileExtension);
}
private void createContentNodeRef()
{
AuthenticationUtil.RunAsWork<NodeRef> createTargetWork = new AuthenticationUtil.RunAsWork<NodeRef>()
{
@Override
public NodeRef doWork() throws Exception
{
if (log.isDebugEnabled())
{
log.debug("Creating temporary NodeRefs for testing.");
}
final NodeRef companyHome = repositoryHelper.getCompanyHome();
// Create a folder
Map<QName, Serializable> folderProps = new HashMap<>();
folderProps.put(ContentModel.PROP_NAME, this.getClass().getSimpleName() + System.currentTimeMillis());
NodeRef folderNodeRef = nodeService.createNode(companyHome, ContentModel.ASSOC_CONTAINS,
ContentModel.ASSOC_CONTAINS, ContentModel.TYPE_FOLDER, folderProps).getChildRef();
// Mark folder for removing after test
nodesToDeleteAfterTest.add(folderNodeRef);
String fileName = testFile.getName();
Map<QName, Serializable> props = new HashMap<>();
props.put(ContentModel.PROP_NAME, fileName);
NodeRef node = nodeService.createNode(
folderNodeRef,
ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, fileName),
ContentModel.TYPE_CONTENT,
props).getChildRef();
// Make sure the error message contains the file name. Without this it is null.
nodeService.setProperty(node, ContentModel.PROP_NAME, fileName);
options.setSourceNodeRef(node);
// node should be removed after tests
nodesToDeleteAfterTest.add(node);
ContentWriter writer = contentService.getWriter(node, ContentModel.PROP_CONTENT, true);
String targetMimeType = mimetypeService.guessMimetype(fileName);
writer.setMimetype(targetMimeType);
writer.setEncoding("UTF-8");
writer.putContent(testFile);
return node;
}
};
contentNodeRef = AuthenticationUtil.runAs(createTargetWork, AuthenticationUtil.getSystemUserName());
nodesToDeleteAfterTest.add(contentNodeRef);
}
//MNT-16381 related: make sure we match a mime-type with known type aliases and don't dismiss documents as having non-matching type<->actual content
public void testTypeAliasesMatch() throws Exception
{
File testFile = AbstractContentTransformerTest.loadNamedQuickTestFile("quick.xml");
ContentReader sourceReader = new FileContentReader(testFile);
sourceReader.setMimetype(MimetypeMap.MIMETYPE_XML); // "text/xml"
// Detected mimetype is "application/xml"
assertNull(mimetypeService.getMimetypeIfNotMatches(sourceReader));
testFile = AbstractContentTransformerTest.loadNamedQuickTestFile("quick.bmp");
sourceReader = new FileContentReader(testFile);
sourceReader.setMimetype("image/bmp");
// Detected mimetype is "image/x-ms-bmp"
assertNull(mimetypeService.getMimetypeIfNotMatches(sourceReader));
}
@After
public void deleteTemporaryNodeRefsAndTempFiles()
{
// Tidy up the test nodes we created
RetryingTransactionHelper.RetryingTransactionCallback<Void> deleteNodeCallback = new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
// Delete them in reverse order.
for (Iterator<NodeRef> iter = nodesToDeleteAfterTest.descendingIterator(); iter.hasNext(); )
{
NodeRef nextNodeToDelete = iter.next();
if (nodeService.exists(nextNodeToDelete))
{
if (log.isDebugEnabled())
{
log.debug("Deleting temporary node " + nextNodeToDelete);
}
nodeService.deleteNode(nextNodeToDelete);
}
}
return null;
}
};
transactionService.getRetryingTransactionHelper().doInTransaction(deleteNodeCallback);
}
}

View File

@@ -1,267 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2019 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.filestore.FileContentReader;
import org.alfresco.repo.content.filestore.FileContentWriter;
import org.alfresco.repo.management.subsystems.ChildApplicationContextFactory;
import org.alfresco.repo.rendition2.SynchronousTransformClient;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.alfresco.util.TempFileProvider;
import java.io.File;
import java.util.Collections;
/**
* @see org.alfresco.repo.content.transform.EMLTransformer
*
* @author Jamal Kaabi-Mofrad
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class EMLTransformerTest extends AbstractContentTransformerTest
{
private static final String QUICK_EML_CONTENT = "Gym class featuring a brown fox and lazy dog";
private static final String QUICK_EML_CONTENT_SPANISH_UNICODE = "El r\u00E1pido zorro marr\u00F3n salta sobre el perro perezoso";
private static final String QUICK_EML_WITH_ATTACHMENT_CONTENT = "Mail with attachment content";
private static final String QUICK_EML_ATTACHMENT_CONTENT = "File attachment content";
private static final String QUICK_EML_ALTERNATIVE_CONTENT = "alternative plain text";
private static final String QUICK_EML_NESTED_ALTERNATIVE_CONTENT = "nested alternative plain text";
private static final String HTML_SPACE_SPECIAL_CHAR = "&nbsp;";
private EMLTransformer transformer;
private ContentTransformerRegistry registry;
private SynchronousTransformClient synchronousTransformClient;
@Override
public void setUp() throws Exception
{
super.setUp();
transformer = new EMLTransformer();
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
RemoteTransformerClient remoteTransformerClient = new RemoteTransformerClient("miscRemoteTransformerClient", "http://localhost:8090/");
transformer.setRemoteTransformerClient(remoteTransformerClient);
registry = (ContentTransformerRegistry) ctx.getBean("contentTransformerRegistry");
synchronousTransformClient = (SynchronousTransformClient) ctx.getBean("synchronousTransformClient");
}
@Override
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
public void testIsTransformable() throws Exception
{
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_RFC822,
new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_RFC822, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN,
new TransformationOptions()));
}
/**
* Test transforming a valid eml file to text
*/
public void testRFC822ToText() throws Exception
{
File emlSourceFile = loadQuickTestFile("eml");
File txtTargetFile = TempFileProvider.createTempFile("test", ".txt");
ContentReader reader = new FileContentReader(emlSourceFile);
reader.setMimetype(MimetypeMap.MIMETYPE_RFC822);
ContentWriter writer = new FileContentWriter(txtTargetFile);
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
transformer.transform(reader, writer);
ContentReader reader2 = new FileContentReader(txtTargetFile);
reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
assertTrue(reader2.getContentString().contains(QUICK_EML_CONTENT));
}
/**
* Test transforming a valid eml file to pdf using complex transformer ("Rfc822ToPdf") - eg. for HTML5 preview
*/
public void testRFC822ToPdf() throws Exception
{
String sourceMimetype = MimetypeMap.MIMETYPE_RFC822;
String targetMimetype = MimetypeMap.MIMETYPE_PDF;
// force Transformers subsystem to start (this will also load the ContentTransformerRegistry - including complex/dynamic pipelines)
// note: a call to contentService.getTransformer would also do this .. even if transformer cannot be found (returned as null)
ChildApplicationContextFactory transformersSubsystem = (ChildApplicationContextFactory) ctx.getBean("Transformers");
transformersSubsystem.start();
assertNotNull(registry.getTransformer("transformer.complex.Rfc822ToPdf"));
// note: txt -> pdf currently uses OpenOffice/LibreOffice
if (! isOpenOfficeWorkerAvailable())
{
// no connection
System.err.println("ooWorker available - skipping testRFC822ToPdf !!");
return;
}
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
assertTrue(synchronousTransformClient.isSupported(sourceMimetype, -1, null, targetMimetype, Collections.emptyMap(), null, null));
String sourceExtension = mimetypeService.getExtension(sourceMimetype);
String targetExtension = mimetypeService.getExtension(targetMimetype);
File emlSourceFile = loadQuickTestFile("eml");
ContentReader sourceReader = new FileContentReader(emlSourceFile);
// make a writer for the target file
File targetFile = TempFileProvider.createTempFile(getClass().getSimpleName() + "_"
+ getName() + "_" + sourceExtension + "_", "." + targetExtension);
ContentWriter targetWriter = new FileContentWriter(targetFile);
// do the transformation
sourceReader.setMimetype(sourceMimetype);
targetWriter.setMimetype(targetMimetype);
synchronousTransformClient.transform(sourceReader, targetWriter, Collections.emptyMap(), null, null);
ContentReader targetReader = new FileContentReader(targetFile);
assertTrue(targetReader.getSize() > 0);
}
/**
* Test transforming a non-ascii eml file to text
*/
public void testNonAsciiRFC822ToText() throws Exception
{
File emlSourceFile = loadQuickTestFile("spanish.eml");
File txtTargetFile = TempFileProvider.createTempFile("test2", ".txt");
ContentReader reader = new FileContentReader(emlSourceFile);
reader.setMimetype(MimetypeMap.MIMETYPE_RFC822);
ContentWriter writer = new FileContentWriter(txtTargetFile);
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
transformer.transform(reader, writer);
ContentReader reader2 = new FileContentReader(txtTargetFile);
reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
String contentStr = reader2.getContentString();
assertTrue(contentStr.contains(QUICK_EML_CONTENT_SPANISH_UNICODE));
}
/**
* Test transforming a valid eml with an attachment to text; attachment should be ignored
*/
public void testRFC822WithAttachmentToText() throws Exception
{
File emlSourceFile = loadQuickTestFile("attachment.eml");
File txtTargetFile = TempFileProvider.createTempFile("test3", ".txt");
ContentReader reader = new FileContentReader(emlSourceFile);
reader.setMimetype(MimetypeMap.MIMETYPE_RFC822);
ContentWriter writer = new FileContentWriter(txtTargetFile);
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
transformer.transform(reader, writer);
ContentReader reader2 = new FileContentReader(txtTargetFile);
reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
String contentStr = reader2.getContentString();
assertTrue(contentStr.contains(QUICK_EML_WITH_ATTACHMENT_CONTENT));
assertTrue(!contentStr.contains(QUICK_EML_ATTACHMENT_CONTENT));
}
/**
* Test transforming a valid eml with minetype multipart/alternative to text
*/
public void testRFC822AlternativeToText() throws Exception
{
File emlSourceFile = loadQuickTestFile("alternative.eml");
File txtTargetFile = TempFileProvider.createTempFile("test4", ".txt");
ContentReader reader = new FileContentReader(emlSourceFile);
reader.setMimetype(MimetypeMap.MIMETYPE_RFC822);
ContentWriter writer = new FileContentWriter(txtTargetFile);
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
transformer.transform(reader, writer);
ContentReader reader2 = new FileContentReader(txtTargetFile);
reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
String contentStr = reader2.getContentString();
assertTrue(contentStr.contains(QUICK_EML_ALTERNATIVE_CONTENT));
}
/**
* Test transforming a valid eml with nested mimetype multipart/alternative to text
*/
public void testRFC822NestedAlternativeToText() throws Exception
{
File emlSourceFile = loadQuickTestFile("nested.alternative.eml");
File txtTargetFile = TempFileProvider.createTempFile("test5", ".txt");
ContentReader reader = new FileContentReader(emlSourceFile);
reader.setMimetype(MimetypeMap.MIMETYPE_RFC822);
ContentWriter writer = new FileContentWriter(txtTargetFile);
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
transformer.transform(reader, writer);
ContentReader reader2 = new FileContentReader(txtTargetFile);
reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
String contentStr = reader2.getContentString();
assertTrue(contentStr.contains(QUICK_EML_NESTED_ALTERNATIVE_CONTENT));
}
/**
* Test transforming a valid eml with a html part containing html special characters to text
*/
public void testHtmlSpecialCharsToText() throws Exception
{
File emlSourceFile = loadQuickTestFile("htmlChars.eml");
File txtTargetFile = TempFileProvider.createTempFile("test6", ".txt");
ContentReader reader = new FileContentReader(emlSourceFile);
reader.setMimetype(MimetypeMap.MIMETYPE_RFC822);
ContentWriter writer = new FileContentWriter(txtTargetFile);
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
transformer.transform(reader, writer);
ContentReader reader2 = new FileContentReader(txtTargetFile);
reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
String contentStr = reader2.getContentString();
assertTrue(!contentStr.contains(HTML_SPACE_SPECIAL_CHAR));
}
}

View File

@@ -1,148 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.alfresco.util.ApplicationContextHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Tests the FailoverContentTransformer.
*
* @see org.alfresco.repo.content.transform.FailoverContentTransformer
*
* @author Neil McErlean
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class FailoverContentTransformerTest extends AbstractContentTransformerTest
{
private static final String sourceMimeType = MimetypeMap.MIMETYPE_PDF;
private static final String targetMimeType = MimetypeMap.MIMETYPE_IMAGE_PNG;
private static ApplicationContext failoverAppContext =
new ClassPathXmlApplicationContext(new String[] {"classpath:org/alfresco/repo/content/transform/FailoverContentTransformerTest-context.xml"},
ApplicationContextHelper.getApplicationContext());
private FailoverContentTransformer transformer;
@Override
public void setUp() throws Exception
{
super.setUp();
ApplicationContextHelper.getApplicationContext();
transformer = (FailoverContentTransformer) failoverAppContext.getBean("transformer.failover.Test-FailThenSucceed");
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
}
/**
* @return Returns the same transformer regardless - it is allowed
*/
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
public void testReliability() throws Exception
{
// The MIME types here are rather arbitrary
boolean reliability = transformer.isTransformable(sourceMimeType, -1, targetMimeType, new TransformationOptions());
assertEquals("Mimetype should be supported", true, reliability);
}
}
/**
* This dummy class is used only for test purposes within this source file.
*
* @author Neil McErlean
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
class DummyTestContentTransformer extends AbstractContentTransformer2 implements BeanNameAware
{
private static Log logger = LogFactory.getLog(DummyTestContentTransformer.class);
/** Bean name for logging */
private String springBeanName;
private boolean alwaysFail;
public void setAlwaysFail(boolean value)
{
this.alwaysFail = value;
}
@Override
protected void transformInternal(ContentReader reader,
ContentWriter writer, TransformationOptions options)
throws Exception
{
// Do not actually perform any transformation. The test above is only interested in whether
// an exception is thrown and handled.
if (logger.isInfoEnabled())
{
logger.info(springBeanName + " is attempting a transformation");
}
reader.getContentString();
if (alwaysFail)
{
throw new AlfrescoRuntimeException("Test code intentionally failed method call.");
}
else
{
return;
}
}
@Override
public boolean isTransformableMimetype(String sourceMimetype,
String targetMimetype, TransformationOptions options)
{
// We'll arbitrarily claim to be able to transform PDF to PNG
return (MimetypeMap.MIMETYPE_PDF.equals(sourceMimetype) &&
MimetypeMap.MIMETYPE_IMAGE_PNG.equals(targetMimetype));
}
public void setBeanName(String name)
{
this.springBeanName = name;
}
}

View File

@@ -1,229 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import java.io.File;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.filestore.FileContentReader;
import org.alfresco.repo.content.filestore.FileContentWriter;
import org.alfresco.service.cmr.repository.ContentIOException;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.alfresco.util.ApplicationContextHelper;
import org.alfresco.util.TempFileProvider;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Test for the MNT-9257: html2pdf transformer is being triggered incorrectly for password protected MS files
*
* @see org.alfresco.repo.content.transform.FailoverContentTransformer
*
* @author Viachaslau Tsikhanovich
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class FailoverUnsupportedSubtransformerTest extends AbstractContentTransformerTest
{
private static final String sourceMimeType = MimetypeMap.MIMETYPE_EXCEL;
private static final String targetMimeType = MimetypeMap.MIMETYPE_PDF;
private static ApplicationContext failoverAppContext =
new ClassPathXmlApplicationContext(new String[] {"classpath:org/alfresco/repo/content/transform/FailoverContentTransformerTest-context.xml"},
ApplicationContextHelper.getApplicationContext());
private TestFailoverContentTransformer transformer;
@Override
public void setUp() throws Exception
{
super.setUp();
ApplicationContextHelper.getApplicationContext();
transformer = (TestFailoverContentTransformer) failoverAppContext.getBean("transformer.failover.Test-PasswordProtectedMSExcel2Pdf");
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.getTriggered().setValue(false);
}
/**
* @return Returns the same transformer regardless - it is allowed
*/
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
public void testReliability() throws Exception
{
// The MIME types here are rather arbitrary
boolean reliability = transformer.isTransformable(sourceMimeType, -1, targetMimeType, new TransformationOptions());
assertEquals("Mimetype should be supported", true, reliability);
}
@Override
public void testAllConversions() throws Exception
{
// skip
}
public void testExcelToPdfConversion() throws Exception
{
String[] quickFiles = getQuickFilenames(sourceMimeType);
for (String quickFile : quickFiles)
{
String sourceExtension = quickFile.substring(quickFile.lastIndexOf('.') + 1);
// is there a test file for this conversion?
File sourceFile = AbstractContentTransformerTest.loadNamedQuickTestFile(quickFile);
if (sourceFile == null)
{
continue; // no test file available for that extension
}
ContentReader sourceReader = new FileContentReader(sourceFile);
// make a writer for the target file
File targetFile = TempFileProvider.createTempFile(getClass().getSimpleName() + "_" + getName() + "_" + sourceExtension + "_", ".pdf");
ContentWriter targetWriter = new FileContentWriter(targetFile);
// do the transformation
sourceReader.setMimetype(sourceMimeType);
targetWriter.setMimetype(targetMimeType);
try
{
transformer.transform(sourceReader.getReader(), targetWriter);
}
catch (ContentIOException e)
{
// all transformers expected to fail for password protected MS office document
}
if (transformer.getTriggered().getValue())
{
org.junit.Assert.fail("final AbstractContentTransformer2.transform was called for html2pdf");
}
}
}
}
/**
* To share with DummyTestComplexSubtransformer to detect if html2pdf was triggered
*/
@Deprecated
class TestHtml2PdfTriggeredFlag
{
private boolean value;
public boolean getValue()
{
return value;
}
public void setValue(boolean value)
{
this.value = value;
}
}
@Deprecated
class TestFailoverContentTransformer extends FailoverContentTransformer
{
private TestHtml2PdfTriggeredFlag triggered;
public void setTriggered(TestHtml2PdfTriggeredFlag triggered)
{
this.triggered = triggered;
}
public TestHtml2PdfTriggeredFlag getTriggered()
{
return triggered;
}
}
/**
* This dummy class is used only for test purposes within this source file.
*/
@Deprecated
class DummyTestComplexSubtransformer extends ComplexContentTransformer
{
private TestHtml2PdfTriggeredFlag triggered;
public void setTriggered(TestHtml2PdfTriggeredFlag triggered)
{
this.triggered = triggered;
}
@Override
protected void checkTransformable(ContentReader reader, ContentWriter writer, TransformationOptions options)
{
// checkTransformable is called only from AbstractContentTransformer2.transform
// that is final and cannot be overridden
triggered.setValue(true);
super.checkTransformable(reader, writer, options);
}
@Override
public void transformInternal(ContentReader reader,
ContentWriter writer, TransformationOptions options)
throws Exception
{
triggered.setValue(true);
reader.getContentString();
// alwaysFail
throw new AlfrescoRuntimeException("Test code intentionally failed method call.");
}
}
/**
* This dummy class is used only for test purposes within this source file.
*
* Supported source mimetype can be set
*/
@Deprecated
class DummyAnyToPDFTestSubtransformer extends DummyTestContentTransformer
{
@Override
public boolean isTransformableMimetype(String sourceMimetype,
String targetMimetype, TransformationOptions options)
{
// We'll arbitrarily claim to be able to transform PDF to PNG
return MimetypeMap.MIMETYPE_PDF.equals(targetMimetype);
}
}

View File

@@ -1,198 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import java.io.ByteArrayInputStream;
import java.io.File;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.filestore.FileContentWriter;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.TransformationOptions;
/**
* @see org.alfresco.repo.content.transform.HtmlParserContentTransformer
*
* @author Derek Hulley
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class HtmlParserContentTransformerTest extends AbstractContentTransformerTest
{
private HtmlParserContentTransformer transformer;
@Override
public void setUp() throws Exception
{
super.setUp();
transformer = new HtmlParserContentTransformer();
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
transformer.afterPropertiesSet();
}
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
public void testSetUp() throws Exception
{
assertNotNull(transformer);
}
public void checkIsTransformable() throws Exception
{
// check reliability
boolean reliability = transformer.isTransformable(MimetypeMap.MIMETYPE_HTML, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions());
assertTrue(reliability); // plain text to plain text is supported
// check other way around
reliability = transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_HTML, new TransformationOptions());
assertFalse(reliability); // plain text to plain text is not supported
}
/**
* 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)
*
* On Windows, org.htmlparser.beans.StringBean.carriageReturn() appends a new system dependent new line
* so we must be careful when checking the returned text
*/
public void testEncodingHandling() throws Exception
{
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;
String partC = "</body></html>";
final String expected = TITLE + NEWLINE + TEXT_P1 + NEWLINE + TEXT_P2 + NEWLINE + TEXT_P3 + NEWLINE;
ContentWriter content;
ContentWriter dest;
File tmpS = null;
File tmpD = null;
try
{
// Content set to ISO 8859-1
tmpS = File.createTempFile("test", ".html");
content = new FileContentWriter(tmpS);
content.setEncoding("ISO-8859-1");
content.setMimetype(MimetypeMap.MIMETYPE_HTML);
content.putContent(partA+partB+partC);
tmpD = File.createTempFile("test", ".txt");
dest = new FileContentWriter(tmpD);
dest.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
transformer.transform(content.getReader(), dest);
assertEquals(expected, dest.getReader().getContentString());
tmpS.delete();
tmpD.delete();
// Content set to UTF-8
tmpS = File.createTempFile("test", ".html");
content = new FileContentWriter(tmpS);
content.setEncoding("UTF-8");
content.setMimetype(MimetypeMap.MIMETYPE_HTML);
content.putContent(partA+partB+partC);
tmpD = File.createTempFile("test", ".txt");
dest = new FileContentWriter(tmpD);
dest.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
transformer.transform(content.getReader(), dest);
assertEquals(expected, dest.getReader().getContentString());
tmpS.delete();
tmpD.delete();
// Content set to UTF-16
tmpS = File.createTempFile("test", ".html");
content = new FileContentWriter(tmpS);
content.setEncoding("UTF-16");
content.setMimetype(MimetypeMap.MIMETYPE_HTML);
content.putContent(partA+partB+partC);
tmpD = File.createTempFile("test", ".txt");
dest = new FileContentWriter(tmpD);
dest.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
transformer.transform(content.getReader(), dest);
assertEquals(expected, dest.getReader().getContentString());
tmpS.delete();
tmpD.delete();
// Note - since HTML Parser 2.0 META tags specifying the
// document encoding will ONLY be respected if the original
// content type was set to ISO-8859-1.
//
// This means there is now only one test which we can perform
// to ensure that this now-limited overriding of the encoding
// takes effect.
// Content set to ISO 8859-1, meta set to UTF-8
tmpS = File.createTempFile("test", ".html");
content = new FileContentWriter(tmpS);
content.setMimetype(MimetypeMap.MIMETYPE_HTML);
String str = partA+
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" +
partB+partC;
content.putContent(new ByteArrayInputStream(str.getBytes("UTF-8")));
content.setEncoding("ISO-8859-1");
tmpD = File.createTempFile("test", ".txt");
dest = new FileContentWriter(tmpD);
dest.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
transformer.transform(content.getReader(), dest);
assertEquals(expected, dest.getReader().getContentString());
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
}
finally
{
if (tmpS != null && tmpS.exists()) tmpS.delete();
if (tmpD != null && tmpD.exists()) tmpD.delete();
}
}
}

View File

@@ -1,90 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2017 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import static org.junit.Assert.assertNotNull;
import org.alfresco.repo.content.AbstractJodConverterBasedTest;
import org.alfresco.model.ContentModel;
import org.alfresco.repo.thumbnail.ThumbnailDefinition;
import org.alfresco.repo.thumbnail.ThumbnailRegistry;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.repository.NodeRef;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
/**
*
* @author Neil McErlean
* @since 3.2 SP1
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class JodContentTransformerOOoTest extends AbstractJodConverterBasedTest
{
private static Log log = LogFactory.getLog(JodContentTransformerOOoTest.class);
/**
* This test method tests the built-in thumbnail transformations - all for a Word source document.
* This will include transformations doc-pdf-png and doc-pdf-swf. ALF-2070
*/
@Test
public void thumbnailTransformationsUsingJodConverter()
{
// If OpenOffice is not available then we will ignore this test (by passing it).
// This is because not all the build servers have OOo installed.
if (!isOpenOfficeAvailable())
{
System.out.println("Did not run " + this.getClass().getSimpleName() + ".thumbnailTransformationsUsingJodConverter" +
" because OOo is not available.");
return;
}
transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
ThumbnailRegistry thumbnailRegistry = thumbnailService.getThumbnailRegistry();
for (ThumbnailDefinition thumbDef : thumbnailRegistry.getThumbnailDefinitions())
{
if (log.isDebugEnabled())
{
log.debug("Testing thumbnail definition " + thumbDef.getName());
}
NodeRef thumbnail = thumbnailService.createThumbnail(contentNodeRef, ContentModel.PROP_CONTENT,
thumbDef.getMimetype(), thumbDef.getTransformationOptions(), thumbDef.getName());
assertNotNull("Thumbnail was unexpectedly null.", thumbnail);
}
return null;
}
});
}
}

View File

@@ -1,181 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import org.alfresco.repo.rendition2.SynchronousTransformClient;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.alfresco.service.cmr.repository.NodeService;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.alfresco.repo.content.transform.TransformerDebugLogTest.assertDebugEntriesEquals;
import static org.alfresco.repo.content.transform.TransformerLogTest.stripDateStamp;
import static org.alfresco.repo.content.transform.TransformerPropertyNameExtractorTest.mockMimetypes;
import static org.junit.Assert.assertArrayEquals;
import static org.mockito.Mockito.when;
/**
* Test class for LegacyTransformerDebugTest.
*
* @author Alan Davis
*/
@Deprecated
public class LegacyTransformerDebugTest
{
@Mock
private NodeService nodeService;
@Mock
private MimetypeService mimetypeService;
@Mock
private ContentTransformerRegistry transformerRegistry;
@Mock
private TransformerConfig transformerConfig;
@Mock
private SynchronousTransformClient synchronousTransformClient;
@Mock
private AbstractContentTransformerLimits transformer1;
@Mock
private AbstractContentTransformerLimits transformer2;
@Mock
private AbstractContentTransformerLimits transformer3;
@Mock
private AbstractContentTransformerLimits transformer4;
private LegacyTransformerDebug transformerDebug;
private TransformerLog log;
private TransformerDebugLog debug;
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
log = new TransformerLog();
debug = new TransformerDebugLog();
when(transformerConfig.getProperty("transformer.log.entries")).thenReturn("10");
when(transformerConfig.getProperty("transformer.debug.entries")).thenReturn("10");
mockMimetypes(mimetypeService,
"application/pdf", "pdf",
"text/plain", "txt");
when(transformer1.getName()).thenReturn("transformer1");
when(transformer2.getName()).thenReturn("transformer2");
when(transformer3.getName()).thenReturn("transformer3");
when(transformer4.getName()).thenReturn("transformer4");
transformerDebug = new LegacyTransformerDebug();
transformerDebug.setNodeService(nodeService);
transformerDebug.setMimetypeService(mimetypeService);
transformerDebug.setTransformerRegistry(transformerRegistry);
transformerDebug.setTransformerConfig(transformerConfig);
transformerDebug.setTransformerLog(log);
transformerDebug.setTransformerDebugLog(debug);
transformerDebug.setSynchronousTransformClient(synchronousTransformClient);
log.setTransformerDebug(transformerDebug);
log.setTransformerConfig(transformerConfig);
debug.setTransformerDebug(transformerDebug);
debug.setTransformerConfig(transformerConfig);
}
// Replaces any transformer reference numbers N.N.N with "0" before checking
private String[] unnumbered(String actual[])
{
for (int i = actual.length-1; i >= 0; i--)
{
StringJoiner sj = new StringJoiner("\n");
String[] bits = actual[i].split("\n");
for (String bit: bits)
{
Pattern p = Pattern.compile("^[0-9.]*");
Matcher m = p.matcher(bit);
bit = m.replaceFirst("0");
sj.add(bit);
}
actual[i] = sj.toString();
}
return actual;
}
// Replaces any times with " NN ms" before checking
private String[] untimed(String[] actual)
{
for (int i = actual.length-1; i >= 0; i--)
{
actual[i] = actual[i].replaceAll(" \\d+ ms", " NN ms");
}
return actual;
}
@Test
public void alf18373Test()
{
long sourceSize = 1024*1024*3/2;
transformerDebug.pushAvailable("sourceUrl", "application/pdf", "text/plain", null, null);
transformerDebug.unavailableTransformer(transformer1, "application/pdf", "text/plain", 50);
transformerDebug.unavailableTransformer(transformer2, "application/pdf", "text/plain", 0);
transformerDebug.unavailableTransformer(transformer3, "application/pdf", "text/plain", 50);
transformerDebug.unavailableTransformer(transformer4, "application/pdf", "text/plain", 50);
List<ContentTransformer> transformers = Arrays.asList(new ContentTransformer[] {});
transformerDebug.availableTransformers(transformers, sourceSize, null, null, "ContentService.transform(...)");
transformerDebug.popAvailable();
assertDebugEntriesEquals(new String[] {
"0 pdf txt 1.5 MB ContentService.transform(...) NO transformers\n"+
"0 --a) [---] Legacy:transformer1<<Component>> > 50 KB\n"+
"0 --b) [---] Legacy:transformer3<<Component>> > 50 KB\n"+
"0 --c) [---] Legacy:transformer4<<Component>> > 50 KB\n"+
"0 Finished in NN ms Just checking if a transformer is available"}, unnumbered(untimed(debug.getEntries(10))));
assertArrayEquals(new String[] {
"0 pdf txt WARN 1.5 MB NN ms No transformers as file is > 50 KB"}, unnumbered(untimed(stripDateStamp(log.getEntries(10)))));
}
}

View File

@@ -1,140 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import java.io.File;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.filestore.FileContentReader;
import org.alfresco.repo.content.filestore.FileContentWriter;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.alfresco.util.TempFileProvider;
/**
* @see org.alfresco.repo.content.transform.MailContentTransformer
*
* @author Kevin Roast
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class MailContentTransformerTest extends AbstractContentTransformerTest
{
private MailContentTransformer transformer;
@Override
public void setUp() throws Exception
{
super.setUp();
transformer = new MailContentTransformer();
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
transformer.afterPropertiesSet();
}
/**
* @return Returns the same transformer regardless - it is allowed
*/
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
public void testIsTransformable() throws Exception
{
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_OUTLOOK_MSG, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_OUTLOOK_MSG, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
}
/**
* Test transforming a valid msg file to text
*/
public void testMsgToText() throws Exception
{
File msgSourceFile = loadQuickTestFile("msg");
File txtTargetFile = TempFileProvider.createTempFile(getName() + "-target-1", ".txt");
ContentReader reader = new FileContentReader(msgSourceFile);
reader.setMimetype(MimetypeMap.MIMETYPE_OUTLOOK_MSG);
ContentWriter writer = new FileContentWriter(txtTargetFile);
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
transformer.transform(reader, writer);
ContentReader reader2 = new FileContentReader(txtTargetFile);
reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
assertTrue(reader2.getContentString().contains(QUICK_CONTENT));
}
/**
* Test transforming a valid unicode msg file to text
*/
public void testUnicodeMsgToText() throws Exception
{
File msgSourceFile = loadQuickTestFile("unicode.msg");
File txtTargetFile = TempFileProvider.createTempFile(getName() + "-target-2", ".txt");
ContentReader reader = new FileContentReader(msgSourceFile);
reader.setMimetype(MimetypeMap.MIMETYPE_OUTLOOK_MSG);
ContentWriter writer = new FileContentWriter(txtTargetFile);
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
transformer.transform(reader, writer);
ContentReader reader2 = new FileContentReader(txtTargetFile);
reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
assertTrue(reader2.getContentString().contains(QUICK_CONTENT));
}
/**
* Test transforming a chinese non-unicode msg file to
* text
*/
public void testNonUnicodeChineseMsgToText() throws Exception
{
File msgSourceFile = loadQuickTestFile("chinese.msg");
File txtTargetFile = TempFileProvider.createTempFile(getName() + "-target-2", ".txt");
ContentReader reader = new FileContentReader(msgSourceFile);
reader.setMimetype(MimetypeMap.MIMETYPE_OUTLOOK_MSG);
ContentWriter writer = new FileContentWriter(txtTargetFile);
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
transformer.transform(reader, writer);
ContentReader reader2 = new FileContentReader(txtTargetFile);
reader2.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
// Check the quick text
String text = reader2.getContentString();
assertTrue(text.contains(QUICK_CONTENT));
// Now check the non quick parts came out ok
assertTrue(text.contains("(\u5f35\u6bd3\u502b)"));
assertTrue(text.contains("\u683c\u5f0f\u6e2c\u8a66 )"));
}
}

View File

@@ -1,129 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.filestore.FileContentReader;
import org.alfresco.repo.content.filestore.FileContentWriter;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.alfresco.util.TempFileProvider;
/**
* @see org.alfresco.repo.content.transform.MediaWikiContentTransformer
*
* @author Roy Wetherall
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class MediaWikiContentTransformerTest extends AbstractContentTransformerTest
{
private MediaWikiContentTransformer transformer;
private static final String WIKI_TEXT =
"== This is a title ==\n" +
"\n" +
"'''This is bold''' and some ''italics on the same line''\n" +
"\n" +
"Here is a link to the main page .... [[Main Page]]\n" +
"\n" +
"*and\n" +
"*what\n" +
"*about\n" +
"*a list\n" +
"\n" +
" Some indented text that should apear different\n" +
"\n" +
"What about an external link [http://www.alfresco.com Alfresco]\n" +
"\n" +
"<nowiki>This markup should be ignored [[Main Page]]</nowiki>\n" +
"\n" +
"----\n" +
"\n" +
"Lets put some text at the end :)\n";
@Override
public void setUp() throws Exception
{
super.setUp();
transformer = new MediaWikiContentTransformer();
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
}
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
public void testSetUp() throws Exception
{
assertNotNull(transformer);
}
public void testIsTransformable() throws Exception
{
// check reliability
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_MEDIAWIKI, -1, MimetypeMap.MIMETYPE_HTML, new TransformationOptions()));
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_HTML, -1, MimetypeMap.MIMETYPE_TEXT_MEDIAWIKI, new TransformationOptions()));
}
public void testMediaWikiToHTML() throws Exception
{
File input = TempFileProvider.createTempFile("mediaWikiTest", ".mw");
FileOutputStream fos = new FileOutputStream(input);
fos.write(WIKI_TEXT.getBytes());
fos.close();
File output = TempFileProvider.createTempFile("mediaWikiTest", ".htm");
ContentReader contentReader = new FileContentReader(input);
contentReader.setMimetype(MimetypeMap.MIMETYPE_TEXT_MEDIAWIKI);
contentReader.setEncoding("UTF-8");
ContentWriter contentWriter = new FileContentWriter(output);
contentWriter.setMimetype(MimetypeMap.MIMETYPE_HTML);
contentWriter.setEncoding("UTF-8");
transformer.transform(contentReader, contentWriter);
String line = null;
BufferedReader reader = new BufferedReader(new FileReader(output));
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
}
}

View File

@@ -1,73 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.service.cmr.repository.TransformationOptions;
/**
* Test case for {@link OOXMLThumbnailContentTransformer} content transformer.
*
* @author Nick Burch
* @since 4.0.1
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class OOXMLThumbnailContentTransformerTest extends AbstractContentTransformerTest
{
private ContentTransformer transformer;
@Override
public void setUp() throws Exception
{
super.setUp();
transformer = new OOXMLThumbnailContentTransformer();
// Ugly cast just to set the MimetypeService
((ContentTransformerHelper)transformer).setMimetypeService(mimetypeService);
}
@Override
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
public void testIsTransformable() throws Exception
{
// Does support Thumbnails
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_OPENXML_SPREADSHEET, MimetypeMap.MIMETYPE_IMAGE_JPEG, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_OPENXML_PRESENTATION, MimetypeMap.MIMETYPE_IMAGE_JPEG, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_OPENXML_WORDPROCESSING, MimetypeMap.MIMETYPE_IMAGE_JPEG, new TransformationOptions()));
// Unlike iWorks, it doesn't handle PDF previews
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_OPENXML_SPREADSHEET, MimetypeMap.MIMETYPE_PDF, new TransformationOptions()));
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_OPENXML_PRESENTATION, MimetypeMap.MIMETYPE_PDF, new TransformationOptions()));
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_OPENXML_WORDPROCESSING, MimetypeMap.MIMETYPE_PDF, new TransformationOptions()));
}
}

View File

@@ -1,202 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import java.io.File;
import java.net.URL;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.filestore.FileContentReader;
import org.alfresco.repo.content.filestore.FileContentWriter;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.alfresco.util.TempFileProvider;
import org.junit.Ignore;
/**
* We no longer use ooo.direct in Community. This test class now is connnected up to the JODConverter which was moved
* from the Enterprise Edition.
*
* @author Derek Hulley
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class OpenOfficeContentTransformerTest extends AbstractContentTransformerTest
{
private static String MIMETYPE_RUBBISH = "text/rubbish";
private ContentTransformerWorker worker;
private ProxyContentTransformer transformer;
@Override
public void setUp() throws Exception
{
super.setUp();
this.worker = (ContentTransformerWorker) ctx.getBean("transformer.worker.JodConverter");
RemoteTransformerClient remoteTransformerClient = new RemoteTransformerClient("miscRemoteTransformerClient", "http://localhost:8090/");
worker.setRemoteTransformerClient(remoteTransformerClient);
transformer = new ProxyContentTransformer();
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
transformer.setWorker(this.worker);
}
/**
* @return Returns the same transformer regardless - it is allowed
*/
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
public void testSetUp() throws Exception
{
super.testSetUp();
assertNotNull(mimetypeService);
}
public void testReliability() throws Exception
{
if (!isOpenOfficeWorkerAvailable())
{
// no connection
System.err.println("ooWorker not available - skipping testReliability !!");
return;
}
boolean reliability = transformer.isTransformable(MIMETYPE_RUBBISH, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions());
assertEquals("Mimetype should not be supported", false, reliability);
reliability = transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MIMETYPE_RUBBISH, new TransformationOptions());
assertEquals("Mimetype should not be supported", false, reliability);
reliability = transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_XHTML, new TransformationOptions());
assertEquals("Mimetype should not be supported", false, reliability);
reliability = transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_WORD, new TransformationOptions());
assertEquals("Mimetype should be supported", true, reliability);
reliability = transformer.isTransformable(MimetypeMap.MIMETYPE_WORD, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions());
assertEquals("Mimetype should be supported", true, reliability);
}
/**
* Test what is up with HTML to PDF
*/
public void testHtmlToPdf() throws Exception
{
if (!isOpenOfficeWorkerAvailable())
{
// no connection
System.err.println("ooWorker not available - skipping testHtmlToPdf !!");
return;
}
File htmlSourceFile = loadQuickTestFile("html");
File pdfTargetFile = TempFileProvider.createTempFile(getName() + "-target-", ".pdf");
ContentReader reader = new FileContentReader(htmlSourceFile);
reader.setMimetype(MimetypeMap.MIMETYPE_HTML);
ContentWriter writer = new FileContentWriter(pdfTargetFile);
writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
transformer.transform(reader, writer);
}
/**
* ALF-219. Transforamtion from .html to .pdf for empty file.
* @throws Exception
*/
// The test was never run and fails on remote transformer
public void ignoreTestEmptyHtmlToEmptyPdf() throws Exception
{
if (!isOpenOfficeWorkerAvailable())
{
// no connection
System.err.println("ooWorker not available - skipping testEmptyHtmlToEmptyPdf !!");
return;
}
URL url = this.getClass().getClassLoader().getResource("misc/empty.html");
assertNotNull("URL was unexpectedly null", url);
File htmlSourceFile = new File(url.getFile());
assertTrue("Test file does not exist.", htmlSourceFile.exists());
File pdfTargetFile = TempFileProvider.createTempFile(getName() + "-target-", ".pdf");
ContentReader reader = new FileContentReader(htmlSourceFile);
reader.setMimetype(MimetypeMap.MIMETYPE_HTML);
ContentWriter writer = new FileContentWriter(pdfTargetFile);
writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
transformer.transform(reader, writer);
}
/**
* Some transformations fail intermittently within OOo on our test server.
* Rather than exclude these transformations from product code, where they
* may work (e.g. due to different OOo version installed), they are excluded
* from this test.
*/
@Override
protected boolean isTransformationExcluded(String sourceExtension, String targetExtension)
{
return ((sourceExtension.equals("doc") && targetExtension.equals("docx")) ||
(sourceExtension.equals("doc") && targetExtension.equals("html")) ||
(sourceExtension.equals("doc") && targetExtension.equals("odt")) ||
(sourceExtension.equals("doc") && targetExtension.equals("rtf")) ||
(sourceExtension.equals("doc") && targetExtension.equals("sxw")) ||
(sourceExtension.equals("doc") && targetExtension.equals("txt")) ||
(sourceExtension.equals("docx") && targetExtension.equals("sxw")) ||
(sourceExtension.equals("html") && targetExtension.equals("docx")) ||
(sourceExtension.equals("odp") && targetExtension.equals("pptx")) ||
(sourceExtension.equals("ods") && targetExtension.equals("html")) ||
(sourceExtension.equals("ods") && targetExtension.equals("sxc")) ||
(sourceExtension.equals("ods") && targetExtension.equals("xlsx")) ||
(sourceExtension.equals("ods") && targetExtension.equals("xls")) ||
(sourceExtension.equals("odt") && targetExtension.equals("docx")) ||
(sourceExtension.equals("odt") && targetExtension.equals("txt")) ||
(sourceExtension.equals("ppt") && targetExtension.equals("html")) ||
(sourceExtension.equals("ppt") && targetExtension.equals("pptx")) ||
(sourceExtension.equals("sxc") && targetExtension.equals("xlsx")) ||
(sourceExtension.equals("sxi") && targetExtension.equals("odp")) ||
(sourceExtension.equals("sxi") && targetExtension.equals("pptx")) ||
(sourceExtension.equals("sxw") && targetExtension.equals("docx")) ||
(sourceExtension.equals("txt") && targetExtension.equals("docx")) ||
(sourceExtension.equals("txt") && targetExtension.equals("html")) ||
(sourceExtension.equals("txt") && targetExtension.equals("odt")) ||
(sourceExtension.equals("txt") && targetExtension.equals("pdf")) ||
(sourceExtension.equals("txt") && targetExtension.equals("rtf")) ||
(sourceExtension.equals("txt") && targetExtension.equals("sxw")) ||
(sourceExtension.equals("wpd") && targetExtension.equals("docx")) ||
(sourceExtension.equals("xls") && targetExtension.equals("ods")) ||
(sourceExtension.equals("xls") && targetExtension.equals("pdf")) ||
(sourceExtension.equals("xls") && targetExtension.equals("sxc")) ||
(sourceExtension.equals("xls") && targetExtension.equals("xlsx")) ||
(sourceExtension.equals("txt") && targetExtension.equals("doc")) ||
(sourceExtension.equals("pptx") && targetExtension.equals("html")));
}
}

View File

@@ -1,170 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.filestore.FileContentReader;
import org.alfresco.repo.content.filestore.FileContentWriter;
import org.alfresco.repo.content.metadata.MediaTypeDisablingDocumentSelector;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.alfresco.util.TempFileProvider;
/**
* @see org.alfresco.repo.content.transform.PdfBoxContentTransformer
*
* @author Derek Hulley
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class PdfBoxContentTransformerTest extends AbstractContentTransformerTest
{
private PdfBoxContentTransformer transformer;
@Override
public void setUp() throws Exception
{
super.setUp();
transformer = new PdfBoxContentTransformer();
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
// Disable parsing of embedded images
MediaTypeDisablingDocumentSelector selector = new MediaTypeDisablingDocumentSelector();
selector.setDisabledMediaTypes(Arrays.asList(
MimetypeMap.MIMETYPE_IMAGE_JPEG,
MimetypeMap.MIMETYPE_IMAGE_TIFF,
MimetypeMap.MIMETYPE_IMAGE_PNG));
transformer.setDocumentSelector(selector);
transformer.afterPropertiesSet();
}
/**
* @return Returns the same transformer regardless - it is allowed
*/
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
public void testIsTransformable() throws Exception
{
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_PDF, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_PDF, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_PDF, -1, MimetypeMap.MIMETYPE_HTML, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_PDF, -1, MimetypeMap.MIMETYPE_XML, new TransformationOptions()));
}
/**
* Added to test a single transform that appeared to have problems.
* Commented out once issue was fixed, but left in the code to help with
* future issues.
* @throws Exception
*/
public void testPdfToTextConversions() throws Exception
{
final String sourceMimetype = MimetypeMap.MIMETYPE_PDF;
final String targetMimetype = MimetypeMap.MIMETYPE_TEXT_PLAIN;
int transforms = 100;
final String filename = "svn-book.pdf";
final CountDownLatch doneSignal = new CountDownLatch(transforms);
int threadCount = 8;
final ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
long time = System.currentTimeMillis();
for (int i=0; i<transforms; i++)
{
threadPool.submit(new Runnable() {
public void run()
{
try
{
pdfToTextTransform(filename, sourceMimetype, targetMimetype);
doneSignal.countDown();
}
catch (IOException e)
{
threadPool.shutdown();
e.printStackTrace();
}
}});
if (i < threadCount)
{
Thread.sleep(1000);
}
}
boolean okay = doneSignal.await(100, TimeUnit.SECONDS);
time = System.currentTimeMillis() - time;
transforms = transforms - (int)doneSignal.getCount();
String message = "Total time "+time+" ms "+(transforms > 0 ? "average="+(time/transforms)+" ms" : "")+" threads="+threadCount+" transforms="+transforms;
System.out.println(message);
if (!okay)
{
// Before the changes to PDFBox, this would fail having only done about 50 transforms.
// After the change, this takes about 55 seconds
fail("********** Transforms did not finish ********** "+message);
}
}
private void pdfToTextTransform(String filename, String sourceMimetype, String targetMimetype) throws IOException
{
ContentWriter targetWriter = null;
String sourceExtension = filename.substring(filename.lastIndexOf('.') + 1);
String targetExtension = mimetypeService.getExtension(targetMimetype);
File sourceFile = AbstractContentTransformerTest.loadNamedQuickTestFile(filename);
ContentReader sourceReader = new FileContentReader(sourceFile);
AbstractContentTransformer2 transformer = (AbstractContentTransformer2) getTransformer(
sourceMimetype, targetMimetype);
// make a writer for the target file
File targetFile = TempFileProvider.createTempFile(getClass().getSimpleName() + "_"
+ getName() + "_" + sourceExtension + "_", "." + targetExtension);
targetWriter = new FileContentWriter(targetFile);
// do the transformation
sourceReader.setMimetype(sourceMimetype);
targetWriter.setMimetype(targetMimetype);
transformer.transform(sourceReader.getReader(), targetWriter);
}
}

View File

@@ -1,83 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.service.cmr.repository.TransformationOptions;
/**
* @see org.alfresco.repo.content.transform.PoiContentTransformer
*
* @author Nick Burch
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class PoiContentTransformerTest extends AbstractContentTransformerTest
{
private PoiContentTransformer transformer;
@Override
public void setUp() throws Exception
{
super.setUp();
transformer = new PoiContentTransformer();
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
transformer.afterPropertiesSet();
}
/**
* @return Returns the same transformer regardless - it is allowed
*/
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
public void testIsTransformable() throws Exception
{
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_WORD, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_WORD, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_WORD, -1, MimetypeMap.MIMETYPE_HTML, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_WORD, -1, MimetypeMap.MIMETYPE_XML, new TransformationOptions()));
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_PPT, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_PPT, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_PPT, -1, MimetypeMap.MIMETYPE_HTML, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_PPT, -1, MimetypeMap.MIMETYPE_XML, new TransformationOptions()));
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_OUTLOOK_MSG, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_OUTLOOK_MSG, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_OUTLOOK_MSG, -1, MimetypeMap.MIMETYPE_HTML, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_OUTLOOK_MSG, -1, MimetypeMap.MIMETYPE_XML, new TransformationOptions()));
// Doesn't claim excel
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_EXCEL, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
}
}

View File

@@ -1,185 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import java.io.File;
import java.io.InputStream;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.filestore.FileContentReader;
import org.alfresco.repo.content.filestore.FileContentWriter;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.alfresco.util.TempFileProvider;
/**
* @see org.alfresco.repo.content.transform.PoiHssfContentTransformer
*
* @author Derek Hulley
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class PoiHssfContentTransformerTest extends TikaPoweredContentTransformerTest
{
private PoiHssfContentTransformer transformer;
@Override
public void setUp() throws Exception
{
super.setUp();
transformer = new PoiHssfContentTransformer();
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
transformer.afterPropertiesSet();
}
@Override
protected String[] getQuickFilenames(String sourceMimetype) {
return new String[] {
"quick.xls", "quick.xlsx"
};
}
/**
* @return Returns the same transformer regardless - it is allowed
*/
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
public void testIsTransformable() throws Exception
{
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_EXCEL, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_EXCEL, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_EXCEL, -1, MimetypeMap.MIMETYPE_TEXT_CSV, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_EXCEL, -1, MimetypeMap.MIMETYPE_HTML, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_EXCEL, -1, MimetypeMap.MIMETYPE_XML, new TransformationOptions()));
}
public void testCsvOutput() throws Exception
{
File sourceFile = AbstractContentTransformerTest.loadQuickTestFile("xls");
ContentReader sourceReader = new FileContentReader(sourceFile);
File targetFile = TempFileProvider.createTempFile(
getClass().getSimpleName() + "_" + getName() + "_xls_",
".csv");
ContentWriter targetWriter = new FileContentWriter(targetFile);
sourceReader.setMimetype(MimetypeMap.MIMETYPE_EXCEL);
targetWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_CSV);
transformer.transform(sourceReader, targetWriter);
ContentReader targetReader = targetWriter.getReader();
String checkContent = targetReader.getContentString();
additionalContentCheck(
MimetypeMap.MIMETYPE_EXCEL,
MimetypeMap.MIMETYPE_TEXT_CSV,
checkContent
);
}
@Override
protected void additionalContentCheck(String sourceMimetype,
String targetMimetype, String contents) {
if(targetMimetype.equals(MimetypeMap.MIMETYPE_TEXT_CSV)) {
assertTrue(
"Content not properly CSV'd",
contents.contains("1,2,2")
);
assertTrue(
"Content not properly CSV'd",
contents.contains("\"The\",\"quick\",\"brown\",\"fox\"")
);
} else if(targetMimetype.equals(MimetypeMap.MIMETYPE_XML)) {
// First check we got the usual bits
super.additionalContentCheck(sourceMimetype, targetMimetype, contents);
// Now check tables came out correctly
assertTrue(
"Content lacks XHTML table tags:\n" + contents,
contents.contains("<table>")
);
assertTrue(
"Content lacks XHTML table tags:\n" + contents,
contents.contains("<tr>")
);
assertTrue(
"Content lacks XHTML table tags:\n" + contents,
contents.contains("<td>1</td>")
);
assertTrue(
"Content lacks XHTML table tags:\n" + contents,
contents.contains("<td>The</td>")
);
} else {
super.additionalContentCheck(sourceMimetype, targetMimetype, contents);
}
}
@Override
protected boolean isQuickPhraseExpected(String targetMimetype) {
if(targetMimetype.equals(MimetypeMap.MIMETYPE_TEXT_CSV)) {
return true;
}
return super.isQuickPhraseExpected(targetMimetype);
}
/**
* Tests a specific failure in the library
*/
public void xxtestBugFixAR114() throws Exception
{
File tempFile = TempFileProvider.createTempFile(
getClass().getSimpleName() + "_" + getName() + "_",
".xls");
FileContentWriter writer = new FileContentWriter(tempFile);
writer.setMimetype(MimetypeMap.MIMETYPE_EXCEL);
// get the test resource and write it (Excel)
InputStream is = getClass().getClassLoader().getResourceAsStream("Plan270904b.xls");
assertNotNull("Test resource not found: Plan270904b.xls");
writer.putContent(is);
// get the source of the transformation
ContentReader reader = writer.getReader();
// make a new location of the transform output (plain text)
tempFile = TempFileProvider.createTempFile(
getClass().getSimpleName() + "_" + getName() + "_",
".txt");
writer = new FileContentWriter(tempFile);
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
// transform it
transformer.transform(reader, writer);
}
}

View File

@@ -1,195 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import java.io.File;
import java.util.concurrent.TimeoutException;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.filestore.FileContentReader;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.service.cmr.repository.ContentIOException;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentService;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.TransformationOptionLimits;
import org.alfresco.service.cmr.repository.TransformationOptions;
/**
* @see org.alfresco.repo.content.transform.PoiOOXMLContentTransformer
*
* @author Nick Burch
* @author Dmitry Velichkevich
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class PoiOOXMLContentTransformerTest extends AbstractContentTransformerTest
{
private static final int SMALL_TIMEOUT = 30;
private static final int ADDITIONAL_PROCESSING_TIME = 1500;
private static final String ENCODING_UTF_8 = "UTF-8";
private static final String TEST_PPTX_FILE_NAME = "quickImg2.pptx";
private ContentService contentService;
private PoiOOXMLContentTransformer transformer;
@Override
public void setUp() throws Exception
{
super.setUp();
transformer = new PoiOOXMLContentTransformer();
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
transformer.afterPropertiesSet();
contentService = serviceRegistry.getContentService();
}
/**
* @return Returns the same transformer regardless - it is allowed
*/
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
public void testIsTransformable() throws Exception
{
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_OPENXML_WORDPROCESSING, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_OPENXML_WORDPROCESSING, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_OPENXML_WORDPROCESSING, -1, MimetypeMap.MIMETYPE_HTML, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_OPENXML_WORDPROCESSING, -1, MimetypeMap.MIMETYPE_XML, new TransformationOptions()));
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_OPENXML_PRESENTATION, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_OPENXML_PRESENTATION, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_OPENXML_PRESENTATION, -1, MimetypeMap.MIMETYPE_HTML, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_OPENXML_PRESENTATION, -1, MimetypeMap.MIMETYPE_XML, new TransformationOptions()));
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_OPENXML_SPREADSHEET, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_OPENXML_SPREADSHEET, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_OPENXML_SPREADSHEET, -1, MimetypeMap.MIMETYPE_HTML, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_OPENXML_SPREADSHEET, -1, MimetypeMap.MIMETYPE_XML, new TransformationOptions()));
}
/**
* MNT-12043: CLONE - Upload of PPTX causes very high memory usage leading to system instability
*
* @throws Exception
*/
public void testMnt12043() throws Exception
{
transformer.setMimetypeService(mimetypeService);
transformer.setAdditionalThreadTimout(0);
configureExtractorLimits(transformer, SMALL_TIMEOUT);
File sourceFile = AbstractContentTransformerTest.loadNamedQuickTestFile(TEST_PPTX_FILE_NAME);
ContentReader sourceReader = new FileContentReader(sourceFile)
{
@Override
public void setLimits(TransformationOptionLimits limits)
{
// Test without content reader input stream timeout limits
}
};
sourceReader.setMimetype(MimetypeMap.MIMETYPE_OPENXML_PRESENTATION);
ContentWriter tempWriter = AuthenticationUtil.runAs(new RunAsWork<ContentWriter>()
{
@Override
public ContentWriter doWork() throws Exception
{
ContentWriter result = contentService.getTempWriter();
result.setEncoding(ENCODING_UTF_8);
result.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
return result;
}
}, AuthenticationUtil.getAdminUserName());
long startTime = System.currentTimeMillis();
try
{
transformer.transform(sourceReader, tempWriter);
// should not get here unless transform is too fast
long transformationTime = System.currentTimeMillis() - startTime;
fail("Content transformation took " + transformationTime + " ms, but should have failed with a timeout at " + SMALL_TIMEOUT + " ms");
}
catch (ContentIOException e)
{
long transformationTime = System.currentTimeMillis() - startTime;
assertTrue((TimeoutException.class.getName() + " exception is expected as the cause of transformation failure"), e.getCause() instanceof TimeoutException);
// Not sure we can have the following assert as we may have introduced an intermittent test failure. Already seen a time of 1009ms
assertTrue(("Failed content transformation took " + transformationTime + " ms, but should have failed with a timeout at " + SMALL_TIMEOUT + " ms"),
transformationTime <= (SMALL_TIMEOUT + ADDITIONAL_PROCESSING_TIME));
}
assertFalse("Readable channel was not closed after transformation attempt!", sourceReader.isChannelOpen());
assertFalse("Writable channel was not closed after transformation attempt!", tempWriter.isChannelOpen());
}
/**
* Configures timeout for given <code>transformer</code>
*
* @param transformer - {@link PoiOOXMLContentTransformer} instance
* @param timeout - {@link Long} value which specifies timeout for <code>transformer</code>
*/
private void configureExtractorLimits(PoiOOXMLContentTransformer transformer, final long timeout)
{
transformer.setTransformerConfig(new TransformerConfigImpl()
{
@Override
public TransformationOptionLimits getLimits(ContentTransformer transformer, String sourceMimetype, String targetMimetype, String use)
{
TransformationOptionLimits result = new TransformationOptionLimits();
result.setTimeoutMs(timeout);
return result;
}
@Override
public TransformerStatistics getStatistics(ContentTransformer transformer, String sourceMimetype, String targetMimetype, boolean createNew)
{
return transformerConfig.getStatistics(transformer, sourceMimetype, targetMimetype, createNew);
}
@Override
public boolean isSupportedTransformation(ContentTransformer transformer, String sourceMimetype, String targetMimetype, TransformationOptions options)
{
return transformerConfig.isSupportedTransformation(transformer, sourceMimetype, targetMimetype, options);
}
});
}
}

View File

@@ -1,119 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.alfresco.MiscContextTestSuite;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.filestore.FileContentWriter;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.util.BaseAlfrescoTestCase;
import org.alfresco.util.TempFileProvider;
import org.alfresco.util.exec.RuntimeExec;
/**
* @see org.alfresco.repo.content.transform.RuntimeExecutableContentTransformerWorker
*
* @author Derek Hulley
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class RuntimeExecutableContentTransformerTest extends BaseAlfrescoTestCase
{
private ContentTransformer transformer;
@Override
protected void setUpContext() {
// We use a smaller context
ctx = MiscContextTestSuite.getMinimalContext();
}
@Override
protected void setUp() throws Exception
{
super.setUp();
RuntimeExecutableContentTransformerWorker worker = new RuntimeExecutableContentTransformerWorker();
// the command to execute
RuntimeExec transformCommand = new RuntimeExec();
Map<String, String> commandMap = new HashMap<String, String>(5);
commandMap.put("Mac OS X", "mv -f ${source} ${target}");
commandMap.put("Linux", "mv -f ${source} ${target}");
commandMap.put(".*", "cmd /c copy /Y \"${source}\" \"${target}\"");
transformCommand.setCommandMap(commandMap);
transformCommand.setErrorCodes("1, 2");
worker.setTransformCommand(transformCommand);
worker.setMimetypeService(serviceRegistry.getMimetypeService());
// set the explicit transformations
List<ExplictTransformationDetails> explicitTranformations = new ArrayList<ExplictTransformationDetails>(1);
explicitTranformations.add(
new ExplictTransformationDetails(MimetypeMap.MIMETYPE_TEXT_PLAIN, MimetypeMap.MIMETYPE_XML));
worker.setExplicitTransformations(explicitTranformations);
// initialise so that it doesn't score 0
worker.afterPropertiesSet();
TransformerDebug transformerDebug = (TransformerDebug) ctx.getBean("transformerDebug");
TransformerConfig transformerConfig = (TransformerConfig) ctx.getBean("transformerConfig");
ProxyContentTransformer transformer = new ProxyContentTransformer();
transformer.setMimetypeService(serviceRegistry.getMimetypeService());
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
transformer.setWorker(worker);
this.transformer = transformer;
}
public void testCopyCommand() throws Exception
{
String content = "<A><B></B></A>";
// create the source
File sourceFile = TempFileProvider.createTempFile(getName() + "_", ".txt");
ContentWriter tempWriter = new FileContentWriter(sourceFile);
tempWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
tempWriter.putContent(content);
ContentReader reader = tempWriter.getReader();
// create the target
File targetFile = TempFileProvider.createTempFile(getName() + "_", ".xml");
ContentWriter writer = new FileContentWriter(targetFile);
writer.setMimetype(MimetypeMap.MIMETYPE_XML);
// do the transformation
transformer.transform(reader, writer); // no options on the copy
// make sure that the content was copied over
ContentReader checkReader = writer.getReader();
String checkContent = checkReader.getContentString();
assertEquals("Content not copied", content, checkContent);
}
}

View File

@@ -1,193 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Random;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.filestore.FileContentReader;
import org.alfresco.repo.content.filestore.FileContentWriter;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.alfresco.util.TempFileProvider;
/**
* @see org.alfresco.repo.content.transform.StringExtractingContentTransformer
*
* @author Derek Hulley
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class StringExtractingContentTransformerTest extends AbstractContentTransformerTest
{
private static final String SOME_CONTENT;
static
{
// force the content to be encoded in a particular way, independently of the source file encoding
try
{
SOME_CONTENT = new String("azAz10!<21>$%^&*()\t\r\n".getBytes("UTF-8"), "MacDingbat");
}
catch (UnsupportedEncodingException e)
{
throw new AlfrescoRuntimeException("Encoding not recognised", e);
}
}
private StringExtractingContentTransformer transformer;
/** the final destination of transformations */
private ContentWriter targetWriter;
@Override
public void setUp() throws Exception
{
super.setUp();
transformer = new StringExtractingContentTransformer();
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
targetWriter = new FileContentWriter(getTempFile());
targetWriter.setMimetype("text/plain");
targetWriter.setEncoding("UTF-8");
transformer.afterPropertiesSet();
}
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
public void testSetUp() throws Exception
{
assertNotNull(transformer);
}
/**
* @return Returns a new temp file
*/
private File getTempFile()
{
return TempFileProvider.createTempFile(getName(), ".txt");
}
/**
* Writes some content using the mimetype and encoding specified.
*
* @param mimetype String
* @param encoding String
* @return Returns a reader onto the newly written content
*/
private ContentReader writeContent(String mimetype, String encoding)
{
ContentWriter writer = new FileContentWriter(getTempFile());
writer.setMimetype(mimetype);
writer.setEncoding(encoding);
// put content
writer.putContent(SOME_CONTENT);
// return a reader onto the new content
return writer.getReader();
}
public void testDirectTransform() throws Exception
{
ContentReader reader = writeContent("text/plain", "MacDingbat");
// check transformability
assertTrue(transformer.isTransformable(reader.getMimetype(), -1, targetWriter.getMimetype(), new TransformationOptions()));
// transform
transformer.transform(reader, targetWriter);
// get a reader onto the transformed content and check
ContentReader checkReader = targetWriter.getReader();
String checkContent = checkReader.getContentString();
assertEquals("Content check failed", SOME_CONTENT, checkContent);
}
public void testInterTextTransform() throws Exception
{
ContentReader reader = writeContent("text/xml", "MacDingbat");
// check transformability
assertTrue(transformer.isTransformable(reader.getMimetype(), -1, targetWriter.getMimetype(), new TransformationOptions()));
// transform
transformer.transform(reader, targetWriter);
// get a reader onto the transformed content and check
ContentReader checkReader = targetWriter.getReader();
String checkContent = checkReader.getContentString();
assertEquals("Content check failed", SOME_CONTENT, checkContent);
}
/**
* Generate a large file and then transform it using the text extractor.
* We are not creating super-large file (1GB) in order to test the transform
* as it takes too long to create the file in the first place. Rather,
* this test can be used during profiling to ensure that memory is not
* being consumed.
*/
public void testLargeFileStreaming() throws Exception
{
File sourceFile = TempFileProvider.createTempFile(getName(), ".txt");
int chars = 1000000; // a million characters should do the trick
Random random = new Random();
Writer charWriter = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(sourceFile)));
for (int i = 0; i < chars; i++)
{
char next = (char)(random.nextDouble() * 93D + 32D);
charWriter.write(next);
}
charWriter.close();
// get a reader and a writer
ContentReader reader = new FileContentReader(sourceFile);
reader.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
File outputFile = TempFileProvider.createTempFile(getName(), ".txt");
ContentWriter writer = new FileContentWriter(outputFile);
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
// transform
transformer.transform(reader, writer);
// delete files
sourceFile.delete();
outputFile.delete();
}
}

View File

@@ -1,112 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import java.io.File;
import java.io.InputStream;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.filestore.FileContentWriter;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.alfresco.util.TempFileProvider;
/**
* @see org.alfresco.repo.content.transform.TextMiningContentTransformer
* Note - Is actually POI (soon to be Tika), and not the
* old and unsupported Text Mining library!
*
* @author Derek Hulley
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class TextMiningContentTransformerTest extends AbstractContentTransformerTest
{
private TextMiningContentTransformer transformer;
@Override
public void setUp() throws Exception
{
super.setUp();
transformer = new TextMiningContentTransformer();
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
transformer.afterPropertiesSet();
}
/**
* @return Returns the same transformer regardless - it is allowed
*/
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
@Override
protected String[] getQuickFilenames(String sourceMimetype) {
return new String[] {
"quick.doc", "quick95.doc", "quick6.doc"
};
}
public void testIsTransformable() throws Exception
{
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_WORD, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_WORD, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
}
/**
* Tests a specific failure in the library
*/
public void testBugFixAR1() throws Exception
{
File tempFile = TempFileProvider.createTempFile(
getClass().getSimpleName() + "_" + getName() + "_",
".doc");
FileContentWriter writer = new FileContentWriter(tempFile);
writer.setMimetype(MimetypeMap.MIMETYPE_WORD);
// get the test resource and write it (MS Word)
InputStream is = getClass().getClassLoader().getResourceAsStream("farmers_markets_list_2003.doc");
assertNotNull("Test resource not found: farmers_markets_list_2003.doc");
writer.putContent(is);
// get the source of the transformation
ContentReader reader = writer.getReader();
// make a new location of the transform output (plain text)
tempFile = TempFileProvider.createTempFile(
getClass().getSimpleName() + "_" + getName() + "_",
".txt");
writer = new FileContentWriter(tempFile);
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
// transform it
transformer.transform(reader, writer);
}
}

View File

@@ -1,213 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.Charset;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.filestore.FileContentWriter;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.alfresco.util.TempFileProvider;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
/**
* @see org.alfresco.repo.content.transform.TextToPdfContentTransformer
*
* @author Derek Hulley
* @since 2.1.0
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class TextToPdfContentTransformerTest extends AbstractContentTransformerTest
{
private TextToPdfContentTransformer transformer;
@Override
public void setUp() throws Exception
{
super.setUp();
transformer = new TextToPdfContentTransformer();
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
transformer.setStandardFont("Times-Roman");
transformer.setFontSize(20);
transformer.setBeanName("transformer.test"+System.currentTimeMillis()%100000);
transformer.afterPropertiesSet();
}
/**
* @return Returns the same transformer regardless - it is allowed
*/
@Override
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
public void testReliability() throws Exception
{
transformer.setPageLimit(-1);
transformer.register();
boolean reliability = transformer.isTransformable(MimetypeMap.MIMETYPE_PDF, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions());
assertEquals("Mimetype should not be supported", false, reliability);
reliability = transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_PDF, new TransformationOptions());
assertEquals("Mimetype should be supported", true, reliability);
reliability = transformer.isTransformable(MimetypeMap.MIMETYPE_XML, -1, MimetypeMap.MIMETYPE_PDF, new TransformationOptions());
assertEquals("Mimetype should be supported", true, reliability);
}
/**
* Tests that we can produce PDFs from a variety of different
* source encodings.
* TODO Re-enable this test once we've fixed ALF-2534
*/
public void DISABLEDtestUnicodeTextAndEncodings() throws Exception
{
String allAscii = "This is a simple set of text\n" +
"It is all nice and dull\n";
String european = "En français où les choses sont accentués\n" +
"En español, así";
for(String text : new String[] {allAscii, european})
{
for(String encoding : new String[] {"ISO-8859-1", "UTF-8", "UTF-16"})
{
// Newlines etc may be different, so zap them
String checkText = clean(text);
transformTextAndCheck(text, encoding, checkText);
}
}
}
public void testUnlimitedPages() throws Exception
{
transformTextAndCheckPageLength(-1);
}
public void testLimitedTo1Page() throws Exception
{
transformTextAndCheckPageLength(1);
}
public void testLimitedTo2Pages() throws Exception
{
transformTextAndCheckPageLength(2);
}
public void testLimitedTo50Pages() throws Exception
{
transformTextAndCheckPageLength(50);
}
private void transformTextAndCheckPageLength(int pageLimit) throws IOException
{
transformer.setPageLimit(pageLimit);
transformer.register();
int pageLength = 32;
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++)
{
sb.append(i);
sb.append(" I must not talk in class or feed my homework to my cat.\n");
if (i == cutoff)
checkText = sb.toString();
}
sb.append("\nBart\n");
String text = sb.toString();
checkText = (checkText == null) ? clean(text) : clean(checkText);
transformTextAndCheck(text, "UTF-8", checkText);
}
private void transformTextAndCheck(String text, String encoding, String checkText)
throws IOException
{
// Get a reader for the text
ContentReader reader = buildContentReader(text, Charset.forName(encoding));
// And a temp writer
File out = TempFileProvider.createTempFile("AlfrescoTest_", ".pdf");
ContentWriter writer = new FileContentWriter(out);
writer.setMimetype("application/pdf");
// Transform to PDF
transformer.transform(reader, writer);
// Read back in the PDF and check it
PDDocument doc = PDDocument.load(out);
PDFTextStripper textStripper = new PDFTextStripper();
StringWriter textWriter = new StringWriter();
textStripper.writeText(doc, textWriter);
doc.close();
String roundTrip = clean(textWriter.toString());
assertEquals(
"Incorrect text in PDF when starting from text in " + encoding,
checkText, roundTrip
);
}
private String clean(String text)
{
text = text.replaceAll("\\s+\\r", "");
text = text.replaceAll("\\s+\\n", "");
text = text.replaceAll("\\r", "");
text = text.replaceAll("\\n", "");
return text;
}
public void testSetUp() throws Exception
{
transformer.setPageLimit(-1);
transformer.register();
super.testSetUp();
}
public void testAllConversions() throws Exception
{
transformer.setPageLimit(-1);
transformer.register();
super.testAllConversions();
}
}

View File

@@ -1,107 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.apache.tika.config.TikaConfig;
/**
* Most of the work for testing the Tika Auto-Detect transformer
* is automatically done by {@link AbstractContentTransformerTest}
*
* @see org.alfresco.repo.content.transform.TikaAutoContentTransformer
*
* @author Nick Burch
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class TikaAutoContentTransformerTest extends TikaPoweredContentTransformerTest
{
private TikaAutoContentTransformer transformer;
@Override
public void setUp() throws Exception
{
super.setUp();
TikaConfig config = (TikaConfig)ctx.getBean("tikaConfig");
transformer = new TikaAutoContentTransformer( config );
transformer.setMimetypeService(mimetypeService);
transformer.setTransformerDebug(transformerDebug);
transformer.setTransformerConfig(transformerConfig);
transformer.afterPropertiesSet();
}
/**
* @return Returns the same transformer regardless - it is allowed
*/
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
/**
* Ensure we picked up a mixture of content
* types from Tika
*/
public void testIsTransformable() throws Exception
{
// Excel (but this isn't normally used)
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_EXCEL, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_EXCEL, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_EXCEL, -1, MimetypeMap.MIMETYPE_HTML, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_EXCEL, -1, MimetypeMap.MIMETYPE_XML, new TransformationOptions()));
// Word
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_WORD, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_WORD, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_WORD, -1, MimetypeMap.MIMETYPE_HTML, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_WORD, -1, MimetypeMap.MIMETYPE_XML, new TransformationOptions()));
// PDF
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_PDF, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_PDF, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_PDF, -1, MimetypeMap.MIMETYPE_HTML, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_PDF, -1, MimetypeMap.MIMETYPE_XML, new TransformationOptions()));
// Open Office
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_TEXT_PLAIN, -1, MimetypeMap.MIMETYPE_OPENDOCUMENT_PRESENTATION, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_OPENDOCUMENT_PRESENTATION, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_OPENDOCUMENT_PRESENTATION, -1, MimetypeMap.MIMETYPE_HTML, new TransformationOptions()));
assertTrue(transformer.isTransformable(MimetypeMap.MIMETYPE_OPENDOCUMENT_PRESENTATION, -1, MimetypeMap.MIMETYPE_XML, new TransformationOptions()));
// We don't do images
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_IMAGE_JPEG, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_IMAGE_JPEG, -1, MimetypeMap.MIMETYPE_HTML, new TransformationOptions()));
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_IMAGE_JPEG, -1, MimetypeMap.MIMETYPE_XML, new TransformationOptions()));
// Ditto music
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_MP3, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions()));
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_MP3, -1, MimetypeMap.MIMETYPE_HTML, new TransformationOptions()));
assertFalse(transformer.isTransformable(MimetypeMap.MIMETYPE_MP3, -1, MimetypeMap.MIMETYPE_XML, new TransformationOptions()));
}
}

View File

@@ -1,115 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import org.alfresco.repo.content.MimetypeMap;
/**
* Parent test for Tika powered transformer tests
*
* @author Nick Burch
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public abstract class TikaPoweredContentTransformerTest extends AbstractContentTransformerTest
{
protected boolean isQuickPhraseExpected(String targetMimetype)
{
return (
targetMimetype.equals(MimetypeMap.MIMETYPE_TEXT_PLAIN) ||
targetMimetype.equals(MimetypeMap.MIMETYPE_HTML) ||
targetMimetype.equals(MimetypeMap.MIMETYPE_XML)
);
}
protected boolean isQuickWordsExpected(String targetMimetype)
{
return (
targetMimetype.startsWith(StringExtractingContentTransformer.PREFIX_TEXT) ||
targetMimetype.equals(MimetypeMap.MIMETYPE_HTML) ||
targetMimetype.equals(MimetypeMap.MIMETYPE_XML)
);
}
/**
* Tests for html vs xml vs plain text
*/
protected void additionalContentCheck(String sourceMimetype, String targetMimetype, String contents)
{
if(targetMimetype.equals(MimetypeMap.MIMETYPE_XML))
{
// Look for header and footer to confirm it was translated
assertTrue(
"XML header not found",
contents.contains("<?xml version=")
);
assertTrue(
"XHTML header not found",
contents.contains("<html")
);
assertTrue(
"XHTML footer not found",
contents.contains("</html>")
);
}
else if(targetMimetype.equals(MimetypeMap.MIMETYPE_HTML))
{
// Look for header and footer to confirm it was translated
assertFalse(
"XML header found but shouldn't be there for HTML",
contents.contains("<?xml version=")
);
assertTrue(
"HTML header not found",
contents.contains("<html")
);
assertTrue(
"HTML footer not found",
contents.contains("</html>")
);
assertTrue(
"Expanded HTML title not found",
contents.contains("</title>")
);
}
else if(targetMimetype.equals(MimetypeMap.MIMETYPE_TEXT_PLAIN))
{
// Ensure it really is plain text not xml/html
assertFalse(
"XML header found but shouldn't be there for Plain Text",
contents.contains("<?xml version=")
);
assertFalse(
"XHTML header found but shouldn't be there for Plain Text",
contents.contains("<html")
);
assertFalse(
"XHTML footer found but shouldn't be there for Plain Text",
contents.contains("</html>")
);
}
}
}

View File

@@ -1,488 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import static org.alfresco.repo.content.transform.TransformerPropertyNameExtractorTest.mockMimetypes;
import static org.alfresco.repo.content.transform.TransformerPropertyNameExtractorTest.mockProperties;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import java.util.Properties;
import org.alfresco.repo.rendition2.LegacySynchronousTransformClient;
import org.alfresco.service.cmr.module.ModuleDetails;
import org.alfresco.service.cmr.module.ModuleService;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.alfresco.service.descriptor.Descriptor;
import org.alfresco.service.descriptor.DescriptorService;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/**
* Tests the TransformerConfigDynamicTransformers class.
*
* @author Alan Davis
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class TransformerConfigDynamicTransformersTest
{
@Mock
private TransformerConfig transformerConfig;
@Mock
private TransformerProperties transformerProperties;
@Mock
private MimetypeService mimetypeService;
@Mock
private LegacySynchronousTransformClient legacySynchronousTransformClient;
@Mock
private LegacyTransformerDebug transformerDebug;
@Mock
ModuleService moduleService;
@Mock
ModuleDetails moduleDetails;
@Mock
DescriptorService descriptorService;
@Mock
Descriptor descriptor;
ContentTransformerRegistry transformerRegistry;
private ContentTransformer transformer1;
private ContentTransformer transformer2;
private ContentTransformer transformer3;
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
transformer1 = new DummyContentTransformer("transformer.transformer1");
transformer2 = new DummyContentTransformer("transformer.transformer2");
transformer3 = new DummyContentTransformer("transformer.transformer3");
transformerRegistry = new ContentTransformerRegistry(null);
transformerRegistry.addComponentTransformer(transformer1);
transformerRegistry.addComponentTransformer(transformer2);
transformerRegistry.addComponentTransformer(transformer3);
mockMimetypes(mimetypeService,
"application/pdf", "pdf",
"image/png", "png",
"text/plain", "txt");
assertEquals(3, transformerRegistry.getAllTransformers().size());
assertEquals(0, transformerRegistry.getTransformers().size());
}
@Test
// Simple pipeline
public void pipelineTest()
{
mockProperties(transformerProperties,
"content.transformer.transformerA.pipeline", "transformer1|pdf|transformer2|png|transformer3");
assertEquals(0, new TransformerConfigDynamicTransformers(transformerConfig, transformerProperties, mimetypeService, legacySynchronousTransformClient,
transformerRegistry, transformerDebug, null, null, null).getErrorCount());
assertEquals(4, transformerRegistry.getAllTransformers().size());
assertEquals(1, transformerRegistry.getTransformers().size());
// Throws an exception if it does not exist
ContentTransformer trans = transformerRegistry.getTransformer("transformer.transformerA");
// Check the pipeline
ComplexContentTransformer transformer = (ComplexContentTransformer)trans;
assertEquals(2, transformer.getIntermediateMimetypes().size());
assertEquals("application/pdf", transformer.getIntermediateMimetypes().get(0));
assertEquals("image/png", transformer.getIntermediateMimetypes().get(1));
assertEquals(3, transformer.getIntermediateTransformers().size());
assertEquals("transformer.transformer1", transformer.getIntermediateTransformers().get(0).getName());
assertEquals("transformer.transformer2", transformer.getIntermediateTransformers().get(1).getName());
assertEquals("transformer.transformer3", transformer.getIntermediateTransformers().get(2).getName());
//
transformer.isTransformable("application/pdf", -1, "text/txt", new TransformationOptions());
}
@Test
// Pipeline - too few components in the value
public void pipelineTooFewCompsTest()
{
mockProperties(transformerProperties,
"content.transformer.transformerA.pipeline", "transformer1|pdf");
assertEquals(1, new TransformerConfigDynamicTransformers(transformerConfig, transformerProperties, mimetypeService, legacySynchronousTransformClient,
transformerRegistry, transformerDebug, null, null, null).getErrorCount());
}
@Test
// Pipeline - final transformer is missing
public void pipelineMissingFinalTransformerTest()
{
mockProperties(transformerProperties,
"content.transformer.transformerA.pipeline", "transformer1|pdf|transformer2|png");
assertEquals(1, new TransformerConfigDynamicTransformers(transformerConfig, transformerProperties, mimetypeService, legacySynchronousTransformClient,
transformerRegistry, transformerDebug, null, null, null).getErrorCount());
}
@Test
// Pipeline - transformer name is in use
public void pipelineTransformerAlreadyExistsTest()
{
mockProperties(transformerProperties,
"content.transformer.transformer3.pipeline", "transformer1|pdf|transformer2");
assertEquals(1, new TransformerConfigDynamicTransformers(transformerConfig, transformerProperties, mimetypeService, legacySynchronousTransformClient,
transformerRegistry, transformerDebug, null, null, null).getErrorCount());
}
@Test
// Pipeline with wildcard mimetype
public void pipelineWildcardMimetypeTest()
{
mockProperties(transformerProperties,
"content.transformer.transformerA.pipeline", "transformer1|*|transformer2|png|transformer3");
new TransformerConfigDynamicTransformers(transformerConfig, transformerProperties, mimetypeService, legacySynchronousTransformClient,
transformerRegistry, transformerDebug, null, null, null);
transformerRegistry.getTransformer("transformer.transformerA");
}
@Test
// Pipeline with wildcard transformer
public void pipelineWildcardTransformerTest()
{
mockProperties(transformerProperties,
"content.transformer.transformerA.pipeline", "transformer1|pdf|*|png|transformer3");
new TransformerConfigDynamicTransformers(transformerConfig, transformerProperties, mimetypeService, legacySynchronousTransformClient,
transformerRegistry, transformerDebug, null, null, null);
transformerRegistry.getTransformer("transformer.transformerA");
}
@Test
// Pipeline with an unknown sub transformer
public void pipelineBadSubtransformerTest()
{
mockProperties(transformerProperties,
"content.transformer.transformerA.pipeline", "unknown1|pdf|unknown2|png|unknown3");
assertEquals(1, new TransformerConfigDynamicTransformers(transformerConfig, transformerProperties, mimetypeService, legacySynchronousTransformClient,
transformerRegistry, transformerDebug, null, null, null).getErrorCount());
}
@Test
// Sets available=false
public void pipelineUnavailableTest()
{
mockProperties(transformerProperties,
"content.transformer.transformerA.pipeline", "transformer1|pdf|transformer2|png|transformer3",
"content.transformer.transformerA.available", "false");
new TransformerConfigDynamicTransformers(transformerConfig, transformerProperties, mimetypeService, legacySynchronousTransformClient,
transformerRegistry, transformerDebug, null, null, null);
assertEquals(4, transformerRegistry.getAllTransformers().size());
assertEquals(0, transformerRegistry.getTransformers().size()); // << note 0 rather than 1
transformerRegistry.getTransformer("transformer.transformerA");
}
// --------------------------------------------------------------
@Test
// Simple failover
public void failoverTest()
{
mockProperties(transformerProperties,
"content.transformer.transformerA.failover", "transformer1|transformer2|transformer3");
assertEquals(0, new TransformerConfigDynamicTransformers(transformerConfig, transformerProperties, mimetypeService, legacySynchronousTransformClient,
transformerRegistry, transformerDebug, null, null, null).getErrorCount());
assertEquals(4, transformerRegistry.getAllTransformers().size());
assertEquals(1, transformerRegistry.getTransformers().size());
// Throws an exception if it does not exist
transformerRegistry.getTransformer("transformer.transformerA");
}
@Test
// Failover - too few components in the value
public void failoverTooFewCompsTest()
{
mockProperties(transformerProperties,
"content.transformer.transformerA.failover", "transformer1");
assertEquals(1, new TransformerConfigDynamicTransformers(transformerConfig, transformerProperties, mimetypeService, legacySynchronousTransformClient,
transformerRegistry, transformerDebug, null, null, null).getErrorCount());
}
@Test
// Failover - transformer name is in use
public void failoverTransformerAlreadyExistsTest()
{
mockProperties(transformerProperties,
"content.transformer.transformer3.failover", "transformer1|transformer2");
assertEquals(1, new TransformerConfigDynamicTransformers(transformerConfig, transformerProperties, mimetypeService, legacySynchronousTransformClient,
transformerRegistry, transformerDebug, null, null, null).getErrorCount());
}
@Test
// Failover with wildcard transformer
public void failoverWildcardTransformerTest()
{
mockProperties(transformerProperties,
"content.transformer.transformerA.failover", "transformer1|*|transformer3");
new TransformerConfigDynamicTransformers(transformerConfig, transformerProperties, mimetypeService, legacySynchronousTransformClient,
transformerRegistry, transformerDebug, null, null, null);
transformerRegistry.getTransformer("transformer.transformerA");
}
@Test
// Failover with an unknown sub transformer
public void failoverBadSubtransformerTest()
{
mockProperties(transformerProperties,
"content.transformer.transformerA.failover", "unknown1|unknown2|unknown3");
assertEquals(1, new TransformerConfigDynamicTransformers(transformerConfig, transformerProperties, mimetypeService, legacySynchronousTransformClient,
transformerRegistry, transformerDebug, null, null, null).getErrorCount());
}
@Test
// Failover sets available=false
public void failoverUnavailableTest()
{
mockProperties(transformerProperties,
"content.transformer.transformerA.failover", "transformer1|transformer2|transformer3",
"content.transformer.transformerA.available", "false");
new TransformerConfigDynamicTransformers(transformerConfig, transformerProperties, mimetypeService, legacySynchronousTransformClient,
transformerRegistry, transformerDebug, null, null, null);
assertEquals(4, transformerRegistry.getAllTransformers().size());
assertEquals(0, transformerRegistry.getTransformers().size()); // << note 0 rather than 1
transformerRegistry.getTransformer("transformer.transformerA");
}
@Test
// Dynamic transformer that references other dynamic transformers
public void referenceDynamicTest()
{
mockProperties(transformerProperties,
"content.transformer.transformerA.failover", "transformer1|transformerB",
"content.transformer.transformerB.failover", "transformer1|transformerC",
"content.transformer.transformerC.failover", "transformer1|transformerD",
"content.transformer.transformerD.failover", "transformer1|transformerE",
"content.transformer.transformerE.failover", "transformer1|transformer1");
new TransformerConfigDynamicTransformers(transformerConfig, transformerProperties, mimetypeService, legacySynchronousTransformClient,
transformerRegistry, transformerDebug, null, null, null);
assertEquals(5, transformerRegistry.getTransformers().size());
transformerRegistry.getTransformer("transformer.transformerA");
}
@Test
// Dynamic transformer that references other dynamic transformers and form a loop
public void referrenceDynamicLoopTest()
{
mockProperties(transformerProperties,
"content.transformer.transformerA.failover", "transformer1|transformerB",
"content.transformer.transformerB.failover", "transformer1|transformer1",
"content.transformer.transformerC.failover", "transformer1|transformerD",
"content.transformer.transformerD.failover", "transformer1|transformerE",
"content.transformer.transformerE.failover", "transformer1|transformerC");
new TransformerConfigDynamicTransformers(transformerConfig, transformerProperties, mimetypeService, legacySynchronousTransformClient,
transformerRegistry, transformerDebug, null, null, null);
assertEquals(2, transformerRegistry.getTransformers().size());
transformerRegistry.getTransformer("transformer.transformerA");
}
private void entrerpriseTransformer(String edition)
{
when(descriptorService.getServerDescriptor()).thenReturn(descriptor);
when(descriptor.getEdition()).thenReturn(edition);
mockProperties(transformerProperties,
"content.transformer.transformerA.failover", "transformer1|transformer2|transformer3",
"content.transformer.transformerA.edition", "Enterprise");
new TransformerConfigDynamicTransformers(transformerConfig, transformerProperties, mimetypeService, legacySynchronousTransformClient,
transformerRegistry, transformerDebug, null, descriptorService, null);
}
private void ampTransformer(String moduleId)
{
when(moduleService.getModule("testAmp")).thenReturn(moduleDetails);
mockProperties(transformerProperties,
"content.transformer.transformerA.failover", "transformer1|transformer2|transformer3",
"content.transformer.transformerA.amp", moduleId);
new TransformerConfigDynamicTransformers(transformerConfig, transformerProperties, mimetypeService, legacySynchronousTransformClient,
transformerRegistry, transformerDebug, moduleService, null, null);
}
@Test
// Test that enterprise transformers are not available to community.
public void communityTest()
{
entrerpriseTransformer("Community");
assertEquals(3, transformerRegistry.getAllTransformers().size());
}
@Test
// Test that enterprise transformers are available to enterprise.
public void enterpriseTest()
{
entrerpriseTransformer("Enterprise");
assertEquals(4, transformerRegistry.getAllTransformers().size());
}
@Test
// Test that enterprise transformers are not available to community.
public void noAmpTest()
{
ampTransformer("AmpNotInstalled");
assertEquals(3, transformerRegistry.getAllTransformers().size());
}
@Test
// Test that enterprise transformers are available to enterprise.
public void ampTest()
{
ampTransformer("testAmp");
assertEquals(4, transformerRegistry.getAllTransformers().size());
}
// for MNT-16381
@Test
public void failoverPropertyFFTest()
{
internalPropertyTest(false, false, false);
}
@Test
public void failoverPropertyFTTest()
{
internalPropertyTest(false, false, true);
}
@Test
public void failoverPropertyTFTest()
{
internalPropertyTest(false, true, false);
}
@Test
public void failoverPropertyTTTest()
{
internalPropertyTest(false, true, true);
}
@Test
public void pipelinePropertyFFTest()
{
internalPropertyTest(true, false, false);
}
@Test
public void pipelinePropertyFTTest()
{
internalPropertyTest(true, false, true);
}
@Test
public void pipelinePropertyTFTest()
{
internalPropertyTest(true, true, false);
}
@Test
public void pipelinePropertyTTTest()
{
internalPropertyTest(true, true, true);
}
private void internalPropertyTest(boolean pipeline, boolean expectedRetry, boolean expectedCheck)
{
String[] transformerNamesAndValues = pipeline
? new String[] {"content.transformer.transformerA.pipeline", "transformer1|pdf|transformer2"}
: new String[] {"content.transformer.transformerA.failover", "transformer1|transformer2|transformer3"};
Properties properties = new Properties();
if (expectedRetry)
{
properties.setProperty("content.transformer.retryOn.different.mimetype", "true");
}
if (expectedCheck)
{
properties.setProperty("transformer.strict.mimetype.check", "true");
}
mockProperties(transformerProperties, transformerNamesAndValues);
assertEquals(0, new TransformerConfigDynamicTransformers(transformerConfig, transformerProperties, mimetypeService, legacySynchronousTransformClient,
transformerRegistry, transformerDebug, null, null, properties).getErrorCount());
// Throws an exception if it does not exist
AbstractContentTransformer2 transformer = (AbstractContentTransformer2)transformerRegistry.getTransformer("transformer.transformerA");
assertEquals("retryTransformOnDifferentMimeType was not set", expectedRetry, transformer.getRetryTransformOnDifferentMimeType());
assertEquals("strictMimetypeCheck was not set", expectedCheck, transformer.getStrictMimeTypeCheck());
}
}

View File

@@ -1,345 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import static org.alfresco.repo.content.transform.TransformerPropertyNameExtractorTest.mockMimetypes;
import static org.alfresco.repo.content.transform.TransformerPropertyNameExtractorTest.mockProperties;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import org.alfresco.repo.management.subsystems.ChildApplicationContextFactory;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.alfresco.service.cmr.repository.TransformationOptionLimits;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.context.ApplicationContext;
/**
* Test class for TransformerConfigImpl. This class generally calls onto
* secondary classes to handle the request, so most test simply check that
* the real method is called.
*
* @author Alan Davis
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class TransformerConfigImplTest
{
@Mock
private ApplicationContext applicationContext;
@Mock
private MimetypeService mimetypeService;
@Mock
private ContentTransformerRegistry transformerRegistry;
@Mock
private TransformerLog transformerLog;
@Mock
private TransformerDebugLog transformerDebugLog;
@Mock
private ChildApplicationContextFactory subsystem;
@Mock
private TransformerProperties transformerProperties;
@Mock
private TransformationOptions options;
@Mock
private
ContentTransformer transformer1;
private TransformerConfigImpl config;
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
Properties globalProperties = new Properties();
config = new TransformerConfigImpl()
{
@Override
synchronized ChildApplicationContextFactory getSubsystem()
{
return subsystem;
}
};
config.setApplicationContext(applicationContext);
config.setMimetypeService(mimetypeService);
config.setContentTransformerRegistry(transformerRegistry);
config.setTransformerLog(transformerLog);
config.setTransformerDebugLog(transformerDebugLog);
config.setGlobalProperties(globalProperties);
mockMimetypes(mimetypeService,
"application/pdf", "pdf",
"image/png", "png");
finishSetup();
}
private void finishSetup()
{
when(transformer1.getName()).thenReturn("transformer.abc");
when(transformerRegistry.getTransformer("transformer.abc")).thenReturn(transformer1);
when(transformer1.getComments(false)).thenReturn("");
config.initialise();
}
/**
* Mock up the responses from the subsystem so that it returns all the supplied
* property names and values.
* @param subsystem to mock the return values
* @param namesAndValues a sequence of property names and values.
* @throws IllegalStateException if there is not a value for every property
*/
public static void mockProperties(ChildApplicationContextFactory subsystem, String... namesAndValues)
{
if (namesAndValues.length % 2 != 0)
{
// Not using IllegalArgumentException as this is thrown by classes under test
throw new java.lang.IllegalStateException("There should be a value for every property");
}
final Set<String> propertyNames = new TreeSet<String>();
for (int i=0; i < namesAndValues.length; i+=2)
{
propertyNames.add(namesAndValues[i]);
when(subsystem.getProperty(namesAndValues[i])).thenReturn(namesAndValues[i+1]);
}
when(subsystem.getPropertyNames()).thenReturn(propertyNames);
}
@Test
public void getPropertyTest()
{
when(subsystem.getProperty("abc")).thenReturn("xyz");
String actual = config.getProperty("abc");
assertEquals("xyz", actual);
}
@Test
public void getPropertiesTest()
{
when(transformerLog.getPropertyName()).thenReturn("transformer.log.entries");
when(transformerDebugLog.getPropertyName()).thenReturn("transformer.debug.entries");
when(transformerLog.getPropertyAndValue(any(Properties.class))).thenReturn("transformer.log.entries=0 # default=50");
when(transformerDebugLog.getPropertyAndValue(any(Properties.class))).thenReturn("# transformer.debug.entries=0");
String actual = config.getProperties(false);
assertEquals("# LOG and DEBUG history sizes\n" +
"# ===========================\n" +
"# Use small values as these logs are held in memory. 0 to disable.\n" +
"transformer.log.entries=0 # default=50\n" +
"# transformer.debug.entries=0\n" +
"\n" +
"# Miscellaneous settings\n" +
"# ======================\n" +
"# transformer.strict.mimetype.check.whitelist.mimetypes=application/eps;application/postscript;application/illustrator;application/pdf;application/x-tar;application/x-gtar;application/acp;application/zip;application/vnd.stardivision.math;application/x-tika-msoffice\n",
actual);
}
@Test
public void setPropertiesTest()
{
config.setProperties("transformer.debug.entries=56\ntransformer.log.entries=76");
Map<String, String> expected = new HashMap<String, String>();
expected.put("transformer.debug.entries", "56");
expected.put("transformer.log.entries", "76");
verify(subsystem).setProperties(expected);
}
@Test
public void removePropertiesTest()
{
mockProperties(subsystem, "content.transformer.abc.extensions.pdf.png.maxPages", "23");
finishSetup();
config.removeProperties("content.transformer.abc.extensions.pdf.png.maxPages");
Set<String> expected = new HashSet<String>();
expected.add("content.transformer.abc.extensions.pdf.png.maxPages");
verify(subsystem).removeProperties(expected);
}
@Test
public void getStatisticsTest()
{
TransformerStatistics actual = config.getStatistics(transformer1, "application/pdf", "image/png", true);
actual.recordTime(100);
actual.recordTime(200);
actual = config.getStatistics(transformer1, "application/pdf", "image/png", false);
assertEquals(150, actual.getAverageTime());
}
@Test
public void getLimitsTest()
{
mockProperties(subsystem, "content.transformer.abc.extensions.pdf.png.maxPages", "23");
finishSetup();
TransformationOptionLimits actual = config.getLimits(transformer1, "application/pdf", "image/png", null);
assertEquals(23, actual.getMaxPages());
}
@Test
public void isSupportedTransformationTest()
{
mockProperties(subsystem, "content.transformer.abc.extensions.pdf.png.suppoprted", "true");
finishSetup();
assertTrue(config.isSupportedTransformation(transformer1, "application/pdf", "image/png", options));
}
@Test
public void getPriorityTest()
{
mockProperties(subsystem,
"content.transformer.default.priority", "22",
"content.transformer.abc.extensions.pdf.png.priority", "67");
finishSetup();
assertEquals(67, config.getPriority(transformer1, "application/pdf", "image/png"));
}
@Test
public void getPriorityBadTest()
{
mockProperties(subsystem,
"content.transformer.default.priority", "22",
"content.transformer.abc.extensions.pdf.png.priority", "bad");
finishSetup();
assertEquals(22, config.getPriority(transformer1, "application/pdf", "image/png"));
}
@Test
public void getThresholdCountTest()
{
mockProperties(subsystem,
"content.transformer.default.thresholdCount", "22",
"content.transformer.abc.extensions.pdf.png.thresholdCount", "67");
finishSetup();
assertEquals(67, config.getThresholdCount(transformer1, "application/pdf", "image/png"));
}
@Test
public void getThresholdCountBadTest()
{
mockProperties(subsystem,
"content.transformer.default.thresholdCount", "22",
"content.transformer.abc.extensions.pdf.png.thresholdCount", "bad");
finishSetup();
assertEquals(22, config.getThresholdCount(transformer1, "application/pdf", "image/png"));
}
@Test
public void getErrorTimeTest()
{
mockProperties(subsystem,
"content.transformer.default.errorTime", "22",
"content.transformer.abc.extensions.pdf.png.errorTime", "67");
finishSetup();
assertEquals(67, config.getErrorTime(transformer1, "application/pdf", "image/png"));
}
@Test
public void getErrorTimeBadTest()
{
mockProperties(subsystem,
"content.transformer.default.errorTime", "22",
"content.transformer.abc.extensions.pdf.png.errorTime", "bad");
finishSetup();
assertEquals(22, config.getErrorTime(transformer1, "application/pdf", "image/png"));
}
@Test
public void getInitialAverageTimeTest()
{
mockProperties(subsystem,
"content.transformer.default.time", "22",
"content.transformer.abc.extensions.pdf.png.time", "67");
finishSetup();
assertEquals(67, config.getInitialAverageTime(transformer1, "application/pdf", "image/png"));
}
@Test
public void getInitialAverageTimeBadTest()
{
mockProperties(subsystem,
"content.transformer.default.time", "22",
"content.transformer.abc.extensions.pdf.png.time", "bad");
finishSetup();
assertEquals(22, config.getInitialAverageTime(transformer1, "application/pdf", "image/png"));
}
@Test
public void getInitialCountTest()
{
mockProperties(subsystem,
"content.transformer.default.count", "22",
"content.transformer.abc.extensions.pdf.png.count", "67");
finishSetup();
assertEquals(67, config.getInitialCount(transformer1, "application/pdf", "image/png"));
}
@Test
public void getInitialCountBadTest()
{
mockProperties(subsystem,
"content.transformer.default.count", "22",
"content.transformer.abc.extensions.pdf.png.count", "bad");
finishSetup();
assertEquals(22, config.getInitialCount(transformer1, "application/pdf", "image/png"));
}
}

View File

@@ -1,412 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import static org.alfresco.repo.content.transform.TransformerPropertyNameExtractorTest.mockMimetypes;
import static org.alfresco.repo.content.transform.TransformerPropertyNameExtractorTest.mockProperties;
import static org.junit.Assert.assertEquals;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.alfresco.service.cmr.repository.TransformationOptionLimits;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/**
* Test class for TransformerConfigLimits.
*
* @author Alan Davis
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class TransformerConfigLimitsTest
{
@Mock
private TransformerProperties transformerProperties;
@Mock
private MimetypeService mimetypeService;
private ContentTransformer transformer1;
private ContentTransformer transformer2;
private TransformerConfigLimits extractor;
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
transformer1 = new DummyContentTransformer("transformer.transformer1");
transformer2 = new DummyContentTransformer("transformer.transformer2");
mockMimetypes(mimetypeService,
"application/pdf", "pdf",
"image/png", "png",
"text/plain", "txt");
}
@Test
// A value is specified for a transformer and mimetypes
public void transformerMimetypesTest()
{
mockProperties(transformerProperties, "content.transformer.transformer1.extensions.pdf.png.maxSourceSizeKBytes", "10");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits limits = extractor.getLimits(transformer1, "application/pdf", "image/png", null);
assertEquals(10, limits.getMaxSourceSizeKBytes());
}
@Test
// A value is specified for a transformer
public void transformerTest()
{
mockProperties(transformerProperties, "content.transformer.transformer1.maxSourceSizeKBytes", "10");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits limits = extractor.getLimits(transformer1, "application/pdf", "image/png", null);
assertEquals(10, limits.getMaxSourceSizeKBytes());
}
@Test
// A value is specified as a transformer default with mimetypes
public void defaultMimetypesTest()
{
mockProperties(transformerProperties, "content.transformer.default.extensions.pdf.png.maxSourceSizeKBytes", "10");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits limits = extractor.getLimits(transformer1, "application/pdf", "image/png", null);
assertEquals(10, limits.getMaxSourceSizeKBytes());
}
@Test
// A value is specified as a transformer default without mimetypes
public void defaultTest()
{
mockProperties(transformerProperties, "content.transformer.default.maxSourceSizeKBytes", "10");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits limits = extractor.getLimits(transformer1, "application/pdf", "image/png", null);
assertEquals(10, limits.getMaxSourceSizeKBytes());
}
// ---------------------------------------
@Test
// Checks that transformer defaults are combined to construct mimetype specific values
public void transformerDefaultsUsedInMimetypesTest()
{
mockProperties(transformerProperties,
"content.transformer.transformer1.extensions.pdf.png.maxSourceSizeKBytes", "10",
"content.transformer.transformer1.timeoutMs", "10000");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits limits = extractor.getLimits(transformer1, "application/pdf", "image/png", null);
assertEquals(10, limits.getMaxSourceSizeKBytes());
assertEquals(10000L, limits.getTimeoutMs());
}
@Test
// Checks that transformer mimetype values override transformer defaults even if unlimited.
// This was new in 4.2. Prior to this they would have been combined, because of the need to
// always specify them in the spring configuration, which was removed in 4.2.
public void dontCombineTest()
{
mockProperties(transformerProperties,
"content.transformer.transformer1.extensions.pdf.png.maxSourceSizeKBytes", "-1",
"content.transformer.transformer1.maxSourceSizeKBytes", "20");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits limits = extractor.getLimits(transformer1, "application/pdf", "image/png", null);
assertEquals(-1, limits.getMaxSourceSizeKBytes());
}
@Test
// Checks that system wide defaults (and system wide mimetype defaults) have been used to construct
// transformer specific values.
public void systemWideDefaultsUsedInTransformersTest()
{
mockProperties(transformerProperties,
"content.transformer.transformer1.extensions.pdf.png.maxSourceSizeKBytes", "10",
"content.transformer.transformer1.maxSourceSizeKBytes", "15",
"content.transformer.default.timeoutMs", "120000",
"content.transformer.default.extensions.txt.png.pageLimit", "1");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits pdfToPngLimits = extractor.getLimits(transformer1, "application/pdf", "image/png", null);
assertEquals(10, pdfToPngLimits.getMaxSourceSizeKBytes());
assertEquals(120000L, pdfToPngLimits.getTimeoutMs());
assertEquals(-1, pdfToPngLimits.getPageLimit());
TransformationOptionLimits txtToPngLimits = extractor.getLimits(transformer1, "text/plain", "image/png", null);
assertEquals(15, txtToPngLimits.getMaxSourceSizeKBytes());
assertEquals(120000L, txtToPngLimits.getTimeoutMs());
assertEquals(1, txtToPngLimits.getPageLimit());
}
@Test
// Checks wildcard usage at the transformer level
public void transformerWildcardTest()
{
mockProperties(transformerProperties,
"content.transformer.transformer1.extensions.*.png.maxSourceSizeKBytes", "10");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits limits = extractor.getLimits(transformer1, "application/pdf", "image/png", null);
assertEquals(10, limits.getMaxSourceSizeKBytes());
}
@Test
// Checks wildcard usage at the system wide level
public void systemWideWildcardTest()
{
mockProperties(transformerProperties,
"content.transformer.transformer1.maxSourceSizeKBytes", "15",
"content.transformer.default.timeoutMs", "120000",
"content.transformer.default.extensions.txt.*.pageLimit", "1");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits txtToPngLimits = extractor.getLimits(transformer1, "text/plain", "image/png", null);
assertEquals(15, txtToPngLimits.getMaxSourceSizeKBytes());
assertEquals(120000L, txtToPngLimits.getTimeoutMs());
assertEquals(1, txtToPngLimits.getPageLimit());
}
// MNT-14295 With Java 7 the order in which properties were supplied changed from
// what happen with Java 6 and happens with 8. When combined with a bug to do with
// always clearing the max value when setting a limit or the limit when setting
// the max value, the initial map of TransformerConfigLimits would be different.
// Java 7 was used as the runtime for 4.2 and the 5.0 but Java 8 became the default
// from 5.0.1.
// None of the other unit tests in this class failed as a none of them provided
// both max and limit values.
@Test
public void propertyOrderJava7Test()
{
mockProperties(transformerProperties,
"content.transformer.default.timeoutMs", "120000",
"content.transformer.default.readLimitTimeMs", "-1");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits limits = extractor.getLimits(transformer1, "text/plain", "image/png", null);
assertEquals(120000L, limits.getTimeoutMs());
assertEquals(-1L, limits.getReadLimitTimeMs());
}
@Test
public void propertyOrderJava8or6Test()
{
mockProperties(transformerProperties,
"content.transformer.default.timeoutMs", "-1",
"content.transformer.default.readLimitTimeMs", "120000");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits limits = extractor.getLimits(transformer1, "text/plain", "image/png", null);
assertEquals(-1L, limits.getTimeoutMs());
assertEquals(120000L, limits.getReadLimitTimeMs());
}
@Test
public void bothMaxAndLimitSetIgnoreLimitTest()
{
mockProperties(transformerProperties,
"content.transformer.default.readLimitTimeMs", "990000",
"content.transformer.default.timeoutMs", "120000");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits limits = extractor.getLimits(transformer1, "text/plain", "image/png", null);
assertEquals(120000L, limits.getTimeoutMs());
assertEquals(-1L, limits.getReadLimitTimeMs());
}
@Test
public void bothMaxAndLimitSetIgnoreMaxTest()
{
mockProperties(transformerProperties,
"content.transformer.default.readLimitTimeMs", "120000",
"content.transformer.default.timeoutMs", "990000");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits limits = extractor.getLimits(transformer1, "text/plain", "image/png", null);
assertEquals(-1L, limits.getTimeoutMs());
assertEquals(120000L, limits.getReadLimitTimeMs());
}
// ---------------------------------------
@Test
// A value is specified for a transformer, mimetypes and use
public void transformerMimetypesUseTest()
{
mockProperties(transformerProperties,
"content.transformer.transformer1.extensions.pdf.png.maxSourceSizeKBytes", "10",
"content.transformer.transformer1.extensions.pdf.png.maxSourceSizeKBytes.use.index", "20");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits limits = extractor.getLimits(transformer1, "application/pdf", "image/png", null);
assertEquals(10, limits.getMaxSourceSizeKBytes());
limits = extractor.getLimits(transformer1, "application/pdf", "image/png", "index");
assertEquals(20, limits.getMaxSourceSizeKBytes());
}
@Test
// A value is specified for a transformer and use
public void transformerUseTest()
{
mockProperties(transformerProperties,
"content.transformer.transformer2.maxSourceSizeKBytes", "10",
"content.transformer.transformer1.maxSourceSizeKBytes.use.index", "20",
// The following is ignored when "index" is specified, as the 'use' property is transformer wide.
"content.transformer.transformer1.maxSourceSizeKBytes", "30");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits limits = extractor.getLimits(transformer1, "application/pdf", "image/png", null);
assertEquals(30, limits.getMaxSourceSizeKBytes());
limits = extractor.getLimits(transformer1, "application/pdf", "image/png", "index");
assertEquals(20, limits.getMaxSourceSizeKBytes());
limits = extractor.getLimits(transformer2, "application/pdf", "image/png", "index");
assertEquals(10, limits.getMaxSourceSizeKBytes());
}
@Test
// A value is specified as a transformer default with mimetypes and use
public void defaultMimetypesUseTest()
{
mockProperties(transformerProperties,
"content.transformer.default.extensions.pdf.png.maxSourceSizeKBytes", "10",
"content.transformer.default.extensions.pdf.png.maxSourceSizeKBytes.use.index", "20",
// The following is ignored when "index" is specified, as the 'use' property is system wide.
"content.transformer.transformer2.maxSourceSizeKBytes", "30");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits limits = extractor.getLimits(transformer1, "application/pdf", "image/png", null);
assertEquals(10, limits.getMaxSourceSizeKBytes());
limits = extractor.getLimits(transformer2, "application/pdf", "image/png", "doclib");
assertEquals(30, limits.getMaxSourceSizeKBytes());
limits = extractor.getLimits(transformer2, "application/pdf", "image/png", "index");
assertEquals(20, limits.getMaxSourceSizeKBytes());
}
@Test
// A value is specified as a transformer default without mimetypes but with a use
public void defaultUseTest()
{
mockProperties(transformerProperties,
"content.transformer.default.maxSourceSizeKBytes", "10",
"content.transformer.default.maxSourceSizeKBytes.use.index", "20");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits limits = extractor.getLimits(transformer1, "application/pdf", "image/png", null);
assertEquals(10, limits.getMaxSourceSizeKBytes());
limits = extractor.getLimits(transformer1, "application/pdf", "image/png", "index");
assertEquals(20, limits.getMaxSourceSizeKBytes());
}
@Test
// A value is specified as a transformer default without mimetypes but with a use
public void defaultUseTest2()
{
mockProperties(transformerProperties,
"content.transformer.default.maxSourceSizeKBytes", "10",
"content.transformer.default.maxSourceSizeKBytes.use.index", "20",
// The following is ignored when "index" is specified, as the 'use' property is system wide.
"content.transformer.transformer2.maxSourceSizeKBytes", "30");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits limits = extractor.getLimits(transformer1, "application/pdf", "image/png", null);
assertEquals(10, limits.getMaxSourceSizeKBytes());
limits = extractor.getLimits(transformer2, "application/pdf", "image/png", null);
assertEquals(30, limits.getMaxSourceSizeKBytes());
limits = extractor.getLimits(transformer1, "application/pdf", "image/png", "index");
assertEquals(20, limits.getMaxSourceSizeKBytes());
limits = extractor.getLimits(transformer2, "application/pdf", "image/png", "index");
assertEquals(20, limits.getMaxSourceSizeKBytes());
}
@Test
// Checks limit does not change if use param is specified but not specifically set
public void useUnsetTest()
{
mockProperties(transformerProperties,
"content.transformer.transformer1.pageLimit", "76");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits transformerDefaultLimits = extractor.getLimits(transformer1, null, null, null);
TransformationOptionLimits transformerDoclibLimits = extractor.getLimits(transformer1, null, null, "doclib");
assertEquals(76, transformerDefaultLimits.getPageLimit());
assertEquals(76, transformerDoclibLimits.getPageLimit());
}
@Test
// Checks limit does not change if use param is specified but not specifically set
public void useSetTest()
{
mockProperties(transformerProperties,
"content.transformer.transformer1.pageLimit.use.doclib", "22",
"content.transformer.transformer1.pageLimit", "76");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits transformerDefaultLimits = extractor.getLimits(transformer1, null, null, null);
TransformationOptionLimits transformerDoclibLimits = extractor.getLimits(transformer1, null, null, "doclib");
assertEquals(76, transformerDefaultLimits.getPageLimit());
assertEquals(22, transformerDoclibLimits.getPageLimit());
}
@Test
// Checks wildcard usage at the system wide level
public void systemWideWildcardUseTest()
{
mockProperties(transformerProperties,
"content.transformer.default.extensions.txt.*.pageLimit", "1",
"content.transformer.default.extensions.txt.*.pageLimit.use.index", "2",
"content.transformer.default.extensions.pdf.*.pageLimit.use.index", "3",
"content.transformer.default.extensions.pdf.txt.pageLimit.use.index", "4");
extractor = new TransformerConfigLimits(transformerProperties, mimetypeService);
TransformationOptionLimits txtToPngLimits = extractor.getLimits(transformer1, "text/plain", "image/png", null);
assertEquals(1, txtToPngLimits.getPageLimit());
txtToPngLimits = extractor.getLimits(transformer1, "text/plain", "image/png", "index");
assertEquals(2, txtToPngLimits.getPageLimit());
TransformationOptionLimits pdfToPngLimits = extractor.getLimits(transformer1, "application/pdf", "image/png", "index");
assertEquals(3, pdfToPngLimits.getPageLimit());
TransformationOptionLimits pdfToTxtLimits = extractor.getLimits(transformer1, "application/pdf", "text/plain", "index");
assertEquals(4, pdfToTxtLimits.getPageLimit());
}
}

View File

@@ -25,44 +25,31 @@
*/
package org.alfresco.repo.content.transform;
import static org.alfresco.repo.content.transform.TransformerPropertyNameExtractorTest.mockMimetypes;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
/**
* Test class for TransformerConfigMBeanImpl.
*
* @author Alan Davis
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class TransformerConfigMBeanImplTest
{
@Mock
private ContentTransformerRegistry transformerRegistry;
@Mock
private LegacyTransformerDebug transformerDebug;
@Mock
private TransformerConfig transformerConfig;
private AdminUiTransformerDebug transformerDebug;
@Mock
private MimetypeService mimetypeService;
@@ -99,9 +86,7 @@ public class TransformerConfigMBeanImplTest
MockitoAnnotations.initMocks(this);
mbean = new TransformerConfigMBeanImpl();
mbean.setContentTransformerRegistry(transformerRegistry);
mbean.setTransformerDebug(transformerDebug);
mbean.setTransformerConfig(transformerConfig);
mbean.setMimetypeService(mimetypeService);
mbean.setTransformerLog(transformerLog);
mbean.setTransformerDebugLog(transformerDebugLog);
@@ -112,6 +97,33 @@ public class TransformerConfigMBeanImplTest
"text/plain", "txt");
}
/**
* Mock up the responses from the mimetypeService so that it:
* a) returns all the supplied mimetypes
* b) returns the extension given the mimetype
* c) returns the mimetype given the extension.
* @param mimetypeService mimetype service
* @param mimetypesAndExtensions sequence of mimetypes and extenstions.
* @throws IllegalStateException if there is not an extension for every mimetype
*/
public static void mockMimetypes(MimetypeService mimetypeService, String... mimetypesAndExtensions)
{
if (mimetypesAndExtensions.length % 2 != 0)
{
// Not using IllegalArgumentException as this is thrown by classes under test
throw new java.lang.IllegalStateException("There should be an extension for every mimetype");
}
final Set<String> allMimetypes = new HashSet<String>();
for (int i=0; i < mimetypesAndExtensions.length; i+=2)
{
allMimetypes.add(mimetypesAndExtensions[i]);
when(mimetypeService.getExtension(mimetypesAndExtensions[i])).thenReturn(mimetypesAndExtensions[i+1]);
when(mimetypeService.getMimetype(mimetypesAndExtensions[i+1])).thenReturn(mimetypesAndExtensions[i]);
}
when(mimetypeService.getMimetypes()).thenReturn(new ArrayList<String>(allMimetypes));
}
@Test
public void getExtensionsAndMimetypesTest()
{
@@ -128,154 +140,40 @@ public class TransformerConfigMBeanImplTest
public void getTransformationsByExtensionTest()
{
setupForGetTransformationsByExtension();
assertEquals("One result", mbean.getTransformationsByExtension("pdf", "png", null));
assertEquals("One result", mbean.getTransformationsByExtension("pdf", "png"));
}
@Test
public void getTransformationsByExtensionUpperCaseTest()
{
setupForGetTransformationsByExtension();
assertEquals("One result", mbean.getTransformationsByExtension("PDF", "PNG", null));
assertEquals("One result", mbean.getTransformationsByExtension("PDF", "PNG"));
}
@Test
public void getTransformationsByExtensionNullSourceTest()
{
setupForGetTransformationsByExtension();
assertEquals("Lots of results to png", mbean.getTransformationsByExtension(null, "PNG", null));
assertEquals("Lots of results to png", mbean.getTransformationsByExtension(null, "PNG"));
}
@Test
public void getTransformationsByExtensionNullTargetTest()
{
setupForGetTransformationsByExtension();
assertEquals("Lots of results from pdf", mbean.getTransformationsByExtension("pdf", null, null));
assertEquals("Lots of results from pdf", mbean.getTransformationsByExtension("pdf", null));
}
private void setupForGetTransformationsByExtension()
{
when(transformerDebug.transformationsByExtension("pdf", "png", true, true, false, null)).thenReturn("One result");
when(transformerDebug.transformationsByExtension(null, "png", true, true, false, null)).thenReturn("Lots of results to png");
when(transformerDebug.transformationsByExtension("pdf", null, true, true, false, null)).thenReturn("Lots of results from pdf");
}
@Test
public void getTransformationStatisticsTransformer1FromToTest()
{
setupForGetTransformationStatistics();
// Should not be a transformer summary as there might be other transforms and the
// totals would not add up
assertEquals(
"transformer.transformer1 pdf png count=10 errors=0 averageTime=200 ms",
mbean.getTransformationStatistics("transformer1", "pdf", "png"));
}
@Test
public void getTransformationStatisticsTransformer1AllTest()
{
setupForGetTransformationStatistics();
// Should be transformer summaries as all transforms were requested and the
// totals will add up
assertEquals(
"transformer.transformer1 * * count=30 errors=0 averageTime=133 ms\n" +
"transformer.transformer1 pdf png count=10 errors=0 averageTime=200 ms\n" +
"transformer.transformer1 txt png count=20 errors=0 averageTime=100 ms",
mbean.getTransformationStatistics("transformer1", null, null));
}
@Test
public void getTransformationStatisticsFromToTest()
{
setupForGetTransformationStatistics();
// Should be an overall summary as the transformer is not specified
// Should not be a transformer summary as there 'might' be other transforms and the
// totals would not add up
assertEquals(
"SUMMARY pdf png count=10 errors=0 averageTime=200 ms\n" +
"SUMMARY txt png count=24 errors=0 averageTime=234 ms\n" +
"\n" +
"transformer.transformer1 pdf png count=10 errors=0 averageTime=200 ms\n" +
"transformer.transformer1 txt png count=20 errors=0 averageTime=100 ms\n" +
"\n" +
"transformer.transformer2 txt png count=4 errors=0 averageTime=654 ms",
mbean.getTransformationStatistics(null, null, "png"));
}
@Test
public void getTransformationStatisticsAllTest()
{
setupForGetTransformationStatistics();
// Should be an overall summary as the transformer is not specified
// Should be a transformer1 summary but not for transformer2 as it only has done txt->png
assertEquals(
"SUMMARY * * count=34 errors=0 averageTime=222 ms\n" +
"SUMMARY pdf png count=10 errors=0 averageTime=200 ms\n" +
"SUMMARY txt png count=24 errors=0 averageTime=234 ms\n" +
"\n" +
"transformer.transformer1 * * count=30 errors=0 averageTime=133 ms\n" +
"transformer.transformer1 pdf png count=10 errors=0 averageTime=200 ms\n" +
"transformer.transformer1 txt png count=20 errors=0 averageTime=100 ms\n" +
"\n" +
"transformer.transformer2 txt png count=4 errors=0 averageTime=654 ms",
mbean.getTransformationStatistics(null, null, null));
}
@Test
public void getTransformationStatisticsNoneTest()
{
setupForGetTransformationStatistics();
assertEquals(
"No transformations to report",
mbean.getTransformationStatistics("transformer1", "png", "pdf"));
}
@SuppressWarnings("unchecked")
private void setupForGetTransformationStatistics()
{
ContentTransformer transformer1 = (ContentTransformer) new DummyContentTransformer("transformer.transformer1");
ContentTransformer transformer2 = (ContentTransformer) new DummyContentTransformer("transformer.transformer2");
Collection<ContentTransformer> transformerList1=Arrays.asList(new ContentTransformer[] {transformer1});
when(transformerDebug.sortTransformersByName("transformer.transformer1")).thenReturn(
transformerList1);
Collection<ContentTransformer> transformerList2=Arrays.asList(new ContentTransformer[] {transformer1, transformer2});
when(transformerDebug.sortTransformersByName(null)).thenReturn(
transformerList2);
when(transformerDebug.getSourceMimetypes("pdf")).thenReturn(Collections.singletonList("application/pdf"));
when(transformerDebug.getSourceMimetypes("png")).thenReturn(Collections.singletonList("image/png"));
when(transformerDebug.getSourceMimetypes("txt")).thenReturn(Collections.singletonList("text/plain"));
when(transformerDebug.getSourceMimetypes(null)).thenReturn(Arrays.asList(new String[] {"application/pdf", "image/png", "text/plain"}));
when(transformerDebug.getTargetMimetypes(any(), eq("pdf"), (Collection<String>) any())).thenReturn(Collections.singletonList("application/pdf"));
when(transformerDebug.getTargetMimetypes(any(), eq("png"), (Collection<String>) any())).thenReturn(Collections.singletonList("image/png"));
when(transformerDebug.getTargetMimetypes(any(), eq("txt"), (Collection<String>) any())).thenReturn(Collections.singletonList("text/plain"));
when(transformerDebug.getTargetMimetypes(any(), (String)eq(null), (Collection<String>) any())).thenReturn(Arrays.asList(new String[] {"application/pdf", "image/png", "text/plain"}));
when(transformerConfig.getStatistics(null, null, null, false)).thenReturn(
new TransformerStatisticsImpl(mimetypeService, "*", "*", null, null, 130000, 222, 34));
when(transformerConfig.getStatistics(null, "application/pdf", "image/png", false)).thenReturn(
new TransformerStatisticsImpl(mimetypeService, "application/pdf", "image/png", null, null, 130001, 200, 10));
when(transformerConfig.getStatistics(null, "text/plain", "image/png", false)).thenReturn(
new TransformerStatisticsImpl(mimetypeService, "text/plain", "image/png", null, null, 130002, 234, 24));
when(transformerConfig.getStatistics(transformer1, "application/pdf", "image/png", false)).thenReturn(
new TransformerStatisticsImpl(mimetypeService, "application/pdf", "image/png", transformer1, null, 120000, 200, 10));
when(transformerConfig.getStatistics(transformer1, "text/plain", "image/png", false)).thenReturn(
new TransformerStatisticsImpl(mimetypeService, "text/plain", "image/png", transformer1, null, 120001, 100, 20));
when(transformerConfig.getStatistics(transformer1, null, null, false)).thenReturn(
new TransformerStatisticsImpl(mimetypeService, "*", "*", transformer1, null, 120002, 133, 30));
when(transformerConfig.getStatistics(transformer2, "text/plain", "image/png", false)).thenReturn(
new TransformerStatisticsImpl(mimetypeService, "text/plain", "image/png", transformer2, null, 120003, 654, 4));
when(transformerConfig.getStatistics(transformer2, null, null, false)).thenReturn(
new TransformerStatisticsImpl(mimetypeService, "*", "*", transformer2, null, 120004, 654, 4));
when(transformerDebug.transformationsByExtension("pdf", "png", true)).thenReturn("One result");
when(transformerDebug.transformationsByExtension(null, "png", true)).thenReturn("Lots of results to png");
when(transformerDebug.transformationsByExtension("pdf", null, true)).thenReturn("Lots of results from pdf");
}
@Test
public void getTransformationLogTest()
{
// when(transformerLog.getEntries(5)).thenReturn(new String[] {"test message 1", "test message 2"});
logEntries.add("test message 1");
logEntries.add("test message 2");
assertArrayEquals(new String[] {"test message 1", "test message 2"}, mbean.getTransformationLog(5));
@@ -284,14 +182,12 @@ public class TransformerConfigMBeanImplTest
@Test
public void getTransformationLogZeroTest()
{
// when(transformerLog.getEntries(5)).thenReturn(new String[0]);
assertArrayEquals(new String[] {"No transformations to report"}, mbean.getTransformationLog(5));
}
@Test
public void getTransformationDebugLogTest()
{
// when(transformerDebugLog.getEntries(5)).thenReturn(new String[] {"test message 1", "test message 2"});
logEntries.add("test message 1");
logEntries.add("test message 2");
assertArrayEquals(new String[] {"test message 1", "test message 2"}, mbean.getTransformationDebugLog(5));
@@ -300,56 +196,20 @@ public class TransformerConfigMBeanImplTest
@Test
public void getTransformationDebugLogZeroTest()
{
// when(transformerDebugLog.getEntries(5)).thenReturn(new String[0]);
assertArrayEquals(new String[] {"No transformations to report"}, mbean.getTransformationDebugLog(5));
}
@Test
public void getPropertiesTest()
{
when(transformerConfig.getProperties(false)).thenReturn("some properties");
assertEquals("some properties", mbean.getProperties(true));
}
@Test
public void setPropertiesTest()
{
when(transformerConfig.setProperties("abc")).thenReturn(12);
assertEquals("Properties added or changed: 12", mbean.setProperties("abc"));
}
@Test
public void setPropertiesDataProblemTest()
{
when(transformerConfig.setProperties("abc=12\nabc=1")).thenThrow(new IllegalArgumentException("abc has been specified more than once"));
assertEquals("abc has been specified more than once", mbean.setProperties("abc=12\nabc=1"));
}
@Test
public void removePropertiesTest()
{
when(transformerConfig.removeProperties("abc")).thenReturn(1);
assertEquals("Properties removed: 1", mbean.removeProperties("abc"));
}
@Test
public void removePropertiesDataProblemTest()
{
when(transformerConfig.removeProperties("abc")).thenThrow(new IllegalArgumentException("Unexpected property: abc Does not exist"));
assertEquals("Unexpected property: abc Does not exist", mbean.removeProperties("abc"));
}
@Test
public void testTransformAnyTransformerTest()
{
when(transformerDebug.testTransform("pdf", "png", null)).thenReturn("debug output");
assertEquals("debug output", mbean.testTransform("String", "pdf", "png", null));
when(transformerDebug.testTransform("pdf", "png")).thenReturn("debug output");
assertEquals("debug output", mbean.testTransform("pdf", "png"));
}
@Test
public void testTransformAnyTransformerBadExtensionTest()
{
when(transformerDebug.testTransform("bad", "png", null)).thenThrow(new IllegalArgumentException("Unknown source extension: bad"));
assertEquals("Unknown source extension: bad", mbean.testTransform(null, "bad", "png", null));
when(transformerDebug.testTransform("bad", "png")).thenThrow(new IllegalArgumentException("Unknown source extension: bad"));
assertEquals("Unknown source extension: bad", mbean.testTransform("bad", "png"));
}
}

View File

@@ -1,239 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import static org.alfresco.repo.content.transform.TransformerConfig.ANY;
import static org.alfresco.repo.content.transform.TransformerConfig.BLACKLIST;
import static org.alfresco.repo.content.transform.TransformerConfig.PRIORITY;
import static org.alfresco.repo.content.transform.TransformerPropertyNameExtractorTest.mockMimetypes;
import static org.alfresco.repo.content.transform.TransformerPropertyNameExtractorTest.mockProperties;
import static org.junit.Assert.assertEquals;
import java.math.BigInteger;
import org.alfresco.service.cmr.repository.MalformedNodeRefException;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/**
* Test class for TransformerConfigProperty.
*
* @author Alan Davis
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class TransformerConfigPropertyTest
{
@Mock
private TransformerProperties transformerProperties;
@Mock
private MimetypeService mimetypeService;
private TransformerConfigProperty extractor;
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
mockMimetypes(mimetypeService,
"application/pdf", "pdf",
"image/png", "png");
}
@Test
public void simpleTest()
{
mockProperties(transformerProperties, "content.transformer.abc.xyz.priority", "87");
extractor = new TransformerConfigProperty(transformerProperties, mimetypeService, PRIORITY, "55");
int actual = extractor.getInt((ContentTransformer) new DummyContentTransformer("transformer.abc.xyz"), null, null);
assertEquals("transformer default priority", 87, actual);
}
@Test
public void getSystemWideDefaultTest()
{
mockProperties(transformerProperties, "content.transformer.default.priority", "87");
extractor = new TransformerConfigProperty(transformerProperties, mimetypeService, PRIORITY, "55");
int actual = extractor.getInt(null, null, null);
assertEquals("default priority", 87, actual);
}
@Test
public void getSystemWideDefaultWithAnyTest()
{
// Same as getSystemWideDefaultTest except getInt uses ANY rather than null
mockProperties(transformerProperties, "content.transformer.default.priority", "87");
extractor = new TransformerConfigProperty(transformerProperties, mimetypeService, PRIORITY, "55");
int actual = extractor.getInt(null, ANY, ANY);
assertEquals("default priority", 87, actual);
}
@Test
public void useSystemWideDefaultTest()
{
mockProperties(transformerProperties, "content.transformer.default.priority", "87");
extractor = new TransformerConfigProperty(transformerProperties, mimetypeService, PRIORITY, "55");
int actual = extractor.getInt((ContentTransformer) new DummyContentTransformer("transformer.abc.xyz"), null, null);
assertEquals("default priority", 87, actual);
}
@Test
public void useNonExistentSystemWideDefaultTest()
{
mockProperties(transformerProperties);
extractor = new TransformerConfigProperty(transformerProperties, mimetypeService, PRIORITY, "55");
int actual = extractor.getInt((ContentTransformer) new DummyContentTransformer("transformer.abc.xyz"), null, null);
assertEquals("default priority", 55, actual);
}
@Test
public void mimetypesTest()
{
mockProperties(transformerProperties, "content.transformer.abc.xyz.mimetypes.application/pdf.image/png.priority", "87");
extractor = new TransformerConfigProperty(transformerProperties, mimetypeService, PRIORITY, "55");
int actual = extractor.getInt((ContentTransformer) new DummyContentTransformer("transformer.abc.xyz"), "application/pdf", "image/png");
assertEquals("transformer default priority", 87, actual);
}
@Test
public void extensionsTest()
{
mockProperties(transformerProperties, "content.transformer.abc.xyz.extensions.pdf.png.priority", "87");
extractor = new TransformerConfigProperty(transformerProperties, mimetypeService, PRIORITY, "55");
int actual = extractor.getInt((ContentTransformer) new DummyContentTransformer("transformer.abc.xyz"), "application/pdf", "image/png");
assertEquals("transformer default priority", 87, actual);
}
@Test
public void multiplePropertiesTest()
{
mockProperties(transformerProperties,
"content.transformer.default.priority", "11",
"content.transformer.abc.extensions.pdf.png.priority", "22",
"content.transformer.abc.xyz.extensions.pdf.png.priority", "33");
extractor = new TransformerConfigProperty(transformerProperties, mimetypeService, PRIORITY, "55");
int actual = extractor.getInt((ContentTransformer) new DummyContentTransformer("transformer.qaz"), "application/pdf", "image/png");
assertEquals("default", 11, actual);
actual = extractor.getInt((ContentTransformer) new DummyContentTransformer("transformer.abc"), "application/pdf", "image/png");
assertEquals("abc", 22, actual);
actual = extractor.getInt((ContentTransformer) new DummyContentTransformer("transformer.abc.xyz"), "application/pdf", "image/png");
assertEquals("abc.xyz", 33, actual);
}
@Test
public void longTest()
{
mockProperties(transformerProperties, "content.transformer.abc.xyz.extensions.pdf.png.priority", "1234567890");
extractor = new TransformerConfigProperty(transformerProperties, mimetypeService, PRIORITY, "55");
long actual = extractor.getInt((ContentTransformer) new DummyContentTransformer("transformer.abc.xyz"), "application/pdf", "image/png");
assertEquals("transformer default priority", 1234567890L, actual);
}
@Test(expected=NumberFormatException.class)
public void badIntTest()
{
mockProperties(transformerProperties, "content.transformer.abc.xyz.extensions.pdf.png.priority",
Long.toString(((long)Integer.MAX_VALUE)+1));
extractor = new TransformerConfigProperty(transformerProperties, mimetypeService, PRIORITY, "55");
extractor.getInt((ContentTransformer) new DummyContentTransformer("transformer.abc.xyz"), "application/pdf", "image/png");
}
@Test(expected=NumberFormatException.class)
public void badIntAbcTest()
{
mockProperties(transformerProperties, "content.transformer.abc.xyz.extensions.pdf.png.priority", "abc");
extractor = new TransformerConfigProperty(transformerProperties, mimetypeService, PRIORITY, "55");
extractor.getInt((ContentTransformer) new DummyContentTransformer("transformer.abc.xyz"), "application/pdf", "image/png");
}
@Test(expected=NumberFormatException.class)
public void badLongTest()
{
mockProperties(transformerProperties, "content.transformer.abc.xyz.extensions.pdf.png.priority",
new BigInteger(""+Long.MAX_VALUE).add(BigInteger.ONE).toString());
extractor = new TransformerConfigProperty(transformerProperties, mimetypeService, PRIORITY, "55");
extractor.getLong((ContentTransformer) new DummyContentTransformer("transformer.abc.xyz"), "application/pdf", "image/png");
}
@Test(expected=NumberFormatException.class)
public void badLongAbcTest()
{
mockProperties(transformerProperties, "content.transformer.abc.xyz.extensions.pdf.png.priority", "abc");
extractor = new TransformerConfigProperty(transformerProperties, mimetypeService, PRIORITY, "55");
extractor.getLong((ContentTransformer) new DummyContentTransformer("transformer.abc.xyz"), "application/pdf", "image/png");
}
@Test
public void goodNodeRefTest()
{
// ".+://.+/.+"
mockProperties(transformerProperties, "content.transformer.abc.xyz.extensions.pdf.png.blacklist", "abc://mno/xyz");
extractor = new TransformerConfigProperty(transformerProperties, mimetypeService, BLACKLIST, "abc/mno/xyz");
String actual = extractor.getNodeRefs((ContentTransformer) new DummyContentTransformer("transformer.abc.xyz"), "application/pdf", "image/png").toString();
assertEquals("blacklist", "[abc://mno/xyz]", actual);
}
@Test
public void goodNodeRefListTest()
{
// ".+://.+/.+"
mockProperties(transformerProperties, "content.transformer.abc.xyz.extensions.pdf.png.blacklist", "abc://mno/xyz, ,a://m/x,b://n/y");
extractor = new TransformerConfigProperty(transformerProperties, mimetypeService, BLACKLIST, "abc://mno/xyz, ,a://m/x,b://n/y");
String actual = extractor.getNodeRefs((ContentTransformer) new DummyContentTransformer("transformer.abc.xyz"), "application/pdf", "image/png").toString();
assertEquals("blacklist", "[abc://mno/xyz, a://m/x, b://n/y]", actual);
}
@Test(expected=MalformedNodeRefException.class)
public void badNodeRefTest()
{
mockProperties(transformerProperties, "content.transformer.abc.xyz.extensions.pdf.png.blacklist", "abc");
extractor = new TransformerConfigProperty(transformerProperties, mimetypeService, BLACKLIST, "abc");
extractor.getNodeRefs((ContentTransformer) new DummyContentTransformer("transformer.abc.xyz"), "application/pdf", "image/png");
}
}

View File

@@ -1,260 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import static org.alfresco.repo.content.transform.TransformerPropertyNameExtractorTest.mockMimetypes;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/**
* Test class for TransformerConfigStatistics.
*
* @author Alan Davis
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class TransformerConfigStatisticsTest
{
@Mock
private TransformerConfigImpl transformerConfig;
@Mock
private MimetypeService mimetypeService;
private ContentTransformer transformer1;
private TransformerConfigStatistics stats;
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
stats = new TransformerConfigStatistics(transformerConfig, mimetypeService);
transformer1 = new DummyContentTransformer("transformer.transformer1");
mockMimetypes(mimetypeService,
"application/pdf", "pdf",
"image/png", "png",
"text/plain", "txt");
}
@Test
public void createTest()
{
TransformerStatistics statistics = stats.getStatistics(transformer1, "application/pdf", "image/png", true);
assertTrue(statistics != null);
assertEquals(0L, statistics.getAverageTime());
assertEquals(0L, statistics.getCount());
assertEquals(0L, statistics.getErrorCount());
assertEquals("pdf", statistics.getSourceExt());
assertEquals("png", statistics.getTargetExt());
assertEquals("transformer.transformer1", statistics.getTransformerName());
}
@Test
public void createSetAverageTimeTest()
{
when(transformerConfig.getInitialAverageTime(transformer1, "application/pdf", "image/png")).thenReturn(12345L);
when(transformerConfig.getInitialCount(transformer1, "application/pdf", "image/png")).thenReturn(123);
TransformerStatistics statistics = stats.getStatistics(transformer1, "application/pdf", "image/png", true);
assertTrue(statistics != null);
assertEquals(12345L, statistics.getAverageTime());
assertEquals(123L, statistics.getCount());
}
@Test
public void create0CountOnSetAverageTimeTest()
{
// getInitialCount should be defaulted to 0 if the average time is set and there is no default
when(transformerConfig.getInitialAverageTime(transformer1, "application/pdf", "image/png")).thenReturn(12345L);
TransformerStatistics statistics = stats.getStatistics(transformer1, "application/pdf", "image/png", true);
assertTrue(statistics != null);
assertEquals(12345L, statistics.getAverageTime());
assertEquals(0L, statistics.getCount());
}
@Test
public void createSetErrorTimeTest()
{
when(transformerConfig.getErrorTime(transformer1, "application/pdf", "image/png")).thenReturn(12345L);
TransformerStatistics statistics = stats.getStatistics(transformer1, "application/pdf", "image/png", true);
statistics.recordError(100L); // 100 does not get used if errorTime is set
assertEquals(12345L, statistics.getAverageTime());
assertEquals(1L, statistics.getCount());
assertEquals(1L, statistics.getErrorCount());
}
@Test
public void createNoSetErrorTimeTest()
{
TransformerStatistics statistics = stats.getStatistics(transformer1, "application/pdf", "image/png", true);
statistics.recordError(100L);
assertEquals(100L, statistics.getAverageTime());
assertEquals(1L, statistics.getCount());
assertEquals(1L, statistics.getErrorCount());
}
@Test
public void mayCreateButExistsTest()
{
TransformerStatistics statistics = stats.getStatistics(transformer1, "application/pdf", "image/png", true);
statistics.recordTime(100L);
// Call again (with createNew=true) and then make sure it is the same object returned
statistics = stats.getStatistics(transformer1, "application/pdf", "image/png", true);
assertEquals(100L, statistics.getAverageTime());
}
@Test
public void mayNotCreateButExistsTest()
{
TransformerStatistics statistics = stats.getStatistics(transformer1, "application/pdf", "image/png", true);
statistics.recordTime(100L);
// Call again (with createNew=false) and then make sure it is the same object returned
statistics = stats.getStatistics(transformer1, "application/pdf", "image/png", false);
assertEquals(100L, statistics.getAverageTime());
}
@Test
public void doesNotExistTest()
{
assertEquals(null, stats.getStatistics(transformer1, "application/pdf", "image/png", false));
}
@Test
// i.e. the system wide summary
public void nullTransformerTest()
{
TransformerStatistics statistics = stats.getStatistics(null, "application/pdf", "image/png", true);
assertEquals("SUMMARY", statistics.getTransformerName());
}
@Test
public void nullMimetypesTest()
{
TransformerStatistics statistics = stats.getStatistics(transformer1, null, null, true);
assertEquals("transformer.transformer1", statistics.getTransformerName());
assertEquals("*", statistics.getSourceExt());
assertEquals("*", statistics.getTargetExt());
}
@Test
public void createSummaryTooTest()
{
// Same as createTest()
TransformerStatistics statistics = stats.getStatistics(transformer1, "application/pdf", "image/png", true);
// The summary for the transformer should also have been created
statistics = stats.getStatistics(transformer1, "*", "*", false);
assertTrue(statistics != null);
assertEquals(0L, statistics.getAverageTime());
assertEquals(0L, statistics.getCount());
assertEquals(0L, statistics.getErrorCount());
assertEquals("*", statistics.getSourceExt()); // pdf in createTest
assertEquals("*", statistics.getTargetExt()); // png in createTest
assertEquals("transformer.transformer1", statistics.getTransformerName());
}
@Test
// check the transformer summary gets reused
public void transformerSummaryTest()
{
// Create pdf->png and summary from transformer1
TransformerStatistics pdfToPng = stats.getStatistics(transformer1, "application/pdf", "image/png", true);
TransformerStatistics summary = stats.getStatistics(transformer1, "*", "*", false);
// Create txt->png for transformer1
TransformerStatistics txtToPng = stats.getStatistics(transformer1, "text/plain", "image/png", true);
pdfToPng.recordTime(100);
txtToPng.recordTime(200);
assertEquals(2, summary.getCount());
assertEquals(150L, summary.getAverageTime());
}
@Test
// check the system wide statistics gather up values
public void systemWideSummaryTest()
{
TransformerStatistics transformer1PdfToPng = stats.getStatistics(transformer1, "application/pdf", "image/png", true);
TransformerStatistics transformer1TxtToPng = stats.getStatistics(transformer1, "text/plain", "image/png", true);
ContentTransformer transformer2 = new DummyContentTransformer("transformer.transformer2");
TransformerStatistics transformer2PdfToPng = stats.getStatistics(transformer2, "application/pdf", "image/png", true);
TransformerStatistics transformer2TxtToPdf = stats.getStatistics(transformer2, "text/plain", "application/pdf", true);
TransformerStatistics summaryPdfToPng = stats.getStatistics(null, "application/pdf", "image/png", true);
TransformerStatistics summaryTxtToPng = stats.getStatistics(null, "text/plain", "image/png", true);
TransformerStatistics summaryTxtToPdf = stats.getStatistics(null, "text/plain", "application/pdf", true);
TransformerStatistics summary = stats.getStatistics(null, "*", "*", false);
// Run a few transforms
recordTime(summaryPdfToPng, transformer1PdfToPng, 100);
recordTime(summaryPdfToPng, transformer1PdfToPng, 100);
recordTime(summaryPdfToPng, transformer2PdfToPng, 400);
recordTime(summaryTxtToPng, transformer1TxtToPng, 200);
recordTime(summaryTxtToPdf, transformer2TxtToPdf, 400);
// Check summaries
assertEquals(5, summary.getCount());
assertEquals(3, summaryPdfToPng.getCount());
assertEquals(1, summaryTxtToPng.getCount());
assertEquals(1, summaryTxtToPdf.getCount());
assertEquals(200L, summaryPdfToPng.getAverageTime());
assertEquals(200L, summaryTxtToPng.getAverageTime());
assertEquals(400L, summaryTxtToPdf.getAverageTime());
assertEquals(240L, summary.getAverageTime()); // 100+100+400+200+400 = 1200
}
// Calls both transformer and summary recordTime() methods in the same way
// AbstractContentTransformer2.recordTime(String, String, long) would do for
// a top level transformation
private void recordTime(TransformerStatistics summaryAToB, TransformerStatistics transformerAToB, long time)
{
transformerAToB.recordTime(time);
summaryAToB.recordTime(time);
}
}

View File

@@ -1,276 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import static org.alfresco.repo.content.transform.TransformerPropertyNameExtractorTest.mockMimetypes;
import static org.alfresco.repo.content.transform.TransformerPropertyNameExtractorTest.mockProperties;
import static org.junit.Assert.assertEquals;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/**
* Test class for TransformerConfigSupported.
*
* @author Alan Davis
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class TransformerConfigSupportedTest
{
@Mock
private TransformerProperties transformerProperties;
@Mock
private MimetypeService mimetypeService;
@Mock
private TransformationOptions options;
private TransformerConfigSupported extractor;
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
mockMimetypes(mimetypeService,
"application/pdf", "pdf",
"image/png", "png",
"text/xml", "xml");
}
@Test
public void supportedTest()
{
mockProperties(transformerProperties, "content.transformer.abc.extensions.pdf.png.supported", "true");
extractor = new TransformerConfigSupported(transformerProperties, mimetypeService);
boolean supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "application/pdf", "image/png", options);
assertEquals("supported", true, supported);
supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "image/png", "text/xml", options);
assertEquals("xyz supported", false, supported);
}
@Test
public void unsupportedTest()
{
mockProperties(transformerProperties, "content.transformer.abc.extensions.pdf.png.supported", "false");
extractor = new TransformerConfigSupported(transformerProperties, mimetypeService);
boolean supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "application/pdf", "image/png", options);
assertEquals("supported", false, supported);
supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "image/png", "text/xml", options);
assertEquals("xyz supported", true, supported);
}
@Test
public void mixedCaseTrueTest()
{
mockProperties(transformerProperties, "content.transformer.abc.extensions.pdf.png.supported", "tRUE");
extractor = new TransformerConfigSupported(transformerProperties, mimetypeService);
boolean supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "application/pdf", "image/png", options);
assertEquals("supported", true, supported);
}
@Test
public void unsupportedMimetypesTest()
{
mockProperties(transformerProperties, "content.transformer.abc.mimetypes.application/pdf.image/png.supported", "false");
extractor = new TransformerConfigSupported(transformerProperties, mimetypeService);
boolean supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "application/pdf", "image/png", options);
assertEquals("supported", false, supported);
}
@Test
public void badValueIsUnsupportedTest()
{
mockProperties(transformerProperties, "content.transformer.abc.extensions.pdf.png.supported", "bad");
extractor = new TransformerConfigSupported(transformerProperties, mimetypeService);
boolean supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "application/pdf", "image/png", options);
assertEquals("supported", false, supported);
}
@Test
public void otherMimetypesTest()
{
mockProperties(transformerProperties, "content.transformer.abc.extensions.png.pdf.supported", "false");
extractor = new TransformerConfigSupported(transformerProperties, mimetypeService);
boolean supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "application/pdf", "image/png", options);
assertEquals("supported", true, supported);
}
@Test
public void supportedByDefaultTest()
{
mockProperties(transformerProperties);
extractor = new TransformerConfigSupported(transformerProperties, mimetypeService);
boolean supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "application/pdf", "image/png", options);
assertEquals("supported", true, supported);
}
@Test
public void multipleTest()
{
mockProperties(transformerProperties,
"content.transformer.abc.extensions.pdf.png.supported", "false",
"content.transformer.def.extensions.pdf.png.supported", "true",
"content.transformer.xyz.extensions.pdf.png.supported", "false");
extractor = new TransformerConfigSupported(transformerProperties, mimetypeService);
boolean supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "application/pdf", "image/png", options);
assertEquals("abc supported", false, supported);
supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.def"), "application/pdf", "image/png", options);
assertEquals("def supported", true, supported);
supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.xyz"), "application/pdf", "image/png", options);
assertEquals("xyz supported", false, supported);
}
@Test
public void withoutDefaultTest()
{
mockProperties(transformerProperties,
"content.transformer.abc.extensions.pdf.*.supported", "false",
"content.transformer.abc.extensions.pdf.png.supported", "true");
extractor = new TransformerConfigSupported(transformerProperties, mimetypeService);
boolean supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "application/pdf", "application/pdf", options);
assertEquals("abc supported", false, supported);
supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "application/pdf", "image/png", options);
assertEquals("def supported", true, supported);
supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "image/png", "text/xml", options);
assertEquals("xyz supported", false, supported); // << not the same in withDefaultTest
}
@Test
public void withDefaultTest()
{
mockProperties(transformerProperties,
"content.transformer.abc.extensions.*.*.supported", "true", // << not the same in withoutDefaultTest
"content.transformer.abc.extensions.pdf.*.supported", "false",
"content.transformer.abc.extensions.pdf.png.supported", "true");
extractor = new TransformerConfigSupported(transformerProperties, mimetypeService);
boolean supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "application/pdf", "application/pdf", options);
assertEquals("abc supported", false, supported);
supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "application/pdf", "image/png", options);
assertEquals("def supported", true, supported);
supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "image/png", "text/xml", options);
assertEquals("xyz supported", true, supported); // << not the same in withoutDefaultTest
}
@Test
public void withoutDefaultNegatedTest()
{
mockProperties(transformerProperties,
"content.transformer.abc.extensions.pdf.*.supported", "true",
"content.transformer.abc.extensions.pdf.png.supported", "false");
extractor = new TransformerConfigSupported(transformerProperties, mimetypeService);
boolean supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "application/pdf", "application/pdf", options);
assertEquals("abc supported", true, supported);
supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "application/pdf", "image/png", options);
assertEquals("def supported", false, supported);
supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "image/png", "text/xml", options);
assertEquals("xyz supported", false, supported);
}
@Test
public void withDefaultNegatedTest()
{
mockProperties(transformerProperties,
"content.transformer.abc.extensions.*.*.supported", "false",
"content.transformer.abc.extensions.pdf.*.supported", "true",
"content.transformer.abc.extensions.pdf.png.supported", "false");
extractor = new TransformerConfigSupported(transformerProperties, mimetypeService);
boolean supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "application/pdf", "application/pdf", options);
assertEquals("abc supported", true, supported);
supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "application/pdf", "image/png", options);
assertEquals("def supported", false, supported);
supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "image/png", "text/xml", options);
assertEquals("xyz supported", false, supported);
}
@Test
public void bothUnsupportedAndSupportedTest()
{
// mimetypes should win if both are supplied
mockProperties(transformerProperties,
"content.transformer.abc.extensions.pdf.png.supported", "false",
"content.transformer.abc.mimetypes.application/pdf.image/png.supported", "true");
extractor = new TransformerConfigSupported(transformerProperties, mimetypeService);
boolean supported = extractor.isSupportedTransformation((ContentTransformer) new DummyContentTransformer("transformer.abc"), "application/pdf", "image/png", options);
assertEquals("supported", true, supported);
}
@Test
public void supportedWildcardMimetypeTest()
{
mockMimetypes(mimetypeService,
"application/pdf", "pdf",
"image/png", "png",
"image/x-raw-adobe", "dng",
"image/x-raw-hasselblad", "3fr",
"image/x-raw-fuji", "raf",
"image/x-raw-canon", "cr2",
"image/x-raw-kodak", "k25",
"text/xml", "xml");
mockProperties(transformerProperties, "content.transformer.abc.mimetypes.image/x-raw*.application/pdf.supported", "true");
extractor = new TransformerConfigSupported(transformerProperties, mimetypeService);
ContentTransformer transformer = (ContentTransformer) new DummyContentTransformer("transformer.abc");
boolean supported = extractor.isSupportedTransformation(transformer, "image/png", "application/pdf", options);
assertEquals("png supported", false, supported);
supported = extractor.isSupportedTransformation(transformer, "image/x-raw-adobe", "application/pdf", options);
assertEquals("dng supported", true, supported);
supported = extractor.isSupportedTransformation(transformer, "image/x-raw-hasselblad", "application/pdf", options);
assertEquals("3fr supported", true, supported);
supported = extractor.isSupportedTransformation(transformer, "image/x-raw-fuji", "application/pdf", options);
assertEquals("raf supported", true, supported);
supported = extractor.isSupportedTransformation(transformer, "image/x-raw-canon", "application/pdf", options);
assertEquals("cr2 supported", true, supported);
supported = extractor.isSupportedTransformation(transformer, "image/x-raw-kodak", "application/pdf", options);
assertEquals("k25 supported", true, supported);
supported = extractor.isSupportedTransformation(transformer, "text/xml", "application/pdf", options);
assertEquals("txt supported", false, supported);
}
}

View File

@@ -37,27 +37,14 @@ import org.junit.runners.Suite.SuiteClasses;
*/
@RunWith(Suite.class)
@SuiteClasses({
TransformerConfigStatisticsTest.class,
TransformerConfigLimitsTest.class,
TransformerConfigSupportedTest.class,
TransformerConfigPropertyTest.class,
TransformerPropertyNameExtractorTest.class,
TransformerPropertyGetterTest.class,
TransformerPropertySetterTest.class,
TransformerConfigDynamicTransformersTest.class,
LogAdapterTest.class,
LogTeeTest.class,
TransformerLoggerTest.class,
TransformerLogTest.class,
TransformerDebugLogTest.class,
LegacyTransformerDebugTest.class,
TransformerConfigImplTest.class,
TransformerConfigMBeanImplTest.class,
TransformerSelectorImplTest.class})
TransformerConfigMBeanImplTest.class})
/**
* Test classes in the Transformers subsystem

View File

@@ -25,18 +25,16 @@
*/
package org.alfresco.repo.content.transform;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
import java.util.Date;
import java.util.Deque;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
/**
* Test class for TransformerDebugLog.
*
@@ -48,7 +46,7 @@ public class TransformerDebugLogTest
private TransformerDebug transformerDebug;
@Mock
private TransformerConfig transformerConfig;
private Properties properties;
private TransformerDebugLog log;
@@ -59,7 +57,7 @@ public class TransformerDebugLogTest
log = new TransformerDebugLog();
log.setTransformerDebug(transformerDebug);
log.setTransformerConfig(transformerConfig);
log.setProperties(properties);
}
static void assertDebugEntriesEquals(String[] expected, String[] actual)
@@ -91,7 +89,7 @@ public class TransformerDebugLogTest
@Test
public void oneTest()
{
when(transformerConfig.getProperty("transformer.debug.entries")).thenReturn("3");
when(properties.getProperty("transformer.debug.entries")).thenReturn("3");
log.debug("56 one");
log.debug("56 Finished in 23 ms");
@@ -101,7 +99,7 @@ public class TransformerDebugLogTest
@Test
public void incompleteTest()
{
when(transformerConfig.getProperty("transformer.debug.entries")).thenReturn("3");
when(properties.getProperty("transformer.debug.entries")).thenReturn("3");
log.debug("56 one");
assertDebugEntriesEquals(new String[] {"56 one\n <<-- INCOMPLETE -->>"}, log.getEntries(10));
@@ -110,7 +108,7 @@ public class TransformerDebugLogTest
@Test
public void nullEntryTest()
{
when(transformerConfig.getProperty("transformer.debug.entries")).thenReturn("3");
when(properties.getProperty("transformer.debug.entries")).thenReturn("3");
log.debug(null);
assertDebugEntriesEquals(new String[] {}, log.getEntries(10));
@@ -119,7 +117,7 @@ public class TransformerDebugLogTest
@Test
public void zeroLengthIdEntryTest()
{
when(transformerConfig.getProperty("transformer.debug.entries")).thenReturn("3");
when(properties.getProperty("transformer.debug.entries")).thenReturn("3");
log.debug("one"); // as the 1st char is not a digit the id is taken to be ""
assertDebugEntriesEquals(new String[] {"one\n <<-- INCOMPLETE -->>"}, log.getEntries(10));
@@ -128,7 +126,7 @@ public class TransformerDebugLogTest
@Test
public void twoAndAHalfTest()
{
when(transformerConfig.getProperty("transformer.debug.entries")).thenReturn("3");
when(properties.getProperty("transformer.debug.entries")).thenReturn("3");
log.debug("56 one");
log.debug("56 Finished in 23 ms");
log.debug("57 one");
@@ -150,7 +148,7 @@ public class TransformerDebugLogTest
{
// The sequence will still be based on the first entry of each request,
// but subsequent debug may be out of order.
when(transformerConfig.getProperty("transformer.debug.entries")).thenReturn("3");
when(properties.getProperty("transformer.debug.entries")).thenReturn("3");
log.debug("56 one");
log.debug("57 one");
log.debug("56 Finished in 23 ms");

View File

@@ -29,6 +29,7 @@ import static org.junit.Assert.assertArrayEquals;
import static org.mockito.Mockito.when;
import java.util.Date;
import java.util.Properties;
import org.junit.Before;
import org.junit.Test;
@@ -46,7 +47,7 @@ public class TransformerLogTest
private TransformerDebug transformerDebug;
@Mock
private TransformerConfig transformerConfig;
private Properties properties;
private TransformerLog log;
@@ -57,7 +58,7 @@ public class TransformerLogTest
log = new TransformerLog();
log.setTransformerDebug(transformerDebug);
log.setTransformerConfig(transformerConfig);
log.setProperties(properties);
}
static String[] stripDateStamp(String[] actual)
@@ -84,7 +85,7 @@ public class TransformerLogTest
@Test
public void oneEntryTest()
{
when(transformerConfig.getProperty("transformer.log.entries")).thenReturn("3");
when(properties.getProperty("transformer.log.entries")).thenReturn("3");
log.debug("one");
assertLogEntriesEquals(new String[] {"one"}, log.getEntries(10));
@@ -93,7 +94,7 @@ public class TransformerLogTest
@Test
public void fiveEntryTest()
{
when(transformerConfig.getProperty("transformer.log.entries")).thenReturn("3");
when(properties.getProperty("transformer.log.entries")).thenReturn("3");
log.debug("one");
log.debug("two");

View File

@@ -44,17 +44,13 @@ import org.mockito.MockitoAnnotations;
* Test class for TransformerLogger.
*
* @author Alan Davis
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class TransformerLoggerTest
{
@Mock
private TransformerDebug transformerDebug;
@Mock
private TransformerConfig transformerConfig;
private Properties properties = new Properties();
private TransformerLogger<String> log;
@@ -62,12 +58,12 @@ public class TransformerLoggerTest
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
log = newLogger(new AtomicInteger(1), transformerDebug, transformerConfig);
log = newLogger(new AtomicInteger(1), transformerDebug, properties);
}
private TransformerLogger<String> newLogger(final AtomicInteger numberOfMessagesToAdd,
TransformerDebug transformerDebug, TransformerConfig transformerConfig)
TransformerDebug transformerDebug, Properties properties)
{
TransformerLogger<String> log = new TransformerLogger<String>()
{
@@ -109,53 +105,10 @@ public class TransformerLoggerTest
}
};
log.setTransformerDebug(transformerDebug);
log.setTransformerConfig(transformerConfig);
log.setProperties(properties);
return log;
}
@Test
public void propertyExistsTest()
{
when(transformerConfig.getProperty("property.name")).thenReturn("5");
assertEquals("property.name=5 # default=0", log.getPropertyAndValue(null));
}
@Test
public void propertyExistsAndDefaultSetTest()
{
when(transformerConfig.getProperty("property.name")).thenReturn("5");
Properties properties = new Properties();
properties.setProperty("property.name", "23");
assertEquals("property.name=5 # default=23", log.getPropertyAndValue(properties));
}
@Test
public void propertyDoesNotExistTest()
{
assertEquals("# property.name=0", log.getPropertyAndValue(null));
}
@Test
public void propertyNegativeTest()
{
when(transformerConfig.getProperty("property.name")).thenReturn("-2");
assertEquals("# property.name=0", log.getPropertyAndValue(null));
}
@Test
public void propertyGreaterThanMax()
{
when(transformerConfig.getProperty("property.name")).thenReturn("1000");
assertEquals("property.name=176 # default=0", log.getPropertyAndValue(null));
}
@Test
public void propertyBadTest()
{
when(transformerConfig.getProperty("property.name")).thenReturn("abc");
assertEquals("# property.name=0", log.getPropertyAndValue(null));
}
@Test
public void isDebugEnabled0EntriesTest()
{
@@ -166,7 +119,7 @@ public class TransformerLoggerTest
@Test
public void isDebugEnabled5EntriesTest()
{
when(transformerConfig.getProperty("property.name")).thenReturn("5");
properties.setProperty("property.name", "5");
assertTrue(log.isDebugEnabled());
}
@@ -174,14 +127,14 @@ public class TransformerLoggerTest
public void isDebugEnabledHasStringBuilderTest()
{
when(transformerDebug.getStringBuilder()).thenReturn(new StringBuilder());
when(transformerConfig.getProperty("property.name")).thenReturn("5");
properties.setProperty("property.name", "5");
assertFalse(log.isDebugEnabled());
}
@Test
public void noEntriesTest()
{
when(transformerConfig.getProperty("property.name")).thenReturn("3");
properties.setProperty("property.name", "3");
assertArrayEquals(new String[] {}, log.getEntries(10));
}
@@ -194,7 +147,7 @@ public class TransformerLoggerTest
@Test
public void oneEntryTest()
{
when(transformerConfig.getProperty("property.name")).thenReturn("3");
properties.setProperty("property.name", "3");
log.debug("one");
assertArrayEquals(new String[] {"one"}, log.getEntries(10));
@@ -204,7 +157,7 @@ public class TransformerLoggerTest
// newest entry first
public void fiveEntryTest()
{
when(transformerConfig.getProperty("property.name")).thenReturn("3");
properties.setProperty("property.name", "3");
log.debug("one");
log.debug("two");
@@ -219,7 +172,7 @@ public class TransformerLoggerTest
// <= 0 indicates return all
public void limit0Test()
{
when(transformerConfig.getProperty("property.name")).thenReturn("3");
properties.setProperty("property.name", "3");
log.debug("one");
log.debug("two");
@@ -233,7 +186,7 @@ public class TransformerLoggerTest
// < 0 indicates return all - most current first
public void limitAllTest()
{
when(transformerConfig.getProperty("property.name")).thenReturn("3");
properties.setProperty("property.name", "3");
log.debug("one");
log.debug("two");
@@ -246,7 +199,7 @@ public class TransformerLoggerTest
// Returns latest
public void limit1Test()
{
when(transformerConfig.getProperty("property.name")).thenReturn("3");
properties.setProperty("property.name", "3");
log.debug("one");
log.debug("two");
@@ -258,7 +211,7 @@ public class TransformerLoggerTest
@Test
public void limitMoreThanEntriesTest()
{
when(transformerConfig.getProperty("property.name")).thenReturn("3");
properties.setProperty("property.name", "3");
log.debug("one");
log.debug("two");
@@ -272,8 +225,8 @@ public class TransformerLoggerTest
public void addTwoEntriesTest()
{
AtomicInteger numberOfMessagesToAdd = new AtomicInteger(2);
log = newLogger(numberOfMessagesToAdd, transformerDebug, transformerConfig);
when(transformerConfig.getProperty("property.name")).thenReturn("5");
log = newLogger(numberOfMessagesToAdd, transformerDebug, properties);
properties.setProperty("property.name", "5");
log.debug("one");
assertArrayEquals(new String[] {"one", "one"}, log.getEntries(10));
@@ -290,8 +243,8 @@ public class TransformerLoggerTest
{
// Same as addTwoEntriesTest but without hitting the buffer limit
AtomicInteger numberOfMessagesToAdd = new AtomicInteger(2);
log = newLogger(numberOfMessagesToAdd, transformerDebug, transformerConfig);
when(transformerConfig.getProperty("property.name")).thenReturn("10");
log = newLogger(numberOfMessagesToAdd, transformerDebug, properties);
properties.setProperty("property.name", "10");
log.debug("one");
log.debug("two");
log.debug("three");

View File

@@ -1,93 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2017 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import org.alfresco.repo.management.subsystems.ChildApplicationContextFactory;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.Properties;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
/**
* Test class for TransformerProperties. Currently just that The old oooDirect (OpenOffice) transformer settings
* are aliased to JodConverter settings if they are not set up.
*
* @author Alan Davis
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class TransformerPropertiesTest
{
@Mock
private ChildApplicationContextFactory subsystem;
private TransformerProperties transformerProperties;
private Properties globalProperties;
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
globalProperties = new Properties();
transformerProperties = new TransformerProperties(subsystem, globalProperties);
}
@Test
public void aliasOpenOfficeToJodTest()
{
when(subsystem.getProperty(Matchers.any())).thenReturn(null);
// Should be picked up as normal
globalProperties.setProperty("content.transformer.complex.JodConverter.Image.priority", "150");
// JodConverter value should override the OpenOffice value
globalProperties.setProperty("content.transformer.complex.OpenOffice.Image.extensions.docx.txt.supported", "true");
globalProperties.setProperty("content.transformer.complex.JodConverter.Image.extensions.docx.txt.supported", "false");
// Should be picked up as a JodConverter value
globalProperties.setProperty("content.transformer.complex.OpenOffice.Image.extensions.xlsb.txt.maxSourceSizeKBytes", "1024");
Set<String> propertyNames = transformerProperties.getPropertyNames();
assertEquals("The combined settings should be seen as only three entries", 3, propertyNames.size());
assertTrue(propertyNames.contains("content.transformer.complex.JodConverter.Image.priority"));
assertTrue(propertyNames.contains("content.transformer.complex.JodConverter.Image.extensions.docx.txt.supported"));
assertTrue(propertyNames.contains("content.transformer.complex.JodConverter.Image.extensions.xlsb.txt.maxSourceSizeKBytes"));
assertEquals("150", transformerProperties.getProperty("content.transformer.complex.JodConverter.Image.priority"));
assertEquals("false", transformerProperties.getProperty("content.transformer.complex.JodConverter.Image.extensions.docx.txt.supported"));
assertEquals("1024", transformerProperties.getProperty("content.transformer.complex.JodConverter.Image.extensions.xlsb.txt.maxSourceSizeKBytes"));
}
}

View File

@@ -1,479 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import static org.alfresco.repo.content.transform.TransformerPropertyNameExtractorTest.mockMimetypes;
import static org.alfresco.repo.content.transform.TransformerPropertyNameExtractorTest.mockProperties;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/**
* Test class for TransformerPropertyGetter.
*
* @author Alan Davis
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class TransformerPropertyGetterTest
{
@Mock
private TransformerProperties transformerProperties;
@Mock
private MimetypeService mimetypeService;
@Mock
ContentTransformerRegistry transformerRegistry;
@Mock
TransformerLog transformerLog;
@Mock
TransformerDebugLog transformerDebugLog;
private ContentTransformer transformer1;
private ContentTransformer transformer2;
private ContentTransformer transformer3;
private class DummyContentTransformer2 extends AbstractContentTransformer2 {
private final String name;
DummyContentTransformer2(String name)
{
this.name = name;
}
@Override
public String getName()
{
return name;
}
@Override
protected void transformInternal(ContentReader reader, ContentWriter writer,
TransformationOptions options) throws Exception
{
}};
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
transformer1 = new DummyContentTransformer2("transformer.transformer1");
transformer2 = new DummyContentTransformer2("transformer.transformer2");
transformer3 = new DummyContentTransformer2("transformer.transformer3");
when(transformerLog.getPropertyName()).thenReturn("transformer.log.entries");
when(transformerDebugLog.getPropertyName()).thenReturn("transformer.debug.entries");
when(transformerProperties.getDefaultProperties()).thenReturn(new Properties());
mockMimetypes(mimetypeService,
"application/pdf", "pdf",
"image/png", "png",
"text/plain", "txt");
}
public static void mockAllTransformers(ContentTransformerRegistry transformerRegistry, ContentTransformer... transformers)
{
List<ContentTransformer> allTransformers = new ArrayList<ContentTransformer>();
for (ContentTransformer transformer: transformers)
{
allTransformers.add(transformer);
}
when(transformerRegistry.getAllTransformers()).thenReturn(allTransformers);
}
@Test
public void logEntriesTest()
{
when(transformerLog.getPropertyAndValue(any(Properties.class))).thenReturn("# transformer.log.entries=0");
when(transformerDebugLog.getPropertyAndValue(any(Properties.class))).thenReturn("# transformer.debug.entries=0");
String actual = new TransformerPropertyGetter(false, transformerProperties,
mimetypeService, transformerRegistry, transformerLog, transformerDebugLog).toString();
assertEquals("# LOG and DEBUG history sizes\n" +
"# ===========================\n" +
"# Use small values as these logs are held in memory. 0 to disable.\n" +
"# transformer.log.entries=0\n" +
"# transformer.debug.entries=0\n", actual);
}
@Test
public void miscTest()
{
Properties defaultProperties = new Properties();
defaultProperties.setProperty("transformer.another", "aValue");
defaultProperties.setProperty("transformer.yet.another", "77");
defaultProperties.setProperty("transformer.strict.mimetype.check.whitelist.mimetypes", "application/eps;application/postscript;application/illustrator;application/pdf");
when(transformerProperties.getDefaultProperties()).thenReturn(defaultProperties);
mockProperties(transformerProperties,
"transformer.strict.mimetype.check.whitelist.mimetypes", "application/eps;application/postscript;application/illustrator;application/pdf", // same value
"transformer.another", "aNewValue"); // changed value
when(transformerLog.getPropertyAndValue(any(Properties.class))).thenReturn("# transformer.log.entries=0");
when(transformerDebugLog.getPropertyAndValue(any(Properties.class))).thenReturn("# transformer.debug.entries=0");
String actual = new TransformerPropertyGetter(false, transformerProperties,
mimetypeService, transformerRegistry, transformerLog, transformerDebugLog).toString();
assertEquals("# LOG and DEBUG history sizes\n" +
"# ===========================\n" +
"# Use small values as these logs are held in memory. 0 to disable.\n" +
"# transformer.log.entries=0\n" +
"# transformer.debug.entries=0\n" +
"\n" +
"# Miscellaneous settings\n" +
"# ======================\n" +
"transformer.another=aNewValue # default=aValue\n" +
"# transformer.strict.mimetype.check.whitelist.mimetypes=application/eps;application/postscript;application/illustrator;application/pdf\n" +
"# transformer.yet.another=77\n",
actual);
}
@Test
public void defaultTest()
{
mockProperties(transformerProperties,
"content.transformer.default.priority", "100",
"content.transformer.default.count", "0",
"content.transformer.default.maxPages.use.XXX", "88");
when(transformerLog.getPropertyAndValue(any(Properties.class))).thenReturn("# transformer.log.entries=0");
when(transformerDebugLog.getPropertyAndValue(any(Properties.class))).thenReturn("# transformer.debug.entries=0");
String actual = new TransformerPropertyGetter(false, transformerProperties,
mimetypeService, transformerRegistry, transformerLog, transformerDebugLog).toString();
assertEquals("# LOG and DEBUG history sizes\n" +
"# ===========================\n" +
"# Use small values as these logs are held in memory. 0 to disable.\n" +
"# transformer.log.entries=0\n" +
"# transformer.debug.entries=0\n" +
"\n" +
"# Default transformer settings\n" +
"# ============================\n" +
"content.transformer.default.count=0\n" +
"content.transformer.default.maxPages.use.XXX=88\n"+
"content.transformer.default.priority=100\n", actual);
}
@Test
public void defaultWithOverridesTest()
{
defaultWithOverridesTest(false,
"# LOG and DEBUG history sizes\n" +
"# ===========================\n" +
"# Use small values as these logs are held in memory. 0 to disable.\n" +
"# transformer.log.entries=0\n" +
"# transformer.debug.entries=0\n" +
"\n" +
"# Default transformer settings\n" +
"# ============================\n" +
"# content.transformer.default.count=0\n" +
"content.transformer.default.maxPages.use.XXX=88 # default=77\n"+
"content.transformer.default.priority=100 # default=111\n");
}
@Test
public void defaultWithOnlyOverridesTest()
{
defaultWithOverridesTest(true,
"# Default transformer settings\n" +
"# ============================\n" +
"content.transformer.default.maxPages.use.XXX=88 # default=77\n"+
"content.transformer.default.priority=100 # default=111\n");
}
private void defaultWithOverridesTest(boolean onlyChanges, String expected)
{
Properties defaultProperties = new Properties();
defaultProperties.setProperty("content.transformer.default.priority", "111");
defaultProperties.setProperty("content.transformer.default.count", "0");
defaultProperties.setProperty("content.transformer.default.maxPages.use.XXX", "77");
when(transformerProperties.getDefaultProperties()).thenReturn(defaultProperties);
mockProperties(transformerProperties,
"content.transformer.default.priority", "100",
"content.transformer.default.count", "0",
"content.transformer.default.maxPages.use.XXX", "88");
when(transformerLog.getPropertyAndValue(any(Properties.class))).thenReturn("# transformer.log.entries=0");
when(transformerDebugLog.getPropertyAndValue(any(Properties.class))).thenReturn("# transformer.debug.entries=0");
String actual = new TransformerPropertyGetter(onlyChanges, transformerProperties,
mimetypeService, transformerRegistry, transformerLog, transformerDebugLog).toString();
assertEquals(expected, actual);
}
@Test
public void allSuffixesTest()
{
mockProperties(transformerProperties,
"content.transformer.transformer1.timeoutMs", "1",
"content.transformer.transformer1.extensions.pdf.png.readLimitTimeMs", "2",
"content.transformer.transformer1.maxSourceSizeKBytes", "3",
"content.transformer.transformer1.extensions.pdf.png.readLimitKBytes", "4",
"content.transformer.transformer1.maxPages", "5",
"content.transformer.transformer1.extensions.pdf.png.pageLimit", "6",
"content.transformer.transformer1.maxPages.use.index", "12",
"content.transformer.transformer1.maxPages.use.webpreview", "13",
"content.transformer.transformer1.extensions.pdf.png.supported", "true",
"content.transformer.transformer1.priority", "7",
"content.transformer.transformer1.errorTime", "8",
"content.transformer.transformer2.time", "9",
"content.transformer.transformer2.count", "10",
"content.transformer.transformer1.thresholdCount", "11",
"content.transformer.transformer1.failover", "qwe|qaz",
"content.transformer.transformer1.pipeline", "qwe|pdf|qaz");
when(transformerRegistry.getTransformer("transformer.transformer1")).thenReturn(transformer1);
when(transformerRegistry.getTransformer("transformer.transformer2")).thenReturn(transformer2);
when(transformerRegistry.getTransformers()).thenReturn(Arrays.asList(new ContentTransformer[] {transformer1, transformer2}));
when(transformerLog.getPropertyAndValue(any(Properties.class))).thenReturn("# transformer.log.entries=0");
when(transformerDebugLog.getPropertyAndValue(any(Properties.class))).thenReturn("# transformer.debug.entries=0");
String actual = new TransformerPropertyGetter(false, transformerProperties,
mimetypeService, transformerRegistry, transformerLog, transformerDebugLog).toString();
assertEquals("# LOG and DEBUG history sizes\n" +
"# ===========================\n" +
"# Use small values as these logs are held in memory. 0 to disable.\n" +
"# transformer.log.entries=0\n" +
"# transformer.debug.entries=0\n" +
"\n" +
"# Transformers with configuration settings\n" +
"# ========================================\n" +
"# Commented out settings are hard coded values for information purposes\n" +
"\n" +
"# transformer1\n" +
"# ------------\n" +
"content.transformer.transformer1.pipeline=qwe|pdf|qaz\n" +
"content.transformer.transformer1.errorTime=8\n" +
"content.transformer.transformer1.failover=qwe|qaz\n" +
"content.transformer.transformer1.maxPages=5\n" +
"content.transformer.transformer1.maxPages.use.index=12\n"+
"content.transformer.transformer1.maxPages.use.webpreview=13\n"+
"content.transformer.transformer1.maxSourceSizeKBytes=3\n" +
"content.transformer.transformer1.priority=7\n" +
"content.transformer.transformer1.thresholdCount=11\n" +
"content.transformer.transformer1.timeoutMs=1\n" +
"content.transformer.transformer1.extensions.pdf.png.pageLimit=6\n" +
"content.transformer.transformer1.extensions.pdf.png.readLimitKBytes=4\n" +
"content.transformer.transformer1.extensions.pdf.png.readLimitTimeMs=2\n" +
"content.transformer.transformer1.extensions.pdf.png.supported=true\n" +
"\n" +
"# transformer2\n"+
"# ------------\n" +
"content.transformer.transformer2.count=10\n"+
"content.transformer.transformer2.time=9\n", actual);
}
@Test
public void normalTest()
{
normalTest(true);
}
@Test
// Output for a transformer that may only be used as part of another transformer
public void normalComponentTest()
{
normalTest(false);
}
private void normalTest(boolean isAvailable)
{
AbstractContentTransformer2 simple = new AbstractContentTransformer2() {
@Override
protected void transformInternal(ContentReader reader, ContentWriter writer,
TransformationOptions options) throws Exception
{
}};
simple.setBeanName("transformer.exampleSimple");
when(transformerRegistry.getAllTransformers()).thenReturn(Arrays.asList(new ContentTransformer[] {(ContentTransformer)simple}));
if (isAvailable)
{
when(transformerRegistry.getTransformers()).thenReturn(Arrays.asList(new ContentTransformer[] {(ContentTransformer)simple}));
}
when(transformerLog.getPropertyAndValue(any(Properties.class))).thenReturn("# transformer.log.entries=0");
when(transformerDebugLog.getPropertyAndValue(any(Properties.class))).thenReturn("# transformer.debug.entries=0");
String actual = new TransformerPropertyGetter(false, transformerProperties,
mimetypeService, transformerRegistry, transformerLog, transformerDebugLog).toString();
assertEquals("# LOG and DEBUG history sizes\n" +
"# ===========================\n" +
"# Use small values as these logs are held in memory. 0 to disable.\n" +
"# transformer.log.entries=0\n" +
"# transformer.debug.entries=0\n" +
"\n" +
"# Transformers without extra configuration settings\n" +
"# =================================================\n" +
"\n" +
"# exampleSimple\n" +
"# -------------\n" +
(isAvailable ? "" : "# content.transformer.exampleSimple.available=false\n"), actual);
}
@Test
public void complexTest()
{
complexTest(true);
}
@Test
// Output for a transformer that may only be used as part of another transformer
public void complexComponentTest()
{
complexTest(false);
}
private void complexTest(boolean isAvailable)
{
ComplexContentTransformer complex = new ComplexContentTransformer();
complex.setTransformers(Arrays.asList(new ContentTransformer[] {transformer1, transformer2, transformer3}));
complex.setIntermediateMimetypes(Arrays.asList(new String[] {"application/pdf", null}));
complex.setBeanName("transformer.examplePipeline");
complex.setMimetypeService(mimetypeService);
if (isAvailable)
{
when(transformerRegistry.getTransformers()).thenReturn(Arrays.asList(new ContentTransformer[] {complex, transformer1, transformer2, transformer3}));
}
else
{
when(transformerRegistry.getTransformers()).thenReturn(Arrays.asList(new ContentTransformer[] {transformer1, transformer2, transformer3}));
}
when(transformerRegistry.getAllTransformers()).thenReturn(Arrays.asList(new ContentTransformer[] {complex, transformer1, transformer2, transformer3}));
when(transformerLog.getPropertyAndValue(any(Properties.class))).thenReturn("# transformer.log.entries=0");
when(transformerDebugLog.getPropertyAndValue(any(Properties.class))).thenReturn("# transformer.debug.entries=0");
String actual = new TransformerPropertyGetter(false, transformerProperties,
mimetypeService, transformerRegistry, transformerLog, transformerDebugLog).toString();
assertEquals("# LOG and DEBUG history sizes\n" +
"# ===========================\n" +
"# Use small values as these logs are held in memory. 0 to disable.\n" +
"# transformer.log.entries=0\n" +
"# transformer.debug.entries=0\n" +
"\n" +
"# Transformers without extra configuration settings\n" +
"# =================================================\n" +
"\n" +
"# examplePipeline\n" +
"# ---------------\n" +
(isAvailable ? "" : "# content.transformer.examplePipeline.available=false\n") +
"# content.transformer.examplePipeline.pipeline=transformer1|pdf|transformer2||transformer3\n"+
"\n" +
"# transformer1\n" +
"# ------------\n" +
"\n" +
"# transformer2\n" +
"# ------------\n" +
"\n" +
"# transformer3\n" +
"# ------------\n", actual);
}
@Test
public void failoverTest()
{
failoverTest(true);
}
@Test
// Output for a failover transformer that may only be used as part of another transformer
public void failoverComponentTest()
{
failoverTest(false);
}
private void failoverTest(boolean isAvailable)
{
FailoverContentTransformer failover = new FailoverContentTransformer();
failover.setTransformers(Arrays.asList(new ContentTransformer[] {transformer1, transformer2}));
failover.setBeanName("transformer.exampleFailover");
if (isAvailable)
{
when(transformerRegistry.getTransformers()).thenReturn(Arrays.asList(new ContentTransformer[] {failover, transformer1, transformer2}));
}
else
{
when(transformerRegistry.getTransformers()).thenReturn(Arrays.asList(new ContentTransformer[] {transformer1, transformer2}));
}
when(transformerRegistry.getAllTransformers()).thenReturn(Arrays.asList(new ContentTransformer[] {failover, transformer1, transformer2}));
when(transformerLog.getPropertyAndValue(any(Properties.class))).thenReturn("# transformer.log.entries=0");
when(transformerDebugLog.getPropertyAndValue(any(Properties.class))).thenReturn("# transformer.debug.entries=0");
String actual = new TransformerPropertyGetter(false, transformerProperties,
mimetypeService, transformerRegistry, transformerLog, transformerDebugLog).toString();
assertEquals("# LOG and DEBUG history sizes\n" +
"# ===========================\n" +
"# Use small values as these logs are held in memory. 0 to disable.\n" +
"# transformer.log.entries=0\n" +
"# transformer.debug.entries=0\n" +
"\n" +
"# Transformers without extra configuration settings\n" +
"# =================================================\n" +
"\n" +
"# exampleFailover\n" +
"# ---------------\n" +
(isAvailable ? "" : "# content.transformer.exampleFailover.available=false\n") +
"# content.transformer.exampleFailover.failover=transformer1|transformer2\n" +
"\n" +
"# transformer1\n" +
"# ------------\n" +
"\n" +
"# transformer2\n" +
"# ------------\n", actual);
}
}

View File

@@ -1,721 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import static org.alfresco.repo.content.transform.TransformerConfig.ANY;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicInteger;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/**
* Test class for some of the regex methods and TransformerPropertyNameExtractor in general.
*
* @author Alan Davis
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
@SuppressWarnings("deprecation")
public class TransformerPropertyNameExtractorTest
{
@Mock
private TransformerProperties transformerProperties;
@Mock
private MimetypeService mimetypeService;
private Map<TransformerSourceTargetSuffixKey, TransformerSourceTargetSuffixValue> map;
private TestTransformerPropertyNameExtractor extractor;
private Collection<String> suffixes = Collections.singleton(".suffix");
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
extractor = new TestTransformerPropertyNameExtractor();
mockMimetypes(mimetypeService,
"application/pdf", "pdf",
"image/png", "png");
}
/**
* Mock up the responses from the subsystem so that it returns all the supplied
* property names and values.
* @param transformerProperties to mock the return values
* @param namesAndValues a sequence of property names and values.
* @throws IllegalStateException if there is not a value for every property
*/
public static void mockProperties(TransformerProperties transformerProperties, String... namesAndValues)
{
if (namesAndValues.length % 2 != 0)
{
// Not using IllegalArgumentException as this is thrown by classes under test
throw new java.lang.IllegalStateException("There should be a value for every property");
}
final Set<String> propertyNames = new TreeSet<String>();
for (int i=0; i < namesAndValues.length; i+=2)
{
String name = namesAndValues[i];
String value = namesAndValues[i+1];
if (name.startsWith(TransformerConfig.PREFIX))
{
propertyNames.add(name);
}
when(transformerProperties.getProperty(name)).thenReturn(value);
}
when(transformerProperties.getPropertyNames()).thenReturn(propertyNames);
}
/**
* Mock up the responses from the mimetypeService so that it:
* a) returns all the supplied mimetypes
* b) returns the extension given the mimetype
* c) returns the mimetype given the extension.
* @param mimetypeService mimetype service
* @param mimetypesAndExtensions sequence of mimetypes and extenstions.
* @throws IllegalStateException if there is not an extension for every mimetype
*/
public static void mockMimetypes(MimetypeService mimetypeService, String... mimetypesAndExtensions)
{
if (mimetypesAndExtensions.length % 2 != 0)
{
// Not using IllegalArgumentException as this is thrown by classes under test
throw new java.lang.IllegalStateException("There should be an extension for every mimetype");
}
final Set<String> allMimetypes = new HashSet<String>();
for (int i=0; i < mimetypesAndExtensions.length; i+=2)
{
allMimetypes.add(mimetypesAndExtensions[i]);
when(mimetypeService.getExtension(mimetypesAndExtensions[i])).thenReturn(mimetypesAndExtensions[i+1]);
when(mimetypeService.getMimetype(mimetypesAndExtensions[i+1])).thenReturn(mimetypesAndExtensions[i]);
}
when(mimetypeService.getMimetypes()).thenReturn(new ArrayList<String>(allMimetypes));
}
/**
* Asserts two List<String> are equal after they are sorted.
* @param msg to be included in the assertEquals call.
* @param expected list
* @param actual list
*/
public void assertEqualsLists(String msg, List<String> expected, List<String> actual)
{
if (expected.size() > 1)
{
Collections.sort(expected);
}
if (actual.size() > 1)
{
Collections.sort(actual);
}
assertEquals(msg, expected, actual);
}
@Test
public void textSplitExt()
{
String[][] values = new String[][]
{
{"AAA.BBB", "AAA", "BBB"},
{"AA\\.BB.CC\\.DD\\.EE", "AA.BB", "CC.DD.EE"},
};
for (String[] args: values)
{
String input = args[0];
String expectedSource = args[1];
String expectedTarget = args[2];
String[] sourceTarget = extractor.splitExt(input);
assertEquals("length", sourceTarget.length, 2);
assertEquals("source", expectedSource, sourceTarget[0]);
assertEquals("target", expectedTarget, sourceTarget[1]);
}
}
@Test
public void testPattern()
{
assertTrue( extractor.pattern("ABC").matcher("ABC").matches());
assertFalse(extractor.pattern("ABC").matcher("x").matches());
assertFalse(extractor.pattern("ABC").matcher("ABCD").matches());
assertFalse(extractor.pattern("ABC").matcher("DABC").matches());
assertTrue( extractor.pattern("*B").matcher("B").matches());
assertTrue( extractor.pattern("*B").matcher("xxB").matches());
assertFalse(extractor.pattern("*B").matcher("xxBx").matches());
assertFalse(extractor.pattern("B*").matcher("").matches());
assertTrue( extractor.pattern("C*").matcher("C").matches());
assertTrue( extractor.pattern("C*").matcher("CxxB").matches());
assertFalse(extractor.pattern("C*").matcher("xxBx").matches());
assertTrue(extractor.pattern("D*E*F").matcher("DEF").matches());
assertTrue(extractor.pattern("D*E*F").matcher("DxxExxF").matches());
assertTrue(extractor.pattern("D*E*F").matcher("D*E*F").matches());
assertTrue( extractor.pattern("A+").matcher("A+").matches());
assertFalse(extractor.pattern("A+").matcher("AA").matches());
assertFalse(extractor.pattern("A+").matcher("AAA").matches());
assertFalse(extractor.pattern("A+").matcher("A+A").matches());
}
@Test
public void getMatchingExtensionsFromMimetypesTest()
{
mockMimetypes(mimetypeService,
"mimetypeAx", "aExt",
"mimetypeBx", "bExt",
"mimetypeC", "cExt");
String[][] data = new String[][]
{
{"*C", "cExt"},
{"*ypeAx", "aExt"},
{"mimetype*x", "aExt bExt"},
{"mimetypeBx", "bExt"},
{"*mime*", "aExt bExt cExt"},
{"*", ANY}, // special meaning on its own
{"", null},
{"bad", null}
};
for (String[] entry: data)
{
List<String> expected = entry[1] == null ? Collections.<String>emptyList() : Arrays.asList(entry[1].split(" "));
List<String> actual = extractor.getMatchingExtensionsFromMimetypes(entry[0], mimetypeService);
assertEqualsLists("getMatchingExtensionsFromMimetypes("+entry[0]+")", expected, actual);
}
}
@Test
public void getMatchingExtensionsFromExtensionsTest()
{
mockMimetypes(mimetypeService,
"mimetypeAx", "aExt",
"mimetypeBx", "bExt",
"mimetypeC", "cExt");
String[][] data = new String[][]
{
{"c*", "cExt"},
{"*a*", "aExt"},
{"a*xt", "aExt"},
{"*Ext", "aExt bExt cExt"},
{"*t", "aExt bExt cExt"},
{"*", ANY}, // special meaning on its own
{"", null},
{"bad", null}
};
for (String[] entry: data)
{
List<String> expected = entry[1] == null ? Collections.<String>emptyList() : Arrays.asList(entry[1].split(" "));
List<String> actual = extractor.getMatchingExtensionsFromExtensions(entry[0], mimetypeService);
assertEqualsLists("getMatchingExtensionsFromMimetypes("+entry[0]+")", expected, actual);
}
}
@Test
public void transformerSourceTargetSuffixKeyHashCodeEqualsTest()
{
// Test data
String[][] data = new String[][]
{
{"transformerName", "sourceExt", "targetExt", ".suffix", null},
{"XXXXXXXXXXXXXXX", "sourceExt", "targetExt", ".suffix", null},
{"transformerName", "XXXXXXXXX", "targetExt", ".suffix", null},
{"transformerName", "sourceExt", "XXXXXXXXX", ".suffix", null},
{"transformerName", "sourceExt", "targetExt", ".XXXXXX", null},
{"transformerName", "sourceExt", "targetExt", ".suffix", "index"},
{"XXXXXXXXXXXXXXX", "sourceExt", "targetExt", ".suffix", "index"},
{"transformerName", "XXXXXXXXX", "targetExt", ".suffix", "index"},
{"transformerName", "sourceExt", "XXXXXXXXX", ".suffix", "index"},
{"transformerName", "sourceExt", "targetExt", ".XXXXXX", "index"}
};
for (int i=data.length+1; i >= 0; i--)
{
// Check properties are set
Object a = i == data.length+1 ? "" : i == data.length ? null : new TransformerSourceTargetSuffixKey(data[i][0], data[i][1], data[i][2], data[i][3], data[i][4]);
if (a instanceof TransformerSourceTargetSuffixKey)
{
assertEquals(i+" transformerName", ((TransformerSourceTargetSuffixKey)a).transformerName, data[i][0]);
assertEquals(i+" sourceExt", ((TransformerSourceTargetSuffixKey)a).sourceExt, data[i][1]);
assertEquals(i+" targetExt", ((TransformerSourceTargetSuffixKey)a).targetExt, data[i][2]);
assertEquals(i+" suffix", ((TransformerSourceTargetSuffixKey)a).suffix, data[i][3]);
assertEquals(i+" use", ((TransformerSourceTargetSuffixKey)a).use, data[i][4]);
}
// Try out the hashCode and equals methods
for (int j=data.length+1; j >= 0; j--)
{
Object b = j == data.length+1 ? "" : j == data.length ? null : new TransformerSourceTargetSuffixKey(data[j][0], data[j][1], data[j][2], data[j][3], data[j][4]);
if (a != null)
{
if (i == j)
{
assertTrue( i+" "+j+" equals", a.equals(b));
assertEquals(i+" "+j+" hashCode", a.hashCode(), b.hashCode());
}
else
{
assertFalse( i+" "+j+" equals ", a.equals(b));
if (b != null)
{
assertFalse(i+" "+j+" hashCode", a.hashCode() == b.hashCode());
}
}
}
}
}
}
@Test
public void transformerSourceTargetSuffixValueHashCodeEqualsTest()
{
mockMimetypes(mimetypeService,
"sourceMimetype", "sourceExt",
"sourceXXXXXXXX", "sourceXXX",
"targetMimetype", "targetExt",
"targetXXXXXXXX", "targetXXX");
// Test data
String[][] data = new String[][]
{
{"transformerName", "sourceExt", "targetExt", ".suffix", null, "value", "sourceMimetype", "targetMimetype"},
{"XXXXXXXXXXXXXXX", "sourceExt", "targetExt", ".suffix", null, "value", "sourceMimetype", "targetMimetype"},
{"transformerName", "sourceXXX", "targetExt", ".suffix", null, "value", "sourceXXXXXXXX", "targetMimetype"},
{"transformerName", "sourceExt", "targetXXX", ".suffix", null, "value", "sourceMimetype", "targetXXXXXXXX"},
{"transformerName", "sourceExt", "targetExt", ".XXXXXX", null, "value", "sourceMimetype", "targetMimetype"},
{"transformerName", "sourceExt", "targetExt", ".suffix", null, "XXXXX", "sourceMimetype", "targetMimetype"},
{"transformerName", "sourceExt", "targetExt", ".suffix", "index", "value", "sourceMimetype", "targetMimetype"},
{"XXXXXXXXXXXXXXX", "sourceExt", "targetExt", ".suffix", "index", "value", "sourceMimetype", "targetMimetype"},
{"transformerName", "sourceXXX", "targetExt", ".suffix", "index", "value", "sourceXXXXXXXX", "targetMimetype"},
{"transformerName", "sourceExt", "targetXXX", ".suffix", "index", "value", "sourceMimetype", "targetXXXXXXXX"},
{"transformerName", "sourceExt", "targetExt", ".XXXXXX", "index", "value", "sourceMimetype", "targetMimetype"},
{"transformerName", "sourceExt", "targetExt", ".suffix", "index", "XXXXX", "sourceMimetype", "targetMimetype"}
};
for (int i=data.length+1; i >= 0; i--)
{
// Check properties are set
Object a = i == data.length+1 ? "" : i == data.length ? null : new TransformerSourceTargetSuffixValue(data[i][0], data[i][1], data[i][2], data[i][3], data[i][4], data[i][5], mimetypeService);
if (a instanceof TransformerSourceTargetSuffixValue)
{
assertEquals(i+" transformerName", data[i][0], ((TransformerSourceTargetSuffixValue)a).transformerName);
assertEquals(i+" sourceExt", data[i][1], ((TransformerSourceTargetSuffixValue)a).sourceExt);
assertEquals(i+" targetExt", data[i][2], ((TransformerSourceTargetSuffixValue)a).targetExt);
assertEquals(i+" suffix", data[i][3], ((TransformerSourceTargetSuffixValue)a).suffix);
assertEquals(i+" use", data[i][4], ((TransformerSourceTargetSuffixValue)a).use);
assertEquals(i+" value", data[i][5], ((TransformerSourceTargetSuffixValue)a).value);
assertEquals(i+" sourceMimetype", data[i][6], ((TransformerSourceTargetSuffixValue)a).sourceMimetype);
assertEquals(i+" targetMimetype", data[i][7], ((TransformerSourceTargetSuffixValue)a).targetMimetype);
assertEquals(i+" key",
new TransformerSourceTargetSuffixKey(data[i][0], data[i][1], data[i][2], data[i][3], data[i][4]),
((TransformerSourceTargetSuffixValue)a).key());
}
// Try out the hashCode and equals methods
for (int j=data.length+1; j >= 0; j--)
{
Object b = j == data.length+1 ? "" : j == data.length ? null : new TransformerSourceTargetSuffixValue(data[j][0], data[j][1], data[j][2], data[j][3], data[j][4], data[j][5], mimetypeService);
if (a != null)
{
if (i == j)
{
assertTrue( i+" "+j+" equals", a.equals(b));
assertEquals(i+" "+j+" hashCode", a.hashCode(), b.hashCode());
}
else
{
assertFalse( i+" "+j+" equals ", a.equals(b));
if (b != null)
{
assertFalse(i+" "+j+" hashCode", a.hashCode() == b.hashCode());
}
}
}
}
}
}
@Test
public void transformerSourceTargetSuffixValuetoStringTest()
{
mockMimetypes(mimetypeService,
"sourceMimetype", "sourceExt",
"targetMimetype", "targetExt");
// Test data
String[][] data = new String[][]
{
{"transformerName", "sourceExt", "targetExt", ".suffix", null, "value", "transformerName.extensions.sourceExt.targetExt.suffix=value"},
{"transformerName", "sourceExt", "targetExt", ".suffix", "index", "value", "transformerName.extensions.sourceExt.targetExt.suffix.use.index=value"},
{"transformerName", ANY, ANY, ".suffix", null, "value", "transformerName.suffix=value"}
};
for (int i=data.length-1; i >= 0; i--)
{
// Check properties are set
TransformerSourceTargetSuffixValue a = new TransformerSourceTargetSuffixValue(data[i][0], data[i][1], data[i][2], data[i][3], data[i][4], data[i][5], mimetypeService);
assertEquals(i+" toString", data[i][6], a.toString());
}
}
@Test
public void getPropertyTest()
{
mockMimetypes(mimetypeService,
"sourceMimetype", "sourceExt",
"sourceAAAAAAAA", "sourceAAA",
"targetMimetype", "targetExt");
// Test data
String[][] data = new String[][]
{
{"transformerName", "sourceExt", "targetExt", ".suffix", null, "value1"},
{"transformerName", null, null, ".suffix", null, "value2"},
{"transformerName", ANY, ANY, ".suffix", null, "value2"},
{"transformerName", "sourceAAA", "targetExt", ".suffix", null, "value3"},
{"transformerXXXX", null, null, ".suffix", null, null},
{"transformerName", "sourceExt", "targetExt", ".suffix", "index", "value4"},
{"transformerName", null, null, ".suffix", "index", "value5"},
{"transformerName", ANY, ANY, ".suffix", "index", "value5"},
{"transformerName", "sourceAAA", "targetExt", ".suffix", "index", "value6"},
{"transformerXXXX", null, null, ".suffix", "index", null}
};
// Populate the test Map
Map<TransformerSourceTargetSuffixKey, TransformerSourceTargetSuffixValue> transformerSourceTargetSuffixValues =
new HashMap<TransformerSourceTargetSuffixKey, TransformerSourceTargetSuffixValue>();
for (int i=data.length-1; i >= 0; i--)
{
TransformerSourceTargetSuffixValue keyValue = new TransformerSourceTargetSuffixValue(data[i][0], data[i][1], data[i][2], data[i][3], data[i][4], data[i][5], mimetypeService);
transformerSourceTargetSuffixValues.put(keyValue.key(), keyValue);
}
// Check we can return the values including the last one which was not added so has a null value
for (int i=data.length-1; i >= 0; i--)
{
assertEquals(i+" getProperty", data[i][5], extractor.getProperty(data[i][0], data[i][1], data[i][2], data[i][3], data[i][4], transformerSourceTargetSuffixValues));
}
}
@Test
public void transformerWideTest()
{
mockProperties(transformerProperties, "content.transformer.abc.suffix", "value1");
extractor = new TestTransformerPropertyNameExtractor();
map = extractor.getTransformerSourceTargetValuesMap(suffixes, true, true, false, transformerProperties, mimetypeService);
assertEquals("value1", extractor.getProperty("transformer.abc", null, null, ".suffix", null, map));
}
@Test
public void excludeSummaryTest()
{
mockProperties(transformerProperties, "content.transformer.abc.suffix", "value1");
extractor = new TestTransformerPropertyNameExtractor();
map = extractor.getTransformerSourceTargetValuesMap(suffixes, false, true, false, transformerProperties, mimetypeService);
assertEquals(null, extractor.getProperty("transformer.abc", null, null, ".suffix", null, map));
}
@Test
public void extensionTest()
{
mockProperties(transformerProperties, "content.transformer.abc.extensions.pdf.png.suffix", "value1");
extractor = new TestTransformerPropertyNameExtractor();
map = extractor.getTransformerSourceTargetValuesMap(suffixes, true, true, false, transformerProperties, mimetypeService);
assertEquals("value1", extractor.getProperty("transformer.abc", "pdf", "png", ".suffix", null, map));
}
@Test
public void excludeExtensionsTest()
{
mockProperties(transformerProperties, "content.transformer.abc.extensions.pdf.png.suffix", "value1");
extractor = new TestTransformerPropertyNameExtractor();
map = extractor.getTransformerSourceTargetValuesMap(suffixes, true, false, false, transformerProperties, mimetypeService);
assertEquals(null, extractor.getProperty("transformer.abc", "pdf", "png", ".suffix", null, map));
}
@Test
public void mimetypeTest()
{
mockProperties(transformerProperties, "content.transformer.abc.mimetypes.application/pdf.image/png.suffix", "value1");
extractor = new TestTransformerPropertyNameExtractor();
map = extractor.getTransformerSourceTargetValuesMap(suffixes, true, true, false, transformerProperties, mimetypeService);
assertEquals("value1", extractor.getProperty("transformer.abc", "pdf", "png", ".suffix", null, map));
}
@Test
public void multipleSuffix1Test()
{
suffixes = Arrays.asList(new String[] {".suffix1", ".suffix2", ".suffix3", ".suffix4"});
mockProperties(transformerProperties, "content.transformer.abc.suffix1", "value1");
extractor = new TestTransformerPropertyNameExtractor();
map = extractor.getTransformerSourceTargetValuesMap(suffixes, true, true, false, transformerProperties, mimetypeService);
assertEquals("value1", extractor.getProperty("transformer.abc", null, null, ".suffix1", null, map));
}
@Test
public void multipleSuffix4Test()
{
suffixes = Arrays.asList(new String[] {".suffix1", ".suffix2", ".suffix3", ".suffix4"});
mockProperties(transformerProperties, "content.transformer.abc.suffix4", "value1");
extractor = new TestTransformerPropertyNameExtractor();
map = extractor.getTransformerSourceTargetValuesMap(suffixes, true, true, false, transformerProperties, mimetypeService);
assertEquals("value1", extractor.getProperty("transformer.abc", null, null, ".suffix4", null, map));
}
@Test
public void noPrefixTest()
{
mockProperties(transformerProperties, "the.cat.sat", "on the mat");
extractor = new TestTransformerPropertyNameExtractor();
assertEquals(0, extractor.getTransformerSourceTargetValues(suffixes, true, false, transformerProperties, mimetypeService).size());
}
@Test
public void multipleValuesTest()
{
suffixes = TransformerConfig.LIMIT_SUFFIXES;
mockProperties(transformerProperties,
"content.transformer.abc.maxSourceSizeKBytes", "1",
"content.transformer.abc.timeoutMs", "2",
"content.transformer.abc.extensions.pdf.png.maxPages", "3",
"content.transformer.x.y.mimetypes.application/pdf.image/png.maxPages", "4",
"content.transformer.abc.maxSourceSizeKBytes.use.index", "5",
"content.transformer.abc.timeoutMs.use.index", "6",
"content.transformer.abc.extensions.pdf.png.maxPages.use.index", "7",
"content.transformer.x.y.mimetypes.application/pdf.image/png.maxPages.use.index", "8");
extractor = new TestTransformerPropertyNameExtractor();
map = extractor.getTransformerSourceTargetValuesMap(suffixes, true, true, false, transformerProperties, mimetypeService);
assertEquals("1", extractor.getProperty("transformer.abc", null, null, ".maxSourceSizeKBytes", null, map));
assertEquals("2", extractor.getProperty("transformer.abc", null, null, ".timeoutMs", null, map));
assertEquals("3", extractor.getProperty("transformer.abc", "pdf", "png", ".maxPages", null, map));
assertEquals("4", extractor.getProperty("transformer.x.y", "pdf", "png", ".maxPages", null, map));
assertEquals(null, extractor.getProperty("transformer.abc", null, null, ".maxSourceSizeKBytes", "index", map));
assertEquals(null, extractor.getProperty("transformer.abc", null, null, ".timeoutMs", "index", map));
assertEquals(null, extractor.getProperty("transformer.abc", "pdf", "png", ".maxPages", "index", map));
assertEquals(null, extractor.getProperty("transformer.x.y", "pdf", "png", ".maxPages", "index", map));
map = extractor.getTransformerSourceTargetValuesMap(suffixes, true, true, true, transformerProperties, mimetypeService);
assertEquals("1", extractor.getProperty("transformer.abc", null, null, ".maxSourceSizeKBytes", null, map));
assertEquals("2", extractor.getProperty("transformer.abc", null, null, ".timeoutMs", null, map));
assertEquals("3", extractor.getProperty("transformer.abc", "pdf", "png", ".maxPages", null, map));
assertEquals("4", extractor.getProperty("transformer.x.y", "pdf", "png", ".maxPages", null, map));
assertEquals("5", extractor.getProperty("transformer.abc", null, null, ".maxSourceSizeKBytes", "index", map));
assertEquals("6", extractor.getProperty("transformer.abc", null, null, ".timeoutMs", "index", map));
assertEquals("7", extractor.getProperty("transformer.abc", "pdf", "png", ".maxPages", "index", map));
assertEquals("8", extractor.getProperty("transformer.x.y", "pdf", "png", ".maxPages", "index", map));
}
@Test
public void wildcardTest()
{
suffixes = TransformerConfig.LIMIT_SUFFIXES;
mockProperties(transformerProperties,
"content.transformer.abc.extensions.p*.*g.maxPages", "value");
extractor = new TestTransformerPropertyNameExtractor();
map = extractor.getTransformerSourceTargetValuesMap(suffixes, true, true, false, transformerProperties, mimetypeService);
assertEquals("pdf,png to png", 2, map.size());
assertEquals("value", extractor.getProperty("transformer.abc", "pdf", "png", ".maxPages", null, map));
assertEquals("value", extractor.getProperty("transformer.abc", "png", "png", ".maxPages", null, map));
}
@Test
public void mimetypeWinsOverExtensionFirstTest()
{
// Extension property is provided first
suffixes = TransformerConfig.LIMIT_SUFFIXES;
mockProperties(transformerProperties,
"content.transformer.abc.extensions.pdf.png.maxPages", "extension",
"content.transformer.abc.mimetypes.application/pdf.image/png.maxPages", "mimetype");
extractor = new TestTransformerPropertyNameExtractor();
map = extractor.getTransformerSourceTargetValuesMap(suffixes, true, true, false, transformerProperties, mimetypeService);
assertEquals("mimetype", extractor.getProperty("transformer.abc", "pdf", "png", ".maxPages", null, map));
}
@Test
public void mimetypeWinsOverExtensionSecondTest()
{
// Extension property is provided second
suffixes = TransformerConfig.LIMIT_SUFFIXES;
mockProperties(transformerProperties,
"content.transformer.abc.mimetypes.application/pdf.image/png.maxPages", "mimetype",
"content.transformer.abc.extensions.pdf.png.maxPages", "extension");
extractor = new TestTransformerPropertyNameExtractor();
map = extractor.getTransformerSourceTargetValuesMap(suffixes, true, true, false, transformerProperties, mimetypeService);
assertEquals("mimetype", extractor.getProperty("transformer.abc", "pdf", "png", ".maxPages", null, map));
}
@Test
public void callsToHandlePropertyTest()
{
final String[][] data = new String[][]
{ // Must sort the property names
{"content.transformer.abc.extensions.pdf.png.suffix", "value2", "transformer.abc", ".extensions.", "pdf", "png", ".suffix", null},
{"content.transformer.abc.extensions.pdf.png.suffix.use.index", "value2", "transformer.abc", ".extensions.", "pdf", "png", ".suffix", "index"},
{"content.transformer.abc.mimetypes.application/pdf.image/png.suffix", "value2", "transformer.abc", ".mimetypes.", "application/pdf", "image/png", ".suffix", null},
{"content.transformer.abc.mimetypes.application/pdf.image/png.suffix.use.index", "value2", "transformer.abc", ".mimetypes.", "application/pdf", "image/png", ".suffix", "index"},
{"content.transformer.abc.suffix", "value1", "transformer.abc", null, null, null, ".suffix", null},
{"content.transformer.abc.suffix.use.index", "value1", "transformer.abc", null, null, null, ".suffix", "index"},
{"xxxx.transformer.abc.extensions.pdf.png.suffix", "value2", null},
{"xxxx.transformer.abc.extensions.pdf.png.suffix.use.index", "value2", null}
};
List<String> properties = new ArrayList<String>();
final Set<String> suffixes = new HashSet<String>();
for (String[] entry: data)
{
properties.add(entry[0]);
properties.add(entry[1]);
if (entry.length == 8)
{
suffixes.add(entry[6]);
}
}
mockProperties(transformerProperties, properties.toArray(new String[properties.size()]));
final AtomicInteger i = new AtomicInteger(0);
extractor = new TestTransformerPropertyNameExtractor()
{
protected void handleProperty(String transformerName, String separator,
String firstExpression, String secondExpression, String suffix, String use, String value,
String propertyName,
Map<TransformerSourceTargetSuffixKey, TransformerSourceTargetSuffixValue> transformerSourceTargetSuffixValues, MimetypeService mimetypeService)
{
// Ignore non transformer properties
int j;
do
{
j = i.getAndIncrement();
} while(j < data.length && data[j].length != 8);
if (j < data.length)
{
assertEquals(j+" transformerName", data[j][2], transformerName);
assertEquals(j+" separator", data[j][3], separator);
assertEquals(j+" firstExpression", data[j][4], firstExpression);
assertEquals(j+" secondExpression", data[j][5], secondExpression);
assertEquals(j+" suffix", data[j][6], suffix);
assertEquals(j+" use", data[j][7], use);
assertEquals(j+" value", data[j][1], value);
assertEquals(j+" propertyName", data[j][0], propertyName);
}
while(j+1 < data.length && data[j+1].length < 8)
{
j = i.getAndIncrement();
}
super.handleProperty(transformerName, separator, firstExpression, secondExpression, suffix, use, value, propertyName, transformerSourceTargetSuffixValues, mimetypeService);
}
};
extractor.callGetTransformerSourceTargetValuesMap(suffixes, true, transformerProperties, mimetypeService);
assertEquals("counter", 8, i.get());
}
}
@Deprecated
@SuppressWarnings("deprecation")
class TestTransformerPropertyNameExtractor extends TransformerPropertyNameExtractor
{
public Collection<TransformerSourceTargetSuffixValue> callGetTransformerSourceTargetValues(Collection<String> suffixes,
boolean includeSummary, TransformerProperties transformerProperties, MimetypeService mimetypeService)
{
return getTransformerSourceTargetValues(suffixes, includeSummary, false, transformerProperties, mimetypeService);
}
public Map<TransformerSourceTargetSuffixKey, TransformerSourceTargetSuffixValue> callGetTransformerSourceTargetValuesMap(Collection<String> suffixes,
boolean includeSummary, TransformerProperties transformerProperties, MimetypeService mimetypeService)
{
return getTransformerSourceTargetValuesMap(suffixes, includeSummary, true, true, transformerProperties, mimetypeService);
}
};

View File

@@ -1,739 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import static org.junit.Assert.assertEquals;
import static org.alfresco.repo.content.transform.TransformerPropertyNameExtractorTest.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.alfresco.service.cmr.repository.ContentIOException;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.MimetypeService;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/**
* Tests TransformerPropertySetter.
*
* @author Alan Davis
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class TransformerPropertySetterTest
{
@Mock
private TransformerProperties transformerProperties;
@Mock
private MimetypeService mimetypeService;
@Mock
private ContentTransformerRegistry transformerRegistry;
private TransformerPropertySetter setter;
private Properties properties;
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
mockAllTransformers(transformerRegistry, "abc", "complex.PDF.Image", "transformer1", "transformer2", "transformer3");
mockMimetypes(mimetypeService,
"application/pdf", "pdf",
"image/png", "png");
setter = new TransformerPropertySetter(transformerProperties, mimetypeService, transformerRegistry);
properties = new Properties();
when(transformerProperties.getDefaultProperties()).thenReturn(properties);
}
public static void mockAllTransformers(ContentTransformerRegistry transformerRegistry, String... shortTransformerNames)
{
List<ContentTransformer> allTransformers = new ArrayList<ContentTransformer>();
for (String shortTransformerName: shortTransformerNames)
{
allTransformers.add(new DummyContentTransformer(TransformerConfig.TRANSFORMER+shortTransformerName));
}
when(transformerRegistry.getAllTransformers()).thenReturn(allTransformers);
}
private Map<String, String> expectedProperties(String... namesAndValues)
{
Map<String, String> expected = new HashMap<String, String>();
String name = null;
for (String string: namesAndValues)
{
if (name == null)
{
name = string;
}
else
{
expected.put(name, string);
name = null;
}
}
return expected;
}
private Collection<String> expectedNames(String... names)
{
Set<String> expected = new HashSet<String>();
expected.addAll(Arrays.asList(names));
return expected;
}
@Test
public void simpleTest()
{
int count = setter.setProperties("transformer.log.entries=12");
verify(transformerProperties).setProperties(expectedProperties("transformer.log.entries", "12"));
assertEquals("Added count", 1, count);
}
@Test
public void debugLineSplitTest()
{
int count = setter.setProperties(
"transformer.log.entries=12\n" +
"transformer.debug.entries=23");
verify(transformerProperties).setProperties(expectedProperties(
"transformer.debug.entries", "23",
"transformer.log.entries", "12"));
assertEquals("Added count", 2, count);
}
@Test
public void mixedCaseTest()
{
setter.setProperties("Transformer.LOG.entries=12");
verify(transformerProperties).setProperties(expectedProperties("Transformer.LOG.entries", "12"));
}
@Test
public void debugLogSizeTest()
{
setter.setProperties(
"transformer.log.entries=12\n" +
"transformer.debug.entries=-1");
verify(transformerProperties).setProperties(expectedProperties(
"transformer.debug.entries", "-1",
"transformer.log.entries", "12"));
}
@Test
public void mimetypeListTest()
{
setter.setProperties(
"transformer.strict.mimetype.check.whitelist.mimetypes=image/png;application/pdf");
verify(transformerProperties).setProperties(expectedProperties(
"transformer.strict.mimetype.check.whitelist.mimetypes", "image/png;application/pdf"));
}
public void mimetypeListBlankTest()
{
setter.setProperties(
"transformer.strict.mimetype.check.whitelist.mimetypes=");
verify(transformerProperties).setProperties(expectedProperties(
"transformer.strict.mimetype.check.whitelist.mimetypes", ""));
}
@Test(expected=IllegalArgumentException.class)
public void mimetypeListUnevenTest()
{
setter.setProperties(
"transformer.strict.mimetype.check.whitelist.mimetypes=image/png");
}
@Test(expected=IllegalArgumentException.class)
public void mimetypeListBadDeclaredTypeTest()
{
setter.setProperties(
"transformer.strict.mimetype.check.whitelist.mimetypes=BAD;image/png");
}
public void mimetypeListBadDetectedTypeTest()
{
// Tika may detect a mimetype we have not registered, so let it through
setter.setProperties(
"transformer.strict.mimetype.check.whitelist.mimetypes=image/png;BAD");
}
@Test(expected=IllegalArgumentException.class)
public void badPropertyNameTest()
{
setter.setProperties("trans.bad=11");
}
@Test(expected=IllegalArgumentException.class)
public void duplicateNameTest()
{
setter.setProperties(
"transformer.log.entries=12\n" +
"transformer.log.entries=-1");
}
@Test(expected=IllegalArgumentException.class)
public void badIntegerTest()
{
setter.setProperties("transformer.debug.entries=--1");
}
@Test(expected=IllegalArgumentException.class)
public void badInteger2Test()
{
setter.setProperties("transformer.debug.entries=1a");
}
@Test(expected=IllegalArgumentException.class)
public void noValueEqualsTest()
{
// setProiperties must have an =
setter.setProperties("transformer.debug.entries");
}
@Test
public void booleanTest()
{
setter.setProperties("content.transformer.complex.PDF.Image.extensions.pdf.png.supported=TruE");
verify(transformerProperties).setProperties(expectedProperties(
"content.transformer.complex.PDF.Image.extensions.pdf.png.supported", "TruE"));
}
@Test(expected=IllegalArgumentException.class)
public void badBooleanTest()
{
setter.setProperties("content.transformer.complex.PDF.Image.extensions.pdf.png.supported=yes");
}
@Test
public void defaultTransformerTest()
{
setter.setProperties(
"content.transformer.default.priority=100\n"+
"content.transformer.default.thresholdCount=3\n"+
"content.transformer.default.time=0\n"+
"content.transformer.default.count=100000\n"+
"content.transformer.default.errorTime=120000\n"+
"content.transformer.default.timeoutMs=120000\n"+
"content.transformer.default.readLimitTimeMs=-1\n"+
"content.transformer.default.maxSourceSizeKBytes=-1\n"+
"content.transformer.default.readLimitKBytes=-1\n"+
"content.transformer.default.pageLimit=-1\n"+
"content.transformer.default.maxPages=-1");
verify(transformerProperties).setProperties(expectedProperties(
"content.transformer.default.priority", "100",
"content.transformer.default.thresholdCount", "3",
"content.transformer.default.time", "0",
"content.transformer.default.count", "100000",
"content.transformer.default.errorTime", "120000",
"content.transformer.default.timeoutMs", "120000",
"content.transformer.default.readLimitTimeMs", "-1",
"content.transformer.default.maxSourceSizeKBytes", "-1",
"content.transformer.default.readLimitKBytes", "-1",
"content.transformer.default.pageLimit", "-1",
"content.transformer.default.maxPages", "-1"));
}
@Test
public void defaultUseTransformerTest()
{
setter.setProperties(
"content.transformer.default.maxSourceSizeKBytes.use.doclib=67");
verify(transformerProperties).setProperties(expectedProperties(
"content.transformer.default.maxSourceSizeKBytes.use.doclib", "67"));
}
@Test
public void commentAndWhiteSpaceTest()
{
setter.setProperties(
"# hi mum\n"+
"content.transformer.default.priority=100\n"+
" content.transformer.default.thresholdCount=3 \n"+
"\t content.transformer.default.time=0\n"+
"\t\t \t content.transformer.default.count=100000 # another comment\n"+
"#\n"+
" \n"+
"\n"+
"content.transformer.default.errorTime=120000\n");
verify(transformerProperties).setProperties(expectedProperties(
"content.transformer.default.priority", "100",
"content.transformer.default.thresholdCount", "3",
"content.transformer.default.time", "0",
"content.transformer.default.count", "100000",
"content.transformer.default.errorTime", "120000"));
}
@Test
public void fixJConsolesMissingNewlinesTest()
{
// Variable names based on what JConsole does to newlines and what fixJConsolesMissingNewlines does to spaces
String nl2nl = "@";
String nl2space = "~";
String space2nl = "%";
String data =
"transformer.log.entries=12"+nl2nl+
"transformer.log.entries=-1"+nl2space+
"# a line of comment"+nl2nl+
"content.transformer.default.priority=100"+nl2space+
"#"+nl2space+ // Will discard the next property, but this is still best we can do
"content.transformer.default.thresholdCount=3 "+nl2nl+
"content.transformer.default.time=0 # end of line comment "+nl2nl+
"content.transformer.default.count=100000 "+nl2space+
" "+space2nl+"content.transformer.default.errorTime=120000 "+nl2nl+
"content.transformer.default.timeoutMs=120000 "+nl2nl+
"content.transformer.default.readLimitTimeMs=-1";
// What we paste into JConsole
String original = data.replace(nl2nl, "\n").replace(nl2space, "\n").replace(space2nl, " ");
// What we get from JConsole
String missingNl = data.replace(nl2nl, " ").replace(nl2space, " ").replace(space2nl, " ");
// What we expect to recover as a result of this method
String expected = data.replace(nl2nl, "\n").replace(nl2space, " ").replace(space2nl, "\n");
// What we do get from fixJConsolesMissingNewlines
String actual = setter.fixJConsolesMissingNewlines(missingNl);
String indentOriginal = ("\n"+original).replaceAll("\n", "\n ");
assertEquals("Having entered:"+indentOriginal+"\n", expected, actual);
}
@Test(expected=IllegalArgumentException.class)
public void midNameWhiteSpaceTest()
{
setter.setProperties("transformer. log.entries=12");
}
@Test(expected=IllegalArgumentException.class)
public void prefixValueWhiteSpaceTest()
{
setter.setProperties("transformer.log.entries= 12");
}
@Test
public void namedTransformerTest()
{
setter.setProperties(
"content.transformer.abc.priority=100\n"+
"content.transformer.abc.thresholdCount=3\n"+
"content.transformer.abc.time=0\n"+
"content.transformer.abc.count=100000\n"+
"content.transformer.abc.errorTime=120000\n"+
"content.transformer.abc.timeoutMs=120000\n"+
"content.transformer.abc.readLimitTimeMs=-1\n"+
"content.transformer.abc.maxSourceSizeKBytes=-1\n"+
"content.transformer.abc.readLimitKBytes=-1\n"+
"content.transformer.abc.pageLimit=-1\n"+
"content.transformer.abc.maxPages=-1\n"+
"content.transformer.abc.failover=transformer1|transformer2|transformer3\n"+
"content.transformer.abc.pipeline=transformer1|pdf|transformer2");
verify(transformerProperties).setProperties(expectedProperties(
"content.transformer.abc.priority", "100",
"content.transformer.abc.thresholdCount", "3",
"content.transformer.abc.time", "0",
"content.transformer.abc.count", "100000",
"content.transformer.abc.errorTime", "120000",
"content.transformer.abc.timeoutMs", "120000",
"content.transformer.abc.readLimitTimeMs", "-1",
"content.transformer.abc.maxSourceSizeKBytes", "-1",
"content.transformer.abc.readLimitKBytes", "-1",
"content.transformer.abc.pageLimit", "-1",
"content.transformer.abc.maxPages", "-1",
"content.transformer.abc.failover", "transformer1|transformer2|transformer3",
"content.transformer.abc.pipeline", "transformer1|pdf|transformer2"));
}
@Test
public void simpleExtensionsTest()
{
setter.setProperties("content.transformer.abc.extensions.pdf.png.maxPages=-1");
}
@Test
public void namedTransformerExtensionTest()
{
setter.setProperties(
"content.transformer.abc.extensions.pdf.png.priority=100\n"+
"content.transformer.abc.extensions.pdf.png.thresholdCount=3\n"+
"content.transformer.abc.extensions.pdf.png.time=0\n"+
"content.transformer.abc.extensions.pdf.png.count=100000\n"+
"content.transformer.abc.extensions.pdf.png.errorTime=120000\n"+
"content.transformer.abc.extensions.pdf.png.timeoutMs=120000\n"+
"content.transformer.abc.extensions.pdf.png.readLimitTimeMs=-1\n"+
"content.transformer.abc.extensions.pdf.png.maxSourceSizeKBytes=-1\n"+
"content.transformer.abc.extensions.pdf.png.readLimitKBytes=-1\n"+
"content.transformer.abc.extensions.pdf.png.pageLimit=-1\n"+
"content.transformer.abc.extensions.pdf.png.maxPages=-1\n"+
"content.transformer.abc.extensions.pdf.png.supported=true");
verify(transformerProperties).setProperties(expectedProperties(
"content.transformer.abc.extensions.pdf.png.priority", "100",
"content.transformer.abc.extensions.pdf.png.thresholdCount", "3",
"content.transformer.abc.extensions.pdf.png.time", "0",
"content.transformer.abc.extensions.pdf.png.count", "100000",
"content.transformer.abc.extensions.pdf.png.errorTime", "120000",
"content.transformer.abc.extensions.pdf.png.timeoutMs", "120000",
"content.transformer.abc.extensions.pdf.png.readLimitTimeMs", "-1",
"content.transformer.abc.extensions.pdf.png.maxSourceSizeKBytes", "-1",
"content.transformer.abc.extensions.pdf.png.readLimitKBytes", "-1",
"content.transformer.abc.extensions.pdf.png.pageLimit", "-1",
"content.transformer.abc.extensions.pdf.png.maxPages", "-1",
"content.transformer.abc.extensions.pdf.png.supported", "true"));
}
@Test(expected=IllegalArgumentException.class)
public void badSourceExtensionsTest()
{
setter.setProperties("content.transformer.abc.extensions.bad.png.maxPages=-1");
}
@Test(expected=IllegalArgumentException.class)
public void badTargetExtensionsTest()
{
setter.setProperties("content.transformer.abc.extensions.pdf.bad.maxPages=-1");
}
@Test
public void simpleMimetypeTest()
{
setter.setProperties("content.transformer.abc.mimetypes.application/pdf.image/png.maxPages=-1");
}
@Test
public void namedTransformerMimetypeTest()
{
setter.setProperties(
"content.transformer.abc.mimetypes.application/pdf.image/png.priority=100\n"+
"content.transformer.abc.mimetypes.application/pdf.image/png.thresholdCount=3\n"+
"content.transformer.abc.mimetypes.application/pdf.image/png.time=0\n"+
"content.transformer.abc.mimetypes.application/pdf.image/png.count=100000\n"+
"content.transformer.abc.mimetypes.application/pdf.image/png.errorTime=120000\n"+
"content.transformer.abc.mimetypes.application/pdf.image/png.timeoutMs=120000\n"+
"content.transformer.abc.mimetypes.application/pdf.image/png.readLimitTimeMs=-1\n"+
"content.transformer.abc.mimetypes.application/pdf.image/png.maxSourceSizeKBytes=-1\n"+
"content.transformer.abc.mimetypes.application/pdf.image/png.readLimitKBytes=-1\n"+
"content.transformer.abc.mimetypes.application/pdf.image/png.pageLimit=-1\n"+
"content.transformer.abc.mimetypes.application/pdf.image/png.maxPages=-1\n"+
"content.transformer.abc.mimetypes.application/pdf.image/png.supported=true");
verify(transformerProperties).setProperties(expectedProperties(
"content.transformer.abc.mimetypes.application/pdf.image/png.priority", "100",
"content.transformer.abc.mimetypes.application/pdf.image/png.thresholdCount", "3",
"content.transformer.abc.mimetypes.application/pdf.image/png.time", "0",
"content.transformer.abc.mimetypes.application/pdf.image/png.count", "100000",
"content.transformer.abc.mimetypes.application/pdf.image/png.errorTime", "120000",
"content.transformer.abc.mimetypes.application/pdf.image/png.timeoutMs", "120000",
"content.transformer.abc.mimetypes.application/pdf.image/png.readLimitTimeMs", "-1",
"content.transformer.abc.mimetypes.application/pdf.image/png.maxSourceSizeKBytes", "-1",
"content.transformer.abc.mimetypes.application/pdf.image/png.readLimitKBytes", "-1",
"content.transformer.abc.mimetypes.application/pdf.image/png.pageLimit", "-1",
"content.transformer.abc.mimetypes.application/pdf.image/png.maxPages", "-1",
"content.transformer.abc.mimetypes.application/pdf.image/png.supported", "true"));
}
@Test(expected=IllegalArgumentException.class)
public void badSourceMimetypeTest()
{
setter.setProperties("content.transformer.abc.mimetypes.bad.image/png.maxPages=-1");
}
@Test(expected=IllegalArgumentException.class)
public void badTargetMimetypeTest()
{
setter.setProperties("content.transformer.abc.mimetypes.application/pdf.bad.maxPages=-1");
}
public void pipelineTest()
{
setter.setProperties("content.transformer.abc.pipeline=transformer1|pdf|transformer2");
}
@Test(expected=IllegalArgumentException.class)
public void pipelineWithExtensionsTest()
{
setter.setProperties("content.transformer.abc.extensions.pdf.png.pipeline=transformer1|pdf|transformer2");
}
@Test(expected=IllegalArgumentException.class)
public void pipelineWithMimetypesTest()
{
setter.setProperties("content.transformer.abc.mimetypes.application/pdf.image/png.pipeline=transformer1|application/pdf|transformer2");
}
@Test(expected=IllegalArgumentException.class)
public void pipelineTooFewTest()
{
setter.setProperties("content.transformer.abc.pipeline=transformer1");
}
@Test(expected=IllegalArgumentException.class)
public void pipelineMissingTransformerTest()
{
setter.setProperties("content.transformer.abc.pipeline=transformer1|pdf|transformer2|png");
}
@Test(expected=IllegalArgumentException.class)
public void pipelineBadTransformerTest()
{
setter.setProperties("content.transformer.abc.pipeline=transformer1|pdf|bad");
}
@Test(expected=IllegalArgumentException.class)
public void pipelineBadExtensionTest()
{
setter.setProperties("content.transformer.abc.pipeline=transformer1|bad|transformer2");
}
public void failoverTest()
{
setter.setProperties("content.transformer.abc.failover=transformer1|transformer2");
}
@Test(expected=IllegalArgumentException.class)
public void failoverWithExtensionsTest()
{
setter.setProperties("content.transformer.abc.extensions.pdf.png.pipeline=transformer1|pdf|transformer2");
}
@Test(expected=IllegalArgumentException.class)
public void failoverWithMimetypeTest()
{
setter.setProperties("content.transformer.abc.mimetypes.application/pdf.image/png.failover=transformer1|transformer2");
}
@Test(expected=IllegalArgumentException.class)
public void failoverTooFewTest()
{
setter.setProperties("content.transformer.abc.failover=transformer1");
}
@Test(expected=IllegalArgumentException.class)
public void failoverBadTransformerTest()
{
setter.setProperties("content.transformer.abc.failover=transformer1|bad|transformer2");
}
@Test(expected=IllegalArgumentException.class)
public void removeUnsetPropetyTest()
{
setter.removeProperties("transformer.log.entries");
}
@Test
public void removeSimplePropertyTest()
{
mockProperties(transformerProperties, "transformer.log.entries", "12");
int count = setter.removeProperties("transformer.log.entries");
verify(transformerProperties).removeProperties(expectedNames("transformer.log.entries"));
assertEquals("Removed count", 1, count);
}
@Test
// removeProperties optionally has a value
public void removeOptionalValueTest()
{
mockProperties(transformerProperties, "transformer.log.entries", "12");
setter.removeProperties("transformer.log.entries=12");
}
@Test(expected=IllegalArgumentException.class)
// removeProperties on a default property
public void removeDefaultValueTest()
{
mockProperties(transformerProperties, "transformer.log.entries", "12");
properties.setProperty("transformer.log.entries", "10");
setter.removeProperties("transformer.log.entries=12");
}
@Test
public void dynamicTransformerReferenceTest()
{
setter.setProperties(
"content.transformer.abc.failover=transformer1|xyz\n"+ // Reference the transformer xyz
"content.transformer.xyz.pipeline=transformer1|pdf|transformer2"); // Create the transformer xyz
}
@Test
public void removeMultiplePropetiesTest()
{
mockProperties(transformerProperties,
"content.transformer.default.priority", "100",
"content.transformer.default.thresholdCount", "3",
"content.transformer.default.time", "0",
"content.transformer.default.count", "100000",
"content.transformer.default.errorTime", "120000");
int count = setter.removeProperties(
"# hi mum\n"+
"content.transformer.default.priority=100\n"+
" content.transformer.default.thresholdCount=3 \n"+
"\t content.transformer.default.time=0\n"+
"\t\t \t content.transformer.default.count=100000 # another comment\n"+
"#\n"+
" \n"+
"\n"+
"content.transformer.default.errorTime=120000\n");
verify(transformerProperties).removeProperties(expectedNames(
"content.transformer.default.priority",
"content.transformer.default.thresholdCount",
"content.transformer.default.time",
"content.transformer.default.count",
"content.transformer.default.errorTime"));
assertEquals("Removed count", 5, count);
}
}
@Deprecated
class DummyContentTransformer implements ContentTransformer
{
private final String name;
DummyContentTransformer(String name)
{
this.name = name;
}
@Override
public String getName()
{
return name;
}
@Override
public boolean isTransformable(String sourceMimetype, String targetMimetype,
TransformationOptions options)
{
return false;
}
@Override
public boolean isTransformable(String sourceMimetype, long sourceSize,
String targetMimetype, TransformationOptions options)
{
return false;
}
@Override
public boolean isTransformableMimetype(String sourceMimetype, String targetMimetype,
TransformationOptions options)
{
return false;
}
@Override
public boolean isTransformableSize(String sourceMimetype, long sourceSize,
String targetMimetype, TransformationOptions options)
{
return false;
}
@Override
public String getComments(boolean available)
{
return "";
}
@Override
public long getMaxSourceSizeKBytes(String sourceMimetype, String targetMimetype,
TransformationOptions options)
{
return 0;
}
@Override
public boolean isExplicitTransformation(String sourceMimetype, String targetMimetype,
TransformationOptions options)
{
return false;
}
@Override
public long getTransformationTime()
{
return 0;
}
@Override
public long getTransformationTime(String sourceMimetype, String targetMimetype)
{
return 0;
}
@Override
public void transform(ContentReader reader, ContentWriter writer) throws ContentIOException
{
}
@Override
public void transform(ContentReader reader, ContentWriter writer,
Map<String, Object> options) throws ContentIOException
{
}
@Override
public void transform(ContentReader reader, ContentWriter contentWriter,
TransformationOptions options) throws ContentIOException
{
}
};

View File

@@ -1,329 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
/**
* Test class for TransformerSelectorImpl.
*
* @author Alan Davis
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class TransformerSelectorImplTest
{
private static final String PNG = "image/png";
private static final String PDF = "application/pdf";
@Mock
private TransformerConfig transformerConfig;
@Mock
private ContentTransformerRegistry contentTransformerRegistry;
@Mock
private TransformationOptions options;
@Mock
private DummyContentTransformer transformer1;
@Mock
private DummyContentTransformer transformer2;
@Mock
private DummyContentTransformer transformer3;
@Mock
private DummyContentTransformer transformer4;
private List<ContentTransformer> allTransformers;
private TransformerSelectorImpl selector;
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(this);
selector = new TransformerSelectorImpl();
selector.setTransformerConfig(transformerConfig);
selector.setContentTransformerRegistry(contentTransformerRegistry);
when(transformer1.getName()).thenReturn("transformer.1");
when(transformer2.getName()).thenReturn("transformer.2");
when(transformer3.getName()).thenReturn("transformer.3");
when(transformer4.getName()).thenReturn("transformer.4");
allTransformers = new ArrayList<ContentTransformer>();
when(contentTransformerRegistry.getTransformers()).thenReturn(allTransformers);
}
private void mockTransformer(DummyContentTransformer transformer, int priority, String sourceMimetype, String targetMimetype)
{
when(transformerConfig.getPriority(transformer, sourceMimetype, targetMimetype)).thenReturn(priority);
allTransformers.add(transformer);
}
private void mockTransformer(DummyContentTransformer transformer, int priority, String sourceMimetype, String targetMimetype,
int count, int averageTime, int threshold)
{
mockTransformer(transformer, priority, sourceMimetype, targetMimetype);
when(transformer.isTransformable(sourceMimetype, -1, targetMimetype, options)).thenReturn(true);
when(transformerConfig.getStatistics(transformer, sourceMimetype, targetMimetype, true)).thenReturn(new DummyTransformerStatistics(count, averageTime));
when(transformerConfig.getThresholdCount(transformer, sourceMimetype, targetMimetype)).thenReturn(threshold);
}
private void assertTransformers(String context, List<ContentTransformer> expected,
List<ContentTransformer> actual)
{
String expectedNames = getNames(expected);
String actualNames = getNames(actual);
assertEquals(context, expectedNames, actualNames);
}
private String getNames(List<ContentTransformer> transformers)
{
StringBuilder sb = new StringBuilder();
for (ContentTransformer transformer: transformers)
{
if (sb.length() > 0)
{
sb.append(' ');
}
sb.append(transformer.getName());
}
return sb.toString();
}
private void runMultipleSelections(int[][] data) throws Exception
{
// Run a sequence of selections up to the thresholds and beyond
List<ContentTransformer> expected = null;
for (int i=0; i<data.length; i++)
{
int[] test = data[i];
setUp();
mockTransformer(transformer1, 100, PDF, PNG, test[0], test[1], test[2]);
mockTransformer(transformer2, 100, PDF, PNG);
mockTransformer(transformer3, 100, PDF, PNG);
mockTransformer(transformer4, 100, PDF, PNG, test[3], test[4], test[5]);
expected = test[6] == 1
? Arrays.asList(new ContentTransformer[] {transformer1, transformer4})
: Arrays.asList(new ContentTransformer[] {transformer4, transformer1});
List<ContentTransformer> actual = selector.selectTransformers(PDF, -1, PNG, options);
assertTransformers(i+" multiple", expected, actual);
}
}
@Test
public void firstRunUnderThresholdTest()
{
// 1 and 4 can do PDF->PNG, same priority (100) and neither have not been run
mockTransformer(transformer1, 100, PDF, PNG, 0, 0, 3);
mockTransformer(transformer2, 100, PDF, PNG);
mockTransformer(transformer3, 100, PDF, PNG);
mockTransformer(transformer4, 100, PDF, PNG, 0, 0, 3);
List<ContentTransformer> expected = Arrays.asList(new ContentTransformer[] {transformer1, transformer4});
List<ContentTransformer> actual = selector.selectTransformers(PDF, -1, PNG, options);
assertTransformers("", expected, actual);
}
@Test
public void secondRunUnderThresholdOneRunTest()
{
// 1 and 4 can do PDF->PNG, same priority (100) and but 1 has been run
// Should continue to round robin to 2
mockTransformer(transformer1, 100, PDF, PNG, 1, 23, 3);
mockTransformer(transformer2, 100, PDF, PNG);
mockTransformer(transformer3, 100, PDF, PNG);
mockTransformer(transformer4, 100, PDF, PNG, 0, 0, 3);
List<ContentTransformer> expected = Arrays.asList(new ContentTransformer[] {transformer4, transformer1});
List<ContentTransformer> actual = selector.selectTransformers(PDF, -1, PNG, options);
assertTransformers("", expected, actual);
}
@Test
public void thirdRunUnderThresholdTwoRunTest()
{
// 1 and 4 can do PDF->PNG, same priority (100) and both have been run, but still under threshold
// Note: If the threshold was not taken into account 4 would be selected
// Should continue to round robin
mockTransformer(transformer1, 100, PDF, PNG, 1, 23, 3);
mockTransformer(transformer2, 100, PDF, PNG);
mockTransformer(transformer3, 100, PDF, PNG);
mockTransformer(transformer4, 100, PDF, PNG, 1, 16, 3);
List<ContentTransformer> expected = Arrays.asList(new ContentTransformer[] {transformer1, transformer4});
List<ContentTransformer> actual = selector.selectTransformers(PDF, -1, PNG, options);
assertTransformers("", expected, actual);
}
@Test
public void multipleTestSameThreshold() throws Exception
{
int[][] data = new int[][]
{
{ 0, 0, 3, 0, 0, 3, 1}, // same as firstRunUnderThresholdTest
{ 1, 23, 3, 0, 0, 3, 4}, // same as secondRunUnderThresholdTest
{ 1, 23, 3, 1, 16, 3, 1}, // same as thirdRunUnderThresholdTwoRunTest
{ 2, 25, 3, 1, 16, 3, 4},
{ 2, 25, 3, 2, 27, 3, 1},
{ 3, 24, 3, 2, 27, 3, 4},
{ 3, 24, 3, 3, 27, 3, 1},
// Threshold past for both transformers - 1 was faster
{ 4, 25, 3, 3, 27, 3, 1},
{ 5, 22, 3, 3, 27, 3, 1},
{ 6, 21, 3, 3, 27, 3, 1},
// 1 is slower than 4 now, so it switches
{ 7, 28, 3, 3, 27, 3, 4},
{ 7, 28, 3, 4, 26, 3, 4},
};
runMultipleSelections(data);
}
@Test
public void multipleTestDifferentThreshold() throws Exception
{
int[][] data = new int[][]
{
{ 0, 0, 2, 0, 0, 4, 1},
{ 1, 23, 2, 0, 0, 4, 4},
{ 1, 23, 2, 1, 16, 4, 1},
// Threshold past for 1 but not 4
{ 2, 25, 2, 1, 16, 4, 4},
{ 2, 25, 2, 2, 27, 4, 4},
{ 2, 25, 2, 3, 22, 4, 4},
// Threshold past for both transformers
{ 2, 25, 2, 4, 22, 4, 4},
{ 2, 25, 2, 5, 29, 4, 1},
{ 3, 28, 2, 5, 29, 4, 1},
// 1 is slower than 4 now, so it switches
{ 4, 30, 2, 5, 29, 4, 4},
};
runMultipleSelections(data);
}
@Test
public void priorityTest()
{
// 1 and 4 can do PDF->PNG, but 4 is higher priority, even though 1 appears faster
mockTransformer(transformer1, 100, PDF, PNG, 10, 22, 3);
mockTransformer(transformer2, 100, PDF, PNG);
mockTransformer(transformer3, 100, PDF, PNG);
mockTransformer(transformer4, 50, PDF, PNG, 10, 44, 3);
List<ContentTransformer> expected = Arrays.asList(new ContentTransformer[] {transformer4, transformer1});
List<ContentTransformer> actual = selector.selectTransformers(PDF, -1, PNG, options);
assertTransformers("", expected, actual);
}
@Test
public void priorityAndTimeTest()
{
// 1, 2 and 4 can do PDF->PNG, but 4 is higher priority, even though 1 and 2 appear faster
mockTransformer(transformer1, 100, PDF, PNG, 10, 22, 3);
mockTransformer(transformer2, 100, PDF, PNG, 10, 23, 3);
mockTransformer(transformer3, 100, PDF, PNG);
mockTransformer(transformer4, 50, PDF, PNG, 10, 44, 3);
List<ContentTransformer> expected = Arrays.asList(new ContentTransformer[] {transformer4, transformer1, transformer2});
List<ContentTransformer> actual = selector.selectTransformers(PDF, -1, PNG, options);
assertTransformers("", expected, actual);
}
@Test
public void priorityAndThresholdTest()
{
// 1, 2 and 4 can do PDF->PNG, but 4 is higher priority, even though 1 and 2 have not reached the threshold
mockTransformer(transformer1, 100, PDF, PNG, 0, 0, 3);
mockTransformer(transformer2, 100, PDF, PNG, 0, 0, 3);
mockTransformer(transformer3, 100, PDF, PNG);
mockTransformer(transformer4, 50, PDF, PNG, 10, 44, 3);
List<ContentTransformer> expected = Arrays.asList(new ContentTransformer[] {transformer4, transformer1, transformer2});
List<ContentTransformer> actual = selector.selectTransformers(PDF, -1, PNG, options);
assertTransformers("", expected, actual);
}
}
@Deprecated
class DummyTransformerStatistics extends TransformerStatisticsImpl
{
private final long count;
private final long averageTime;
public DummyTransformerStatistics(long count, long averageTime)
{
super(null, null, null, null, null, 0L, 0L, 0L);
this.count = count;
this.averageTime = averageTime;
}
@Override
public long getCount()
{
return count;
}
@Override
public long getAverageTime()
{
return averageTime;
}
}

View File

@@ -1,273 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.content.transform.magick;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.alfresco.repo.content.MimetypeMap;
import org.alfresco.repo.content.filestore.FileContentReader;
import org.alfresco.repo.content.filestore.FileContentWriter;
import org.alfresco.repo.content.transform.AbstractContentTransformerTest;
import org.alfresco.repo.content.transform.ContentTransformer;
import org.alfresco.repo.content.transform.ProxyContentTransformer;
import org.alfresco.repo.content.transform.RemoteTransformerClient;
import org.alfresco.service.cmr.repository.ContentReader;
import org.alfresco.service.cmr.repository.ContentWriter;
import org.alfresco.service.cmr.repository.PagedSourceOptions;
import org.alfresco.service.cmr.repository.TransformationOptions;
import org.alfresco.service.cmr.repository.TransformationSourceOptions;
import org.alfresco.util.TempFileProvider;
import org.junit.AfterClass;
import org.junit.BeforeClass;
/**
* @see org.alfresco.repo.content.transform.magick.ImageMagickContentTransformerWorker
*
* @author Derek Hulley
*
* @deprecated The transformations code is being moved out of the codebase and replaced by the new async RenditionService2 or other external libraries.
*/
@Deprecated
public class ImageMagickContentTransformerTest extends AbstractContentTransformerTest
{
private ProxyContentTransformer transformer;
@BeforeClass
public static void before()
{
// Use the docker images for transforms (legacy)
System.setProperty("alfresco-pdf-renderer.url", "http://localhost:8090/");
System.setProperty("img.url", "http://localhost:8090/");
System.setProperty("jodconverter.url", "http://localhost:8090/");
System.setProperty("tika.url", "http://localhost:8090/");
System.setProperty("transform.misc.url", "http://localhost:8090/");
}
@AfterClass
public static void after()
{
System.clearProperty("alfresco-pdf-renderer.url");
System.clearProperty("img.url");
System.clearProperty("jodconverter.url");
System.clearProperty("tika.url");
System.clearProperty("transform.misc.url");
}
@Override
public void setUp() throws Exception
{
super.setUp();
// Setup a mimetype service that will return a truncated set of mimetypes
MockMimetypeService testMimetypeService = new MockMimetypeService();
testMimetypeService.setConfigService(((MimetypeMap) mimetypeService).getConfigService());
testMimetypeService.setContentCharsetFinder(((MimetypeMap) mimetypeService).getContentCharsetFinder());
testMimetypeService.init();
this.mimetypeService = testMimetypeService;
transformer = (ProxyContentTransformer) ctx.getBean("transformer.ImageMagick");
RemoteTransformerClient remoteTransformerClient = new RemoteTransformerClient("miscRemoteTransformerClient", "http://localhost:8090/");
transformer.getWorker().setRemoteTransformerClient(remoteTransformerClient);
}
/**
* @return Returns the same transformer regardless - it is allowed
*/
protected ContentTransformer getTransformer(String sourceMimetype, String targetMimetype)
{
return transformer;
}
public void testReliability() throws Exception
{
if (!this.transformer.getWorker().isAvailable())
{
return;
}
boolean reliability = transformer.isTransformable(
MimetypeMap.MIMETYPE_IMAGE_GIF, -1, MimetypeMap.MIMETYPE_TEXT_PLAIN, new TransformationOptions());
assertEquals("Mimetype should not be supported", false, reliability);
reliability = transformer.isTransformable(
MimetypeMap.MIMETYPE_IMAGE_GIF, -1, MimetypeMap.MIMETYPE_IMAGE_JPEG, new TransformationOptions());
assertEquals("Mimetype should be supported", true, reliability);
}
protected long transform(String sourceMimetype, String targetMimetype, TransformationOptions options) throws IOException
{
long size = -1;
String[] quickFiles = getQuickFilenames(sourceMimetype);
for (String quickFile : quickFiles)
{
String sourceExtension = quickFile.substring(quickFile.lastIndexOf('.')+1);
String targetExtension = mimetypeService.getExtension(targetMimetype);
// is there a test file for this conversion?
File sourceFile = AbstractContentTransformerTest.loadNamedQuickTestFile(quickFile);
if (sourceFile == null)
{
continue; // no test file available for that extension
}
ContentReader sourceReader = new FileContentReader(sourceFile);
// make a writer for the target file
File targetFile = TempFileProvider.createTempFile(
getClass().getSimpleName() + "_" + getName() + "_" + sourceExtension + "_",
"." + targetExtension);
ContentWriter targetWriter = new FileContentWriter(targetFile);
// do the transformation
sourceReader.setMimetype(sourceMimetype);
targetWriter.setMimetype(targetMimetype);
transformer.transform(sourceReader.getReader(), targetWriter, options);
ContentReader targetReader = targetWriter.getReader();
size = targetReader.getSize();
assertTrue(size > 0);
}
return size;
}
public void testGifToPng() throws Exception
{
ImageTransformationOptions options = new ImageTransformationOptions();
transform(MimetypeMap.MIMETYPE_IMAGE_GIF, MimetypeMap.MIMETYPE_IMAGE_PNG, options);
}
public void testJpegToPng() throws Exception
{
ImageTransformationOptions options = new ImageTransformationOptions();
transform(MimetypeMap.MIMETYPE_IMAGE_JPEG, MimetypeMap.MIMETYPE_IMAGE_PNG, options);
}
public void testDeprecatedCommandOptions() throws Exception
{
// The commandOption should be removed, but is currently needed for custom renditions.
// This test uses it to resize the file. This happens to be one of the standard options.
ImageTransformationOptions options = new ImageTransformationOptions();
long defaultSize = transform(MimetypeMap.MIMETYPE_IMAGE_JPEG, MimetypeMap.MIMETYPE_IMAGE_PNG, options);
options.setCommandOptions("-resize 200%");
long biggerSize = transform(MimetypeMap.MIMETYPE_IMAGE_JPEG, MimetypeMap.MIMETYPE_IMAGE_PNG, options);
assertTrue("The commandOption appears not to have been used as the file size " + biggerSize +
" is not larger than the default size " + defaultSize, biggerSize > defaultSize);
}
// This fails with remote transformers
// The thumbnails actually have parameters in real life
public void ignoreTestPageSourceOptions() throws Exception
{
// Test empty source options
ImageTransformationOptions options = new ImageTransformationOptions();
this.transform(MimetypeMap.MIMETYPE_PDF, MimetypeMap.MIMETYPE_IMAGE_PNG, options);
// Test first page
options = new ImageTransformationOptions();
List<TransformationSourceOptions> sourceOptionsList = new ArrayList<TransformationSourceOptions>();
sourceOptionsList.add(PagedSourceOptions.getPage1Instance());
options.setSourceOptionsList(sourceOptionsList);
this.transform(MimetypeMap.MIMETYPE_PDF, MimetypeMap.MIMETYPE_IMAGE_PNG, options);
// Test second page
options = new ImageTransformationOptions();
sourceOptionsList = new ArrayList<TransformationSourceOptions>();
PagedSourceOptions sourceOptions = new PagedSourceOptions();
sourceOptions.setStartPageNumber(2);
sourceOptions.setEndPageNumber(2);
sourceOptionsList.add(sourceOptions);
options.setSourceOptionsList(sourceOptionsList);
this.transform(MimetypeMap.MIMETYPE_PDF, MimetypeMap.MIMETYPE_IMAGE_PNG, options);
// Test page range invalid for target type
options = new ImageTransformationOptions();
sourceOptionsList = new ArrayList<TransformationSourceOptions>();
sourceOptions = new PagedSourceOptions();
sourceOptions.setStartPageNumber(1);
sourceOptions.setEndPageNumber(2);
sourceOptionsList.add(sourceOptions);
options.setSourceOptionsList(sourceOptionsList);
try {
this.transform(MimetypeMap.MIMETYPE_PDF, MimetypeMap.MIMETYPE_IMAGE_PNG, options);
fail("An exception regarding an invalid page range should have been thrown");
}
catch (Exception e)
{
// failure expected
}
// Test page out of range
options = new ImageTransformationOptions();
sourceOptionsList = new ArrayList<TransformationSourceOptions>();
sourceOptions = new PagedSourceOptions();
sourceOptions.setStartPageNumber(3);
sourceOptions.setEndPageNumber(3);
sourceOptionsList.add(sourceOptions);
options.setSourceOptionsList(sourceOptionsList);
try {
this.transform(MimetypeMap.MIMETYPE_PDF, MimetypeMap.MIMETYPE_IMAGE_PNG, options);
fail("An exception regarding an invalid page range should have been thrown");
}
catch (Exception e)
{
// failure expected
}
}
/**
* Mock mimetype service which returns a limited set of mimetypes
* as {@link AbstractContentTransformerTest#testAllConversions()} will
* fail if delegates are not available on the test agent.
*
* @author rgauss
*/
public class MockMimetypeService extends MimetypeMap
{
private List<String> testMimetypes;
public void init()
{
super.init();
testMimetypes = new ArrayList<String>(10);
testMimetypes.add(MimetypeMap.MIMETYPE_IMAGE_GIF);
testMimetypes.add(MimetypeMap.MIMETYPE_IMAGE_JPEG);
testMimetypes.add(MimetypeMap.MIMETYPE_IMAGE_PNG);
testMimetypes.add(MimetypeMap.MIMETYPE_IMAGE_TIFF);
testMimetypes.add(MimetypeMap.MIMETYPE_APPLICATION_ILLUSTRATOR);
testMimetypes.add(MimetypeMap.MIMETYPE_APPLICATION_EPS);
testMimetypes.add(MimetypeMap.MIMETYPE_APPLICATION_PHOTOSHOP);
testMimetypes.add(MimetypeMap.MIMETYPE_PDF);
}
@Override
public List<String> getMimetypes()
{
return testMimetypes;
}
}
}

View File

@@ -2568,7 +2568,7 @@ public class RenditionServiceIntegrationTest extends BaseAlfrescoSpringTest
ContentReader reader = contentService.getReader(newImageRendition, ContentModel.PROP_CONTENT);
assertNotNull("Reader to rendered image was null", reader);
BufferedImage srcImg = ImageIO.read(reader.getContentInputStream());
checkTopLeftBottomRight(srcImg, topLeft, bottomRight);
checkTopLeftBottomRight(srcImg, topLeft, bottomRight, "rendered image");
return null;
}
@@ -2581,16 +2581,16 @@ public class RenditionServiceIntegrationTest extends BaseAlfrescoSpringTest
File imageFile = new File(url.getFile());
BufferedImage img = ImageIO.read(url);
assertNotNull("image was null", img);
checkTopLeftBottomRight(img, WHITE, BLACK);
checkTopLeftBottomRight(img, WHITE, BLACK, "original image");
return imageFile;
}
private static void checkTopLeftBottomRight(BufferedImage img, String topLeft, String bottomRight)
private static void checkTopLeftBottomRight(BufferedImage img, String topLeft, String bottomRight, String srcImage)
{
int rgbAtTopLeft = img.getRGB(1, 1);
assertTrue("upper left should be "+topLeft, Integer.toHexString(rgbAtTopLeft).endsWith(topLeft));
int rgbAtBottomRight = img.getRGB(img.getWidth() - 1, img.getHeight() - 1);
assertTrue("lower right should be "+bottomRight, Integer.toHexString(rgbAtBottomRight).endsWith(bottomRight));
String rgbAtTopLeft = Integer.toHexString(img.getRGB(1, 1));
assertTrue("upper left "+ rgbAtTopLeft +" should end with "+topLeft+" "+srcImage, rgbAtTopLeft.endsWith(topLeft));
String rgbAtBottomRight = Integer.toHexString(img.getRGB(img.getWidth() - 1, img.getHeight() - 1));
assertTrue("lower right "+ rgbAtBottomRight +" should end with "+bottomRight+" "+srcImage, rgbAtBottomRight.endsWith(bottomRight));
}
/**

View File

@@ -117,9 +117,6 @@ public abstract class AbstractRenditionIntegrationTest extends BaseSpringTest
@Autowired
protected LocalTransformServiceRegistry localTransformServiceRegistry;
@Autowired
protected LegacyTransformServiceRegistry legacyTransformServiceRegistry;
@Autowired
protected TransformationOptionsConverter converter;
@@ -137,13 +134,6 @@ public abstract class AbstractRenditionIntegrationTest extends BaseSpringTest
@BeforeClass
public static void before()
{
// Use the docker images for transforms (legacy)
System.setProperty("alfresco-pdf-renderer.url", "http://localhost:8090/");
System.setProperty("img.url", "http://localhost:8090/");
System.setProperty("jodconverter.url", "http://localhost:8090/");
System.setProperty("tika.url", "http://localhost:8090/");
System.setProperty("transform.misc.url", "http://localhost:8090/");
// Use the docker images for transforms (local)
System.setProperty("localTransform.core-aio.url", "http://localhost:8090/");
}
@@ -152,21 +142,12 @@ public abstract class AbstractRenditionIntegrationTest extends BaseSpringTest
{
System.setProperty("transform.service.enabled", "false");
System.setProperty("local.transform.service.enabled", "false");
System.setProperty("legacy.transform.service.enabled", "false");
}
protected static void legacy()
{
System.setProperty("transform.service.enabled", "false");
System.setProperty("local.transform.service.enabled", "false");
System.setProperty("legacy.transform.service.enabled", "true");
}
protected static void local()
{
System.setProperty("transform.service.enabled", "false");
System.setProperty("local.transform.service.enabled", "true");
System.setProperty("legacy.transform.service.enabled", "false");
// Strict MimetypeCheck
System.setProperty("transformer.strict.mimetype.check", "true");
@@ -178,21 +159,12 @@ public abstract class AbstractRenditionIntegrationTest extends BaseSpringTest
{
System.setProperty("transform.service.enabled", "true");
System.setProperty("local.transform.service.enabled", "false");
System.setProperty("legacy.transform.service.enabled", "false");
}
protected static void legacyLocal()
{
System.setProperty("transform.service.enabled", "false");
System.setProperty("local.transform.service.enabled", "true");
System.setProperty("legacy.transform.service.enabled", "true");
}
protected static void legacyLocalService()
protected static void localService()
{
System.setProperty("transform.service.enabled", "true");
System.setProperty("local.transform.service.enabled", "true");
System.setProperty("legacy.transform.service.enabled", "true");
}
@Before
@@ -200,22 +172,26 @@ public abstract class AbstractRenditionIntegrationTest extends BaseSpringTest
{
assertTrue("The RenditionService2 needs to be enabled", renditionService2.isEnabled());
legacyTransformServiceRegistry.setEnabled(Boolean.parseBoolean(System.getProperty("legacy.transform.service.enabled")));
legacyTransformServiceRegistry.afterPropertiesSet();
origLocalTransCron = localTransformServiceRegistry.getCronExpression();
localTransformServiceRegistry.setCronExpression(null);
localTransformServiceRegistry.setEnabled(Boolean.parseBoolean(System.getProperty("local.transform.service.enabled")));
boolean localTransformServiceEnabled = Boolean.parseBoolean(System.getProperty("local.transform.service.enabled"));
localTransformServiceRegistry.setEnabled(localTransformServiceEnabled);
localTransformServiceRegistry.afterPropertiesSet();
origRenditionCron = renditionDefinitionRegistry2.getCronExpression();
renditionDefinitionRegistry2.setCronExpression(null);
renditionDefinitionRegistry2.setTransformServiceRegistry(transformServiceRegistry);
renditionDefinitionRegistry2.afterPropertiesSet();
if (transformServiceRegistry instanceof LocalTransformServiceRegistry)
{
((LocalTransformServiceRegistry)transformServiceRegistry).setEnabled(localTransformServiceEnabled);
}
thumbnailRegistry.setTransformServiceRegistry(transformServiceRegistry);
thumbnailRegistry.setLocalTransformServiceRegistry(localTransformServiceRegistry);
thumbnailRegistry.setConverter(converter);
origRenditionCron = renditionDefinitionRegistry2.getCronExpression();
renditionDefinitionRegistry2.setCronExpression(null);
renditionDefinitionRegistry2.setTransformServiceRegistry(transformServiceRegistry);
renditionDefinitionRegistry2.setTransformServiceRegistry(localTransformServiceRegistry);
renditionDefinitionRegistry2.afterPropertiesSet();
}
@After
@@ -230,17 +206,9 @@ public abstract class AbstractRenditionIntegrationTest extends BaseSpringTest
@AfterClass
public static void after()
{
System.clearProperty("alfresco-pdf-renderer.url");
System.clearProperty("img.url");
System.clearProperty("jodconverter.url");
System.clearProperty("tika.url");
System.clearProperty("transform.misc.url");
System.clearProperty("localTransform.core-aio.url");
System.clearProperty("transform.service.enabled");
System.clearProperty("local.transform.service.enabled");
System.clearProperty("legacy.transform.service.enabled");
}
protected void checkRendition(String testFileName, String renditionName, boolean expectedToPass)

View File

@@ -1,54 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2018 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.rendition2;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
/**
* Repeats quick file rendition tests with local transforms and legacy transformers enabled.
* The Transform Service does not exist for the Community edition.
* Should be the same result as with legacy or local transforms on their own.
*
* @author adavis
*/
@Deprecated
public class LegacyLocalRenditionTest extends AbstractRenditionTest
{
@BeforeClass
public static void before()
{
AbstractRenditionIntegrationTest.before();
legacyLocal();
}
@AfterClass
public static void after()
{
AbstractRenditionIntegrationTest.after();
}
}

View File

@@ -1,70 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2018 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.rendition2;
import org.alfresco.util.testing.category.DebugTests;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
/**
* Repeats quick file rendition tests with local transforms disabled but legacy transformers enabled.
* The Transform Service does not exist for the Community edition.
* Should be the same result as with local transforms.
*
* @author adavis
*/
public class LegacyRenditionTest extends AbstractRenditionTest
{
@BeforeClass
public static void before()
{
AbstractRenditionIntegrationTest.before();
legacy();
}
@Override
@Before
public void setUp() throws Exception
{
super.setUp();
}
@AfterClass
public static void after()
{
AbstractRenditionIntegrationTest.after();
}
@Test
@Override
public void testSelectedMetadataExtracts() throws Exception
{
internalTestSelectedMetadataExtracts(7, 7);
}
}

View File

@@ -1,61 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2018 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.rendition2;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Integration tests for {@link LegacyTransformClient}
*/
@Deprecated
public class LegacySynchronousTransformClientIntegrationTest extends LocalSynchronousTransformClientIntegrationTest
{
@Autowired
protected SynchronousTransformClient legacySynchronousTransformClient;
@BeforeClass
public static void before()
{
AbstractRenditionIntegrationTest.before();
legacy();
}
@AfterClass
public static void after()
{
AbstractRenditionIntegrationTest.after();
}
@Before
public void setUp() throws Exception
{
super.setUp();
synchronousTransformClient = legacySynchronousTransformClient;
}
}

View File

@@ -1,61 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2018 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.rendition2;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Integration tests for {@link LegacyTransformClient}
*/
@Deprecated
public class LegacyTransformClientIntegrationTest extends LocalTransformClientIntegrationTest
{
@Autowired
protected TransformClient legacyTransformClient;
@BeforeClass
public static void before()
{
AbstractRenditionIntegrationTest.before();
legacy();
}
@AfterClass
public static void after()
{
AbstractRenditionIntegrationTest.after();
}
@Before
public void setUp() throws Exception
{
super.setUp();
transformClient = legacyTransformClient;
}
}

View File

@@ -1,86 +0,0 @@
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2018 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.rendition2;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static org.alfresco.transform.client.model.Mimetype.MIMETYPE_IMAGE_JPEG;
/**
* Integration tests for {@link LegacyTransformServiceRegistry}
*/
@Deprecated
public class LegacyTransformServiceRegistryIntegrationTest extends LocalTransformServiceRegistryIntegrationTest
{
@Autowired
private LegacyTransformServiceRegistry legacyTransformServiceRegistry;
@Before
public void setUp() throws Exception
{
super.setUp();
transformServiceRegistry = legacyTransformServiceRegistry;
targetMimetype = MIMETYPE_IMAGE_JPEG;
}
@BeforeClass
public static void before()
{
AbstractRenditionIntegrationTest.before();
legacy();
}
@AfterClass
public static void after()
{
AbstractRenditionIntegrationTest.after();
}
@Override
protected void setEnabled(boolean enabled)
{
legacyTransformServiceRegistry.setEnabled(enabled);
legacyTransformServiceRegistry.afterPropertiesSet();
}
@Override
protected boolean isEnabled()
{
return legacyTransformServiceRegistry.isEnabled();
}
@Test
@Override
public void testIsSupported()
{
// There are no longer any standard transforms with a size limit without a lower priority fallback,
// so this test cannot be codded.
}
}

View File

@@ -34,7 +34,7 @@ import org.junit.experimental.categories.Category;
import java.util.Collections;
/**
* Repeats quick file rendition tests with local transforms and legacy transformers disabled.
* Repeats quick file rendition tests with local transforms disabled.
* The Transform Service does not exist for the Community edition.
*
* @author adavis

View File

@@ -55,7 +55,7 @@ public class RenditionService2IntegrationTest extends AbstractRenditionIntegrati
public static void before()
{
AbstractRenditionIntegrationTest.before();
legacyLocal();
local();
}
// PDF transformation

View File

@@ -2,7 +2,7 @@
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2019 Alfresco Software Limited
* Copyright (C) 2005 - 2020 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of

View File

@@ -25,7 +25,6 @@
*/
package org.alfresco.repo.rendition2;
import org.alfresco.repo.content.transform.magick.ImageMagickContentTransformerWorker;
import org.alfresco.repo.content.transform.magick.ImageResizeOptions;
import org.alfresco.repo.content.transform.magick.ImageTransformationOptions;
import org.alfresco.repo.content.transform.swf.SWFTransformationOptions;
@@ -81,22 +80,11 @@ public class TransformationOptionsConverterTest
private void assertConverterToMapAndBack(TransformationOptions oldOptions, String sourceMimetype,
String targetMimetype, String expectedOldOptionsToString,
String expectedArgs,
boolean checkImageMagickContentTransformerWorkerResult)
String expectedArgs)
{
String sortedOldOptions = getSortedOptions(oldOptions, sourceMimetype, targetMimetype);
assertEquals("oldOptions was not set up correctly", expectedOldOptionsToString, oldOptions.toString());
// This check will need to be removed when the ImageMagickContentTransformerWorker is removed.
// It is really checking that the supplied expectedArgs (just used to check the sortedNewOptions) are correct.
if (checkImageMagickContentTransformerWorkerResult)
{
String[] tEngineArgs = getOptionalTEngineArgs(oldOptions, sourceMimetype, targetMimetype);
String sortedTEngineOptions = getSortedOptions(tEngineArgs)+"timeout=-1 ";
assertEquals("Test error: expectedArgs are not what is generated by ImageMagickContentTransformerWorker",
expectedArgs, sortedTEngineOptions);
}
Map<String, String> newOptions = converter.getOptions(oldOptions, sourceMimetype, targetMimetype);
Map<String, String> newOptionsWithoutDiscards = discardNoopOptions(newOptions);
String sortedNewOptions = getSortedOptions(newOptionsWithoutDiscards);
@@ -109,14 +97,6 @@ public class TransformationOptionsConverterTest
assertEquals("Having converted twice the map is different", sortedOldOptions, sortedBackToOldOptions);
}
// Discards the transformerName, sourceMimetype, sourceExtension and targetMimetype elements which are always in the first 3 elements.
private String[] getOptionalTEngineArgs(TransformationOptions oldOptions, String sourceMimetype, String targetMimetype)
{
String[] args = ImageMagickContentTransformerWorker.getTEngineArgs(oldOptions, sourceMimetype, null, targetMimetype,
"Version: ImageMagick 6.7.5");
return Arrays.copyOfRange(args, 4*2, args.length);
}
private String getSortedOptions(TransformationOptions options, String sourceMimetype, String targetMimetype)
{
Map<String, String> map = converter.getOptions(options, sourceMimetype, targetMimetype);
@@ -192,8 +172,8 @@ public class TransformationOptionsConverterTest
"resizeHeight=30 " +
"resizeWidth=20 " +
"startPage=0 " +
"timeout=-1 ",
true);
"timeout=-1 "
);
}
@Test
@@ -205,8 +185,8 @@ public class TransformationOptionsConverterTest
assertConverterToMapAndBack(oldOptions, MIMETYPE_IMAGE_JPEG, MIMETYPE_IMAGE_PNG,
"ImageTransformationOptions [commandOptions=, resizeOptions=null, autoOrient=true]]",
"autoOrient=true " +
"timeout=-1 ",
true);
"timeout=-1 "
);
}
@Test
@@ -218,8 +198,8 @@ public class TransformationOptionsConverterTest
assertConverterToMapAndBack(oldOptions, MIMETYPE_IMAGE_JPEG, MIMETYPE_IMAGE_PNG,
"ImageTransformationOptions [commandOptions=, resizeOptions=null, autoOrient=false]]",
"timeout=-1 ",
true);
"timeout=-1 "
);
}
@Test
@@ -233,8 +213,8 @@ public class TransformationOptionsConverterTest
assertConverterToMapAndBack(oldOptions, MIMETYPE_IMAGE_JPEG, MIMETYPE_IMAGE_JPEG,
"ImageTransformationOptions [commandOptions=, resizeOptions=null, autoOrient=false]]",
"alphaRemove=true " +
"timeout=-1 ",
true);
"timeout=-1 "
);
}
@Test
@@ -252,8 +232,8 @@ public class TransformationOptionsConverterTest
"[height=-1, width=-1, xOffset=0, yOffset=0, isPercentageCrop=false, gravity=null]} ]",
"cropXOffset=0 " +
"cropYOffset=0 " +
"timeout=-1 ",
true);
"timeout=-1 "
);
}
@Test
@@ -273,8 +253,8 @@ public class TransformationOptionsConverterTest
"cropGravity=North " +
"cropXOffset=0 " +
"cropYOffset=0 " +
"timeout=-1 ",
true);
"timeout=-1 "
);
}
@Test
@@ -296,8 +276,8 @@ public class TransformationOptionsConverterTest
"cropWidth=30 " +
"cropXOffset=0 " +
"cropYOffset=0 " +
"timeout=-1 ",
true);
"timeout=-1 "
);
}
@Test
@@ -317,8 +297,8 @@ public class TransformationOptionsConverterTest
"cropPercentage=true " +
"cropXOffset=0 " +
"cropYOffset=0 " +
"timeout=-1 ",
true);
"timeout=-1 "
);
}
@Test
@@ -338,8 +318,8 @@ public class TransformationOptionsConverterTest
"[height=-1, width=-1, xOffset=20, yOffset=59, isPercentageCrop=false, gravity=null]} ]",
"cropXOffset=20 " +
"cropYOffset=59 " +
"timeout=-1 ",
true);
"timeout=-1 "
);
}
@Test
@@ -355,8 +335,8 @@ public class TransformationOptionsConverterTest
"ImageTransformationOptions [commandOptions=, " +
"resizeOptions=ImageResizeOptions [width=-1, height=-1, maintainAspectRatio=true, " +
"percentResize=false, resizeToThumbnail=false, allowEnlargement=true], autoOrient=false]]",
"timeout=-1 ",
true);
"timeout=-1 "
);
}
@Test
@@ -374,8 +354,8 @@ public class TransformationOptionsConverterTest
"resizeOptions=ImageResizeOptions [width=-1, height=-1, maintainAspectRatio=true, " +
"percentResize=false, resizeToThumbnail=false, allowEnlargement=false], autoOrient=false]]",
"allowEnlargement=false " +
"timeout=-1 ",
true);
"timeout=-1 "
);
}
@Test
@@ -393,8 +373,8 @@ public class TransformationOptionsConverterTest
"resizeOptions=ImageResizeOptions [width=-1, height=-1, maintainAspectRatio=false, " +
"percentResize=false, resizeToThumbnail=false, allowEnlargement=true], autoOrient=false]]",
"maintainAspectRatio=false " +
"timeout=-1 ",
true);
"timeout=-1 "
);
}
@Test
@@ -414,8 +394,8 @@ public class TransformationOptionsConverterTest
"percentResize=false, resizeToThumbnail=false, allowEnlargement=false], autoOrient=false]]",
"allowEnlargement=false " +
"maintainAspectRatio=false " +
"timeout=-1 ",
true);
"timeout=-1 "
);
}
@Test
@@ -437,8 +417,8 @@ public class TransformationOptionsConverterTest
"allowEnlargement=false " +
"maintainAspectRatio=false " +
"thumbnail=true " +
"timeout=-1 ",
true);
"timeout=-1 "
);
}
@Test
@@ -462,8 +442,8 @@ public class TransformationOptionsConverterTest
"maintainAspectRatio=false " +
"resizeHeight=15 " +
"resizeWidth=18 " +
"timeout=-1 ",
true);
"timeout=-1 "
);
}
@Test
@@ -485,8 +465,8 @@ public class TransformationOptionsConverterTest
"allowEnlargement=false " +
"maintainAspectRatio=false " +
"resizePercentage=true " +
"timeout=-1 ",
true);
"timeout=-1 "
);
}
@Test
@@ -505,8 +485,8 @@ public class TransformationOptionsConverterTest
"resizeOptions=null, autoOrient=false], " +
"sourceOptions={ PagedSourceOptionsPagedSourceOptions {1, 1}} ]",
"endPage=0 startPage=0 " +
"timeout=-1 ",
true);
"timeout=-1 "
);
}
@Test
@@ -525,8 +505,8 @@ public class TransformationOptionsConverterTest
"contentWriterNodeRef=null, pageLimit=-1, flashVersion=9, timeoutMs=-1, maxPages=-1, " +
"sourceContentProperty=null, targetContentProperty=null, includeEmbedded=null, readLimitTimeMs=-1}",
"flashVersion=9 " +
"timeout=-1 ",
false); // SWFTransformationOptions are not used by ImageMagickContentTransformerWorker
"timeout=-1 "
); // SWFTransformationOptions are not used by ImageMagickContentTransformerWorker
}
@Test
@@ -582,7 +562,7 @@ public class TransformationOptionsConverterTest
"resizeHeight=30 " +
"resizeWidth=20 " +
"startPage=0 " +
"timeout=-1 ",
true);
"timeout=-1 "
);
}
}

View File

@@ -50,7 +50,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
/**
* Tests for retrieving frozen content from a verioned node
* Tests for getting content readers and writers.
*
* @author Roy Wetherall
*/
@@ -110,57 +110,6 @@ public class ContentServiceImplTest extends BaseVersionStoreTest
assertEquals(UPDATED_CONTENT, contentReader2.getContentString());
}
@Test
@Deprecated
public void testTransformAndNulls()
{
NodeRef versionableNode = createNewVersionableNode();
ContentReader contentReader = this.contentService.getReader(versionableNode, ContentModel.PROP_CONTENT);
ContentWriter contentWriter = this.contentService.getWriter(versionableNode, ContentModel.PROP_CONTENT, false);
// this.nodeService.setProperty(versionableNode, ContentModel.PROP_NAME, "for debugTransformers.txt");
try
{
this.contentService.transform(new MimetypeMapTest.DummyContentReader(MimetypeMap.MIMETYPE_TEXT_PLAIN),
new MimetypeMapTest.DummyContentWriter(MimetypeMap.MIMETYPE_IMAGE_PNG),
new TransformationOptions(versionableNode,ContentModel.PROP_NAME, null, null));
} catch (NoTransformerException nte)
{
nte.getMessage().contains("No transformation exists");
}
try
{
this.contentService.transform(null, null, new TransformationOptions());
fail("Should throw exception");
}
catch (AlfrescoRuntimeException are)
{
are.getMessage().contains("The content reader must be set");
}
ContentReader empty = new EmptyContentReader("empty.txt");
try
{
this.contentService.transform(empty, null, new TransformationOptions());
fail("Should throw exception");
}
catch (AlfrescoRuntimeException are)
{
are.getMessage().contains("The content reader mimetype must be set");
}
try
{
contentWriter.setMimetype(null);
this.contentService.transform(contentReader, contentWriter, new TransformationOptions());
fail("Should throw exception");
}
catch (AlfrescoRuntimeException are)
{
are.getMessage().contains("The content writer mimetype must be set");
}
}
/**
* Test getWriter
*/
@@ -230,40 +179,4 @@ public class ContentServiceImplTest extends BaseVersionStoreTest
assertEquals(null, contentService.getDirectAccessUrl(nodeRef, null));
assertEquals(null, contentService.getDirectAccessUrl(nodeRef, expiresAt));
}
// Commented out as OpenOffice is not on the build machines.
// public void testGetTransformer0()
// {
// ContentTransformer transformer = contentService.getTransformer("test", "application/vnd.ms-excel", 0,
// "application/x-shockwave-flash", new TransformationOptions());
// assertTrue("Should have found a transformer for 0 bytes", transformer != null);
// }
//
// public void testGetTransformer10K()
// {
// ContentTransformer transformer = contentService.getTransformer("test", "application/vnd.ms-excel", 1024*10,
// "application/x-shockwave-flash", new TransformationOptions());
// assertTrue("Should have found a transformer for 10 K", transformer != null);
// }
//
// public void testGetTransformer1M()
// {
// ContentTransformer transformer = contentService.getTransformer("test", "application/vnd.ms-excel", 1024*1024,
// "application/x-shockwave-flash", new TransformationOptions());
// assertTrue("Should have found a transformer for 1M", transformer != null);
// }
//
// public void testGetTransformer10M()
// {
// ContentTransformer transformer = contentService.getTransformer("test", "application/vnd.ms-excel", 1024*1024*10,
// "application/x-shockwave-flash", new TransformationOptions());
// assertTrue("Should NOT have found a transformer for 10M as the is a 1M limit on xsl mimetype", transformer == null);
// }
//
// public void testGetMaxSourceSizeByes()
// {
// long maxSourceSizeBytes = contentService.getMaxSourceSizeBytes("application/vnd.ms-excel",
// "application/x-shockwave-flash", new TransformationOptions());
// assertEquals("Should have found a transformer that can handle 1M", 1024*1024, maxSourceSizeBytes);
// }
}

View File

@@ -1,11 +0,0 @@
#
# Copied form PdfBoxMetadataExtracter
#
# Namespaces
namespace.prefix.cm=http://www.alfresco.org/model/content/1.0
# Mappings
author=cm:author
title=cm:title
subject=cm:description
created=cm:created

View File

@@ -225,11 +225,6 @@ log4j.logger.freemarker.runtime=
# Metadata extraction
log4j.logger.org.alfresco.repo.content.metadata.AbstractMappingMetadataExtracter=warn
# Reduces PDFont error level due to ALF-7105
log4j.logger.org.apache.pdfbox.pdmodel.font.PDSimpleFont=fatal
log4j.logger.org.apache.pdfbox.pdmodel.font.PDFont=fatal
log4j.logger.org.apache.pdfbox.pdmodel.font.PDCIDFont=fatal
# no index support
log4j.logger.org.alfresco.repo.search.impl.noindex.NoIndexIndexer=fatal
log4j.logger.org.alfresco.repo.search.impl.noindex.NoIndexSearchService=fatal
@@ -255,7 +250,6 @@ log4j.logger.org.alfresco.repo.content.transform.TransformerDebug=debug
log4j.logger.org.alfresco.repo.rendition2=debug
#log4j.logger.org.alfresco.repo.rendition2.LocalTransformClient=debug
#log4j.logger.org.alfresco.repo.rendition2.LegacyTransformClient=debug
#log4j.logger.org.alfresco.repo.rendition.RenditionServiceImpl=debug
#log4j.logger.org.alfresco.enterprise.repo.rendition2.RemoteTransformClient=debug
log4j.logger.org.alfresco.repo.thumbnail.ThumbnailServiceImplTest=DEBUG

View File

@@ -1,100 +0,0 @@
<?xml version='1.0' encoding='UTF-8'?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="transformer.Test-PdfToText-AlwaysFails"
class="org.alfresco.repo.content.transform.DummyTestContentTransformer"
parent="baseContentTransformer" >
<property name="alwaysFail">
<value>true</value>
</property>
</bean>
<bean id="transformer.Test-PdfToText-AlwaysSucceeds"
class="org.alfresco.repo.content.transform.DummyTestContentTransformer"
parent="baseContentTransformer" >
<property name="alwaysFail">
<value>false</value>
</property>
</bean>
<bean id="transformer.failover.Test-FailThenSucceed"
class="org.alfresco.repo.content.transform.FailoverContentTransformer"
parent="baseContentTransformer" >
<property name="transformers">
<list>
<ref bean="transformer.Test-PdfToText-AlwaysFails"/>
<ref bean="transformer.Test-PdfToText-AlwaysSucceeds"/>
</list>
</property>
</bean>
<bean id="transformer.Test-DummyOpenOffice"
class="org.alfresco.repo.content.transform.DummyAnyToPDFTestSubtransformer"
parent="baseContentTransformer" >
</bean>
<bean id="transformer.Test-PasswordProtectedMSExcel2Pdf-AlwaysFails"
class="org.alfresco.repo.content.transform.DummyAnyToPDFTestSubtransformer"
parent="baseContentTransformer" >
<property name="alwaysFail">
<value>true</value>
</property>
</bean>
<bean id="transformer.Test-TriggeredFlag"
class="org.alfresco.repo.content.transform.TestHtml2PdfTriggeredFlag" />
<bean id="transformer.Test-Html2Pdf-ShoulNotBeTriggered"
class="org.alfresco.repo.content.transform.DummyTestComplexSubtransformer"
parent="baseComplexContentTransformer" >
<property name="triggered" ref="transformer.Test-TriggeredFlag" />
<property name="transformers">
<list>
<ref bean="transformer.Test-DummyOpenOffice" />
<ref bean="transformer.Test-DummyOpenOffice" />
</list>
</property>
<property name="intermediateMimetypes">
<list>
<value>application/vnd.oasis.opendocument.text</value>
</list>
</property>
<property name="supportedTransformations">
<list>
<bean class="org.alfresco.repo.content.transform.SupportedTransformation" >
<property name="sourceMimetype"><value>text/html</value></property>
<property name="targetMimetype"><value>application/pdf</value></property>
</bean>
</list>
</property>
<property name="explicitTransformations">
<list>
<bean class="org.alfresco.repo.content.transform.ExplictTransformationDetails" >
<property name="sourceMimetype"><value>text/html</value></property>
<property name="targetMimetype"><value>application/pdf</value></property>
</bean>
</list>
</property>
</bean>
<bean id="transformer.failover.Test-PasswordProtectedMSExcel2Pdf"
class="org.alfresco.repo.content.transform.TestFailoverContentTransformer"
parent="baseContentTransformer" >
<property name="triggered" ref="transformer.Test-TriggeredFlag" />
<property name="transformers">
<list>
<ref bean="transformer.Test-PasswordProtectedMSExcel2Pdf-AlwaysFails"/>
<ref bean="transformer.Test-Html2Pdf-ShoulNotBeTriggered"/>
</list>
</property>
</bean>
</beans>

View File

@@ -6,7 +6,7 @@
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="synchronousTransformClient" class="org.alfresco.repo.rendition2.TestSynchronousTransformClient">
<constructor-arg name="delegate" ref="switchingSynchronousTransformClient" />
<constructor-arg name="delegate" ref="localSynchronousTransformClient" />
</bean>
<bean id="transformClient" class="org.alfresco.repo.rendition2.TestAsynchronousTransformClient">

View File

@@ -9,7 +9,7 @@
</bean>
<!-- Keep it simple. Disable retries when the mimetype is wrong and we can transform what it is actually -->
<bean id="localTransformServiceRegistryImpl" class="org.alfresco.repo.content.transform.LocalTransformServiceRegistry" >
<bean id="localTransformServiceRegistry" class="org.alfresco.repo.content.transform.LocalTransformServiceRegistry" >
<property name="jsonObjectMapper" ref="localTransformServiceRegistryJsonObjectMapper" />
<property name="pipelineConfigDir" value="${local.transform.pipeline.config.dir}" />
<property name="enabled" value="${local.transform.service.enabled}" />