Java Code Examples for org.alfresco.service.cmr.repository.NodeRef

The following are top voted examples for showing how to use org.alfresco.service.cmr.repository.NodeRef. 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: FileFolderServiceImpl.java   View source code 6 votes vote down vote up
@Override
public void setHidden(NodeRef nodeRef, boolean isHidden)
{
    int mask = 0;
    boolean allVisible = true;
    Visibility webDavVisibility = isHidden ? Visibility.NotVisible : Visibility.Visible;
    for (Client client : hiddenAspect.getClients())
    {
        Visibility clientVisibility = client == FileFilterMode.getClient() ? webDavVisibility : hiddenAspect
                .getVisibility(client, nodeRef);
        if (clientVisibility != Visibility.Visible)
        {
            allVisible = false;
        }
        mask |= hiddenAspect.getClientVisibilityMask(client, clientVisibility);
    }
    if (allVisible)
    {
        hiddenAspect.showNode(nodeRef, true);
    }
    else
    {
        hiddenAspect.hideNode(nodeRef, mask, true, true, false);
    }
}
 
Example 2
Project: alfresco-remote-api   File: SiteServiceTest.java   View source code 6 votes vote down vote up
private void checkPermissions(NodeRef nodeRef, String necessatyAuth, String expectedPermission, String actionInfo)
{
    Set<AccessPermission> allSetPermissions = permissionService.getAllSetPermissions(nodeRef);
    for (AccessPermission perm : allSetPermissions)
    {
        String authority = perm.getAuthority();
        if (necessatyAuth.equals(authority))
        {
            if (expectedPermission.equals(perm.getPermission()))
            {
                return;
            }
            fail("Expected permissions for authority \"" + necessatyAuth + "\" are incorrect. Expected: " + expectedPermission + ", but actual permission: "
                    + perm.getPermission() + ". Check position: " + actionInfo);
        }
    }
    fail("Expected authority \"" + necessatyAuth + "\" wasn't found. Check position: " + actionInfo);
}
 
Example 3
Project: alfresco-repository   File: EditionServiceImplTest.java   View source code 6 votes vote down vote up
private void checkFirstVersion(NodeRef mlContainerNodeRef)
{
    // get the edition list of edition
    VersionHistory editionHistory = editionService.getEditions(mlContainerNodeRef);

    // Ensure that the first edition of the mlContainer is created
    assertNotNull("The edition history can't be null", editionHistory);
    // Ensure that it contains only one version
    assertTrue("The edition history must contain only one edition", editionHistory.getAllVersions().size() == 1);

    // get the edition
    Version currentEdition = editionHistory.getAllVersions().iterator().next();

    // Ensure that this version is the edition of the mlContainer
    assertTrue("The versioned mlContainer noderef of the editon must be the noderef of the created mlContainer", currentEdition.getVersionedNodeRef().equals(mlContainerNodeRef));

    // get the list of translations
    List<VersionHistory> translations = editionService.getVersionedTranslations(currentEdition);

    // Ensure that the get versioned translations is empty
    assertNotNull("The translations list of the current edition can't be null", translations);
    // Ensure that the list is empty
    assertTrue("The translations list of the current edition would be empty", translations.size() == 0);
}
 
Example 4
Project: alfresco-repository   File: TransferServiceImpl2.java   View source code 6 votes vote down vote up
/**
 * Given the noderef of a group of transfer targets, return all the contained transfer targets.
 * @param groupNode NodeRef
 * @return Set<TransferTarget>
 */
private Set<TransferTarget> getTransferTargets(NodeRef groupNode)
{
    Set<TransferTarget> result = new HashSet<TransferTarget>();
    List<ChildAssociationRef>children = nodeService.getChildAssocs(groupNode, ContentModel.ASSOC_CONTAINS, RegexQNamePattern.MATCH_ALL);
    
    for(ChildAssociationRef child : children)
    {
        if(nodeService.getType(child.getChildRef()).equals(TransferModel.TYPE_TRANSFER_TARGET))
        {
            TransferTargetImpl newTarget = new TransferTargetImpl();
            mapTransferTarget(child.getChildRef(), newTarget);
            result.add(newTarget);
        }
    }
    return result;
}
 
