Java Code Examples for org.alfresco.service.cmr.repository.ChildAssociationRef#getChildRef()

The following examples show how to use org.alfresco.service.cmr.repository.ChildAssociationRef#getChildRef() . 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: DbNodeServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * @throws UnsupportedOperationException        Always
 */
@Extend(traitAPI=NodeServiceTrait.class,extensionAPI=NodeServiceExtension.class)
public void deleteStore(StoreRef storeRef) throws InvalidStoreRefException
{
    // Cannot delete the root node but we can delete, without archive, all immediate children
    NodeRef rootNodeRef = nodeDAO.getRootNode(storeRef).getSecond();
    List<ChildAssociationRef> childAssocRefs = getChildAssocs(rootNodeRef);
    for (ChildAssociationRef childAssocRef : childAssocRefs)
    {
        NodeRef childNodeRef = childAssocRef.getChildRef();
        // We do NOT want to archive these, so mark them as temporary
        deleteNode(childNodeRef, false);
    }
    // Rename the store.  This takes all the nodes with it.
    StoreRef deletedStoreRef = new StoreRef(StoreRef.PROTOCOL_DELETED, GUID.generate());
    nodeDAO.moveStore(storeRef, deletedStoreRef);
    
    // Done
    if (logger.isDebugEnabled())
    {
        logger.debug("Marked store for deletion: " + storeRef + " --> " + deletedStoreRef);
    }
}
 
Example 2
Source File: HomeFolderProviderSynchronizerTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void deleteNonAdminGuestFolders(final Set<NodeRef> adminGuestUserHomeFolders)
{
    // Delete folders from under the home folder root path in case they have been left over
    // from another test. Admin and Guest home folder should not be under here, but lets
    // double check.
    for (ChildAssociationRef childAssocs: nodeService.getChildAssocs(rootNodeRef))
    {
        NodeRef nodeRef = childAssocs.getChildRef();
        if (!adminGuestUserHomeFolders.contains(nodeRef))
        {
            System.out.println("TearDown remove '"+childAssocs.getQName().getLocalName()+
                    "' from under the home folder root.");
            nodeService.deleteNode(nodeRef);
        }
    }
}
 
Example 3
Source File: ActionServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Populate the details of the action from the node reference
 * 
 * @param actionNodeRef the action node reference
 * @param action the action
 */
private void populateAction(NodeRef actionNodeRef, Action action)
{
    // Populate the action properties
    populateActionProperties(actionNodeRef, action);

    // Set the parameters
    populateParameters(actionNodeRef, action);

    // Set the conditions
    List<ChildAssociationRef> conditions = this.nodeService.getChildAssocs(actionNodeRef,
                RegexQNamePattern.MATCH_ALL, ActionModel.ASSOC_CONDITIONS);

    if (logger.isDebugEnabled())
        logger.debug("Retrieving " + (conditions == null ? " null" : conditions.size()) + " conditions");

    if (conditions != null)
    {
        for (ChildAssociationRef condition : conditions)
        {
            NodeRef conditionNodeRef = condition.getChildRef();
            action.addActionCondition(createActionCondition(conditionNodeRef));
        }
    }
}
 
