Java Code Examples for org.alfresco.service.cmr.repository.ContentWriter#putContent()

The following examples show how to use org.alfresco.service.cmr.repository.ContentWriter#putContent() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RoutingContentServiceTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testOnContentReadPolicy()
{
    // Register interest in the content read event for a versionable node
    this.policyComponent.bindClassBehaviour(
            QName.createQName(NamespaceService.ALFRESCO_URI, "onContentRead"),
            ContentModel.ASPECT_VERSIONABLE,
            new JavaBehaviour(this, "onContentReadBehaviourTest"));
    
    // First check that the policy is not fired when the versionable aspect is not present
    this.contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertFalse(this.readPolicyFired);
    
    // Write some content and check that the policy is still not fired
    ContentWriter contentWriter2 = this.contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter2.putContent("content update two");
    this.contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertFalse(this.readPolicyFired);
    
    // Now check that the policy is fired when the versionable aspect is present
    this.nodeService.addAspect(this.contentNodeRef, ContentModel.ASPECT_VERSIONABLE, null);
    this.contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertTrue(this.readPolicyFired);
}
 
Example 2
Source File: MultiUserRenditionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private NodeRef createPdfDocumentAsCurrentlyAuthenticatedUser(final String nodeName)
{
    Map<QName, Serializable> props = new HashMap<QName, Serializable>();
    props.put(ContentModel.PROP_NAME, nodeName);
    NodeRef result = nodeService.createNode(testFolder, 
                                            ContentModel.ASSOC_CONTAINS, 
                                            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, nodeName), 
                                            ContentModel.TYPE_CONTENT,
                                            props).getChildRef();
    
    File file = loadQuickPdfFile();

    // Set the content
    ContentWriter writer = contentService.getWriter(result, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
    writer.setEncoding("UTF-8");
    
    writer.putContent(file);
    
    return result;
}
 
Example 3
Source File: ThumbnailServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 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 4
Source File: GetChildrenCannedQueryTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private NodeRef createContent(NodeRef parentNodeRef, QName childAssocType, String fileName, QName contentType) throws IOException
{
    Map<QName,Serializable> properties = new HashMap<QName,Serializable>();
    properties.put(ContentModel.PROP_NAME, fileName);
    properties.put(ContentModel.PROP_TITLE, fileName+" my title");
    properties.put(ContentModel.PROP_DESCRIPTION, fileName+" my description");
    
    NodeRef nodeRef = nodeService.getChildByName(parentNodeRef, childAssocType, fileName);
    if (nodeRef != null)
    {
        nodeService.deleteNode(nodeRef);
    }
    
    nodeRef = nodeService.createNode(parentNodeRef,
    		childAssocType,
    		QName.createQName(fileName),
    		contentType,
    		properties).getChildRef();

    ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(mimetypeService.guessMimetype(fileName));
    writer.putContent("my text content");

    return nodeRef;
}
 
Example 5
Source File: FullTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void canGuessMimeType()
{
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    
    ContentService contentService = (ContentService) ctx.getBean("ContentService");
    NodeService nodeService = (NodeService) ctx.getBean("NodeService");
    StoreRef storeRef = nodeService.createStore("workspace", getClass().getName()+UUID.randomUUID());
    NodeRef rootNodeRef = nodeService.getRootNode(storeRef);
    NodeRef nodeRef = nodeService.createNode(
                rootNodeRef,
                ContentModel.ASSOC_CHILDREN,
                QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, getClass().getSimpleName()),
                ContentModel.TYPE_CONTENT).getChildRef();

    ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    // Pre-condition of test is that we're testing with a potentially problematic BackingStoreAwareCacheWriter
    // rather than a FileContentWriter, which we would expect to work.
    assertTrue(writer instanceof BackingStoreAwareCacheWriter);
    
    String content = "This is some content";
    writer.putContent(content);
    writer.guessMimetype("myfile.txt");
    
    assertEquals("text/plain", writer.getMimetype());
}
 
