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

The following examples show how to use org.alfresco.service.cmr.repository.ContentWriter#setEncoding() . 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: AbstractWritableContentStoreTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testStringTruncation() throws Exception
{
    String content = "1234567890";
    
    ContentWriter writer = getWriter();
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    writer.setEncoding("UTF-8");  // shorter format i.t.o. bytes used
    // write the content
    writer.putContent(content);
    
    // get a reader - get it in a larger format i.t.o. bytes
    ContentReader reader = writer.getReader();
    String checkContent = reader.getContentString(5);
    assertEquals("Truncated strings don't match", "12345", checkContent);
}
 
Example 2
Source File: GenericEMailTemplateUpdatePatch.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void updateContent(NodeRef nodeRef, String path, String fileName, boolean newFile)
{
    // Make versionable
    nodeService.addAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE, null);
    
    // Update content
    InputStream is = this.getClass().getClassLoader().getResourceAsStream(path + fileName);
    if (is != null)
    {
        ContentWriter contentWriter = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
        if (newFile == true)
        {
            contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
            contentWriter.setEncoding("UTF-8");
        }
        contentWriter.putContent(is);
    }
}
 
Example 3
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 4
Source File: RoutingContentServiceTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testWriteToNodeWithoutAnyContentProperties() throws Exception
{
    NodeRef nodeRef = nodeService.createNode(
            rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName(TEST_NAMESPACE, GUID.generate()),
            ContentModel.TYPE_CONTENT).getChildRef();

    ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);

    assertNull(writer.getMimetype());
    assertEquals("UTF-8", writer.getEncoding());
    assertEquals(Locale.getDefault(), writer.getLocale());
    
    // now set it on the writer
    writer.setMimetype("text/plain");
    writer.setEncoding("UTF-16");
    writer.setLocale(Locale.FRENCH);
    
    String content = "The quick brown fox ...";
    writer.putContent(content);
    
    // the properties should have found their way onto the node
    ContentData contentData = (ContentData) nodeService.getProperty(nodeRef, ContentModel.PROP_CONTENT);
    assertEquals("metadata didn't get onto node", writer.getContentData(), contentData);
    
    // check that the reader's metadata is set
    ContentReader reader = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
    assertEquals("Metadata didn't get set on reader", writer.getContentData(), reader.getContentData());
}
 
Example 5
Source File: UserUsageTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void updateTextContent(NodeRef contentRef, String textData)
{
    ContentWriter writer = contentService.getWriter(contentRef, ContentModel.PROP_CONTENT, true);
    
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    writer.setEncoding("UTF-8");
    
    writer.putContent(textData);
}
 
Example 6
Source File: FileContentReader.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Checks the existing reader provided and replaces it with a reader onto some
 * fake content if required.  If the existing reader is invalid, an debug message
 * will be logged under this classname category.
 * <p>
 * It is a convenience method that clients can use to cheaply get a reader that
 * is valid, regardless of whether the initial reader is valid.
 * 
 * @param existingReader a potentially invalid reader or null
 * @param msgTemplate the template message that will used to format the final <i>fake</i> content
 * @param args arguments to put into the <i>fake</i> content
 * @return Returns a the existing reader or a new reader onto some generated text content
 */
public static ContentReader getSafeContentReader(ContentReader existingReader, String msgTemplate, Object ... args)
{
    ContentReader reader = existingReader;
    if (existingReader == null || !existingReader.exists())
    {
        // the content was never written to the node or the underlying content is missing
        String fakeContent = MessageFormat.format(msgTemplate, args);
        
        // log it
        if (logger.isDebugEnabled())
        {
            logger.debug(fakeContent);
        }
        
        // fake the content
        File tempFile = TempFileProvider.createTempFile("getSafeContentReader_", ".txt");
        ContentWriter writer = new FileContentWriter(tempFile);
        writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
        writer.setEncoding("UTF-8");
        writer.putContent(fakeContent);
        // grab the reader from the temp writer
        reader = writer.getReader();
    }
    // done
    if (logger.isDebugEnabled())
    {
        logger.debug("Created safe content reader: \n" +
                "   existing reader: " + existingReader + "\n" +
                "   safe reader: " + reader);
    }
    return reader;
}
 
Example 7
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 8
Source File: RepoPrimaryManifestProcessorImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @param nodeToUpdate NodeRef
 * @param contentProps Map<QName, Serializable>
 * @return true if any content property has been updated for the needToUpdate node
 */
