Java Code Examples for org.alfresco.model.ContentModel

The following are top voted examples for showing how to use org.alfresco.model.ContentModel. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: alfresco-repository   File: ImporterComponent.java   View source code 6 votes vote down vote up
/**
 * Construct
 * 
 * @param rootRef NodeRef
 * @param location Location
 * @param binding ImporterBinding
 * @param streamHandler ImportPackageHandler
 * @param progress ImporterProgress
 */
private NodeImporter(NodeRef rootRef, Location location, ImporterBinding binding, ImportPackageHandler streamHandler, ImporterProgress progress)
{
    this.rootRef = rootRef;
    this.rootAssocType = location.getChildAssocType();
    this.location = location;
    this.binding = binding;
    this.progress = progress;
    this.streamHandler = streamHandler;
    this.importStrategy = createNodeImporterStrategy(binding == null ? null : binding.getUUIDBinding());
    this.updateStrategy = new UpdateExistingNodeImporterStrategy();

    // initialise list of content models to exclude from import
    if (binding == null || binding.getExcludedClasses() == null)
    {
        this.excludedClasses = new QName[] { ContentModel.ASPECT_REFERENCEABLE };
    }
    else
    {
        this.excludedClasses = binding.getExcludedClasses();
    }
}
 
Example 2
Project: alfresco-remote-api   File: LoginTest.java   View source code 6 votes vote down vote up
private void createUser(String userName, String password)
{
    if (this.authenticationService.authenticationExists(userName) == false)
    {
        this.authenticationService.createAuthentication(userName, password.toCharArray());
        
        PropertyMap ppOne = new PropertyMap(4);
        ppOne.put(ContentModel.PROP_USERNAME, userName);
        ppOne.put(ContentModel.PROP_FIRSTNAME, "firstName");
        ppOne.put(ContentModel.PROP_LASTNAME, "lastName");
        ppOne.put(ContentModel.PROP_EMAIL, "[email protected]");
        ppOne.put(ContentModel.PROP_JOBTITLE, "jobTitle");
        
        this.personService.createPerson(ppOne);
    }        
}
 
Example 3
Project: alfresco-repository   File: MultilingualContentServiceImpl.java   View source code 6 votes vote down vote up
/**
 * @return Returns a reference to the node that will hold all the <b>cm:mlContainer</b> nodes.
 */
private NodeRef getMLContainerRoot()
{
    NodeRef rootNodeRef = nodeService.getRootNode(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
    List<ChildAssociationRef> assocRefs = nodeService.getChildAssocs(
            rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QNAME_ASSOC_ML_ROOT);
    if (assocRefs.size() != 1)
    {
        throw new AlfrescoRuntimeException(
                "Unable to find bootstrap location for ML Root using query: " + QNAME_ASSOC_ML_ROOT);
    }
    NodeRef mlRootNodeRef = assocRefs.get(0).getChildRef();
    // Done
    return mlRootNodeRef;
}
 
Example 4
Project: alfresco-repository   File: MultiTDemoTest.java   View source code 6 votes vote down vote up
private void loginLogoutUser(String username, String password)
{
    // authenticate via the authentication service
    authenticationService.authenticate(username, password.toCharArray());
    
    // set the user name as stored by the back end 
    username = authenticationService.getCurrentUserName();
    
    NodeRef personRef = personService.getPerson(username);
    NodeRef homeSpaceRef = (NodeRef)nodeService.getProperty(personRef, ContentModel.PROP_HOMEFOLDER);
    
    // check that the home space node exists - else user cannot login
    if (nodeService.exists(homeSpaceRef) == false)
    {
       throw new InvalidNodeRefException(homeSpaceRef);
    }
    
    // logout
    authenticationService.clearCurrentSecurityContext();
}
 
Example 5
Project: alfresco-repository   File: NodeFormProcessor.java   View source code 6 votes vote down vote up
/**
 * Determines whether the given node represents a working copy, if it does
 * the name field is searched for and set to protected as the name field
 * should not be edited for a working copy.
 * 
 * If the node is not a working copy this method has no effect.
 * 
 * @param nodeRef NodeRef of node to check and potentially process
 * @param form The generated form
 */
protected void processWorkingCopy(NodeRef nodeRef, Form form)
{
    // if the node is a working copy ensure that the name field (id present)
    // is set to be protected as it can not be edited
    if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_WORKING_COPY))
    {
        // go through fields looking for name field
        for (FieldDefinition fieldDef : form.getFieldDefinitions())
        {
            if (fieldDef.getName().equals(ContentModel.PROP_NAME.toPrefixString(this.namespaceService)))
            {
                fieldDef.setProtectedField(true);
                
                if (getLogger().isDebugEnabled())
                {
                    getLogger().debug("Set " + ContentModel.PROP_NAME.toPrefixString(this.namespaceService) +
                                "field to protected as it is a working copy");
                }
                
                break;
            }
        }
    }
}
 