Example 5
Project: alfresco-repository   File: ActionFormProcessorTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override protected void executeImpl(Action action, NodeRef actionedUponNodeRef)
      {
          Object checkValue = action.getParameterValue("check");
          assertEquals("Parameter value should be Boolean", checkValue.getClass(), Boolean.class);

          Object dateValue = action.getParameterValue("date");
          assertEquals("Parameter value should be Date", dateValue.getClass(), Date.class);

          Object qnameValue = action.getParameterValue("qname");
          assertEquals("Parameter value should be ArrayList", qnameValue.getClass(), ArrayList.class);
          for (QName qname : (ArrayList<QName>)qnameValue)
          {
              assertEquals("The item value should be QName", qname.getClass(), QName.class);
          }

          Object nodeRefsValue = action.getParameterValue("nodeRefs");
          assertEquals("Parameter value should be ArrayList", nodeRefsValue.getClass(), ArrayList.class);
          for (NodeRef nodeRef : (ArrayList<NodeRef>)nodeRefsValue)
          {
              assertEquals("The item value should be NodeRef", nodeRef.getClass(), NodeRef.class);
          }
      }
 
Example 6
Project: alfresco-repository   File: ImapServiceImpl.java   View source code 6 votes vote down vote up
public void unsubscribe(AlfrescoImapUser user, String mailbox)
{
    if (logger.isDebugEnabled())
    {
        logger.debug("Unsubscribing: " + user + ", " + mailbox);
    }
    AlfrescoImapFolder mailFolder = getOrCreateMailbox(user, mailbox, true, false);
    if(mailFolder.getFolderInfo() != null)
    {
        PersonService personService = serviceRegistry.getPersonService();
        NodeRef userRef = personService.getPerson(user.getLogin());
        nodeService.createAssociation(userRef, mailFolder.getFolderInfo().getNodeRef(), ImapModel.ASSOC_IMAP_UNSUBSCRIBED);
    }
    else
    {
        // perhaps the folder has been deleted by another async process?
        logger.debug("Unable to find folder to unsubscribe");
    }
}
 
Example 7
Project: alfresco-repository   File: HomeFolderProviderSynchronizerTest.java   View source code 6 votes vote down vote up
@Test
public void test20OverrideProvider() throws Exception
{
    NodeRef person = createUser("a/b/c", "fred");
    moveUserHomeFolders();
    assertHomeFolderLocation("fred", "fr/fred");
    
    homeFolderProviderSynchronizer.setOverrideHomeFolderProviderName(
            testHomeFolderProviderName);
    moveUserHomeFolders();

    assertHomeFolderLocation("fred", "a/b/c/fred");
    String providerName = (String) nodeService.getProperty(person,
            ContentModel.PROP_HOME_FOLDER_PROVIDER);
    assertEquals(testHomeFolderProviderName , providerName);
}
 
Example 8
Project: alfresco-repository   File: HomeFolderProviderSynchronizerTest.java   View source code 6 votes vote down vote up
private void deleteUser(final Set<NodeRef> adminGuestUserHomeFolders,
        NodeRef person, String username, String domainUsername)
{
    if (!domainUsername.equals("admin") && !domainUsername.equals("guest"))
    {
        personService.deletePerson(person);
        System.out.println("deleted user "+username);
    }
    else
    {
        NodeRef homeFolder = DefaultTypeConverter.INSTANCE.convert(
                NodeRef.class, nodeService.getProperty(person,
                ContentModel.PROP_HOMEFOLDER));
        adminGuestUserHomeFolders.add(homeFolder);
    }
}
 
Example 9
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 getWorkingCopy(NodeRef nodeRef)
{
    NodeRef workingCopy = null;
    if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_CHECKED_OUT))
    {
        List<AssociationRef> assocs = nodeService.getTargetAssocs(nodeRef, ContentModel.ASSOC_WORKING_COPY_LINK);
        // It is a 1:1 relationship
        if (assocs.size() == 0)
        {
            logger.warn("Found node with cm:checkedOut 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 from node: " + nodeRef);
        }
        else
        {
            workingCopy = assocs.get(0).getTargetRef();
        }
    }
    
    return workingCopy;
}
 
Example 10
Project: alfresco-repository   File: QuickShareServiceImpl.java   View source code 6 votes vote down vote up
private void removeSharedId(final String sharedId)
{
    TenantUtil.runAsDefaultTenant(new TenantRunAsWork<Void>()
    {
        public Void doWork() throws Exception
        {
            attributeService.removeAttribute(ATTR_KEY_SHAREDIDS_ROOT, sharedId);
            return null;
        }
    });

    try
    {
        // Remove scheduled expiry action if any
        NodeRef expiryActionNodeRef = getQuickShareLinkExpiryActionNode(sharedId);
        if (expiryActionNodeRef != null)
        {
            deleteQuickShareLinkExpiryAction(expiryActionNodeRef);
        }
    }
    catch (Exception ex)
    {
        throw new QuickShareLinkExpiryActionException("Couldn't delete the quick share link expiry action for the sharedId:" + sharedId);
    }
}
 
