Search in sources :

Example 36 with AssociationDefinition

use of org.alfresco.service.cmr.dictionary.AssociationDefinition in project records-management by Alfresco.

the class RelationshipServiceImpl method persistUpdatedAssocTitle.

/**
 * This method writes the specified String into the association's title property.
 * For RM custom properties and references, Title is used to store the identifier.
 *
 * NOTE: Currently RMC custom associations only
 * @param associationDefinitionQName Qualified name for the association definition
 * @param newTitle The new title
 * @return Qualified name for the association definition
 */
private QName persistUpdatedAssocTitle(QName associationDefinitionQName, String newTitle) {
    mandatory("associationDefinitionQName", associationDefinitionQName);
    AssociationDefinition assocDefn = getDictionaryService().getAssociation(associationDefinitionQName);
    if (assocDefn == null) {
        StringBuilder sb = new StringBuilder();
        sb.append("Cannot find the association definiton for '").append(associationDefinitionQName.getLocalName()).append("'.");
        throw new AlfrescoRuntimeException(sb.toString());
    }
    // defaults to RM_CUSTOM_URI
    NodeRef modelRef = getCustomModelRef("");
    M2Model deserializedModel = readCustomContentModel(modelRef);
    String customAspectName = ASPECT_CUSTOM_ASSOCIATIONS.toPrefixString(getNamespaceService());
    M2Aspect customAssocsAspect = deserializedModel.getAspect(customAspectName);
    for (M2ClassAssociation assoc : customAssocsAspect.getAssociations()) {
        if (associationDefinitionQName.toPrefixString(getNamespaceService()).equals(assoc.getName()) && newTitle != null) {
            assoc.setTitle(newTitle);
        }
    }
    writeCustomContentModel(modelRef, deserializedModel);
    if (logger.isInfoEnabled()) {
        logger.info("persistUpdatedAssocTitle: " + associationDefinitionQName + "=" + newTitle + " to aspect: " + customAspectName);
    }
    return associationDefinitionQName;
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) AssociationDefinition(org.alfresco.service.cmr.dictionary.AssociationDefinition) ChildAssociationDefinition(org.alfresco.service.cmr.dictionary.ChildAssociationDefinition) M2Model(org.alfresco.repo.dictionary.M2Model) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) ParameterCheck.mandatoryString(org.alfresco.util.ParameterCheck.mandatoryString) M2Aspect(org.alfresco.repo.dictionary.M2Aspect) M2ClassAssociation(org.alfresco.repo.dictionary.M2ClassAssociation)

Example 37 with AssociationDefinition

use of org.alfresco.service.cmr.dictionary.AssociationDefinition in project records-management by Alfresco.

the class RelationshipServiceImpl method addRelationship.

/**
 * @see org.alfresco.module.org_alfresco_module_rm.relationship.RelationshipService#addRelationship(java.lang.String, org.alfresco.service.cmr.repository.NodeRef, org.alfresco.service.cmr.repository.NodeRef)
 */
