Java Code Examples for org.alfresco.service.cmr.repository.ContentService#getWriter()

The following examples show how to use org.alfresco.service.cmr.repository.ContentService#getWriter() . 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: ScriptNode.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Delete the content stream
 */
public void delete()
{
    ContentService contentService = services.getContentService();
    ContentWriter writer = contentService.getWriter(nodeRef, this.property, true);
    OutputStream output = writer.getContentOutputStream();
    try
    {
        output.close();
    }
    catch (IOException e)
    {
        // NOTE: fall-through
    }
    writer.setMimetype(null);
    writer.setEncoding(null);
    
    // update cached variables after putContent()
    updateContentData(true);
}
 
Example 2
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 3
Source File: MoveMethod.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void copyContentOnly(FileInfo sourceFileInfo, FileInfo destFileInfo, FileFolderService fileFolderService) throws WebDAVServerException
{
	ContentService contentService = getContentService();
    ContentReader reader = contentService.getReader(sourceFileInfo.getNodeRef(), ContentModel.PROP_CONTENT);
    if (reader == null)
    {
        // There is no content for the node if it is a folder
        if (!sourceFileInfo.isFolder())
        {
            // Non-folders should have content available.
            logger.error("Unable to get ContentReader for source node " + sourceFileInfo.getNodeRef());
            throw new WebDAVServerException(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    else
    {
        ContentWriter contentWriter = contentService.getWriter(destFileInfo.getNodeRef(), ContentModel.PROP_CONTENT, true);
        contentWriter.putContent(reader);
    }
}
 
Example 4
Source File: AbstractEmailMessageHandler.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Write content to the node from InputStream.
 * 
 * @param nodeRef Target node.
 * @param content Content stream.
 * @param mimetype MIME content type.
 * @param encoding Encoding. Can be null for text based content, n which case the best guess.
 */
protected void writeContent(NodeRef nodeRef, InputStream content, String mimetype, String encoding)
{
    InputStream bis = new BufferedInputStream(content, 4092);

    // Only guess the encoding if it has not been supplied
    if (encoding == null)
    {
        if (mimetypeService.isText(mimetype))
        {
            ContentCharsetFinder charsetFinder = mimetypeService.getContentCharsetFinder();
            encoding = charsetFinder.getCharset(bis, mimetype).name();
        }
        else
        {
            encoding = "UTF-8";
        }
    }
    
    if (log.isDebugEnabled())
    {
        log.debug("Write content (MimeType=\"" + mimetype + "\", Encoding=\"" + encoding + "\"");
    }
    
    
    ContentService contentService = getContentService();
    ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(mimetype);
    writer.setEncoding(encoding);
    writer.putContent(bis);
}
 
Example 5
Source File: FolderEmailMessageHandler.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * This method writes space as a content. We need this space because rules doesn't proceed documents with empty content. We need rule processing for command email messages with
 * empty body.
 * 
 * @param nodeRef Reference to the parent node
 */
private void writeSpace(NodeRef nodeRef)
{
    if (log.isDebugEnabled())
    {
        log.debug("Write space string");
    }

    ContentService contentService = getContentService();
    ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    writer.setEncoding("UTF-8");
    writer.putContent(" ");
}
 
Example 6
Source File: ScriptNode.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Generic method to transform Node content from one mimetype to another.
 * 
 * @param transformer   The Transformer delegate supplying the transformation logic
 * @param mimetype      Mimetype of the destination content
 * @param destination   Destination folder location for the resulting document
 * 
 * @return Node representing the transformed content - or null if the transform failed
 */
private ScriptNode transformNode(Transformer transformer, String mimetype, NodeRef destination)
{
    ScriptNode transformedNode = null;
    
    // get the content reader
    ContentService contentService = this.services.getContentService();
    ContentReader reader = contentService.getReader(this.nodeRef, ContentModel.PROP_CONTENT);
    
    // only perform the transformation if some content is available
    if (reader != null)
    {
        // Copy the content node to a new node
        String copyName = TransformActionExecuter.transformName(this.services.getMimetypeService(), getName(),
                mimetype, true);
        NodeRef copyNodeRef = this.services.getCopyService().copy(this.nodeRef, destination,
                ContentModel.ASSOC_CONTAINS,
                QName.createQName(ContentModel.PROP_CONTENT.getNamespaceURI(), QName.createValidLocalName(copyName)),
                false);
        
        // modify the name of the copy to reflect the new mimetype
        this.nodeService.setProperty(copyNodeRef, ContentModel.PROP_NAME, copyName);
        
        // get the writer and set it up
        ContentWriter writer = contentService.getWriter(copyNodeRef, ContentModel.PROP_CONTENT, true);
        writer.setMimetype(mimetype); // new mimetype
        writer.setEncoding(reader.getEncoding()); // original encoding
        
        // Try and transform the content using the supplied delegate
        transformedNode = transformer.transform(synchronousTransformClient, copyNodeRef, reader, writer);
    }
    
    return transformedNode;
}
 
Example 7
Source File: ScriptNode.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Set the content stream
 * 
 * @param content    Content string to set
 */
public void setContent(String content)
{
    ContentService contentService = services.getContentService();
    ContentWriter writer = contentService.getWriter(nodeRef, this.property, true);
    writer.setMimetype(getMimetype()); // use existing mimetype value
    writer.putContent(content);
    
    // update cached variables after putContent()
    updateContentData(true);
}
 
Example 8
Source File: ScriptNode.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Set the content stream from another content object.
 *  
 * @param content  ScriptContent to set
 */
public void write(Content content)
{
    ContentService contentService = services.getContentService();
    ContentWriter writer = contentService.getWriter(nodeRef, this.property, true);
    writer.setMimetype(content.getMimetype());
    writer.setEncoding(content.getEncoding());
    writer.putContent(content.getInputStream());

    // update cached variables after putContent()
    updateContentData(true);
}
 
Example 9
Source File: ScriptNode.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Set the content stream from another input stream.
 *  
 * @param inputStream InputStream
 */
public void write(InputStream inputStream)
{
    ContentService contentService = services.getContentService();
    ContentWriter writer = contentService.getWriter(nodeRef, this.property, true);
    writer.putContent(inputStream);

    // update cached variables after putContent()
    updateContentData(true);
}
 
Example 10
Source File: RoutingContentServiceTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void setUp() throws Exception
{
    ctx = ApplicationContextHelper.getApplicationContext();
    transactionService = (TransactionService) ctx.getBean("TransactionService");
    nodeService = (NodeService) ctx.getBean("NodeService");
    contentService = (ContentService) ctx.getBean(ServiceRegistry.CONTENT_SERVICE.getLocalName());
    copyService = (CopyService) ctx.getBean("CopyService");
    this.policyComponent = (PolicyComponent) ctx.getBean("policyComponent");
    this.authenticationComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
    
    // authenticate
    this.authenticationComponent.setSystemUserAsCurrentUser();
    
    // start the transaction
    txn = getUserTransaction();
    txn.begin();
    
    // create a store and get the root node
    StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, getName());
    if (!nodeService.exists(storeRef))
    {
        storeRef = nodeService.createStore(storeRef.getProtocol(), storeRef.getIdentifier());
    }
    rootNodeRef = nodeService.getRootNode(storeRef);

    ChildAssociationRef assocRef = nodeService.createNode(
            rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName(TEST_NAMESPACE, GUID.generate()),
            ContentModel.TYPE_CONTENT);
    contentNodeRef = assocRef.getChildRef();

    ContentWriter writer = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
    writer.setEncoding("UTF-16");
    writer.setLocale(Locale.CHINESE);
    writer.setMimetype("text/plain");
    writer.putContent("sample content");
}
 
Example 11
Source File: TestPeople.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private NodeRef createAvatarDirect(NodeRef personRef, File avatarFile)
{
    // create new avatar node
    nodeService.addAspect(personRef, ContentModel.ASPECT_PREFERENCES, null);
    ChildAssociationRef assoc = nodeService.createNode(
            personRef,
            ContentModel.ASSOC_PREFERENCE_IMAGE,
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "origAvatar"),
            ContentModel.TYPE_CONTENT);
    final NodeRef avatarRef = assoc.getChildRef();

    // JSF client compatibility?
    nodeService.createAssociation(personRef, avatarRef, ContentModel.ASSOC_AVATAR);

    // upload the avatar content
    ContentService contentService = applicationContext.getBean("ContentService", ContentService.class);
    ContentWriter writer = contentService.getWriter(avatarRef, ContentModel.PROP_CONTENT, true);
    writer.guessMimetype(avatarFile.getName());
    writer.putContent(avatarFile);

    Rendition avatarR = new Rendition();
    avatarR.setId("avatar");
    Renditions renditions = applicationContext.getBean("Renditions", Renditions.class);
    renditions.createRendition(avatarRef, avatarR, false, null);

    return avatarRef;
}
 
Example 12
Source File: FFCLoadsOfFiles.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static void doExample(ServiceRegistry serviceRegistry) throws Exception
    {
        //
        // locate the company home node
        //
        SearchService searchService = serviceRegistry.getSearchService();
        NodeService nodeService = serviceRegistry.getNodeService();
        NamespaceService namespaceService = serviceRegistry.getNamespaceService();
        StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
        NodeRef rootNodeRef = nodeService.getRootNode(storeRef);
        List<NodeRef> results = searchService.selectNodes(rootNodeRef, "/app:company_home", null, namespaceService, false);
        if (results.size() == 0)
        {
            throw new AlfrescoRuntimeException("Can't find /app:company_home");
        }
        NodeRef companyHomeNodeRef = results.get(0);
        results = searchService.selectNodes(companyHomeNodeRef, "./cm:LoadTest", null, namespaceService, false);
        final NodeRef loadTestHome;
        if (results.size() == 0)
        {
            loadTestHome = nodeService.createNode(
                    companyHomeNodeRef,
                    ContentModel.ASSOC_CHILDREN,
                    QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "LoadTest"),
                    ContentModel.TYPE_FOLDER).getChildRef();
        }
        else
        {
            loadTestHome = results.get(0);
        }

        if ((currentDoc + docsPerTx) > totalNumDocs)
        {
        	docsPerTx = totalNumDocs - currentDoc;
        }
        // Create new Space
        String spaceName = "Bulk Load Space (" + System.currentTimeMillis() + ") from " + currentDoc + " to " + (currentDoc + docsPerTx - 1) + " of " + totalNumDocs;
        Map<QName, Serializable> spaceProps = new HashMap<QName, Serializable>();
    	spaceProps.put(ContentModel.PROP_NAME, spaceName);
        NodeRef  newSpace = nodeService.createNode(loadTestHome, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_PREFIX, spaceName),ContentModel.TYPE_FOLDER,spaceProps).getChildRef();
        

        // create new content node within new Space home
        for (int k = 1;k<=docsPerTx;k++)
        {
    		currentDoc++;
    		System.out.println("About to start document " + currentDoc);
        	// assign name
        	String name = "BulkLoad (" + System.currentTimeMillis() + ") " + currentDoc ;
        	Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>();
        	contentProps.put(ContentModel.PROP_NAME, name);
        	
        	// create content node
        	// NodeService nodeService = serviceRegistry.getNodeService();
        	ChildAssociationRef association = nodeService.createNode(newSpace, 
        			ContentModel.ASSOC_CONTAINS, 
        			QName.createQName(NamespaceService.CONTENT_MODEL_PREFIX, 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);
        	nodeService.addAspect(content, ContentModel.ASPECT_TITLED, titledProps);
        	
        	//
        	// write some content to new node
        	//

        	ContentService contentService = serviceRegistry.getContentService();
        	ContentWriter writer = contentService.getWriter(content, ContentModel.PROP_CONTENT, true);
        	writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
        	writer.setEncoding("UTF-8");
        	String text = "This is some text in a doc";
        	writer.putContent(text);
    		System.out.println("About to get child assocs ");        	
        	//Circa
//        	nodeService.getChildAssocs(newSpace);
    	       for (int count=0;count<=10000;count++)
    	        {
    	        	nodeService.getChildAssocs(newSpace);
    	        }
       	
        }
    	//doSearch(searchService);
 		System.out.println("About to end transaction " );

    }
 