Example 11
Project: alfresco-remote-api   File: NodesImpl.java   View source code 6 votes vote down vote up
@Override
public NodeRef validateNode(StoreRef storeRef, String nodeId)
{
    String versionLabel = null;

    int idx = nodeId.indexOf(";");
    if (idx != -1)
    {
        versionLabel = nodeId.substring(idx + 1);
        nodeId = nodeId.substring(0, idx);
        if (versionLabel.equals("pwc"))
        {
            // TODO correct exception?
            throw new EntityNotFoundException(nodeId);
        }
    }

    NodeRef nodeRef = new NodeRef(storeRef, nodeId);
    return validateNode(nodeRef);
}
 
Example 12
Project: alfresco-repository   File: Reference.java   View source code 6 votes vote down vote up
/**
 * Quick Reference compliance check of a {@link NodeRef}.<br>
 * NodeRef Reference representations validated by this method should produce
 * valid Reference objects based on the given {@link NodeRef} when passed to
 * the {@link #fromNodeRef(NodeRef)} method.
 * 
 * @deprecated
 * @param nodeRef
 * @return <code>true</code> if the given {@link NodeRef} is a valid
 *         Reference representation<br>
 *         <code>false</code> otherwise
 */
public static final boolean isReference(NodeRef nodeRef)
{
    if (nodeRef != null)
    {
        String id = nodeRef.getId();
        if ((id != null) && (id.length() > 1) && (id.startsWith("" + VIRTUAL_TOKEN)))
        {
            char token = id.charAt(1);
            Encoding encoding = Encodings.fromToken(token);
            if (encoding != null)
            {
                return true;
            }
        }
        else
        {
            if (logger.isDebugEnabled())
            {
                logger.debug("NodeRef is not a reference.");
            }
        }
    }
    return false;
}
 
Example 13
Project: alfresco-repository   File: VirtualNodeServiceExtensionTest.java   View source code 6 votes vote down vote up
@Test
public void testCreateNode_noFilingRule() throws Exception
{
    NodeRef testTemplate2 = createVirtualizedFolder(testRootFolder.getNodeRef(),
                                                    "aVFTestTemplate2",
                                                    TEST_TEMPLATE_2_JSON_SYS_PATH);
    NodeRef testTemplate2Node2 = nodeService.getChildByName(testTemplate2,
                                                            ContentModel.ASSOC_CONTAINS,
                                                            "Node2");

    try
    {
        createContent(testTemplate2Node2,
                      "shouldNotBeCreated");
        fail("Should not be able to create node in a readonly context.");
    }
    catch (AccessDeniedException e)
    {
        logger.info("Succesfully denied creation in readonly",
                    e);
    }
}
 
Example 14
Project: alfresco-repository   File: LockOwnerDynamicAuthority.java   View source code 6 votes vote down vote up
public boolean hasAuthority(final NodeRef nodeRef, final String userName)
{
    return AuthenticationUtil.runAs(new RunAsWork<Boolean>(){

        public Boolean doWork() throws Exception
        {
            if (lockService.getLockStatus(nodeRef, userName) == LockStatus.LOCK_OWNER)
            {
                return true;
            }
            NodeRef original = checkOutCheckInService.getCheckedOut(nodeRef);
            if (original != null)
            {
                return (lockService.getLockStatus(original, userName) == LockStatus.LOCK_OWNER);
            }
            else
            {
                return false;
            }
        }}, AuthenticationUtil.getSystemUserName());
    
    
    
}
 
Example 15
Project: alfresco-repository   File: PermissionServiceImpl.java   View source code 6 votes vote down vote up
/**
 * Key for a cache object is built from all the known Authorities (which can change dynamically so they must all be
 * used) the NodeRef ID and the permission reference itself. This gives a unique key for each permission test.
 */
Serializable generateKey(Set<String> auths, NodeRef nodeRef, PermissionReference perm, CacheType type)
{
    LinkedHashSet<Serializable> key = new LinkedHashSet<Serializable>();
    key.add(perm.toString());
    // We will just have to key our dynamic sets by username. We wrap it so as not to be confused with a static set
    if (auths instanceof AuthorityServiceImpl.UserAuthoritySet)
    {
        key.add((Serializable)Collections.singleton(((AuthorityServiceImpl.UserAuthoritySet)auths).getUsername()));
    }
    else
    {
        key.addAll(auths);            
    }        
    key.add(nodeRef);
    // Ensure some concept of node version or transaction is included in the key so we can track without cache replication 
    NodeRef.Status nodeStatus = nodeService.getNodeStatus(nodeRef);
    key.add(nodeStatus == null ? "null" : nodeStatus.getChangeTxnId());
    key.add(type);
    return key;
}
 
