Java Code Examples for org.alfresco.service.namespace.QName

The following are top voted examples for showing how to use org.alfresco.service.namespace.QName. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: alfresco-repository   File: ActivitiPropertyConverter.java   6 votes vote down vote up
/**
 * @param task Task
 * @param properties Map<QName, Serializable>
 */
private void setTaskOwner(Task task, Map<QName, Serializable> properties)
{
    QName ownerKey = ContentModel.PROP_OWNER;
    if (properties.containsKey(ownerKey))
    {
        Serializable owner = properties.get(ownerKey);
        if (owner != null && !(owner instanceof String))
        {
            throw getInvalidPropertyValueException(ownerKey, owner);
        }
        String assignee = (String) owner;
        String currentAssignee = task.getAssignee();
        // Only set the assignee if the value has changes to prevent
        // triggering assignementhandlers when not needed
        if (ObjectUtils.equals(currentAssignee, assignee)==false)
        {
            activitiUtil.getTaskService().setAssignee(task.getId(), assignee);
        }
    }
}
 
Example 2
Project: alfresco-repository   File: PermissionServiceImpl.java   6 votes vote down vote up
public void init()
{
    policyComponent.bindClassBehaviour(QName.createQName(NamespaceService.ALFRESCO_URI, "onMoveNode"), ContentModel.TYPE_BASE, new JavaBehaviour(this, "onMoveNode"));
    
    policyComponent.bindClassBehaviour(QName.createQName(NamespaceService.ALFRESCO_URI, "onCreateChildAssociation"), ContentModel.TYPE_AUTHORITY_CONTAINER, new JavaBehaviour(this, "onCreateChildAssociation"));
    policyComponent.bindClassBehaviour(QName.createQName(NamespaceService.ALFRESCO_URI, "beforeDeleteChildAssociation"), ContentModel.TYPE_AUTHORITY_CONTAINER, new JavaBehaviour(this, "beforeDeleteChildAssociation"));
    
    onGrantLocalPermissionDelegate = policyComponent.registerClassPolicy(PermissionServicePolicies.OnGrantLocalPermission.class);
    onRevokeLocalPermissionDelegate = policyComponent.registerClassPolicy(PermissionServicePolicies.OnRevokeLocalPermission.class);
    onInheritPermissionsEnabledDelegate = policyComponent.registerClassPolicy(PermissionServicePolicies.OnInheritPermissionsEnabled.class);
    onInheritPermissionsDisabledDelegate = policyComponent.registerClassPolicy(PermissionServicePolicies.OnInheritPermissionsDisabled.class);
}
 
Example 3
Project: alfresco-repository   File: PolicyScope.java   6 votes vote down vote up
/**
 * Add a property 
 * 
 * @param classRef  the class reference
 * @param qName		the qualified name of the property
 * @param value		the value of the property
 */
public void addProperty(QName classRef, QName qName, Serializable value) 
{
	if (classRef.equals(this.classRef) == true)
	{
		addProperty(qName, value);
	}
	else
	{
		AspectDetails aspectDetails = this.aspectCopyDetails.get(classRef);
		if (aspectDetails == null)
		{
			// Add the aspect
			aspectDetails = addAspect(classRef);
		}
		aspectDetails.addProperty(qName, value);
	}
}
 
Example 4
Project: alfresco-repository   File: PasswordCredentialsFactory.java   6 votes vote down vote up
/**
 * Serializes the given {@link BaseCredentialsInfo} object to node properties.
 * 
 * @param info The Credentials object to serialize
 * @return The final set of properties to be serialized for the node
 */
public Map<QName,Serializable> serializeCredentials(BaseCredentialsInfo info)
{
    if (! (info instanceof PasswordCredentialsInfo))
    {
        throw new IllegalStateException("Incorrect registration, info must be a PasswordCredentialsInfo");
    }
    
    // Encrypt the password
    PasswordCredentialsInfo credentials = (PasswordCredentialsInfo)info;
    Serializable passwordEncrypted = metadataEncryptor.encrypt(
            RemoteCredentialsModel.PROP_REMOTE_PASSWORD, credentials.getRemotePassword());

    // Store our specific types and return
    Map<QName,Serializable> properties = new HashMap<QName, Serializable>();
    properties.put(RemoteCredentialsModel.PROP_REMOTE_PASSWORD, passwordEncrypted);
    return properties;
}
 
Example 5
Project: alfresco-repository   File: LockServiceImpl.java   6 votes vote down vote up
/**
 * Invoke the before log policy
 * 
 * @param nodeRef       the node to be locked
 * @param lockType      the lock type
 */
private void invokeBeforeLock(
        NodeRef nodeRef,
        LockType lockType)
{
    if (!nodeService.exists(nodeRef))
    {
        return;
    }
    List<QName> classes = getInvokeClasses(nodeRef);
    for (QName invokeClass : classes)
    {            
        Collection<BeforeLock> policies = beforeLock.getList(invokeClass);
        for (BeforeLock policy : policies) 
        {
            policy.beforeLock(nodeRef, lockType);
        }
    }
}
 
Example 6
Project: alfresco-repository   File: ResetPasswordServiceImplTest.java   6 votes vote down vote up
private static void createUser(TestPerson testPerson)
{
    if (authenticationService.authenticationExists(testPerson.userName))
    {
        return;
    }
    authenticationService.createAuthentication(testPerson.userName, testPerson.password.toCharArray());

    Map<QName, Serializable> map = new HashMap<>(4);
    map.put(ContentModel.PROP_USERNAME, testPerson.userName);
    map.put(ContentModel.PROP_FIRSTNAME, testPerson.firstName);
    map.put(ContentModel.PROP_LASTNAME, testPerson.lastName);
    map.put(ContentModel.PROP_EMAIL, testPerson.email);

    personService.createPerson(map);
}
 
Example 7
Project: alfresco-repository   File: BaseNodeServiceTest.java   6 votes vote down vote up
public void testAddProperties() throws Exception
{
    Map<QName, Serializable> properties = nodeService.getProperties(rootNodeRef);
    // Add an aspect with a default value
    nodeService.addAspect(rootNodeRef, ASPECT_QNAME_TEST_TITLED, null);
    assertNull("Expected null property", nodeService.getProperty(rootNodeRef, PROP_QNAME_TEST_TITLE));
    assertNull("Expected null property", nodeService.getProperty(rootNodeRef, PROP_QNAME_TEST_DESCRIPTION));
    
    // Now add a map of two properties and check
    Map<QName, Serializable> addProperties = new HashMap<QName, Serializable>(11);
    addProperties.put(PROP_QNAME_TEST_TITLE, "Title");
    addProperties.put(PROP_QNAME_TEST_DESCRIPTION, "Description");
    nodeService.addProperties(rootNodeRef, addProperties);
    
    // Check
    Map<QName, Serializable> checkProperties = nodeService.getProperties(rootNodeRef);
    assertEquals("Title", checkProperties.get(PROP_QNAME_TEST_TITLE));
    assertEquals("Description", checkProperties.get(PROP_QNAME_TEST_DESCRIPTION));
}
 
Example 8
Project: alfresco-repository   File: BlogDetails.java   6 votes vote down vote up
/**
 * Create a BlogDetails object from a node that has the blogDetails aspect applied.
 * 
 * @param nodeService   the node service
 * @param nodeRef       the node reference
 * @return BlogDetails  the blog details 
 */
public static BlogDetails createBlogDetails(NodeService nodeService, NodeRef nodeRef)
{
    // Check for the blog details aspect
    if (nodeService.hasAspect(nodeRef, ASPECT_BLOG_DETAILS) == false)
    {
        throw new BlogIntegrationRuntimeException("Can not create blog details object since node does not have blogDetails aspect.");
    }
    
    // Get the blog details
    Map<QName, Serializable> props = nodeService.getProperties(nodeRef);
    return new BlogDetails(
            (String)props.get(PROP_BLOG_IMPLEMENTATION),
            (String)props.get(PROP_ID),
            (String)props.get(PROP_URL),
            (String)props.get(PROP_USER_NAME),
            (String)props.get(PROP_PASSWORD),
            (String)props.get(PROP_NAME),
            (String)props.get(PROP_DESCRIPTION),
            nodeRef);        
}
 
