Search in sources :

Example 11 with ApiException

use of org.alfresco.rest.framework.core.exceptions.ApiException in project alfresco-remote-api by Alfresco.

the class ProcessDefinitionsImpl method getProcessDefinitionImage.

@Override
public BinaryResource getProcessDefinitionImage(String definitionId) {
    ProcessDefinitionQuery query = activitiProcessEngine.getRepositoryService().createProcessDefinitionQuery().processDefinitionId(definitionId);
    if (tenantService.isEnabled() && deployWorkflowsInTenant) {
        query.processDefinitionKeyLike("@" + TenantUtil.getCurrentDomain() + "@%");
    }
    org.activiti.engine.repository.ProcessDefinition processDefinition = query.singleResult();
    if (processDefinition == null) {
        throw new EntityNotFoundException(definitionId);
    }
    try {
        InputStream processDiagram = activitiProcessEngine.getRepositoryService().getProcessDiagram(definitionId);
        if (processDiagram != null) {
            File file = TempFileProvider.createTempFile(definitionId + UUID.randomUUID(), ".png");
            FileOutputStream fos = new FileOutputStream(file);
            IOUtils.copy(processDiagram, fos);
            fos.close();
            return new FileBinaryResource(file);
        } else {
            throw new ApiException("No image available for definitionId " + definitionId);
        }
    } catch (IOException error) {
        throw new ApiException("Error while getting process definition image.");
    }
}
Also used : InputStream(java.io.InputStream) FileOutputStream(java.io.FileOutputStream) ProcessDefinitionQuery(org.activiti.engine.repository.ProcessDefinitionQuery) EntityNotFoundException(org.alfresco.rest.framework.core.exceptions.EntityNotFoundException) IOException(java.io.IOException) File(java.io.File) FileBinaryResource(org.alfresco.rest.framework.resource.content.FileBinaryResource) ApiException(org.alfresco.rest.framework.core.exceptions.ApiException)

Example 12 with ApiException

use of org.alfresco.rest.framework.core.exceptions.ApiException in project alfresco-remote-api by Alfresco.

the class ProcessesImpl method getProcessImage.

@Override
public BinaryResource getProcessImage(String processId) {
    validateIfUserAllowedToWorkWithProcess(processId);
    ProcessInstance processInstance = activitiProcessEngine.getRuntimeService().createProcessInstanceQuery().processInstanceId(processId).singleResult();
    if (processInstance == null) {
        throw new EntityNotFoundException(processId);
    }
    try {
        BpmnModel model = activitiProcessEngine.getRepositoryService().getBpmnModel(processInstance.getProcessDefinitionId());
        if (model != null && model.getLocationMap().size() > 0) {
            List<String> activeActivities = activitiProcessEngine.getRuntimeService().getActiveActivityIds(processId);
            ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
            InputStream generateDiagram = generator.generateDiagram(model, "png", activeActivities);
            File file = TempFileProvider.createTempFile(processId + UUID.randomUUID(), ".png");
            FileOutputStream fos = new FileOutputStream(file);
            IOUtils.copy(generateDiagram, fos);
            fos.close();
            return new FileBinaryResource(file);
        } else {
            throw new EntityNotFoundException(processId + "/image");
        }
    } catch (IOException error) {
        throw new ApiException("Error while getting process image.");
    }
}
Also used : InputStream(java.io.InputStream) DefaultProcessDiagramGenerator(org.activiti.image.impl.DefaultProcessDiagramGenerator) EntityNotFoundException(org.alfresco.rest.framework.core.exceptions.EntityNotFoundException) IOException(java.io.IOException) FileBinaryResource(org.alfresco.rest.framework.resource.content.FileBinaryResource) BpmnModel(org.activiti.bpmn.model.BpmnModel) ProcessDiagramGenerator(org.activiti.image.ProcessDiagramGenerator) DefaultProcessDiagramGenerator(org.activiti.image.impl.DefaultProcessDiagramGenerator) FileOutputStream(java.io.FileOutputStream) ProcessInstance(org.activiti.engine.runtime.ProcessInstance) HistoricProcessInstance(org.activiti.engine.history.HistoricProcessInstance) File(java.io.File) ApiException(org.alfresco.rest.framework.core.exceptions.ApiException)

