org.alfresco.service.cmr.repository.Path Java Examples

The following examples show how to use org.alfresco.service.cmr.repository.Path. 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: FilenameFilteringInterceptor.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private boolean isSystemPath(NodeRef parentNodeRef, String filename)
{
    boolean ret = false;
    Path path = nodeService.getPath(parentNodeRef);

    Iterator<Element> it = path.iterator();
    while(it.hasNext())
    {
        Path.ChildAssocElement elem = (Path.ChildAssocElement)it.next();
        QName qname = elem.getRef().getQName();
        if(qname != null && systemPaths.isFiltered(qname.getLocalName()))
        {
            ret = true;
            break;
        }
    }

    return ret;
}
 
Example #2
Source File: ACPExportPackageHandler.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * @param path Path
 * @return  display path
 */
private String toDisplayPath(Path path)
{
    StringBuffer displayPath = new StringBuffer();
    if (path.size() == 1)
    {
        displayPath.append("/");
    }
    else
    {
        for (int i = 1; i < path.size(); i++)
        {
            Path.Element element = path.get(i);
            if (element instanceof ChildAssocElement)
            {
                ChildAssociationRef assocRef = ((ChildAssocElement)element).getRef();
                NodeRef node = assocRef.getChildRef();
                displayPath.append("/");
                displayPath.append(nodeService.getProperty(node, ContentModel.PROP_NAME));
            }
        }
    }
    return displayPath.toString();
}
 
Example #3
Source File: TransferServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private  UnitTestTransferManifestNodeFactory unitTestKludgeToTransferGuestHomeToCompanyHome()
{
    /**
     *  For unit test 
     *  - replace the HTTP transport with the in-process transport
     *  - replace the node factory with one that will map node refs, paths etc.
     */
    TransferTransmitter transmitter = new UnitTestInProcessTransmitterImpl(this.receiver, this.contentService, transactionService);
    transferServiceImpl.setTransmitter(transmitter);
    UnitTestTransferManifestNodeFactory testNodeFactory = new UnitTestTransferManifestNodeFactory(this.transferManifestNodeFactory); 
    transferServiceImpl.setTransferManifestNodeFactory(testNodeFactory); 
    List<Pair<Path, Path>> pathMap = testNodeFactory.getPathMap();
    // Map company_home/guest_home to company_home so tranferred nodes and moved "up" one level.
    pathMap.add(new Pair<Path, Path>(PathHelper.stringToPath(GUEST_HOME_XPATH_QUERY), PathHelper.stringToPath(COMPANY_HOME_XPATH_QUERY)));
   
    DescriptorService mockedDescriptorService = getMockDescriptorService(REPO_ID_A);
    transferServiceImpl.setDescriptorService(mockedDescriptorService);
    
    return testNodeFactory;
}
 
Example #4
Source File: NodeChangeTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Before
public void setUp() throws Exception
{
    namespaceService = mock(NamespaceService.class);
    Collection<String> cmAlways = new ArrayList<String>();
    cmAlways.add("cm");
    when(namespaceService.getPrefixes(anyString())).thenReturn(cmAlways);
    when(namespaceService.getNamespaceURI(anyString())).thenReturn("cm");
    
    nodeService = mock(NodeService.class);
    
    Path rootPath = newPath(null, "/");
    Path homeFolderPath = newPath(rootPath, "cm:homeFolder");
    folderPath1 = newPath(homeFolderPath, "cm:folder1");
    folderPath2 = newPath(homeFolderPath, "cm:folder2");
    folder1 = newFolder(folderPath1);
    folder2 = newFolder(folderPath2);
    content1 = newContent(folderPath1, "cm:content1");
    
    nodeInfoFactory = new NodeInfoFactory(nodeService, namespaceService);
    nodeChange = new NodeChange(nodeInfoFactory, namespaceService, content1);
}
 