Example 13
Source File: XmlMetadataExtracterTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Tests metadata extraction using an action with an EAGER MetadataExtracter for XML.
 */
public void testLifecycleOfXmlMetadataExtraction() throws Exception
{
    NodeService nodeService = serviceRegistry.getNodeService();
    ContentService contentService = serviceRegistry.getContentService();
    ActionExecuter executer = (ActionExecuter) ctx.getBean("extract-metadata");
    Action action = new ActionImpl(null, GUID.generate(), SetPropertyValueActionExecuter.NAME, null);
    
    StoreRef storeRef = new StoreRef("test", getName());
    NodeRef rootNodeRef = null;
    if (nodeService.exists(storeRef))
    {
        rootNodeRef = nodeService.getRootNode(storeRef);
    }
    else
    {
        nodeService.createStore("test", getName());
        rootNodeRef = nodeService.getRootNode(storeRef);
    }
    
    // Set up some properties
    PropertyMap properties = new PropertyMap();
    properties.put(ContentModel.PROP_TITLE, "My title");
    properties.put(ContentModel.PROP_DESCRIPTION, "My description");
    
    NodeRef contentNodeRef = nodeService.createNode(
            rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, getName()),
            ContentModel.TYPE_CONTENT,
            properties).getChildRef();
    // Add some content
    ContentReader alfrescoModelReader = getReader(FILE_ALFRESCO_MODEL);
    assertTrue(alfrescoModelReader.exists());
    ContentWriter writer = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
    writer.setEncoding("UTF-8");
    writer.setMimetype(MimetypeMap.MIMETYPE_XML);
    writer.putContent(alfrescoModelReader);
    
    // Execute the action
    executer.execute(action, contentNodeRef);
    
    // Check the node's properties.  The EAGER overwrite policy should have replaced the required
    // properties.
    String checkTitle = (String) nodeService.getProperty(contentNodeRef, ContentModel.PROP_TITLE);
    String checkDescription = (String) nodeService.getProperty(contentNodeRef, ContentModel.PROP_DESCRIPTION);
    assertEquals("fm:forummodel", checkTitle);
    assertEquals("Forum Model", checkDescription);
}
 