Example 6
Source File: MessageServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void addMessageResource(NodeRef rootNodeRef, String name, InputStream resourceStream) throws Exception
{       
    Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>();
    contentProps.put(ContentModel.PROP_NAME, name);
    
    ChildAssociationRef association = nodeService.createNode(rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name),
            ContentModel.TYPE_CONTENT,
            contentProps);
    
    NodeRef content = association.getChildRef();
    
    ContentWriter writer = contentService.getWriter(content, ContentModel.PROP_CONTENT, true);

    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    writer.setEncoding("UTF-8");

    writer.putContent(resourceStream);
    resourceStream.close();
}
 
Example 7
Source File: FixTemplatePatch.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void updateContent(NodeRef nodeRef)
{
    // Make versionable
    nodeService.addAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE, null);
    
    // Update content
    InputStream is = this.getClass().getClassLoader().getResourceAsStream(source);
    if (is != null)
    {
        ContentWriter contentWriter = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
        contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
        contentWriter.setEncoding("UTF-8");
        contentWriter.putContent(is);
    }
}
 
Example 8
Source File: MultiTDemoTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private NodeRef addContent(NodeRef spaceRef, String name, InputStream is, String mimeType)
{
    Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>();
    contentProps.put(ContentModel.PROP_NAME, name);
    
    ChildAssociationRef association = nodeService.createNode(spaceRef,
            ContentModel.ASSOC_CONTAINS, 
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name), 
            ContentModel.TYPE_CONTENT,
            contentProps);
    
    NodeRef content = association.getChildRef();
    
    // add titled aspect (for Web Client display)
    Map<QName, Serializable> titledProps = new HashMap<QName, Serializable>();
    titledProps.put(ContentModel.PROP_TITLE, name);
    titledProps.put(ContentModel.PROP_DESCRIPTION, name);
    this.nodeService.addAspect(content, ContentModel.ASPECT_TITLED, titledProps);
    
    ContentWriter writer = contentService.getWriter(content, ContentModel.PROP_CONTENT, true);
    
    writer.setMimetype(mimeType);
    writer.setEncoding("UTF-8");
    
    writer.putContent(is);
    
    return content;
}
 
Example 9
Source File: FileFolderServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testGetReaderWriter() throws Exception
{
    // testing a failure
    txn.commit();
    txn = transactionService.getUserTransaction();
    txn.begin();

    FileInfo dirInfo = getByName(NAME_L0_FOLDER_A, true);

    UserTransaction rollbackTxn = null;
    try
    {
        rollbackTxn = transactionService.getNonPropagatingUserTransaction();
        rollbackTxn.begin();
        fileFolderService.getWriter(dirInfo.getNodeRef());
        fail("Failed to detect content write to folder");
    }
    catch (RuntimeException e)
    {
        // expected
    }
    finally
    {
        rollbackTxn.rollback();
    }

    FileInfo fileInfo = getByName(NAME_L1_FILE_A, false);

    ContentWriter writer = fileFolderService.getWriter(fileInfo.getNodeRef());
    assertNotNull("Writer is null", writer);
    // write some content
    String content = "ABC";
    writer.putContent(content);
    // read the content
    ContentReader reader = fileFolderService.getReader(fileInfo.getNodeRef());
    assertNotNull("Reader is null", reader);
    String checkContent = reader.getContentString();
    assertEquals("Content mismatch", content, checkContent);
}
 