Example #5
Source File: NodeResourceHelper.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public NodeResource.Builder createNodeResourceBuilder(NodeRef nodeRef)
{
    final QName type = nodeService.getType(nodeRef);
    final Path path = nodeService.getPath(nodeRef);

    final Map<QName, Serializable> properties = getProperties(nodeRef);

    // minor: save one lookup if creator & modifier are the same
    Map<String, UserInfo> mapUserCache = new HashMap<>(2);

    return NodeResource.builder().setId(nodeRef.getId())
                       .setName((String) properties.get(ContentModel.PROP_NAME))
                       .setNodeType(getQNamePrefixString(type))
                       .setIsFile(isSubClass(type, ContentModel.TYPE_CONTENT))
                       .setIsFolder(isSubClass(type, ContentModel.TYPE_FOLDER))
                       .setCreatedByUser(getUserInfo((String) properties.get(ContentModel.PROP_CREATOR), mapUserCache))
                       .setCreatedAt(getZonedDateTime((Date)properties.get(ContentModel.PROP_CREATED)))
                       .setModifiedByUser(getUserInfo((String) properties.get(ContentModel.PROP_MODIFIER), mapUserCache))
                       .setModifiedAt(getZonedDateTime((Date)properties.get(ContentModel.PROP_MODIFIED)))
                       .setContent(getContentInfo(properties))
                       .setPrimaryHierarchy(PathUtil.getNodeIdsInReverse(path, false))
                       .setProperties(mapToNodeProperties(properties))
                       .setAspectNames(getMappedAspects(nodeRef));
}
 
Example #6
Source File: NodeMonitor.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * The relative path of a renamed/moved node
 * 
 * ALF-2309: construct the path from the old parent of the moved
 * node (parentNodeRef) - this will have the correct path
 * 
 * @param parentNodeRef the old parent of the node
 * @param nodeName		the old name of the childs
 * @return String
 */
private String buildRelativePathString(NodeRef parentNodeRef, String nodeName) {
	Path nodePath = m_nodeService.getPath(parentNodeRef);
	
	StringBuilder pathStr = new StringBuilder();
	pathStr.append(nodePath.toDisplayPath(m_nodeService, m_permissionService));
	if (pathStr.length() == 0 
			||  pathStr.charAt(pathStr.length() - 1) != '/' && pathStr.charAt(pathStr.length() - 1) != '\\')
		pathStr.append("/");

	pathStr.append((String) m_nodeService.getProperty( parentNodeRef, ContentModel.PROP_NAME))
		.append("\\")
		.append( nodeName);

	return pathStr.toString();
}
 
Example #7
Source File: NodeMonitor.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private StringBuilder calculateDisplayPath(final NodeRef nodeRef)
{
    return AuthenticationUtil.runAs(new RunAsWork<StringBuilder>()
    {
        @Override
        public StringBuilder doWork() throws Exception
        {
            // Get the full path to the file/folder node
            Path nodePath = m_nodeService.getPath(nodeRef);
            String fName = (String) m_nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);

            // Build the share relative path to the node
            StringBuilder result = new StringBuilder();
            result.append(nodePath.toDisplayPath(m_nodeService, m_permissionService));
            if ((0 == result.length()) || ('/' != (result.charAt(result.length() - 1)) && ('\\' != result.charAt(result.length() - 1))))
            {
                result.append("\\");
            }
            return result.append(fName);
        }
    }, AuthenticationUtil.SYSTEM_USER_NAME);
}
 
Example #8
Source File: ViewXMLExporter.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void startNode(NodeRef nodeRef)
{
    try
    {
        AttributesImpl attrs = new AttributesImpl(); 

        Path path = nodeService.getPath(nodeRef);
        if (path.size() > 1)
        {
            // a child name does not exist for root
            Path.ChildAssocElement pathElement = (Path.ChildAssocElement)path.last();
            QName childQName = pathElement.getRef().getQName();
            attrs.addAttribute(NamespaceService.REPOSITORY_VIEW_1_0_URI, CHILDNAME_LOCALNAME, CHILDNAME_QNAME.toPrefixString(), null, toPrefixString(childQName));
        }
        
        QName type = nodeService.getType(nodeRef);
        contentHandler.startElement(type.getNamespaceURI(), type.getLocalName(), toPrefixString(type), attrs);
    }
    catch (SAXException e)
    {
        throw new ExporterException("Failed to process start node event - node ref " + nodeRef.toString(), e);
    }
}
 
