Java Code Examples for org.alfresco.repo.content.MimetypeMap

The following are top voted examples for showing how to use org.alfresco.repo.content.MimetypeMap. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: alfresco-repository   File: MultiTDemoTest.java   Source Code and License 6 votes vote down vote up
public void test18AddCustomWebClient()
{
    // note: add as demo files - need to re-start Alfresco to see custom web client config / messages 
    logger.info("test add custom web client config");
    
    for (final String tenantDomain : tenants)
    {    
        final String tenantAdminName = tenantService.getDomainUser(AuthenticationUtil.getAdminUserName(), tenantDomain);
        
        TenantUtil.runAsUserTenant(new TenantRunAsWork<Object>()
        {
            public Object doWork() throws Exception
            {
                NodeRef webClientExtFolder = getWebClientExtensionNodeRef(SPACES_STORE);
                
                InputStream is = getClass().getClassLoader().getResourceAsStream("tenant/webclient.properties");
                addContent(webClientExtFolder, "webclient.properties", is, MimetypeMap.MIMETYPE_TEXT_PLAIN);
                
                is = getClass().getClassLoader().getResourceAsStream("tenant/web-client-config-custom.xml");
                addContent(webClientExtFolder, "web-client-config-custom.xml", is, MimetypeMap.MIMETYPE_XML);
                
                return null;
            }
        }, tenantAdminName, tenantDomain);
    }
}
 
Example 2
Project: alfresco-repository   File: MetadataExtracterLimitsTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests that delayed metadata extraction times out properly for mimetype-specific limits.
 *
 * @throws Exception
 */
@Test
public void testMimetypeSpecificTimeout() throws Exception
{
    long timeoutMs = 1000;

    MetadataExtracterLimits limits = new MetadataExtracterLimits();
    limits.setTimeoutMs(timeoutMs);
    HashMap<String, MetadataExtracterLimits> mimetypeLimits =
            new HashMap<String, MetadataExtracterLimits>(1);
    mimetypeLimits.put(MimetypeMap.MIMETYPE_TEXT_PLAIN, limits);
    ((MockDelayedMetadataExtracter) getExtracter()).setMimetypeLimits(mimetypeLimits);

    File file = AbstractContentTransformerTest.loadNamedQuickTestFile("quick.txt");

    long startTime = (new Date()).getTime();
    extractFromFile(file, MimetypeMap.MIMETYPE_TEXT_PLAIN);
    long extractionTime = (new Date()).getTime() - startTime;

    assertTrue("Metadata extraction took (" + extractionTime + "ms) " +
            "but should have failed with a timeout at " + timeoutMs + "ms",
            extractionTime < (timeoutMs + 50)); // bit of wiggle room for logging, cleanup, etc.
}
 
Example 3
Project: alfresco-repository   File: RepositoryExporterComponent.java   Source Code and License 6 votes vote down vote up
public FileExportHandle exportSystem(String packageName)
{
    // create a temporary file to hold the system info export
    File tempFile = TempFileProvider.createTempFile("repoExpSystemInfo", ".xml");

    try
    {
        OutputStream outputStream = new FileOutputStream(tempFile);
        systemExporterImporter.exportSystem(outputStream);
    }
    catch(FileNotFoundException e)
    {
        tempFile.delete();
        throw new ExporterException("Failed to create temporary file for holding export of system info");
    }
    
    // return handle onto temp file
    FileExportHandle handle = new FileExportHandle();
    handle.storeRef = null;
    handle.packageName = packageName;
    handle.mimeType = MimetypeMap.MIMETYPE_XML;
    handle.exportFile = tempFile;
    return handle;
}
 
Example 4
Project: alfresco-repository   File: EMLTransformerTest.java   Source Code and License 6 votes vote down vote up
/**
 * 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));
}
 
Example 5
Project: alfresco-repository   File: ActionServiceImpl2Test.java   Source Code and License 6 votes vote down vote up
@Test//(expected = AccessDeniedException.class)
public void testTransform() throws Exception
{
    final File file = loadAndAddQuickFileAsManager(testNode, "quick.txt", MimetypeMap.MIMETYPE_TEXT_PLAIN);
    assertNotNull("Failed to load required test file.", file);

    // Set authentication to SiteConsumer.
    AuthenticationUtil.setFullyAuthenticatedUser(testSiteAndMemberInfo.siteManager);
    transactionHelper.doInTransaction(new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            Action action = actionService.createAction(TransformActionExecuter.NAME);
            Map<String, Serializable> map = new HashMap<String, Serializable>();
            map.put(TransformActionExecuter.PARAM_MIME_TYPE, MimetypeMap.MIMETYPE_HTML);
            map.put(TransformActionExecuter.PARAM_DESTINATION_FOLDER, nodeService.getPrimaryParent(testNode)
                    .getParentRef());
            action.setParameterValues(map);

            actionService.executeAction(action, testNode);

            return null;
        }
    });
}
 
Example 6
Project: alfresco-repository   File: ActionServiceImplTest.java   Source Code and License 6 votes vote down vote up
@Override
protected void onSetUpInTransaction() throws Exception
{
    super.onSetUpInTransaction();

    this.transactionHelper = (RetryingTransactionHelper)this.applicationContext.getBean("retryingTransactionHelper");

    // Create the node used for tests
    this.nodeRef = this.nodeService.createNode(
            this.rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("{test}testnode"),
            ContentModel.TYPE_CONTENT).getChildRef();
    this.nodeService.setProperty(
            this.nodeRef,
            ContentModel.PROP_CONTENT,
            new ContentData(null, MimetypeMap.MIMETYPE_TEXT_PLAIN, 0L, null));
    this.folder = this.nodeService.createNode(
            this.rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("{test}testFolder"),
            ContentModel.TYPE_FOLDER).getChildRef();
    
    // Register the test executor, if needed
    SleepActionExecuter.registerIfNeeded(applicationContext);
}
 
Example 7
Project: alfresco-remote-api   File: ResourceWebScriptPut.java   Source Code and License 6 votes vote down vote up
/**
    * Returns the basic content info from the request.
    * @param req WebScriptRequest
    * @return BasicContentInfo
    */
   private BasicContentInfo getContentInfo(WebScriptRequest req) {
   	
	String encoding = "UTF-8";
	String contentType = MimetypeMap.MIMETYPE_BINARY;
	
	if (StringUtils.isNotEmpty(req.getContentType()))
	{
		MediaType media = MediaType.parseMediaType(req.getContentType());
		contentType = media.getType()+'/'+media.getSubtype();
		if (media.getCharSet() != null)
		{
			encoding = media.getCharSet().toString();
		}			
	}

       return new ContentInfoImpl(contentType, encoding, -1, Locale.getDefault());
}
 
Example 8
Project: alfresco-repository   File: MediaWikiContentTransformerTest.java   Source Code and License 6 votes vote down vote up
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);
   }
}
 