Example 4
Source File: VirtualNodeServiceExtensionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testCreate_NodeProtocolParent() throws Exception
{
    NodeRef assocNode2 = nodeService.getChildByName(virtualFolder1NodeRef,
                                                    ContentModel.ASSOC_CONTAINS,
                                                    "Node2");
    NodeRef assocNode2_1 = nodeService.getChildByName(assocNode2,
                                                      ContentModel.ASSOC_CONTAINS,
                                                      "Node2_1");
    ChildAssociationRef childAssocRef = createContent(assocNode2_1,
                                                      "Content");
    NodeRef node = childAssocRef.getChildRef();
    Reference reference = Reference.fromNodeRef(node);
    assertNotNull(reference);
    assertTrue(reference.getProtocol().equals(Protocols.NODE.protocol));
    
    QName nodeTypeQName = ContentModel.TYPE_THUMBNAIL;
    QName assocQName = QName.createQName("cm", "contentThumbnail", environment.getNamespacePrefixResolver());
    QName assocTypeQName = RenditionModel.ASSOC_RENDITION;
    ChildAssociationRef assoc = nodeService.createNode(node,
                                          assocTypeQName,
                                          assocQName,
                                          nodeTypeQName);
    NodeRef virtualRenditionNode = assoc.getChildRef();
    NodeRef virtualRenditionParent = assoc.getParentRef();        
    assertEquals(node, virtualRenditionParent);
    
    Reference child = Reference.fromNodeRef(virtualRenditionNode);
    Reference parent = Reference.fromNodeRef(virtualRenditionParent);
    NodeRef physicalRenditionNode = child.execute(new GetActualNodeRefMethod(environment));
    NodeRef physicalRenditionParent = parent.execute(new GetActualNodeRefMethod(environment));
    List<ChildAssociationRef> refs = nodeService.getChildAssocs(physicalRenditionParent);
    assertEquals(physicalRenditionNode, refs.get(0).getChildRef()); // the association exists for the physical nodes
    
    List<ChildAssociationRef> virtualRefs = nodeService.getChildAssocs(virtualRenditionParent);
    assertEquals(physicalRenditionNode, virtualRefs.get(0).getChildRef()); // the association exists for the virtual nodes
}
 
Example 5
Source File: TransferReporterImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public NodeRef writeDestinationReport(String transferName,
        TransferTarget target,
        File tempFile)
{
   
    String title = transferName + "_destination";
    String description = "Transfer Destination Report - target: " + target.getName();
    String name = title + ".xml";
    
    logger.debug("writing destination transfer report " + title);
    logger.debug("parent node ref " + target.getNodeRef());
    
    Map<QName, Serializable> properties = new HashMap<QName, Serializable> ();
    properties.put(ContentModel.PROP_NAME, name);
    properties.put(ContentModel.PROP_TITLE, title);
    properties.put(ContentModel.PROP_DESCRIPTION, description);
    ChildAssociationRef ref = nodeService.createNode(target.getNodeRef(), 
            ContentModel.ASSOC_CONTAINS, 
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, name), 
            TransferModel.TYPE_TRANSFER_REPORT_DEST, 
            properties);
    
    ContentWriter writer = contentService.getWriter(ref.getChildRef(), 
            ContentModel.PROP_CONTENT, true);
    writer.setLocale(Locale.getDefault());
    writer.setMimetype(MimetypeMap.MIMETYPE_XML);
    writer.setEncoding(DEFAULT_ENCODING);
    writer.putContent(tempFile);
    
    logger.debug("written " + name + ", " + ref.getChildRef());
    
    return ref.getChildRef();
}
 
Example 6
Source File: GetChildAssocsMethod.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public List<ChildAssociationRef> execute(NodeProtocol protocol, Reference reference) throws ProtocolMethodException
{
    NodeRef actualNodeRef = reference.execute(new GetActualNodeRefMethod(null));
    NodeRef nodeRefReference = reference.toNodeRef();
    List<ChildAssociationRef> referenceAssociations = new LinkedList<>();
    if (!environment.isSubClass(environment.getType(nodeRefReference), ContentModel.TYPE_FOLDER))
    {
        List<ChildAssociationRef> actualAssociations = environment.getChildAssocs(actualNodeRef,
                                                                                  typeQNamePattern,
                                                                                  qnamePattern,
                                                                                  maxResults,
                                                                                  preload);

        for (ChildAssociationRef actualAssoc : actualAssociations)
        {
            ChildAssociationRef referenceChildAssocRef = new ChildAssociationRef(actualAssoc.getTypeQName(),
                                                                                 nodeRefReference,
                                                                                 actualAssoc.getQName(),
                                                                                 actualAssoc.getChildRef(),
                                                                                 actualAssoc.isPrimary(),
                                                                                 actualAssoc.getNthSibling());

            referenceAssociations.add(referenceChildAssocRef);
        }
    }
    return referenceAssociations;
}
 