Example 10
Source File: StreamingNodeImporterFactory.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected final void importContentAndMetadata(NodeRef nodeRef, ImportableItem.ContentAndMetadata contentAndMetadata, MetadataLoader.Metadata metadata)
 {
 	// Write the content of the file
 	if (contentAndMetadata.contentFileExists())
 	{
 		String filename = getFileName(contentAndMetadata.getContentFile());

 		if (logger.isDebugEnabled())
{
 			logger.debug("Streaming contents of file '" + filename + "' into node '" + nodeRef.toString() + "'.");
}

 		ContentWriter writer = fileFolderService.getWriter(nodeRef);
 		try
 		{
 		    writer.putContent(Files.newInputStream(contentAndMetadata.getContentFile()));
 		}
 		catch (IOException e)
 		{
 		    throw new ContentIOException("Failed to copy content from file: \n" +
 		            "   writer: " + writer + "\n" +
 		            "   file: " + contentAndMetadata.getContentFile(),
 		            e);
 		}
 	}
 	else
 	{
 		if (logger.isDebugEnabled()) logger.debug("No content to stream into node '" + nodeRef.toString() + "' - importing metadata only.");
 	}

 	// Attach aspects and set all properties
 	importImportableItemMetadata(nodeRef, contentAndMetadata.getContentFile(), metadata);
 }
 
Example 11
Source File: ImporterActionExecuterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void putContent(NodeRef zipFileNodeRef, String resource)
{
    URL url = AbstractContentTransformerTest.class.getClassLoader().getResource(resource);
    final File file = new File(url.getFile());
    
    ContentWriter writer = contentService.getWriter(zipFileNodeRef, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(MimetypeMap.MIMETYPE_ZIP);
    writer.putContent(file);
}
 
Example 12
Source File: AggregatingContentStoreTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * This implementation creates some content in the store and returns the new content URL.
 */
protected String getExistingContentUrl()
{
    ContentWriter writer = getWriter();
    writer.putContent("Content for getExistingContentUrl");
    return writer.getContentUrl();
}
 
Example 13
Source File: StringExtractingContentTransformerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 14
Source File: RuleServiceCoverageTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
   * Test:
   *          rule type:  inbound
   *          condition:  no-condition()
   *          action:     transform()
   */
  public void testTransformAction() throws Throwable
  {
      Map<String, Serializable> params = new HashMap<String, Serializable>(1);
params.put(TransformActionExecuter.PARAM_MIME_TYPE, MimetypeMap.MIMETYPE_TEXT_PLAIN);
      params.put(TransformActionExecuter.PARAM_DESTINATION_FOLDER, this.rootNodeRef);
      params.put(TransformActionExecuter.PARAM_ASSOC_TYPE_QNAME, ContentModel.ASSOC_CHILDREN);
      params.put(TransformActionExecuter.PARAM_ASSOC_QNAME, QName.createQName(TEST_NAMESPACE, "transformed"));
      
      Rule rule = createRule(
      		RuleType.INBOUND, 
      		TransformActionExecuter.NAME, 
      		params, 
      		NoConditionEvaluator.NAME, 
      		null);
      
      this.ruleService.saveRule(this.nodeRef, rule);

      UserTransaction tx = transactionService.getUserTransaction();
tx.begin();

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

// Create the node at the root
      NodeRef newNodeRef = this.nodeService.createNode(
              this.nodeRef,
              ContentModel.ASSOC_CHILDREN,                
              QName.createQName(TEST_NAMESPACE, "origional"),
              ContentModel.TYPE_CONTENT,
              props).getChildRef(); 

// Set some content on the origional
ContentWriter contentWriter = this.contentService.getWriter(newNodeRef, ContentModel.PROP_CONTENT, true);
      contentWriter.setMimetype(MimetypeMap.MIMETYPE_EXCEL);
File testFile = AbstractContentTransformerTest.loadQuickTestFile("xls");
contentWriter.putContent(testFile);

tx.commit();
      
      //System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.testStoreRef));
      
      AuthenticationComponent authenticationComponent = (AuthenticationComponent)applicationContext.getBean("authenticationComponent");
      authenticationComponent.setCurrentUser(authenticationComponent.getSystemUserName());
      
      // Check that the created node is still there
      List<ChildAssociationRef> origRefs = this.nodeService.getChildAssocs(
              this.nodeRef, 
              RegexQNamePattern.MATCH_ALL, QName.createQName(TEST_NAMESPACE, "origional"));
      assertNotNull(origRefs);
      assertEquals(1, origRefs.size());
      NodeRef origNodeRef = origRefs.get(0).getChildRef();
      assertEquals(newNodeRef, origNodeRef);

      // Check that the created node has been copied
      List<ChildAssociationRef> copyChildAssocRefs = this.nodeService.getChildAssocs(
                                                  this.rootNodeRef, 
                                                  RegexQNamePattern.MATCH_ALL, QName.createQName(TEST_NAMESPACE, "test.txt"));
      assertNotNull(copyChildAssocRefs);
      assertEquals(1, copyChildAssocRefs.size());
      NodeRef copyNodeRef = copyChildAssocRefs.get(0).getChildRef();
      assertTrue(this.nodeService.hasAspect(copyNodeRef, ContentModel.ASPECT_COPIEDFROM));
      NodeRef source = copyService.getOriginal(copyNodeRef);
      assertEquals(newNodeRef, source);
      
      // Check the transformed content
      ContentData contentData = (ContentData) nodeService.getProperty(copyNodeRef, ContentModel.PROP_CONTENT);
assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, contentData.getMimetype());
  }
 
