anchor.diff:  [source,java,linenums]
   ----
   DmnEngine dmnEngine = DmnEngines.getDefaultDmnEngine();
  -
   DmnRuleService dmnRuleService = dmnEngine.getDmnRuleService();
   DmnRepositoryService dmnRepositoryService = dmnEngine.getDmnRepositoryService();
   DmnManagementService dmnManagementService = dmnEngine.getDmnManagementService();
  
positive.code: 
  +DmnEngines.getDefaultDmnEngine()+ will initialize and build a DMN engine the first time it is called and afterwards always return the same DMN engine. Proper creation and closing of all DMN engines can be done with +DMNEngines.init()+  and +DMNEngines.destroy()+.
  
  
  The DmnEngines class will scan for all +flowable.dmn.cfg.xml+ and +flowable-dmn-context.xml+ files. For all +flowable.dmn.cfg.xml+ files, the DMN engine will be built in the typical Flowable way: +DmnEngineConfiguration.createDmnEngineConfigurationFromInputStream(inputStream).buildDmnEngine()+. For all +flowable-dmn-context.xml+ files, the DMN engine will be built in the Spring way: First the Spring application context is created and then the DMN engine is obtained from that application context.
  
  All services are stateless. This means that you can easily run Flowable DMN on multiple nodes in a cluster, each going to the same database, without having to worry about which machine actually executed previous calls. Any call to any service is idempotent regardless of where it is executed.
  
  The *DmnRepositoryService* is probably the first service needed when working with the Flowable DMN engine. This service offers operations for managing and manipulating +deployments+ and +DMN definitions+. A DMN definition is the root concept of a DMN model. (The main concepts of DMN are explained in the <dmn-introduction, DMN introduction section>) It contains the definition of the +Decision Table+. 
  A +deployment+ is the unit of packaging within the Flowable DMN engine. A deployment can contain multiple DMN xml files. Deploying a deployment means it is uploaded to the engine, where all DMN definitions are inspected and parsed before being stored in the database. From that point on, the deployment is known to the system and any process included in the deployment can now be started.
  
  Furthermore, this service allows to
  
  * Query on deployments and process definitions known to the engine.
  * Suspend and activate deployments as a whole or specific process definitions. Suspending means no further operations can be done on them, while activation is the opposite operation.
  * Retrieve various resources such as files contained within the deployment or process diagrams that were auto generated by the engine.
  * Retrieve a POJO version of the process definition which can be used to introspect the process using Java rather than xml.
  
  While the +RepositoryService+ is rather about static information (i.e. data that doesn't change, or at least not a lot), the *RuntimeService* is quite the opposite. It deals with starting new process instances of process definitions. As said above, a +process definition+ defines the structure and behaviour of the different steps in a process. A process instance is one execution of such a process definition. For each process definition there typically are many instances running at the same time. The +RuntimeService+ also is the service which is used to retrieve and store +process variables+. This is data which is specific to the given process instance and can be used by various constructs in the process (e.g. an exclusive gateway often uses process variables to determine which path is chosen to continue the process). The +Runtimeservice+ also allows to query on process instances and executions. Executions are a representation of the +$$'token'$$+ concept of BPMN 2.0. Basically an execution is a pointer pointing to where the process instance currently is. Lastly, the +RuntimeService+ is used whenever a process instance is waiting for an external trigger and the process needs to be continued. A process instance can have various +wait states+ and this service contains various operations to 'signal' the instance that the external trigger is received and the process instance can be continued.
  
  
  Tasks that need to be performed by actual human users of the system are core to a BPM engine such as Flowable. Everything around tasks is grouped in the *TaskService*, such as
  
  * Querying tasks assigned to users or groups
  * Creating new _standalone_ tasks. These are tasks that are not related to a process instances.
  * Manipulating to which user a task is assigned or which users are in some way involved with the task.
  * Claiming and completing a task. Claiming means that someone decided to be the assignee for the task, meaning that this user will complete the task. Completing means 'doing the work of the tasks'. Typically this is filling in a form of sorts.
  
  The *IdentityService* is pretty simple. It allows the management (creation, update, deletion, querying, ...) of groups and users. It is important to understand that Flowable actually doesn't do any checking on users at runtime. For example, a task could be assigned to any user, but the engine does not verify if that user is known to the system. This is because the Flowable engine can also be used in conjunction with services such as LDAP, Active Directory, etc.
  
  The *FormService* is an optional service. Meaning that Flowable can perfectly be used without it, without sacrificing any functionality. This service introduces the concept of a _start form_ and a _task form_. A _start form_ is a form that is shown to the user before the process instance is started, while a _task form_ is the form that is displayed when a user wants to complete a form. Flowable allows to define these forms in the BPMN 2.0 process definition. This service exposes this data in an easy way to work with. But again, this is optional as forms don't need to be embedded in the process definition.
  
  The *HistoryService* exposes all historical data gathered by the Flowable engine. When executing processes, a lot of data can be kept by the engine (this is configurable) such as process instance start times, who did which tasks, how long it took to complete the tasks, which path was followed in each process instance, etc. This service exposes mainly query  capabilities to access this data.
  
  The *ManagementService* is typically not needed when coding custom application using Flowable. It allows to retrieve information about the database tables and table metadata. Furthermore, it exposes query capabilities and management operations for jobs. Jobs are used in Flowable for various things such as timers, asynchronous continuations, delayed suspension/activation, etc. Later on, these topics will be discussed in more detail.
  
  The *DynamicBpmnService* can be used to change part of the process definition without needing to redeploy it. You can for example change the assignee definition for a user task in a process definition, or change the class name of a service task.
  
  For more detailed information on the service operations and the engine API, see link:$$flowable/index.html$$[the javadocs].
  
  
  === Exception strategy
  
  The base exception in Flowable is the +org.flowable.engine.FlowableException+, an unchecked exception. This exception can be thrown at all times by the API, but 'expected' exceptions that happen in specific methods are documented in the link:$$http://flowable.org/javadocs/index.html$$[ the javadocs]. For example, an extract from ++TaskService++:
  
  [source,java,linenums]
  ----
  /**
   * Called when the task is successfully executed.
   * @param taskId the id of the task to complete, cannot be null.
   * @throws FlowableObjectNotFoundException when no task exists with the given id.
   */
   void complete(String taskId);
  ----
  
  In the example above, when an id is passed for which no task exists, an exception will be thrown. Also, since the javadoc *explicitly states that taskId cannot be null, an +FlowableIllegalArgumentException+ will be thrown when +null+ is passed*.
  
  Even though we want to avoid a big exception hierarchy, the following subclasses were added which are thrown in specific cases. All other errors that occur during process-execution or API-invocation that don't fit into the possible exceptions below, are thrown as regular ++FlowableExceptions++s.
  
  * ++FlowableWrongDbException++: Thrown when the Flowable engine discovers a mismatch between the database schema version and the engine version.
  * ++FlowableOptimisticLockingException++: Thrown when an optimistic locking occurs in the data store caused by concurrent access of the same data entry.
  * ++FlowableClassLoadingException++: Thrown when a class requested to load was not found or when an error occurred while loading it (e.g. JavaDelegates, TaskListeners, ...).
  * ++AFlowableObjectNotFoundException++: Thrown when an object that is requested or action on does not exist.
  * ++FlowableIllegalArgumentException++: An exception indicating that an illegal argument has been supplied in a Flowable API-call, an illegal value was configured in the engine's configuration or an illegal value has been supplied or an illegal value is used in a process-definition.
  * ++FlowableTaskAlreadyClaimedException++: Thrown when a task is already claimed, when the +taskService.claim(...)+ is called.
  
  
  [[queryAPI]]
  
  
negative.code: 
  [source,java,linenums]
  ----
  List<DmnDeployment> dmnDeployments = dmnRepositoryService.createDeploymentQuery()
      .deploymentNameLike("deployment%")
      .orderByDeployTime()
      .list();
  ----
  
  Sometimes you need more powerful queries, e.g. queries using an OR operator or restrictions you cannot express using the Query API. For these cases, we introduced native queries, which allow you to write your own SQL queries. The return type is defined by the Query object you use and the data is mapped into the correct objects, e.g. Deployment, ProcessInstance, Execution, etc.... Since the query will be fired at the database you have to use table and column names as they are defined in the database; this requires some knowledge about the internal data structure and it is recommended to use native queries with care. The table names can be retrieved via the API to keep the dependency as small as possible.
  
  [source,java,linenums]
  ----
  
  long count = dmnRepositoryService.createNativeDeploymentQuery()
      .sql("SELECT count(*) FROM " + dmnManagementService.getTableName(DmnDeploymentEntity.class) + " D1, "
          + dmnManagementService.getTableName(DecisionTableEntity.class) + " D2 "
          + "WHERE D1.ID_ = D2.DEPLOYMENT_ID_ "
          + "AND D1.ID_ = #{deploymentId}")
      .parameter("deploymentId", deployment.getId())
      .count();
  ----
  
  [[apiVariables]]
  
  
  [[apiUnitTesting]]
  
  
  === Unit testing
  
  Since Flowable DMN is an embeddable Java engine, writing unit tests for DMN definitions is as simple as writing regular unit tests.
  
  Flowable supports both JUnit versions 3 and 4 styles of unit testing. In the JUnit 3 style, the +org.flowable.dmn.engine.test.AbstractFlowableDmnTestCase+ must be extended. This will make the DmnEngine and the services available through protected member fields. In the +setup()+ of the test, the DmnEngine will be initialized by default with the +flowable.dmn.cfg.xml+ resource on the classpath.  To specify a different configuration file, override the _getConfigurationResource()_ method. DMN engines are cached statically over multiple unit tests when the configuration resource is the same.
  
  By extending +AbstractFlowableDmnTestCase+, you can annotate test methods with +org.flowable.dmn.engine.test.DmnDeploymentAnnotation+. Before the test is run, a resource file of the form +testClassName.testMethod.dmn+ in the same package as the test class, will be deployed. At the end of the test, the deployment will be deleted, including all decision tables. The +DmnDeploymentAnnotation+ annotation also supports setting the resource location explicitly. See the class itself for more information.
  
  Taking all that in account, a JUnit 3 style test looks as follows.
  
  [source,java,linenums]
  ----
  public class MyDmnDeploymentTest extends AbstractFlowableDmnTestCase {
  
    @DmnDeploymentAnnotation
    public void simpleDeploymentTest() {
        DmnDeployment deployment = repositoryService.createDeploymentQuery().singleResult();
        assertNotNull(deployment);
    }
  }
  ----
  
  To get the same functionality when using the JUnit 4 style of writing unit tests, the +org.flowable.dmn.engine.test.FlowableDmnRule+ Rule must be used. Through this rule, the DMN engine and services are available through getters. As with the +AbstractFlowableDmnTestCase+ (see above), including this +Rule+ will enable the use of the +org.flowable.dmn.engine.test.DmnDeploymentAnnotation+ annotation (see above for an explanation of its use and configuration) and it will look for the default configuration file on the classpath. DMN engines are statically cached over multiple unit tests when using the same configuration resource.
  
  The following code snippet shows an example of using the JUnit 4 style of testing and the usage of the +FlowableDmnRule+.
  
  [source,java,linenums]
  ----
  public class MyDecisionTableTest {
  
    @Rule
    public FlowableDmnRule flowableDmnRule = new FlowableDmnRule();
  
    @Test
    @DmnDeploymentAnnotation
    public void ruleUsageExample() {
      DmnEngine dmnEngine = flowableDmnRule.getDmnEngine();
      DmnRuleService dmnRuleService = dmnEngine.getDmnRuleService();
  
      Map<String, Object> inputVariables = new HashMap<>();
      inputVariables.put("inputVariable1", 2);
      inputVariables.put("inputVariable2", "test2");
  
      RuleEngineExecutionResult result = dmnRuleService.executeDecisionByKey("decision1", inputVariables);
  
      Assert.assertEquals("result2", result.getResultVariables().get("outputVariable1"));
    }
  }
  ----
  
  [[apiDebuggingUnitTest]]
  
  
  === Debugging unit tests
  
  //TODO
  
  When using the in-memory H2 database for unit tests, the following instructions allow to easily inspect the data in the Flowable DMN database during a debugging session. The screenshots here are taken in Eclipse, but the mechanism should be similar for other IDEs.
  
  Suppose we have put a _breakpoint_ somewhere in our unit test. In Eclipse this is done by double-clicking in the left border next to the code:
  
  image::images/api.test.debug.breakpoint.png[align="center"]
  
  If we now run the unit test in _debug_ mode (right-click in test class, select 'Run as' and then 'JUnit test'), the test execution halts at our breakpoint, where we can now inspect the variables of our test as shown in the right upper panel.
  
  image::images/api.test.debug.view.png[align="center"]
  
  To inspect the Flowable data, open up the _'Display'_ window (if this window isn't there, open Window->Show View->Other and select _Display_.) and type (code completion is available) +org.h2.tools.Server.createWebServer("-web").start()+
  
  image::images/api.test.debug.start.h2.server.png[align="center"]
  
  Select the line you've just typed and right-click on it. Now select 'Display' (or execute the shortcut instead of right-clicking)
  
  image::images/api.test.debug.start.h2.server.2.png[align="center"]
  
  Now open up a browser and go to link:$$http://localhost:8082$$[http://localhost:8082], and fill in the JDBC URL to the in-memory database (by default this is ++jdbc:h2:mem:flowable++), and hit the connect button.
  
  image::images/api.test.debug.h2.login.png[align="center"]
  
  You can now see the Flowable data and use it to understand how and why your unit test is executing your process in a certain way.
  
  image::images/api.test.debug.h2.tables.png[align="center"]
  
  
  
  [[apiProcessEngineInWebApp]]
  
  
  === The DMN engine in a web application
  
  The +DmnEngine+ is a thread-safe class and can easily be shared among multiple threads. In a web application, this means it is possible to create the DMN engine once when the container boots and shut down the engine when the container goes down.
  
  The following code snippet shows how you can write a simple +ServletContextListener+ to initialize and destroy process engines in a plain Servlet environment:
  
  [source,java,linenums]
  ----
  public class DmnEnginesServletContextListener implements ServletContextListener {
  
    public void contextInitialized(ServletContextEvent servletContextEvent) {
      DmnEngines.init();
    }
  
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
      DmnEngines.destroy();
    }
  
  }
  ----
  
  The +contextInitialized+ method will delegate to +DmnEngines.init()+. That will look for +flowable.dmn.cfg.xml+ resource files on the classpath, and create a +DmnEngine+ for the given configurations (e.g. multiple jars with a configuration file). If you have multiple such resource files on the classpath, make sure they all have different names. When the DMN engine is needed, it can be fetched using
  
  [source,java,linenums]
  ----
  DmnEngines.getDefaultDmnEngine()
  ----
  
  or
  
  [source,java,linenums]
  ----
  DmnEngines.getDmnEngine("myName");
  ----
  
  Of course, it is also possible to use any of the variants of creating a DMN engine,
  as described in the <<configuration,configuration section>>.
  
  
  The +contextDestroyed+ method of the context-listener delegates to +DmnEngines.destroy()+. That will properly close all initialized DMN engines.
  