Example 16
Project: alfresco-repository   File: ThumbnailServiceImplTest.java   View source code 6 votes vote down vote up
public void testJSAPI() throws Exception
{
    NodeRef jpgOrig = createOriginalContent(this.folder, MimetypeMap.MIMETYPE_IMAGE_JPEG);
    NodeRef gifOrig = createOriginalContent(this.folder, MimetypeMap.MIMETYPE_IMAGE_GIF);
    NodeRef pdfOrig = createOriginalContent(this.folder, MimetypeMap.MIMETYPE_PDF);
    NodeRef docOrig = createOriginalContent(this.folder, MimetypeMap.MIMETYPE_WORD);

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

    ScriptLocation location = new ClasspathScriptLocation("org/alfresco/repo/thumbnail/script/test_thumbnailAPI.js");
    this.scriptService.executeScript(location, model);
}
 
Example 17
Project: alfresco-repository   File: AbstractUsageDAOImpl.java   View source code 6 votes vote down vote up
public long getTotalDeltaSize(NodeRef nodeRef, boolean removeDeltas)
{
    long nodeId = getNodeIdNotNull(nodeRef);
    UsageDeltaEntity entity = selectTotalUsageDeltaSize(nodeId);
    Long totalSize = entity.getDeltaSize();
    // Remove the deltas, making sure that the correct number are removed
    if (removeDeltas)
    {
        int deleted = deleteUsageDeltaEntitiesByNodeId(nodeId);
        if (entity.getDeltaCount() != null && entity.getDeltaCount().intValue() != deleted)
        {
            throw new ConcurrencyFailureException(
                    "The number of usage deltas was " + entity.getDeltaCount() + " but only " + deleted + " were deleted.");
        }
    }
    return (totalSize != null ? totalSize : 0L);
}
 
Example 18
Project: alfresco-repository   File: UpdateAuditTemplatePatch.java   View source code 6 votes vote down vote up
@Override
protected String applyInternal() throws Exception
{
    StoreRef storeRef = importerBootstrap.getStoreRef();
    NodeRef rootNodeRef = nodeService.getRootNode(storeRef);
    List<NodeRef> results = searchService.selectNodes(rootNodeRef, copyPath, null, namespaceService, true);
    if (results.size() > 1)
    {
        throw new PatchException(ERR_MULTIPLE_FOUND, copyPath);
    }
    else if (results.size() == 1)
    {
        makeCopy(results.get(0));
        return I18NUtil.getMessage(MSG_CREATED);
    }
   
    
    return null;
}
 
Example 19
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 20
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 21
Project: alfresco-repository   File: FixedAclUpdaterTest.java   View source code 6 votes vote down vote up
@Override
public void setUp() throws Exception
{
    ctx = ApplicationContextHelper.getApplicationContext();
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    txnHelper = serviceRegistry.getTransactionService().getRetryingTransactionHelper();
    fileFolderService = serviceRegistry.getFileFolderService();
    repository = (Repository) ctx.getBean("repositoryHelper");
    fixedAclUpdater = (FixedAclUpdater) ctx.getBean("fixedAclUpdater");
    permissionsDaoComponent = (PermissionsDaoComponent) ctx.getBean("admPermissionsDaoComponent");
    permissionService = (PermissionService) ctx.getBean("permissionService");
    nodeDAO = (NodeDAO) ctx.getBean("nodeDAO");

    AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());

    NodeRef home = repository.getCompanyHome();
    // create a folder hierarchy for which will change permission inheritance
    int[] filesPerLevel = { 5, 5, 10 };
    RetryingTransactionCallback<NodeRef> cb = createFolderHierchyCallback(home, fileFolderService, "ROOT", filesPerLevel);
    folderNodeRef = txnHelper.doInTransaction(cb);

    // change setFixedAclMaxTransactionTime to lower value so setInheritParentPermissions on created folder hierarchy require async call
    setFixedAclMaxTransactionTime(permissionsDaoComponent, home, 50);

}
 