Example 9
Project: alfresco-repository   File: RenditionServiceIntegrationTest.java   Source Code and License 6 votes vote down vote up
private NodeRef createFreeMarkerNode(NodeRef companyHome)
{
    NodeRef fmNode = createContentNode(companyHome, "testFreeMarkerNode");
    nodeService.setProperty(fmNode, ContentModel.PROP_CONTENT, new ContentData(null,
                MimetypeMap.MIMETYPE_TEXT_PLAIN, 0L, null));

    URL url = getClass().getResource(FM_TEMPLATE);
    assertNotNull("The url is null", url);
    File templateFile = new File(url.getFile());
    assertTrue("The template file does not exist", templateFile.exists());

    ContentWriter fmWriter = contentService.getWriter(fmNode, ContentModel.PROP_CONTENT, true);
    fmWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    fmWriter.setEncoding("UTF-8");
    fmWriter.putContent(templateFile);
    return fmNode;
}
 
Example 10
Project: alfresco-repository   File: OOoContentTransformerHelper.java   Source Code and License 6 votes vote down vote up
/**
 * There are some conversions that fail, despite the converter believing them possible.
 * This method can be used by subclasses to check if a targetMimetype or source/target
 * Mimetype pair are blocked.
 * 
 * @param sourceMimetype String
 * @param targetMimetype String
 * @return <code>true</code> if the mimetypes are blocked, else <code>false</code>
 */
protected boolean isTransformationBlocked(String sourceMimetype, String targetMimetype)
{
    if (targetMimetype.equals(MimetypeMap.MIMETYPE_XHTML))
    {
        return true;
    }
    else if (targetMimetype.equals(MimetypeMap.MIMETYPE_WORDPERFECT))
    {
        return true;
    }
    else if (targetMimetype.equals(MimetypeMap.MIMETYPE_FLASH))
    {
        return true;
    }
    else
    {
        return false;
    }
}
 
Example 11
Project: alfresco-repository   File: SpoofedTextContentReaderTest.java   Source Code and License 6 votes vote down vote up
public void testStaticUrlForm_02()
{
    // To URL
    String url = SpoofedTextContentReader.createContentUrl(Locale.ENGLISH, 12345L, 1024L);
    assertTrue(url.startsWith("spoof://{"));
    assertTrue(url.contains("\"locale\":\"en\""));
    assertTrue(url.contains("\"seed\":\"12345\""));
    assertTrue(url.contains("\"size\":\"1024\""));
    assertTrue(url.contains("\"words\":[]"));
    assertTrue(url.endsWith("}"));
    // From Reader
    SpoofedTextContentReader reader = new SpoofedTextContentReader(url);
    assertNotNull(reader.getTextGenerator());
    assertEquals(Locale.ENGLISH, reader.getLocale());
    assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, reader.getMimetype());
    assertEquals("UTF-8", reader.getEncoding());
    assertEquals(12345L, reader.getSeed());
    assertEquals(1024L, reader.getSize());
    assertNotNull(reader.getWords());
    assertEquals(0, reader.getWords().length);
}
 
Example 12
Project: alfresco-remote-api   File: ThumbnailServiceTest.java   Source Code and License 6 votes vote down vote up
public void testCreateThumbnailInReadonlyMode() throws Exception
{
    createUser(USER_ALFRESCO);
    AuthenticationUtil.setFullyAuthenticatedUser(USER_ALFRESCO);
    this.transactionService.setAllowWrite(false);
    
    // do pdfToSWF transformation in read-only
    if (this.contentService.getTransformer(MimetypeMap.MIMETYPE_PDF, MimetypeMap.MIMETYPE_FLASH) != null)
    {
        // in share creation of thumbnail for webpreview is forced
        String url = "/api/node/" + pdfNode.getStoreRef().getProtocol() + "/" + pdfNode.getStoreRef().getIdentifier() + "/" + pdfNode.getId() + "/content/thumbnails/webpreview?c=force";
        
        JSONObject tn = new JSONObject();
        tn.put("thumbnailName", "webpreview");
        
        sendRequest(new GetRequest(url), 200, USER_ALFRESCO);
    }
    
    this.transactionService.setAllowWrite(true);
    
    // Check getAll whilst we are here 
    Response getAllResp = sendRequest(new GetRequest(getThumbnailsURL(jpgNode)), 200);
    JSONArray getArr = new JSONArray(getAllResp.getContentAsString());
    assertNotNull(getArr);
    assertEquals(0, getArr.length());
}
 
Example 13
Project: alfresco-repository   File: PdfBoxMetadataExtracterTest.java   Source Code and License 6 votes vote down vote up
@Override
public void setUp() throws Exception
{
    super.setUp();
    extracter = new PdfBoxMetadataExtracter();
    extracter.setDictionaryService(dictionaryService);
    
    MetadataExtracterLimits pdfLimit = new MetadataExtracterLimits();
    pdfLimit.setMaxConcurrentExtractionsCount(MAX_CONCURENT_EXTRACTIONS);
    pdfLimit.setMaxDocumentSizeMB(MAX_DOC_SIZE_MB);
    Map<String,MetadataExtracterLimits> limits = new HashMap<>();
    limits.put(MimetypeMap.MIMETYPE_PDF,pdfLimit);
    
    extracter.setMimetypeLimits(limits);
    extracter.register();
}
 
Example 14
Project: alfresco-repository   File: AlfrescoPdfRendererContentTransformerWorker.java   Source Code and License 6 votes vote down vote up
@Override
public boolean isTransformable(String sourceMimetype, String targetMimetype, TransformationOptions options)
{
    if (!available)
    {
        return false;
    }

    // Add limited support (so lots of other transforms are not supported)
    // for PDF to PNG.
    if ((MimetypeMap.MIMETYPE_PDF.equals(sourceMimetype) || MimetypeMap.MIMETYPE_APPLICATION_ILLUSTRATOR.equals(sourceMimetype)) &&
        MimetypeMap.MIMETYPE_IMAGE_PNG.equals(targetMimetype))
    {
        return true;
    }

    return false;
}
 
Example 15
Project: alfresco-remote-api   File: SerializeTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testInvokeMultiPartEntity() throws IOException
{
    ResourceWithMetadata entityResource = locator.locateEntityResource(api,"multiparttest", HttpMethod.POST);
    assertNotNull(entityResource);
    MultiPartResourceAction.Create<?> resource = (MultiPartResourceAction.Create<?>) entityResource.getResource();

    File file = TempFileProvider.createTempFile("ParamsExtractorTests-", ".txt");
    PrintWriter writer = new PrintWriter(file);
    writer.println("Multipart Mock test2.");
    writer.close();

    MultiPartRequest reqBody = MultiPartBuilder.create()
                .setFileData(new FileData(file.getName(), file, MimetypeMap.MIMETYPE_TEXT_PLAIN))
                .build();

    MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST", "");
    mockRequest.setContent(reqBody.getBody());
    mockRequest.setContentType(reqBody.getContentType());

    String out = writeResponse(helper.processAdditionsToTheResponse(mock(WebScriptResponse.class), api,null, NOT_USED, resource.create(new FormData(mockRequest), NOT_USED, callBack)));
    assertTrue("There must be json output", StringUtils.startsWith(out, "{\"entry\":"));
}
 