Example 13 with ApiException

use of org.alfresco.rest.framework.core.exceptions.ApiException 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)

Example 14 with ApiException

use of org.alfresco.rest.framework.core.exceptions.ApiException in project alfresco-remote-api by Alfresco.

the class WorkflowRestImpl method createItemInProcess.

/**
 *  Create a new item in the process package variable
 */
public Item createItemInProcess(String itemId, String processId) {
    NodeRef nodeRef = getNodeRef(itemId);
    ActivitiScriptNode packageScriptNode = null;
    try {
        packageScriptNode = (ActivitiScriptNode) activitiProcessEngine.getRuntimeService().getVariable(processId, BPM_PACKAGE);
    } catch (ActivitiObjectNotFoundException e) {
        throw new EntityNotFoundException(processId);
    }
    if (packageScriptNode == null) {
        throw new InvalidArgumentException("process doesn't contain a workflow package variable");
    }
    // check if noderef exists
    try {
        nodeService.getProperties(nodeRef);
    } catch (Exception e) {
        throw new EntityNotFoundException("item with id " + nodeRef.toString() + " not found");
    }
    try {
        QName workflowPackageItemId = QName.createQName("wpi", nodeRef.toString());
        nodeService.addChild(packageScriptNode.getNodeRef(), nodeRef, WorkflowModel.ASSOC_PACKAGE_CONTAINS, workflowPackageItemId);
    } catch (Exception e) {
        throw new ApiException("could not add item to process " + e.getMessage(), e);
    }
    Item responseItem = createItemForNodeRef(nodeRef);
    activitiWorkflowEngine.dispatchPackageUpdatedEvent(packageScriptNode, null, null, processId, null);
    return responseItem;
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) Item(org.alfresco.rest.workflow.api.model.Item) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) ActivitiScriptNode(org.alfresco.repo.workflow.activiti.ActivitiScriptNode) QName(org.alfresco.service.namespace.QName) EntityNotFoundException(org.alfresco.rest.framework.core.exceptions.EntityNotFoundException) ActivitiObjectNotFoundException(org.activiti.engine.ActivitiObjectNotFoundException) PermissionDeniedException(org.alfresco.rest.framework.core.exceptions.PermissionDeniedException) EntityNotFoundException(org.alfresco.rest.framework.core.exceptions.EntityNotFoundException) ConversionException(org.apache.commons.beanutils.ConversionException) InvalidNodeRefException(org.alfresco.service.cmr.repository.InvalidNodeRefException) ApiException(org.alfresco.rest.framework.core.exceptions.ApiException) ActivitiObjectNotFoundException(org.activiti.engine.ActivitiObjectNotFoundException) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) ApiException(org.alfresco.rest.framework.core.exceptions.ApiException)

Example 15 with ApiException

use of org.alfresco.rest.framework.core.exceptions.ApiException in project alfresco-remote-api by Alfresco.

the class ExceptionResolverTests method testMatchException.

