.. This work is licensed under a Creative Commons Attribution 4.0 International License. .. http://creativecommons.org/licenses/by/4.0 .. _apex-myFirstExample: HowTo: My First Policy ********************** .. contents:: :depth: 3 Introduction ^^^^^^^^^^^^ .. container:: sectionbody .. container:: paragraph Consider a scenario where a supermarket chain called *HyperM* controls how it sells items in a policy-based manner. Each time an item is processed by *HyperM*'s point-of-sale (PoS) system an event is generated and published about that item of stock being sold. This event can then be used to update stock levels, etc.. .. container:: paragraph *HyperM* want to extend this approach to allow some checks to be performed before the sale can be completed. This can be achieved by requesting a policy-controlled decision as each item is processed by for sale by each PoS system. The decision process is integrated with *HyperM*'s other IT systems that manage stock control, sourcing and purchasing, personnel systems, etc. .. container:: paragraph In this document we will show how APEX and APEX Policies can be used to achieve this, starting with a simple policy, building up to more complicated policy that demonstrates the features of APEX. Data Models ^^^^^^^^^^^ .. container:: sectionbody .. container:: sect2 .. rubric:: Sales Input Event :name: sales_input_event .. container:: paragraph Each time a PoS system processes a sales item an event with the following format is emitted: .. table:: Table 1. Sale Input Event +----------------------+----------------------+-----------------------+ | Event | Fields | Description | +======================+======================+=======================+ | SALE_INPUT | time, sale_ID, | Event indicating a | | | amount, item_ID, | sale of an item is | | | quantity, | occurring | | | assistant_ID, | | | | branch_ID, notes, …​ | | +----------------------+----------------------+-----------------------+ .. container:: paragraph In each ``SALE_INPUT`` event the ``sale_ID`` field is a unique ID generated by the PoS system. A timestamp for the event is stored in the ``time`` field. The ``amount`` field refers to the value of the item(s) to be sold (in cents). The ``item_ID`` field is a unique identifier for each item type, and can be used to retrieve more information about the item from *HyperM*'s stock control system. The ``quantity`` field refers to the quantity of the item to be sold. The ``assistant_ID`` field is a unique identifier for the PoS operator, and can be used to retrieve more information about the operator from the *HyperM*'s personnel system. Since *HyperM* has many branches the ``branch_ID`` identifies the shop. The ``notes`` field contains arbitrary notes about the sale. .. container:: sect2 .. rubric:: Sales Decision Event :name: sales_decision_event .. container:: paragraph After a ``SALE_INPUT`` event is emitted by the PoS system *HyperM*'s policy-based controlled sales checking system emits a Sale Authorization Event indicating whether the sale is authorized or denied. The PoS system can then listen for this event before continuing with the sale. .. table:: Table 2. Sale Authorisation Event +----------------------+----------------------+-----------------------+ | Event | Fields | Description | +======================+======================+=======================+ | SALE_AUTH | sale_ID, time, | Event indicating a | | | authorized, amount, | sale of an item is | | | item_ID, quantity, | authorized or denied | | | assistant_ID, | | | | branch_ID, notes, | | | | message…​ | | +----------------------+----------------------+-----------------------+ .. container:: paragraph In each ``SALE_AUTH`` event the ``sale_ID`` field is copied from the ``SALE_INPUT`` event that trigger the decision request. The ``SALE_AUTH`` event is also timestamped using the ``time`` field, and a field called ``authorised`` is set to ``true`` or ``false`` depending on whether the sale is authorized or denied. The ``message`` field carries an optional message about why a sale was not authorized. The other fields from the ``SALE_INPUT`` event are also included for completeness. .. container:: sect2 .. rubric:: Stock Control: Items :name: stock_control_items .. container:: paragraph *HyperM* maintains information about each item for sale in a database table called ``ITEMS``. .. table:: Table 3. Items Database +----------------------+----------------------+-----------------------+ | Table | Fields | Description | +======================+======================+=======================+ | ITEMS | item_ID, | Database table | | | description, | describing each item | | | cost_price, barcode, | for sale | | | supplier_ID, | | | | category, …​ | | +----------------------+----------------------+-----------------------+ .. container:: paragraph The database table ``ITEMS`` has a row for each items that *HyperM* sells. Each item is identified by an ``item_ID`` value. The ``description`` field stores a description of the item. The cost price of the item is given in ``cost_price``. The barcode of the item is encoded in ``barcode``, while the item supplier is identified by ``supplier_ID``. Items may also be classified into categories using the ``category`` field. Useful categories might include: ``soft drinks``, ``alcoholic drinks``, ``cigarettes``, ``knives``, ``confectionery``, ``bakery``, ``fruit&vegetables``, ``meat``, etc.. .. container:: sect2 .. rubric:: Personnel System: Assistants :name: personnel_system_assistants .. table:: Table 4. Assistants Database +----------------------+----------------------+-----------------------+ | Table | Fields | Description | +======================+======================+=======================+ | ASSISTANTS | assistant_ID, | Database table | | | surname, firstname, | describing each | | | middlename, age, | *HyperM* sales | | | grade, phone_number, | assistant | | | …​ | | +----------------------+----------------------+-----------------------+ .. container:: paragraph The database table ``ASSISTANTS`` has a row for each sales assistant employed by *HyperM*. Each assistant is identified by an ``assistant_ID`` value, with their name given in the ``firstname``, ``middlename`` and ``surname`` fields. The assistant’s age in years is given in ``age``, while their phone number is contained in the ``phone_number`` field. The assistant’s grade is encoded in ``grade``. Useful values for ``grade`` might include: ``trainee``, ``operator``, ``supervisor``, etc.. .. container:: sect2 .. rubric:: Locations: Branches :name: locations_branches .. table:: Table 5. Branches Database +----------------------+----------------------+-----------------------+ | Table | Fields | Description | +======================+======================+=======================+ | BRANCHES | branch_ID, | Database table | | | branch_Name, | describing each | | | category, street, | *HyperM* branch | | | city, country, | | | | postcode, …​ | | +----------------------+----------------------+-----------------------+ .. container:: paragraph *HyperM* operates a number of branches. Each branch is described in the ``BRANCHES`` database table. Each branch is identified by a ``branch_ID``, with a branch name given in ``branch_Name``. The address for the branch is encoded in ``street``, ``city``, ``country`` and ``postcode``. The branch category is given in the ``category`` field. Useful values for ``category`` might include: ``Small``, ``Large``, ``Super``, ``Hyper``, etc.. Policy Step 1 ^^^^^^^^^^^^^ .. container:: sectionbody .. container:: sect1 .. rubric:: Scenario :name: scenario .. container:: paragraph For the first version of our policy, let’s start with something simple. Let us assume that there exists some restriction that alcohol products cannot be sold before 11:30am. In this section we will go through the necessary steps to define a policy that can enforce this for *HyperM*. .. container:: ulist - Alcohol cannot be sold before 11:30am... New Policy Model ---------------- .. container:: sectionbody .. container:: sect1 .. rubric:: Create the an new empty Policy Model ``MyFirstPolicyModel`` :name: create_the_an_new_empty_policy_model_code_myfirstpolicymodel_code .. container:: paragraph Since an organisation like *HyperM* may have many policies covering many different domains, policies should be grouped into policy sets. In order to edit or deploy a policy, or policy set, the definition of the policy(ies) and all required events, tasks, states, etc., are grouped together into a 'Policy Model'. An organization might define many Policy Models, each containing a different set of policies. .. container:: paragraph So the first step is to create a new empty Policy Model called ``MyFirstPolicyModel``. Using the APEX Policy Editor, click on the 'File' menus and select 'New'. Then define our new policy model called ``MyFirstPolicyModel``. Use the 'Generate UUID' button to create a new unique ID for the policy model, and fill in a description for the policy model. Press the ``Submit`` button to save your changes. .. container:: imageblock .. container:: content |File > New to create a new Policy Model| .. container:: imageblock .. container:: content |Create a new Policy Model| Events ------ .. container:: sectionbody .. container:: sect1 .. rubric:: Create the input event ``SALE_INPUT`` and the output event ``SALE_AUTH`` :name: create_the_input_event_code_sale_input_code_and_the_output_event_code_sale_auth_code .. container:: paragraph Using the APEX Policy Editor, click on the 'Events' tab. In the 'Events' pane, right click and select 'New': .. container:: imageblock .. container:: content |Right click to create a new event| .. container:: paragraph Create a new event type called ``SALE_INPUT``. Use the 'Generate UUID' button to create a new unique ID for the event type, and fill in a description for the event. Add a namespace, e.g. ``com.hyperm``. We can add hard-coded strings for the ``Source`` and ``Target``, e.g. ``POS`` and ``APEX``. At this stage we will not add any parameter fields, we will leave this until later. Use the ``Submit`` button to create the event. .. container:: imageblock .. container:: content |Fill in the necessary information for the 'SALE_INPUT' event and click 'Submit'| .. container:: paragraph Repeat the same steps for a new event type called ``SALE_AUTH``. Just use ``APEX`` as source and ``POS`` as target, since this is the output event coming from APEX going to the sales point. .. container:: paragraph Before we can add parameter fields to an event we must first define APEX Context Item Schemas that can be used by those fields. .. container:: paragraph To create new item schemas, click on the 'Context Item Schemas' tab. In that 'Context Item Schemas' pane, right click and select 'Create new ContextSchema'. .. container:: imageblock .. container:: content |Right click to create a new Item Schema| .. container:: paragraph Create item schemas with the following characteristics, each with its own unique UUID: .. table:: Table 1. Item Schemas +-----------------+-----------------+-----------------+-----------------+ | Name | Schema Flavour | Schema | Description | | | | Definition | | +=================+=================+=================+=================+ | timestamp_type | Java | java.lang.Long | A type for | | | | | ``time`` values | +-----------------+-----------------+-----------------+-----------------+ | sale_ID_type | Java | java.lang.Long | A type for | | | | | ``sale_ID`` | | | | | values | +-----------------+-----------------+-----------------+-----------------+ | price_type | Java | java.lang.Long | A type for | | | | | ``amo | | | | | unt``/``price`` | | | | | values | +-----------------+-----------------+-----------------+-----------------+ | item_ID_type | Java | java.lang.Long | A type for | | | | | ``item_ID`` | | | | | values | +-----------------+-----------------+-----------------+-----------------+ | as | Java | java.lang.Long | A type for | | sistant_ID_type | | | ` | | | | | `assistant_ID`` | | | | | values | +-----------------+-----------------+-----------------+-----------------+ | quantity_type | Java | ja | A type for | | | | va.lang.Integer | ``quantity`` | | | | | values | +-----------------+-----------------+-----------------+-----------------+ | branch_ID_type | Java | java.lang.Long | A type for | | | | | ``branch_ID`` | | | | | values | +-----------------+-----------------+-----------------+-----------------+ | notes_type | Java | j | A type for | | | | ava.lang.String | ``notes`` | | | | | values | +-----------------+-----------------+-----------------+-----------------+ | authorised_type | Java | ja | A type for | | | | va.lang.Boolean | ``authorised`` | | | | | values | +-----------------+-----------------+-----------------+-----------------+ | message_type | Java | j | A type for | | | | ava.lang.String | ``message`` | | | | | values | +-----------------+-----------------+-----------------+-----------------+ .. container:: imageblock .. container:: content |Create a new Item Schema| .. container:: paragraph The item schemas can now be seen on the 'Context Item Schemas' tab, and can be updated at any time by right-clicking on the item schemas on the 'Context Item Schemas' tab. Now we can go back to the event definitions for ``SALE_INPUT`` and ``SALE_AUTH`` and add some parameter fields. .. TIP:: .. container:: paragraph APEX natively supports schema definitions in ``Java`` and ``Avro``. ``Java`` schema definitions are simply the name of a Java Class. There are some restrictions: .. container:: ulist - the class must be instantiatable, i.e. not an Java interface or abstract class - primitive types are not supported, i.e. use ``java.lang.Integer`` instead of ``int``, etc. - it must be possible to find the class, i.e. the class must be contained in the Java classpath. .. container:: paragraph ``Avro`` schema definitions can be any valid `Avro `__ schema. For events using fields defined with Avro schemas, any incoming event containing that field must contain a value that conforms to the Avro schema. .. container:: paragraph Click on the 'Events' tab, then right click the ``SALE_INPUT`` row and select 'Edit Event :literal:`SALE_INPUT’. To add a new event parameter use the 'Add Event Parameter' button at the bottom of the screen. For the `SALE_INPUT` event add the following event parameters: .. table:: Table 2. Event Parameter Fields for the ``SALE_INPUT`` Event +----------------------+----------------------+-----------------------+ | Parameter Name | Parameter Type | Optional | +======================+======================+=======================+ | time | timestamp_type | no | +----------------------+----------------------+-----------------------+ | sale_ID | sale_ID_type | no | +----------------------+----------------------+-----------------------+ | amount | price_type | no | +----------------------+----------------------+-----------------------+ | item_ID | item_ID_type | no | +----------------------+----------------------+-----------------------+ | quantity | quantity_type | no | +----------------------+----------------------+-----------------------+ | assistant_ID | assistant_ID_type | no | +----------------------+----------------------+-----------------------+ | branch_ID | branch_ID_type | no | +----------------------+----------------------+-----------------------+ | notes | notes_type | *yes* | +----------------------+----------------------+-----------------------+ .. container:: paragraph Remember to click the 'Submit' button at the bottom of the event definition pane. .. TIP:: .. container:: paragraph Parameter fields can be *optional* in events. If a parameter is not marked as *optional* then by default it is *mandatory*, so it must appear in any input event passed to APEX. If an *optional* field is not set for an output event then value will be set to ``null``. .. container:: imageblock .. container:: content |Add new event parameters to an event| .. container:: paragraph Select the ``SALE_AUTH`` event and add the following event parameters: .. table:: Table 3. Event Parameter Fields for the ``SALE_AUTH`` Event +----------------------+----------------------+-----------------------+ | Parameter Name | Parameter Type | no | +======================+======================+=======================+ | sale_ID | sale_ID_type | no | +----------------------+----------------------+-----------------------+ | time | timestamp_type | no | +----------------------+----------------------+-----------------------+ | authorised | authorised_type | no | +----------------------+----------------------+-----------------------+ | message | message_type | *yes* | +----------------------+----------------------+-----------------------+ | amount | price_type | no | +----------------------+----------------------+-----------------------+ | item_ID | item_ID_type | no | +----------------------+----------------------+-----------------------+ | assistant_ID | assistant_ID_type | no | +----------------------+----------------------+-----------------------+ | quantity | quantity_type | no | +----------------------+----------------------+-----------------------+ | branch_ID | branch_ID_type | no | +----------------------+----------------------+-----------------------+ | notes | notes_type | *yes* | +----------------------+----------------------+-----------------------+ .. container:: paragraph Remember to click the 'Submit' button at the bottom of the event definition pane. .. container:: paragraph The events for our policy are now defined. New Policy ---------- .. container:: sectionbody .. container:: sect1 .. rubric:: Create a new Policy and add the *"No Booze before 11:30"* check :name: create_a_new_policy_and_add_the_em_no_booze_before_11_30_em_check .. container:: paragraph APEX policies are defined using a state-machine model. Each policy comprises one or more *states* that can be individually executed. Where there is more than one *state* the states are chained together to form a `Directed Acyclic Graph (DAG) `__ of states. A *state* is triggered by passing it a single input (or 'trigger') event and once executed each state then emits an output event. For each *state* the logic for the *state* is embedded in one or more *tasks*. Each *task* contains specific *task logic* that is executed by the APEX execution environment each time the *task* is invoked. Where there is more than one *task* in a *state* then the *state* also defines some *task selection logic* to select an appropriate task each time the *state* is executed. .. container:: paragraph Therefore, to create a new policy we must first define one or more tasks. .. container:: paragraph To create a new Task click on the 'Tasks' tab. In the 'Tasks' pane, right click and select 'Create new Task'. Create a new Task called ``MorningBoozeCheck``. Use the 'Generate UUID' button to create a new unique ID for the task, and fill in a description for the task. .. container:: imageblock .. container:: content |Right click to create a new task| .. container:: paragraph Tasks are configured with a set of *input fields* and a set of *output fields*. To add new input/output fields for a task use the 'Add Task Input Field' and 'Add Task Output Field' button. The list of input and out fields to add for the ``MorningBoozeCheck`` task are given below. The input fields are drawn from the parameters in the state’s input event, and the task’s output fields are used to populate the state’s output event. The task’s input and output fields must be a subset of the event parameters defined for the input and output events for any state that uses that task. (You may have noticed that the input and output fields for the ``MorningBoozeCheck`` task have the exact same names and reuse the item schemas that we used for the parameters in the ``SALE_INPUT`` and ``SALE_AUTH`` events respectively). .. table:: Table 1. Input fields for ``MorningBoozeCheck`` task +-----------------------------------+-----------------------------------+ | Parameter Name | Parameter Type | +===================================+===================================+ | time | timestamp_type | +-----------------------------------+-----------------------------------+ | sale_ID | sale_ID_type | +-----------------------------------+-----------------------------------+ | amount | price_type | +-----------------------------------+-----------------------------------+ | item_ID | item_ID_type | +-----------------------------------+-----------------------------------+ | quantity | quantity_type | +-----------------------------------+-----------------------------------+ | assistant_ID | assistant_ID_type | +-----------------------------------+-----------------------------------+ | branch_ID | branch_ID_type | +-----------------------------------+-----------------------------------+ | notes | notes_type | +-----------------------------------+-----------------------------------+ .. table:: Table 2. Output fields for ``MorningBoozeCheck`` task +-----------------------------------+-----------------------------------+ | Parameter Name | Parameter Type | +===================================+===================================+ | sale_ID | sale_ID_type | +-----------------------------------+-----------------------------------+ | time | timestamp_type | +-----------------------------------+-----------------------------------+ | authorised | authorised_type | +-----------------------------------+-----------------------------------+ | message | message_type | +-----------------------------------+-----------------------------------+ | amount | price_type | +-----------------------------------+-----------------------------------+ | item_ID | item_ID_type | +-----------------------------------+-----------------------------------+ | assistant_ID | assistant_ID_type | +-----------------------------------+-----------------------------------+ | quantity | quantity_type | +-----------------------------------+-----------------------------------+ | branch_ID | branch_ID_type | +-----------------------------------+-----------------------------------+ | notes | notes_type | +-----------------------------------+-----------------------------------+ .. container:: imageblock .. container:: content |Add input and out fields for the task| .. container:: paragraph Each task must include some 'Task Logic' that implements the behaviour for the task. Task logic can be defined in a number of different ways using a choice of languages. For this task we will author the logic using the Java-like scripting language called ```MVEL`` `__. .. container:: paragraph For simplicity use the code for the task logic here(|taskLogicMvel_link|). Paste the script text into the 'Task Logic' box, and use "MVEL" as the 'Task Logic Type / Flavour'. .. container:: paragraph This logic assumes that all items with ``item_ID`` between 1000 and 2000 contain alcohol, which is not very realistic, but we will see a better approach for this later. It also uses the standard ``Java`` time utilities to check if the current time is between ``00:00:00 GMT`` and ``11:30:00 GMT``. For a detailed guide to how to write your own logic in ```JavaScript`` `__, ```MVEL`` `__ or one of the other supported languages please refer to APEX Programmers Guide. .. container:: imageblock .. container:: content |Add task logic the task| .. container:: paragraph An alternative version of the same logic is available in JavaScript(|taskLogicJS_link|). Just use "JAVASCRIPT" as the 'Task Logic Type / Flavour' instead. .. container:: paragraph The task definition is now complete so click the 'Submit' button to save the task. The task can now be seen on the 'Tasks' tab, and can be updated at any time by right-clicking on the task on the 'Task' tab. Now that we have created our task, we can can create a policy that uses that task. .. container:: paragraph To create a new Policy click on the 'Policies' tab. In the 'Policies' pane, right click and select 'Create new Policy': .. container:: paragraph Create a new Policy called ``MyFirstPolicy``. Use the 'Generate UUID' button to create a new unique ID for the policy, and fill in a description for the policy. Use 'FREEFORM' as the 'Policy Flavour'. .. container:: paragraph Each policy must have at least one state. Since this is 'freeform' policy we can add as many states as we wish. Let’s start with one state. Add a new state called ``BoozeAuthDecide`` to this ``MyFirstPolicy`` policy using the 'Add new State' button after filling in the name of our new state. .. container:: imageblock .. container:: content |Create a new policy| .. container:: paragraph Each state must uses one input event type. For this new state select the ``SALE_INPUT`` event as the input event. .. container:: paragraph Each policy must define a 'First State' and a 'Policy Trigger Event'. The 'Policy Trigger Event' is the input event for the policy as a whole. This event is then passed to the first state in the chain of states in the policy, therefore the 'Policy Trigger Event' will be the input event for the first state. Each policy can only have one 'First State'. For our ``MyFirstPolicy`` policy, select ``BoozeAuthDecide`` as the 'First State'. This will automatically select ``SALE_INPUT`` as the 'Policy Trigger Event' for our policy. .. container:: imageblock .. container:: content |Create a state| .. container:: paragraph In this case we will create a reference the pre-existing ``MorningBoozeCheck`` task that we defined above using the 'Add New Task' button. Select the ``MorningBoozeCheck`` task, and use the name of the task as the 'Local Name' for the task. .. container:: paragraph in the case where a state references more than one task, a 'Default Task' must be selected for the state and some logic ('Task Selection Logic') must be specified to select the appropriate task at execution time. Since our new state ``BoozeAuthDecide`` only has one task the default task is automatically selected and no 'Task Selection Logic' is required. .. NOTE:: .. container:: paragraph In a 'Policy' 'State' a 'State Output Mapping' has 3 roles: 1) Select which 'State' should be executed next, 2) Select the type of the state’s 'Outgoing Event', and 3) Populate the state’s 'Outgoing Event'. This is how states are chained together to form a (`Directed Acyclic Graph (DAG) `__) of states. The final state(s) of a policy are those that do not select any 'next' state. Since a 'State' can only accept a single type of event, the type of the event emitted by a previous 'State' must match the incoming event type of the next 'State'. This is also how the last state(s) in a policy can emit events of different types. The 'State Output Mapping' is also responsible for taking the fields that are output by the task executed in the state and populating the state’s output populating the state’s output event before it is emitted. Each 'Task' referenced in 'State' must have a defined 'Output Mapping' to take the output of the task, select an 'Outgoing Event' type for the state, populate the state's outgoing event, and then select the next state to be executed (if any). There are 2 basic types of output mappings: .. container:: olist arabic #. **Direct Output Mappings** have a single value for 'Next State' and a single value for 'State Output Event'. The outgoing event for the state is automatically created, any outgoing event parameters that were present in the incoming event are copied into the outgoing event, then any task output fields that have the same name and type as parameters in the outgoing event are automatically copied into the outgoing event. #. **Logic-Based State Output Mappings / Finalizers** have some logic defined that dynamically selects and creates the 'State Outgoing Event', manages the population of the outgoing event parameters (perhaps changing or adding to the outputs from the task), and then dynamically selects the next state to be executed (if any). .. container:: paragraph Each task reference must also have an associated 'Output State Mapping' so we need an 'Output State Mapping' for the ``BoozeAuthDecide`` state to use when the ``MorningBoozeCheck`` task is executed. The simplest type of output mapping is a 'Direct Output Mapping'. .. container:: paragraph Create a new 'Direct Output Mapping' for the state called ``MorningBoozeCheck_Output_Direct`` using the 'Add New Direct State Output Mapping' button. Select ``SALE_AUTH`` as the output event and select ``None`` for the next state value. We can then select this output mapping for use when the the ``MorningBoozeCheck`` task is executed. Since there is only state, and only one task for that state, this output mapping ensures that the ``BoozeAuthDecide`` state is the only state executed and the state (and the policy) can only emit events of type ``SALE_AUTH``. (You may remember that the output fields for the ``MorningBoozeCheck`` task have the exact same names and reuse the item schemas that we used for the parameters in ``SALE_AUTH`` event. The ``MorningBoozeCheck_Output_Direct`` direct output mapping can now automatically copy the values from the ``MorningBoozeCheck`` task directly into outgoing ``SALE_AUTH`` events.) .. container:: imageblock .. container:: content |Add a Task and Output Mapping| .. container:: paragraph Click the 'Submit' button to complete the definition of our ``MyFirstPolicy`` policy. The policy ``MyFirstPolicy`` can now be seen in the list of policies on the 'Policies' tab, and can be updated at any time by right-clicking on the policy on the 'Policies' tab. .. container:: paragraph The ``MyFirstPolicyModel``, including our ``MyFirstPolicy`` policy can now be checked for errors. Click on the 'Model' menu and select 'Validate'. The model should validate without any 'Warning' or 'Error' messages. If you see any 'Error' or 'Warning' messages, carefully read the message as a hint to find where you might have made a mistake when defining some aspect of your policy model. .. container:: imageblock .. container:: content |Validate the policy model for error using the 'Model' > 'Validate' menu item| .. container:: paragraph Congratulations, you have now completed your first APEX policy. The policy model containing our new policy can now be exported from the editor and saved. Click on the 'File' menu and select 'Download' to save the policy model in JSON format. The exported policy model is then available in the directory you selected, for instance ``$APEX_HOME/examples/models/MyFirstPolicy/1/MyFirstPolicyModel_0.0.1.json``. The exported policy can now be loaded into the APEX Policy Engine, or can be re-loaded and edited by the APEX Policy Editor. .. container:: imageblock .. container:: content |Download the completed policy model using the 'File' > 'Download' menu item| Test The Policy --------------- .. container:: sectionbody .. container:: sect1 .. rubric:: Test Policy Step 1 :name: test_policy_step_1 .. container:: paragraph To start a new APEX Engine you can use the following |policy1_configuration|. In a full APEX installation you can find this configuration in ``$APEX_HOME/examples/config/MyFirstPolicy/1/MyFirstPolicyConfigStdin2StdoutJsonEvent.json``. This configuration expects incoming events to be in ``JSON`` format and to be passed into the APEX Engine from ``stdin``, and result events will be printed in ``JSON`` format to ``stdout``. This configuration loads the policy model stored in the file 'MyFirstPolicyModel_0.0.1.json' as exported from the APEX Editor. Note, you may need to edit this file to provide the full path to wherever you stored the exported policy model file. .. container:: paragraph To test the policy try paste the following events into the console as the APEX engine executes: .. list-table:: Title :widths: 25 40 35 :header-rows: 1 * - Input Event (JSON) - Output Event (JSON) - comment * - .. literalinclude:: events/1/EventIn_NonBoozeItem_101309GMT.json :language: JSON - .. literalinclude:: events/1/EventOut_NonBoozeItem_101309GMT.json :language: JSON - .. container:: paragraph Request to buy a non-alcoholic item (item_ID=5123) at 10:13:09 on Tuesday, 10 January 2017. Sale is authorized. * - .. literalinclude:: events/1/EventIn_BoozeItem_084106GMT.json :language: JSON - .. literalinclude:: events/1/EventOut_BoozeItem_084106GMT.json :language: JSON - .. container:: paragraph Request to buy alcohol item (`item_ID=1249`) at 08:41:06 on Monday, 02 January 2017. Sale is not authorized. * - .. literalinclude:: events/1/EventIn_BoozeItem_201713GMT.json :language: JSON - .. literalinclude:: events/1/EventOut_BoozeItem_201713GMT.json :language: JSON - .. container:: paragraph Request to buy alcohol (`item_ID=1943`) at 20:17:13 on Tuesday, 20 December 2016. Sale is authorized. CLI Editor File --------------- .. container:: sectionbody .. container:: sect1 .. rubric:: Policy 1 in CLI Editor :name: policy_1_in_cli_editor .. container:: paragraph An equivalent version of the ``MyFirstPolicyModel`` policy model can again be generated using the APEX CLI editor. A sample APEX CLI script is shown below: .. container:: ulist - |policy1ModelMvel_link| - |policy1ModelJs_link| Policy Step 2 ^^^^^^^^^^^^^ .. container:: sectionbody .. container:: sect1 .. rubric:: Scenario :name: scenario_policy2 .. container:: paragraph *HyperM* have just opened a new branch in a different country, but that country has different rules about when alcohol can be sold! In this section we will go through the necessary steps to extend our policy to enforce this for *HyperM*. .. container:: ulist - In some branches alcohol cannot be sold before 1pm, and not at all on Sundays. .. container:: paragraph Although there are a number of ways to accomplish this the easiest approach for us is to define another task and then select which task is appropriate at runtime depending on the branch identifier in the incoming event. Extend Policy Model ------------------- .. container:: sectionbody .. container:: sect2 .. rubric:: Extend the Policy with the new Scenario :name: extend_the_policy_with_the_new_scenario .. container:: paragraph To create a new Task click on the 'Tasks' tab. In the 'Tasks' pane, right click and select 'Create new Task': .. container:: paragraph Create a new Task called ``MorningBoozeCheckAlt1``. Use the 'Generate UUID' button to create a new unique ID for the task, and fill in a description for the task. Select the same input and output fields that we used earlier when we defined the ``MorningBoozeCheck`` task earlier. .. table:: Table 1. Input fields for ``MorningBoozeCheckAlt1`` task +-----------------------------------+-----------------------------------+ | Parameter Name | Parameter Type | +===================================+===================================+ | time | timestamp_type | +-----------------------------------+-----------------------------------+ | sale_ID | sale_ID_type | +-----------------------------------+-----------------------------------+ | amount | price_type | +-----------------------------------+-----------------------------------+ | item_ID | item_ID_type | +-----------------------------------+-----------------------------------+ | quantity | quantity_type | +-----------------------------------+-----------------------------------+ | assistant_ID | assistant_ID_type | +-----------------------------------+-----------------------------------+ | branch_ID | branch_ID_type | +-----------------------------------+-----------------------------------+ | notes | notes_type | +-----------------------------------+-----------------------------------+ .. table:: Table 2. Output fields for ``MorningBoozeCheckAlt1`` task +-----------------------------------+-----------------------------------+ | Parameter Name | Parameter Type | +===================================+===================================+ | sale_ID | sale_ID_type | +-----------------------------------+-----------------------------------+ | time | timestamp_type | +-----------------------------------+-----------------------------------+ | authorised | authorised_type | +-----------------------------------+-----------------------------------+ | message | message_type | +-----------------------------------+-----------------------------------+ | amount | price_type | +-----------------------------------+-----------------------------------+ | item_ID | item_ID_type | +-----------------------------------+-----------------------------------+ | assistant_ID | assistant_ID_type | +-----------------------------------+-----------------------------------+ | quantity | quantity_type | +-----------------------------------+-----------------------------------+ | branch_ID | branch_ID_type | +-----------------------------------+-----------------------------------+ | notes | notes_type | +-----------------------------------+-----------------------------------+ .. container:: paragraph This task also requires some 'Task Logic' to implement the new behaviour for this task. .. container:: paragraph For simplicity use the following code for the task logic (|policy2_taskLogic_link|). It again assumes that all items with ``item_ID`` between 1000 and 2000 contain alcohol. We again use the standard ``Java`` time utilities to check if the current time is between ``00:00:00 CET`` and ``13:00:00 CET`` or if it is ``Sunday``. .. container:: paragraph For this task we will again author the logic using the ```MVEL`` `__ scripting language. Sample task logic code (specified in ```MVEL`` `__) is given below. For a detailed guide to how to write your own logic in ```JavaScript`` `__, ```MVEL`` `__ or one of the other supported languages please refer to APEX Programmers Guide. .. container:: imageblock .. container:: content |Create a new alternative task \`MorningBoozeCheckAlt1\`| .. container:: paragraph The task definition is now complete so click the 'Submit' button to save the task. Now that we have created our task, we can can add this task to the single pre-existing state (``BoozeAuthDecide``) in our policy. .. container:: paragraph To edit the ``BoozeAuthDecide`` state in our policy click on the 'Policies' tab. In the 'Policies' pane, right click on our ``MyFirstPolicy`` policy and select 'Edit'. Navigate to the ``BoozeAuthDecide`` state in the 'states' section at the bottom of the policy definition pane. .. container:: imageblock .. container:: content |Right click to edit a policy| .. container:: paragraph To add our new task ``MorningBoozeCheckAlt1``, scroll down to the ``BoozeAuthDecide`` state in the 'States' section. In the 'State Tasks' section for ``BoozeAuthDecide`` use the 'Add new task' button. Select our new ``MorningBoozeCheckAlt1`` task, and use the name of the task as the 'Local Name' for the task. The ``MorningBoozeCheckAlt1`` task can reuse the same ``MorningBoozeCheck_Output_Direct`` 'Direct State Output Mapping' that we used for the ``MorningBoozeCheck`` task. (Recall that the role of the 'State Output Mapping' is to select the output event for the state, and select the next state to be executed. These both remain the same as before.) .. container:: paragraph Since our state has more than one task we must define some logic to determine which task should be used each time the state is executed. This *task selection logic* is defined in the state definition. For our ``BoozeAuthDecide`` state we want the choice of which task to use to be based on the ``branch_ID`` from which the ``SALE_INPUT`` event originated. For simplicity sake let us assume that branches with ``branch_ID`` between ``0`` and ``999`` should use the ``MorningBoozeCheck`` task, and the branches with with ``branch_ID`` between ``1000`` and ``1999`` should use the ``MorningBoozeCheckAlt1`` task. .. container:: paragraph This time, for variety, we will author the task selection logic using the ```JavaScript`` `__ scripting language. Sample task selection logic code is given here (|policy2_taskSelectionLogic_link|). Paste the script text into the 'Task Selection Logic' box, and use "JAVASCRIPT" as the 'Task Selection Logic Type / Flavour'. It is necessary to mark one of the tasks as the 'Default Task' so that the task selection logic always has a fallback default option in cases where a particular task cannot be selected. In this case the ``MorningBoozeCheck`` task can be the default task. .. container:: imageblock .. container:: content |State definition with 2 Tasks and Task Selection Logic| .. container:: paragraph When complete don’t forget to click the 'Submit' button at the bottom of 'Policies' pane for our ``MyFirstPolicy`` policy after updating the ``BoozeAuthDecide`` state. .. container:: paragraph Congratulations, you have now completed the second step towards your first APEX policy. The policy model containing our new policy can again be validated and exported from the editor and saved as shown in Step 1. .. container:: paragraph The exported policy model is then available in the directory you selected, as **MyFirstPolicyModel_0.0.1.json**. The exported policy can now be loaded into the APEX Policy Engine, or can be re-loaded and edited by the APEX Policy Editor. Test The Policy --------------- .. container:: sectionbody .. container:: sect2 .. rubric:: Test Policy Step 2 :name: test_policy_step_2 .. container:: paragraph To start a new APEX Engine you can use the following |policy2_configuration_link|. In a full APEX installation you can find this configuration in ``$APEX_HOME/examples/config/MyFirstPolicy/2/MyFirstPolicyConfigStdin2StdoutJsonEvent.json``. Note, this has changed from the configuration file in Step 1 to enable the ``JAVASCRIPT`` executor for our new 'Task Selection Logic'. .. container:: paragraph To test the policy try paste the following events into the console as the APEX engine executes. Note, all tests from Step 1 will still work perfectly since none of those events originate from a branch with ``branch_ID`` between ``1000`` and ``2000``. The 'Task Selection Logic' will therefore pick the ``MorningBoozeCheck`` task as expected, and will therefore give the same results. .. list-table:: Table 1. Inputs and Outputs when testing *My First Policy* :widths: 25 40 35 :header-rows: 1 * - Input Event (JSON) - Output Event (JSON) - comment * - .. literalinclude:: events/1/EventIn_BoozeItem_084106GMT.json :language: JSON - .. literalinclude:: events/1/EventOut_BoozeItem_084106GMT.json :language: JSON - .. container:: paragraph Request to buy alcohol item (`item_ID=1249`) at 08:41:06 GMT on Monday, 02 January 2017. Sale is not authorized. Uses the `MorningBoozeCheck` task. * - .. literalinclude:: events/2/EventIn_BoozeItem_101433CET_thurs.json :language: JSON - .. literalinclude:: events/2/EventOut_BoozeItem_101433CET_thurs.json :language: JSON - .. container:: paragraph Request to buy alcohol (`item_ID=1047`) at 10:14:33 on Thursday, 22 December 2016. Sale is not authorized. Uses the `MorningBoozeCheckAlt1` task. * - .. literalinclude:: events/2/EventIn_BoozeItem_171937CET_sun.json :language: JSON - .. literalinclude:: events/2/EventOut_BoozeItem_171937CET_sun.json :language: JSON - .. container:: paragraph Request to buy alcohol (`item_ID=1443`) at 17:19:37 on Sunday, 18 December 2016. Sale is not authorized. Uses the `MorningBoozeCheckAlt1` task. * - .. literalinclude:: events/2/EventIn_NonBoozeItem_111309CET_mon.json :language: JSON - .. literalinclude:: events/2/EventOut_NonBoozeItem_111309CET_mon.json :language: JSON - .. container:: paragraph Request to buy non-alcoholic item (`item_ID=5321`) at 11:13:09 on Monday, 2 January 2017. Sale is authorized. Uses the `MorningBoozeCheckAlt1` task. CLI Editor File --------------- .. container:: sectionbody .. container:: sect2 .. rubric:: Policy 2 in CLI Editor :name: policy_2_in_cli_editor .. container:: paragraph An equivalent version of the ``MyFirstPolicyModel`` policy model can again be generated using the APEX CLI editor. A sample APEX CLI script is shown below: .. container:: ulist - |policy2_Model_link| .. container:: :name: footer-text 2.3.0-SNAPSHOT Last updated 2020-04-03 16:04:24 IST .. |File > New to create a new Policy Model| image:: images/mfp/MyFirstPolicy_P1_newPolicyModel1.png .. |Create a new Policy Model| image:: images/mfp/MyFirstPolicy_P1_newPolicyModel2.png .. |Right click to create a new event| image:: images/mfp/MyFirstPolicy_P1_newEvent1.png .. |Fill in the necessary information for the 'SALE_INPUT' event and click 'Submit'| image:: images/mfp/MyFirstPolicy_P1_newEvent2.png .. |Right click to create a new Item Schema| image:: images/mfp/MyFirstPolicy_P1_newItemSchema1.png .. |Create a new Item Schema| image:: images/mfp/MyFirstPolicy_P1_newItemSchema2.png .. |Add new event parameters to an event| image:: images/mfp/MyFirstPolicy_P1_newEvent3.png .. |Right click to create a new task| image:: images/mfp/MyFirstPolicy_P1_newTask1.png .. |Add input and out fields for the task| image:: images/mfp/MyFirstPolicy_P1_newTask2.png .. |Add task logic the task| image:: images/mfp/MyFirstPolicy_P1_newTask3.png .. |Create a new policy| image:: images/mfp/MyFirstPolicy_P1_newPolicy1.png .. |Create a state| image:: images/mfp/MyFirstPolicy_P1_newState1.png .. |Add a Task and Output Mapping| image:: images/mfp/MyFirstPolicy_P1_newState2.png .. |Validate the policy model for error using the 'Model' > 'Validate' menu item| image:: images/mfp/MyFirstPolicy_P1_validatePolicyModel.png .. |Download the completed policy model using the 'File' > 'Download' menu item| image:: images/mfp/MyFirstPolicy_P1_exportPolicyModel1.png .. |Create a new alternative task `MorningBoozeCheckAlt1`| image:: images/mfp/MyFirstPolicy_P2_newTask1.png .. |Right click to edit a policy| image:: images/mfp/MyFirstPolicy_P2_editPolicy1.png .. |State definition with 2 Tasks and Task Selection Logic| image:: images/mfp/MyFirstPolicy_P2_editState1.png .. |taskLogicMvel_link| raw:: html Task Logic: MorningBoozeCheck.mvel .. |taskLogicJs_link| raw:: html Task Logic: MorningBoozeCheck.js .. |policy1_configuration| raw:: html configuration .. |policy1ModelMvel_link| raw:: html APEX CLI Editor code for Policy 1 using .Mvel Task Logic .. |policy1ModelJs_link| raw:: html APEX CLI Editor code for Policy 1 using .Js Task Logic .. |policy2_taskLogic_link| raw:: html `MorningBoozeCheckAlt1` task logic (`MVEL`) .. |policy2_taskSelectionLogic_link| raw:: html `BoozeAuthDecide` task selection logic (`JavaScript`) .. |policy2_configuration_link| raw:: html configuration .. |policy2_Model_link| raw:: html APEX CLI Editor code for Policy 2