Example 16
Project: alfresco-remote-api   File: RepoService.java   Source Code and License 6 votes vote down vote up
public NodeRef addUserDescription(final String personId, final TestNetwork network, final String personDescription)
{
	return AuthenticationUtil.runAsSystem(new RunAsWork<NodeRef>()
	{
		//@Override
		public NodeRef doWork() throws Exception
		{
			NodeRef userRef = personService.getPersonOrNull(personId);
			if (userRef == null)
			{
				throw new AuthenticationException("User name does not exist: " + personId);
			}

			ContentWriter writer = contentService.getWriter(userRef, ContentModel.PROP_PERSONDESC, true);
			writer.setMimetype(MimetypeMap.MIMETYPE_HTML);
			writer.putContent(personDescription);

			log("Updated person description " + personId + (network != null ? " in network " + network : ""));
			return userRef;
		}
	});
}
 
Example 17
Project: alfresco-repository   File: TikaAutoMetadataExtracter.java   Source Code and License 6 votes vote down vote up
/**
 * Because some editors use JPEG_IMAGE_HEIGHT_TAG when
 * saving JPEG images , a more reliable source for
 * image size are the values provided by Tika
 * and not the exif/tiff metadata read from the file
 * This will override the tiff:Image size 
 * which gets embedded into the alfresco node properties
 * for jpeg files that contain such exif information
 */
@Override
protected Map<String, Serializable> extractSpecific(Metadata metadata,
     Map<String, Serializable> properties, Map<String,String> headers) 
{
    
    if(MimetypeMap.MIMETYPE_IMAGE_JPEG.equals(metadata.get(Metadata.CONTENT_TYPE)))                
    {
        //check if the image has exif information
        if(metadata.get(EXIF_IMAGE_WIDTH_TAG) != null && metadata.get(EXIF_IMAGE_HEIGHT_TAG) != null )
        {    
            //replace the exif size properties that will be embedded in the node with
            //the guessed dimensions from Tika
            putRawValue(TIFF.IMAGE_LENGTH.getName(), extractSize(metadata.get(JPEG_IMAGE_HEIGHT_TAG)), properties);
            putRawValue(TIFF.IMAGE_WIDTH.getName(), extractSize(metadata.get(JPEG_IMAGE_WIDTH_TAG)), properties);
        }
    }
    return properties;
}
 
Example 18
Project: alfresco-remote-api   File: QuickShareRestApiTest.java   Source Code and License 6 votes vote down vote up
private void checkTransformer()
{
    AuthenticationUtil.runAs(new RunAsWork<Void>()
    {
        @Override
        public Void doWork() throws Exception
        {
            ContentTransformer transformer = contentService.getImageTransformer();

            assertNotNull("No transformer returned for 'getImageTransformer'", transformer);

            // Check that it is working
            ImageTransformationOptions imageTransformationOptions = new ImageTransformationOptions();
            if (!transformer.isTransformable(MimetypeMap.MIMETYPE_IMAGE_JPEG, -1, MimetypeMap.MIMETYPE_IMAGE_PNG, imageTransformationOptions))

            {
                fail("Image transformer is not working.  Please check your image conversion command setup.");
            }

            return null;
        }
    }, AuthenticationUtil.getAdminUserName());
}
 
Example 19
Project: alfresco-repository   File: PoiHssfContentTransformerTest.java   Source Code and License 6 votes vote down vote up
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
   );
}
 
Example 20
Project: alfresco-repository   File: DictionaryModelTypeTest.java   Source Code and License 6 votes vote down vote up
private NodeRef createActiveModel(String contentFile)
{
    PropertyMap properties = new PropertyMap(1);
    properties.put(ContentModel.PROP_MODEL_ACTIVE, true);
    NodeRef modelNode = this.nodeService.createNode(
             this.rootNodeRef,
             ContentModel.ASSOC_CHILDREN,
             QName.createQName(NamespaceService.ALFRESCO_URI, "dictionaryModels"),
             ContentModel.TYPE_DICTIONARY_MODEL,
             properties).getChildRef();
     assertNotNull(modelNode);

     ContentWriter contentWriter = this.contentService.getWriter(modelNode, ContentModel.PROP_CONTENT, true);
     contentWriter.setEncoding("UTF-8");
     contentWriter.setMimetype(MimetypeMap.MIMETYPE_XML);
     contentWriter.putContent(Thread.currentThread().getContextClassLoader().getResourceAsStream(contentFile));
     return modelNode;
}
 
Example 21
Project: alfresco-repository   File: EMLTransformerTest.java   Source Code and License 6 votes vote down vote up
/**
 * 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));
}
 
Example 22
Project: alfresco-expirable-content   File: ExpiredContentReportWriter.java   Source Code and License 6 votes vote down vote up
private NodeRef createContentNode(NodeRef parent, String name, String text) {

        Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
        props.put(ContentModel.PROP_NAME, name);

        // use the node service to create a new node
        NodeRef node = this.nodeService.createNode(
                parent,
                ContentModel.ASSOC_CONTAINS,
                QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name),
                ContentModel.TYPE_CONTENT,
                props).getChildRef();

        // Use the content service to set the content onto the newly created node
        ContentWriter writer = this.contentService.getWriter(node, ContentModel.PROP_CONTENT, true);
        writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
        writer.setEncoding("UTF-8");
        writer.putContent(text);

        // Return a node reference to the newly created node
        return node;
    }
 
Example 23
Project: alfresco-repository   File: EMLTransformerTest.java   Source Code and License 6 votes vote down vote up
/**
 * 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));
}
 
Example 24
Project: alfresco-repository   File: ThumbnailServiceImplTest.java   Source Code and License 6 votes vote down vote up
private NodeRef createCorruptedContent(NodeRef parentFolder) throws IOException
{
    // The below pdf file has been truncated such that it is identifiable as a PDF but otherwise corrupt.
    File corruptPdfFile = AbstractContentTransformerTest.loadNamedQuickTestFile("quickCorrupt.pdf");
    assertNotNull("Failed to load required test file.", corruptPdfFile);

    Map<QName, Serializable> props = new HashMap<QName, Serializable>();
    props.put(ContentModel.PROP_NAME, "corrupt.pdf");
    NodeRef node = this.secureNodeService.createNode(parentFolder, ContentModel.ASSOC_CONTAINS,
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "quickCorrupt.pdf"),
            ContentModel.TYPE_CONTENT, props).getChildRef();

    secureNodeService.setProperty(node, ContentModel.PROP_CONTENT, new ContentData(null,
                MimetypeMap.MIMETYPE_PDF, 0L, null));
    ContentWriter writer = contentService.getWriter(node, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
    writer.setEncoding("UTF-8");
    writer.putContent(corruptPdfFile);
    
    return node;
}
 
Example 25
Project: alfresco-repository   File: ThumbnailServiceImplTest.java   Source Code and License 6 votes vote down vote up
public void testJSAPI() throws Exception
{
    NodeRef jpgOrig = createOriginalContent(this.folder, MimetypeMap.MIMETYPE_IMAGE_JPEG);
    NodeRef gifOrig = createOriginalContent(this.folder, MimetypeMap.MIMETYPE_IMAGE_GIF);
    NodeRef pdfOrig = createOriginalContent(this.folder, MimetypeMap.MIMETYPE_PDF);
    NodeRef docOrig = createOriginalContent(this.folder, MimetypeMap.MIMETYPE_WORD);

    Map<String, Object> model = new HashMap<String, Object>(2);
    model.put("jpgOrig", jpgOrig);
    model.put("gifOrig", gifOrig);
    model.put("pdfOrig", pdfOrig);
    model.put("docOrig", docOrig);

    ScriptLocation location = new ClasspathScriptLocation("org/alfresco/repo/thumbnail/script/test_thumbnailAPI.js");
    this.scriptService.executeScript(location, model);
}
 
Example 26
Project: alfresco-repository   File: PoiContentTransformerTest.java   Source Code and License 6 votes vote down vote up
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()));
}
 
Example 27
Project: alfresco-repository   File: MetadataExtracterLimitsTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests that delayed metadata extraction times out properly for wildcard mimetype limits.
 *
 * @throws Exception
 */