Example 7
Source File: AbstractNodeRelation.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected CollectionWithPagingInfo<Node> listNodeChildAssocs(List<ChildAssociationRef> childAssocRefs, Parameters parameters, Boolean isPrimary, boolean returnChild)
{
    Map<QName, String> qnameMap = new HashMap<>(3);

    Map<String, UserInfo> mapUserInfo = new HashMap<>(10);

    List<String> includeParam = parameters.getInclude();

    List<Node> collection = new ArrayList<Node>(childAssocRefs.size());
    for (ChildAssociationRef childAssocRef : childAssocRefs)
    {
        if (isPrimary == null || (isPrimary == childAssocRef.isPrimary()))
        {
            // minimal info by default (unless "include"d otherwise)
            NodeRef nodeRef = (returnChild ? childAssocRef.getChildRef() : childAssocRef.getParentRef());

            Node node = nodes.getFolderOrDocument(nodeRef, null, null, includeParam, mapUserInfo);

            QName assocTypeQName = childAssocRef.getTypeQName();

            if (!EXCLUDED_NS.contains(assocTypeQName.getNamespaceURI()))
            {
                String assocType = qnameMap.get(assocTypeQName);
                if (assocType == null)
                {
                    assocType = assocTypeQName.toPrefixString(namespaceService);
                    qnameMap.put(assocTypeQName, assocType);
                }

                node.setAssociation(new AssocChild(assocType, childAssocRef.isPrimary()));
                
                collection.add(node);
            }
        }
    }
    
    return listPage(collection, parameters.getPaging());
}
 
Example 8
Source File: AbstractForumEmailMessageHandler.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Adds topic node into Alfresco repository
 * 
 * @param parentNode        Parent node
 * @param name              Topic name
 * @return                  Reference to created node
 */
protected NodeRef addTopicNode(NodeRef parentNode, String name)
{
    String workingName = encodeSubject(name);
    
    NodeService nodeService = getNodeService();
    Map<QName, Serializable> properties = new HashMap<QName, Serializable>(1);
    properties.put(ContentModel.PROP_NAME, workingName);

    NodeRef topicNode = nodeService.getChildByName(parentNode, ContentModel.ASSOC_CONTAINS, workingName);
    if (topicNode == null)
    {
        ChildAssociationRef association = nodeService.createNode(
                parentNode,
                ContentModel.ASSOC_CONTAINS,
                QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, workingName),
                ForumModel.TYPE_TOPIC,
                properties);
        topicNode = association.getChildRef();
    }

    // Add necessary aspects
    properties.clear();
    properties.put(ApplicationModel.PROP_ICON, "topic");
    getNodeService().addAspect(topicNode, ApplicationModel.ASPECT_UIFACETS, properties);

    return topicNode;
}
 
Example 9
Source File: ExporterComponentTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @param storeRef StoreRef
 * @param rootNode NodeRef
 * @return ChildAssociationRef
 */
private ChildAssociationRef createContentWithCategories(StoreRef storeRef, NodeRef rootNode)
{   
    Collection<ChildAssociationRef> assocRefs = categoryService.
        getRootCategories(storeRef, ContentModel.ASPECT_GEN_CLASSIFIABLE);
    assertTrue("Pre-condition failure: not enough categories", assocRefs.size() >= 2);
    Iterator<ChildAssociationRef> it = assocRefs.iterator();
    NodeRef softwareDocCategoryNode = it.next().getChildRef();
    it.next(); // skip one
    NodeRef regionsCategoryNode = it.next().getChildRef();        
    
    
    // Create a content node to categorise
    FileInfo exportFileInfo = fileFolderService.create(rootNode, "Export Folder", ContentModel.TYPE_FOLDER);
    Map<QName, Serializable> properties = Collections.singletonMap(ContentModel.PROP_NAME, (Serializable)"test.txt");
    ChildAssociationRef contentChildAssocRef = nodeService.createNode(
                exportFileInfo.getNodeRef(),
                ContentModel.ASSOC_CHILDREN,
                ContentModel.ASSOC_CHILDREN,
                ContentModel.TYPE_CONTENT,
                properties);
    
    NodeRef contentNodeRef = contentChildAssocRef.getChildRef();

    // Attach categories
    ArrayList<NodeRef> categories = new ArrayList<NodeRef>(2);
    categories.add(softwareDocCategoryNode);
    categories.add(regionsCategoryNode);
    if(!nodeService.hasAspect(contentNodeRef, ContentModel.ASPECT_GEN_CLASSIFIABLE))
    {
        HashMap<QName, Serializable> props = new HashMap<QName, Serializable>();
        props.put(ContentModel.PROP_CATEGORIES, categories);
        nodeService.addAspect(contentNodeRef, ContentModel.ASPECT_GEN_CLASSIFIABLE, props);
    }
    else
    {
        nodeService.setProperty(contentNodeRef, ContentModel.PROP_CATEGORIES, categories);
    }
    return contentChildAssocRef;
}
 