Example 6
Project: alfresco-repository   File: HiddenAspectTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unused")
@Test
public void testCheckHidden() throws Exception
{
    String nodeName = GUID.generate();

    interceptor.setEnabled(false);

    try
    {
        // Create some nodes that should be hidden but aren't
        NodeRef node = fileFolderService.create(topNodeRef, nodeName, ContentModel.TYPE_FOLDER).getNodeRef();
        NodeRef node11 = fileFolderService.create(node, nodeName + ".11", ContentModel.TYPE_FOLDER).getNodeRef();
        NodeRef node12 = fileFolderService.create(node, ".12", ContentModel.TYPE_CONTENT).getNodeRef();
        NodeRef node21 = fileFolderService.create(node11, nodeName + ".21", ContentModel.TYPE_FOLDER).getNodeRef();
        NodeRef node22 = fileFolderService.create(node11, nodeName + ".22", ContentModel.TYPE_CONTENT).getNodeRef();
        NodeRef node31 = fileFolderService.create(node21, ".31", ContentModel.TYPE_FOLDER).getNodeRef();
        NodeRef node41 = fileFolderService.create(node31, nodeName + ".41", ContentModel.TYPE_CONTENT).getNodeRef();

        txn.commit();
    }
    finally
    {
        interceptor.setEnabled(true);
    }
}
 
Example 7
Project: alfresco-repository   File: BlogServiceImpl.java   View source code 6 votes vote down vote up
/**
 * Builds up a {@link BlogPostInfo} object for the given node
 */
private BlogPostInfo buildBlogPost(NodeRef nodeRef, NodeRef parentNodeRef, String postName)
{
   BlogPostInfoImpl post = new BlogPostInfoImpl(nodeRef, parentNodeRef, postName);
   
   // Grab all the properties, we need the bulk of them anyway
   Map<QName,Serializable> props = nodeService.getProperties(nodeRef);

   // Populate them
   post.setTitle((String)props.get(ContentModel.PROP_TITLE));
   // TODO Populate the rest
   
   // Finally set tags
   // TODO
   
   // All done
   return post;
}
 
Example 8
Project: alfresco-remote-api   File: AbstractGetBlogWebScript.java   View source code 6 votes vote down vote up
/**
 * Fetches all posts of the given blog
 */
private PagingResults<BlogPostInfo> getBlogPostList(SiteInfo site, NodeRef nonSiteContainer, 
      Date fromDate, Date toDate, String tag, PagingRequest pagingReq)
{
    // Currently we only support CannedQuery-based gets without tags:
    if (tag == null || tag.trim().isEmpty())
    {
        return getBlogResultsImpl(site, nonSiteContainer, fromDate, toDate, pagingReq);
    }
    else
    {
        RangedDateProperty dateRange = new RangedDateProperty(fromDate, toDate, ContentModel.PROP_CREATED);  
        if(site != null)
        {
           return blogService.findBlogPosts(site.getShortName(), dateRange, tag, pagingReq);
        }
        else
        {
           return blogService.findBlogPosts(nonSiteContainer, dateRange, tag, pagingReq);
        }
    }
}
 
Example 9
Project: alfresco-repository   File: MultilingualContentServiceImplTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unused")
public void testCreateEmptyTranslation() throws Exception
{
    NodeRef chineseContentNodeRef = createContent("Document.txt");
    multilingualContentService.makeTranslation(chineseContentNodeRef, Locale.CHINESE);

    // This should use the pivot language
    NodeRef emptyNodeRef = multilingualContentService.addEmptyTranslation(chineseContentNodeRef, "Document.txt", Locale.CANADA);

    // Ensure that the empty translation is not null
    assertNotNull("The creation of the empty document failed ", emptyNodeRef);
    // Ensure that the empty translation has the mlDocument aspect
    assertTrue("The empty document must have the mlDocument aspect",
            nodeService.hasAspect(emptyNodeRef, ContentModel.ASPECT_MULTILINGUAL_DOCUMENT));
    // Ensure that the empty translation has the mlEmptyTranslation aspect
    assertTrue("The empty document must have the mlEmptyTranslation aspect",
            nodeService.hasAspect(emptyNodeRef, ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION));
    // Check that the auto renaming worked
    String emptyName = DefaultTypeConverter.INSTANCE.convert(String.class,
            nodeService.getProperty(emptyNodeRef, ContentModel.PROP_NAME));
    assertEquals("Empty auto-rename didn't work for same-named document", "Document_en_CA.txt", emptyName);

    // Check that the content is identical
    ContentData chineseContentData = fileFolderService.getReader(chineseContentNodeRef).getContentData();
    ContentData emptyContentData = fileFolderService.getReader(emptyNodeRef).getContentData();
}
 
Example 10
Project: alfresco-repository   File: FileFolderServiceImpl.java   View source code 6 votes vote down vote up
@Override
public NodeRef searchSimple(NodeRef contextNodeRef, String name)
{
    ParameterCheck.mandatory("name", name);
    ParameterCheck.mandatory("contextNodeRef", contextNodeRef);
    
    NodeRef childNodeRef = nodeService.getChildByName(contextNodeRef, ContentModel.ASSOC_CONTAINS, name);
    if (logger.isTraceEnabled())
    {
        logger.trace(
                "Simple name search results: \n" +
                "   parent: " + contextNodeRef + "\n" +
                "   name: " + name + "\n" +
                "   result: " + childNodeRef);
    }
    return childNodeRef;
}
 