@Test
public void testWildcardTimeout() throws Exception
{
    long timeoutMs = 1000;

    MetadataExtracterLimits limits = new MetadataExtracterLimits();
    limits.setTimeoutMs(timeoutMs);
    HashMap<String, MetadataExtracterLimits> mimetypeLimits =
            new HashMap<String, MetadataExtracterLimits>(1);
    mimetypeLimits.put("*", limits);
    ((MockDelayedMetadataExtracter) getExtracter()).setMimetypeLimits(mimetypeLimits);

    File file = AbstractContentTransformerTest.loadNamedQuickTestFile("quick.txt");

    long startTime = (new Date()).getTime();
    extractFromFile(file, MimetypeMap.MIMETYPE_TEXT_PLAIN);
    long extractionTime = (new Date()).getTime() - startTime;

    assertTrue("Metadata extraction took (" + extractionTime + "ms) " +
            "but should have failed with a timeout at " + timeoutMs + "ms",
            extractionTime < (timeoutMs + 50)); // bit of wiggle room for logging, cleanup, etc.
}
 
Example 28
Project: alfresco-remote-api   File: ThumbnailServiceTest.java   Source Code and License 6 votes vote down vote up
public void testPlaceHolder()
    throws Exception
{
    if (this.contentService.getTransformer(MimetypeMap.MIMETYPE_PDF, MimetypeMap.MIMETYPE_FLASH) != null)
    {
        // Check that there is no place holder set for webpreview
        sendRequest(new GetRequest(getThumbnailsURL(pdfNode) + "/webpreview"), 404);
        sendRequest(new GetRequest(getThumbnailsURL(pdfNode) + "/webpreview?ph=true"), 404);
    }
    
    // Check that here is a place holder for medium
    sendRequest(new GetRequest(getThumbnailsURL(jpgNode) + "/medium"), 404);
    sendRequest(new GetRequest(getThumbnailsURL(jpgNode) + "/medium?ph=true"), 200);
    
    System.out.println(getThumbnailsURL(jpgNode) + "/medium?ph=true");
}
 
Example 29
Project: alfresco-repository   File: RenditionServiceIntegrationTest.java   Source Code and License 5 votes vote down vote up
private CompositeRenditionDefinition makeCompositeReformatAndResizeDefinition(final QName renditionName,
            final int newX, final int newY)
{
    CompositeRenditionDefinition compositeDefinition = renditionService
                .createCompositeRenditionDefinition(renditionName);
    RenditionDefinition reformatDefinition = makeReformatAction(null, MimetypeMap.MIMETYPE_IMAGE_JPEG);
    RenditionDefinition rescaleImageDefinition = makeRescaleImageAction();
    rescaleImageDefinition.setParameterValue(ImageRenderingEngine.PARAM_RESIZE_WIDTH, newX);
    rescaleImageDefinition.setParameterValue(ImageRenderingEngine.PARAM_RESIZE_HEIGHT, newY);

    compositeDefinition.addAction(reformatDefinition);
    compositeDefinition.addAction(rescaleImageDefinition);
    return compositeDefinition;
}
 
Example 30
Project: alfresco-repository   File: PdfBoxContentTransformerTest.java   Source Code and License 5 votes vote down vote up
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()));
}
 
Example 31
Project: alfresco-repository   File: RepositoryExporterComponent.java   Source Code and License 5 votes vote down vote up
public FileExportHandle exportStore(ExporterCrawlerParameters exportParameters, String packageName, Exporter progress)
{
    // create a temporary file to hold the acp export
    File systemTempDir = TempFileProvider.getSystemTempDir();
    File tempFile = TempFileProvider.createTempFile("repoExp" + packageName, "." + ACPExportPackageHandler.ACP_EXTENSION, systemTempDir);

    // create acp export handler around the temp file
    File dataFile = new File(packageName);
    File contentDir = new File(packageName);
    try
    {
        OutputStream outputStream = new FileOutputStream(tempFile);
        ACPExportPackageHandler acpHandler = new ACPExportPackageHandler(outputStream, dataFile, contentDir, mimetypeService);

        // export the store
        exporterService.exportView(acpHandler, exportParameters, progress);
    }
    catch(FileNotFoundException e)
    {
        tempFile.delete();
        throw new ExporterException("Failed to create temporary file for holding export of store " + exportParameters.getExportFrom().getStoreRef());
    }
        
    // return handle onto temp file
    FileExportHandle handle = new FileExportHandle();
    handle.storeRef = exportParameters.getExportFrom().getStoreRef();
    handle.packageName = packageName;
    handle.mimeType = MimetypeMap.MIMETYPE_ACP;
    handle.exportFile = tempFile;
    return handle;
}
 
Example 32
Project: alfresco-repository   File: RepositoryExporterComponent.java   Source Code and License 5 votes vote down vote up
public FileExportHandle exportStore(ExporterCrawlerParameters exportParameters, String packageName, Exporter progress)
{
    // create a file to hold the acp export
    File file = new File(directoryDestination, packageName + "." + ACPExportPackageHandler.ACP_EXTENSION);

    // create acp export handler around the temp file
    File dataFile = new File(packageName);
    File contentDir = new File(packageName);
    try
    {
        OutputStream outputStream = new FileOutputStream(file);
        ACPExportPackageHandler acpHandler = new ACPExportPackageHandler(outputStream, dataFile, contentDir, mimetypeService);

        // export the store
        exporterService.exportView(acpHandler, exportParameters, progress);
    }
    catch(FileNotFoundException e)
    {
        file.delete();
        throw new ExporterException("Failed to create file " + file.getAbsolutePath() + " for holding the export of store " + exportParameters.getExportFrom().getStoreRef());
    }
        
    // return handle onto temp file
    FileExportHandle handle = new FileExportHandle();
    handle.storeRef = exportParameters.getExportFrom().getStoreRef();
    handle.packageName = packageName;
    handle.mimeType = MimetypeMap.MIMETYPE_ACP;
    handle.exportFile = file;
    return handle;
}
 
Example 33
Project: alfresco-repository   File: TemporaryNodes.java   Source Code and License 5 votes vote down vote up
/**
 * This method creates a cm:content NodeRef whose content is taken from the named Alfresco 'quick' file and adds it to the internal
 * list of NodeRefs to be tidied up by the rule.
 * This method will be run in its own transaction and will be run with the specified user as the fully authenticated user,
 * thus ensuring the named user is the cm:creator of the new node.
 *
 * @param quickFileName the file name of the quick file - will also be the cm:name of the new node.
 * @param parentNode the parent node
 * @param nodeCreator the username of the person who will create the node
 * @return the newly created NodeRef.
 * @since 4.1.4
 */