Example 10
Source File: ActionServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Saves the parameters associated with an action or condition
 * 
 * @param parameterizedNodeRef the parameterized item node reference
 * @param item the parameterized item
 */
private void saveParameters(NodeRef parameterizedNodeRef, ParameterizedItem item)
{
    Map<String, Serializable> parameterMap = new HashMap<String, Serializable>();
    parameterMap.putAll(item.getParameterValues());

    List<ChildAssociationRef> parameters = this.nodeService.getChildAssocs(parameterizedNodeRef,
                ActionModel.ASSOC_PARAMETERS, ActionModel.ASSOC_PARAMETERS);
    for (ChildAssociationRef ref : parameters)
    {
        NodeRef paramNodeRef = ref.getChildRef();
        Map<QName, Serializable> nodeRefParameterMap = this.nodeService.getProperties(paramNodeRef);
        String paramName = (String) nodeRefParameterMap.get(ActionModel.PROP_PARAMETER_NAME);
        if (parameterMap.containsKey(paramName) == false)
        {
            // Delete parameter from node ref
            this.nodeService.removeChild(parameterizedNodeRef, paramNodeRef);
        }
        else
        {
            // Update the parameter value
            nodeRefParameterMap.put(ActionModel.PROP_PARAMETER_VALUE, parameterMap.get(paramName));
            this.nodeService.setProperties(paramNodeRef, nodeRefParameterMap);
            parameterMap.remove(paramName);
        }
    }

    // Add any remaining parameters
    for (Map.Entry<String, Serializable> entry : parameterMap.entrySet())
    {
        Map<QName, Serializable> nodeRefProperties = new HashMap<QName, Serializable>(2);
        nodeRefProperties.put(ActionModel.PROP_PARAMETER_NAME, entry.getKey());
        nodeRefProperties.put(ActionModel.PROP_PARAMETER_VALUE, entry.getValue());

        this.nodeService.createNode(parameterizedNodeRef, ActionModel.ASSOC_PARAMETERS,
                    ActionModel.ASSOC_PARAMETERS, ActionModel.TYPE_ACTION_PARAMETER, nodeRefProperties);
    }
}
 
Example 11
Source File: TaggingServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void onMoveNode(ChildAssociationRef oldChildAssocRef, ChildAssociationRef newChildAssocRef)
{
    NodeRef oldRef = oldChildAssocRef.getChildRef();
    NodeRef oldParent = oldChildAssocRef.getParentRef();
    NodeRef newRef = newChildAssocRef.getChildRef();
    NodeRef newParent = newChildAssocRef.getParentRef();
    
    // Do nothing if it's a "rename" not a move
    if (oldParent.equals(newParent))
    {
        return;
    }
    
    // It has moved somewhere
    // Remove the tags from the old location
    if (this.nodeService.hasAspect(oldRef, ContentModel.ASPECT_TAGGABLE))
    {
        // Use the parent we were passed in, rather than re-fetching
        // via the node, as we need to reference the old scope!
        ChildAssociationRef scopeParent;
        if (oldChildAssocRef.isPrimary())
        {
            scopeParent = oldChildAssocRef;
        }
        else
        {
            scopeParent = this.nodeService.getPrimaryParent(oldParent);
        }
        if (scopeParent != null)
        {
            updateAllScopeTags(oldRef, scopeParent.getParentRef(), Boolean.FALSE);
        }
    }
    // Add the tags at its new location
    if (this.nodeService.hasAspect(newRef, ContentModel.ASPECT_TAGGABLE))
    {
        updateAllScopeTags(newRef, Boolean.TRUE);
    }
}
 
