Search in sources :

Example 71 with BpmnModel

use of org.activiti.bpmn.model.BpmnModel in project Activiti by Activiti.

the class SimpleWorkflowResource method createWorkflow.

@RequestMapping(value = "/simple-workflow", method = RequestMethod.POST, produces = "application/json")
public SimpleWorkflowSuccessResponse createWorkflow(@RequestBody String json) {
    // Convert json to simple workflow definition
    SimpleWorkflowJsonConverter jsonConverter = new SimpleWorkflowJsonConverter();
    WorkflowDefinition workflowDefinition = jsonConverter.readWorkflowDefinition(json.getBytes());
    WorkflowDefinitionConversionFactory conversionFactory = new WorkflowDefinitionConversionFactory();
    WorkflowDefinitionConversion conversion = conversionFactory.createWorkflowDefinitionConversion(workflowDefinition);
    conversion.convert();
    // Deploy process
    BpmnModel bpmnModel = conversion.getBpmnModel();
    Deployment deployment = repositoryService.createDeployment().addBpmnModel(bpmnModel.getProcesses().get(0).getName() + ".bpmn20.xml", bpmnModel).deploy();
    // Fetch process definition id
    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).singleResult();
    return new SimpleWorkflowSuccessResponse(processDefinition.getId());
}
Also used : WorkflowDefinitionConversion(org.activiti.workflow.simple.converter.WorkflowDefinitionConversion) WorkflowDefinitionConversionFactory(org.activiti.workflow.simple.converter.WorkflowDefinitionConversionFactory) WorkflowDefinition(org.activiti.workflow.simple.definition.WorkflowDefinition) Deployment(org.activiti.engine.repository.Deployment) SimpleWorkflowJsonConverter(org.activiti.workflow.simple.converter.json.SimpleWorkflowJsonConverter) ProcessDefinition(org.activiti.engine.repository.ProcessDefinition) BpmnModel(org.activiti.bpmn.model.BpmnModel) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 72 with BpmnModel

use of org.activiti.bpmn.model.BpmnModel in project Activiti by Activiti.

the class BpmnDeployer method deploy.

