Java Code Examples for org.alfresco.service.cmr.repository.NodeRef#equals()

The following examples show how to use org.alfresco.service.cmr.repository.NodeRef#equals() . 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: RepoTransferReceiverImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * When an alien node is moved it may un-invade its old location and invade a new
 * location.   The node may also cease to be alien.
 */
public void onMoveNode(ChildAssociationRef oldChildAssocRef,
        ChildAssociationRef newChildAssocRef)
{

    log.debug("onMoveNode");
    log.debug("oldChildAssocRef:" + oldChildAssocRef);
    log.debug("newChildAssocRef:" + newChildAssocRef);

    NodeRef oldParentRef = oldChildAssocRef.getParentRef();
    NodeRef newParentRef = newChildAssocRef.getParentRef();

    if(newParentRef.equals(oldParentRef))
    {
        log.debug("old parent and new parent are the same - this is a rename, do nothing");
    }
    else
    {
        if(log.isDebugEnabled())
        {
            log.debug("moving node from oldParentRef:" + oldParentRef +" to:" + newParentRef);
        }
        alienProcessor.beforeDeleteAlien(newChildAssocRef.getChildRef(), oldChildAssocRef);
        alienProcessor.afterMoveAlien(newChildAssocRef);
    }
}
 
Example 2
Source File: CMISResultSet.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private boolean allNodeRefsEqual(Map<String, NodeRef> selected)
{
    NodeRef last = null;
    for (NodeRef current : selected.values())
    {
        if (last == null)
        {
            last = current;
        } else
        {
            if (!last.equals(current))
            {
                return false;
            }
        }
    }
    return true;
}
 
Example 3
Source File: CommentsImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
  public void deleteComment(String nodeId, String commentNodeId)
  {
  	try
  	{
          NodeRef nodeRef = nodes.validateNode(nodeId);
       NodeRef commentNodeRef = nodes.validateNode(commentNodeId);
          
          if (! nodeRef.equals(commentService.getDiscussableAncestor(commentNodeRef)))
          {
              throw new InvalidArgumentException("Unexpected "+nodeId+","+commentNodeId);
          }
          
          commentService.deleteComment(commentNodeRef);
}
catch(IllegalArgumentException e)
{
	throw new ConstraintViolatedException(e.getMessage());
}
  }
 
Example 4
Source File: VirtualNodeServiceExtensionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private ChildAssociationRef findActualAssocPeer(ChildAssociationRef virtualAssoc, NodeRef actualParentNodeRef)
{
    List<ChildAssociationRef> actualAssocs = nodeService.getChildAssocs(actualParentNodeRef);
    NodeRef virtualChildNodeRef = virtualAssoc.getChildRef();
    Reference vChildNodeRef = Reference.fromNodeRef(virtualChildNodeRef);
    assertNotNull(vChildNodeRef);
    NodeRef materialNodeRef = smartStore.materialize(vChildNodeRef);

    for (ChildAssociationRef actualAssocRef : actualAssocs)
    {
        if (materialNodeRef.equals(actualAssocRef.getChildRef()))
        {
            if (virtualAssoc.getQName().getLocalName().equals(actualAssocRef.getQName().getLocalName())
                        && virtualAssoc.getTypeQName().equals(actualAssocRef.getTypeQName()))
            {
                return actualAssocRef;
            }
        }
    }

    return null;
}
 
Example 5
Source File: ContentUsageImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private boolean alreadyDeleted(NodeRef nodeRef)
{
    Set<NodeRef> deletedNodes = (Set<NodeRef>)AlfrescoTransactionSupport.getResource(KEY_DELETED_NODES);
    if (deletedNodes != null)
    {
        for (NodeRef deletedNodeRef : deletedNodes)
        {
            if (deletedNodeRef.equals(nodeRef))
            {
                if (logger.isDebugEnabled()) logger.debug("alreadyDeleted: nodeRef="+nodeRef);
                return true;
            }
        }
    }
    return false;
}
 
Example 6
Source File: AbstractRenderingEngine.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * This method manages the <code>rn:rendition</code> aspects on the rendition node. It applies the
 * correct rendition aspect based on the rendition node's location and removes any out-of-date rendition
 * aspect.
 */