Example 22
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 23
Project: alfresco-remote-api   File: QueriesPeopleApiTest.java   View source code 5 votes vote down vote up
private void createTestUsers() throws IllegalArgumentException, SystemException, NotSupportedException, HeuristicRollbackException, HeuristicMixedException, RollbackException
{
    AuthenticationUtil.setFullyAuthenticatedUser(user1);
    for (String[] properties: userProperties)
    {
        int l = properties.length;
        if (l > 0)
        {
            PersonInfo personInfo = newPersonInfo(properties);
            String originalUsername = personInfo.getUsername();
            String id = createUser(personInfo, networkOne);
            Person person = new Person(
                           id,
                           null, // Not set to originalUsername, as the returned JSON does not set it
                           true, // enabled
                personInfo.getFirstName(),
                personInfo.getLastName(),
                personInfo.getCompany(),
                personInfo.getSkype(),
                personInfo.getLocation(),
                personInfo.getTel(),
                personInfo.getMob(),
                personInfo.getInstantmsg(),
                personInfo.getGoogle(),
                           null); // description
            testUsernames.add(originalUsername);
            testPersons.add(person);

            // The following call to personService.getPerson(id) returns a NodeRef like:
            //    workspace://SpacesStore/9db76769-96de-4de4-bdb4-a127130af362
            // We call tenantService.getName(nodeRef) to get a fully qualified NodeRef as Solr returns this.
            // They look like:
            //    workspace://@[email protected]/9db76769-96de-4de4-bdb4-a127130af362
            NodeRef nodeRef = personService.getPerson(id);
            nodeRef = tenantService.getName(nodeRef);
            testPersonNodeRefs.add(nodeRef);
        }
    }
}
 
Example 24
Project: alfresco-repository   File: RepoRemoteService.java   View source code 5 votes vote down vote up
public InputStream readFile(NodeRef base, String path) 
{
    NodeRef fileRef = lookup(base, path).getFirst();
    if (fileRef == null)
    {
        throw new AlfrescoRuntimeException("Not Found: " + path);
    }
    return fContentService.getReader(fileRef, ContentModel.PROP_CONTENT).getContentInputStream();
}
 
Example 25
Project: alfresco-repository   File: SubscriptionDAOTest.java   View source code 5 votes vote down vote up
protected void delete(final String userId, final NodeRef node) throws Exception
{
    RetryingTransactionCallback<Object> callback = new RetryingTransactionCallback<Object>()
    {
        public Object execute() throws Throwable
        {
            subscriptionsDAO.deleteSubscription(userId, node);
            return null;
        }
    };
    txnHelper.doInTransaction(callback, false, false);
}
 
Example 26
Project: alfresco-repository   File: AbstractManifestProcessorBase.java   View source code 5 votes vote down vote up
/**
 * Puts information about current <code>childRef</code> and its <code>parentRef</code> into log in TRACE level. Information includes 'name', 'fromRepositoryId', 'aliened' and
 * 'invadedBy' properties. Additionally, collects the same information for children of <code>childRef</code>
 * 
 * @param parentRef - {@link NodeRef} instance of child node
 * @param childRef - {@link NodeRef} instance of parent of the <code>childRef</code>
 * @param nodeService - {@link NodeService} instance to get properties and checking other states
 * @param log - {@link Log} instance to put log for appropriate class
 */
protected void logInvasionHierarchy(NodeRef parentRef, NodeRef childRef, NodeService nodeService, Log log)
{
    Map<QName, Serializable> properties = nodeService.getProperties(childRef);
    Map<QName, Serializable> parentProperties = nodeService.getProperties(parentRef);
    StringBuilder message = new StringBuilder("Information about '").append(properties.get(ContentModel.PROP_NAME)).append("' node:\n    fromRepositoryId: ").append(
            properties.get(TransferModel.PROP_FROM_REPOSITORY_ID)).append("\n").append("    invadedBy: ").append(properties.get(TransferModel.PROP_INVADED_BY)).append("\n")
            .append("    alien: ").append(nodeService.hasAspect(childRef, TransferModel.ASPECT_ALIEN)).append("\n").append("    repositoryId: ").append(
                    properties.get(TransferModel.PROP_REPOSITORY_ID)).append("\n").append("    parent: ").append(parentProperties.get(ContentModel.PROP_NAME)).append("(")
            .append(parentProperties.get(TransferModel.PROP_FROM_REPOSITORY_ID)).append(")").append(parentProperties.get(TransferModel.PROP_INVADED_BY)).append(": ").append(
                    nodeService.hasAspect(parentRef, TransferModel.ASPECT_ALIEN)).append("\n").append("    children:\n");

    List<ChildAssociationRef> childAssocs = nodeService.getChildAssocs(childRef);

    if ((null != childAssocs) && !childAssocs.isEmpty())
    {
        for (ChildAssociationRef child : childAssocs)
        {
            properties = nodeService.getProperties(child.getChildRef());
            message.append("        ").append(properties.get(ContentModel.PROP_NAME)).append("(").append(properties.get(TransferModel.PROP_FROM_REPOSITORY_ID)).append(")")
                    .append(properties.get(TransferModel.PROP_INVADED_BY)).append(": ").append(nodeService.hasAspect(child.getChildRef(), TransferModel.ASPECT_ALIEN)).append(
                            "\n");
        }
    }

    log.trace(message.toString());
}
 