public void deploy(DeploymentEntity deployment, Map<String, Object> deploymentSettings) {
    log.debug("Processing deployment {}", deployment.getName());
    List<ProcessDefinitionEntity> processDefinitions = new ArrayList<ProcessDefinitionEntity>();
    Map<String, ResourceEntity> resources = deployment.getResources();
    Map<String, BpmnModel> bpmnModelMap = new HashMap<String, BpmnModel>();
    final ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
    for (String resourceName : resources.keySet()) {
        log.info("Processing resource {}", resourceName);
        if (isBpmnResource(resourceName)) {
            ResourceEntity resource = resources.get(resourceName);
            byte[] bytes = resource.getBytes();
            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            BpmnParse bpmnParse = bpmnParser.createParse().sourceInputStream(inputStream).setSourceSystemId(resourceName).deployment(deployment).name(resourceName);
            if (deploymentSettings != null) {
                // Schema validation if needed
                if (deploymentSettings.containsKey(DeploymentSettings.IS_BPMN20_XSD_VALIDATION_ENABLED)) {
                    bpmnParse.setValidateSchema((Boolean) deploymentSettings.get(DeploymentSettings.IS_BPMN20_XSD_VALIDATION_ENABLED));
                }
                // Process validation if needed
                if (deploymentSettings.containsKey(DeploymentSettings.IS_PROCESS_VALIDATION_ENABLED)) {
                    bpmnParse.setValidateProcess((Boolean) deploymentSettings.get(DeploymentSettings.IS_PROCESS_VALIDATION_ENABLED));
                }
            } else {
                // On redeploy, we assume it is validated at the first deploy
                bpmnParse.setValidateSchema(false);
                bpmnParse.setValidateProcess(false);
            }
            bpmnParse.execute();
            for (ProcessDefinitionEntity processDefinition : bpmnParse.getProcessDefinitions()) {
                processDefinition.setResourceName(resourceName);
                if (deployment.getTenantId() != null) {
                    // process definition inherits the tenant id
                    processDefinition.setTenantId(deployment.getTenantId());
                }
                String diagramResourceName = getDiagramResourceForProcess(resourceName, processDefinition.getKey(), resources);
                // time the process definition is added to the deployment-cache when diagram-generation has failed the first time.
                if (deployment.isNew()) {
                    if (processEngineConfiguration.isCreateDiagramOnDeploy() && diagramResourceName == null && processDefinition.isGraphicalNotationDefined()) {
                        try {
                            byte[] diagramBytes = IoUtil.readInputStream(processEngineConfiguration.getProcessDiagramGenerator().generateDiagram(bpmnParse.getBpmnModel(), "png", processEngineConfiguration.getActivityFontName(), processEngineConfiguration.getLabelFontName(), processEngineConfiguration.getAnnotationFontName(), processEngineConfiguration.getClassLoader()), null);
                            diagramResourceName = getProcessImageResourceName(resourceName, processDefinition.getKey(), "png");
                            createResource(diagramResourceName, diagramBytes, deployment);
                        } catch (Throwable t) {
                            // if anything goes wrong, we don't store the image (the process will still be executable).
                            log.warn("Error while generating process diagram, image will not be stored in repository", t);
                        }
                    }
                }
                processDefinition.setDiagramResourceName(diagramResourceName);
                processDefinitions.add(processDefinition);
                bpmnModelMap.put(processDefinition.getKey(), bpmnParse.getBpmnModel());
            }
        }
    }
    // check if there are process definitions with the same process key to prevent database unique index violation
    List<String> keyList = new ArrayList<String>();
    for (ProcessDefinitionEntity processDefinition : processDefinitions) {
        if (keyList.contains(processDefinition.getKey())) {
            throw new ActivitiException("The deployment contains process definitions with the same key '" + processDefinition.getKey() + "' (process id atrribute), this is not allowed");
        }
        keyList.add(processDefinition.getKey());
    }
    CommandContext commandContext = Context.getCommandContext();
    ProcessDefinitionEntityManager processDefinitionManager = commandContext.getProcessDefinitionEntityManager();
    DbSqlSession dbSqlSession = commandContext.getSession(DbSqlSession.class);
    for (ProcessDefinitionEntity processDefinition : processDefinitions) {
        List<TimerEntity> timers = new ArrayList<TimerEntity>();
        if (deployment.isNew()) {
            int processDefinitionVersion;
            ProcessDefinitionEntity latestProcessDefinition = null;
            if (processDefinition.getTenantId() != null && !ProcessEngineConfiguration.NO_TENANT_ID.equals(processDefinition.getTenantId())) {
                latestProcessDefinition = processDefinitionManager.findLatestProcessDefinitionByKeyAndTenantId(processDefinition.getKey(), processDefinition.getTenantId());
            } else {
                latestProcessDefinition = processDefinitionManager.findLatestProcessDefinitionByKey(processDefinition.getKey());
            }
            if (latestProcessDefinition != null) {
                processDefinitionVersion = latestProcessDefinition.getVersion() + 1;
            } else {
                processDefinitionVersion = 1;
            }
            processDefinition.setVersion(processDefinitionVersion);
            processDefinition.setDeploymentId(deployment.getId());
            String nextId = idGenerator.getNextId();
            String processDefinitionId = processDefinition.getKey() + ":" + processDefinition.getVersion() + ":" + // ACT-505
            nextId;
            // ACT-115: maximum id length is 64 charcaters
            if (processDefinitionId.length() > 64) {
                processDefinitionId = nextId;
            }
            processDefinition.setId(processDefinitionId);
            if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
                commandContext.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_CREATED, processDefinition));
            }
            removeObsoleteTimers(processDefinition);
            addTimerDeclarations(processDefinition, timers);
            removeExistingMessageEventSubscriptions(processDefinition, latestProcessDefinition);
            addMessageEventSubscriptions(processDefinition);
            removeExistingSignalEventSubScription(processDefinition, latestProcessDefinition);
            addSignalEventSubscriptions(processDefinition);
            dbSqlSession.insert(processDefinition);
            addAuthorizations(processDefinition);
            if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
                commandContext.getProcessEngineConfiguration().getEventDispatcher().dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_INITIALIZED, processDefinition));
            }
            scheduleTimers(timers);
        } else {
            String deploymentId = deployment.getId();
            processDefinition.setDeploymentId(deploymentId);
            ProcessDefinitionEntity persistedProcessDefinition = null;
            if (processDefinition.getTenantId() == null || ProcessEngineConfiguration.NO_TENANT_ID.equals(processDefinition.getTenantId())) {
                persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKey(deploymentId, processDefinition.getKey());
            } else {
                persistedProcessDefinition = processDefinitionManager.findProcessDefinitionByDeploymentAndKeyAndTenantId(deploymentId, processDefinition.getKey(), processDefinition.getTenantId());
            }
            if (persistedProcessDefinition != null) {
                processDefinition.setId(persistedProcessDefinition.getId());
                processDefinition.setVersion(persistedProcessDefinition.getVersion());
                processDefinition.setSuspensionState(persistedProcessDefinition.getSuspensionState());
            }
        }
        // Add to cache
        DeploymentManager deploymentManager = processEngineConfiguration.getDeploymentManager();
        deploymentManager.getProcessDefinitionCache().add(processDefinition.getId(), processDefinition);
        addDefinitionInfoToCache(processDefinition, processEngineConfiguration, commandContext);
        // Add to deployment for further usage
        deployment.addDeployedArtifact(processDefinition);
        createLocalizationValues(processDefinition.getId(), bpmnModelMap.get(processDefinition.getKey()).getProcessById(processDefinition.getKey()));
    }
}
Also used : ActivitiException(org.activiti.engine.ActivitiException) ProcessDefinitionEntityManager(org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntityManager) CommandContext(org.activiti.engine.impl.interceptor.CommandContext) HashMap(java.util.HashMap) TimerEntity(org.activiti.engine.impl.persistence.entity.TimerEntity) DeploymentManager(org.activiti.engine.impl.persistence.deploy.DeploymentManager) ArrayList(java.util.ArrayList) BpmnModel(org.activiti.bpmn.model.BpmnModel) DbSqlSession(org.activiti.engine.impl.db.DbSqlSession) ByteArrayInputStream(java.io.ByteArrayInputStream) ResourceEntity(org.activiti.engine.impl.persistence.entity.ResourceEntity) ProcessDefinitionEntity(org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity) ProcessEngineConfigurationImpl(org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl) BpmnParse(org.activiti.engine.impl.bpmn.parser.BpmnParse)