// 04180006 Authentication failed for Web Script org/alfresco/api/ResourceWebScript.get
@Test
public void testMatchException() {
    ErrorResponse response = assistant.resolveException(new ApiException(null));
    assertNotNull(response);
    // default to INTERNAL_SERVER_ERROR
    assertEquals(500, response.getStatusCode());
    response = assistant.resolveException(new InvalidArgumentException(null));
    // default to STATUS_BAD_REQUEST
    assertEquals(400, response.getStatusCode());
    response = assistant.resolveException(new InvalidQueryException(null));
    // default to STATUS_BAD_REQUEST
    assertEquals(400, response.getStatusCode());
    response = assistant.resolveException(new NotFoundException(null));
    // default to STATUS_NOT_FOUND
    assertEquals(404, response.getStatusCode());
    response = assistant.resolveException(new EntityNotFoundException(null));
    // default to STATUS_NOT_FOUND
    assertEquals(404, response.getStatusCode());
    response = assistant.resolveException(new RelationshipResourceNotFoundException(null, null));
    // default to STATUS_NOT_FOUND
    assertEquals(404, response.getStatusCode());
    response = assistant.resolveException(new PermissionDeniedException(null));
    // default to STATUS_FORBIDDEN
    assertEquals(403, response.getStatusCode());
    response = assistant.resolveException(new UnsupportedResourceOperationException(null));
    // default to STATUS_METHOD_NOT_ALLOWED
    assertEquals(405, response.getStatusCode());
    response = assistant.resolveException(new DeletedResourceException(null));
    // default to STATUS_METHOD_NOT_ALLOWED
    assertEquals(405, response.getStatusCode());
    response = assistant.resolveException(new ConstraintViolatedException(null));
    // default to STATUS_CONFLICT
    assertEquals(409, response.getStatusCode());
    response = assistant.resolveException(new StaleEntityException(null));
    // default to STATUS_CONFLICT
    assertEquals(409, response.getStatusCode());
    // Try a random exception
    response = assistant.resolveException(new FormNotFoundException(null));
    // default to INTERNAL_SERVER_ERROR
    assertEquals(500, response.getStatusCode());
    response = assistant.resolveException(new InsufficientStorageException(null));
    assertEquals(507, response.getStatusCode());
    response = assistant.resolveException(new IntegrityException(null));
    assertEquals(422, response.getStatusCode());
}
Also used : UnsupportedResourceOperationException(org.alfresco.rest.framework.core.exceptions.UnsupportedResourceOperationException) InsufficientStorageException(org.alfresco.rest.framework.core.exceptions.InsufficientStorageException) FormNotFoundException(org.alfresco.repo.forms.FormNotFoundException) RelationshipResourceNotFoundException(org.alfresco.rest.framework.core.exceptions.RelationshipResourceNotFoundException) EntityNotFoundException(org.alfresco.rest.framework.core.exceptions.EntityNotFoundException) NotFoundException(org.alfresco.rest.framework.core.exceptions.NotFoundException) IntegrityException(org.alfresco.repo.node.integrity.IntegrityException) EntityNotFoundException(org.alfresco.rest.framework.core.exceptions.EntityNotFoundException) DeletedResourceException(org.alfresco.rest.framework.core.exceptions.DeletedResourceException) ConstraintViolatedException(org.alfresco.rest.framework.core.exceptions.ConstraintViolatedException) ErrorResponse(org.alfresco.rest.framework.core.exceptions.ErrorResponse) RelationshipResourceNotFoundException(org.alfresco.rest.framework.core.exceptions.RelationshipResourceNotFoundException) InvalidArgumentException(org.alfresco.rest.framework.core.exceptions.InvalidArgumentException) FormNotFoundException(org.alfresco.repo.forms.FormNotFoundException) PermissionDeniedException(org.alfresco.rest.framework.core.exceptions.PermissionDeniedException) StaleEntityException(org.alfresco.rest.framework.core.exceptions.StaleEntityException) InvalidQueryException(org.alfresco.rest.framework.resource.parameters.where.InvalidQueryException) ApiException(org.alfresco.rest.framework.core.exceptions.ApiException) Test(org.junit.Test)

Aggregations

ApiException (org.alfresco.rest.framework.core.exceptions.ApiException)15 EntityNotFoundException (org.alfresco.rest.framework.core.exceptions.EntityNotFoundException)11 InvalidArgumentException (org.alfresco.rest.framework.core.exceptions.InvalidArgumentException)9 ConstraintViolatedException (org.alfresco.rest.framework.core.exceptions.ConstraintViolatedException)6 PermissionDeniedException (org.alfresco.rest.framework.core.exceptions.PermissionDeniedException)6 IOException (java.io.IOException)5 NodeRef (org.alfresco.service.cmr.repository.NodeRef)5 QName (org.alfresco.service.namespace.QName)5 FileBinaryResource (org.alfresco.rest.framework.resource.content.FileBinaryResource)4 File (java.io.File)3 InputStream (java.io.InputStream)3 NotFoundException (org.alfresco.rest.framework.core.exceptions.NotFoundException)3 WebScriptException (org.springframework.extensions.webscripts.WebScriptException)3 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 FileOutputStream (java.io.FileOutputStream)2 Serializable (java.io.Serializable)2 Date (java.util.Date)2 HashMap (java.util.HashMap)2 ActivitiObjectNotFoundException (org.activiti.engine.ActivitiObjectNotFoundException)2