private void manageRenditionAspects(NodeRef sourceNode, ChildAssociationRef renditionParentAssoc)
{
    NodeRef renditionNode = renditionParentAssoc.getChildRef();
    NodeRef primaryParent = renditionParentAssoc.getParentRef();

    // If the rendition is located directly underneath its own source node
    if (primaryParent.equals(sourceNode))
    {
        // It should be a 'hidden' rendition.
        // Ensure we do not update the 'modifier' due to rendition addition
        behaviourFilter.disableBehaviour(renditionNode, ContentModel.ASPECT_AUDITABLE);
        try
        {
            nodeService.addAspect(renditionNode, RenditionModel.ASPECT_HIDDEN_RENDITION, null);
            nodeService.removeAspect(renditionNode, RenditionModel.ASPECT_VISIBLE_RENDITION);
        }
        finally
        {
            behaviourFilter.enableBehaviour(renditionNode, ContentModel.ASPECT_AUDITABLE);
        }
        // We remove the other aspect to cover the potential case where a
        // rendition
        // has been updated in a different location.
    } else
    {
        // Renditions stored underneath any node other than their source are
        // 'visible'.
        behaviourFilter.disableBehaviour(renditionNode, ContentModel.ASPECT_AUDITABLE);
        try
        {
            nodeService.addAspect(renditionNode, RenditionModel.ASPECT_VISIBLE_RENDITION, null);
            nodeService.removeAspect(renditionNode, RenditionModel.ASPECT_HIDDEN_RENDITION);
        }
        finally
        {
            behaviourFilter.enableBehaviour(renditionNode, ContentModel.ASPECT_AUDITABLE);
        }
    }
}
 
Example 7
Source File: AbstractNodeImporter.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected final void importImportableItemMetadata(NodeRef nodeRef, Path parentFile, MetadataLoader.Metadata metadata)
{
    // Attach aspects
    if (metadata.getAspects() != null)
    {
        for (final QName aspect : metadata.getAspects())
        {
            if (logger.isDebugEnabled()) logger.debug("Attaching aspect '" + aspect.toString() + "' to node '" + nodeRef.toString() + "'.");

            nodeService.addAspect(nodeRef, aspect, null);  // Note: we set the aspect's properties separately, hence null for the third parameter
        }
    }

    // Set property values for both the type and any aspect(s)
    if (metadata.getProperties() != null)
    {
        if (logger.isDebugEnabled()) logger.debug("Adding properties to node '" + nodeRef.toString() + "':\n" + mapToString(metadata.getProperties()));

        try
        {
            nodeService.addProperties(nodeRef, metadata.getProperties());
        }
        catch (final InvalidNodeRefException inre)
        {
            if (!nodeRef.equals(inre.getNodeRef()))
            {
                // Caused by an invalid NodeRef in the metadata (e.g. in an association)
                throw new IllegalStateException("Invalid nodeRef found in metadata for '" + getFileName(parentFile) + "'.  " +
                        "Probable cause: an association is being populated via metadata, but the " +
                        "NodeRef for the target of that association ('" + inre.getNodeRef() + "') is invalid.  " +
                        "Please double check your metadata file and try again.", inre);
            }
            else
            {
                // Logic bug in the BFSIT.  :-(
                throw inre;
            }
        }
    }
}
 
Example 8
Source File: WebDAVHelper.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Return the relative path for the node walking back to the specified root node
 * 
 * @param rootNodeRef the root below which the path will be valid
 * @param nodeRef the node's path to get
 * @return Returns string of form <b>/A/B/C</b> where C represents the from node and 
 */