Example #9
Source File: NodesMetaDataGet.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
private ArrayList<NodeRef> getAncestors(Path path)
{
    ArrayList<NodeRef> ancestors = new ArrayList<NodeRef>(8);
    for (Iterator<Path.Element> elit = path.iterator(); elit.hasNext(); /**/)
    {
        Path.Element element = elit.next();
        if (!(element instanceof Path.ChildAssocElement))
        {
            throw new IndexerException("Confused path: " + path);
        }
        Path.ChildAssocElement cae = (Path.ChildAssocElement) element;
        NodeRef parentRef = cae.getRef().getParentRef();
        if(parentRef != null)
        {
            ancestors.add(0, parentRef);
        }

    }
    return ancestors;
}
 
Example #10
Source File: PathHelper.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Converts a String representation of a path to a Path
 * 
 * e.g "/{http://www.alfresco.org/model/application/1.0}company_home/{http://www.alfresco.org/model/application/1.0}dictionary/{http://www.alfresco.org/model/application/1.0}transfers/{http://www.alfresco.org/model/content/1.0}default/{http://www.alfresco.org/model/transfer/1.0}snapshotMe";
 * @param value the string representation of the path.
 * @return Path 
 */
public static Path stringToPath(String value)
{
    Path path = new Path();
    
    // pattern for QName e.g. /{stuff}stuff
    
    Pattern pattern = Pattern.compile("/\\{[a-zA-Z:./0-9]*\\}[^/]*");
    Matcher matcher = pattern.matcher(value);
    
    // This is the root node
    path.append(new SimplePathElement("/"));
           
    while ( matcher.find() )
    {
        String group = matcher.group();
        final String val = ISO9075.decode(group.substring(1));
        path.append(new SimplePathElement(val));
    }
    
    return path;
}
 
Example #11
Source File: CachingCorrespondingNodeResolverImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public ResolvedParentChildPair resolveCorrespondingNode(NodeRef sourceNodeRef, ChildAssociationRef primaryAssoc,
        Path parentPath)
{
    
    ResolvedParentChildPair result = cache.get(sourceNodeRef);

    if (result != null)
    {
        if (log.isDebugEnabled()) 
        {
            log.debug("Found fully-resolved entry in cache for node " + sourceNodeRef);
        }
        return result;
    }

    result = delegateResolver.resolveCorrespondingNode(sourceNodeRef, primaryAssoc, parentPath);

    //If we have fully resolved the parent and child nodes then stick it in the cache...
    if (result.resolvedChild != null && result.resolvedParent != null)
    {
        cache.put(sourceNodeRef, result);
    }
    return result;
}
 
Example #12
Source File: LuceneCategoryServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private String buildXPath(Path path)
{
    StringBuilder pathBuffer = new StringBuilder(64);
    for (Iterator<Path.Element> elit = path.iterator(); elit.hasNext(); /**/)
    {
        Path.Element element = elit.next();
        if (!(element instanceof Path.ChildAssocElement))
        {
            throw new IndexerException("Confused path: " + path);
        }
        Path.ChildAssocElement cae = (Path.ChildAssocElement) element;
        if (cae.getRef().getParentRef() != null)
        {
            pathBuffer.append("/");
            pathBuffer.append(getPrefix(cae.getRef().getQName().getNamespaceURI()));
            pathBuffer.append(ISO9075.encode(cae.getRef().getQName().getLocalName()));
        }
    }
    return pathBuffer.toString();
}
 
Example #13
Source File: HiddenAspect.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Checks whether the node is on a hidden path
 *
 * @param nodeRef NodeRef
 * @return the matching filter, or null if no match
 */
public HiddenFileInfo onHiddenPath(NodeRef nodeRef)
{
    HiddenFileInfo ret = null;
    // TODO would be nice to check each part of the path in turn, bailing out if a match is found
    Path path = nodeService.getPath(nodeRef);
    nodeService.getProperty(nodeRef, ContentModel.PROP_NAME);

    Iterator<Element> it = path.iterator();
    while(it.hasNext())
    {
        Path.ChildAssocElement elem = (Path.ChildAssocElement)it.next();
        QName qname = elem.getRef().getQName();
        if(qname != null)
        {
            ret = isHidden(qname.getLocalName());
            if(ret != null)
            {
                break;
            }
        }
    }

    return ret;
}
 