Example 11
Project: alfresco-repository   File: BaseNodeServiceTest.java   View source code 6 votes vote down vote up
public void testCreateStore() throws Exception
{
    StoreRef storeRef = createStore();
    
    // check that it exists
    assertTrue("NodeService reports that store doesn't exist", nodeService.exists(storeRef));
    
    // get the root node
    NodeRef storeRootNode = nodeService.getRootNode(storeRef);
    // make sure that it has the root aspect
    boolean isRoot = nodeService.hasAspect(storeRootNode, ContentModel.ASPECT_ROOT);
    assertTrue("Root node of store does not have root aspect", isRoot);
    // and is of the correct type
    QName rootType = nodeService.getType(storeRootNode);
    assertEquals("Store root node of incorrect type", ContentModel.TYPE_STOREROOT, rootType);
}
 
Example 12
Project: alfresco-repository   File: MultiTDemoTest.java   View source code 6 votes vote down vote up
private void clearUsage(String userName)
{
    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName()); // authenticate as super-admin
    
    // find person
    final NodeRef personNodeRef = personService.getPerson(userName);
    // clear user usage
    nodeService.setProperty(personNodeRef, ContentModel.PROP_SIZE_CURRENT, new Long(-1L));
    transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>()
    {
        @Override
        public Void execute() throws Throwable
        {
            usageService.deleteDeltas(personNodeRef);
            return null;
        }
    }, false);
}
 
Example 13
Project: alfresco-repository   File: MultiTDemoTest.java   View source code 6 votes vote down vote up
private NodeRef createFolderNode(NodeRef parentFolderNodeRef, String nameValue)
{
    if (nameValue != null)
    {       
        Map<QName, Serializable> folderProps = new HashMap<QName, Serializable>();
        folderProps.put(ContentModel.PROP_NAME, nameValue);
        
        return this.nodeService.createNode(
                parentFolderNodeRef, 
                ContentModel.ASSOC_CONTAINS, 
                QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, nameValue),
                ContentModel.TYPE_FOLDER,
                folderProps).getChildRef();
    }
    
    return null;
}
 
Example 14
Project: alfresco-repository   File: RuleServiceIntegrationTest.java   View source code 6 votes vote down vote up
@BeforeClass public static void setupTest() throws Exception
{
	
	SERVICE_REGISTRY          = (ServiceRegistry)APP_CONTEXT_INIT.getApplicationContext().getBean(ServiceRegistry.SERVICE_REGISTRY);
    NODE_SERVICE              = SERVICE_REGISTRY.getNodeService();
    TRANSACTION_HELPER        = SERVICE_REGISTRY.getTransactionService().getRetryingTransactionHelper();
    ACTION_SERVICE			  = SERVICE_REGISTRY.getActionService();
    RULE_SERVICE			  = SERVICE_REGISTRY.getRuleService();
    CONTENT_SERVICE 		  = SERVICE_REGISTRY.getContentService();
    MAIL_ACTION_EXECUTER 		  = APP_CONTEXT_INIT.getApplicationContext().getBean("OutboundSMTP", ApplicationContextFactory.class).getApplicationContext().getBean("mail", MailActionExecuter.class);
    
    WAS_IN_TEST_MODE = MAIL_ACTION_EXECUTER.isTestMode();
    MAIL_ACTION_EXECUTER.setTestMode(true);
    
    Repository repositoryHelper = (Repository) APP_CONTEXT_INIT.getApplicationContext().getBean("repositoryHelper");
    COMPANY_HOME = repositoryHelper.getCompanyHome();
    
    // Create some static test content
    TEST_FOLDER = STATIC_TEST_NODES.createNode(COMPANY_HOME, "testFolder", ContentModel.TYPE_FOLDER, AuthenticationUtil.getAdminUserName());
   
}
 
Example 15
Project: alfresco-repository   File: TransitionSimpleWorkflowActionExecuterTest.java   View source code 6 votes vote down vote up
/** Test for MNT-14730*/
public void testExecutionRejectWhenDestinationSameAsSource()
{
    addWorkflowAspect(node, sourceFolder, Boolean.FALSE, Boolean.FALSE);
    
    assertTrue(nodeService.hasAspect(node, ApplicationModel.ASPECT_SIMPLE_WORKFLOW));
    NodeRef pParent = nodeService.getPrimaryParent(node).getParentRef();
    assertEquals(sourceFolder, pParent);
    assertEquals(0, nodeService.getChildAssocs(destinationFolder).size());
    
    ActionImpl action = new ActionImpl(null, ID, "reject-simpleworkflow", null);
    rejectExecuter.execute(action, node);
    
    assertFalse(nodeService.hasAspect(node, ApplicationModel.ASPECT_SIMPLE_WORKFLOW));
    pParent = nodeService.getPrimaryParent(node).getParentRef();
    assertEquals(sourceFolder, pParent);        
    assertEquals(0, nodeService.getChildAssocs(destinationFolder).size());
    
    String copyName = QName.createValidLocalName("Copy of my node.txt");
    NodeRef nodeRef = nodeService.getChildByName(sourceFolder, ContentModel.ASSOC_CONTAINS, copyName);
    assertNotNull(nodeRef);
}
 