Example 73 with BpmnModel

use of org.activiti.bpmn.model.BpmnModel in project Activiti by Activiti.

the class MessageEventDefinitionWithExtensionElementsTest method testParseMessagedDefinitionWithExtension.

@Test
public void testParseMessagedDefinitionWithExtension() {
    BpmnParse bpmnParseMock = Mockito.mock(BpmnParse.class);
    MessageEventDefinition messageEventDefinitionMock = Mockito.mock(MessageEventDefinition.class);
    BpmnModel bpmnModelMock = Mockito.mock(BpmnModel.class);
    Message messageMock = Mockito.mock(Message.class);
    @SuppressWarnings("unchecked") Map<String, List<ExtensionElement>> extensionElementMap = Mockito.mock(Map.class);
    Mockito.when(bpmnParseMock.getBpmnModel()).thenReturn(bpmnModelMock);
    Mockito.when(messageEventDefinitionMock.getMessageRef()).thenReturn("messageId");
    Mockito.when(bpmnModelMock.containsMessageId("messageId")).thenReturn(true);
    Mockito.when(bpmnModelMock.getMessage("messageId")).thenReturn(messageMock);
    Mockito.when(messageMock.getName()).thenReturn("MessageWithExtensionElements");
    Mockito.when(messageMock.getExtensionElements()).thenReturn(extensionElementMap);
    MessageEventDefinitionParseHandler handler = new MessageEventDefinitionParseHandler();
    handler.parse(bpmnParseMock, messageEventDefinitionMock);
    Mockito.verify(messageEventDefinitionMock).setMessageRef("MessageWithExtensionElements");
    Mockito.verify(messageEventDefinitionMock).setExtensionElements(extensionElementMap);
}
Also used : Message(org.activiti.bpmn.model.Message) MessageEventDefinitionParseHandler(org.activiti.engine.impl.bpmn.parser.handler.MessageEventDefinitionParseHandler) MessageEventDefinition(org.activiti.bpmn.model.MessageEventDefinition) List(java.util.List) BpmnParse(org.activiti.engine.impl.bpmn.parser.BpmnParse) BpmnModel(org.activiti.bpmn.model.BpmnModel) Test(org.junit.Test)