private boolean writeContent(NodeRef nodeToUpdate, Map<QName, Serializable> contentProps)
{
    boolean contentUpdated = false;
    File stagingDir = getStagingFolder();
    for (Map.Entry<QName, Serializable> contentEntry : contentProps.entrySet())
    {
        ContentData contentData = (ContentData) contentEntry.getValue();
        String contentUrl = contentData.getContentUrl();
        if(contentUrl == null || contentUrl.isEmpty())
        {
            log.debug("content data is null or empty:" + nodeToUpdate);
            ContentData cd = new ContentData(null, null, 0, null);
            nodeService.setProperty(nodeToUpdate, contentEntry.getKey(), cd);
            contentUpdated = true;
        }
        else
        {
            String fileName = TransferCommons.URLToPartName(contentUrl);
            File stagedFile = new File(stagingDir, fileName);
            if (!stagedFile.exists())
            {
                error(MSG_REFERENCED_CONTENT_FILE_MISSING);
            }
            ContentWriter writer = contentService.getWriter(nodeToUpdate, contentEntry.getKey(), true);
            writer.setEncoding(contentData.getEncoding());
            writer.setMimetype(contentData.getMimetype());
            writer.setLocale(contentData.getLocale());
            writer.putContent(stagedFile);
            contentUpdated = true;
        }
    }
    return contentUpdated;
}
 
Example 9
Source File: NodeServiceTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void addContentToNode(NodeRef nodeRef)
{
    String content = "Some content";
    ContentWriter contentWriter = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype("text/plain");
    contentWriter.setEncoding("UTF-8");
    contentWriter.putContent(content);
}
 
Example 10
Source File: TransferReporterImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public NodeRef writeDestinationReport(String transferName,
        TransferTarget target,
        File tempFile)
{
   
    String title = transferName + "_destination";
    String description = "Transfer Destination Report - target: " + target.getName();
    String name = title + ".xml";
    
    logger.debug("writing destination transfer report " + title);
    logger.debug("parent node ref " + target.getNodeRef());
    
    Map<QName, Serializable> properties = new HashMap<QName, Serializable> ();
    properties.put(ContentModel.PROP_NAME, name);
    properties.put(ContentModel.PROP_TITLE, title);
    properties.put(ContentModel.PROP_DESCRIPTION, description);
    ChildAssociationRef ref = nodeService.createNode(target.getNodeRef(), 
            ContentModel.ASSOC_CONTAINS, 
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name), 
            TransferModel.TYPE_TRANSFER_REPORT_DEST, 
            properties);
    
    ContentWriter writer = contentService.getWriter(ref.getChildRef(), 
            ContentModel.PROP_CONTENT, true);
    writer.setLocale(Locale.getDefault());
    writer.setMimetype(MimetypeMap.MIMETYPE_XML);
    writer.setEncoding(DEFAULT_ENCODING);
    writer.putContent(tempFile);
    
    logger.debug("written " + name + ", " + ref.getChildRef());
    
    return ref.getChildRef();
}
 
Example 11
Source File: RepoTransferProgressMonitorImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected Writer createUnderlyingLogWriter(String transferId)
{
    NodeRef node = new NodeRef(transferId);
    ContentWriter contentWriter = contentService.getWriter(node, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype(MimetypeMap.MIMETYPE_XML);
    contentWriter.setEncoding("UTF-8");
    return Channels.newWriter(contentWriter.getWritableChannel(), "UTF-8");
}
 
Example 12
Source File: CopyServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * https://issues.alfresco.com/jira/browse/ALF-17549
 */
public void testALF17549() throws Exception
{
    permissionService.setPermission(rootNodeRef, USER_1, PermissionService.COORDINATOR, true);

    AuthenticationUtil.setRunAsUser(USER_1);

    String sourceName = "sourceNode.txt";
    Map<QName, Serializable> props = new HashMap<QName, Serializable>();

    props.put(ContentModel.PROP_NAME, sourceName);

    NodeRef sourceNodeRef = nodeService.createNode(this.rootNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName("{test}" + sourceName), ContentModel.TYPE_CONTENT, props)
            .getChildRef();

    ContentWriter writer = contentService.getWriter(sourceNodeRef, ContentModel.PROP_CONTENT, true);
    writer.setEncoding("UTF-8");
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    writer.putContent("This is sample text content for unit test.");

    NodeRef targetNodeRef = nodeService.createNode(this.rootNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName("{test}targetNode"), ContentModel.TYPE_FOLDER)
            .getChildRef();

    List<ChildAssociationRef> childAssoc = nodeService.getChildAssocs(targetNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName("{test}sourceNode.html"));

    assertEquals(0, childAssoc.size());

    Action action = this.actionService.createAction(TransformActionExecuter.NAME);

    action.setParameterValue(TransformActionExecuter.PARAM_MIME_TYPE, MimetypeMap.MIMETYPE_HTML);
    action.setParameterValue(TransformActionExecuter.PARAM_DESTINATION_FOLDER, targetNodeRef);
    action.setParameterValue(TransformActionExecuter.PARAM_ASSOC_QNAME, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "copy"));
    action.setParameterValue(TransformActionExecuter.PARAM_ASSOC_TYPE_QNAME, ContentModel.ASSOC_CONTAINS);
    actionService.executeAction(action, sourceNodeRef);

    childAssoc = nodeService.getChildAssocs(targetNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName("{test}sourceNode.html"));

    assertEquals(1, childAssoc.size());
}
 