Example 27
Project: alfresco-repository   File: ActivitiWorkflowServiceIntegrationTest.java   View source code 5 votes vote down vote up
/**
 * Test to validate fix for ALF-19822
 */
public void testMultiInstanceListenersCalled() throws Exception
{
    // start pooled review and approve workflow
    WorkflowDefinition workflowDef = deployDefinition(getParallelReviewDefinitionPath());
    assertNotNull(workflowDef);
    
    // Create workflow parameters
    Map<QName, Serializable> params = new HashMap<QName, Serializable>();
    Serializable wfPackage = workflowService.createPackage(null);
    params.put(WorkflowModel.ASSOC_PACKAGE, wfPackage);
    Date dueDate = new Date();
    params.put(WorkflowModel.PROP_WORKFLOW_DUE_DATE, dueDate);
    params.put(WorkflowModel.PROP_WORKFLOW_PRIORITY, 1);
    params.put(WorkflowModel.PROP_WORKFLOW_DESCRIPTION, "This is the description");
    NodeRef group = groupManager.get(GROUP);
    assertNotNull(group);
    
    List<NodeRef> assignees = Arrays.asList(personManager.get(USER2), personManager.get(USER3));
    params.put(WorkflowModel.ASSOC_ASSIGNEES, (Serializable) assignees);
    
    // Start a workflow instance
    WorkflowPath path = workflowService.startWorkflow(workflowDef.getId(), params);
    assertNotNull(path);
    assertTrue(path.isActive());
    String instnaceId = path.getInstance().getId();
    
    WorkflowTask startTask = workflowService.getStartTask(instnaceId);
    workflowService.endTask(startTask.getId(), null);
    
    personManager.setUser(USER2);
    List<WorkflowTask> tasks = workflowService.getAssignedTasks(USER2, WorkflowTaskState.IN_PROGRESS);
    assertEquals(1, tasks.size());

    //Assert task description
    assertEquals("Documents for review and approval", tasks.get(0).getDescription());

    //Assert workflow link name
    assertEquals("This is the description", tasks.get(0).getProperties().get(WorkflowModel.PROP_DESCRIPTION));
}
 
Example 28
Project: alfresco-repository   File: ActionConditionEvaluatorAbstractBase.java   View source code 5 votes vote down vote up
/**
 * @see org.alfresco.repo.action.evaluator.ActionConditionEvaluator#evaluate(org.alfresco.service.cmr.action.ActionCondition, org.alfresco.service.cmr.repository.NodeRef)
 */
public boolean evaluate(ActionCondition actionCondition, NodeRef actionedUponNodeRef)
{
    checkMandatoryProperties(actionCondition, getActionConditionDefintion());
    boolean result = evaluateImpl(actionCondition, actionedUponNodeRef);
    if (actionCondition.getInvertCondition() == true)
    {
        result = !result;
    }
    return result;
}
 