Example #14
Source File: TaggingServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.tagging.TaggingService#findTaggedNodes(StoreRef, java.lang.String, org.alfresco.service.cmr.repository.NodeRef)
 */
public List<NodeRef> findTaggedNodes(StoreRef storeRef, String tag, NodeRef nodeRef)
{
    // Lower the case of the tag
    tag = tag.toLowerCase();
    
    // Get path
    Path nodePath = this.nodeService.getPath(nodeRef);
    String pathString = nodePath.toPrefixString(this.namespaceService);
    ResultSet resultSet = null;
    
    try
    {
        // Do query
        resultSet = this.searchService.query(
            storeRef, 
            SearchService.LANGUAGE_LUCENE, 
            "+PATH:\"" + pathString + "//*\" +PATH:\"/cm:taggable/cm:" + ISO9075.encode(tag) + "/member\"");
        List<NodeRef> nodeRefs = resultSet.getNodeRefs();
        return nodeRefs;
    }
    finally
    {
        if(resultSet != null) {resultSet.close();}
    }
}
 
Example #15
Source File: XMLTransferManifestWriter.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void writePrimaryParent(ChildAssociationRef parentAssoc, Path parentPath)
            throws SAXException
{
    writer.startElement(TransferModel.TRANSFER_MODEL_1_0_URI,
                ManifestModel.LOCALNAME_ELEMENT_PRIMARY_PARENT, PREFIX + ":"
                            + ManifestModel.LOCALNAME_ELEMENT_PRIMARY_PARENT, EMPTY_ATTRIBUTES);

    writeParentAssoc(parentAssoc);

    writer.startElement(TransferModel.TRANSFER_MODEL_1_0_URI,
                ManifestModel.LOCALNAME_ELEMENT_PRIMARY_PATH, PREFIX + ":"
                            + ManifestModel.LOCALNAME_ELEMENT_PRIMARY_PATH, EMPTY_ATTRIBUTES);
    if (parentPath != null)
    {
        String path = parentPath.toString();
        writer.characters(path.toCharArray(), 0, path.length());
    }
    writer.endElement(TransferModel.TRANSFER_MODEL_1_0_URI,
                ManifestModel.LOCALNAME_ELEMENT_PRIMARY_PATH, PREFIX + ":"
                            + ManifestModel.LOCALNAME_ELEMENT_PRIMARY_PATH);

    writer.endElement(TransferModel.TRANSFER_MODEL_1_0_URI,
                ManifestModel.LOCALNAME_ELEMENT_PRIMARY_PARENT, PREFIX + ":"
                            + ManifestModel.LOCALNAME_ELEMENT_PRIMARY_PARENT);
}
 
Example #16
Source File: RepoTransferReceiverImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * move transfer node to new parent.
 * @param childNode
 * @param newParent
 */
private void moveNode(TransferManifestNormalNode childNode, TransferManifestNormalNode newParent)
{
    List<ChildAssociationRef> currentParents = childNode.getParentAssocs();
    List<ChildAssociationRef> newParents = new ArrayList<ChildAssociationRef>();

    for (ChildAssociationRef parent : currentParents)
    {
        if (!parent.isPrimary())
        {
            newParents.add(parent);
        }
        else
        {
            ChildAssociationRef newPrimaryAssoc = new ChildAssociationRef(ContentModel.ASSOC_CONTAINS, newParent
                    .getNodeRef(), parent.getQName(), parent.getChildRef(), true, -1);
            newParents.add(newPrimaryAssoc);
            childNode.setPrimaryParentAssoc(newPrimaryAssoc);
            Path newParentPath = new Path();
            newParentPath.append(newParent.getParentPath());
            newParentPath.append(new Path.ChildAssocElement(newParent.getPrimaryParentAssoc()));
            childNode.setParentPath(newParentPath);
        }
    }
    childNode.setParentAssocs(newParents);
}
 