Example 13
Source File: RenditionServiceIntegrationTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void setImageContentOnNode(NodeRef nodeWithImage, String mimetypeImage, File imageFile)
{
    assertTrue(imageFile.exists());
    nodeService.setProperty(nodeWithImage, ContentModel.PROP_CONTENT, new ContentData(null,
                mimetypeImage, 0L, null));
    ContentWriter writer = contentService.getWriter(nodeWithImage, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(mimetypeImage);
    writer.setEncoding("UTF-8");
    writer.putContent(imageFile);
}
 
Example 14
Source File: TransferReporterImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Write exception transfer report
 * 
 * @return NodeRef the node ref of the new transfer report
 */
public NodeRef createTransferReport(String transferName,
            Exception e, 
            TransferTarget target,
            TransferDefinition definition, 
            List<TransferEvent> events, 
            File snapshotFile)
{
    Map<QName, Serializable> properties = new HashMap<QName, Serializable> ();
    
    String title = transferName;
    String description = "Transfer Report - target: " + target.getName();
    String name = transferName + ".xml";
    
    properties.put(ContentModel.PROP_NAME, name);
    properties.put(ContentModel.PROP_TITLE, title);
    properties.put(ContentModel.PROP_DESCRIPTION, description);
    ChildAssociationRef ref = nodeService.createNode(target.getNodeRef(), ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name), TransferModel.TYPE_TRANSFER_REPORT, properties);
    ContentWriter writer = contentService.getWriter(ref.getChildRef(), ContentModel.PROP_CONTENT, true);
    writer.setLocale(Locale.getDefault());
    writer.setMimetype(MimetypeMap.MIMETYPE_XML);
    writer.setEncoding(DEFAULT_ENCODING);
    
    XMLTransferReportWriter reportWriter = new XMLTransferReportWriter();
    
    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(writer.getContentOutputStream()));

    try
    {
        reportWriter.startTransferReport(DEFAULT_ENCODING, bufferedWriter);
        
        reportWriter.writeTarget(target);
        
        reportWriter.writeDefinition(definition);
        
        reportWriter.writeException(e);
        
        reportWriter.writeTransferEvents(events);
        
        reportWriter.endTransferReport();
        
        return ref.getChildRef();
    }
    
    catch (SAXException se)
    {
        return null;
    }
    finally
    {
        try
        {
            bufferedWriter.close();
        }
        catch (IOException error)
        {
            error.printStackTrace();
        }
    }
}
 
Example 15
Source File: LinksServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public LinkInfo createLink(String siteShortName, String title,
      String description, String url, boolean internal) 
{
   // Grab the location to store in
   NodeRef container = getSiteLinksContainer(siteShortName, true);
   
   // Get the properties for the node
   Map<QName, Serializable> props = new HashMap<QName, Serializable>();
   props.put(LinksModel.PROP_TITLE,       title);
   props.put(LinksModel.PROP_DESCRIPTION, description);
   props.put(LinksModel.PROP_URL,         url);
   
   if (internal)
   {
      props.put(LinksModel.PROP_IS_INTERNAL, "true");
   }
   
   // Generate a unique name
   // (Should be unique, but will retry for a new one if not)
   String name = "link-" + (new Date()).getTime() + "-" + 
                 Math.round(Math.random()*10000);
   props.put(ContentModel.PROP_NAME, name);
   
   // Build the node
   NodeRef nodeRef = nodeService.createNode(
         container,
         ContentModel.ASSOC_CONTAINS,
         QName.createQName(name),
         LinksModel.TYPE_LINK,
         props
   ).getChildRef();
   
   // Duplicate the url into the node as the content property
   ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
   writer.setEncoding("UTF-8");
   writer.putContent(url);
   
   // Generate the wrapping object for it
   // Build it that way, so creator and created date come through
   return buildLink(nodeRef, container, name);
}
 