Example 16
Project: alfresco-repository   File: FileFolderServiceImplTest.java   View source code 6 votes vote down vote up
public void testRenameWithoutAssocQNameChange() throws Exception
{
    FileInfo folderInfo = getByName(NAME_L0_FOLDER_A, true);
    assertNotNull(folderInfo);
    NodeRef folderNodeRef = folderInfo.getNodeRef();
    // Create a child file
    QName assocQName = QName.createQName(NamespaceService.APP_MODEL_1_0_URI, "abc");
    NodeRef newFileNodeRef = fileFolderService.create(folderNodeRef, "AnotherFile.txt", ContentModel.TYPE_CONTENT,
            assocQName).getNodeRef();
    // Make sure that the correct association QName was used
    QName checkQName = nodeService.getPrimaryParent(newFileNodeRef).getQName();
    assertEquals("The given assoc QName was not used for the path", assocQName, checkQName);
    // Rename
    String newName = "AnotherFile-new.txt";
    folderInfo = fileFolderService.rename(newFileNodeRef, newName);
    // Make sure that the association QName did not change
    checkQName = nodeService.getPrimaryParent(newFileNodeRef).getQName();
    assertEquals("The given assoc QName was not used for the path after a rename", assocQName, nodeService
            .getPrimaryParent(newFileNodeRef).getQName());
}
 
Example 17
Project: alfresco-repository   File: MultilingualDocumentAspectTest.java   View source code 6 votes vote down vote up
public void testUpdateLocale() throws Exception
{
    NodeRef pivot  = createContent();
    NodeRef trans1 = createContent();
    multilingualContentService.makeTranslation(pivot, Locale.FRENCH);
    NodeRef mlContainer = multilingualContentService.getTranslationContainer(pivot);
    multilingualContentService.addTranslation(trans1, pivot, Locale.KOREAN);

    // modify the locale for the translation
    Map<QName, Serializable> props = nodeService.getProperties(trans1);
    props.put(ContentModel.PROP_LOCALE, Locale.GERMAN);
    nodeService.setProperties(trans1, props);

    // Ensure that the pivot reference is not changed for the mlContainer and the locale is changed for the translation
    assertEquals("The locale for the pivot would be changed ",Locale.GERMAN, nodeService.getProperty(trans1, ContentModel.PROP_LOCALE));
    assertEquals("The pivot reference would not be changed in the mlContainer", Locale.FRENCH, nodeService.getProperty(mlContainer, ContentModel.PROP_LOCALE));

    // modify the locale for the pivot
    props = nodeService.getProperties(pivot);
    props.put(ContentModel.PROP_LOCALE, Locale.US);
    nodeService.setProperties(pivot, props);

    // Ensure that the pivot reference is changed (in the pivot and in the mlContainer)
    assertEquals("The locale for the pivot would be changed ", Locale.US, nodeService.getProperty(pivot, ContentModel.PROP_LOCALE));
    assertEquals("The pivot reference would be changes in the mlContainer", Locale.US, nodeService.getProperty(mlContainer, ContentModel.PROP_LOCALE));
}
 
Example 18
Project: alfresco-repository   File: CheckOutCheckInServiceImpl.java   View source code 6 votes vote down vote up
@Override
@Extend(traitAPI=CheckOutCheckInServiceTrait.class,extensionAPI=CheckOutCheckInServiceExtension.class)
public NodeRef getCheckedOut(NodeRef nodeRef)
{
    NodeRef original = null;
    if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_WORKING_COPY))
    {
        List<AssociationRef> assocs = nodeService.getSourceAssocs(nodeRef, ContentModel.ASSOC_WORKING_COPY_LINK);
        // It is a 1:1 relationship
        if (assocs.size() == 0)
        {
            logger.warn("Found node with cm:workingcopy aspect but no association.  Current node state: " + nodeService.getNodeStatus(nodeRef));
        }
        else if (assocs.size() > 1)
        {
            logger.warn("Found multiple " + ContentModel.ASSOC_WORKING_COPY_LINK + " association to node: " + nodeRef);
        }
        else
        {
            original = assocs.get(0).getSourceRef();
        }
    }
    
    return original;
}
 
Example 19
Project: alfresco-repository   File: CheckOutCheckInServiceImplTest.java   View source code 6 votes vote down vote up
/**
 * Test when the aspect is not set when check-in is performed
 */
public void testVersionAspectNotSetOnCheckIn()
{
    // Create a bag of props
    Map<QName, Serializable> bagOfProps = createTypePropertyBag();
    bagOfProps.put(ContentModel.PROP_CONTENT, new ContentData(null, MimetypeMap.MIMETYPE_TEXT_PLAIN, 0L, "UTF-8"));

    // Create a new node 
    ChildAssociationRef childAssocRef = nodeService.createNode(
            rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("test"),
            ContentModel.TYPE_CONTENT,
            bagOfProps);
    NodeRef noVersionNodeRef = childAssocRef.getChildRef();
    
    // Check out and check in
    NodeRef workingCopy = cociService.checkout(noVersionNodeRef);
    cociService.checkin(workingCopy, new HashMap<String, Serializable>());
    
    // Check that the origional node has no version history dispite sending verion props
    assertNull(this.versionService.getVersionHistory(noVersionNodeRef));        
}
 