public NodeRef createQuickFileByName(final String quickFileName, final NodeRef parentNode, final String nodeCreator)
{
    final MimetypeMap mimetypeService = (MimetypeMap) appContextRule.getApplicationContext().getBean("mimetypeService");
    final RetryingTransactionHelper transactionHelper = (RetryingTransactionHelper) appContextRule.getApplicationContext().getBean("retryingTransactionHelper");
    
    AuthenticationUtil.pushAuthentication();
    AuthenticationUtil.setFullyAuthenticatedUser(nodeCreator);
    
    NodeRef newNodeRef = transactionHelper.doInTransaction(new RetryingTransactionCallback<NodeRef>()
    {
        public NodeRef execute() throws Throwable
        {
            final NodeRef result = createNode(quickFileName, parentNode, ContentModel.TYPE_CONTENT);
            
            File quickFile = AbstractContentTransformerTest.loadNamedQuickTestFile(quickFileName);
            
            ContentService contentService = appContextRule.getApplicationContext().getBean("contentService", ContentService.class);
            ContentWriter writer = contentService.getWriter(result, ContentModel.PROP_CONTENT, true);
            writer.setMimetype(mimetypeService.guessMimetype(quickFileName));
            writer.setEncoding("UTF-8");
            writer.putContent(quickFile);
            
            return result;
        }
    });
    
    AuthenticationUtil.popAuthentication();
    
    this.temporaryNodeRefs.add(newNodeRef);
    return newNodeRef;
}
 
Example 34
Project: alfresco-repository   File: RuleTypeImplTest.java   Source Code and License 5 votes vote down vote up
public void testMockInboundRuleType()
{
	List<RuleTrigger> triggers = new ArrayList<RuleTrigger>(2);
    triggers.add((RuleTrigger)this.applicationContext.getBean("on-content-create-trigger"));
	triggers.add((RuleTrigger)this.applicationContext.getBean("on-create-node-trigger"));
	triggers.add((RuleTrigger)this.applicationContext.getBean("on-create-child-association-trigger"));
	
	ExtendedRuleType ruleType = new ExtendedRuleType(triggers);
	assertFalse(ruleType.rulesTriggered);
	
    NodeRef nodeRef = this.nodeService.createNode(
            this.rootNodeRef, 
            ContentModel.ASSOC_CHILDREN,
            ContentModel.ASSOC_CHILDREN,
            ContentModel.TYPE_CONTENT).getChildRef();
    
	// Update some content in order to trigger the rule type
	ContentWriter contentWriter = this.contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
	contentWriter.putContent("any old content");        
	assertTrue(ruleType.rulesTriggered);
	
    NodeRef nodeRef2 = this.nodeService.createNode(
            this.rootNodeRef, 
            ContentModel.ASSOC_CHILDREN,
            ContentModel.ASSOC_CHILDREN,
            ContentModel.TYPE_CONTAINER).getChildRef();
	
	// Reset
	ruleType.rulesTriggered = false;
	assertFalse(ruleType.rulesTriggered);
	
	// Create a child association in order to trigger the rule type
	this.nodeService.addChild(
			nodeRef2, 
			nodeRef, 
			ContentModel.ASSOC_CHILDREN,
			ContentModel.ASSOC_CHILDREN);
	assertTrue(ruleType.rulesTriggered);
}
 
Example 35
Project: alfresco-repository   File: AbstractJodConverterBasedTest.java   Source Code and License 5 votes vote down vote up
/**
 * Returns <code>true</code> if OpenOffice-based transformations are currently known to
 * be available, else <code>false</code>.
 */
protected boolean isOpenOfficeAvailable()
{
	ContentTransformer transformer = contentService.getTransformer(null, MimetypeMap.MIMETYPE_WORD, -1, MimetypeMap.MIMETYPE_PDF, new TransformationOptions());

	// A transformer may not be returned here if it is unavailable.
	if (transformer == null)
	{
		return false;
	}
	
	// Maybe it's non-null, but not available.
	boolean isTransformable = transformer.isTransformable(MimetypeMap.MIMETYPE_WORD, -1, MimetypeMap.MIMETYPE_PDF, null);
	return isTransformable;
}
 
Example 36
Project: alfresco-repository   File: AbstractImageMagickContentTransformerWorker.java   Source Code and License 5 votes vote down vote up
/**
 * Some image formats are not supported by ImageMagick, or at least appear not to work.
 * 
 * @param mimetype the mimetype to check
 * @return Returns true if ImageMagic can handle the given image format
 */
public static boolean isSupported(String mimetype)
{
    // There are a few mimetypes in the system that do not start with "image/" but which
    // nevertheless are supported by this transformer.
    if (mimetype.equals(MimetypeMap.MIMETYPE_APPLICATION_EPS))
    {
        return true;
    }
    else if (mimetype.equals(MimetypeMap.MIMETYPE_APPLICATION_PHOTOSHOP))
    {
        return true;
    }
    
    else if (!mimetype.startsWith(MIMETYPE_IMAGE_PREFIX))
    {
        return false;   // not an image
    }
    else if (mimetype.equals(MimetypeMap.MIMETYPE_IMAGE_RGB))
    {
        return false;   // rgb extension doesn't work
    }
    else if (mimetype.equals(MimetypeMap.MIMETYPE_IMAGE_SVG))
    {
        return false;   // svg extension doesn't work
    }
    else if (mimetype.equals(MimetypeMap.MIMETYPE_IMG_DWG))
    {
        return false;   // dwg extension doesn't work
    }
    else if (mimetype.equals(MimetypeMap.MIMETYPE_IMAGE_DWT))
    {
        return false;   // dwt extension doesn't work
    }
    else
    {
        return true;
    }
}
 
Example 37
Project: alfresco-repository   File: AbstractImageMagickContentTransformerWorker.java   Source Code and License 5 votes vote down vote up
/**
 * Supports image to image conversion, but only if the JMagick library and required
 * libraries are available.
 */
public boolean isTransformable(String sourceMimetype, String targetMimetype, TransformationOptions options)
{
    if (!available)
    {
        return false;
    }
    
    // Add limited support (so lots of other transforms are not supported) for PDF to PNG. An ALF-14303 workaround.
    // Will only be used as part of failover transformer.PdfToImage. Note .ai is the same format as .pdf
    if ( (MimetypeMap.MIMETYPE_PDF.equals(sourceMimetype) ||
          MimetypeMap.MIMETYPE_APPLICATION_ILLUSTRATOR.equals(sourceMimetype)) &&
          MimetypeMap.MIMETYPE_IMAGE_PNG.equals(targetMimetype))
    {
        return true;
    }
    
    // Add extra support for tiff to pdf to allow multiple page preview (ALF-7278)
    if (MimetypeMap.MIMETYPE_IMAGE_TIFF.equals(sourceMimetype) &&
        MimetypeMap.MIMETYPE_PDF.equals(targetMimetype))
    {
        return true;
    }
    
    if (!AbstractImageMagickContentTransformerWorker.isSupported(sourceMimetype) ||
            !AbstractImageMagickContentTransformerWorker.isSupported(targetMimetype))
    {
        // only support IMAGE -> IMAGE (excl. RGB)
        return false;
    }
    else
    {
        return true;
    }
}
 