@Override
public void addRelationship(String uniqueName, NodeRef source, NodeRef target) {
    mandatoryString("uniqueName", uniqueName);
    mandatory("source", source);
    mandatory("target", target);
    // check the source node exists
    if (!getNodeService().exists(source)) {
        throw new AlfrescoRuntimeException("Can't create relationship '" + uniqueName + "', because source node doesn't exist.");
    }
    // check the target node exists
    if (!getNodeService().exists(target)) {
        throw new AlfrescoRuntimeException("Can't create relationship " + uniqueName + ", because target node doesn't exist.");
    }
    if (getNodeService().hasAspect(target, ASPECT_FROZEN)) {
        StringBuilder sb = new StringBuilder();
        sb.append("Relationship cannot be created as the target '").append(getNodeService().getProperty(target, ContentModel.PROP_NAME)).append("' is in a hold.");
        throw new AlfrescoRuntimeException(sb.toString());
    }
    // Check that the association definition for the given unique name exists.
    AssociationDefinition associationDefinition = getAssociationDefinition(uniqueName);
    if (associationDefinition == null) {
        StringBuilder sb = new StringBuilder();
        sb.append("No association definition found for '").append(uniqueName).append("'.");
        throw new IllegalArgumentException(sb.toString());
    }
    // Get the association definition name
    QName associationDefinitionName = associationDefinition.getName();
    // Check if an instance of this association already exists in the same direction
    boolean associationAlreadyExists = associationExists(associationDefinition, source, target);
    if (associationAlreadyExists) {
        StringBuilder sb = new StringBuilder();
        sb.append("Association '").append(associationDefinitionName.getLocalName()).append("' already exists from '").append(source).append("' to '").append(target).append("'.");
        throw new AlfrescoRuntimeException(sb.toString());
    }
    // Invoke before create reference policy
    invokeBeforeCreateReference(source, target, associationDefinitionName);
    if (associationDefinition.isChild()) {
        getNodeService().addChild(source, target, associationDefinitionName, associationDefinitionName);
    } else {
        getNodeService().createAssociation(source, target, associationDefinitionName);
    }
    // Invoke on create reference policy
    invokeOnCreateReference(source, target, associationDefinitionName);
}
Also used : AssociationDefinition(org.alfresco.service.cmr.dictionary.AssociationDefinition) ChildAssociationDefinition(org.alfresco.service.cmr.dictionary.ChildAssociationDefinition) QName(org.alfresco.service.namespace.QName) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException)

Example 38 with AssociationDefinition

use of org.alfresco.service.cmr.dictionary.AssociationDefinition in project records-management by Alfresco.

the class RmRestApiTest method postCustomReferenceDefinitions.

/**
 * This method creates a child and a non-child reference and returns their generated ids.
 *
 * @return String[] with element 0 = refId of p/c ref, 1 = refId pf bidi.
 */
private String[] postCustomReferenceDefinitions() throws JSONException, IOException, UnsupportedEncodingException {
    String[] result = new String[2];
    // 1. Child association.
    String jsonString = new JSONStringer().object().key("referenceType").value(RelationshipType.PARENTCHILD).key("source").value(CHILD_SRC).key("target").value(CHILD_TGT).endObject().toString();
    // System.out.println(jsonString);
    // Submit the JSON request.
    final int expectedStatus = 200;
    Response rsp = sendRequest(new PostRequest(RMA_CUSTOM_REFS_DEFINITIONS_URL, jsonString, APPLICATION_JSON), expectedStatus);
    String rspContent = rsp.getContentAsString();
    assertTrue(rspContent.contains("success"));
    // System.out.println(rspContent);
    JSONObject jsonRsp = new JSONObject(new JSONTokener(rspContent));
    String generatedChildRefId = jsonRsp.getJSONObject("data").getString("refId");
    result[0] = generatedChildRefId;
    // 2. Non-child or standard association.
    jsonString = new JSONStringer().object().key("referenceType").value(RelationshipType.BIDIRECTIONAL).key("label").value(BI_DI).endObject().toString();
    // System.out.println(jsonString);
    // Submit the JSON request.
    rsp = sendRequest(new PostRequest(RMA_CUSTOM_REFS_DEFINITIONS_URL, jsonString, APPLICATION_JSON), expectedStatus);
    rspContent = rsp.getContentAsString();
    assertTrue(rspContent.contains("success"));
    // System.out.println(rspContent);
    jsonRsp = new JSONObject(new JSONTokener(rspContent));
    String generatedBidiRefId = jsonRsp.getJSONObject("data").getString("refId");
    result[1] = generatedBidiRefId;
    // Now assert that both have appeared in the data dictionary.
    AspectDefinition customAssocsAspect = dictionaryService.getAspect(ASPECT_CUSTOM_ASSOCIATIONS);
    assertNotNull("Missing customAssocs aspect", customAssocsAspect);
    QName newRefQname = adminService.getQNameForClientId(generatedChildRefId);
    Map<QName, AssociationDefinition> associations = customAssocsAspect.getAssociations();
    assertTrue("Custom child assoc not returned by dataDictionary.", associations.containsKey(newRefQname));
    newRefQname = adminService.getQNameForClientId(generatedBidiRefId);
    assertTrue("Custom std assoc not returned by dataDictionary.", customAssocsAspect.getAssociations().containsKey(newRefQname));
    return result;
}
Also used : Response(org.springframework.extensions.webscripts.TestWebScriptServer.Response) JSONTokener(org.json.JSONTokener) PostRequest(org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest) JSONObject(org.json.JSONObject) AssociationDefinition(org.alfresco.service.cmr.dictionary.AssociationDefinition) QName(org.alfresco.service.namespace.QName) AspectDefinition(org.alfresco.service.cmr.dictionary.AspectDefinition) JSONStringer(org.json.JSONStringer)