public final String getPathFromNode(NodeRef rootNodeRef, NodeRef nodeRef) throws FileNotFoundException
{
    // Check if the nodes are valid, or equal
    if (rootNodeRef == null || nodeRef == null)
        throw new IllegalArgumentException("Invalid node(s) in getPathFromNode call");
    
    // short cut if the path node is the root node
    if (rootNodeRef.equals(nodeRef))
        return "";
    
    FileFolderService fileFolderService = getFileFolderService();
    
    // get the path elements
    List<String> pathInfos = fileFolderService.getNameOnlyPath(rootNodeRef, nodeRef);
    
    // build the path string
    StringBuilder sb = new StringBuilder(pathInfos.size() * 20);
    for (String fileInfo : pathInfos)
    {
        sb.append(WebDAVHelper.PathSeperatorChar);
        sb.append(fileInfo);
    }
    // done
    if (logger.isDebugEnabled())
    {
        logger.debug("Build name path for node: \n" +
                "   root: " + rootNodeRef + "\n" +
                "   target: " + nodeRef + "\n" +
                "   path: " + sb);
    }
    return sb.toString();
}
 
Example 9
Source File: ViewXMLExporter.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Helper to convert a path into an indexed path which uniquely identifies a node
 * 
 * @param nodeRef NodeRef
 * @param path Path
 * @return Path
 */
private Path createIndexedPath(NodeRef nodeRef, Path path)
{
    // Add indexes for same name siblings
    // TODO: Look at more efficient approach
    for (int i = path.size() - 1; i >= 0; i--)
    {
        Path.Element pathElement = path.get(i);
        if (i > 0 && pathElement instanceof Path.ChildAssocElement)
        {
            int index = 1;  // for xpath index compatibility
            String searchPath = path.subPath(i).toPrefixString(namespaceService);
            List<NodeRef> siblings = searchService.selectNodes(nodeRef, searchPath, null, namespaceService, false);
            if (siblings.size() > 1)
            {
                ChildAssociationRef childAssoc = ((Path.ChildAssocElement)pathElement).getRef();
                NodeRef childRef = childAssoc.getChildRef();
                for (NodeRef sibling : siblings)
                {
                    if (sibling.equals(childRef))
                    {
                        childAssoc.setNthSibling(index);
                        break;
                    }
                    index++;
                }
            }
        }
    }
    
    return path;
}
 
Example 10
Source File: RuleServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void setRulePosition(NodeRef nodeRef, NodeRef ruleNodeRef, int index)
{
    NodeRef ruleFolder = getSavedRuleFolderRef(nodeRef);
    if (ruleFolder != null)
    {
        List<ChildAssociationRef> assocs = this.runtimeNodeService.getChildAssocs(ruleFolder, RegexQNamePattern.MATCH_ALL, ASSOC_NAME_RULES_REGEX);
        List<ChildAssociationRef> orderedAssocs = new ArrayList<ChildAssociationRef>(assocs.size());
        ChildAssociationRef movedAssoc = null;
        for (ChildAssociationRef assoc : assocs)
        {
            NodeRef childNodeRef = assoc.getChildRef();
            if (childNodeRef.equals(ruleNodeRef) == true)
            {
                movedAssoc = assoc;
            }
            else
            {
                orderedAssocs.add(assoc);
            }
        }          
        if (movedAssoc != null)
        {
            orderedAssocs.add(index, movedAssoc);
        }
        
        index = 0;
        for (ChildAssociationRef orderedAssoc : orderedAssocs)
        {
            nodeService.setChildAssociationIndex(orderedAssoc, index);
            index++;
        }
    }
}
 
Example 11
Source File: AuthorityDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private NodeRef getAuthorityOrNull(final String name, final AuthorityType authType)
{
    try
    {
        switch (authType)
        {
            case USER:
                return personService.getPerson(name, false);
            case GUEST:
            case ADMIN:
            case EVERYONE:
            case OWNER:
                return null;
            default:
            {
                Pair<String, String> cacheKey = cacheKey(name);
                NodeRef result = authorityLookupCache.get(cacheKey);
                if (result == null)
                {
                    List<ChildAssociationRef> results = nodeService.getChildAssocs(getAuthorityContainer(), ContentModel.ASSOC_CHILDREN,
                                QName.createQName("cm", name, namespacePrefixResolver), false);
                    result = results.isEmpty() ? NULL_NODEREF : results.get(0).getChildRef();
                    authorityLookupCache.put(cacheKey, result);
                }
                return result.equals(NULL_NODEREF) ? null : result;
            }
        }
    }
    catch (NoSuchPersonException e)
    {
        return null;
    }
}
 