Example #17
Source File: AbstractEventsService.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public NodeInfo(String eventType, String txnId, String name, NodeRef nodeRef, Status status, List<Path> nodePaths,
        Long modificationTimestamp, QName type, Set<QName> aspects, String siteId, Client client, Boolean nodeExists, boolean include,
        Boolean isVisible, Boolean typeMatches)
{
    super();
    this.eventType = eventType;
    this.txnId = txnId;
    this.name = name;
    this.nodeRef = nodeRef;
    this.status = status;
    this.nodePaths = nodePaths;
    this.modificationTimestamp = modificationTimestamp;
    this.type = type;
    this.aspects = aspects;
    this.siteId = siteId;
    this.client = client;
    this.nodeExists = nodeExists;
    this.include = include;
    this.isVisible = isVisible;
    this.typeMatches = typeMatches;
}
 
Example #18
Source File: AbstractNodeDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public List<Path> getPaths(Pair<Long, NodeRef> nodePair, boolean primaryOnly) throws InvalidNodeRefException
{
    // create storage for the paths - only need 1 bucket if we are looking for the primary path
    List<Path> paths = new ArrayList<Path>(primaryOnly ? 1 : 10);
    // create an empty current path to start from
    Path currentPath = new Path();
    // create storage for touched associations
    Stack<Long> assocIdStack = new Stack<Long>();
    
    // call recursive method to sort it out
    prependPaths(nodePair, null, currentPath, paths, assocIdStack, primaryOnly);
    
    // check that for the primary only case we have exactly one path
    if (primaryOnly && paths.size() != 1)
    {
        throw new RuntimeException("Node has " + paths.size() + " primary paths: " + nodePair);
    }
    
    // done
    if (loggerPaths.isDebugEnabled())
    {
        StringBuilder sb = new StringBuilder(256);
        if (primaryOnly)
        {
            sb.append("Primary paths");
        }
        else
        {
            sb.append("Paths");
        }
        sb.append(" for node ").append(nodePair);
        for (Path path : paths)
        {
            sb.append("\n").append("   ").append(path);
        }
        loggerPaths.debug(sb);
    }
    return paths;
}
 
Example #19
Source File: AlfrescoScriptVirtualContext.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @return an array containing the plain qname path at index 0 and the
 *         ISO9075 element-encoded qname path at index 1
 */
private String[] createQNamePaths()
{
    final NamespaceService ns = serviceRegistry.getNamespaceService();
    final Map<String, String> cache = new HashMap<String, String>();
    final StringBuilder bufPlain = new StringBuilder(128);
    final StringBuilder bufISO9075 = new StringBuilder(128);

    final Path path = serviceRegistry.getNodeService().getPath(context.getActualNodeRef());
    for (final Path.Element e : path)
    {
        if (e instanceof Path.ChildAssocElement)
        {
            final QName qname = ((Path.ChildAssocElement) e).getRef().getQName();
            if (qname != null)
            {
                String prefix = cache.get(qname.getNamespaceURI());
                if (prefix == null)
                {
                    // first request for this namespace prefix, get and
                    // cache result
                    Collection<String> prefixes = ns.getPrefixes(qname.getNamespaceURI());
                    prefix = prefixes.size() != 0 ? prefixes.iterator().next() : "";
                    cache.put(qname.getNamespaceURI(),
                              prefix);
                }
                bufISO9075.append('/').append(prefix).append(':').append(ISO9075.encode(qname.getLocalName()));
                bufPlain.append('/').append(prefix).append(':').append(qname.getLocalName());
            }
        }
        else
        {
            bufISO9075.append('/').append(e.toString());
            bufPlain.append('/').append(e.toString());
        }
    }
    String[] qnamePaths = new String[] { bufPlain.toString(), bufISO9075.toString() };

    return qnamePaths;
}
 