Example 14
Source File: ContentSignatureActionExecuter.java    From CounterSign with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) 
{
	NodeService nodeService = serviceRegistry.getNodeService();
	ContentService contentService = serviceRegistry.getContentService();
	byte[] sigBytes;

	if (nodeService.exists(actionedUponNodeRef) == false)
       {
           return;
       }
   	 
       String location = (String)ruleAction.getParameterValue(PARAM_LOCATION);
       String geolocation = (String)ruleAction.getParameterValue(PARAM_GEOLOCATION);
       String reason = (String)ruleAction.getParameterValue(PARAM_REASON);
       String keyPassword = (String)ruleAction.getParameterValue(PARAM_KEY_PASSWORD);
       
	// get a hash of the document
       InputStream contentStream = contentService.
       		getReader(actionedUponNodeRef, ContentModel.PROP_CONTENT).getContentInputStream();
	
       try
       {
           // get the user's private key
        String user = AuthenticationUtil.getRunAsUser();
    	SignatureProvider signatureProvider = signatureProviderFactory.getSignatureProvider(user);
        KeyStore keystore = signatureProvider.getUserKeyStore(keyPassword);
        PrivateKey key = (PrivateKey)keystore.getKey(alias, keyPassword.toCharArray());
        
        // compute the document hash
        byte[] hash = signatureProvider.computeHash(contentStream);
        
		// sign the hash
		sigBytes = signatureProvider.signHash(hash, keyPassword);
		
		// create a "signature" node and associate it with the signed doc
        NodeRef sig = addSignatureNodeAssociation(actionedUponNodeRef, location, reason, 
        		"none", new java.util.Date(), geolocation, -1, "none");
        
		// save the signature
		ContentWriter writer = contentService.getWriter(sig, ContentModel.PROP_CONTENT, true);
		writer.putContent(new ByteArrayInputStream(sigBytes));
		
		// also save the expected hash in the signature
		nodeService.setProperty(sig, CounterSignSignatureModel.PROP_DOCHASH, new String(hash));
       }
       catch(UnrecoverableKeyException uke)
       {
       	throw new AlfrescoRuntimeException(uke.getMessage());
       } 
       catch (KeyStoreException kse) 
       {
		throw new AlfrescoRuntimeException(kse.getMessage());
	} 
       catch (NoSuchAlgorithmException nsae) 
	{
		throw new AlfrescoRuntimeException(nsae.getMessage());
	} 
       catch (Exception e) 
       {
		throw new AlfrescoRuntimeException(e.getMessage());
	}
}