Example 9
Project: alfresco-repository   File: ChildAssocEntity.java   6 votes vote down vote up
/**
 * Find a CRC value for the full QName using UTF-8 conversion.
 * 
 * @param qname                 the association qname
 * @return                      Returns the CRC value (UTF-8 compatible)
 */
public static Long getQNameCrc(QName qname)
{
    CRC32 crc = new CRC32();
    try
    {
        crc.update(qname.getNamespaceURI().getBytes("UTF-8"));
        crc.update(qname.getLocalName().getBytes("UTF-8"));
    }
    catch (UnsupportedEncodingException e)
    {
        throw new RuntimeException("UTF-8 encoding is not supported");
    }
    return crc.getValue();
    
}
 
Example 10
Project: alfresco-repository   File: AbstractRenderingEngine.java   6 votes vote down vote up
/**
 * Sets the default rendition-node type.
 * 
 * @param type String
 */
public void setDefaultRenditionNodeType(String type)
{
    QName qname;
    try
    {
        qname = QName.createQName(type);
    }
    catch (NamespaceException nx)
    {
        if (logger.isErrorEnabled())
        {
            logger.error("Error when setting default rendition node type: ", nx);
        }
        throw nx;
    }

    if (logger.isInfoEnabled())
    {
        logger.info("Using default rendition node type: " + qname);
    }
    this.defaultRenditionNodeType = qname;
}
 
Example 11
Project: alfresco-repository   File: LockableAspectInterceptorTest.java   6 votes vote down vote up
@Test
public void testHasAspectEphemeralLock()
{
    QName nodeName = QName.createQName("http://www.alfresco.org/test/" + getClass().getSimpleName(), "testNode");
    NodeRef nodeRef = nodeService.createNode(
                rootNode,
                ContentModel.ASSOC_CHILDREN,
                nodeName,
                ContentModel.TYPE_BASE).getChildRef();
    
    assertFalse("Node should not be reported as lockable",
                nodeService.hasAspect(nodeRef, ContentModel.ASPECT_LOCKABLE));
    
    lockStore.set(nodeRef, LockState.createLock(nodeRef, LockType.WRITE_LOCK, lockOwner, null, Lifetime.EPHEMERAL, null));
    
    assertTrue("Node should be reported as lockable",
                nodeService.hasAspect(nodeRef, ContentModel.ASPECT_LOCKABLE));
}
 
Example 12
Project: alfresco-repository   File: SiteAspect.java   6 votes vote down vote up
/**
 * Deny renames.
 */
public void onMoveNode(ChildAssociationRef oldChildAssocRef,
      ChildAssociationRef newChildAssocRef) 
{
   NodeRef oldParent = oldChildAssocRef.getParentRef();
   NodeRef newParent = newChildAssocRef.getParentRef();
   
   // Deny renames
   if (oldParent.equals(newParent))
   {
       QName type = nodeService.getType((oldChildAssocRef.getChildRef()));
       if (dictionaryService.isSubClass(type, SiteModel.TYPE_SITE))
       {
           throw new SiteServiceException("Sites can not be renamed.");
       }
       else
       {
           throw new SiteServiceException("Site containers can not be renamed.");
       }
   }
}
 
Example 13
Project: alfresco-repository   File: PermissionModelTest.java   6 votes vote down vote up
public void testRequiredPermissions()
{
    Set<PermissionReference> required = permissionModelDAO.getRequiredPermissions(SimplePermissionReference.getPermissionReference(QName.createQName("sys", "base",
            namespacePrefixResolver), "Read"), QName.createQName("sys", "base", namespacePrefixResolver), Collections.<QName> emptySet(), On.NODE);
    assertEquals(3, required.size());

    required = permissionModelDAO.getRequiredPermissions(SimplePermissionReference.getPermissionReference(QName.createQName("sys", "base", namespacePrefixResolver),
            "ReadContent"), QName.createQName("sys", "base", namespacePrefixResolver), Collections.<QName> emptySet(), On.NODE);
    assertEquals(1, required.size());

    required = permissionModelDAO.getRequiredPermissions(SimplePermissionReference.getPermissionReference(QName.createQName("sys", "base", namespacePrefixResolver),
            "_ReadContent"), QName.createQName("sys", "base", namespacePrefixResolver), Collections.<QName> emptySet(), On.NODE);
    assertEquals(0, required.size());

    required = permissionModelDAO.getRequiredPermissions(SimplePermissionReference.getPermissionReference(QName.createQName("cm", "cmobject", namespacePrefixResolver),
            "Coordinator"), QName.createQName("cm", "cmobject", namespacePrefixResolver), Collections.<QName> emptySet(), On.NODE);
    assertEquals(17, required.size());

    required = permissionModelDAO.getRequiredPermissions(SimplePermissionReference.getPermissionReference(QName.createQName("sys", "base", namespacePrefixResolver),
            "FullControl"), QName.createQName("sys", "base", namespacePrefixResolver), Collections.<QName> emptySet(), On.NODE);
    assertEquals(17, required.size());

}
 
Example 14
Project: alfresco-repository   File: DWGMetadataExtracterTest.java   6 votes vote down vote up
/**
 * We also provide the creation date - check that
 */
protected void testFileSpecificMetadata(String mimetype,
      Map<QName, Serializable> properties) 
{
   // Check for extra fields
   assertEquals(
         "Property " + ContentModel.PROP_AUTHOR + " not found for mimetype " + mimetype,
         "Nevin Nollop",
         DefaultTypeConverter.INSTANCE.convert(String.class, properties.get(ContentModel.PROP_AUTHOR)));
   
   // Ensure that we can also get things which are standard
   //  Tika metadata properties, if we so choose to
   assertTrue( 
         "Test Property " + TIKA_LAST_AUTHOR_TEST_PROPERTY + " not found for mimetype " + mimetype,
         properties.containsKey(TIKA_LAST_AUTHOR_TEST_PROPERTY)
   );
   assertEquals(
         "Test Property " + TIKA_LAST_AUTHOR_TEST_PROPERTY + " incorrect for mimetype " + mimetype,
         "paolon",
         DefaultTypeConverter.INSTANCE.convert(String.class, properties.get(TIKA_LAST_AUTHOR_TEST_PROPERTY)));
}
 
Example 15
Project: alfresco-repository   File: MultiTDemoTest.java   6 votes vote down vote up
private NodeRef createFolderNode(NodeRef parentFolderNodeRef, String nameValue)
{
    if (nameValue != null)
    {       
        Map<QName, Serializable> folderProps = new HashMap<QName, Serializable>();
        folderProps.put(ContentModel.PROP_NAME, nameValue);
        
        return this.nodeService.createNode(
                parentFolderNodeRef, 
                ContentModel.ASSOC_CONTAINS, 
                QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, nameValue),
                ContentModel.TYPE_FOLDER,
                folderProps).getChildRef();
    }
    
    return null;
}
 
Example 16
Project: alfresco-repository   File: NodeDAOImpl.java   6 votes vote down vote up
@Override
protected void selectChildAssocsByPropertyValue(Long parentNodeId,
        QName propertyQName, 
        NodePropertyValue nodeValue,
        ChildAssocRefQueryCallback resultsCallback)
{
    ChildPropertyEntity assocProp = new ChildPropertyEntity();
    // Parent
    assocProp.setParentNodeId(parentNodeId);
    // Property name
    Pair<Long,QName> propName = qnameDAO.getQName(propertyQName);
    if (propName == null)
    {
        resultsCallback.done();
        return;
    }
    
    // Property
    assocProp.setValue(nodeValue);
    assocProp.setPropertyQNameId(propName.getFirst());

    ChildAssocResultHandler resultHandler = new ChildAssocResultHandler(resultsCallback);
    template.select(SELECT_CHILD_ASSOCS_BY_PROPERTY_VALUE, assocProp, resultHandler);
    resultsCallback.done();
}
 