Example 20
Project: alfresco-repository   File: VersionServiceImpl.java   View source code 6 votes vote down vote up
/**
 * Freeze associations
 *
 * @param versionNodeRef   the version node reference
 * @param associations     the list of associations
 */
private void freezeAssociations(NodeRef versionNodeRef, List<AssociationRef> associations)
{
    for (AssociationRef targetAssoc : associations)
    {
        HashMap<QName, Serializable> properties = new HashMap<QName, Serializable>();

        // Set the qname of the association
        properties.put(PROP_QNAME_ASSOC_TYPE_QNAME, targetAssoc.getTypeQName());

        // Set the reference property to point to the child node
        properties.put(ContentModel.PROP_REFERENCE, targetAssoc.getTargetRef());

        // Create child version reference
        this.dbNodeService.createNode(
                versionNodeRef,
                CHILD_QNAME_VERSIONED_ASSOCS,
                CHILD_QNAME_VERSIONED_ASSOCS,
                TYPE_QNAME_VERSIONED_ASSOC,
                properties);
    }
}
 
Example 21
Project: alfresco-repository   File: VirtualFileFolderServiceExtensionTest.java   View source code 6 votes vote down vote up
@Test
public void testCreateTempFile() throws Exception
{
    NodeRef vf = createVirtualizedFolder(testRootFolder.getNodeRef(),
                                         "TestVirtualFileFolderService_testVirtualFolderVirtualChild",
                                         TEST_TEMPLATE_3_JSON_SYS_PATH);
    NodeRef node2 = nodeService.getChildByName(vf,
                                               ContentModel.ASSOC_CHILDREN,
                                               "Node2");
    String contentName = "ContentVirtualChild";
    createContent(node2,
                  contentName);
    NodeRef childByName = nodeService.getChildByName(node2,
                                                     ContentModel.ASSOC_CHILDREN,
                                                     contentName);

    // TODO to test with minimized nodeRef id when minimisation is finished
    File file = File.createTempFile("dedededede",
                                    ".tmp",
                                    TempFileProvider.getTempDir());
    assertNotNull(file);
}
 
Example 22
Project: alfresco-repository   File: BlogServiceImpl.java   View source code 6 votes vote down vote up
@Override
public BlogPostInfo getBlogPost(NodeRef parentNodeRef, String postName) 
{
   NodeRef postNode;
   try
   {
      postNode = nodeService.getChildByName(parentNodeRef, ContentModel.ASSOC_CONTAINS, postName);
   }
   catch(AccessDeniedException e)
   {
      // You can't see that blog post
      // For compatibility with the old webscripts, rather than
      //  reporting permission denied, pretend it isn't there
      postNode = null;
   }

   // If we found a node, wrap it as a BlogPostInfo
   if (postNode != null)
   {
      return buildBlogPost(postNode, parentNodeRef, postName);
   }
   return null;
}
 
Example 23
Project: alfresco-repository   File: QuickShareServiceIntegrationTest.java   View source code 6 votes vote down vote up
@Test public void cloud928()
{
    final NodeRef node = testNodes.createNodeWithTextContent(userHome,
            "CLOUD-928 Test Node",
            ContentModel.TYPE_CONTENT, 
            user1.getUsername(),
            "Quick Share Test Node Content");
    
    QuickShareDTO dto = share(node, user1.getUsername());

    attributeService.removeAttribute(QuickShareServiceImpl.ATTR_KEY_SHAREDIDS_ROOT, dto.getId());
    
    AuthenticationUtil.runAs(new RunAsWork<Object>(){

        @Override
        public Object doWork() throws Exception {
            nodeService.deleteNode(node);
            return null;
        }
    }, user1.getUsername());
 
    AuthenticationUtil.setAdminUserAsFullyAuthenticatedUser();
    Assert.assertFalse(nodeService.exists(node));
}
 
Example 24
Project: alfresco-remote-api   File: SOLRWebScriptTest.java   View source code 6 votes vote down vote up
private void buildTransactions7()
{
    txnHelper.doInTransaction(new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            PropertyMap props = new PropertyMap();
            props.put(ContentModel.PROP_NAME, "Container7");
            container7 = nodeService.createNode(
                    rootNodeRef,
                    ContentModel.ASSOC_CHILDREN,
                    ContentModel.ASSOC_CHILDREN,
                    ContentModel.TYPE_FOLDER,
                    props).getChildRef();

            FileInfo contentInfo = fileFolderService.create(container7, "Content1", ContentModel.TYPE_CONTENT);
            contents.add(contentInfo.getNodeRef());

            Map<QName, Serializable> aspectProperties = new HashMap<QName, Serializable>();
            aspectProperties.put(ContentModel.PROP_AUTHOR, "ste\"ve");
            nodeService.addAspect(contentInfo.getNodeRef(), ContentModel.ASPECT_AUTHOR, aspectProperties);

            return null;
        }
    });
}
 
Example 25
Project: alfresco-repository   File: CounterIncrementActionExecuter.java   View source code 6 votes vote down vote up
/**
 * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.action.Action, org.alfresco.service.cmr.repository.NodeRef)
 */