Example 12
Source File: LockServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void onMoveNode(ChildAssociationRef oldChildAssocRef, ChildAssociationRef newChildAssocRef)
{
    NodeRef nodeRef = oldChildAssocRef.getChildRef();
    checkForLock(nodeRef);
}
 
Example 13
Source File: SiteServiceImplMoreTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void onCreateNodeSetTitle(ChildAssociationRef childAssocRef)
{
    NodeRef newRef = childAssocRef.getChildRef();
    NODE_SERVICE.setProperty(newRef, ContentModel.PROP_TITLE, "Testing REPO-1688");
}
 
Example 14
Source File: DiscussableAspect.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void afterVersionRevert(NodeRef nodeRef, Version version)
{
    NodeRef versionNodeRef = version.getFrozenStateNodeRef();
    if (!this.nodeService.hasAspect(versionNodeRef, ForumModel.ASPECT_DISCUSSABLE))
    {
        return;
    }
    
    // Get the discussion assoc references from the version store
    List<ChildAssociationRef> childAssocRefs = this.nodeService.getChildAssocs(VersionUtil.convertNodeRef(versionNodeRef), ForumModel.ASSOC_DISCUSSION,
            RegexQNamePattern.MATCH_ALL);
    for (ChildAssociationRef childAssocRef : childAssocRefs)
    {
        // Get the child reference
        NodeRef childRef = childAssocRef.getChildRef();
        NodeRef referencedNode = (NodeRef) this.dbNodeService.getProperty(childRef, ContentModel.PROP_REFERENCE);

        if (referencedNode != null && this.nodeService.exists(referencedNode) == false)
        {
            StoreRef orginalStoreRef = referencedNode.getStoreRef();
            NodeRef archiveRootNodeRef = this.nodeService.getStoreArchiveNode(orginalStoreRef);
            if (archiveRootNodeRef == null)
            {
                // Store doesn't support archiving
                continue;
            }
            NodeRef archivedNodeRef = new NodeRef(archiveRootNodeRef.getStoreRef(), referencedNode.getId());

            if (!this.nodeService.exists(archivedNodeRef) || !nodeService.hasAspect(archivedNodeRef, ContentModel.ASPECT_ARCHIVED))
            {
                // Node doesn't support archiving or it was deleted within parent node.
                continue;
            }

            NodeRef existingChild = this.nodeService.getChildByName(nodeRef, childAssocRef.getTypeQName(), this.nodeService
                    .getProperty(archivedNodeRef, ContentModel.PROP_NAME).toString());
            if (existingChild != null)
            {
                this.nodeService.deleteNode(existingChild);
            }

            this.nodeService.restoreNode(archivedNodeRef, null, null, null);
        }
    }
}
 
Example 15
Source File: AbstractSignatureActionExecuter.java    From CounterSign with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Creates a "signature" object and associates it with the signed doc
 * @param node
 * @param location
 * @param reason
 */