Example 38
Project: alfresco-repository   File: PoiHssfContentTransformer.java   Source Code and License 5 votes vote down vote up
/**
 * Make sure we win over openoffice when it comes to producing
 *  HTML
 */
@Override
public boolean isExplicitTransformation(String sourceMimetype, String targetMimetype, TransformationOptions options)
{
   if(sourceMimeTypes.contains(sourceMimetype) &&
         (MimetypeMap.MIMETYPE_HTML.equals(targetMimetype) ||
          MimetypeMap.MIMETYPE_XHTML.equals(targetMimetype)) )
   {
      // Special case to win for HTML 
      return true;
   }
   
   // Otherwise fall back on the default Tika rules
   return super.isTransformableMimetype(sourceMimetype, targetMimetype, options);
}
 
Example 39
Project: alfresco-repository   File: TikaPoweredContentTransformer.java   Source Code and License 5 votes vote down vote up
/**
 * Returns an appropriate Tika ContentHandler for the
 *  requested content type. Normally you'll let this
 *  work as default, but if you need fine-grained
 *  control of how the Tika events become text then
 *  override and supply your own.
 */
protected ContentHandler getContentHandler(String targetMimeType, Writer output) 
               throws TransformerConfigurationException
{
   if(MimetypeMap.MIMETYPE_TEXT_PLAIN.equals(targetMimeType)) 
   {
      return new BodyContentHandler(output);
   }
   
   SAXTransformerFactory factory = (SAXTransformerFactory)
         SAXTransformerFactory.newInstance();
   TransformerHandler handler = factory.newTransformerHandler();
   handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
   handler.setResult(new StreamResult(output));
   
   if(MimetypeMap.MIMETYPE_HTML.equals(targetMimeType))
   {
      handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "html");
      return new ExpandedTitleContentHandler(handler);
   }
   else if(MimetypeMap.MIMETYPE_XHTML.equals(targetMimeType) ||
           MimetypeMap.MIMETYPE_XML.equals(targetMimeType))
   {
      handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "xml");
   }
   else
   {
      throw new TransformerInfoException(
            WRONG_FORMAT_MESSAGE_ID,
            new IllegalArgumentException("Requested target type " + targetMimeType + " not supported")
      );
   }
   return handler;
}
 
Example 40
Project: alfresco-remote-api   File: SearchProxy.java   Source Code and License 5 votes vote down vote up
/**
 * Construct a "proxied" search engine url
 * 
 * @param engine  engine name (as identified by <engine proxy="<name>">)
 * @param mimetype  url to proxy (as identified by mimetype)
 * @return  "proxied" url
 */
public String createUrl(OpenSearchConfigElement.EngineConfig engine, String mimetype)
{
    Map<String, String> urls = engine.getUrls();
    String url = urls.get(mimetype);
    if (url != null)
    {
        String proxy = engine.getProxy();
        if (proxy != null && !mimetype.equals(MimetypeMap.MIMETYPE_OPENSEARCH_DESCRIPTION))
        {
            url = createUrl(proxy, url, mimetype);
        }
    }
    return url;
}
 
Example 41
Project: alfresco-repository   File: ActivitiTimerExecutionTest.java   Source Code and License 5 votes vote down vote up
protected WorkflowDefinition deployDefinition(String resource)
{
    InputStream input = getInputStream(resource);
    WorkflowDeployment deployment = workflowService.deployDefinition(ActivitiConstants.ENGINE_ID, input, MimetypeMap.MIMETYPE_XML);
    WorkflowDefinition definition = deployment.getDefinition();
    return definition;
}
 
Example 42
Project: alfresco-repository   File: DifferrentMimeTypeTest.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 43
Project: alfresco-repository   File: EMLTransformer.java   Source Code and License 5 votes vote down vote up
@Override
public boolean isTransformableMimetype(String sourceMimetype, String targetMimetype, TransformationOptions options)
{
    if (!MimetypeMap.MIMETYPE_RFC822.equals(sourceMimetype)
            || !MimetypeMap.MIMETYPE_TEXT_PLAIN.equals(targetMimetype))
    {
        // only support RFC822 -> TEXT
        return false;
    }
    else
    {
        return true;
    }
}
 
Example 44
Project: alfresco-repository   File: DifferrentMimeTypeTest.java   Source Code and License 5 votes vote down vote up
public void testWrongExtensionStrict() throws IOException
{
    testTransformToJPeg("quick-differentMimetype.docx",
        MimetypeMap.MIMETYPE_OPENXML_WORDPROCESSING,
        MimetypeMap.MIMETYPE_OPENXML_WORDPROCESSING,
        MimetypeMap.MIMETYPE_IMAGE_PNG,
        STRICT, FAILURE);
}
 
Example 45
Project: alfresco-repository   File: BinaryPassThroughContentTransformerTest.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 46
Project: alfresco-repository   File: XPathContentWorkerSelector.java   Source Code and License 5 votes vote down vote up
public XPathContentWorkerSelector()
{
    try
    {
        documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        xpathFactory = XPathFactory.newInstance();
    }
    catch (Throwable e)
    {
        throw new AlfrescoRuntimeException("Failed to initialize XPathContentWorkerSelector", e);
    }
    supportedMimetypes = new HashSet<String>();
    supportedMimetypes.add(MimetypeMap.MIMETYPE_XML);
}
 
Example 47
Project: alfresco-repository   File: ContentStoreCleanerScalabilityRunner.java   Source Code and License 5 votes vote down vote up
private void loadData(final int maxCount)
{
    final MutableInt doneCount = new MutableInt(0);
    // Batches of 1000 objects
    RetryingTransactionCallback<Integer> makeNodesCallback = new RetryingTransactionCallback<Integer>()
    {
        public Integer execute() throws Throwable
        {
            for (int i = 0; i < 1000; i++)
            {
                // We don't need to write anything
                String contentUrl = FileContentStore.createNewFileStoreUrl();
                ContentData contentData = new ContentData(contentUrl, MimetypeMap.MIMETYPE_TEXT_PLAIN, 10, "UTF-8");
                nodeHelper.makeNode(contentData);
                
                int count = doneCount.intValue();
                count++;
                doneCount.setValue(count);
                
                // Do some reporting
                if (count % 1000 == 0)
                {
                    System.out.println(String.format("   " + (new Date()) + "Total created: %6d", count));
                }
                
                // Double check for shutdown
                if (vmShutdownListener.isVmShuttingDown())
                {
                    break;
                }
            }
            return maxCount;
        }
    };
    int repetitions = (int) Math.floor((double)maxCount / 1000.0);
    for (int i = 0; i < repetitions; i++)
    {
        transactionService.getRetryingTransactionHelper().doInTransaction(makeNodesCallback);
    }
}
 