protected void executeImpl(Action action, NodeRef actionedUponNodeRef)
{
    // add the cm:countable aspect as required
    if (this.nodeService.hasAspect(actionedUponNodeRef, ContentModel.ASPECT_COUNTABLE) == false)
    {
        // set the value to 1 by default
        Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
        props.put(ContentModel.PROP_COUNTER, 1);
        this.nodeService.addAspect(actionedUponNodeRef, ContentModel.ASPECT_COUNTABLE, props);
    }
    else
    {
        // increment the value and handle possibility that no value has been set yet
        int resultValue = 1;
        Integer value = (Integer)this.nodeService.getProperty(actionedUponNodeRef, ContentModel.PROP_COUNTER);
        if (value != null)
        {
            resultValue = value.intValue() + 1;
        }
        this.nodeService.setProperty(actionedUponNodeRef, ContentModel.PROP_COUNTER, resultValue);
    }
}
 
Example 26
Project: alfresco-repository   File: AbstractBulkImportTests.java   View source code 5 votes vote down vote up
@Before
public void setup() throws SystemException, NotSupportedException
{
    try
    {
        nodeService = (NodeService)ctx.getBean("nodeService");
        fileFolderService = (FileFolderService)ctx.getBean("fileFolderService");
        transactionService = (TransactionService)ctx.getBean("transactionService");
        bulkImporter = (MultiThreadedBulkFilesystemImporter)ctx.getBean("bulkFilesystemImporter");
        contentService = (ContentService)ctx.getBean("contentService");
        actionService = (ActionService)ctx.getBean("actionService");
        ruleService = (RuleService)ctx.getBean("ruleService");
        versionService = (VersionService)ctx.getBean("versionService");

        AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

        String s = "BulkFilesystemImport" + System.currentTimeMillis();

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

        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

        StoreRef storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, s);
        rootNodeRef = nodeService.getRootNode(storeRef);
        top = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{namespace}top"), ContentModel.TYPE_FOLDER).getChildRef();
        
        topLevelFolder = fileFolderService.create(top, s, ContentModel.TYPE_FOLDER);

        txn.commit();
    }
    catch(Throwable e)
    {
        fail(e.getMessage());
    }
}
 
Example 27
Project: alfresco-repository   File: AuthorityServiceTest.java   View source code 5 votes vote down vote up
@Override
public void beforeDeleteNode(NodeRef nodeRef)
{
    String name = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_AUTHORITY_NAME);
    // this call refills the authority cache 
    System.out.println("removing " + authorityService.getAuthorityNodeRef(name));
}
 
Example 28
Project: alfresco-repository   File: PermissionServiceTest.java   View source code 5 votes vote down vote up
@Category(PerformanceTests.class)
public void testAclInsertionPerformanceDefining()
{
    NodeRef parent = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{namespace}one"), ContentModel.TYPE_FOLDER).getChildRef();
    for(int i = 0; i < 1000; i++)
    {
        NodeRef created = nodeService.createNode(parent, ContentModel.ASSOC_CHILDREN, QName.createQName("{namespace}child"+i), ContentModel.TYPE_FOLDER).getChildRef();
        permissionService.setPermission(new SimplePermissionEntry(created, getPermission(PermissionService.CONSUMER), "bob", AccessStatus.ALLOWED));
    }
    long start = System.nanoTime();
    permissionService.setPermission(new SimplePermissionEntry(parent, getPermission(PermissionService.CONSUMER), "andy", AccessStatus.ALLOWED));
    long end = System.nanoTime();

    //assertTrue("Time was "+(end - start)/1000000000.0f, end == start);
}
 
Example 29
Project: alfresco-repository   File: CMISTest.java   View source code 5 votes vote down vote up
private void assertVersions(final NodeRef nodeRef, final String expectedVersionLabel, final VersionType expectedVersionType)
{
    transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<List<Void>>()
    {
        @Override
        public List<Void> execute() throws Throwable
        {
            assertTrue("Node should be versionable", nodeService.hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE));
            
            Version version = versionService.getCurrentVersion(nodeRef);
            
            assertNotNull(version);
            assertEquals(expectedVersionLabel, version.getVersionLabel());
            assertEquals(expectedVersionType, version.getVersionType());
            
            return null;
        }
    });
    
    withCmisService(new CmisServiceCallback<Void>()
    {
        @Override
        public Void execute(CmisService cmisService)
        {
            String repositoryId = cmisService.getRepositoryInfos(null).get(0).getId();
            
            ObjectData data = 
                cmisService.getObjectOfLatestVersion(repositoryId, nodeRef.toString(), null, Boolean.FALSE, null, null, null, null, null, null, null);
            
            assertNotNull(data);
            
            PropertyData<?> prop = data.getProperties().getProperties().get(PropertyIds.VERSION_LABEL);
            Object versionLabelCmisValue = prop.getValues().get(0);
            
            assertEquals(expectedVersionLabel, versionLabelCmisValue);
            
            return null;
        }
    }, CmisVersion.CMIS_1_1);
}
 
