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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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);
}