Example 39 with AssociationDefinition

use of org.alfresco.service.cmr.dictionary.AssociationDefinition in project alfresco-remote-api by Alfresco.

the class WorkflowModelBuilder method buildProperties.

private Map<String, Object> buildProperties(WorkflowTask task, Collection<String> propertyFilters) {
    Map<QName, Serializable> properties = task.getProperties();
    Collection<QName> keys;
    if (propertyFilters == null || propertyFilters.size() == 0) {
        TypeDefinition taskType = task.getDefinition().getMetadata();
        Map<QName, PropertyDefinition> propDefs = taskType.getProperties();
        Map<QName, AssociationDefinition> assocDefs = taskType.getAssociations();
        Set<QName> propKeys = properties.keySet();
        keys = new HashSet<QName>(propDefs.size() + assocDefs.size() + propKeys.size());
        keys.addAll(propDefs.keySet());
        keys.addAll(assocDefs.keySet());
        keys.addAll(propKeys);
        keys.add(WorkflowModel.PROP_HIDDEN_TRANSITIONS);
    } else {
        keys = buildQNameKeys(propertyFilters);
    }
    Map<String, Object> result = buildQNameProperties(properties, keys, task);
    // ALF-18092: Special handling for the "hiddenTransitions" property, as it can be an empty string
    if (keys.contains(WorkflowModel.PROP_HIDDEN_TRANSITIONS)) {
        List<?> hiddenTransitions = getHiddenTransitions(properties);
        if (hiddenTransitions != null) {
            result.put(qNameConverter.mapQNameToName(WorkflowModel.PROP_HIDDEN_TRANSITIONS), hiddenTransitions);
        }
    }
    return result;
}
Also used : Serializable(java.io.Serializable) QName(org.alfresco.service.namespace.QName) PropertyDefinition(org.alfresco.service.cmr.dictionary.PropertyDefinition) TypeDefinition(org.alfresco.service.cmr.dictionary.TypeDefinition) AssociationDefinition(org.alfresco.service.cmr.dictionary.AssociationDefinition)

Example 40 with AssociationDefinition

use of org.alfresco.service.cmr.dictionary.AssociationDefinition in project alfresco-remote-api by Alfresco.

the class ProcessesImpl method create.

