### Verify Java Development Kit (JDK) Installation Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch01-Introduction.adoc This command-line snippet is used to verify the successful installation of a Java Development Kit (JDK) by displaying its version. It helps confirm that the JDK is correctly set up and accessible from the command line. ```shell java -version ``` -------------------------------- ### Comprehensive Activiti Financial Report Process Example in Java Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch07a-BPMN-Introduction.adoc This comprehensive Java example demonstrates a complete Activiti workflow for a financial report process. It covers creating and configuring the process engine, deploying a BPMN definition, starting a process instance, querying and claiming tasks for different groups, completing tasks, and verifying process completion. ```Java public class TenMinuteTutorial { public static void main(String[] args) { // Create Activiti process engine ProcessEngine processEngine = ProcessEngineConfiguration .createStandaloneProcessEngineConfiguration() .buildProcessEngine(); // Get Activiti services RepositoryService repositoryService = processEngine.getRepositoryService(); RuntimeService runtimeService = processEngine.getRuntimeService(); // Deploy the process definition repositoryService.createDeployment() .addClasspathResource("FinancialReportProcess.bpmn20.xml") .deploy(); // Start a process instance String procId = runtimeService.startProcessInstanceByKey("financialReport").getId(); // Get the first task TaskService taskService = processEngine.getTaskService(); List tasks = taskService.createTaskQuery().taskCandidateGroup("accountancy").list(); for (Task task : tasks) { System.out.println("Following task is available for accountancy group: " + task.getName()); // claim it taskService.claim(task.getId(), "fozzie"); } // Verify Fozzie can now retrieve the task tasks = taskService.createTaskQuery().taskAssignee("fozzie").list(); for (Task task : tasks) { System.out.println("Task for fozzie: " + task.getName()); // Complete the task taskService.complete(task.getId()); } System.out.println("Number of tasks for fozzie: " + taskService.createTaskQuery().taskAssignee("fozzie").count()); // Retrieve and claim the second task tasks = taskService.createTaskQuery().taskCandidateGroup("management").list(); for (Task task : tasks) { ``` -------------------------------- ### Example BPMN 2.0 Process Definition Start Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch05-Spring.adoc This snippet shows the beginning of a BPMN 2.0 process definition XML file. When placed in the 'processes' folder, Activiti will automatically deploy such definitions upon application startup. ```XML variables = new HashMap(); variables.put(TEST_VARIABLE, TEST_VALUE); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(USERTASK_PROCESS, BUSINESS_KEY, variables); Task task = taskService.createTaskQuery().taskDefinitionKey("userTask").singleResult(); TimeUnit.MILLISECONDS.sleep(50); taskService.complete(task.getId()); ``` -------------------------------- ### Complete Custom Service Task Implementation with Overrides and Properties Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch11-Designer.adoc Provides a comprehensive example of a custom service task, `AcmeMoneyTask`, showcasing class-level annotations for runtime behavior and help, multiple properties (including required fields and multi-line text), and overridden methods for palette drawer, node name, and small icon path. This example demonstrates a fully functional custom node. ```java /** * @author John Doe * @version 1 * @since 1.0.0 */ @Runtime(javaDelegateClass = "org.acme.runtime.AcmeMoneyJavaDelegation") @Help(displayHelpShort = "Creates a new account", displayHelpLong = "Creates a new account using the account number specified") public class AcmeMoneyTask extends AbstractCustomServiceTask { private static final String HELP_ACCOUNT_NUMBER_LONG = "Provide a number that is suitable as an account number."; @Property(type = PropertyType.TEXT, displayName = "Account Number", required = true) @Help(displayHelpShort = "Provide an account number", displayHelpLong = HELP_ACCOUNT_NUMBER_LONG) private String accountNumber; @Property(type = PropertyType.MULTILINE_TEXT, displayName = "Comments") @Help(displayHelpShort = "Provide comments", displayHelpLong = "You can add comments to the node to provide a brief description.") private String comments; /* * (non-Javadoc) * * @see org.activiti.designer.integration.servicetask.AbstractCustomServiceTask #contributeToPaletteDrawer() */ @Override public String contributeToPaletteDrawer() { return "Acme Corporation"; } @Override public String getName() { return "Money node"; } /* * (non-Javadoc) * * @see org.activiti.designer.integration.servicetask.AbstractCustomServiceTask #getSmallIconPath() */ @Override public String getSmallIconPath() { return "icons/coins.png"; } } ``` -------------------------------- ### Start and Verify Replayed Process Instance in Activiti Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch18-Simulation.adoc This code block illustrates the initialization of the simulation and the subsequent stepping to start the replayed process. It includes assertions to verify that no process instances or tasks are running initially, and then confirms that the replayed process and its associated user task are active after the simulation step. ```Java simRun.init(); // original process is finished - there should not be any running process instance/task assertEquals(0, runtimeService.createProcessInstanceQuery().processDefinitionKey(USERTASK_PROCESS).count()); assertEquals(0, taskService.createTaskQuery().taskDefinitionKey("userTask").count()); simRun.step(); // replay process was started assertEquals(1, runtimeService.createProcessInstanceQuery().processDefinitionKey(USERTASK_PROCESS).count()); // there should be one task assertEquals(1, taskService.createTaskQuery().taskDefinitionKey("userTask").count()); ``` -------------------------------- ### Start New Process Instance by Key with Activiti Java API Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch07a-BPMN-Introduction.adoc This Java code snippet shows how to start a new process instance for a previously deployed process definition. It uses the `runtimeService` and the `startProcessInstanceByKey` method, passing the process definition's key ('financialReport') to initiate a new execution of the business process. ```java ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("financialReport"); ``` -------------------------------- ### Start Activiti Process Instance and Cleanup Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch18-Simulation.adoc This snippet demonstrates how to start a process instance with variables using Activiti's RuntimeService and then perform status checks and clean up the process engine. It highlights the recording of ActivitiEventType.ENTITY_CREATED after process initiation. ```java Map variables = new HashMap(); variables.put(TEST_VARIABLE, TEST_VALUE); processEngine.getRuntimeService().startProcessInstanceByKey(SIMPLEST_PROCESS, BUSINESS_KEY,variables); // check process engine status - there should be one process instance in the history checkStatus(processEngine); // close and destroy process engine EventRecorderTestUtils.closeProcessEngine(processEngine, listener); ProcessEngines.destroy(); ``` -------------------------------- ### Activiti JUnit 3 Unit Test Example Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch04-API.adoc A JUnit 3 style test class extending ActivitiTestCase, demonstrating how to deploy a process definition using the @Deployment annotation and interact with Activiti services to start a process, query tasks, and complete them. ```Java public class MyBusinessProcessTest extends ActivitiTestCase { @Deployment public void testSimpleProcess() { runtimeService.startProcessInstanceByKey("simpleProcess"); Task task = taskService.createTaskQuery().singleResult(); assertEquals("My Task", task.getName()); taskService.complete(task.getId()); assertEquals(0, runtimeService.createProcessInstanceQuery().count()); } } ``` -------------------------------- ### Activiti XML Process Definition Example Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch06-Deployment.adoc Illustrates a basic Activiti BPMN 2.0 XML process definition with an ID and name, used to demonstrate initial deployment and versioning behavior within the Activiti engine. ```xml ... ``` -------------------------------- ### Activiti processes.xml for Auto-Deployment Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch15-Cdi.adoc An example `processes.xml` file used by Activiti CDI for auto-deploying BPMN process definitions. This XML file lists process resources (e.g., BPMN 2.0 XML files) that Activiti CDI will automatically deploy when the application starts, provided the file is located at the top-level of the classpath. ```xml ``` -------------------------------- ### Activiti Java: Start Process Instance by Key Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch07a-BPMN-Introduction.adoc This Java code snippet shows how to start a new process instance using the `startProcessInstanceByKey` method of Activiti's `RuntimeService`. This method uses the process definition's `id` (key) and always activates the latest deployed version. It's distinct from `startProcessInstanceById`, which requires an engine-generated ID. ```Java ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("myProcess"); ``` -------------------------------- ### Java: Configure CommandLineRunner for Initial User Setup Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch05-Spring.adoc This snippet shows how to configure a Spring Boot 'CommandLineRunner' bean. This runner executes the 'createDemoUsers()' method of 'MyService' when the application starts, ensuring initial user data is populated. ```java @Bean public CommandLineRunner init(final MyService myService) { return new CommandLineRunner() { public void run(String... strings) throws Exception { myService.createDemoUsers(); } }; } ``` -------------------------------- ### Additional Spring Configuration for Activiti Example Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch05-Spring.adoc This XML snippet provides additional Spring configuration for a specific example, including enabling annotation-driven transactions and defining a custom `UserBean` that interacts with the `runtimeService`. ```XML ... ``` -------------------------------- ### Activiti Demo Data Properties Configuration Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch02-GettingStarted.adoc This configuration snippet defines properties to enable the creation of demo users, process definitions, models, and reports when Activiti is initialized. Setting these to 'true' ensures that sample data is available for testing and demonstration purposes. ```Properties create.demo.users=true create.demo.definitions=true create.demo.models=true create.demo.reports=true ``` -------------------------------- ### Java Implementation of ProcessEngineConfigurator Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch17-Advanced.adoc This Java class provides an example implementation of a `ProcessEngineConfigurator`. It extends `AbstractProcessEngineConfigurator` and overrides the `configure` method to modify the `ProcessEngineConfigurationImpl`. The example specifically shows how to replace the default process definition cache with a custom `MyCache` instance, demonstrating a powerful way to customize core Activiti components. ```java public class ProcessDefinitionCacheConfigurator extends AbstractProcessEngineConfigurator { public void configure(ProcessEngineConfigurationImpl processEngineConfiguration) { MyCache myCache = new MyCache(); processEngineConfiguration.setProcessDefinitionCache(enterpriseProcessDefinitionCache); } } ``` -------------------------------- ### Initialize Activiti Process Engine and Deploy BPMN Process Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch07a-BPMN-Introduction.adoc This Java code demonstrates how to initialize the Activiti ProcessEngine in standalone mode, obtain RepositoryService and RuntimeService, deploy a BPMN process definition from the classpath, and start a new process instance using its key. It sets up the core components for process automation. ```java public static void main(String[] args) { // Create Activiti process engine ProcessEngine processEngine = ProcessEngineConfiguration .createStandaloneProcessEngineConfiguration() .buildProcessEngine(); // Get Activiti services RepositoryService repositoryService = processEngine.getRepositoryService(); RuntimeService runtimeService = processEngine.getRuntimeService(); // Deploy the process definition repositoryService.createDeployment() .addClasspathResource("FinancialReportProcess.bpmn20.xml") .deploy(); // Start a process instance runtimeService.startProcessInstanceByKey("financialReport"); } ``` -------------------------------- ### Install Pygments Ruby Gem for Syntax Highlighting Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/README.txt Installs the 'pygments.rb' library, a Ruby gem, which is essential for enabling syntax highlighting in documentation generated by Asciidoctor. ```Shell gem install pygments.rb ``` -------------------------------- ### Start Activiti Process Instance with Initial Variables Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch04-API.adoc Demonstrates how to initiate a new Activiti process instance using the `RuntimeService` while simultaneously providing a `Map` of initial process variables. These variables are available to the process from its very beginning. ```java ProcessInstance startProcessInstanceByKey(String processDefinitionKey, Map variables); ``` -------------------------------- ### Starting an Activiti Process Instance with Java RuntimeService Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch04-API.adoc Illustrates how to initiate a new process instance from a deployed process definition using the RuntimeService. It shows how to pass initial process variables, which are crucial for customizing the instance's behavior and data. ```java Map variables = new HashMap(); variables.put("employeeName", "Kermit"); variables.put("numberOfDays", new Integer(4)); variables.put("vacationMotivation", "I'm really tired!"); RuntimeService runtimeService = processEngine.getRuntimeService(); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("vacationRequest", variables); // Verify that we started a new process instance Log.info("Number of process instances: " + runtimeService.createProcessInstanceQuery().count()); ``` -------------------------------- ### Retrieving Initialized Activiti Process Engine Instances Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch04-API.adoc This Java snippet illustrates how to retrieve an initialized Activiti Process Engine instance. It shows methods to get the default engine or a specific engine by its name, useful after the engine has been set up, for example, by a `ServletContextListener`. ```java ProcessEngines.getDefaultProcessEngine() ProcessEngines.getProcessEngine("myName"); ``` -------------------------------- ### Java Method with @StartProcess Annotation Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch15-Cdi.adoc Illustrates the use of the `@StartProcess` annotation from Activiti CDI to declaratively start a process instance by key. The process instance is initiated after the annotated method returns, simplifying process initiation directly within business logic methods. ```java @StartProcess("authorizeBusinessTripRequest") public String submitRequest(BusinessTripRequest request) { // do some work return "success"; } ``` -------------------------------- ### Activiti UEL Method Expression Examples Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch04-API.adoc Examples demonstrating how to invoke methods using method expressions in Activiti, with or without parameters. Parameters can be literal values or other expressions. ```UEL ${printer.print()} ${myBean.addNewOrder('orderName')} ${myBean.doSomething(myVar, execution)} ``` -------------------------------- ### Configure Basic Maven Project Structure in pom.xml Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch11-Designer.adoc This snippet shows the initial structure of a Maven `pom.xml` file, defining the project's `groupId`, `artifactId`, `version`, `packaging`, and `name`. It serves as the foundation for an Activiti Designer extension project. ```xml 4.0.0 org.acme money-tasks 1.0.0 jar Acme Corporation Money Tasks ... ``` -------------------------------- ### Activiti UEL Value Expression Examples Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch04-API.adoc Examples demonstrating how to use value expressions in Activiti, resolving to a specific value. Process variables and Spring beans are available for use. ```UEL ${myVar} ${myBean.myProperty} ``` -------------------------------- ### Retrieve Start Form Data (Java) Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch08-Forms.adoc Demonstrates how to use the `FormService` to retrieve form data required to start a new process instance. The `StartFormData` object contains properties relevant for the initial user input. ```java StartFormData FormService.getStartFormData(String processDefinitionId) ``` -------------------------------- ### Interacting with Activiti Services Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch04-API.adoc Explains the primary method of interacting with the Activiti engine via services exposed by the `org.activiti.engine.ProcessEngine` class. It highlights the `RepositoryService` for managing static data like process definitions and mentions the `taskService.claim` method as an example of API usage. ```APIDOC org.activiti.engine.ProcessEngine: Description: The main entry point for interacting with the Activiti engine, exposing various services. RepositoryService: Description: Service for accessing and managing 'static' data, such as process definitions, within the Activiti engine's repository. taskService.claim(taskId: string): Description: Claims a task for a specific user. Throws ActivitiTaskAlreadyClaimedException if the task is already claimed. ``` -------------------------------- ### Activiti Designer Extension API Reference Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch11-Designer.adoc Reference documentation for key classes and methods used when extending Activiti Designer, including base classes for Process Validators and Export Marshallers, and utilities for marker management and progress reporting. ```APIDOC AbstractDiagramWorker: - clearMarkers(): Clears any previous markers for the current worker. - getResourceForDiagram(diagram): Returns the resource for the given diagram. - addProblemToDiagram(): Adds an error marker to the diagram. - addWarningToDiagram(): Adds a warning marker to the diagram. DiagramWorkerContext: - Provides access to diagram information (Resources, InputStreams) and progress monitor. ProcessValidator (extension point): - Required to subclass AbstractProcessValidator. AbstractProcessValidator (base class): - Extends AbstractDiagramWorker. - getValidatorId(): Returns a globally unique ID for the validator. - getValidatorName(): Returns a logical name for the validator, shown to the user. - getFormatName(): Returns the type of diagram the validator typically validates. - validateDiagram(): Performs the core validation work. - Parameters: (Implicitly, the diagram context) - Returns: boolean (true for success, false for failure) ExportMarshaller (extension point): - Required to subclass AbstractExportMarshaller. AbstractExportMarshaller (base class): - Extends AbstractDiagramWorker. - Provides methods for saving resources to the workspace and invoking validators. ``` -------------------------------- ### Starting an Activiti Process with a JPA Entity Variable Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch09-JPA.adoc This Java snippet demonstrates how to initiate an Activiti process instance. It shows the creation of a HashMap to hold process variables, including a JPA entity (entityToUpdate). The runtimeService.startProcessInstanceByKey method is then used to start the process, passing the entity as a process variable, which Activiti will persist. ```java Map variables = new HashMap(); variables.put("entityToUpdate", entityToUpdate); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("UpdateJPAValuesProcess", variables); ``` -------------------------------- ### Activiti XML Process Definition for a New Process Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch06-Deployment.adoc Shows an XML process definition for a distinct new process. This example highlights how Activiti differentiates processes based on their 'id' attribute, leading to a new version 1 deployment even if the name is identical to an existing process. ```xml ... ``` -------------------------------- ### Configure Activiti Process Engine for Glassfish 3.1.1 Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch15-Cdi.adoc Example Spring configuration file (activiti.cfg.xml) for setting up the Activiti Process Engine in a Glassfish 3.1.1 environment, assuming a pre-configured JDBC datasource. ```XML ``` -------------------------------- ### Define Report Start Form with Form Properties (XML) Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch12-Explorer.adoc This XML snippet illustrates how to configure a start event in an Activiti process definition to include a user-facing form. It uses activiti:formProperty to define input fields for selecting a process definition and a chart type (pie or bar), both marked as required, enabling user interaction before report generation. ```xml ``` -------------------------------- ### Example UserBean with Activiti RuntimeService Injection and Transactional Method Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch05-Spring.adoc Defines the `UserBean` class, showing how `RuntimeService` is injected by Spring and how the `hello()` method is marked `@Transactional` to combine domain logic with Activiti service calls within the same transaction. ```java public class UserBean { /** injected by Spring */ private RuntimeService runtimeService; @Transactional public void hello() { // here you can do transactional stuff in your domain model // and it will be combined in the same transaction as // the startProcessInstanceByKey to the Activiti RuntimeService runtimeService.startProcessInstanceByKey("helloProcess"); } public void setRuntimeService(RuntimeService runtimeService) { this.runtimeService = runtimeService; } } ``` -------------------------------- ### Java: MyService Methods for Process and User Management Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch05-Spring.adoc This Java code snippet defines methods within a 'MyService' class for interacting with Activiti and a 'personRepository'. It includes functionality to start a process instance, retrieve tasks assigned to a user, and create initial demo users if none exist. ```java Person person = personRepository.findByUsername(assignee); Map variables = new HashMap(); variables.put("person", person); runtimeService.startProcessInstanceByKey("oneTaskProcess", variables); } public List getTasks(String assignee) { return taskService.createTaskQuery().taskAssignee(assignee).list(); } public void createDemoUsers() { if (personRepository.findAll().size() == 0) { personRepository.save(new Person("jbarrez", "Joram", "Barrez", new Date())); personRepository.save(new Person("trademakers", "Tijs", "Rademakers", new Date())); } } } ``` -------------------------------- ### Configure Eclipse Project with Maven Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch11-Designer.adoc This snippet shows the Maven command to configure an Eclipse project, setting up source folders like 'src/main/java' and 'src/main/resources' based on the 'pom.xml' instructions. This is a crucial step for preparing the project for Activiti Designer extension development. ```Maven mvn eclipse:eclipse ``` -------------------------------- ### Spring Boot application to run Activiti processes on startup Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch05-Spring.adoc This Java class defines a Spring Boot application that initializes and runs Activiti processes. It includes a CommandLineRunner bean that executes on application startup, querying process definitions and tasks, and starting an instance of the 'oneTaskProcess' to demonstrate Activiti integration. ```java @Configuration @ComponentScan @EnableAutoConfiguration public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } @Bean public CommandLineRunner init(final RepositoryService repositoryService, final RuntimeService runtimeService, final TaskService taskService) { return new CommandLineRunner() { @Override public void run(String... strings) throws Exception { System.out.println("Number of process definitions : " + repositoryService.createProcessDefinitionQuery().count()); System.out.println("Number of tasks : " + taskService.createTaskQuery().count()); runtimeService.startProcessInstanceByKey("oneTaskProcess"); System.out.println("Number of tasks after process start: " + taskService.createTaskQuery().count()); } }; } } ``` -------------------------------- ### Simplest Activiti Process Definition (BPMN XML) Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch18-Simulation.adoc This XML snippet defines 'theSimplestProcess', a basic Activiti BPMN process used for testing purposes in the Crystalball simulation. It includes a start event, a sequence flow, and an end event, representing a minimal process flow without any user tasks. ```XML This is a process for testing purposes ``` -------------------------------- ### Testing Activiti Business Process with JUnit Rule Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch04-API.adoc This Java code demonstrates how to write a JUnit test for an Activiti business process using the `ActivitiRule`. It shows how to start a process instance, query for a task, assert its name, and complete the task, verifying the process instance count afterwards. ```java public class MyBusinessProcessTest { @Rule public ActivitiRule activitiRule = new ActivitiRule(); @Test @Deployment public void ruleUsageExample() { RuntimeService runtimeService = activitiRule.getRuntimeService(); runtimeService.startProcessInstanceByKey("ruleUsage"); TaskService taskService = activitiRule.getTaskService(); Task task = taskService.createTaskQuery().singleResult(); assertEquals("My Task", task.getName()); taskService.complete(task.getId()); assertEquals(0, runtimeService.createProcessInstanceQuery().count()); } } ``` -------------------------------- ### Activiti Process Engine Configuration with Custom EntityManagerFactory Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch09-JPA.adoc Example configuration demonstrating how to provide a custom `EntityManagerFactory` (e.g., OpenJPA) to the Activiti process engine. This allows for more granular control over JPA setup. ```xml ``` -------------------------------- ### Shell: Start Activiti Process Instance via REST API Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch05-Spring.adoc This 'curl' command demonstrates how to initiate a new Activiti process instance by sending an HTTP POST request to the '/process' endpoint. The request body contains a JSON payload specifying the 'assignee' username. ```shell curl -H "Content-Type: application/json" -d '{"assignee" : "jbarrez"}' http://localhost:8080/process ``` -------------------------------- ### Add Activiti Designer Integration Library Dependency to Maven pom.xml Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch11-Designer.adoc This `pom.xml` snippet demonstrates how to include the `org.activiti.designer.integration` library as a dependency in your Maven project. It also specifies the Activiti Maven repository for dependency resolution, ensuring your extension can access necessary Activiti Designer interfaces. ```xml org.activiti.designer org.activiti.designer.integration 5.12.0 compile ... Activiti https://maven.alfresco.com/nexus/content/groups/public/ ``` -------------------------------- ### Run Activiti Explorer Docker Container Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch19-tooling.adoc This command executes the 'activiti/activiti-single-image' Docker image, mapping the container's port 8080 to the host's port 8080, and starts the Activiti Explorer web application. The '-t -i' flags provide an interactive terminal. ```Docker docker run -p 8080:8080 -t -i activiti/activiti-single-image:latest explorer ``` -------------------------------- ### Activiti Process Engine Configuration with JPA Persistence Unit Name Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch09-JPA.adoc Example configuration for the Activiti process engine using `jpaPersistenceUnitName` to reference a JPA persistence unit. This setup automatically detects and handles JPA entities as process variables. ```xml ``` -------------------------------- ### Add and Remove Activiti Event Listeners at Runtime using RuntimeService Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch03-Configuration.adoc This section introduces the capability to dynamically manage event listeners using the Activiti RuntimeService API. The provided Java snippet indicates the start of an API usage example for adding or removing listeners during runtime. ```java /** ``` -------------------------------- ### Deploy BPMN Process Definition with Activiti Java API Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch07a-BPMN-Introduction.adoc This Java code snippet demonstrates how to deploy a BPMN 2.0 process definition to the Activiti engine. It uses the `repositoryService` to create a new deployment, adding the 'FinancialReportProcess.bpmn20.xml' file as a classpath resource, and then deploys it. This makes the process definition available for creating process instances. ```java Deployment deployment = repositoryService.createDeployment() .addClasspathResource("FinancialReportProcess.bpmn20.xml") .deploy(); ``` -------------------------------- ### BPMN Process Definition for Process Instance Overview Report (JDK 6+) Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch12-Explorer.adoc This BPMN 2.0 XML defines a similar process compatible with JDK 6 and higher. It highlights the structural differences required when native JSON capabilities are unavailable, necessitating the use of helper classes (ReportData and Dataset) for data generation within the script task (the full script content is not provided in this truncated example). ```XML getTasks(@RequestParam String assignee) { List tasks = myService.getTasks(assignee); List dtos = new ArrayList(); for (Task task : tasks) { dtos.add(new TaskRepresentation(task.getId(), task.getName())); } return dtos; } static class TaskRepresentation { private String id; private String name; public TaskRepresentation(String id, String name) { this.id = id; this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } } ``` -------------------------------- ### Access Activiti Variables in Delegates and Listeners Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch04-API.adoc Provides simplified examples of how to directly access (get and set) process variables from the `execution` object within common Activiti constructs like Java delegates, execution listeners, or task listeners. These methods offer a convenient way to interact with variables when the `execution` or `task` context is already available. ```java execution.getVariables(); execution.getVariables(Collection variableNames); execution.getVariable(String variableName); execution.setVariables(Map variables); execution.setVariable(String variableName, Object value); ``` -------------------------------- ### Configure Maven Compiler and JAR Plugins in pom.xml Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch11-Designer.adoc This `pom.xml` snippet configures the `maven-compiler-plugin` to set the Java source and target levels to 1.5, enabling annotation usage. It also configures the `maven-jar-plugin` to generate the JAR's `MANIFEST.MF` file, allowing for a custom extension name to be embedded. ```xml maven-compiler-plugin 1.5 1.5 true true true org.apache.maven.plugins maven-jar-plugin 2.3.1 true false true Acme Money ``` -------------------------------- ### Activiti Engine Maven Dependency Tree Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch02-GettingStarted.adoc This snippet displays the Maven dependency tree for the Activiti engine version 5.17.0, outlining its direct and transitive dependencies. It lists essential libraries like Jackson for JSON processing, Spring for core functionalities, Mybatis for persistence, and various Apache Commons libraries, providing a comprehensive view of the required classpath for Activiti applications. ```Maven Dependency Tree org.activiti:activiti-engine:jar:5.17.0 +- org.activiti:activiti-bpmn-converter:jar:5.17.0:compile | \- org.activiti:activiti-bpmn-model:jar:5.17.0:compile | +- com.fasterxml.jackson.core:jackson-core:jar:2.2.3:compile | \- com.fasterxml.jackson.core:jackson-databind:jar:2.2.3:compile | \- com.fasterxml.jackson.core:jackson-annotations:jar:2.2.3:compile +- org.activiti:activiti-process-validation:jar:5.17.0:compile +- org.activiti:activiti-image-generator:jar:5.17.0:compile +- org.apache.commons:commons-email:jar:1.2:compile | +- javax.mail:mail:jar:1.4.1:compile | \- javax.activation:activation:jar:1.1:compile +- org.apache.commons:commons-lang3:jar:3.3.2:compile +- org.mybatis:mybatis:jar:3.2.5:compile +- org.springframework:spring-beans:jar:4.0.6.RELEASE:compile | \- org.springframework:spring-core:jar:4.0.6.RELEASE:compile +- joda-time:joda-time:jar:2.6:compile +- org.slf4j:slf4j-api:jar:1.7.6:compile +- org.slf4j:jcl-over-slf4j:jar:1.7.6:compile ``` -------------------------------- ### Initializing Process Engine with Record Listener Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch18-Simulation.adoc This Java code snippet shows how to initialize an Activiti `ProcessEngine` using `RecordableProcessEngineFactory`. It configures the engine with a record listener to log events, preparing it for recording process execution for later simulation playback. ```Java // get process engine with record listener to log events ProcessEngine processEngine = (new RecordableProcessEngineFactory(THE_SIMPLEST_PROCESS, listener)).getObject(); // start process instance with variables ``` -------------------------------- ### Deploying Activiti Process Definition with Diagram Programmatically (Java) Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch06-Deployment.adoc Java code snippet demonstrating how to programmatically deploy an Activiti process definition along with its associated process diagram image. It uses the `repositoryService` to add both the BPMN XML and the image resource to a deployment. ```java repositoryService.createDeployment() .name("expense-process.bar") .addClasspathResource("org/activiti/expenseProcess.bpmn20.xml") .addClasspathResource("org/activiti/expenseProcess.png") .deploy(); ``` -------------------------------- ### Basic BPMN Start Event Declaration (XML) Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch08-Forms.adoc Shows a minimal BPMN XML declaration for a start event. When no specific form properties are defined, all process variables are available, but `getStartFormData().getFormProperties()` will be empty. ```xml ``` -------------------------------- ### GWT Development Mode Metrics and Plugin Embedding Source: https://github.com/lovemyorange/activitisourcecode/blob/master/modules/activiti-webapp-explorer2/src/main/webapp/VAADIN/widgetsets/org.activiti.explorer.CustomWidgetset/hosted.html This snippet includes logic for tracking lightweight startup metrics within GWT Development Mode, such as `onModuleLoadStart` and `moduleEvalEnd`, which are sent to a `$stats` object. Additionally, it dynamically embeds the GWT Hosted Mode plugin using `` and `` HTML tags if the XPCOM-based plugin is not found, ensuring compatibility across different browser environments. ```JavaScript window.onunload = function() { }; window.fireOnModuleLoadStart = function(className) { $stats && $stats({moduleName:$moduleName, sessionId:$sessionId, subSystem:'startup', evtGroup:'moduleStartup', millis:(new Date()).getTime(), type:'onModuleLoadStart', className:className}); }; window.__gwt_module_id = 0; $stats && $stats({moduleName:$moduleName, sessionId:$sessionId, subSystem:'startup', evtGroup:'moduleStartup', millis:(new Date()).getTime(), type:'moduleEvalEnd'}); if (!findPluginXPCOM()) { document.write(''); document.write(''); document.write(''); document.write(''); } ``` -------------------------------- ### Deploying Activiti Business Archive Programmatically with Java Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch06-Deployment.adoc This Java code snippet demonstrates how to programmatically deploy a business archive (BAR file) to an Activiti Engine. It uses the `repositoryService` to create a deployment, name it, add a `ZipInputStream` from the BAR file, and then deploy it. ```Java String barFileName = "path/to/process-one.bar"; ZipInputStream inputStream = new ZipInputStream(new FileInputStream(barFileName)); repositoryService.createDeployment() .name("process-one.bar") .addZipInputStream(inputStream) .deploy(); ``` -------------------------------- ### APIDOC: Activiti FormService Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch04-API.adoc Documentation for Activiti's optional FormService, which facilitates the use of start forms (before process start) and task forms (for task completion). This service exposes form data defined within BPMN 2.0 process definitions, though its use is not mandatory. ```APIDOC FormService (Optional): - Introduces concepts of: - Start form: Shown before process instance starts. - Task form: Displayed when a user completes a task. - Exposes form data defined in BPMN 2.0 process definitions. - Usage is optional; forms do not need to be embedded in process definitions. ``` -------------------------------- ### Build Activiti ProcessEngine with Chained Programmatic Configuration Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch03-Configuration.adoc This Java snippet demonstrates how to programmatically build a `ProcessEngine` by chaining configuration methods. It starts with a standalone in-memory configuration, then customizes properties like database schema update, JDBC URL, and asynchronous executor settings, finally calling `buildProcessEngine()` to create the engine instance. ```java ProcessEngine processEngine = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration() .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_FALSE) .setJdbcUrl("jdbc:h2:mem:my-own-db;DB_CLOSE_DELAY=1000") .setAsyncExecutorEnabled(true) .setAsyncExecutorActivate(false) .buildProcessEngine(); ``` -------------------------------- ### Java: RestController for Starting Process and Data Transfer Object Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch05-Spring.adoc This Java code defines a Spring 'RestController' with an endpoint to start an Activiti process instance via an HTTP POST request. It includes the 'StartProcessRepresentation' static inner class, which serves as a Data Transfer Object (DTO) for receiving the assignee's username from the request body. ```java @RestController public class MyRestController { @Autowired private MyService myService; @RequestMapping(value="/process", method= RequestMethod.POST) public void startProcessInstance(@RequestBody StartProcessRepresentation startProcessRepresentation) { myService.startProcess(startProcessRepresentation.getAssignee()); } ... static class StartProcessRepresentation { private String assignee; public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } } ``` -------------------------------- ### Activiti Process Engine Configuration Classes Overview Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch03-Configuration.adoc Overview of key Activiti Process Engine Configuration classes, detailing their intended use cases and environments. ```APIDOC org.activiti.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration: Description: Convenience class for unit testing. Uses H2 in-memory database by default. Handles transactions. Usage: Ideal for quick tests without extensive configuration. org.activiti.spring.SpringProcessEngineConfiguration: Description: For use when the process engine is integrated into a Spring environment. Usage: Refer to Spring integration section for details. org.activiti.engine.impl.cfg.JtaProcessEngineConfiguration: Description: For standalone engine execution with JTA transactions. Usage: When JTA transaction management is required in standalone mode. ``` -------------------------------- ### BPMN 2.0: Minimal Process Definition XML Structure Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch07a-BPMN-Introduction.adoc This XML snippet illustrates the minimal structure for a BPMN 2.0 process definition. It defines the root `definitions` element with required `xmlns` and `targetNamespace` attributes, and an embedded `process` element with `id` and `name` attributes. It's recommended to have only one process definition per file for easier maintenance. ```XML .. ``` -------------------------------- ### Programmatic Activiti Process Engine Configuration with JPA Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch09-JPA.adoc Example of programmatically configuring the Activiti process engine to use a JPA persistence unit name. ```java ProcessEngine processEngine = ProcessEngineConfiguration .createProcessEngineConfigurationFromResourceDefault() .setJpaPersistenceUnitName("activiti-pu") .buildProcessEngine(); ``` -------------------------------- ### Configure Activiti REST Service Endpoints Source: https://github.com/lovemyorange/activitisourcecode/blob/master/modules/activiti-webapp-explorer2/src/main/webapp/diagram-viewer/index.html This snippet sets up the base URL for the Activiti REST services and defines specific endpoints for fetching process instance highlights, process definition diagrams by ID, and process definition diagrams by key. These URLs use JSONP ('callback=?') for cross-domain requests. ```JavaScript var baseUrl = window.document.location.protocol + "//" + window.document.location.host + "/"; var shortenedUrl = window.document.location.href.replace(baseUrl, ""); baseUrl = baseUrl + shortenedUrl.substring(0, shortenedUrl.indexOf("/")); ActivitiRest.options = { processInstanceHighLightsUrl: baseUrl + "/service/process-instance/{processInstanceId}/highlights?callback=?", processDefinitionUrl: baseUrl + "/service/process-definition/{processDefinitionId}/diagram-layout?callback=?", processDefinitionByKeyUrl: baseUrl + "/service/process-definition/{processDefinitionKey}/diagram-layout?callback=?" }; ``` -------------------------------- ### Example Printer Class for Spring Bean Expressions Source: https://github.com/lovemyorange/activitisourcecode/blob/master/userguide/src/en/ch05-Spring.adoc Defines a simple `Printer` class with a `printMessage()` method, which is invoked by a BPMN expression as demonstrated in the previous snippet. ```java public class Printer { public void printMessage() { System.out.println("hello world"); } } ```