Example #20
Source File: EventsServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void recordCreated(NodeRef nodeRef)
{
    NodeInfo nodeInfo = getNodeInfo(nodeRef, RecordCreatedEvent.EVENT_TYPE);
    if(nodeInfo.checkNodeInfo())
    {
        //The event should contain the path that points to the original location of the file.
        //When a node is declared as a record, a secondary association is created for the original location, hence use just that.
        List<Path> allPaths = nodeService.getPaths(nodeRef, false);
        Path primaryPath = nodeService.getPath(nodeRef);
        
        if (allPaths.size() >= 2)
        {
            allPaths.remove(primaryPath);
        }

        List<Path> recordPath = Collections.singletonList(allPaths.get(0));
                    
        Event event = RecordCreatedEvent.builder()
                          .seqNumber(nextSequenceNumber())
                          .name(nodeInfo.getName())
                          .txnId(AlfrescoTransactionSupport.getTransactionId())
                          .timestamp(System.currentTimeMillis())
                          .networkId(TenantUtil.getCurrentDomain())
                          .siteId(nodeInfo.getSiteId())
                          .nodeId(nodeInfo.getNodeId())
                          .nodeType(nodeInfo.getType().toPrefixString(namespaceService))
                          .paths(getPaths(recordPath, Arrays.asList(nodeInfo.getName())))
                          .parentNodeIds(this.getNodeIdsFromParent(recordPath))
                          .username(AuthenticationUtil.getFullyAuthenticatedUser())
                          .nodeModificationTime(nodeInfo.getModificationTimestamp())
                          .client(getAlfrescoClient(nodeInfo.getClient()))
                          .aspects(nodeInfo.getAspectsAsStrings())
                          .nodeProperties(nodeInfo.getProperties())
                          .build();
        sendEvent(event);
    }
}
 
Example #21
Source File: NodeChangeTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private NodeRef newNodeRef(Path path, String name, String type)
{
    NodeRef nodeRef = new NodeRef(STORE, name);
    QName qNameType = QName.createQName("URI", type);
    when(nodeService.getType(nodeRef)).thenReturn(qNameType);
    when(nodeService.getPath(nodeRef)).thenReturn(path);
    return nodeRef;
}
 
Example #22
Source File: DbNodeServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * When searching for <code>primaryOnly == true</code>, checks that there is exactly
 * one path.
 */
@Extend(traitAPI=NodeServiceTrait.class,extensionAPI=NodeServiceExtension.class)
public List<Path> getPaths(NodeRef nodeRef, boolean primaryOnly) throws InvalidNodeRefException
{
    // get the starting node
    Pair<Long, NodeRef> nodePair = getNodePairNotNull(nodeRef);
    
    return nodeDAO.getPaths(nodePair, primaryOnly);
}
 
Example #23
Source File: EventsServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void recordRejected(NodeRef nodeRef)
{
    NodeInfo nodeInfo = getNodeInfo(nodeRef, RecordRejectedEvent.EVENT_TYPE);
    if(nodeInfo.checkNodeInfo())
    {
        //The event should contain the path that points to the original location of the file.
        //Since the record creation, the record might've been hidden on the collaboration site, thus removing the secondary parent-child association, 
        //we'll use a RM specific property that stores the original location of the file.
        if (PROP_RMA_RECORD_ORIGINATING_LOCATION == null)
        {
            logger.error(format("Could not generate %s event for node %s because %s property is not found.", RecordRejectedEvent.EVENT_TYPE, nodeRef, RM_MODEL_PROP_NAME_RECORD_ORIGINATING_LOCATION));
            return;
        }
        NodeRef recordOriginatingLocation = (NodeRef) nodeService.getProperty(nodeRef, PROP_RMA_RECORD_ORIGINATING_LOCATION);
        String recordOriginatingParentName = (String) nodeService.getProperty(recordOriginatingLocation, ContentModel.PROP_NAME);
        Path originatingParentPath = nodeService.getPath(recordOriginatingLocation);
        
        Event event = RecordRejectedEvent.builder()
                          .seqNumber(nextSequenceNumber())
                          .name(nodeInfo.getName())
                          .txnId(AlfrescoTransactionSupport.getTransactionId())
                          .timestamp(System.currentTimeMillis())
                          .networkId(TenantUtil.getCurrentDomain())
                          .siteId(nodeInfo.getSiteId())
                          .nodeId(nodeInfo.getNodeId())
                          .nodeType(nodeInfo.getType().toPrefixString(namespaceService))
                          .paths(getPaths(singletonList(originatingParentPath), asList(recordOriginatingParentName, nodeInfo.getName())))
                          .parentNodeIds(this.getNodeIds(singletonList(originatingParentPath)))
                          .username(AuthenticationUtil.getFullyAuthenticatedUser())
                          .nodeModificationTime(nodeInfo.getModificationTimestamp())
                          .client(getAlfrescoClient(nodeInfo.getClient()))
                          .aspects(nodeInfo.getAspectsAsStrings())
                          .nodeProperties(nodeInfo.getProperties())
                          .build();
        sendEvent(event);
    }
}
 