@Override
public ProcessInfo create(ProcessInfo process) {
    if (process == null) {
        throw new InvalidArgumentException("post body expected when starting a new process instance");
    }
    boolean definitionExistingChecked = false;
    RuntimeService runtimeService = activitiProcessEngine.getRuntimeService();
    String processDefinitionId = null;
    if (process.getProcessDefinitionId() != null) {
        processDefinitionId = process.getProcessDefinitionId();
    } else if (process.getProcessDefinitionKey() != null) {
        ProcessDefinition definition = activitiProcessEngine.getRepositoryService().createProcessDefinitionQuery().processDefinitionKey(getProcessDefinitionKey(process.getProcessDefinitionKey())).latestVersion().singleResult();
        if (definition == null) {
            throw new InvalidArgumentException("No workflow definition could be found with key '" + process.getProcessDefinitionKey() + "'.");
        }
        processDefinitionId = definition.getId();
        definitionExistingChecked = true;
    } else {
        throw new InvalidArgumentException("Either processDefinitionId or processDefinitionKey is required");
    }
    if (definitionExistingChecked == false) {
        // Check if the required definition actually exists
        ProcessDefinitionQuery query = activitiProcessEngine.getRepositoryService().createProcessDefinitionQuery().processDefinitionId(processDefinitionId);
        if (tenantService.isEnabled() && deployWorkflowsInTenant) {
            query.processDefinitionKeyLike("@" + TenantUtil.getCurrentDomain() + "@%");
        }
        if (query.count() == 0) {
            throw new InvalidArgumentException("No workflow definition could be found with id '" + processDefinitionId + "'.");
        }
    }
    Map<QName, Serializable> startParams = new HashMap<QName, Serializable>();
    StartFormData startFormData = activitiProcessEngine.getFormService().getStartFormData(processDefinitionId);
    if (startFormData != null) {
        if (CollectionUtils.isEmpty(process.getVariables()) == false) {
            TypeDefinition startTaskType = getWorkflowFactory().getTaskFullTypeDefinition(startFormData.getFormKey(), true);
            // Lookup type definition for the startTask
            Map<QName, PropertyDefinition> taskProperties = startTaskType.getProperties();
            Map<String, QName> propNameMap = new HashMap<String, QName>();
            for (QName key : taskProperties.keySet()) {
                propNameMap.put(key.getPrefixString().replace(':', '_'), key);
            }
            Map<QName, AssociationDefinition> taskAssociations = startTaskType.getAssociations();
            for (QName key : taskAssociations.keySet()) {
                propNameMap.put(key.getPrefixString().replace(':', '_'), key);
            }
            for (String variableName : process.getVariables().keySet()) {
                if (propNameMap.containsKey(variableName)) {
                    Object variableValue = process.getVariables().get(variableName);
                    if (taskAssociations.containsKey(propNameMap.get(variableName))) {
                        AssociationDefinition associationDef = taskAssociations.get(propNameMap.get(variableName));
                        variableValue = convertAssociationDefinitionValue(associationDef, variableName, variableValue);
                    } else if (taskProperties.containsKey(propNameMap.get(variableName))) {
                        PropertyDefinition propDef = taskProperties.get(propNameMap.get(variableName));
                        DataTypeDefinition propDataType = propDef.getDataType();
                        if ("java.util.Date".equalsIgnoreCase(propDataType.getJavaClassName())) {
                            // fix for different ISO 8601 Date format classes in Alfresco (org.alfresco.util and Spring Surf)
                            variableValue = ISO8601DateFormat.parse((String) variableValue);
                        }
                    }
                    if (variableValue instanceof Serializable) {
                        startParams.put(propNameMap.get(variableName), (Serializable) variableValue);
                    }
                }
            }
        }
    }
    String currentUserName = AuthenticationUtil.getFullyAuthenticatedUser();
    Authentication.setAuthenticatedUserId(currentUserName);
    NodeRef workflowPackageNodeRef = null;
    try {
        workflowPackageNodeRef = workflowPackageComponent.createPackage(null);
        startParams.put(WorkflowModel.ASSOC_PACKAGE, workflowPackageNodeRef);
    } catch (Exception e) {
        throw new ApiException("couldn't create workflow package: " + e.getMessage(), e);
    }
    if (org.apache.commons.collections.CollectionUtils.isNotEmpty(process.getItems())) {
        try {
            for (String item : process.getItems()) {
                NodeRef itemNodeRef = getNodeRef(item);
                QName workflowPackageItemId = QName.createQName("wpi", itemNodeRef.toString());
                nodeService.addChild(workflowPackageNodeRef, itemNodeRef, WorkflowModel.ASSOC_PACKAGE_CONTAINS, workflowPackageItemId);
            }
        } catch (Exception e) {
            throw new ApiException("Error while adding items to package: " + e.getMessage(), e);
        }
    }
    // Set start task properties. This should be done before instance is started, since it's id will be used
    Map<String, Object> variables = getPropertyConverter().getStartVariables(processDefinitionId, startParams);
    variables.put(WorkflowConstants.PROP_CANCELLED, Boolean.FALSE);
    // Add company home
    Object companyHome = getNodeConverter().convertNode(repositoryHelper.getCompanyHome());
    variables.put(WorkflowConstants.PROP_COMPANY_HOME, companyHome);
    // Add the initiator
    NodeRef initiator = getPersonNodeRef(currentUserName);
    if (initiator != null) {
        variables.put(WorkflowConstants.PROP_INITIATOR, nodeConverter.convertNode(initiator));
        // Also add the initiator home reference, if one exists
        NodeRef initiatorHome = (NodeRef) nodeService.getProperty(initiator, ContentModel.PROP_HOMEFOLDER);
        if (initiatorHome != null) {
            variables.put(WorkflowConstants.PROP_INITIATOR_HOME, nodeConverter.convertNode(initiatorHome));
        }
    }
    if (tenantService.isEnabled()) {
        // Specify which tenant domain the workflow was started in.
        variables.put(ActivitiConstants.VAR_TENANT_DOMAIN, TenantUtil.getCurrentDomain());
    }
    // Start the process-instance
    ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinitionId, process.getBusinessKey(), variables);
    if (processInstance.isEnded() == false) {
        runtimeService.setVariable(processInstance.getProcessInstanceId(), ActivitiConstants.PROP_START_TASK_END_DATE, new Date());
    }
    HistoricProcessInstance historicProcessInstance = activitiProcessEngine.getHistoryService().createHistoricProcessInstanceQuery().processInstanceId(processInstance.getId()).singleResult();
    return createProcessInfo(historicProcessInstance);
}
Also used : Serializable(java.io.Serializable) HashMap(java.util.HashMap) ProcessDefinition(org.activiti.engine.repository.ProcessDefinition) ProcessDefinitionQuery(org.activiti.engine.repository.ProcessDefinitionQuery) DataTypeDefinition(org.alfresco.service.cmr.dictionary.DataTypeDefinition) TypeDefinition(org.alfresco.service.cmr.dictionary.TypeDefinition) DataTypeDefinition(org.alfresco.service.cmr.dictionary.DataTypeDefinition) NodeRef(org.alfresco.service.cmr.repository.NodeRef) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) StartFormData(org.activiti.engine.form.StartFormData) RuntimeService(org.activiti.engine.RuntimeService) QName(org.alfresco.service.namespace.QName) HistoricProcessInstance(org.activiti.engine.history.HistoricProcessInstance) PropertyDefinition(org.alfresco.service.cmr.dictionary.PropertyDefinition) EntityNotFoundException(org.alfresco.rest.framework.core.exceptions.EntityNotFoundException) ApiException(org.alfresco.rest.framework.core.exceptions.ApiException) ActivitiObjectNotFoundException(org.activiti.engine.ActivitiObjectNotFoundException) IOException(java.io.IOException) InvalidQNameException(org.alfresco.service.namespace.InvalidQNameException) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) Date(java.util.Date) AssociationDefinition(org.alfresco.service.cmr.dictionary.AssociationDefinition) ProcessInstance(org.activiti.engine.runtime.ProcessInstance) HistoricProcessInstance(org.activiti.engine.history.HistoricProcessInstance) ApiException(org.alfresco.rest.framework.core.exceptions.ApiException)