Example 17
Project: alfresco-repository   File: IntegrityEventTest.java   5 votes vote down vote up
public void setUp() throws Exception
{
    nodeRef = new NodeRef("workspace://protocol/ID123");
    typeQName = QName.createQName(NAMESPACE, "SomeTypeQName");
    qname = QName.createQName(NAMESPACE, "qname");
    
    event = new TestIntegrityEvent(null, null, nodeRef, typeQName, qname);
}
 
Example 18
Project: alfresco-repository   File: AssocTargetRoleIntegrityEvent.java   5 votes vote down vote up
public AssocTargetRoleIntegrityEvent(
        NodeService nodeService,
        DictionaryService dictionaryService,
        NodeRef sourceNodeRef,
        QName assocTypeQName,
        QName assocName)
{
    super(nodeService, dictionaryService, sourceNodeRef, assocTypeQName, assocName);
}
 
Example 19
Project: alfresco-repository   File: GetChildrenCannedQuery.java   5 votes vote down vote up
protected boolean includeImpl(boolean ret, NodeRef nodeRef)
{
    // only visible files are returned, relative to the client type.
    try
    {
        if (!nodeService.exists(nodeRef))
        {
            // Node has disappeared
            return ret;
        }
        
        final Client client = FileFilterMode.getClient();
        boolean notHidden = hiddenAspect.getVisibility(client, nodeRef) != Visibility.NotVisible;
        
        boolean notIgnore = true;
        if (ignoreAspectQNames != null)
        {
            if (ignoreAspectQNames.size() > 1)
            {
                Set<QName> nodeAspects = nodeService.getAspects(nodeRef);
                notIgnore = (! nodeAspects.removeAll(ignoreAspectQNames));
            }
            else if (ignoreAspectQNames.size() == 1)
            {
                if (nodeService.hasAspect(nodeRef, ignoreAspectQNames.iterator().next()))
                {
                    notIgnore = false;
                }
            }
        }
        
        return ret && notHidden && notIgnore;
    }
    catch (AccessDeniedException e)
    {
        // user may not have permission to determine the visibility of the node
        return ret;
    }
}
 
Example 20
Project: alfresco-data-model   File: DictionaryDAOImpl.java   5 votes vote down vote up
@Override
public AspectDefinition getAspect(QName aspectName)
{
    AspectDefinition aspectDef = null;

    if (aspectName != null)
    {
        aspectDef = getTenantDictionaryRegistry().getAspect(aspectName);
    }

    return aspectDef;
}
 
Example 21
Project: alfresco-repository   File: ForumEmailMessageHandler.java   5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void processMessage(NodeRef nodeRef, EmailMessage message)
{
    String messageSubject;

    if (message.getSubject() != null)
    {
        messageSubject = message.getSubject();
    }
    else
    {
        messageSubject = "EMPTY_SUBJECT_" + System.currentTimeMillis();
    }

    QName nodeTypeQName = getNodeService().getType(nodeRef);

    if (getDictionaryService().isSubClass(nodeTypeQName, ForumModel.TYPE_FORUM))
    {
        NodeRef topicNode = getTopicNode(nodeRef, messageSubject);

        if (topicNode == null)
        {
            topicNode = addTopicNode(nodeRef, messageSubject);
        }
        addPostNode(topicNode, message);
    }
    else
    {
        throw new AlfrescoRuntimeException("\n" +
                "Message handler " + this.getClass().getName() + " cannot handle type " + nodeTypeQName + ".\n" +
                "Check the message handler mappings.");
    }
}
 
Example 22
Project: alfresco-solrclient   File: SOLRAPIClient.java   5 votes vote down vote up
public AlfrescoModel getModel(String coreName, QName modelName) throws AuthenticationException, IOException, JSONException
{
    // If the model is new to the SOLR side the prefix will be unknown so we can not generate prefixes for the request!
    // Always use the full QName with explicit URI
    StringBuilder url = new StringBuilder(GET_MODEL);

    URLCodec encoder = new URLCodec();
    // must send the long name as we may not have the prefix registered
    url.append("?modelQName=").append(encoder.encode(modelName.toString(), "UTF-8"));
    
    GetRequest req = new GetRequest(url.toString());

    Response response = null;
    try
    {
        response = repositoryHttpClient.sendRequest(req);
        if(response.getStatus() != HttpStatus.SC_OK)
        {
            throw new AlfrescoRuntimeException(coreName + " GetModel return status is " + response.getStatus());
        }

        return new AlfrescoModel(M2Model.createModel(response.getContentAsStream()),
                Long.valueOf(response.getHeader(CHECKSUM_HEADER)));
    }
    finally
    {
        if(response != null)
        {
            response.release();
        }
    }
}
 
Example 23
Project: alfresco-repository   File: NodeDAOImpl.java   5 votes vote down vote up
@Override
public Pair<Long, Long> getNodeIdsIntervalForType(QName type, Long startTxnTime, Long endTxnTime)
{
    final Pair<Long, Long> intervalPair = new Pair<Long, Long>(LONG_ZERO, LONG_ZERO);
    Pair<Long, QName> typePair = qnameDAO.getQName(type);
    if (typePair == null)
    {
        // Return default
        return intervalPair;
    }
    TransactionQueryEntity txnQuery = new TransactionQueryEntity();
    txnQuery.setTypeQNameId(typePair.getFirst());
    txnQuery.setMinCommitTime(startTxnTime);
    txnQuery.setMaxCommitTime(endTxnTime);
    
    ResultHandler resultHandler = new ResultHandler()
    {
        @SuppressWarnings("unchecked")
        public void handleResult(ResultContext context)
        {
            Map<Long, Long> result = (Map<Long, Long>) context.getResultObject();
            if (result != null)
            {
                intervalPair.setFirst(result.get("minId"));
                intervalPair.setSecond(result.get("maxId"));
            }
        }
    };
    template.select(SELECT_NODE_INTERVAL_BY_TYPE, txnQuery, resultHandler);
    return intervalPair;
}
 
Example 24
Project: alfresco-repository   File: XSLTRenderingEngineTest.java   5 votes vote down vote up
public void testParseXMLDocument() throws Exception
{
    try
    {
        FileInfo file = createXmlFile(companyHome);
        createXmlFile(companyHome, "TestXML.xml", sampleXML);
        FileInfo xslFile = createXmlFile(companyHome, callParseXmlDocument);

        RenditionDefinition def = renditionService.createRenditionDefinition(QName.createQName("Test"), XSLTRenderingEngine.NAME);
        def.setParameterValue(XSLTRenderingEngine.PARAM_TEMPLATE_NODE, xslFile.getNodeRef());

        ChildAssociationRef rendition = renditionService.render(file.getNodeRef(), def);
        
        assertNotNull(rendition);
        
        ContentReader reader = contentService.getReader(rendition.getChildRef(), ContentModel.PROP_CONTENT);
        assertNotNull(reader);
        String output = reader.getContentString();
        
        log.debug("XSLT Processor output: " + output);
        assertEquals("Avocado DipBagels, New York StyleBeef Frankfurter, Quarter PoundChicken Pot PieCole SlawEggsHazelnut SpreadPotato ChipsSoy Patties, GrilledTruffles, Dark Chocolate", output);
    }
    catch (Exception ex)
    {
        log.error("Error!", ex);
        fail();
    }
}
 
Example 25
Project: alfresco-repository   File: SiteServiceImpl.java   5 votes vote down vote up
@Override
public void beforePurgeNode(NodeRef nodeRef)
{
    final QName siteType = this.directNodeService.getType(nodeRef);
    final String shortName = getSite(nodeRef).getShortName();
    
    // Delete the associated groups
    AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>()
    {
        public Void doWork() throws Exception
        {
            // Delete the master site group
            final String siteGroup = getSiteGroup(shortName, true);
            if (authorityService.authorityExists(siteGroup))
            {
                authorityService.deleteAuthority(siteGroup, false);

                // Iterate over the role related groups and delete then
                Set<String> permissions = permissionService.getSettablePermissions(siteType);
                for (String permission : permissions)
                {
                    String siteRoleGroup = getSiteRoleGroup(shortName, permission, true);

                    // Delete the site role group
                    authorityService.deleteAuthority(siteRoleGroup);
                }
            }

            return null;
        }
    }, AuthenticationUtil.getSystemUserName());

}
 