Example 12
Source File: ExporterComponent.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Determine if specified Node Reference is within the set of nodes to be exported
 * 
 * @param nodeRef  node reference to check
 * @return  true => node reference is within export set
 */
private boolean isWithinExport(NodeRef nodeRef, ExporterCrawlerParameters parameters)
{
    boolean isWithin = false;

    try
    {
        // Current strategy is to determine if node is a child of the root exported node
        for (NodeRef exportRoot : context.getExportList())
        {
            if (nodeRef.equals(exportRoot) && parameters.isCrawlSelf() == true)
            {
                // node to export is the root export node (and root is to be exported)
                isWithin = true;
            }
            else
            {
                // locate export root in primary parent path of node
                Path nodePath = nodeService.getPath(nodeRef);
                for (int i = nodePath.size() - 1; i >= 0; i--)
                {
                    Path.ChildAssocElement pathElement = (Path.ChildAssocElement) nodePath.get(i);
                    if (pathElement.getRef().getChildRef().equals(exportRoot))
                    {
                        isWithin = true;
                        break;
                    }
                }
            }
        }
    }
    catch (AccessDeniedException accessErr)
    {
        // use default if this occurs
    }
    catch (InvalidNodeRefException nodeErr)
    {
        // use default if this occurs
    }

    return isWithin;
}
 
Example 13
Source File: BatchImporterImpl.java    From alfresco-bulk-import with Apache License 2.0 4 votes vote down vote up
private final void importVersionMetadata(final NodeRef               nodeRef,
                                         final BulkImportItemVersion version,
                                         final boolean               dryRun)
    throws InterruptedException
{
    String                    type     = version.getType();
    Set<String>               aspects  = version.getAspects();
    Map<String, Serializable> metadata = version.getMetadata();
    
    if (type != null)
    {
        if (dryRun)
        {
            if (info(log)) info(log, "[DRY RUN] Would have set type of '" + String.valueOf(nodeRef) + "' to '" + String.valueOf(type) + "'.");
        }
        else
        {
            if (trace(log)) trace(log, "Setting type of '" + String.valueOf(nodeRef) + "' to '" + String.valueOf(type) + "'.");
            nodeService.setType(nodeRef, createQName(serviceRegistry, type));
        }
    }
    
    if (aspects != null)
    {
        for (final String aspect : aspects)
        {
            if (importStatus.isStopping() || Thread.currentThread().isInterrupted()) throw new InterruptedException(Thread.currentThread().getName() + " was interrupted. Terminating early.");

            if (dryRun)
            {
                if (info(log)) info(log, "[DRY RUN] Would have added aspect '" + aspect + "' to '" + String.valueOf(nodeRef) + "'.");
            }
            else
            {
                if (trace(log)) trace(log, "Adding aspect '" + aspect + "' to '" + String.valueOf(nodeRef) + "'.");
                nodeService.addAspect(nodeRef, createQName(serviceRegistry, aspect), null);
            }
        }
    }
    
    if (version.hasMetadata())
    {
        if (metadata == null) throw new IllegalStateException("The import source has logic errors - it says it has metadata, but the metadata is null.");

        
        // QName all the keys.  It's baffling that NodeService doesn't have a method that accepts a Map<String, Serializable>, when things like VersionService do...
        Map<QName, Serializable> qNamedMetadata = new HashMap<>(metadata.size());
        
        for (final String key : metadata.keySet())
        {
            if (importStatus.isStopping() || Thread.currentThread().isInterrupted()) throw new InterruptedException(Thread.currentThread().getName() + " was interrupted. Terminating early.");
            
            QName        keyQName = createQName(serviceRegistry, key);
            Serializable value    = metadata.get(key);
            
            qNamedMetadata.put(keyQName, value);
        }

        if (dryRun)
        {
            if (info(log)) info(log, "[DRY RUN] Would have added the following properties to '" + String.valueOf(nodeRef) +
                                     "':\n" + Arrays.toString(qNamedMetadata.entrySet().toArray()));
        }
        else
        {
            try
            {
                if (trace(log)) trace(log, "Adding the following properties to '" + String.valueOf(nodeRef) +
                                           "':\n" + Arrays.toString(qNamedMetadata.entrySet().toArray()));
                nodeService.addProperties(nodeRef, qNamedMetadata);
            }
            catch (final InvalidNodeRefException inre)
            {
                if (!nodeRef.equals(inre.getNodeRef()))
                {
                    // Caused by an invalid NodeRef in the metadata (e.g. in an association)
                    throw new IllegalStateException("Invalid nodeRef found in metadata file '" + version.getMetadataSource() + "'.  " +
                                                    "Probable cause: an association is being populated via metadata, but the " +
                                                    "NodeRef for the target of that association ('" + inre.getNodeRef() + "') is invalid.  " +
                                                    "Please double check your metadata file and try again.", inre);
                }
                else
                {
                    // Logic bug in the BFSIT.  :-(
                    throw inre;
                }
            }
        }
    }
}
 