Example 15
Source File: OOoContentTransformerHelper.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void transform(
        ContentReader reader,
        ContentWriter writer,
        TransformationOptions options) throws Exception
{
    if (isAvailable() == false)
    {
        throw new ContentIOException("Content conversion failed (unavailable): \n" +
                "   reader: " + reader + "\n" +
                "   writer: " + writer);
    }
    
    if (getLogger().isDebugEnabled())
    {
            StringBuilder msg = new StringBuilder();
            msg.append("transforming content from ")
                .append(reader.getMimetype())
                .append(" to ")
                .append(writer.getMimetype());
            getLogger().debug(msg.toString());
    }
    
    String sourceMimetype = getMimetype(reader);
    String targetMimetype = getMimetype(writer);

    MimetypeService mimetypeService = getMimetypeService();
    String sourceExtension = mimetypeService.getExtension(sourceMimetype);
    String targetExtension = mimetypeService.getExtension(targetMimetype);
    // query the registry for the source format
    DocumentFormat sourceFormat = formatRegistry.getFormatByExtension(sourceExtension);
    if (sourceFormat == null)
    {
        // source format is not recognised
        throw new ContentIOException("No OpenOffice document format for source extension: " + sourceExtension);
    }
    // query the registry for the target format
    DocumentFormat targetFormat = formatRegistry.getFormatByExtension(targetExtension);
    if (targetFormat == null)
    {
        // target format is not recognised
        throw new ContentIOException("No OpenOffice document format for target extension: " + targetExtension);
    }
    // get the family of the target document
    DocumentFamily sourceFamily = sourceFormat.getInputFamily();
    // does the format support the conversion
    if (!formatRegistry.getOutputFormats(sourceFamily).contains(targetFormat)) // same as: targetFormat.getStoreProperties(sourceFamily) == null
    {
        throw new ContentIOException(
                "OpenOffice conversion not supported: \n" +
                "   reader: " + reader + "\n" +
                "   writer: " + writer);
    }

    // There is a bug (reported in ALF-219) whereby JooConverter (the Alfresco Community Edition's 3rd party
    // OpenOffice connector library) struggles to handle zero-size files being transformed to pdf.
    // For zero-length .html files, it throws NullPointerExceptions.
    // For zero-length .txt files, it produces a pdf transformation, but it is not a conformant
    // pdf file and cannot be viewed (contains no pages).
    //
    // For these reasons, if the file is of zero length, we will not use JooConverter & OpenOffice
    // and will instead ask Apache PDFBox to produce an empty pdf file for us.
    final long documentSize = reader.getSize();
    if (documentSize == 0L || temporaryMsFile(options))
    {
        File tempToFile = TempFileProvider.createTempFile(
                getTempFilePrefix()+"-target-",
                "." + targetExtension);
        produceEmptyPdfFile(tempToFile);
        writer.putContent(tempToFile);
    }
    else
    {
        if (remoteTransformerClientConfigured())
        {
            transformRemote(reader, writer, options, sourceMimetype, sourceExtension, targetMimetype, targetExtension);
        }
        else
        {
            transformLocal(reader, writer, options, sourceMimetype,
                    sourceExtension, targetExtension, sourceFormat, targetFormat);
        }
    }

    if (getLogger().isDebugEnabled())
    {
        getLogger().debug("transformation successful");
    }
}
 