Example #24
Source File: NodeChangeTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("serial")
private Path newPath(Path parent, final String name)
{
    Path path = new Path();
    if (parent != null)
    {
        for(Path.Element element: parent)
        {
            path.append(element);
        }
    }
    path.append(new Path.Element()
    {
        @Override
        public String getElementString()
        {
            return name;
        }

        @Override
        public Element getBaseNameElement(TenantService tenantService)
        {
           return this;
        }
    });
    return path;
}
 
Example #25
Source File: EventsServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void secondaryAssociationCreated(final ChildAssociationRef secAssociation)
{
    NodeInfo nodeInfo = getNodeInfo(secAssociation.getChildRef(), NodeAddedEvent.EVENT_TYPE);
    if(nodeInfo.checkNodeInfo())
    {
        String username = AuthenticationUtil.getFullyAuthenticatedUser();
        String networkId = TenantUtil.getCurrentDomain();

        String name = nodeInfo.getName();
        String objectId = nodeInfo.getNodeId();
        String siteId = nodeInfo.getSiteId();
        String txnId = AlfrescoTransactionSupport.getTransactionId();
        
        NodeRef secParentNodeRef = secAssociation.getParentRef();
        String secParentNodeName = (String)nodeService.getProperty(secAssociation.getParentRef(), ContentModel.PROP_NAME);
        List<Path> secParentPath = nodeService.getPaths(secParentNodeRef, true);
        List<String> nodePaths = getPaths(secParentPath, Arrays.asList(secParentNodeName, name));
        List<List<String>> pathNodeIds = this.getNodeIds(secParentPath);
        
        long timestamp = System.currentTimeMillis();
        Long modificationTime = nodeInfo.getModificationTimestamp();
        String nodeType = nodeInfo.getType().toPrefixString(namespaceService);
        Client alfrescoClient = getAlfrescoClient(nodeInfo.getClient());

        Set<String> aspects = nodeInfo.getAspectsAsStrings();
        Map<String, Serializable> properties = nodeInfo.getProperties();

        Event event = new NodeAddedEvent(nextSequenceNumber(), name, txnId, timestamp, networkId, siteId, objectId, nodeType, nodePaths, pathNodeIds,
                username, modificationTime, alfrescoClient, aspects, properties);
        sendEvent(event);
    }
}
 
Example #26
Source File: EventsServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void secondaryAssociationDeleted(final ChildAssociationRef secAssociation)
{
    NodeInfo nodeInfo = getNodeInfo(secAssociation.getChildRef(), NodeRemovedEvent.EVENT_TYPE);
    if(nodeInfo.checkNodeInfo())
    {
        String username = AuthenticationUtil.getFullyAuthenticatedUser();
        String networkId = TenantUtil.getCurrentDomain();

        String name = nodeInfo.getName();
        String objectId = nodeInfo.getNodeId();
        String siteId = nodeInfo.getSiteId();
        String txnId = AlfrescoTransactionSupport.getTransactionId();
        
        NodeRef secParentNodeRef = secAssociation.getParentRef();
        String secParentNodeName = (String)nodeService.getProperty(secAssociation.getParentRef(), ContentModel.PROP_NAME);
        List<Path> secParentPath = nodeService.getPaths(secParentNodeRef, true);
        List<String> nodePaths = getPaths(secParentPath, Arrays.asList(secParentNodeName, name));
        List<List<String>> pathNodeIds = this.getNodeIds(secParentPath);
        
        long timestamp = System.currentTimeMillis();
        Long modificationTime = nodeInfo.getModificationTimestamp();
        String nodeType = nodeInfo.getType().toPrefixString(namespaceService);
        Client alfrescoClient = getAlfrescoClient(nodeInfo.getClient());

        Set<String> aspects = nodeInfo.getAspectsAsStrings();
        Map<String, Serializable> properties = nodeInfo.getProperties();

        Event event = new NodeRemovedEvent(nextSequenceNumber(), name, txnId, timestamp, networkId, siteId, objectId, nodeType,
                nodePaths, pathNodeIds, username, modificationTime, alfrescoClient, aspects, properties);
        sendEvent(event);
    }
}
 