Example 14
Source File: AbstractBaseCopyService.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Calculates {@link QName} type of target association, which will be created after copying
 * 
 * @param sourceNodeRef             the node that will be copied (never <tt>null</tt>)
 * @param sourceParentRef           the parent of the node being copied (may be <tt>null</tt>)
 * @param newName                   the planned new name of the node
 * @param nameChanged               <tt>true</tt> if the name of the node is being changed
 * @return                          Returns the path part for a new association and the effective
 *                                  primary parent association that was used
 */
protected AssociationCopyInfo getAssociationCopyInfo(
        NodeService nodeService,
        NodeRef sourceNodeRef,
        NodeRef sourceParentRef,
        String newName, boolean nameChanged)
{
    // we need the current association type
    ChildAssociationRef primaryAssocRef = nodeService.getPrimaryParent(sourceNodeRef);

    // Attempt to find a template association reference for the new association
    ChildAssociationRef sourceParentAssocRef = primaryAssocRef;
    if (sourceParentRef != null)
    {
        // We have been given a source parent node
        boolean copyingFromPrimaryParent = sourceParentRef.equals(primaryAssocRef.getParentRef());
        if (!copyingFromPrimaryParent)
        {
            // We are not copying from the primary parent.
            // Find a random association to the source parent to use as a template
            List<ChildAssociationRef> assocList = nodeService.getParentAssocs(sourceNodeRef);
            for (ChildAssociationRef assocListEntry : assocList)
            {
                if (sourceParentRef.equals(assocListEntry.getParentRef()))
                {
                    sourceParentAssocRef = assocListEntry;
                    break;
                }
            }
        }
    }

    QName targetAssocQName = null;
    QName existingQName = sourceParentAssocRef.getQName();
    if (nameChanged && !systemNamespaces.contains(existingQName.getNamespaceURI()))
    {
        // Change the localname to match the new name
        targetAssocQName = QName.createQName(sourceParentAssocRef.getQName().getNamespaceURI(), QName.createValidLocalName(newName));
    }
    else
    {
        // Keep the localname
        targetAssocQName = existingQName;
    }

    return new AssociationCopyInfo(targetAssocQName, sourceParentAssocRef);
}
 
Example 15
Source File: RuleServiceCoverageTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Test:
 *          rule type:  inbound
 *          condition:  no-condition()
 *          action:     checkout()
 */