Example 29
Project: alfresco-repository   File: VersionableAspect.java   View source code 5 votes vote down vote up
/**
 * On content update policy behaviour
 * 
 * If applicable and "cm:autoVersion" is TRUE then version the node on content update (even if no property updates)
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public void onContentUpdate(NodeRef nodeRef, boolean newContent)
{
    if (this.nodeService.exists(nodeRef) == true && 
        this.nodeService.hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE) == true && 
        this.nodeService.hasAspect(nodeRef, ContentModel.ASPECT_TEMPORARY) == false)
    {
        Map<NodeRef, NodeRef> versionedNodeRefs = (Map)AlfrescoTransactionSupport.getResource(KEY_VERSIONED_NODEREFS);
        if (versionedNodeRefs == null || versionedNodeRefs.containsKey(nodeRef) == false)
        {
            // Determine whether the node is auto versionable (for content updates) or not
            boolean autoVersion = false;
            Boolean value = (Boolean)this.nodeService.getProperty(nodeRef, ContentModel.PROP_AUTO_VERSION);
            if (value != null)
            {
                // If the value is not null then 
                autoVersion = value.booleanValue();
            }
            // else this means that the default value has not been set and the versionable aspect was applied pre-1.1
            
            if (autoVersion == true)
            {
                // Create the auto-version
                Map<String, Serializable> versionProperties = new HashMap<String, Serializable>(1);
                versionProperties.put(Version.PROP_DESCRIPTION, I18NUtil.getMessage(MSG_AUTO_VERSION));
                versionProperties.put(VersionModel.PROP_VERSION_TYPE, VersionType.MINOR);
                
                createVersionImpl(nodeRef, versionProperties);
            }
        }
    }
}
 
Example 30
Project: alfresco-repository   File: AssocTargetTypeIntegrityEvent.java   View source code 5 votes vote down vote up
public AssocTargetTypeIntegrityEvent(
        NodeService nodeService,
        DictionaryService dictionaryService,
        NodeRef targetNodeRef,
        QName assocTypeQName)
{
    super(nodeService, dictionaryService, targetNodeRef, assocTypeQName, null);
}
 
Example 31
Project: alfresco-repository   File: FileFolderServiceImpl.java   View source code 5 votes vote down vote up
@Override
public ContentReader getReader(NodeRef nodeRef)
{
    FileInfo fileInfo = toFileInfo(nodeRef, false);
    if (fileInfo.isFolder())
    {
        throw new InvalidTypeException("Unable to get a content reader for a folder: " + fileInfo);
    }
    return contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
}
 
Example 32
Project: alfresco-repository   File: StandardRenditionLocationResolverTest.java   View source code 5 votes vote down vote up
private NodeRef makeNode(NodeRef parent, QName nodeType)
{
    String uuid = GUID.generate();
    Map<QName, Serializable> props = new HashMap<QName, Serializable>();
    props.put(ContentModel.PROP_NAME, uuid);
    ChildAssociationRef assoc = nodeService.createNode(parent, ContentModel.ASSOC_CONTAINS, QName.createQName(
                NamespaceService.CONTENT_MODEL_1_0_URI, uuid), nodeType, props);
    return assoc.getChildRef();
}
 
Example 33
Project: alfresco-repository   File: RuleServiceCoverageTest.java   View source code 5 votes vote down vote up
public void testCheckThatModifyNameDoesNotTriggerOutboundRule() throws Exception
{
    Map<QName, Serializable> folderProps = new HashMap<QName, Serializable>(1);
    folderProps.put(ContentModel.PROP_NAME, "myTestFolder");
    NodeRef folder = this.nodeService.createNode(
            this.rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            ContentModel.ASSOC_CHILDREN,
            ContentModel.TYPE_FOLDER,
            folderProps).getChildRef();  
    
    Map<String, Serializable> params = new HashMap<String, Serializable>(1);
    params.put(AddFeaturesActionExecuter.PARAM_ASPECT_NAME, ContentModel.ASPECT_VERSIONABLE);        
    
    Rule rule = createRule(
            RuleType.OUTBOUND,
            AddFeaturesActionExecuter.NAME, 
            params, 
            NoConditionEvaluator.NAME, 
            null);
    
    this.ruleService.saveRule(folder, rule);

    Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>(1);
    contentProps.put(ContentModel.PROP_NAME, "myTestDocument.txt");
    NodeRef newNodeRef = fileFolderService.create(folder, "abc.txt", ContentModel.TYPE_CONTENT).getNodeRef();         
    assertFalse("Should not be versionable", nodeService.hasAspect(newNodeRef, ContentModel.ASPECT_VERSIONABLE));
    
    // Use the file folder to change the name of the node
    fileFolderService.rename(newNodeRef, "myNewName.txt");
    assertFalse("Should not be versionable", nodeService.hasAspect(newNodeRef, ContentModel.ASPECT_VERSIONABLE));
}
 
Example 34
Project: alfresco-repository   File: AssocSourceMultiplicityIntegrityEvent.java   View source code 5 votes vote down vote up
public AssocSourceMultiplicityIntegrityEvent(
        NodeService nodeService,
        DictionaryService dictionaryService,
        NodeRef targetNodeRef,
        QName assocTypeQName,
        boolean isDelete)
{
    super(nodeService, dictionaryService, targetNodeRef, assocTypeQName, null);
    this.isDelete = isDelete;
}
 
Example 35
Project: alfresco-repository   File: EmptyTranslationAspect.java   View source code 5 votes vote down vote up
/** 
  * If a content is added to a <b>cm:mlEmptyTranslation</b>, remove this aspect. 
  */