Example 16
Source File: AggregatingContentStoreTest.java    From alfresco-simple-content-stores with Apache License 2.0 4 votes vote down vote up
@Test
public void defaultSecondaryStoreDeletionWithPartiallyDifferentProtocol() throws Exception
{
    final AggregatingContentStore aggregatingContentStore = new AggregatingContentStore();

    // all stores need to use identical protocol in content URLs
    final FileContentStore store1 = new FileContentStore();
    store1.setRootDirectory(store1Folder.getAbsolutePath());
    store1.setProtocol(STORE_1_PROTOCOL);
    aggregatingContentStore.setPrimaryStore(store1);

    final FileContentStore store2 = new FileContentStore();
    store2.setRootDirectory(store2Folder.getAbsolutePath());
    store2.setProtocol(STORE_1_PROTOCOL);

    final FileContentStore store3 = new FileContentStore();
    store3.setRootDirectory(store3Folder.getAbsolutePath());
    store3.setProtocol(STORE_3_PROTOCOL);

    aggregatingContentStore.setSecondaryStores(Arrays.asList(store2, store3));

    store1.afterPropertiesSet();
    store2.afterPropertiesSet();
    store3.afterPropertiesSet();
    aggregatingContentStore.afterPropertiesSet();

    final String text = generateText(SEED_PRNG.nextLong());

    final ContentWriter primaryWriter = testIndividualWriteAndRead(aggregatingContentStore, text, STORE_1_PROTOCOL);
    final String contentUrl = primaryWriter.getContentUrl();

    // copy into secondary stores
    final String wildcardContentUrl = contentUrl.replaceFirst(STORE_1_PROTOCOL, StoreConstants.WILDCARD_PROTOCOL);
    final ContentWriter store2Writer = store2.getWriter(new ContentContext(null, wildcardContentUrl));
    store2Writer.putContent(primaryWriter.getReader());

    final ContentWriter store3Writer = store3.getWriter(new ContentContext(null, wildcardContentUrl));
    store3Writer.putContent(primaryWriter.getReader());

    final boolean deleted = aggregatingContentStore.delete(contentUrl);
    Assert.assertTrue("Aggregating content store did not report content as deleted", deleted);
    Assert.assertFalse("Primary store still contains deleted content", store1.exists(contentUrl));
    Assert.assertFalse("1st secondary store still contains deleted content", store2.exists(contentUrl));
    Assert.assertTrue("2nd secondary store does not still contain content despite using separate store protocol",
            store3.exists(store3Writer.getContentUrl()));
}
 