public void testCheckOutAction()
{
    Rule rule = createRule(
    		RuleType.INBOUND, 
    		CheckOutActionExecuter.NAME, 
    		null, 
    		NoConditionEvaluator.NAME, 
    		null);
    
    this.ruleService.saveRule(this.nodeRef, rule);
     
    NodeRef newNodeRef = null;
    UserTransaction tx = this.transactionService.getUserTransaction();
    try
    {
    	tx.begin();     
    	
     // Create a new node
     newNodeRef = this.nodeService.createNode(
             this.nodeRef,
                ContentModel.ASSOC_CHILDREN,                
             QName.createQName(TEST_NAMESPACE, "checkout"),
             ContentModel.TYPE_CONTENT,
             getContentProperties()).getChildRef();
     addContentToNode(newNodeRef);
     
     tx.commit();
    }
    catch (Exception exception)
    {
    	throw new RuntimeException(exception);
    }
    
    //System.out.println(NodeStoreInspector.dumpNodeStore(this.nodeService, this.testStoreRef));
    
    // Check that the new node has been checked out
    List<ChildAssociationRef> children = this.nodeService.getChildAssocs(this.nodeRef);
    assertNotNull(children);
    assertEquals(3, children.size()); // includes rule folder
    for (ChildAssociationRef child : children)
    {
        NodeRef childNodeRef = child.getChildRef();
        if (childNodeRef.equals(newNodeRef) == true)
        {
            // check that the node has been locked
            LockStatus lockStatus = this.lockService.getLockStatus(childNodeRef);
            assertEquals(LockStatus.LOCK_OWNER, lockStatus);
        }
        else if (this.nodeService.hasAspect(childNodeRef, ContentModel.ASPECT_WORKING_COPY) == true)
        {
            // assert that it is the working copy that relates to the origional node
            NodeRef copiedFromNodeRef = copyService.getOriginal(childNodeRef);
            assertEquals(newNodeRef, copiedFromNodeRef);
        }
    }
}
 
Example 16
Source File: MultilingualContentServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * @inheritDoc
 */
public void moveTranslationContainer(NodeRef mlContainerNodeRef, NodeRef newParentRef) throws FileExistsException, FileNotFoundException
{
    if(!ContentModel.TYPE_MULTILINGUAL_CONTAINER.equals(nodeService.getType(mlContainerNodeRef)))
    {
        throw new IllegalArgumentException(
                "Node type must be " + ContentModel.TYPE_MULTILINGUAL_CONTAINER);
    }

    // if the container has no translation: nothing to do
    if(nodeService.getChildAssocs(mlContainerNodeRef, ContentModel.ASSOC_MULTILINGUAL_CHILD, RegexQNamePattern.MATCH_ALL).size() < 1)
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("MLContainer has no translation " + mlContainerNodeRef);
        }

        return;
    }

    // keep a reference to the containing space before moving
    NodeRef spaceBefore = nodeService.getPrimaryParent(getPivotTranslation(mlContainerNodeRef)).getParentRef();

    if(spaceBefore.equals(newParentRef))
    {
        // nothing to do
        return;
    }

    // move each translation
    for(NodeRef translationToMove : getTranslations(mlContainerNodeRef).values())
    {
        fileFolderService.move(translationToMove, newParentRef, null);
    }

    if (logger.isDebugEnabled())
    {
        logger.debug("MLContainer moved: \n" +
                "   Old location of " + mlContainerNodeRef + " : " + spaceBefore + ") \n" +
                "   New location of " + mlContainerNodeRef + " : " + newParentRef + ")");
    }
}
 
Example 17
Source File: FileFolderServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Get the file or folder information from the root down to and including the node provided.
 * <ul>
 *   <li>The root node can be of any type and is not included in the path list.</li>
 *   <li>Only the primary path is considered.  If the target node is not a descendant of the
 *       root along purely primary associations, then an exception is generated.</li>
 *   <li>If an invalid type is encountered along the path, then an exception is generated.</li>
 * </ul>
 * 
 * @param rootNodeRef the start of the returned path, or null if the <b>store</b> root
 *        node must be assumed.
 * @param nodeRef a reference to the file or folder
 * @return Returns a list of file/folder infos from the root (excluded) down to and
 *         including the destination file or folder
 * @throws FileNotFoundException if the node could not be found
 */