Example 48
Project: alfresco-repository   File: RefreshTagScopeActionExecuter.java   Source Code and License 5 votes vote down vote up
/**
 * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.action.Action, org.alfresco.service.cmr.repository.NodeRef)
 */
@Override
protected void executeImpl(final Action action, final NodeRef actionedUponNodeRef)
{
    if (this.nodeService.exists(actionedUponNodeRef) == true &&
        this.nodeService.hasAspect(actionedUponNodeRef, ContentModel.ASPECT_TAGSCOPE) == true)
    {
        // Run the update as the system user
        AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>()
        {
            @SuppressWarnings("unchecked")
            public Object doWork() throws Exception
            {
                // Create a new list of tag details
                List<TagDetails> tags = new ArrayList<TagDetails>(10);
                
                // Count the tags found in all the (primary) children of the node
                countTags(actionedUponNodeRef, tags);
                
                // Order the list
                Collections.sort(tags);
                
                // Write new content back to tag scope
                String tagContent = TaggingServiceImpl.tagDetailsToString(tags);
                if(tagContent.length() > 0)
                {
                	// Write out tag content only if non-zero in size
                 ContentWriter contentWriter = contentService.getWriter(actionedUponNodeRef, ContentModel.PROP_TAGSCOPE_CACHE, true);
                 contentWriter.setEncoding("UTF-8");
                 contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
                 contentWriter.putContent(tagContent);
                }

                return null;
            }
            
        }, AuthenticationUtil.getSystemUserName());                      
    }
}
 
Example 49
Project: alfresco-repository   File: MultiTDemoTest.java   Source Code and License 5 votes vote down vote up
public void test12CreateVersionableUserContent()
{
    logger.info("Create demo content");
    
    List<String> users = new ArrayList<String>(3);
    users.add(TEST_USER1);
    users.add(TEST_USER2);
    users.add(TEST_USER3);
    
    for (final String tenantDomain : tenants)
    {
        for (String baseUserName : users)
        {
            if ((! baseUserName.equals(TEST_USER3)) || (tenantDomain.equals(TEST_TENANT_DOMAIN2)))
            {
                final String tenantUserName = tenantService.getDomainUser(baseUserName, tenantDomain);
                
                TenantUtil.runAsUserTenant(new TenantRunAsWork<Object>()
                {
                    public Object doWork() throws Exception
                    {
                        NodeRef homeSpaceRef = getHomeSpaceFolderNode(tenantUserName);
                        
                        NodeRef contentRef = addContent(homeSpaceRef, tenantUserName+" quick brown fox.txt", "The quick brown fox jumps over the lazy dog (tenant " + tenantDomain + ")", MimetypeMap.MIMETYPE_TEXT_PLAIN);
                        nodeService.addAspect(contentRef, ContentModel.ASPECT_VERSIONABLE, null);
                        
                        if (tenantDomain.equals(TEST_TENANT_DOMAIN2))
                        {
                            contentRef = addContent(homeSpaceRef, tenantUserName+" quick brown fox ANO.txt", "The quick brown fox jumps over the lazy dog ANO (tenant " + tenantDomain + ")", MimetypeMap.MIMETYPE_TEXT_PLAIN);
                            nodeService.addAspect(contentRef, ContentModel.ASPECT_VERSIONABLE, null);
                        }
                        
                        return null;
                    }
                }, tenantUserName, tenantDomain);
            }
        }
    }
}
 
Example 50
Project: alfresco-repository   File: RenditionServiceIntegrationTest.java   Source Code and License 5 votes vote down vote up
private String readTextContent(NodeRef nodeRef)
{
    ContentReader reader = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
    assertNotNull("reader was null", reader);
    reader.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    return reader.getContentString();
}
 
Example 51
Project: alfresco-repository   File: ImageMagickContentTransformerTest.java   Source Code and License 5 votes vote down vote up
@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");
}
 
Example 52
Project: alfresco-repository   File: CropSourceOptions.java   Source Code and License 5 votes vote down vote up
@Override
public boolean isApplicableForMimetype(String sourceMimetype)
{
    return ((sourceMimetype != null && 
            sourceMimetype.startsWith(MimetypeMap.PREFIX_IMAGE)) ||
            super.isApplicableForMimetype(sourceMimetype));
}
 
Example 53
Project: alfresco-repository   File: AbstractTenantRoutingContentStoreTest.java   Source Code and License 5 votes vote down vote up
public void testGetAllStores() throws Exception
{
    final RetryingTransactionCallback<Object> txnWork = new RetryingTransactionCallback<Object>()
    {
        public Boolean execute() throws Exception
        {
            // The listener
            final TestAfterRollbackTxnListener listener = new TestAfterRollbackTxnListener();
            AlfrescoTransactionSupport.bindListener(listener);

            NodeRef content = createContent(serviceRegistry);

            ContentWriter writer = contentService.getWriter(content, ContentModel.PROP_CONTENT, true);
            writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
            writer.putContent("The quick brown fox jumps over the lazy dog");

            throw new AlfrescoRuntimeException("Some error that causes RollBack. The transaction will be closed");
        }
    };

    try
    {
        serviceRegistry.getTransactionService().getRetryingTransactionHelper().doInTransaction(txnWork, false, false);
    }
    catch (AlfrescoRuntimeException e)
    {
        // Expected
    }

    assertFalse("getAllStores method returned the list with null entry", isNullEntry);
}
 
Example 54
Project: alfresco-repository   File: BulkImportTest.java   Source Code and License 5 votes vote down vote up
@Test
// Tests the mimetype is set correctly for .ai and eps files, plus gif (which was working anyway).
public void testMNT18275_ai_eps() throws Throwable
{
    NodeRef folderNode = topLevelFolder.getNodeRef();
    NodeImporter nodeImporter = null;

    txn = transactionService.getUserTransaction();
    txn.begin();

    nodeImporter = streamingNodeImporterFactory.getNodeImporter(ResourceUtils.getFile("classpath:bulkimport5"));

    BulkImportParameters bulkImportParameters = new BulkImportParameters();
    bulkImportParameters.setTarget(folderNode);
    bulkImportParameters.setReplaceExisting(true);
    bulkImportParameters.setDisableRulesService(true);
    bulkImportParameters.setBatchSize(40);
    bulkImporter.bulkImport(bulkImportParameters, nodeImporter);

    System.out.println(bulkImporter.getStatus());

    checkFiles(folderNode, null, 0, 3, new ExpectedFile[] {
            new ExpectedFile("quick.gif", MimetypeMap.MIMETYPE_IMAGE_GIF),
            new ExpectedFile("Amazing.ai", MimetypeMap.MIMETYPE_APPLICATION_ILLUSTRATOR),
            new ExpectedFile("quick.eps", MimetypeMap.MIMETYPE_APPLICATION_EPS)
    },
    new ExpectedFolder[] {
    });
}
 
Example 55
Project: alfresco-repository   File: DictionaryRepositoryBootstrapTest.java   Source Code and License 5 votes vote down vote up
/**
 * Create model node 
 * 
 * @param uri String
 * @param prefix String
 * @param modelLocalName String
 * @param importStatement String
 * @param description String
 * @param typeName String
 * @param propertyName String
 * @return NodeRef
 */