protected NodeRef addSignatureNodeAssociation(NodeRef node, String location, String reason, 
		String signatureField, java.util.Date sigDate, String geolocation, int page, String position)
{
	NodeService nodeService = serviceRegistry.getNodeService();
	
	String userId = AuthenticationUtil.getRunAsUser();
	NodeRef person = serviceRegistry.getPersonService().getPerson(userId);
	
	// if page is -1, then this was a signature field, set position to "none"
	if(page == -1) position = "none";
	
	HashMap<QName, Serializable> props = new HashMap<QName, Serializable>();
	props.put(CounterSignSignatureModel.PROP_REASON, reason);
	props.put(CounterSignSignatureModel.PROP_LOCATION, location);
	props.put(CounterSignSignatureModel.PROP_SIGNATUREDATE, sigDate);
	props.put(CounterSignSignatureModel.PROP_SIGNATUREFIELD, signatureField);
	props.put(CounterSignSignatureModel.PROP_SIGNATUREPAGE, page);
	props.put(CounterSignSignatureModel.PROP_SIGNATUREPOSITION, position);
	props.put(CounterSignSignatureModel.PROP_EXTERNALSIGNER, userId);
	
	// check the geolocation data, if it is valid, split it out and add
	if(geolocation.indexOf(",") != -1)
	{
		String[] latLong = geolocation.split(",");
		props.put(ContentModel.PROP_LATITUDE, latLong[0]);
		props.put(ContentModel.PROP_LONGITUDE, latLong[1]);
	}
	else
	{
		props.put(ContentModel.PROP_LATITUDE, -1);
		props.put(ContentModel.PROP_LONGITUDE, -1);
	}
	
	QName assocQName = QName.createQName(
			CounterSignSignatureModel.COUNTERSIGN_SIGNATURE_MODEL_1_0_URI,
			QName.createValidLocalName(userId + "-" + sigDate.getTime()));
		
	ChildAssociationRef sigChildRef = nodeService.createNode(
			node, 
			CounterSignSignatureModel.ASSOC_SIGNATURES, 
			assocQName, 
			CounterSignSignatureModel.TYPE_SIGNATURE, 
			props);
	
	NodeRef signature = sigChildRef.getChildRef();
	
	// add hidden aspect to signature nodes, these should not be 
	// shown in any document lists or other Share views
	HashMap<QName, Serializable> aspectProps = new HashMap<QName, Serializable>();
	aspectProps.put(ContentModel.PROP_VISIBILITY_MASK, HiddenAspect.Visibility.NotVisible.getMask());
	nodeService.addAspect(signature, ContentModel.ASPECT_HIDDEN, aspectProps);

	nodeService.createAssociation(signature, person, CounterSignSignatureModel.ASSOC_SIGNEDBY);
	
	return signature;
}
 
Example 16
Source File: VirtualVersionServiceExtensionTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testCreateVersion() throws Exception
{

    ChildAssociationRef contentWithVersionsAssocRef = createContent(node2_1,
                                                                    "ContentWithVersions");
    NodeRef contentWithVersionsNodeRef = contentWithVersionsAssocRef.getChildRef();
    Reference reference = Reference.fromNodeRef(contentWithVersionsNodeRef);
    assertNotNull(reference);
    NodeRef actualContentWithVersionsNodeRef = 
                    reference.execute(new GetActualNodeRefMethod(environment));

    VersionHistory versionHistory = versionService.getVersionHistory(contentWithVersionsNodeRef);
    assertNull(versionHistory);
    VersionHistory actualVersionHistory = versionService.getVersionHistory(actualContentWithVersionsNodeRef);
    assertNull(actualVersionHistory);

    Version newVersion = versionService.createVersion(contentWithVersionsNodeRef,
                                                      null);

    NodeRef newVersionNodeRef = newVersion.getVersionedNodeRef();
    assertNotNull(Reference.fromNodeRef(newVersionNodeRef));

    versionHistory = versionService.getVersionHistory(newVersionNodeRef);
    assertNotNull(versionHistory);

    Collection<Version> allVersions = versionHistory.getAllVersions();
    assertEquals(1,
                 allVersions.size());

    actualVersionHistory = versionService.getVersionHistory(actualContentWithVersionsNodeRef);
    assertNotNull(actualVersionHistory);

    Collection<Version> allActualVersions = versionHistory.getAllVersions();
    assertEquals(1,
                 allActualVersions.size());

    Version actualVersion = actualVersionHistory.getHeadVersion();

    NodeRef newActualVersionNodeRef = actualVersion.getVersionedNodeRef();
    assertNull(Reference.fromNodeRef(newActualVersionNodeRef));

    assertEquals(newActualVersionNodeRef,
                 actualContentWithVersionsNodeRef);
}
 