@Override
public List<FileInfo> getNamePath(NodeRef rootNodeRef, NodeRef nodeRef) throws FileNotFoundException
{
    // check the root
    if (rootNodeRef == null)
    {
        rootNodeRef = nodeService.getRootNode(nodeRef.getStoreRef());
    }
    try
    {
        ArrayList<FileInfo> results = new ArrayList<FileInfo>(10);
        // get the primary path
        Path path = nodeService.getPath(nodeRef);
        // iterate and turn the results into file info objects
        boolean foundRoot = false;
        for (Path.Element element : path)
        {
            // ignore everything down to the root
            Path.ChildAssocElement assocElement = (Path.ChildAssocElement) element;
            final NodeRef childNodeRef = assocElement.getRef().getChildRef();
            if (childNodeRef.equals(rootNodeRef))
            {
                // just found the root - but we don't put in an entry for it
                foundRoot = true;
                continue;
            }
            else if (!foundRoot)
            {
                // keep looking for the root
                continue;
            }
            // we found the root and expect to be building the path up
            // Run as system as the user could not have access to all folders in the path, see ALF-13816
            FileInfo pathInfo = AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<FileInfo>()
            {
                public FileInfo doWork() throws Exception
                {
                    return toFileInfo(childNodeRef, true);
                }
            }, AuthenticationUtil.getSystemUserName());
            
            // we can't append a path element to the results if there is already a (non-folder) file at the tail
            // since this would result in a path anomoly - file's cannot contain other files.
            if (!results.isEmpty() && !results.get(results.size()-1).isFolder())
            {
                throw new InvalidTypeException(
                            "File is not the last element in path: files cannot contain other files.");
            }
            results.add(pathInfo);
        }
        // check that we found the root
        if (!foundRoot)
        {
            throw new FileNotFoundException(nodeRef);
        }
        // done
        if (logger.isDebugEnabled())
        {
            logger.debug("Built name path for node: \n" +
                    "   root: " + rootNodeRef + "\n" +
                    "   node: " + nodeRef + "\n" +
                    "   path: " + results);
        }
        return results;
    }
    catch (InvalidNodeRefException e)
    {
        throw new FileNotFoundException(nodeRef);
    }
}
 
Example 18
Source File: ImporterComponent.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Link an existing Node
 * 
 * @param context  node to link in
 * @return  node reference of child linked in
 */
private NodeRef linkNode(ImportNode context)
{
    ImportParent parentContext = context.getParentContext();
    NodeRef parentRef = parentContext.getParentRef();
    
    // determine the node reference to link to
    String uuid = context.getUUID();
    if (uuid == null || uuid.length() == 0)
    {
        throw new ImporterException("Node reference does not specify a reference to follow.");
    }
    NodeRef referencedRef = new NodeRef(rootRef.getStoreRef(), uuid);

    // Note: do not link references that are defined in the root of the import
    if (!parentRef.equals(getRootRef()))
    {
        // determine child assoc type
        QName assocType = getAssocType(context);
        AssociationDefinition assocDef = dictionaryService.getAssociation(assocType);
        if (assocDef.isChild())
        {
            // determine child name
            QName childQName = getChildName(context);
            if (childQName == null)
            {
                String name = (String)nodeService.getProperty(referencedRef, ContentModel.PROP_NAME);
                if (name == null || name.length() == 0)
                {
                    throw new ImporterException("Cannot determine node reference child name");
                }
                String localName = QName.createValidLocalName(name);
                childQName = QName.createQName(assocType.getNamespaceURI(), localName);
            }
        
            // create the secondary link
            nodeService.addChild(parentRef, referencedRef, assocType, childQName);
            reportNodeLinked(referencedRef, parentRef, assocType, childQName);
        }
        else
        {
            nodeService.createAssociation(parentRef, referencedRef, assocType);
            reportNodeLinked(parentRef, referencedRef, assocType, null);
        }
    }
    
    // second, perform any specified udpates to the node
    updateStrategy.importNode(context);
    return referencedRef; 
}
 