Example 74 with BpmnModel

use of org.activiti.bpmn.model.BpmnModel in project Activiti by Activiti.

the class ProcessEngineMvcEndpoint method processDefinitionDiagram.

/**
     * Look up the process definition by key. For example,
     * this is <A href="http://localhost:8080/activiti/processes/fulfillmentProcess">process-diagram for</A>
     * a process definition named {@code fulfillmentProcess}.
     */
@RequestMapping(value = "/processes/{processDefinitionKey:.*}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public ResponseEntity processDefinitionDiagram(@PathVariable String processDefinitionKey) {
    ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey).latestVersion().singleResult();
    if (processDefinition == null) {
        return ResponseEntity.status(NOT_FOUND).body(null);
    }
    ProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
    BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
    if (bpmnModel.getLocationMap().size() == 0) {
        BpmnAutoLayout autoLayout = new BpmnAutoLayout(bpmnModel);
        autoLayout.execute();
    }
    InputStream is = processDiagramGenerator.generateJpgDiagram(bpmnModel);
    return ResponseEntity.ok(new InputStreamResource(is));
}
Also used : DefaultProcessDiagramGenerator(org.activiti.image.impl.DefaultProcessDiagramGenerator) ProcessDiagramGenerator(org.activiti.image.ProcessDiagramGenerator) InputStream(java.io.InputStream) BpmnAutoLayout(org.activiti.bpmn.BpmnAutoLayout) ProcessDefinition(org.activiti.engine.repository.ProcessDefinition) DefaultProcessDiagramGenerator(org.activiti.image.impl.DefaultProcessDiagramGenerator) BpmnModel(org.activiti.bpmn.model.BpmnModel) InputStreamResource(org.springframework.core.io.InputStreamResource) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 75 with BpmnModel

use of org.activiti.bpmn.model.BpmnModel in project Activiti by Activiti.

the class ProcessInstanceDetailPanel method addProcessImage.