Example 26
Project: alfresco-repository   File: ContentModelItemData.java   5 votes vote down vote up
public ContentModelItemData(ItemType item,
            Map<QName, PropertyDefinition> propDefs,
            Map<QName, AssociationDefinition> assocDefs,
            Map<QName, Serializable> propValues,
            Map<QName, Serializable> assocValues,
            Map<String, Object> transientValues)
{
    this.item = item;
    this.propDefs = propDefs;
    this.assocDefs = assocDefs;
    this.propValues = propValues;
    this.assocValues = assocValues;
    this.transientValues = transientValues;
}
 
Example 27
Project: alfresco-repository   File: AbstractRenderingEngine.java   5 votes vote down vote up
private ChildAssociationRef createRenditionNodeAssoc(NodeRef sourceNode, RenditionDefinition renditionDefinition)
{
    QName renditionName = renditionDefinition.getRenditionName();

    // The ThumbnailService puts a cm:name property on its thumbnail nodes.
    Map<QName, Serializable> nodeProps = new HashMap<QName, Serializable>();
    nodeProps.put(ContentModel.PROP_NAME, renditionName.getLocalName());
    nodeProps.put(ContentModel.PROP_CONTENT_PROPERTY_NAME, getRenditionContentProp(renditionDefinition));
    QName assocName = QName.createQName(NamespaceService.RENDITION_MODEL_1_0_URI, GUID.generate());
    NodeRef parentNode = renditionDefinition.getRenditionParent();
    QName assocType = renditionDefinition.getRenditionAssociationType();
    QName nodeType = getRenditionNodeType(renditionDefinition);
    
    // Ensure that the creation of rendition children does not cause updates
    // to the modified, modifier properties on the source node
    behaviourFilter.disableBehaviour(parentNode, ContentModel.ASPECT_AUDITABLE);
    ChildAssociationRef childAssoc = null;
    try
    {
        childAssoc = nodeService.createNode(parentNode, assocType, assocName, nodeType, nodeProps);
        if (logger.isDebugEnabled())
        {
            logger.debug("Created node " + childAssoc + " as child of " + parentNode + " with assoc-type " + assocType);
        }
    }
    finally
    {
        behaviourFilter.enableBehaviour(parentNode, ContentModel.ASPECT_AUDITABLE);
    }
    return childAssoc;
}
 
Example 28
Project: alfresco-repository   File: MultiTDemoTest.java   5 votes vote down vote up
public void test14GetProperty()
{
    logger.info("Test get property");
    
    for (final String tenantDomain : tenants)
    {
        String tenantAdminName = tenantService.getDomainUser(AuthenticationUtil.getAdminUserName(), tenantDomain);
        TenantUtil.runAsUserTenant(new TenantRunAsWork<Object>()
        {
            public Object doWork() throws Exception
            {
                NodeRef personNodeRef = createUser(TEST_USER4, tenantDomain, TEST_USER4+" "+tenantDomain);
                
                // Test nodeRef property
                NodeRef homeFolderNodeRef = (NodeRef)nodeService.getProperty(personNodeRef, ContentModel.PROP_HOMEFOLDER);
                assertFalse(homeFolderNodeRef.toString().contains(tenantDomain));
                
                Map<QName, Serializable> props = nodeService.getProperties(personNodeRef);
                assertFalse(props.get(ContentModel.PROP_HOMEFOLDER).toString().contains(tenantDomain));
                
                // Test "store-identifier" property
                String storeId = (String)nodeService.getProperty(personNodeRef, ContentModel.PROP_STORE_IDENTIFIER);
                assertFalse(storeId.contains(tenantDomain));
                
                assertFalse(props.get(ContentModel.PROP_STORE_IDENTIFIER).toString().contains(tenantDomain));
                
                return null;
            }
        }, tenantAdminName, tenantDomain);
    }
}
 
Example 29
Project: alfresco-repository   File: FileFolderServiceImpl.java   5 votes vote down vote up
@Override
public PagingResults<FileInfo> list(NodeRef rootNodeRef,
                                    Set<QName> assocTypeQNames,
                                    Set<QName> searchTypeQNames,
                                    Set<QName> ignoreAspectQNames,
                                    List<Pair<QName, Boolean>> sortProps,
                                    List<FilterProp> filterProps,
                                    PagingRequest pagingRequest)
{
    CannedQueryResults<NodeRef> results = listImpl(rootNodeRef, null,  assocTypeQNames, searchTypeQNames, ignoreAspectQNames, sortProps, filterProps, pagingRequest);
    return getPagingResults(pagingRequest, results);
}
 
Example 30
Project: alfresco-repository   File: DisableAuditableBehaviourInterceptor.java   5 votes vote down vote up
public void setArgumentValues(List<String> argumentValues)
{
    this.argumentQNameValues = new HashSet<QName>(argumentValues.size()*2+1);
    for (String argumentValue : argumentValues)
    {
        QName argumentQNameValue = QName.createQName(argumentValue);
        argumentQNameValues.add(argumentQNameValue);
    }
}
 
Example 31
Project: alfresco-repository   File: CopyServiceImplTest.java   5 votes vote down vote up
/**
 * https://issues.alfresco.com/jira/browse/ALF-17549
 */
public void testALF17549() throws Exception
{
    permissionService.setPermission(rootNodeRef, USER_1, PermissionService.COORDINATOR, true);

    AuthenticationUtil.setRunAsUser(USER_1);

    String sourceName = "sourceNode.txt";
    Map<QName, Serializable> props = new HashMap<QName, Serializable>();

    props.put(ContentModel.PROP_NAME, sourceName);

    NodeRef sourceNodeRef = nodeService.createNode(this.rootNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName("{test}" + sourceName), ContentModel.TYPE_CONTENT, props)
            .getChildRef();

    ContentWriter writer = contentService.getWriter(sourceNodeRef, ContentModel.PROP_CONTENT, true);
    writer.setEncoding("UTF-8");
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    writer.putContent("This is sample text content for unit test.");

    NodeRef targetNodeRef = nodeService.createNode(this.rootNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName("{test}targetNode"), ContentModel.TYPE_FOLDER)
            .getChildRef();

    List<ChildAssociationRef> childAssoc = nodeService.getChildAssocs(targetNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName("{test}sourceNode.html"));

    assertEquals(0, childAssoc.size());

    Action action = this.actionService.createAction(TransformActionExecuter.NAME);

    action.setParameterValue(TransformActionExecuter.PARAM_MIME_TYPE, MimetypeMap.MIMETYPE_HTML);
    action.setParameterValue(TransformActionExecuter.PARAM_DESTINATION_FOLDER, targetNodeRef);
    action.setParameterValue(TransformActionExecuter.PARAM_ASSOC_QNAME, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "copy"));
    action.setParameterValue(TransformActionExecuter.PARAM_ASSOC_TYPE_QNAME, ContentModel.ASSOC_CONTAINS);
    actionService.executeAction(action, sourceNodeRef);

    childAssoc = nodeService.getChildAssocs(targetNodeRef, ContentModel.ASSOC_CONTAINS, QName.createQName("{test}sourceNode.html"));

    assertEquals(1, childAssoc.size());
}
 