Example #27
Source File: BasicCorrespondingNodeResolverImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 *
 * @param store StoreRef
 * @param parentPath Path
 * @return NodeRef
 */
private NodeRef resolveParentPath(StoreRef store, Path parentPath)
{
    if (log.isDebugEnabled()) 
    {
        log.debug("Trying to resolve parent path " + parentPath);
    }
    NodeRef node = nodeService.getRootNode(store);
    int index = 1;
    while (index < parentPath.size())
    {
        Element element = parentPath.get(index++);
        QName name = QName.createQName(element.getElementString());
        List<ChildAssociationRef> children = nodeService.getChildAssocs(node, RegexQNamePattern.MATCH_ALL, name);

        if (children.isEmpty())
        {
            if (log.isDebugEnabled())
            {
                log.debug("Failed to resolve path element " + element.getElementString());
            }
            return null;
        }
        if (log.isDebugEnabled()) 
        {
            log.debug("Resolved path element " + element.getElementString());
        }
        node = children.get(0).getChildRef();
    }
    return node;
}
 
Example #28
Source File: ScriptNode.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns the short name of the site this node is located within. If the 
 * node is not located within a site null is returned.
 * 
 * @return The short name of the site this node is located within, null
 *         if the node is not located within a site.
 */
public String getSiteShortName()
{
    if (!this.siteNameResolved)
    {
        this.siteNameResolved = true;
        
        Path path = this.services.getNodeService().getPath(getNodeRef());
        
        if (logger.isDebugEnabled())
            logger.debug("Determing if node is within a site using path: " + path);
        
        for (int i = 0; i < path.size(); i++)
        {
            if ("st:sites".equals(path.get(i).getPrefixedString(this.services.getNamespaceService())))
            {
                // we now know the node is in a site, find the next element in the array (if there is one)
                if ((i+1) < path.size())
                {
                    // get the site name
                    Path.Element siteName = path.get(i+1);
                 
                    // remove the "cm:" prefix and add to result object
                    this.siteName = ISO9075.decode(siteName.getPrefixedString(
                                this.services.getNamespaceService()).substring(3));
                }
              
                break;
            }
        }
    }
    
    if (logger.isDebugEnabled())
    {
        logger.debug(this.siteName != null ? 
                    "Node is in the site named \"" + this.siteName + "\"" : "Node is not in a site");
    }
    
    return this.siteName;
}
 
Example #29
Source File: GetPathMethod.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Path execute(NodeProtocol protocol, Reference reference) throws ProtocolMethodException
{
    Reference parent = protocol.getVirtualParentReference(reference);
    NodeRef nodeRef = protocol.getNodeRef(reference);
    Path nodeRefPath = environment.getPath(nodeRef);
    Path parentPath = parent.execute(this);
    parentPath.append(nodeRefPath.last());
    return parentPath;
}
 
Example #30
Source File: VirtualNodeServiceExtension.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Path getPath(NodeRef nodeRef)
{
	Reference reference = Reference.fromNodeRef(nodeRef);
    if (reference != null)
    {
        return reference.execute(new GetPathMethod(smartStore,
                                                                        environment));
    }
    else
    {
        return getTrait().getPath(nodeRef);
    }
}