Example 19
Source File: NodesImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected FileInfo moveOrCopyImpl(NodeRef nodeRef, NodeRef parentNodeRef, String name, boolean isCopy)
{
    String targetParentId = parentNodeRef.getId();

    try
    {
        if (isCopy)
        {
            // copy
            FileInfo newFileInfo = fileFolderService.copy(nodeRef, parentNodeRef, name);
            if (newFileInfo.getNodeRef().equals(nodeRef))
            {
                // copy did not happen - eg. same parent folder and name (name can be null or same)
                throw new FileExistsException(nodeRef, "");
            }
            return newFileInfo;
        }
        else
        {
            // move
            if ((! nodeRef.equals(parentNodeRef)) && isSpecialNode(nodeRef, getNodeType(nodeRef)))
            {
                throw new PermissionDeniedException("Cannot move: "+nodeRef.getId());
            }

            // updating "parentId" means moving primary parent !
            // note: in the future (as and when we support secondary parent/child assocs) we may also
            // wish to select which parent to "move from" (in case where the node resides in multiple locations)
            return fileFolderService.move(nodeRef, parentNodeRef, name);
        }
    }
    catch (InvalidNodeRefException inre)
    {
        throw new EntityNotFoundException(targetParentId);
    }
    catch (FileNotFoundException fnfe)
    {
        // convert checked exception
        throw new EntityNotFoundException(targetParentId);
    }
    catch (FileExistsException fee)
    {
        // duplicate - name clash
        throw new ConstraintViolatedException("Name already exists in target parent: "+name);
    }
    catch (FileFolderServiceImpl.InvalidTypeException ite)
    {
        throw new InvalidArgumentException("Invalid type of target parent: "+targetParentId);
    }
}
 
Example 20
Source File: NodesImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected NodeRef updateNodeImpl(String nodeId, Node nodeInfo, Parameters parameters)
{
    validateAspects(nodeInfo.getAspectNames(), EXCLUDED_NS, EXCLUDED_ASPECTS);
    validateProperties(nodeInfo.getProperties(), EXCLUDED_NS,  Arrays.asList());

    final NodeRef nodeRef = validateOrLookupNode(nodeId, null);

    QName nodeTypeQName = getNodeType(nodeRef);

    validateCmObject(nodeTypeQName);

    Map<QName, Serializable> props = new HashMap<>(0);

    if (nodeInfo.getProperties() != null)
    {
        props = mapToNodeProperties(nodeInfo.getProperties());
    }

    String name = nodeInfo.getName();
    if ((name != null) && (! name.isEmpty()))
    {
        // update node name if needed - note: if the name is different than existing then this is equivalent of a rename (within parent folder)
        props.put(ContentModel.PROP_NAME, name);
    }

    String nodeType = nodeInfo.getNodeType();
    if ((nodeType != null) && (! nodeType.isEmpty()))
    {
        // update node type - ensure that we are performing a specialise (we do not support generalise)
        QName destNodeTypeQName = createQName(nodeType);

        if ((! destNodeTypeQName.equals(nodeTypeQName)) &&
             isSubClass(destNodeTypeQName, nodeTypeQName) &&
             (! isSubClass(destNodeTypeQName, ContentModel.TYPE_SYSTEM_FOLDER)))
        {
            nodeService.setType(nodeRef, destNodeTypeQName);
        }
        else if (! destNodeTypeQName.equals(nodeTypeQName))
        {
            throw new InvalidArgumentException("Failed to change (specialise) node type - from "+nodeTypeQName+" to "+destNodeTypeQName);
        }
    }

    NodeRef parentNodeRef = nodeInfo.getParentId();
    if (parentNodeRef != null)
    {
        NodeRef currentParentNodeRef = getParentNodeRef(nodeRef);
        if (currentParentNodeRef == null)
        {
            // implies root (Company Home) hence return 403 here
            throw new PermissionDeniedException();
        }

        if (! currentParentNodeRef.equals(parentNodeRef))
        {
            //moveOrCopy(nodeRef, parentNodeRef, name, false); // not currently supported - client should use explicit POST /move operation instead
            throw new InvalidArgumentException("Cannot update parentId of "+nodeId+" via PUT /nodes/{nodeId}. Please use explicit POST /nodes/{nodeId}/move operation instead");
        }
    }

    List<String> aspectNames = nodeInfo.getAspectNames();
    updateCustomAspects(nodeRef, aspectNames, EXCLUDED_ASPECTS);

    if (props.size() > 0)
    {
        validatePropValues(props);

        try
        {
            handleNodeRename(props, nodeRef);
            // update node properties - note: null will unset the specified property
            nodeService.addProperties(nodeRef, props);
        }
        catch (DuplicateChildNodeNameException dcne)
        {
            throw new ConstraintViolatedException(dcne.getMessage());
        }
    }

    processNodePermissions(nodeRef, nodeInfo);
    
    return nodeRef;
}