Example 32
Project: alfresco-remote-api   File: AbstractWorkflowRestApiTest.java   5 votes vote down vote up
public void testWorkflowInstanceDeleteAsAdministrator() throws Exception
{
    //Start workflow as USER1 
    personManager.setUser(USER1);
    WorkflowDefinition adhocDef = workflowService.getDefinitionByName(getAdhocWorkflowDefinitionName());
    Map<QName, Serializable> params = new HashMap<QName, Serializable>();
    params.put(WorkflowModel.ASSOC_ASSIGNEE, personManager.get(USER2));
    Date dueDate = new Date();
    params.put(WorkflowModel.PROP_DUE_DATE, dueDate);
    params.put(WorkflowModel.PROP_PRIORITY, 1);
    params.put(WorkflowModel.ASSOC_PACKAGE, packageRef);
    params.put(WorkflowModel.PROP_CONTEXT, packageRef);

    WorkflowPath adhocPath = workflowService.startWorkflow(adhocDef.getId(), params);
    WorkflowTask startTask = workflowService.getTasksForWorkflowPath(adhocPath.getId()).get(0);
    startTask = workflowService.endTask(startTask.getId(), null);

    WorkflowInstance adhocInstance = startTask.getPath().getInstance();
    
    // Run next request as admin
    String admin = authenticationComponent.getDefaultAdministratorUserNames().iterator().next();
    AuthenticationUtil.setFullyAuthenticatedUser(admin);
    
    sendRequest(new DeleteRequest(URL_WORKFLOW_INSTANCES + "/" + adhocInstance.getId()), Status.STATUS_OK);

    WorkflowInstance instance = workflowService.getWorkflowById(adhocInstance.getId());
    if (instance != null)
    {
        assertFalse("The deleted workflow is still active!", instance.isActive());
    }
    
    List<WorkflowInstance> instances = workflowService.getActiveWorkflows(adhocInstance.getDefinition().getId());
    for (WorkflowInstance activeInstance : instances)
    {
        assertFalse(adhocInstance.getId().equals(activeInstance.getId()));
    }
}
 
Example 33
Project: alfresco-repository   File: DictionaryModelType.java   5 votes vote down vote up
/**
 * On update properties behaviour implementation
 * 
 * @param nodeRef   the node reference
 * @param before    the values of the properties before update
 * @param after     the values of the properties after the update
 */
public void onUpdateProperties(
        NodeRef nodeRef,
        Map<QName, Serializable> before,
        Map<QName, Serializable> after)
{
    if (logger.isTraceEnabled())
    {
        logger.trace("onUpdateProperties: nodeRef="+nodeRef+ " ["+AlfrescoTransactionSupport.getTransactionId()+"]");
    }
    
    Boolean beforeValue = (Boolean)before.get(ContentModel.PROP_MODEL_ACTIVE);
    Boolean afterValue = (Boolean)after.get(ContentModel.PROP_MODEL_ACTIVE);
    
    if (beforeValue == null && afterValue != null)
    {
        queueModel(nodeRef);
    }
    else if (afterValue == null && beforeValue != null)
    {
        // Remove the model since the value has been cleared
        queueModel(nodeRef);
    }
    else if (beforeValue != null && afterValue != null && beforeValue.equals(afterValue) == false)
    {
        queueModel(nodeRef);
    }
}
 
Example 34
Project: alfresco-repository   File: DictionaryModelType.java   5 votes vote down vote up
public void onRemoveAspect(NodeRef nodeRef, QName aspect)
{
    if (logger.isTraceEnabled())
    {
        logger.trace("onRemoveAspect: nodeRef="+nodeRef+ " ["+AlfrescoTransactionSupport.getTransactionId()+"]");
    }
    
    // undo/cancel checkout removes the "workingcopy" aspect prior to deleting the node - hence need to track here
    if (aspect.equals(ContentModel.ASPECT_WORKING_COPY))
    {
        AlfrescoTransactionSupport.bindResource(KEY_WORKING_COPY, nodeRef);
    }
}
 
Example 35
Project: alfresco-repository   File: HeartBeatJobTest.java   5 votes vote down vote up
@Test
public void testJobLocking() throws Exception
{
    HBBaseDataCollector simpleCollector = mock(HBBaseDataCollector.class);
    when(simpleCollector.getCollectorId()).thenReturn("c1");
    when(simpleCollector.getCronExpression()).thenReturn("0 0 0 ? * *");

    // mock the job context
    JobExecutionContext mockJobExecutionContext = mock(JobExecutionContext.class);
    JobDetail jobDetail = new JobDetail();
    when(mockJobExecutionContext.getJobDetail()).thenReturn(jobDetail);

    JobDataMap jobDataMap = new JobDataMap();
    jobDataMap.put("collector", simpleCollector);
    jobDataMap.put("hbDataSenderService", mockDataSenderService);
    jobDataMap.put("jobLockService", mockJobLockService);
    jobDetail.setJobDataMap(jobDataMap);

    // Simulate job lock service
    String lockToken = "token";
    when(mockJobLockService.getLock(isA(QName.class), anyLong()))
            .thenReturn(lockToken)                                    // first job gets the lock
            .thenThrow(new LockAcquisitionException("", ""));         // second job doesn't get the lock

    // Run two heart beat jobs
    new HeartBeatJob().execute(mockJobExecutionContext);
    new HeartBeatJob().execute(mockJobExecutionContext);

    // Verify that the collector only collects data once, since only one job got the lock
    verify(simpleCollector, Mockito.times(1)).collectData();
    // Verify that data was passed to data sender
    verify(mockDataSenderService, Mockito.times(1)).sendData(any(List.class));
    verify(mockDataSenderService, Mockito.times(0)).sendData(any(HBData.class));
    // Verify that both jobs tried to get the lock
    verify(mockJobLockService, Mockito.times(2)).getLock(any(QName.class), anyLong());
    // Verify that a callback was registered once
    verify(mockJobLockService, Mockito.times(1)).refreshLock(eq(lockToken), any(QName.class),
            anyLong(),
            any(JobLockService.JobLockRefreshCallback.class));
}
 
Example 36
Project: alfresco-repository   File: RenditionServiceIntegrationTest.java   5 votes vote down vote up
private CompositeRenditionDefinition makeCompositeReformatAndResizeDefinition(final QName renditionName,
            final int newX, final int newY)
{
    CompositeRenditionDefinition compositeDefinition = renditionService
                .createCompositeRenditionDefinition(renditionName);
    RenditionDefinition reformatDefinition = makeReformatAction(null, MimetypeMap.MIMETYPE_IMAGE_JPEG);
    RenditionDefinition rescaleImageDefinition = makeRescaleImageAction();
    rescaleImageDefinition.setParameterValue(ImageRenderingEngine.PARAM_RESIZE_WIDTH, newX);
    rescaleImageDefinition.setParameterValue(ImageRenderingEngine.PARAM_RESIZE_HEIGHT, newY);

    compositeDefinition.addAction(reformatDefinition);
    compositeDefinition.addAction(rescaleImageDefinition);
    return compositeDefinition;
}
 
Example 37
Project: alfresco-repository   File: TransferManifestNormalNode.java   5 votes vote down vote up
public void setType(QName type)
{
    this.type = type;
    if (ancestorType == null)
    {
        ancestorType = type;
    }
}
 
Example 38
Project: alfresco-repository   File: AbstractQNameDAOImpl.java   5 votes vote down vote up
public Pair<Long, QName> getQName(final QName qname)
{
    if (qname == null)
    {
        throw new IllegalArgumentException("QName cannot be null");
    }
    Pair<Long, QName> entityPair = qnameCache.getByValue(qname);
    return entityPair;
}
 
Example 39
Project: alfresco-data-model   File: DelegateModelQuery.java   5 votes vote down vote up
public PropertyDefinition getProperty(QName name)
{
    PropertyDefinition def = query.getProperty(name);
    if (def == null)
    {
        def = delegate.getProperty(name);
    }
    return def;
}
 
Example 40
Project: alfresco-repository   File: ScriptServiceImpl.java   5 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.repository.ScriptService#executeScript(java.lang.String, org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.namespace.QName, java.util.Map)
 */
public Object executeScript(String engine, NodeRef scriptRef, QName contentProp, Map<String, Object> model)
    throws ScriptException
{
    ScriptProcessor scriptProcessor = lookupScriptProcessor(engine);
    return execute(scriptProcessor, scriptRef, contentProp, model);
}
 