Example 30
Project: alfresco-repository   File: ContentDiskDriverTest.java   View source code 5 votes vote down vote up
/**
 * Searching for file object with specified name or creating new one if such object is not exist
 * 
 * @param parentRef - {@link NodeRef} of desired parent object
 * @param name - {@link String} value for name of desired file object
 * @param type - {@link QName} instance which determines type of the object. It may be cm:content, cm:folder etc (see {@link ContentModel})
 * @return {@link Pair}&lt;{@link org.alfresco.service.cmr.model.FileInfo}, {@link Boolean}> instance which contains {@link NodeRef} of newly created object and
 *         <code>true</code> value if file object with specified name was not found or {@link NodeRef} of existent file object and <code>false</code> in other case
 */
private Pair<org.alfresco.service.cmr.model.FileInfo, Boolean> getOrCreateNode(NodeRef parentRef, String name, QName type)
{
    NodeRef result = nodeService.getChildByName(parentRef, ContentModel.ASSOC_CONTAINS, name);
    Boolean created = false;
    if (null == result)
    {
        result = nodeService.getChildByName(parentRef, ContentModel.ASSOC_CHILDREN, name);
    }
    if (created = (null == result))
    {
        result = fileFolderService.create(parentRef, name, type).getNodeRef();
    }
    return new Pair<org.alfresco.service.cmr.model.FileInfo, Boolean>(fileFolderService.getFileInfo(result), created);
}
 
Example 31
Project: alfresco-repository   File: TemplateFilingRuleTest.java   View source code 5 votes vote down vote up
@Test
public void testFilingSubPath_specialCharacters() throws Exception
{
    NodeRef vfNodeRef = createVirtualizedFolder(testRootFolder.getNodeRef(),
                                                "Template 6 With Spaces",
                                                TEST_TEMPLATE_5_JSON_SYS_PATH);

    NodeRef sfpNodeRef = nodeService.getChildByName(vfNodeRef,
                                                    ContentModel.ASSOC_CONTAINS,
                                                    "SpecialFilingPath5");

    Reference sfpReference = Reference.fromNodeRef(sfpNodeRef);
    ApplyTemplateMethod applyTemplateMethod = new ApplyTemplateMethod(environment);

    VirtualFolderDefinition structure = sfpReference.execute(applyTemplateMethod);

    FilingRule filingRule = structure.getFilingRule();

    assertTrue(filingRule instanceof TemplateFilingRule);

    NodeRef fn = filingRule.filingNodeRefFor(new FilingParameters(sfpReference));
    assertNull(fn);
    createFolder(vfNodeRef,
                 "Space Sub Folder");
    fn = filingRule.filingNodeRefFor(new FilingParameters(sfpReference));
    assertNotNull(fn);
}
 
Example 32
Project: alfresco-repository   File: EditionServiceImpl.java   View source code 5 votes vote down vote up
/** {@inheritDoc} */
public NodeRef createEdition(NodeRef startingTranslationNodeRef, Map<String, Serializable> versionProperties)
{
    if (nodeService.hasAspect(startingTranslationNodeRef, ContentModel.ASPECT_MULTILINGUAL_DOCUMENT))
    {
        return createEditionImpl(
                startingTranslationNodeRef,
                versionProperties
            );
    }
    else
    {
        throw new IllegalArgumentException("The node " + startingTranslationNodeRef + " is not multilingual.");
    }
}
 
Example 33
Project: alfresco-repository   File: NodeMonitor.java   View source code 5 votes vote down vote up
/**
* Create node event
* 
* @param childAssocRef ChildAssociationRef
*/
  public void onCreateNode(ChildAssociationRef childAssocRef) {
  	
  	// Check if the node is a file/folder
  	
  	NodeRef nodeRef = childAssocRef.getChildRef();
  	if ( nodeRef.getStoreRef().equals( m_storeRef) == false)
  	{
  	    // different store so irrelevant
  		return;
  	}
  	
  	QName nodeType = m_nodeService.getType( nodeRef);
  	FileFolderServiceType fType = m_fileFolderService.getType( nodeType);
  	    	
  	if ( fType != FileFolderServiceType.INVALID) 
  	{
  		// Node is not INVALID - therefore its VALID
  	    Path nodePath = m_nodeService.getPath( nodeRef);
          String relPath = nodePath.toDisplayPath(m_nodeService, m_permissionService);
          String fName = (String) m_nodeService.getProperty( nodeRef, ContentModel.PROP_NAME);

  		if ( logger.isDebugEnabled()) 
  		{
  			logger.debug("OnCreateNode: nodeRef=" + nodeRef + ", name=" + fName + ", path=" + relPath);
  		}
  	
  		// Create an event to process the node creation
  		NodeEvent nodeEvent = new CreateNodeEvent( fType, nodeRef, relPath, fName);
  		
  		// Store the event in the transaction until committed, and register the transaction listener
  		fireNodeEvent(nodeEvent);
  	}
  }
 
Example 34
Project: alfresco-repository   File: RuleServiceCoverageTest.java   View source code 5 votes vote down vote up
/**
 * Adds content to a given node. 
 * <p>
 * Used to trigger rules of type of incomming.
 * 
 * @param nodeRef  the node reference
 */
private void addContentToNode(NodeRef nodeRef)
{
	ContentWriter contentWriter = this.contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
    contentWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    contentWriter.setEncoding("UTF-8");
	assertNotNull(contentWriter);
	contentWriter.putContent(STANDARD_TEXT_CONTENT + System.currentTimeMillis());
}
 