Aggregations

AssociationDefinition (org.alfresco.service.cmr.dictionary.AssociationDefinition)60 QName (org.alfresco.service.namespace.QName)46 PropertyDefinition (org.alfresco.service.cmr.dictionary.PropertyDefinition)24 ChildAssociationDefinition (org.alfresco.service.cmr.dictionary.ChildAssociationDefinition)19 NodeRef (org.alfresco.service.cmr.repository.NodeRef)17 TypeDefinition (org.alfresco.service.cmr.dictionary.TypeDefinition)15 HashMap (java.util.HashMap)13 Serializable (java.io.Serializable)11 ArrayList (java.util.ArrayList)11 ClassDefinition (org.alfresco.service.cmr.dictionary.ClassDefinition)9 DataTypeDefinition (org.alfresco.service.cmr.dictionary.DataTypeDefinition)7 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)6 AspectDefinition (org.alfresco.service.cmr.dictionary.AspectDefinition)6 ChildAssociationRef (org.alfresco.service.cmr.repository.ChildAssociationRef)6 Collection (java.util.Collection)5 AssociationRef (org.alfresco.service.cmr.repository.AssociationRef)5 HashSet (java.util.HashSet)4 List (java.util.List)4 Map (java.util.Map)4 Pair (org.alfresco.util.Pair)3