Example 17
Source File: ThumbnailServiceTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected void setUp() throws Exception
{
    super.setUp();       
 
    this.fileFolderService = (FileFolderService)getServer().getApplicationContext().getBean("FileFolderService");
    this.contentService = (ContentService)getServer().getApplicationContext().getBean("ContentService");
    synchronousTransformClient = (SynchronousTransformClient) getServer().getApplicationContext().getBean("synchronousTransformClient");
    this.repositoryHelper = (Repository)getServer().getApplicationContext().getBean("repositoryHelper");
    this.authenticationService = (MutableAuthenticationService)getServer().getApplicationContext().getBean("AuthenticationService");
    this.personService = (PersonService)getServer().getApplicationContext().getBean("PersonService");
    try
    {
        this.transactionService = (TransactionServiceImpl) getServer().getApplicationContext().getBean("transactionComponent");
    }
    catch (ClassCastException e)
    {
        throw new AlfrescoRuntimeException("The ThumbnailServiceTest needs direct access to the TransactionServiceImpl");
    }
    
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
    
    this.testRoot = this.repositoryHelper.getCompanyHome();
    
    // Get test content
    InputStream pdfStream = ThumbnailServiceTest.class.getClassLoader().getResourceAsStream("org/alfresco/repo/web/scripts/thumbnail/test_doc.pdf");        
    assertNotNull(pdfStream);
    InputStream jpgStream = ThumbnailServiceTest.class.getClassLoader().getResourceAsStream("org/alfresco/repo/web/scripts/thumbnail/test_image.jpg");
    assertNotNull(jpgStream);
    
    String guid = GUID.generate();
    
    // Create new nodes and set test content
    FileInfo fileInfoPdf = this.fileFolderService.create(this.testRoot, "test_doc" + guid + ".pdf", ContentModel.TYPE_CONTENT);
    this.pdfNode = fileInfoPdf.getNodeRef();
    ContentWriter contentWriter = this.contentService.getWriter(fileInfoPdf.getNodeRef(), ContentModel.PROP_CONTENT, true);
    contentWriter.setEncoding("UTF-8");
    contentWriter.setMimetype(MimetypeMap.MIMETYPE_PDF);
    contentWriter.putContent(pdfStream);
    
    FileInfo fileInfoJpg = this.fileFolderService.create(this.testRoot, "test_image" + guid + ".jpg", ContentModel.TYPE_CONTENT);
    this.jpgNode = fileInfoJpg.getNodeRef();
    contentWriter = this.contentService.getWriter(fileInfoJpg.getNodeRef(), ContentModel.PROP_CONTENT, true);
    contentWriter.setEncoding("UTF-8");
    contentWriter.setMimetype(MimetypeMap.MIMETYPE_IMAGE_JPEG);
    contentWriter.putContent(jpgStream);        
}
 
Example 18
Source File: VersionServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Test testDeleteLastVersion
 * MNT-13097. Revert content if the last version was chosen.
 */