Example 41
Project: alfresco-data-model   File: DictionaryDAOTest.java   5 votes vote down vote up
@Test
public void testConstraintsOverrideInheritance()
{
    QName baseQName = QName.createQName(TEST_URL, "base");
    QName fileQName = QName.createQName(TEST_URL, "file");
    QName folderQName = QName.createQName(TEST_URL, "folder");
    QName prop1QName = QName.createQName(TEST_URL, "prop1");

    // get the base property
    PropertyDefinition prop1Def = service.getProperty(baseQName, prop1QName);
    assertNotNull(prop1Def);
    List<ConstraintDefinition> prop1Constraints = prop1Def.getConstraints();
    assertEquals("Incorrect number of constraints", 3, prop1Constraints.size());
    assertTrue("Constraint instance incorrect", prop1Constraints.get(0).getConstraint() instanceof RegexConstraint);
    assertTrue("Constraint instance incorrect", prop1Constraints.get(1).getConstraint() instanceof StringLengthConstraint);
    assertTrue("Constraint instance incorrect", prop1Constraints.get(2).getConstraint() instanceof RegisteredConstraint);

    // check the inherited property on folder (must be same as above)
    prop1Def = service.getProperty(folderQName, prop1QName);
    assertNotNull(prop1Def);
    prop1Constraints = prop1Def.getConstraints();
    assertEquals("Incorrect number of constraints", 3, prop1Constraints.size());
    assertTrue("Constraint instance incorrect", prop1Constraints.get(0).getConstraint() instanceof RegexConstraint);
    assertTrue("Constraint instance incorrect", prop1Constraints.get(1).getConstraint() instanceof StringLengthConstraint);
    assertTrue("Constraint instance incorrect", prop1Constraints.get(2).getConstraint() instanceof RegisteredConstraint);

    // check the overridden property on file (must be reverse of above)
    prop1Def = service.getProperty(fileQName, prop1QName);
    assertNotNull(prop1Def);
    prop1Constraints = prop1Def.getConstraints();
    assertEquals("Incorrect number of constraints", 3, prop1Constraints.size());
    assertTrue("Constraint instance incorrect", prop1Constraints.get(0).getConstraint() instanceof StringLengthConstraint);
    assertTrue("Constraint instance incorrect", prop1Constraints.get(1).getConstraint() instanceof RegexConstraint);
    assertTrue("Constraint instance incorrect", prop1Constraints.get(2).getConstraint() instanceof RegisteredConstraint);
}
 
Example 42
Project: alfresco-repository   File: WorkflowBuilder.java   5 votes vote down vote up
public void addAssociationParameter(QName name, List<NodeRef> values)
{
    if (values instanceof Serializable)
    {
        params.put(name, (Serializable) values);
    }
}
 
Example 43
Project: alfresco-repository   File: NodeServiceTest.java   5 votes vote down vote up
private NodeRef setupTestGetChildren(final NodeRef workspaceRootNodeRef, final int numberOfReferences)
{
    RetryingTransactionCallback<NodeRef> setupCallback = new RetryingTransactionCallback<NodeRef>()
    {
        @Override
        public NodeRef execute() throws Throwable
        {
            NodeRef[] referenceNodeRefs = new NodeRef[numberOfReferences];
            // Create one folder
            Map<QName, Serializable> folderProps = new HashMap<QName, Serializable>(3);
            folderProps.put(ContentModel.PROP_NAME, "folder-" + GUID.generate());
            NodeRef folderNodeRef = nodeService.createNode(
                    workspaceRootNodeRef,
                    ContentModel.ASSOC_CHILDREN,
                    QName.createQName(NAMESPACE, "folder"),
                    ContentModel.TYPE_FOLDER,
                    folderProps).getChildRef();

            // Create some content
            for (int i = 0; i < numberOfReferences; i++)
            {
                Map<QName, Serializable> props = new HashMap<QName, Serializable>(3);
                props.put(ContentModel.PROP_NAME, "reference-" + GUID.generate());
                referenceNodeRefs[i] = nodeService.createNode(
                        folderNodeRef,
                        ContentModel.ASSOC_CONTAINS,
                        QName.createQName(NAMESPACE, "reference"),
                        ContentModel.TYPE_RATING,
                        props).getChildRef();
            }
            return folderNodeRef;
        }
    };
    return txnService.getRetryingTransactionHelper().doInTransaction(setupCallback);
}
 
Example 44
Project: alfresco-repository   File: ActionServiceImpl.java   5 votes vote down vote up
/**
 * Ensures that <b>d:noderef</b> properties are repointed if the target was
 * also copied as part of the hierarchy.
 */
public void onCopyComplete(QName classRef, NodeRef sourceNodeRef, NodeRef targetNodeRef, boolean copyToNewNode,
            Map<NodeRef, NodeRef> copyMap)
{
    ActionParameterTypeCopyBehaviourCallback.INSTANCE.repointNodeRefs(sourceNodeRef, targetNodeRef,
                ActionModel.PROP_PARAMETER_VALUE, copyMap, nodeService);
}
 
Example 45
Project: alfresco-repository   File: AbstractQNameDAOImpl.java   5 votes vote down vote up
/**
 * @return      Returns a set of IDs mapping to the QNames provided.  If create is <tt>false</tt>
 *              then there will not be corresponding entries for the QNames that don't exist.
 *              So there is no guarantee that the returned set will be ordered the same or even
 *              contain the same number of elements as the original unless create is <tt>true</tt>.
 */
public Set<Long> convertQNamesToIds(Set<QName> qnames, boolean create)
{
    Set<Long> qnameIds = new HashSet<Long>(qnames.size(), 1.0F);
    for (QName qname : qnames)
    {
        Long qnameEntityId = null;
        if (create)
        {
            qnameEntityId = getOrCreateQName(qname).getFirst();     // getOrCreateQName(qname) is never null
        }
        else
        {
            Pair<Long, QName> qnamePair = getQName(qname);
            if (qnamePair == null)
            {
                // No such qname and we are not creating one
                continue;
            }
            else
            {
                qnameEntityId = qnamePair.getFirst();
            }
        }
        if (qnameEntityId != null)
        {
            qnameIds.add(qnameEntityId);
        }
    }
    // Done
    return qnameIds;
}
 
Example 46
Project: alfresco-repository   File: AbstractIntegrityEvent.java   5 votes vote down vote up
/**
 * Gets the node type if the node exists
 * 
 * @param nodeRef NodeRef
 * @return Returns the node's type or null if the node no longer exists
 */
protected QName getNodeType(NodeRef nodeRef)
{
    try
    {
        return nodeService.getType(nodeRef);
    }
    catch (InvalidNodeRefException e)
    {
        // node has disappeared
        return null;
    }
}
 
Example 47
Project: alfresco-repository   File: JobLockServiceImpl.java   5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void releaseLock(final String lockToken, final QName lockQName)
{
    RetryingTransactionCallback<Boolean> releaseCallback = new RetryingTransactionCallback<Boolean>()
    {
        public Boolean execute() throws Throwable
        {
            return lockDAO.releaseLock(lockQName, lockToken, false);
        }
    };
    retryingTransactionHelper.doInTransaction(releaseCallback, false, true);
}
 
Example 48
Project: alfresco-repository   File: ThumbnailServiceImpl.java   5 votes vote down vote up
private QName getThumbnailQName(String localThumbnailName)
{
    if (localThumbnailName == null || localThumbnailName.length() == 0)
    {
        localThumbnailName = GUID.generate();
    }
    
    // We're prepending the cm namespace here.
    QName thumbnailQName = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, localThumbnailName);
    return thumbnailQName;
}
 
Example 49
Project: alfresco-remote-api   File: NodesImpl.java   5 votes vote down vote up
private void setCommonProps(Node node, NodeRef nodeRef, Map<QName,Serializable> properties)
{
    node.setGuid(nodeRef);
    node.setTitle((String)properties.get(ContentModel.PROP_TITLE));
    node.setDescription((String)properties.get(ContentModel.PROP_DESCRIPTION));
    node.setModifiedBy((String)properties.get(ContentModel.PROP_MODIFIER));
    node.setCreatedBy((String)properties.get(ContentModel.PROP_CREATOR));
}
 