protected void addProcessImage() {
    ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService).getDeployedProcessDefinition(processDefinition.getId());
    // Only show when graphical notation is defined
    if (processDefinitionEntity != null) {
        boolean didDrawImage = false;
        if (ExplorerApp.get().isUseJavascriptDiagram()) {
            try {
                final InputStream definitionStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), processDefinition.getResourceName());
                XMLInputFactory xif = XmlUtil.createSafeXmlInputFactory();
                XMLStreamReader xtr = xif.createXMLStreamReader(definitionStream);
                BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);
                if (!bpmnModel.getFlowLocationMap().isEmpty()) {
                    int maxX = 0;
                    int maxY = 0;
                    for (String key : bpmnModel.getLocationMap().keySet()) {
                        GraphicInfo graphicInfo = bpmnModel.getGraphicInfo(key);
                        double elementX = graphicInfo.getX() + graphicInfo.getWidth();
                        if (maxX < elementX) {
                            maxX = (int) elementX;
                        }
                        double elementY = graphicInfo.getY() + graphicInfo.getHeight();
                        if (maxY < elementY) {
                            maxY = (int) elementY;
                        }
                    }
                    // using panel for scrollbars
                    Panel imagePanel = new Panel();
                    imagePanel.addStyleName(Reindeer.PANEL_LIGHT);
                    imagePanel.setWidth(100, UNITS_PERCENTAGE);
                    imagePanel.setHeight(100, UNITS_PERCENTAGE);
                    URL explorerURL = ExplorerApp.get().getURL();
                    URL url = new URL(explorerURL.getProtocol(), explorerURL.getHost(), explorerURL.getPort(), explorerURL.getPath().replace("/ui", "") + "diagram-viewer/index.html?processDefinitionId=" + processDefinition.getId() + "&processInstanceId=" + processInstance.getId());
                    Embedded browserPanel = new Embedded("", new ExternalResource(url));
                    browserPanel.setType(Embedded.TYPE_BROWSER);
                    browserPanel.setWidth(maxX + 350 + "px");
                    browserPanel.setHeight(maxY + 220 + "px");
                    HorizontalLayout panelLayoutT = new HorizontalLayout();
                    panelLayoutT.setSizeUndefined();
                    imagePanel.setContent(panelLayoutT);
                    imagePanel.addComponent(browserPanel);
                    panelLayout.addComponent(imagePanel);
                    didDrawImage = true;
                }
            } catch (Exception e) {
                LOGGER.error("Error loading process diagram component", e);
            }
        }
        if (!didDrawImage && processDefinitionEntity.isGraphicalNotationDefined()) {
            ProcessEngineConfiguration processEngineConfiguration = ProcessEngines.getDefaultProcessEngine().getProcessEngineConfiguration();
            ProcessDiagramGenerator diagramGenerator = processEngineConfiguration.getProcessDiagramGenerator();
            StreamResource diagram = new ProcessDefinitionImageStreamResourceBuilder().buildStreamResource(processInstance, repositoryService, runtimeService, diagramGenerator, processEngineConfiguration);
            if (diagram != null) {
                Label header = new Label(i18nManager.getMessage(Messages.PROCESS_HEADER_DIAGRAM));
                header.addStyleName(ExplorerLayout.STYLE_H3);
                header.addStyleName(ExplorerLayout.STYLE_DETAIL_BLOCK);
                header.addStyleName(ExplorerLayout.STYLE_NO_LINE);
                panelLayout.addComponent(header);
                Embedded embedded = new Embedded(null, diagram);
                embedded.setType(Embedded.TYPE_IMAGE);
                embedded.setSizeUndefined();
                // using panel for scrollbars
                Panel imagePanel = new Panel();
                imagePanel.setScrollable(true);
                imagePanel.addStyleName(Reindeer.PANEL_LIGHT);
                imagePanel.setWidth(100, UNITS_PERCENTAGE);
                imagePanel.setHeight(100, UNITS_PERCENTAGE);
                HorizontalLayout panelLayoutT = new HorizontalLayout();
                panelLayoutT.setSizeUndefined();
                imagePanel.setContent(panelLayoutT);
                imagePanel.addComponent(embedded);
                panelLayout.addComponent(imagePanel);
            }
        }
    }
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) InputStream(java.io.InputStream) GraphicInfo(org.activiti.bpmn.model.GraphicInfo) Label(com.vaadin.ui.Label) PrettyTimeLabel(org.activiti.explorer.ui.custom.PrettyTimeLabel) ExternalResource(com.vaadin.terminal.ExternalResource) URL(java.net.URL) BpmnModel(org.activiti.bpmn.model.BpmnModel) BpmnXMLConverter(org.activiti.bpmn.converter.BpmnXMLConverter) HorizontalLayout(com.vaadin.ui.HorizontalLayout) Panel(com.vaadin.ui.Panel) DetailPanel(org.activiti.explorer.ui.custom.DetailPanel) ProcessEngineConfiguration(org.activiti.engine.ProcessEngineConfiguration) StreamResource(com.vaadin.terminal.StreamResource) ProcessDiagramGenerator(org.activiti.image.ProcessDiagramGenerator) ProcessDefinitionEntity(org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity) Embedded(com.vaadin.ui.Embedded) ProcessDefinitionImageStreamResourceBuilder(org.activiti.explorer.ui.process.ProcessDefinitionImageStreamResourceBuilder) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Aggregations

BpmnModel (org.activiti.bpmn.model.BpmnModel)149 Test (org.junit.Test)101 BpmnXMLConverter (org.activiti.bpmn.converter.BpmnXMLConverter)15 InputStream (java.io.InputStream)13 ByteArrayInputStream (java.io.ByteArrayInputStream)10 Deployment (org.activiti.engine.repository.Deployment)10 Process (org.activiti.bpmn.model.Process)8 ProcessDefinition (org.activiti.engine.repository.ProcessDefinition)8 ProcessInstance (org.activiti.engine.runtime.ProcessInstance)8 StartEvent (org.activiti.bpmn.model.StartEvent)7 ActivitiException (org.activiti.engine.ActivitiException)7 ProcessDefinitionEntity (org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity)7 ArrayList (java.util.ArrayList)6 XMLInputFactory (javax.xml.stream.XMLInputFactory)6 XMLStreamReader (javax.xml.stream.XMLStreamReader)6 UserTask (org.activiti.bpmn.model.UserTask)6 FlowElement (org.activiti.bpmn.model.FlowElement)5 BpmnJsonConverter (org.activiti.editor.language.json.converter.BpmnJsonConverter)5 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)4 StreamResource (com.vaadin.terminal.StreamResource)4