@Test
public void testDeleteLastVersion()
{
    // Use 1.0, 2.0 etc for the main part
    versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MAJOR);

    // Create a versionable node with a name, title and content
    NodeRef versionableNode = createNewVersionableNode();
    this.nodeService.setProperty(versionableNode, ContentModel.PROP_NAME, UPDATED_NAME_1);
    this.nodeService.setProperty(versionableNode, ContentModel.PROP_TITLE, UPDATED_TITLE_1);
    ContentWriter contentWriter = this.contentService.getWriter(versionableNode, ContentModel.PROP_CONTENT, true);
    assertNotNull(contentWriter);
    contentWriter.putContent(UPDATED_CONTENT_1);

    // Create first version
    Version version1 = createVersion(versionableNode);

    // Update name, title and content
    this.nodeService.setProperty(versionableNode, ContentModel.PROP_NAME, UPDATED_NAME_2);
    this.nodeService.setProperty(versionableNode, ContentModel.PROP_TITLE, UPDATED_TITLE_2);
    contentWriter = this.contentService.getWriter(versionableNode, ContentModel.PROP_CONTENT, true);
    contentWriter.putContent(UPDATED_CONTENT_2);

    // Create second version
    Version version2 = createVersion(versionableNode);

    // Update name, title and content
    this.nodeService.setProperty(versionableNode, ContentModel.PROP_NAME, UPDATED_NAME_3);
    this.nodeService.setProperty(versionableNode, ContentModel.PROP_TITLE, UPDATED_TITLE_3);
    contentWriter = this.contentService.getWriter(versionableNode, ContentModel.PROP_CONTENT, true);
    contentWriter.putContent(UPDATED_CONTENT_3);

    // Check that the name and title is right
    String name3 = (String) this.nodeService.getProperty(versionableNode, ContentModel.PROP_NAME);
    assertEquals(UPDATED_NAME_3, name3);
    String title3 = (String) this.nodeService.getProperty(versionableNode, ContentModel.PROP_TITLE);
    assertEquals(UPDATED_TITLE_3, title3);

    // Create third version
    Version version3 = createVersion(versionableNode);

    // Check that the version label is right
    Version currentVersion = this.versionService.getCurrentVersion(versionableNode);
    assertEquals(version3.getVersionLabel(), currentVersion.getVersionLabel());

    // Check that the content is right
    ContentReader contentReader1 = this.contentService.getReader(versionableNode, ContentModel.PROP_CONTENT);
    assertEquals(UPDATED_CONTENT_3, contentReader1.getContentString());

    // Delete version 3.0
    this.versionService.deleteVersion(versionableNode, version3);

    // Check that the name and title is reverted to 2.0
    String name2 = (String) this.nodeService.getProperty(versionableNode, ContentModel.PROP_NAME);
    assertEquals(UPDATED_NAME_2, name2);
    String title2 = (String) this.nodeService.getProperty(versionableNode, ContentModel.PROP_TITLE);
    assertEquals(UPDATED_TITLE_2, title2);

    // Check that the version label is reverted to 2.0
    currentVersion = this.versionService.getCurrentVersion(versionableNode);
    assertEquals(version2.getVersionLabel(), currentVersion.getVersionLabel());

    // Check that the content has been reverted to 2.0
    contentReader1 = this.contentService.getReader(versionableNode, ContentModel.PROP_CONTENT);
    assertEquals(UPDATED_CONTENT_2, contentReader1.getContentString());

    // Version 1.0 and 2.0 should left
    VersionHistory vHistory = this.versionService.getVersionHistory(versionableNode);
    assertEquals(2, vHistory.getAllVersions().size());

    // Version 2.0 should be the head version
    Version headVersion = vHistory.getHeadVersion();
    assertEquals("2.0", headVersion.getVersionLabel());
}
 