Example 17
Source File: RepositoryNodeRefResolver.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public NodeRef createQNamePath(String[] reference, String[] names)
{
    Stack<String> notFoundStack = new Stack<>();
    Stack<String> notFoundNameStack = new Stack<>();
    NodeRef found;
    if (reference == null || reference.length == 0)
    {
        found = getRootHome();
    }
    else
    {
        NodeRef parentNodeRef = null;
        for (int i = reference.length; i > 0; i--)
        {
            String[] parent = new String[i];
            System.arraycopy(reference,
                             0,
                             parent,
                             0,
                             i);
            parentNodeRef = resolveQNameReference(parent);
            if (parentNodeRef != null)
            {
                break;
            }
            else
            {
                if (names != null)
                {
                    int offset = reference.length - i;
                    if (offset < names.length)
                    {
                        notFoundNameStack.push(names[names.length - 1 - offset]);
                    }
                }
                notFoundStack.push(reference[i - 1]);
            }
        }
        while (!notFoundStack.isEmpty())
        {
            String stringQNameToCreate = notFoundStack.pop();
            QName qNameToCreate = QName.createQName(stringQNameToCreate,
                                                    namespacePrefixResolver);
            String nameToCreate;
            if (!notFoundNameStack.isEmpty())
            {
                nameToCreate = notFoundNameStack.pop();
            }
            else
            {
                nameToCreate = qNameToCreate.getLocalName();
            }
            final HashMap<QName, Serializable> newProperties = new HashMap<QName, Serializable>();
            newProperties.put(ContentModel.PROP_NAME,
                              nameToCreate);
            ChildAssociationRef newAssoc = nodeService.createNode(parentNodeRef,
                                                                  ContentModel.ASSOC_CONTAINS,
                                                                  qNameToCreate,
                                                                  ContentModel.TYPE_FOLDER,
                                                                  newProperties);
            parentNodeRef = newAssoc.getChildRef();
        }

        found = parentNodeRef;
    }

    return found;

}
 
Example 18
Source File: UserUsageTrackingComponent.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void onCreateNode(ChildAssociationRef childAssocRef)
{
    if (enabled == true)
    {
        final NodeRef personRef = childAssocRef.getChildRef();
        final String userName = (String) this.nodeService.getProperty(personRef, ContentModel.PROP_USERNAME);
        
        if (userName != null)
        {
            RetryingTransactionCallback<Long> updateUserWithUsage = new RetryingTransactionCallback<Long>()
            {
                public Long execute() throws Throwable
                {
                    List<String> stores = contentUsageImpl.getStores();
                    
                    Long currentUsage = null;
                    
                    for (String store : stores)
                    {
                        final StoreRef storeRef = tenantService.getName(new StoreRef(store));
                        
                        Long contentSize = usageDAO.getContentSizeForStoreForUser(storeRef, userName);
                        
                        if (contentSize != null)
                        {
                            currentUsage = (currentUsage == null ? 0L : currentUsage) + contentSize;
                        }
                    }
                    
                    if (currentUsage != null && currentUsage > 0L)
                    {
                        List<Pair<NodeRef, Long>> batchUserUsages = new ArrayList<Pair<NodeRef, Long>>(1);
                        batchUserUsages.add(new Pair<NodeRef, Long>(personRef, currentUsage));
                        
                        updateUsages(batchUserUsages);
                    }
                    
                    return null;
                }
            };
            
            // execute in READ-WRITE txn
            transactionService.getRetryingTransactionHelper().doInTransaction(updateUserWithUsage, false);
        }
    }
}
 