Example 50
Project: alfresco-repository   File: UndeletableAspect.java   5 votes vote down vote up
/**
* Ensures that undeletable nodes cannot be deleted by default.
*/
@Override
public void beforeDeleteNode(NodeRef nodeRef)
{
    QName nodeType = nodeService.getType(nodeRef);
    throw new AlfrescoRuntimeException(nodeType.toPrefixString() + " deletion is not allowed. Attempted to delete " + nodeRef);
}
 
Example 51
Project: alfresco-remote-api   File: CustomModelsImpl.java   4 votes vote down vote up
private void validateTypeAspectParent(AbstractClassModel typeAspect, CustomModel existingModel)
{
    String parentPrefixedName = typeAspect.getParentName();
    if (StringUtils.isBlank(parentPrefixedName))
    {
        return;
    }

    Pair<String, String> prefixLocaNamePair = splitPrefixedQName(parentPrefixedName);
    String parentPrefix = prefixLocaNamePair.getFirst();
    String parentLocalName = prefixLocaNamePair.getSecond();

    // Validate parent prefix and localName
    // We know that the values are not null, we just check against the defined RegEx
    validateName(parentPrefix, null);
    validateName(parentLocalName, null);

    final boolean isAspect = (typeAspect instanceof CustomAspect);
    ClassDefinition classDefinition = null;
    QName qname = null;
    if (existingModel.getNamespacePrefix().equals(parentPrefix))
    {
        // Check for types/aspects within the model
        qname = QName.createQName(existingModel.getNamespaceUri(), parentLocalName);
        classDefinition = (isAspect) ? customModelService.getCustomAspect(qname) : customModelService.getCustomType(qname);
    }
    else
    {
        // Make sure the namespace URI and Prefix are registered
        Pair<String, String> uriPrefixPair = resolveToUriAndPrefix(parentPrefixedName);

        qname = QName.createQName(uriPrefixPair.getFirst(), parentLocalName);
        classDefinition = (isAspect) ? dictionaryService.getAspect(qname) : dictionaryService.getType(qname);
    }

    if (classDefinition == null)
    {
        String msgId = (isAspect) ? "cmm.rest_api.aspect_parent_not_exist" : "cmm.rest_api.type_parent_not_exist";
        throw new ConstraintViolatedException(I18NUtil.getMessage(msgId, parentPrefixedName));
    }
    else
    {
        checkCircularDependency(classDefinition.getModel(), existingModel, parentPrefixedName);
    }
}
 
Example 52
Project: alfresco-repository   File: ADMLuceneIndexerImpl.java   4 votes vote down vote up
public void detectNodeChanges(NodeRef nodeRef, SearchService searcher,
        Collection<ChildAssociationRef> addedParents, Collection<ChildAssociationRef> deletedParents,
        Collection<ChildAssociationRef> createdNodes, Collection<NodeRef> updatedNodes) throws LuceneIndexException
{
    boolean nodeExisted = false;
    boolean relationshipsChanged = false;
    
    ResultSet results = null;
    SearchParameters sp = new SearchParameters();
    sp.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp.addStore(nodeRef.getStoreRef());
    try
    {
        sp.setQuery("ID:" + SearchLanguageConversion.escapeLuceneQuery(nodeRef.toString()));
        results = searcher.query(sp);
        for (ResultSetRow row : results)
        {
            nodeExisted = true;
            Document document = ((LuceneResultSetRow) row).getDocument();
            Field qname = document.getField("QNAME");
            if (qname == null)
            {
                continue;
            }
            Collection<Pair<ChildAssociationRef, QName>> allParents = getAllParents(nodeRef, nodeService.getProperties(nodeRef));
            Set<ChildAssociationRef> dbParents = new HashSet<ChildAssociationRef>(allParents.size() * 2);
            for (Pair<ChildAssociationRef, QName> pair : allParents)
            {
                ChildAssociationRef qNameRef = tenantService.getName(pair.getFirst());
                if ((qNameRef != null) && (qNameRef.getParentRef() != null) && (qNameRef.getQName() != null))
                {
                    dbParents.add(new ChildAssociationRef(ContentModel.ASSOC_CHILDREN, qNameRef.getParentRef(), qNameRef.getQName(), qNameRef.getChildRef()));
                }
            }
                           
            Field[] parents = document.getFields("PARENT");
            String[] qnames = qname.stringValue().split(";/");
            Set<ChildAssociationRef> addedParentsSet = new HashSet<ChildAssociationRef>(dbParents);
            for (int i=0; i<Math.min(parents.length, qnames.length); i++)
            {
                QName parentQname = QName.createQName(qnames[i]);
                parentQname = QName.createQName(parentQname.getNamespaceURI(), ISO9075.decode(parentQname.getLocalName()));
                NodeRef parentRef = new NodeRef(parents[i].stringValue());
                ChildAssociationRef indexedParent = new ChildAssociationRef(ContentModel.ASSOC_CHILDREN, parentRef, parentQname, nodeRef);
                if (!addedParentsSet.remove(indexedParent))
                {
                    deletedParents.add(indexedParent);                        
                    relationshipsChanged = true;
                }
            }
            if (addedParents.addAll(addedParentsSet))
            {
                relationshipsChanged = true;
            }

            break;
        }

        if (!nodeExisted)
        {
            createdNodes.add(nodeService.getPrimaryParent(nodeRef));
        }
        else if (!relationshipsChanged)
        {
            updatedNodes.add(nodeRef);
        }
    }
    finally
    {
        if (results != null) { results.close(); }
    }
    
}
 
Example 53
Project: alfresco-repository   File: PermissionSet.java   4 votes vote down vote up
public QName getQName()
{
    return qname;
}
 
Example 54
Project: alfresco-repository   File: FilingParameters.java   4 votes vote down vote up
public Map<QName, Serializable> getProperties()
{
    return this.properties;
}
 
Example 55
Project: alfresco-repository   File: GetChildrenCannedQueryTest.java   4 votes vote down vote up
public void testPagingGetChildrenCannedQueryWithoutProps() throws Exception
{
    try
    {
        long startTime = System.currentTimeMillis();

        int itemCount = 1500;
        int repeatListCount = 5;

        Set<QName> assocTypeQNames = new HashSet<>(1);
        assocTypeQNames.add(ContentModel.ASSOC_CONTAINS);

        Set<QName> childTypeQNames = new HashSet<>(1);
        childTypeQNames.add(ContentModel.TYPE_FOLDER);

        AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());

        NodeRef testFolder = repositoryHelper.getCompanyHome();

        NodeRef parentFolder = createFolder(testFolder, "testCreateList-"+ GUID.generate(), ContentModel.TYPE_FOLDER);

        for (int i = 1; i <= itemCount; i++)
        {
            String folderName = "folder_" + GUID.generate();
            createFolder(parentFolder, folderName, ContentModel.TYPE_FOLDER);
        }

        for (int j = 1; j <= repeatListCount; j++)
        {
            // page/iterate through the children
            boolean hasMore = true;
            int skipCount = 0;
            int maxItems = 100;

            int count = 0;
            Set<String> docIds = new HashSet<>(itemCount);

            while (hasMore)
            {
                // note: mimic similar to AlfrescoServiceCmisServiceImpl
                PagingResults<NodeRef> results = list(parentFolder, skipCount, maxItems, skipCount + 10000, assocTypeQNames, childTypeQNames, null, null, null, null);
                hasMore = results.hasMoreItems();
                skipCount = skipCount + maxItems;

                for (NodeRef nodeRef : results.getPage())
                {
                    docIds.add(nodeRef.getId());
                    count++;
                }
            }

            assertEquals(itemCount, count);
            assertEquals(itemCount, docIds.size());
        }

        System.out.println("Test time: " + (System.currentTimeMillis() - startTime) + " ms");
    } 
    finally
    {
        AuthenticationUtil.clearCurrentSecurityContext();
    }
}
 
Example 56
Project: alfresco-repository   File: CategoryService.java   4 votes vote down vote up
@Auditable(parameters = {"storeRef", "aspectQName", "depth"})
public Collection<ChildAssociationRef> getCategories(StoreRef storeRef, QName aspectQName, Depth depth );
 