Example 35
Project: alfresco-repository   File: ExporterComponentTest.java   View source code 5 votes vote down vote up
/**
 * @param acpFile File
 * @param destRootNode NodeRef
 * @return FileInfo
 */
private FileInfo importContent(File acpFile, NodeRef destRootNode)
{
    FileInfo importFolderFileInfo = fileFolderService.create(destRootNode, "Import Folder", ContentModel.TYPE_FOLDER);
    ImportPackageHandler importHandler = new ACPImportPackageHandler(acpFile, ACPImportPackageHandler.DEFAULT_ENCODING);
    importerService.importView(importHandler, new Location(importFolderFileInfo.getNodeRef()), null, null);
    return importFolderFileInfo;
}
 
Example 36
Project: alfresco-repository   File: WorkflowServiceImpl.java   View source code 5 votes vote down vote up
/**
 * @param workflowPackage NodeRef
 */
private List<NodeRef> getRepositoryPackageContents(NodeRef workflowPackage)
{
    List<NodeRef> contents = new ArrayList<NodeRef>();
    // get existing workflow package items
    List<ChildAssociationRef> packageAssocs = protectedNodeService.getChildAssocs(workflowPackage);
    for (ChildAssociationRef assoc : packageAssocs)
    {
        // create our Node representation from the NodeRef
        NodeRef nodeRef = assoc.getChildRef();
        QName assocType = assoc.getTypeQName();
        if (!protectedNodeService.exists(nodeRef))
        {
            if (logger.isDebugEnabled())
                logger.debug("Ignoring " + nodeRef + " as it has been removed from the repository");
        }
        else if (!ContentModel.ASSOC_CONTAINS.equals(assocType) && !WorkflowModel.ASSOC_PACKAGE_CONTAINS.equals(assocType))
        {
            if (logger.isDebugEnabled())
                logger.debug("Ignoring " + nodeRef + " as it has an invalid association type: "+assocType);
        }
        else
        {
            if (checkTypeIsInDataDictionary(nodeRef))
            {
                contents.add(nodeRef);
            }
        }
    }
    return contents;
}
 
Example 37
Project: alfresco-better-trashmanagement   File: ArchivedItemsChildrenGet.java   View source code 5 votes vote down vote up
protected void validateArchivedItem(final NodeRef node)
{
    NodeRef currentNode = node;
    while (currentNode != null && !this.nodeService.hasAspect(currentNode, ContentModel.ASPECT_ARCHIVED))
    {
        final ChildAssociationRef primaryParent = this.nodeService.getPrimaryParent(currentNode);
        currentNode = primaryParent != null ? primaryParent.getParentRef() : null;
    }

    if (currentNode == null)
    {
        throw new WebScriptException(Status.STATUS_NOT_FOUND, "Archived node " + node + " does not exist");
    }
}
 
Example 38
Project: alfresco-repository   File: ActionServiceImplTest.java   View source code 5 votes vote down vote up
/**
 * Test evaluate action condition
 */
public void testEvaluateActionCondition()
{
    ActionCondition condition = this.actionService.createActionCondition(ComparePropertyValueEvaluator.NAME);
    condition.setParameterValue(ComparePropertyValueEvaluator.PARAM_VALUE, "*.doc");
    
    assertFalse(this.actionService.evaluateActionCondition(condition, this.nodeRef));
    this.nodeService.setProperty(this.nodeRef, ContentModel.PROP_NAME, "myDocument.doc");
    assertTrue(this.actionService.evaluateActionCondition(condition, this.nodeRef));
    
    // Check that inverting the condition has the correct effect
    condition.setInvertCondition(true);
    assertFalse(this.actionService.evaluateActionCondition(condition, this.nodeRef));
}
 
Example 39
Project: alfresco-repository   File: PermissionServiceTest.java   View source code 5 votes vote down vote up
@Category(PerformanceTests.class)
public void testAclInsertionPerformanceShared()
{
    NodeRef parent = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, QName.createQName("{namespace}one"), ContentModel.TYPE_FOLDER).getChildRef();
    for(int i = 0; i < 1000; i++)
    {
        nodeService.createNode(parent, ContentModel.ASSOC_CHILDREN, QName.createQName("{namespace}child"+i), ContentModel.TYPE_FOLDER).getChildRef();
    }
    long start = System.nanoTime();
    permissionService.setPermission(new SimplePermissionEntry(parent, getPermission(PermissionService.CONSUMER), "andy", AccessStatus.ALLOWED));
    long end = System.nanoTime();

    //assertTrue("Time was "+(end - start)/1000000000.0f, end == start);
}
 
Example 40
Project: alfresco-repository   File: AbstractNodeDAOImpl.java   View source code 5 votes vote down vote up
@Override
public Set<QName> getNodeAspects(Long nodeId)
{
    Set<QName> nodeAspects = getNodeAspectsCached(nodeId);
    // Nodes are always referenceable
    nodeAspects.add(ContentModel.ASPECT_REFERENCEABLE);
    // Nodes are always localized
    nodeAspects.add(ContentModel.ASPECT_LOCALIZED);
    return nodeAspects;
}