Example 19
Source File: PeopleImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public Person uploadAvatarContent(String personId, BasicContentInfo contentInfo, InputStream stream, Parameters parameters)
{
    if (!thumbnailService.getThumbnailsEnabled())
    {
        throw new DisabledServiceException("Thumbnail generation has been disabled.");
    }

    personId = validatePerson(personId);
    checkCurrentUserOrAdmin(personId);

    NodeRef personNode = personService.getPerson(personId);
    NodeRef avatarOrigNodeRef = getAvatarOriginal(personNode);

    if (avatarOrigNodeRef != null)
    {
        deleteAvatar(avatarOrigNodeRef);
    }

    QName origAvatarQName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "origAvatar");
    nodeService.addAspect(personNode, ContentModel.ASPECT_PREFERENCES, null);
    ChildAssociationRef assoc = nodeService.createNode(personNode, ContentModel.ASSOC_PREFERENCE_IMAGE, origAvatarQName,
            ContentModel.TYPE_CONTENT);
    NodeRef avatar = assoc.getChildRef();
    String avatarOriginalNodeId = avatar.getId();

    // TODO do we still need this ? - backward compatible with JSF web-client avatar
    nodeService.createAssociation(personNode, avatar, ContentModel.ASSOC_AVATAR);

    Node n = nodes.updateContent(avatarOriginalNodeId, contentInfo, stream, parameters);
    String mimeType = n.getContent().getMimeType();

    if (mimeType.indexOf("image/") != 0)
    {
        throw new InvalidArgumentException(
                "Uploaded content must be an image (content type determined to be '"+mimeType+"')");
    }

    // create thumbnail synchronously
    Rendition avatarR = new Rendition();
    avatarR.setId("avatar");
    renditions.createRendition(avatar, avatarR, false, parameters);

    List<String> include = Arrays.asList(
            PARAM_INCLUDE_ASPECTNAMES,
            PARAM_INCLUDE_PROPERTIES);

    return getPersonWithProperties(personId, include);
}
 
Example 20
Source File: BaseNodeServiceTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void testMoveNode() throws Exception
{
    Map<QName, ChildAssociationRef> assocRefs = buildNodeGraph();
    ChildAssociationRef n2pn4Ref = assocRefs.get(QName.createQName(BaseNodeServiceTest.NAMESPACE, "n2_p_n4"));
    ChildAssociationRef n5pn7Ref = assocRefs.get(QName.createQName(BaseNodeServiceTest.NAMESPACE, "n5_p_n7"));
    ChildAssociationRef n6pn8Ref = assocRefs.get(QName.createQName(BaseNodeServiceTest.NAMESPACE, "n6_p_n8"));
    NodeRef n4Ref = n2pn4Ref.getChildRef();
    NodeRef n5Ref = n5pn7Ref.getParentRef();
    NodeRef n6Ref = n6pn8Ref.getParentRef();
    NodeRef n8Ref = n6pn8Ref.getChildRef();
    
    MovePolicyTester policy = new MovePolicyTester();
    // bind to listen to the deletion of a node
    policyComponent.bindClassBehaviour(
            QName.createQName(NamespaceService.ALFRESCO_URI, "onMoveNode"),
            policy,
            new JavaBehaviour(policy, "onMoveNode"));   
    
    // move n8 to n5
    ChildAssociationRef assocRef = nodeService.moveNode(
            n8Ref,
            n5Ref,
            ASSOC_TYPE_QNAME_TEST_CHILDREN,
            QName.createQName(BaseNodeServiceTest.NAMESPACE, "n5_p_n8"));
    
    // check that the move policy was fired
    assertEquals("Move policy not fired", 2, policy.policyAssocRefs.size());
    
    // check that n6 is no longer the parent
    List<ChildAssociationRef> n6ChildRefs = nodeService.getChildAssocs(
            n6Ref,
            RegexQNamePattern.MATCH_ALL, QName.createQName(BaseNodeServiceTest.NAMESPACE, "n6_p_n8"));
    assertEquals("Primary child assoc is still present", 0, n6ChildRefs.size());
    // check that n5 is the parent
    ChildAssociationRef checkRef = nodeService.getPrimaryParent(n8Ref);
    assertEquals("Primary assoc incorrent", assocRef, checkRef);
    
    // check that cyclic associations are disallowed
    try
    {
        // n6 is a non-primary child of n4.  Move n4 into n6
        nodeService.moveNode(
                n4Ref,
                n6Ref,
                ASSOC_TYPE_QNAME_TEST_CHILDREN,
                QName.createQName(BaseNodeServiceTest.NAMESPACE, "n6_p_n4"));
        fail("Failed to detect cyclic relationship during move");
    }
    catch (CyclicChildRelationshipException e)
    {
        // expected
    }
}