Example 16
Source File: DifferrentMimeTypeTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void createContentNodeRef()
{
    AuthenticationUtil.RunAsWork<NodeRef> createTargetWork = new AuthenticationUtil.RunAsWork<NodeRef>()
    {
        @Override
        public NodeRef doWork() throws Exception
        {
            if (log.isDebugEnabled())
            {
                log.debug("Creating temporary NodeRefs for testing.");
            }

            final NodeRef companyHome = repositoryHelper.getCompanyHome();
            // Create a folder
            Map<QName, Serializable> folderProps = new HashMap<>();
            folderProps.put(ContentModel.PROP_NAME, this.getClass().getSimpleName() + System.currentTimeMillis());
            NodeRef folderNodeRef = nodeService.createNode(companyHome, ContentModel.ASSOC_CONTAINS,
                    ContentModel.ASSOC_CONTAINS, ContentModel.TYPE_FOLDER, folderProps).getChildRef();

            // Mark folder for removing after test
            nodesToDeleteAfterTest.add(folderNodeRef);

            String fileName = testFile.getName();
            Map<QName, Serializable> props = new HashMap<>();
            props.put(ContentModel.PROP_NAME, fileName);

            NodeRef node = nodeService.createNode(
                    folderNodeRef,
                    ContentModel.ASSOC_CONTAINS,
                    QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, fileName),
                    ContentModel.TYPE_CONTENT,
                    props).getChildRef();
            
            // Make sure the error message contains the file name. Without this it is null.
            nodeService.setProperty(node, ContentModel.PROP_NAME, fileName);
            options.setSourceNodeRef(node);

            // node should be removed after tests
            nodesToDeleteAfterTest.add(node);

            ContentWriter writer = contentService.getWriter(node, ContentModel.PROP_CONTENT, true);
            String targetMimeType = mimetypeService.guessMimetype(fileName);

            writer.setMimetype(targetMimeType);
            writer.setEncoding("UTF-8");
            writer.putContent(testFile);

            return node;
        }
    };

    contentNodeRef = AuthenticationUtil.runAs(createTargetWork, AuthenticationUtil.getSystemUserName());
    nodesToDeleteAfterTest.add(contentNodeRef);
}
 