private NodeRef createModelNode(
        String uri, 
        String prefix, 
        String modelLocalName, 
        String importStatement, 
        String description, 
        String typeName,
        String propertyName)
{
    // Create a model node
    NodeRef model = this.nodeService.createNode(
            this.rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("{test}models"),
            ContentModel.TYPE_DICTIONARY_MODEL).getChildRef();
    ContentWriter contentWriter1 = this.contentService.getWriter(model, ContentModel.PROP_CONTENT, true);
    contentWriter1.setEncoding("UTF-8");
    contentWriter1.setMimetype(MimetypeMap.MIMETYPE_XML);
    String modelOne = getModelString(
                uri,
                prefix,
                modelLocalName,
                importStatement,
                description,
                typeName,
                propertyName);        
    contentWriter1.putContent(modelOne);
    
    // activate the model
    nodeService.setProperty(model, ContentModel.PROP_MODEL_ACTIVE, new Boolean(true));
    
    return model;
}
 
Example 56
Project: alfresco-remote-api   File: ContentGetTest.java   Source Code and License 5 votes vote down vote up
public NodeRef createNodeWithTextContent(NodeRef parentNode, String nodeCmName, QName nodeType, String content)
{
    NodeRef nodeRef = createNode(parentNode, nodeCmName, nodeType);

    // If there is any content, add it.
    if (content != null)
    {
        ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
        writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
        writer.setEncoding("UTF-8");
        writer.putContent(content);
    }
    return nodeRef;

}
 
Example 57
Project: alfresco-repository   File: ContentMetadataExtracterTagMappingTest.java   Source Code and License 5 votes vote down vote up
public TagMappingMetadataExtracter()
{
    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());
    setMappingProperties(mappingProperties);
}
 
Example 58
Project: alfresco-repository   File: ContentMetadataEmbedderTest.java   Source Code and License 5 votes vote down vote up
@Override
protected void onSetUpInTransaction() throws Exception
{
    this.nodeService = (NodeService) this.applicationContext.getBean("nodeService");
    this.contentService = (ContentService) this.applicationContext.getBean("contentService");
    this.dictionaryService = (DictionaryService) this.applicationContext.getBean("dictionaryService");
    this.mimetypeService = (MimetypeService) this.applicationContext.getBean("mimetypeService");
    this.metadataExtracterRegistry  = (MetadataExtracterRegistry) this.applicationContext.getBean("metadataExtracterRegistry");
    
    AuthenticationComponent authenticationComponent = (AuthenticationComponent)applicationContext.getBean("authenticationComponent");
    authenticationComponent.setSystemUserAsCurrentUser();

    // Create the store and get the root node
    this.testStoreRef = this.nodeService.createStore(
            StoreRef.PROTOCOL_WORKSPACE,
            "Test_" + System.currentTimeMillis());
    this.rootNodeRef = this.nodeService.getRootNode(this.testStoreRef);

    // Create the node used for tests
    this.nodeRef = this.nodeService.createNode(
            this.rootNodeRef, ContentModel.ASSOC_CHILDREN,
            QName.createQName("{test}testnode"),
            ContentModel.TYPE_CONTENT).getChildRef();

    // Setup the content from the PDF test data
    ContentWriter cw = this.contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    cw.setMimetype(MimetypeMap.MIMETYPE_PDF);
    cw.putContent(AbstractContentTransformerTest.loadQuickTestFile("pdf"));

    // Get the executer instance
    this.executer = new ContentMetadataEmbedder();
    this.executer.setNodeService(nodeService);
    this.executer.setContentService(contentService);
    this.executer.setMetadataExtracterRegistry(metadataExtracterRegistry);
    this.executer.setApplicableTypes(new String[] { ContentModel.TYPE_CONTENT.toString() });
}
 
Example 59
Project: alfresco-remote-api   File: MimetypesGetTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests the <code>mimetypesGet.getTransformer</code> method directly for
 * varefication of label text
 * 
 * @throws Exception
 */
public void testGetTransformer() throws Exception
{
    MimetypesGet mimetypesGet = new MimetypesGet();
    mimetypesGet.setApplicationContext(ctx);
    mimetypesGet.setContentTransformerRegistry(contentTransformerRegistry);
    mimetypesGet.afterPropertiesSet();
    
    // Test a Java transformer name
    String transformerName = mimetypesGet.getTransformer(MimetypeMap.MIMETYPE_PDF, 1000, MimetypeMap.MIMETYPE_TEXT_PLAIN);
    assertEquals(PdfBoxContentTransformer.class.getCanonicalName(), transformerName);
    
    // Test a generic proxy transformer name
    transformerName = mimetypesGet.getTransformer(MimetypeMap.MIMETYPE_IMAGE_JPEG, 1000, MimetypeMap.MIMETYPE_IMAGE_PNG);
    assertNotNull(transformerName);
    assertTrue("Expected transformerName to contain 'Proxy' but was " + transformerName,
            transformerName.contains("Proxy via"));
    
    boolean jodPresent = ctx.containsBean(MimetypesGet.JOD_WORKER_BEAN);
    
    // Test the office transformer name
    transformerName = mimetypesGet.getTransformer(MimetypeMap.MIMETYPE_WORD, 1000, MimetypeMap.MIMETYPE_PDF);
    assertNotNull(transformerName);
    if (jodPresent)
    {
        assertEquals("Using JOD Converter / Open Office", transformerName);
    }
}
 
Example 60
Project: alfresco-repository   File: RenditionServiceIntegrationTest.java   Source Code and License 5 votes vote down vote up
/**
 * This test method ensures that all the 'built-in' renditionDefinitions are
 * available after startup and that their configuration is correct.
 * 
 * @throws Exception
 */
public void testBuiltinRenditionDefinitions() throws Exception
{
    final RenditionDefinition mediumRenditionDef = loadAndValidateRenditionDefinition("medium");
    final RenditionDefinition doclibRenditionDef = loadAndValidateRenditionDefinition("doclib");
    final RenditionDefinition imgpreviewRenditionDef = loadAndValidateRenditionDefinition("imgpreview");
    final RenditionDefinition webpreviewRenditionDef = loadAndValidateRenditionDefinition("webpreview");
    final RenditionDefinition avatarRenditionDef = loadAndValidateRenditionDefinition("avatar");

    assertEquals(MimetypeMap.MIMETYPE_IMAGE_JPEG, mediumRenditionDef.getParameterValue(AbstractRenderingEngine.PARAM_MIME_TYPE));
    assertEquals(MimetypeMap.MIMETYPE_IMAGE_PNG, doclibRenditionDef.getParameterValue(AbstractRenderingEngine.PARAM_MIME_TYPE));
    assertEquals(MimetypeMap.MIMETYPE_IMAGE_JPEG, imgpreviewRenditionDef.getParameterValue(AbstractRenderingEngine.PARAM_MIME_TYPE));
    assertEquals(MimetypeMap.MIMETYPE_FLASH, webpreviewRenditionDef.getParameterValue(AbstractRenderingEngine.PARAM_MIME_TYPE));
    assertEquals(MimetypeMap.MIMETYPE_IMAGE_PNG, avatarRenditionDef.getParameterValue(AbstractRenderingEngine.PARAM_MIME_TYPE));
}