Example 57
Project: alfresco-data-model   File: M2AnonymousTypeDefinition.java   4 votes vote down vote up
public Map<QName, ChildAssociationDefinition> getChildAssociations()
{
    return Collections.unmodifiableMap(childassociations);
}
 
Example 58
Project: alfresco-repository   File: MockClassAttributeDefinition.java   4 votes vote down vote up
public static MockClassAttributeDefinition mockPropertyDefinition(QName name, QName dataTypeName)
{
    MockClassAttributeDefinition mock = new MockClassAttributeDefinition(name);
    mockDataTypeName(mock, dataTypeName, null);
    return mock;
}
 
Example 59
Project: alfresco-repository   File: OwnableServiceTest.java   4 votes vote down vote up
public void testCMObject()
    {
        authenticationService.authenticate("andy", "andy".toCharArray());
        NodeRef testNode = nodeService.createNode(rootNodeRef, ContentModel.ASSOC_CHILDREN, ContentModel.TYPE_PERSON, ContentModel.TYPE_CMOBJECT, null).getChildRef();
        permissionService.setPermission(rootNodeRef, "andy", PermissionService.TAKE_OWNERSHIP, true);
        assertEquals("andy", ownableService.getOwner(testNode));
        assertTrue(ownableService.hasOwner(testNode));
        assertTrue(nodeService.hasAspect(testNode, ContentModel.ASPECT_AUDITABLE));
        assertFalse(nodeService.hasAspect(testNode, ContentModel.ASPECT_OWNABLE));
        assertTrue(dynamicAuthority.hasAuthority(testNode, "andy"));
        
        assertEquals("andy", ownableService.getOwner(testNode));
        
//        nodeService.setProperty(testNode, ContentModel.PROP_CREATOR, "woof");
//        assertEquals("woof", ownableService.getOwner(testNode));
//        
//        nodeService.setProperty(testNode, ContentModel.PROP_CREATOR, "andy");
//        assertEquals("andy", ownableService.getOwner(testNode));
//        
        permissionService.setInheritParentPermissions(testNode, false);
        
        
        assertEquals(AccessStatus.DENIED, permissionService.hasPermission(rootNodeRef, PermissionService.TAKE_OWNERSHIP));
        assertEquals(AccessStatus.DENIED, permissionService.hasPermission(rootNodeRef, PermissionService.SET_OWNER));
        assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(testNode, PermissionService.TAKE_OWNERSHIP));
        assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(testNode, PermissionService.SET_OWNER));
        
        permissionService.setPermission(rootNodeRef, "andy", PermissionService.WRITE_PROPERTIES, true);
        
        assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(rootNodeRef, PermissionService.TAKE_OWNERSHIP));
        assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(rootNodeRef, PermissionService.SET_OWNER));
        assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(testNode, PermissionService.TAKE_OWNERSHIP));
        assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(testNode, PermissionService.SET_OWNER));
        
       
        
        ownableService.setOwner(testNode, "woof");
        assertEquals("woof", ownableService.getOwner(testNode));
        assertTrue(dynamicAuthority.hasAuthority(testNode, "woof"));
        assertEquals(AccessStatus.DENIED, permissionService.hasPermission(testNode, PermissionService.TAKE_OWNERSHIP));
        assertEquals(AccessStatus.DENIED, permissionService.hasPermission(testNode, PermissionService.SET_OWNER));
        
        
        ownableService.setOwner(testNode, "muppet");
        assertEquals("muppet", ownableService.getOwner(testNode));
        assertTrue(dynamicAuthority.hasAuthority(testNode, "muppet"));
        assertEquals(AccessStatus.DENIED, permissionService.hasPermission(testNode, PermissionService.TAKE_OWNERSHIP));
        assertEquals(AccessStatus.DENIED, permissionService.hasPermission(testNode, PermissionService.SET_OWNER));
        
        
        ownableService.takeOwnership(testNode);
        assertEquals("andy", ownableService.getOwner(testNode));
        assertTrue(dynamicAuthority.hasAuthority(testNode, "andy"));
        assertTrue(nodeService.hasAspect(testNode, ContentModel.ASPECT_AUDITABLE));
        assertTrue(nodeService.hasAspect(testNode, ContentModel.ASPECT_OWNABLE));
      
        assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(rootNodeRef, PermissionService.TAKE_OWNERSHIP));
        assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(rootNodeRef, PermissionService.SET_OWNER));
        assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(testNode, PermissionService.TAKE_OWNERSHIP));
        assertEquals(AccessStatus.ALLOWED, permissionService.hasPermission(testNode, PermissionService.SET_OWNER));
        
        nodeService.setProperty(testNode, ContentModel.PROP_OWNER, "muppet");
        assertEquals("muppet", ownableService.getOwner(testNode));
        nodeService.removeAspect(testNode, ContentModel.ASPECT_OWNABLE);
        assertEquals("andy", ownableService.getOwner(testNode));
        
        HashMap<QName, Serializable> aspectProperties = new HashMap<QName, Serializable>();
        aspectProperties.put(ContentModel.PROP_OWNER, "muppet");
        nodeService.addAspect(testNode, ContentModel.ASPECT_OWNABLE, aspectProperties);
        assertEquals("muppet", ownableService.getOwner(testNode));
        
       
    }
 
Example 60
Project: alfresco-repository   File: ThumbnailServiceImpl.java   4 votes vote down vote up
/**
 * @see org.alfresco.service.cmr.thumbnail.ThumbnailService#updateThumbnail(org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.cmr.repository.TransformationOptions)
 */
public void updateThumbnail(final NodeRef thumbnail, final TransformationOptions transformationOptions)
{
    if (logger.isDebugEnabled() == true)
    {
        logger.debug("Updating thumbnail (thumbnail=" + thumbnail.toString() + ")");
    }
    
    // First check that we are dealing with a rendition object
    if (renditionService.isRendition(thumbnail))
    {
        // Get the node that is the source of the thumbnail
        ChildAssociationRef parentAssoc = renditionService.getSourceNode(thumbnail);
        
        if (parentAssoc == null)
        {
            if (logger.isDebugEnabled() == true)
            {
                logger.debug("Updating thumbnail: The thumbnails parent cannot be found (thumbnail=" + thumbnail.toString() + ")");
            }
            throw new ThumbnailException(ERR_NO_PARENT);
        }
        
        final QName renditionAssociationName = parentAssoc.getQName();
        NodeRef sourceNode = parentAssoc.getParentRef();

        // Get the content property
        QName contentProperty = (QName)nodeService.getProperty(thumbnail, ContentModel.PROP_CONTENT_PROPERTY_NAME);

        // Set the basic detail of the transformation options
        transformationOptions.setSourceNodeRef(sourceNode);
        transformationOptions.setSourceContentProperty(contentProperty);
        transformationOptions.setTargetContentProperty(ContentModel.PROP_CONTENT);

        // Do the thumbnail transformation. Rendition Definitions are persisted underneath the Data Dictionary for which Group ALL
        // has Consumer access by default. However, we cannot assume that that access level applies for all deployments. See ALF-7334.
        RenditionDefinition rendDefn = AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<RenditionDefinition>()
            {
                @Override
                public RenditionDefinition doWork() throws Exception
                {
                    return renditionService.loadRenditionDefinition(renditionAssociationName);
                }
            }, AuthenticationUtil.getSystemUserName());
        
        if (rendDefn == null)
        {
            String renderingEngineName = getRenderingEngineNameFor(transformationOptions);

            rendDefn = renditionService.createRenditionDefinition(parentAssoc.getQName(), renderingEngineName);
        }
        Map<String, Serializable> params = thumbnailRegistry.getThumbnailRenditionConvertor().convert(transformationOptions, null);
        for (String key : params.keySet())
        {
            rendDefn.setParameterValue(key, params.get(key));
        }
        
        renditionService.render(sourceNode, rendDefn);
    }
    else
    {
        if (logger.isDebugEnabled() == true)
        {
            logger.debug("Updating thumbnail: cannot update a thumbnail node that isn't the correct thumbnail type (thumbnail=" + thumbnail.toString() + ")");
        }
    }
}