public void onContentUpdate(NodeRef nodeRef, boolean newContent) 
{
    if (newContent)
    {
        nodeService.removeAspect(nodeRef, ContentModel.ASPECT_MULTILINGUAL_EMPTY_TRANSLATION);
        nodeService.removeAspect(nodeRef, ContentModel.ASPECT_TEMPORARY);
    }
}
 
Example 36
Project: alfresco-repository   File: ActionServiceImpl.java   View source code 5 votes vote down vote up
/**
 * @see org.alfresco.repo.action.RuntimeActionService#directActionExecution(org.alfresco.service.cmr.action.Action,
 *      org.alfresco.service.cmr.repository.NodeRef)
 */
public void directActionExecution(Action action, NodeRef actionedUponNodeRef)
{
    // Debug output
    if (logger.isDebugEnabled())
    {
        logger.debug("The action is being executed as the user: "
                     + this.authenticationContext.getCurrentUserName());
    }

    // Get the action executer and execute
    ActionExecuter executer = (ActionExecuter) this.applicationContext.getBean(action.getActionDefinitionName());
    executer.execute(action, actionedUponNodeRef);
}
 
Example 37
Project: alfresco-user-space-template   File: UserHomeFromTemplate.java   View source code 5 votes vote down vote up
public void onCreateNode(ChildAssociationRef childAssocRef) {

		AlfrescoTransactionSupport.bindListener(transactionListener);

		NodeRef userNodeRef = childAssocRef.getChildRef();

		List<NodeRef> currentRelatedUsers = AlfrescoTransactionSupport.getResource(KEY_RELATED_USERS);
		if (currentRelatedUsers == null) {
			currentRelatedUsers = new ArrayList<NodeRef>();
		}
		currentRelatedUsers.add(userNodeRef);
		AlfrescoTransactionSupport.bindResource(KEY_RELATED_USERS, currentRelatedUsers);

	}
 
Example 38
Project: alfresco-repository   File: FileFolderServiceImplTest.java   View source code 5 votes vote down vote up
public void testRenameDiscussionALF5569() throws Exception
{
    FileInfo fileInfo = getByName(NAME_L0_FILE_A, false);
    assertNotNull(fileInfo);
    
    // create a discussion for the file, this happens in a behaviour
    // when adding the discussable aspect
    nodeService.addAspect(fileInfo.getNodeRef(), ForumModel.ASPECT_DISCUSSABLE, null);
    List<ChildAssociationRef> destChildren = nodeService.getChildAssocs(
          fileInfo.getNodeRef(),
          ForumModel.ASSOC_DISCUSSION,
          RegexQNamePattern.MATCH_ALL);
    assertEquals(1, destChildren.size());
    
    // get the first child
    NodeRef discussionNodeRef = destChildren.get(0).getChildRef();
    
    // check the current name
    String currentName = (String)nodeService.getProperty(discussionNodeRef, ContentModel.PROP_NAME);
    assertFalse(NAME_DISCUSSION_FOLDER.equals(currentName));
    
    // rename the discussion node
    FileInfo newFileInfo = fileFolderService.rename(discussionNodeRef, NAME_DISCUSSION_FOLDER);
    
    // get the name now
    String newName = (String)nodeService.getProperty(newFileInfo.getNodeRef(), ContentModel.PROP_NAME);
    assertEquals(NAME_DISCUSSION_FOLDER, newName);
}
 
Example 39
Project: alfresco-repository   File: AuthenticatedTimerJobHandler.java   View source code 5 votes vote down vote up
protected String getInitiator(ActivitiScriptNode initiatorNode)
{
    if(initiatorNode != null) 
    {
        NodeRef ref = initiatorNode.getNodeRef();
        if(unprotectedNodeService.exists(ref))
        {
            return (String) unprotectedNodeService.getProperty(ref, ContentModel.PROP_USERNAME);
        }
    }
    return null;
}
 
Example 40
Project: alfresco-repository   File: ImporterActionExecuterTest.java   View source code 5 votes vote down vote up
private Action createAction(NodeRef nodeRef, String actionDefinitionName, NodeRef targetNodeRef)
{
    Action action = new ActionImpl(nodeRef, GUID.generate(), actionDefinitionName);
    action.setParameterValue(ImporterActionExecuter.PARAM_DESTINATION_FOLDER, targetNodeRef);
    action.setParameterValue(ImporterActionExecuter.PARAM_ENCODING, "UTF-8");

    return action;
}