Example 17
Source File: CheckOutCheckInServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testDeleteAndRestore()
{
    authenticationComponent.setSystemUserAsCurrentUser();

    StoreRef spacesStoreRef = StoreRef.STORE_REF_WORKSPACE_SPACESSTORE;
    NodeRef spacesRootNodeRef = nodeService.getRootNode(spacesStoreRef);
    NodeRef archiveRootNodeRef = nodeService.getStoreArchiveNode(spacesStoreRef);

    permissionService.setPermission(spacesRootNodeRef, userName, PermissionService.ALL_PERMISSIONS, true);

    authenticationComponent.setCurrentUser(userName);

    // create folder and some content within the the folder
    NodeRef folderRef = createFolder(spacesRootNodeRef, "testDeleteAndRestore-folder-"+System.currentTimeMillis());
    NodeRef contentRef = createContent("testDeleteAndRestore-content", folderRef);
    
    String initialText = "initial text";
    ContentWriter contentWriter = contentService.getWriter(contentRef, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype("text/plain");
    contentWriter.setEncoding("UTF-8");
    contentWriter.putContent(initialText);

    assertFalse(nodeService.hasAspect(contentRef, ContentModel.ASPECT_CHECKED_OUT));

    // checkout content node
    NodeRef workingCopyRef = cociService.checkout(contentRef, folderRef, ContentModel.ASSOC_CHILDREN, QName.createQName("workingCopy"));

    assertNotNull(workingCopyRef);
    assertTrue(nodeService.hasAspect(workingCopyRef, ContentModel.ASPECT_WORKING_COPY));
    assertTrue(nodeService.hasAspect(workingCopyRef, ContentModel.ASPECT_COPIEDFROM));
    assertTrue(nodeService.hasAspect(contentRef, ContentModel.ASPECT_CHECKED_OUT));

    String updatedText = "updated text";
    contentWriter = contentService.getWriter(workingCopyRef, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype("text/plain");
    contentWriter.setEncoding("UTF-8");
    contentWriter.putContent(updatedText);

    assertTrue(nodeService.exists(folderRef));
    assertTrue(nodeService.exists(contentRef));
    assertTrue(nodeService.exists(workingCopyRef));

    // delete folder
    nodeService.deleteNode(folderRef);

    assertFalse(nodeService.exists(folderRef));
    assertFalse(nodeService.exists(contentRef));
    assertFalse(nodeService.exists(workingCopyRef));

    // restore folder
    NodeRef archiveNodeRef = new NodeRef(archiveRootNodeRef.getStoreRef(), folderRef.getId());
    nodeService.restoreNode(archiveNodeRef, null, null, null);

    assertTrue(nodeService.exists(folderRef));
    assertTrue(nodeService.exists(contentRef));
    assertTrue(nodeService.exists(workingCopyRef));

    assertTrue(nodeService.hasAspect(workingCopyRef, ContentModel.ASPECT_WORKING_COPY));
    assertTrue(nodeService.hasAspect(workingCopyRef, ContentModel.ASPECT_COPIEDFROM));
    assertTrue(nodeService.hasAspect(contentRef, ContentModel.ASPECT_CHECKED_OUT));

    assertEquals(initialText, contentService.getReader(contentRef, ContentModel.PROP_CONTENT).getContentString());
    assertEquals(updatedText, contentService.getReader(workingCopyRef, ContentModel.PROP_CONTENT).getContentString());
    
    // belts-and-braces - also show that we can move a folder with checked-out item
    NodeRef folderRef2 = createFolder(spacesRootNodeRef, "testDeleteAndRestore-folder2-"+System.currentTimeMillis());
    
    nodeService.moveNode(folderRef, folderRef2, ContentModel.ASSOC_CONTAINS, ContentModel.ASSOC_CONTAINS);

    // checkin content node (working copy)
    cociService.checkin(workingCopyRef, null);

    assertFalse(nodeService.exists(workingCopyRef));

    assertEquals(updatedText, contentService.getReader(contentRef, ContentModel.PROP_CONTENT).getContentString());
}
 
Example 18
Source File: AlfrescoCmisServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void checkIn(
        String repositoryId, final Holder<String> objectId, final Boolean major,
        final Properties properties, final ContentStream contentStream, final String checkinComment,
        final List<String> policies, final Acl addAces, final Acl removeAces, ExtensionsData extension)
{
    checkRepositoryId(repositoryId);

    CMISNodeInfo info = getOrCreateNodeInfo(objectId.getValue(), "Object");

    // only accept a PWC
    if (!info.isVariant(CMISObjectVariant.PWC))
    {
        throw new CmisVersioningException("Object is not a PWC!");
    }

    // get object
    final NodeRef nodeRef = info.getNodeRef();
    final TypeDefinitionWrapper type = info.getType();

    // check in
    // update PWC
    connector.setProperties(nodeRef, type, properties,
            new String[] { PropertyIds.OBJECT_TYPE_ID });
    connector.applyPolicies(nodeRef, type, policies);
    connector.applyACL(nodeRef, type, addAces, removeAces);

    // handle content
    if (contentStream != null)
    {
        String mimeType = parseMimeType(contentStream);
        String encoding = getEncoding(contentStream.getStream(), mimeType);
        // write content
        ContentWriter writer = connector.getFileFolderService().getWriter(nodeRef);
        writer.setMimetype(mimeType);
        writer.setEncoding(encoding);
        writer.putContent(contentStream.getStream());
    }

    // create version properties
    Map<String, Serializable> versionProperties = new HashMap<String, Serializable>(5);
    versionProperties.put(VersionModel.PROP_VERSION_TYPE, major ? VersionType.MAJOR
            : VersionType.MINOR);
    if (checkinComment != null)
    {
        versionProperties.put(VersionModel.PROP_DESCRIPTION, checkinComment);
    }

    // check in
    NodeRef newNodeRef = connector.getCheckOutCheckInService().checkin(nodeRef, versionProperties);

    connector.getActivityPoster().postFileFolderUpdated(info.isFolder(), newNodeRef);

    objectId.setValue(connector.createObjectId(newNodeRef));
}
 
Example 19
Source File: RepoAdminServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public NodeRef deployModel(InputStream modelStream, String modelFileName, boolean activate)
{
    try
    {   
        // Check that all the passed values are not null
        ParameterCheck.mandatory("ModelStream", modelStream);
        ParameterCheck.mandatoryString("ModelFileName", modelFileName);
        
        Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>();
        contentProps.put(ContentModel.PROP_NAME, modelFileName);
        
        StoreRef storeRef = repoModelsLocation.getStoreRef();
        NodeRef rootNode = nodeService.getRootNode(storeRef);
        
        List<NodeRef> nodeRefs = searchService.selectNodes(rootNode, repoModelsLocation.getPath(), null, namespaceService, false);
        
        if (nodeRefs.size() == 0)
        {
            throw new AlfrescoRuntimeException(MODELS_LOCATION_NOT_FOUND, new Object[] { repoModelsLocation.getPath() });
        }
        else if (nodeRefs.size() > 1)
        {
            // unexpected: should not find multiple nodes with same name
            throw new AlfrescoRuntimeException(MODELS_LOCATION_MULTIPLE_FOUND, new Object[] { repoModelsLocation.getPath() });
        }
        
        NodeRef customModelsSpaceNodeRef = nodeRefs.get(0);
        
        nodeRefs = searchService.selectNodes(customModelsSpaceNodeRef, "*[@cm:name='"+modelFileName+"' and "+defaultSubtypeOfDictionaryModel+"]", null, namespaceService, false);
        
        NodeRef modelNodeRef = null;
            
        if (nodeRefs.size() == 1)
        {
            // re-deploy existing model to the repository       
            
            modelNodeRef = nodeRefs.get(0);
        }
        else
        {
            // deploy new model to the repository
            
            try
            {
                // note: dictionary model type has associated policies that will be invoked
                ChildAssociationRef association = nodeService.createNode(customModelsSpaceNodeRef,
                        ContentModel.ASSOC_CONTAINS,
                        QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, modelFileName),
                        ContentModel.TYPE_DICTIONARY_MODEL,
                        contentProps); // also invokes policies for DictionaryModelType - e.g. onUpdateProperties
                            
                modelNodeRef = association.getChildRef();
            }
            catch (DuplicateChildNodeNameException dcnne)
            {
                String msg = "Model already exists: "+modelFileName+" - "+dcnne;
                logger.warn(msg);

                // for now, assume concurrency failure
                throw new ConcurrencyFailureException(getLocalisedMessage(MODEL_EXISTS, modelFileName));
            }
            
            // add titled aspect (for Web Client display)
            Map<QName, Serializable> titledProps = new HashMap<QName, Serializable>();
            titledProps.put(ContentModel.PROP_TITLE, modelFileName);
            titledProps.put(ContentModel.PROP_DESCRIPTION, modelFileName);
            nodeService.addAspect(modelNodeRef, ContentModel.ASPECT_TITLED, titledProps);
            
            // add versionable aspect (set auto-version)
            Map<QName, Serializable> versionProps = new HashMap<QName, Serializable>();
            versionProps.put(ContentModel.PROP_AUTO_VERSION, true);
            nodeService.addAspect(modelNodeRef, ContentModel.ASPECT_VERSIONABLE, versionProps);
        }
        
        ContentWriter writer = contentService.getWriter(modelNodeRef, ContentModel.PROP_CONTENT, true);

        writer.setMimetype(MimetypeMap.MIMETYPE_XML);
        writer.setEncoding("UTF-8");
        
        writer.putContent(modelStream); // also invokes policies for DictionaryModelType - e.g. onContentUpdate
        modelStream.close();
        
        // activate the model
        nodeService.setProperty(modelNodeRef, ContentModel.PROP_MODEL_ACTIVE, Boolean.valueOf(activate));
        
        // note: model will be loaded as part of DictionaryModelType.beforeCommit()

        return modelNodeRef;
    }
    catch (Throwable e)
    {
        throw new AlfrescoRuntimeException(MODEL_DEPLOYMENT_FAILED, e);
    }     
}
 
Example 20
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 " );

    }