Example 19
Source File: RuleServiceCoverageTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
   * Test image transformation
   *
   */
  public void testImageTransformAction() throws Throwable
  {
      Map<String, Serializable> params = new HashMap<String, Serializable>(1);
params.put(ImageTransformActionExecuter.PARAM_DESTINATION_FOLDER, this.rootNodeRef);
      params.put(ImageTransformActionExecuter.PARAM_ASSOC_TYPE_QNAME, ContentModel.ASSOC_CHILDREN);
      params.put(TransformActionExecuter.PARAM_MIME_TYPE, MimetypeMap.MIMETYPE_IMAGE_JPEG);
      params.put(ImageTransformActionExecuter.PARAM_ASSOC_QNAME, QName.createQName(TEST_NAMESPACE, "transformed"));
      params.put(ImageTransformActionExecuter.PARAM_CONVERT_COMMAND, "-negate");
      
      Rule rule = createRule(
      		RuleType.INBOUND, 
      		ImageTransformActionExecuter.NAME, 
      		params, 
      		NoConditionEvaluator.NAME, 
      		null);
      
      this.ruleService.saveRule(this.nodeRef, rule);

      UserTransaction tx = transactionService.getUserTransaction();
tx.begin();

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

// Create the node at the root
      NodeRef newNodeRef = this.nodeService.createNode(
              this.nodeRef,
              ContentModel.ASSOC_CHILDREN,                
              QName.createQName(TEST_NAMESPACE, "origional"),
              ContentModel.TYPE_CONTENT,
              props).getChildRef(); 

// Set some content on the origional
ContentWriter contentWriter = this.contentService.getWriter(newNodeRef, ContentModel.PROP_CONTENT, true);
      contentWriter.setMimetype(MimetypeMap.MIMETYPE_IMAGE_GIF);
File testFile = AbstractContentTransformerTest.loadQuickTestFile("gif");
contentWriter.putContent(testFile);

tx.commit();
      
      //System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.testStoreRef));
      
      // Check that the created node is still there
      List<ChildAssociationRef> origRefs = this.nodeService.getChildAssocs(
              this.nodeRef, 
              RegexQNamePattern.MATCH_ALL, QName.createQName(TEST_NAMESPACE, "origional"));
      assertNotNull(origRefs);
      assertEquals(1, origRefs.size());
      NodeRef origNodeRef = origRefs.get(0).getChildRef();
      assertEquals(newNodeRef, origNodeRef);

      // Check that the created node has been copied
      List<ChildAssociationRef> copyChildAssocRefs = this.nodeService.getChildAssocs(
                                                  this.rootNodeRef, 
                                                  RegexQNamePattern.MATCH_ALL, QName.createQName(TEST_NAMESPACE, "test.jpg"));
      assertNotNull(copyChildAssocRefs);
      assertEquals(1, copyChildAssocRefs.size());
      NodeRef copyNodeRef = copyChildAssocRefs.get(0).getChildRef();
      assertTrue(this.nodeService.hasAspect(copyNodeRef, ContentModel.ASPECT_COPIEDFROM));
      NodeRef source = copyService.getOriginal(copyNodeRef);
      assertEquals(newNodeRef, source);
  }
 
Example 20
Source File: BlogServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public BlogPostInfo createBlogPost(NodeRef blogContainerNode, String blogTitle,
                                          String blogContent, boolean isDraft)
{
    final String nodeName = getUniqueChildName(blogContainerNode, "post");
    
    // we simply create a new file inside the blog folder
    Map<QName, Serializable> nodeProps = new HashMap<QName, Serializable>();
    nodeProps.put(ContentModel.PROP_NAME, nodeName);
    nodeProps.put(ContentModel.PROP_TITLE, blogTitle);
    QName assocName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, nodeName);
    ChildAssociationRef postNode = null;
    try
    {
        postNode = nodeService.createNode(
                blogContainerNode, ContentModel.ASSOC_CONTAINS, assocName,
                ContentModel.TYPE_CONTENT, nodeProps);
    }
    catch (DuplicateChildNodeNameException e)
    {
        // This will be rare, but it's not impossible.
        // We have to retry the operation.
        throw new ConcurrencyFailureException("Blog post name already used: " + nodeName);
    }
    
    ContentWriter writer = contentService.getWriter(postNode.getChildRef(), ContentModel.PROP_CONTENT, true);
    
    // Blog posts are always HTML (based on the JavaScript this class replaces.)
    writer.setMimetype(MimetypeMap.MIMETYPE_HTML);
    writer.setEncoding("UTF-8");
    writer.putContent(blogContent);
    
    if (isDraft)
    {
        // Comment from the old JavaScript:
        // disable permission inheritance. The result is that only the creator will have access to the draft
        NodeRef draft = postNode.getChildRef();
        permissionService.setInheritParentPermissions(draft, false);
        
        // MNT-12082: give permissions to the post creator. He should be able to comment in his post's
        // forumFolder and commentsFolder, where owner is System user
        String creator = (String) nodeService.getProperty(draft, ContentModel.PROP_CREATOR);
        permissionService.setPermission(draft, creator, permissionService.getAllPermission(), true);
    }
    else
    {
        setOrUpdateReleasedAndUpdatedDates(postNode.getChildRef());
    }
    
    BlogPostInfo post = new BlogPostInfoImpl(postNode.getChildRef(), blogContainerNode, nodeName);
    post.setTitle(blogTitle);
    return post;
}