1 .. This work is licensed under a Creative Commons Attribution 4.0 International License.
2 .. http://creativecommons.org/licenses/by/4.0
4 .. _apex-myFirstExample:
15 .. container:: sectionbody
17 .. container:: paragraph
19 Consider a scenario where a supermarket chain called
20 *HyperM* controls how it sells items in a policy-based
21 manner. Each time an item is processed by *HyperM*'s
22 point-of-sale (PoS) system an event is generated and
23 published about that item of stock being sold. This
24 event can then be used to update stock levels, etc..
26 .. container:: paragraph
28 *HyperM* want to extend this approach to allow some
29 checks to be performed before the sale can be
30 completed. This can be achieved by requesting a
31 policy-controlled decision as each item is processed
32 by for sale by each PoS system. The decision process
33 is integrated with *HyperM*'s other IT systems that
34 manage stock control, sourcing and purchasing,
35 personnel systems, etc.
37 .. container:: paragraph
39 In this document we will show how APEX and APEX
40 Policies can be used to achieve this, starting with a
41 simple policy, building up to more complicated policy
42 that demonstrates the features of APEX.
47 .. container:: sectionbody
51 .. rubric:: Sales Input Event
52 :name: sales_input_event
54 .. container:: paragraph
56 Each time a PoS system processes a sales item an
57 event with the following format is emitted:
59 .. table:: Table 1. Sale Input Event
61 +----------------------+----------------------+-----------------------+
62 | Event | Fields | Description |
63 +======================+======================+=======================+
64 | SALE_INPUT | time, sale_ID, | Event indicating a |
65 | | amount, item_ID, | sale of an item is |
66 | | quantity, | occurring |
68 | | branch_ID, notes, … | |
69 +----------------------+----------------------+-----------------------+
71 .. container:: paragraph
73 In each ``SALE_INPUT`` event the ``sale_ID`` field
74 is a unique ID generated by the PoS system. A
75 timestamp for the event is stored in the ``time``
76 field. The ``amount`` field refers to the value of
77 the item(s) to be sold (in cents). The ``item_ID``
78 field is a unique identifier for each item type,
79 and can be used to retrieve more information about
80 the item from *HyperM*'s stock control system. The
81 ``quantity`` field refers to the quantity of the
82 item to be sold. The ``assistant_ID`` field is a
83 unique identifier for the PoS operator, and can be
84 used to retrieve more information about the
85 operator from the *HyperM*'s personnel system.
86 Since *HyperM* has many branches the ``branch_ID``
87 identifies the shop. The ``notes`` field contains
88 arbitrary notes about the sale.
92 .. rubric:: Sales Decision Event
93 :name: sales_decision_event
95 .. container:: paragraph
97 After a ``SALE_INPUT`` event is emitted by the PoS
98 system *HyperM*'s policy-based controlled sales
99 checking system emits a Sale Authorization Event
100 indicating whether the sale is authorized or
101 denied. The PoS system can then listen for this
102 event before continuing with the sale.
104 .. table:: Table 2. Sale Authorisation Event
106 +----------------------+----------------------+-----------------------+
107 | Event | Fields | Description |
108 +======================+======================+=======================+
109 | SALE_AUTH | sale_ID, time, | Event indicating a |
110 | | authorized, amount, | sale of an item is |
111 | | item_ID, quantity, | authorized or denied |
112 | | assistant_ID, | |
113 | | branch_ID, notes, | |
115 +----------------------+----------------------+-----------------------+
117 .. container:: paragraph
119 In each ``SALE_AUTH`` event the ``sale_ID`` field
120 is copied from the ``SALE_INPUT`` event that
121 trigger the decision request. The ``SALE_AUTH``
122 event is also timestamped using the ``time`` field,
123 and a field called ``authorised`` is set to
124 ``true`` or ``false`` depending on whether the sale
125 is authorized or denied. The ``message`` field
126 carries an optional message about why a sale was
127 not authorized. The other fields from the
128 ``SALE_INPUT`` event are also included for
133 .. rubric:: Stock Control: Items
134 :name: stock_control_items
136 .. container:: paragraph
138 *HyperM* maintains information about each item for
139 sale in a database table called ``ITEMS``.
141 .. table:: Table 3. Items Database
143 +----------------------+----------------------+-----------------------+
144 | Table | Fields | Description |
145 +======================+======================+=======================+
146 | ITEMS | item_ID, | Database table |
147 | | description, | describing each item |
148 | | cost_price, barcode, | for sale |
151 +----------------------+----------------------+-----------------------+
153 .. container:: paragraph
155 The database table ``ITEMS`` has a row for each
156 items that *HyperM* sells. Each item is identified
157 by an ``item_ID`` value. The ``description`` field
158 stores a description of the item. The cost price of
159 the item is given in ``cost_price``. The barcode of
160 the item is encoded in ``barcode``, while the item
161 supplier is identified by ``supplier_ID``. Items
162 may also be classified into categories using the
163 ``category`` field. Useful categories might
164 include: ``soft drinks``, ``alcoholic drinks``,
165 ``cigarettes``, ``knives``, ``confectionery``,
166 ``bakery``, ``fruit&vegetables``, ``meat``, etc..
170 .. rubric:: Personnel System: Assistants
171 :name: personnel_system_assistants
173 .. table:: Table 4. Assistants Database
175 +----------------------+----------------------+-----------------------+
176 | Table | Fields | Description |
177 +======================+======================+=======================+
178 | ASSISTANTS | assistant_ID, | Database table |
179 | | surname, firstname, | describing each |
180 | | middlename, age, | *HyperM* sales |
181 | | grade, phone_number, | assistant |
183 +----------------------+----------------------+-----------------------+
185 .. container:: paragraph
187 The database table ``ASSISTANTS`` has a row for
188 each sales assistant employed by *HyperM*. Each
189 assistant is identified by an ``assistant_ID``
190 value, with their name given in the ``firstname``,
191 ``middlename`` and ``surname`` fields. The
192 assistant’s age in years is given in ``age``, while
193 their phone number is contained in the
194 ``phone_number`` field. The assistant’s grade is
195 encoded in ``grade``. Useful values for ``grade``
196 might include: ``trainee``, ``operator``,
197 ``supervisor``, etc..
201 .. rubric:: Locations: Branches
202 :name: locations_branches
204 .. table:: Table 5. Branches Database
206 +----------------------+----------------------+-----------------------+
207 | Table | Fields | Description |
208 +======================+======================+=======================+
209 | BRANCHES | branch_ID, | Database table |
210 | | branch_Name, | describing each |
211 | | category, street, | *HyperM* branch |
212 | | city, country, | |
214 +----------------------+----------------------+-----------------------+
216 .. container:: paragraph
218 *HyperM* operates a number of branches. Each branch
219 is described in the ``BRANCHES`` database table.
220 Each branch is identified by a ``branch_ID``, with
221 a branch name given in ``branch_Name``. The address
222 for the branch is encoded in ``street``, ``city``,
223 ``country`` and ``postcode``. The branch category
224 is given in the ``category`` field. Useful values
225 for ``category`` might include: ``Small``,
226 ``Large``, ``Super``, ``Hyper``, etc..
232 .. container:: sectionbody
239 .. container:: paragraph
241 For the first version of our policy, let’s start
242 with something simple. Let us assume that there
243 exists some restriction that alcohol products
244 cannot be sold before 11:30am. In this section we
245 will go through the necessary steps to define a
246 policy that can enforce this for *HyperM*.
250 - Alcohol cannot be sold before 11:30am...
255 .. container:: sectionbody
259 .. rubric:: Create the an new empty Policy Model ``MyFirstPolicyModel``
260 :name: create_the_an_new_empty_policy_model_code_myfirstpolicymodel_code
262 .. container:: paragraph
264 Since an organisation like *HyperM* may have many
265 policies covering many different domains, policies should
266 be grouped into policy sets. In order to edit or deploy a
267 policy, or policy set, the definition of the policy(ies)
268 and all required events, tasks, states, etc., are grouped
269 together into a 'Policy Model'. An organization might
270 define many Policy Models, each containing a different
273 .. container:: paragraph
275 So the first step is to create a new empty Policy Model
276 called ``MyFirstPolicyModel``. Using the APEX Policy
277 Editor, click on the 'File' menus and select 'New'. Then
278 define our new policy model called
279 ``MyFirstPolicyModel``. Use the 'Generate UUID' button to
280 create a new unique ID for the policy model, and fill in
281 a description for the policy model. Press the ``Submit``
282 button to save your changes.
284 .. container:: imageblock
286 .. container:: content
288 |File > New to create a new Policy Model|
290 .. container:: imageblock
292 .. container:: content
294 |Create a new Policy Model|
299 .. container:: sectionbody
303 .. rubric:: Create the input event ``SALE_INPUT`` and the
304 output event ``SALE_AUTH``
305 :name: create_the_input_event_code_sale_input_code_and_the_output_event_code_sale_auth_code
307 .. container:: paragraph
309 Using the APEX Policy Editor, click on the 'Events' tab.
310 In the 'Events' pane, right click and select 'New':
312 .. container:: imageblock
314 .. container:: content
316 |Right click to create a new event|
318 .. container:: paragraph
320 Create a new event type called ``SALE_INPUT``. Use the
321 'Generate UUID' button to create a new unique ID for the
322 event type, and fill in a description for the event. Add
323 a namespace, e.g. ``com.hyperm``. We can add hard-coded
324 strings for the ``Source`` and ``Target``, e.g. ``POS``
325 and ``APEX``. At this stage we will not add any parameter
326 fields, we will leave this until later. Use the
327 ``Submit`` button to create the event.
329 .. container:: imageblock
331 .. container:: content
333 |Fill in the necessary information for the
334 'SALE_INPUT' event and click 'Submit'|
336 .. container:: paragraph
338 Repeat the same steps for a new event type called
339 ``SALE_AUTH``. Just use ``APEX`` as source and ``POS`` as
340 target, since this is the output event coming from APEX
341 going to the sales point.
343 .. container:: paragraph
345 Before we can add parameter fields to an event we must
346 first define APEX Context Item Schemas that can be used
349 .. container:: paragraph
351 To create new item schemas, click on the 'Context Item
352 Schemas' tab. In that 'Context Item Schemas' pane, right
353 click and select 'Create new ContextSchema'.
355 .. container:: imageblock
357 .. container:: content
359 |Right click to create a new Item Schema|
361 .. container:: paragraph
363 Create item schemas with the following characteristics,
364 each with its own unique UUID:
366 .. table:: Table 1. Item Schemas
368 +-----------------+-----------------+-----------------+-----------------+
369 | Name | Schema Flavour | Schema | Description |
371 +=================+=================+=================+=================+
372 | timestamp_type | Java | java.lang.Long | A type for |
373 | | | | ``time`` values |
374 +-----------------+-----------------+-----------------+-----------------+
375 | sale_ID_type | Java | java.lang.Long | A type for |
376 | | | | ``sale_ID`` |
378 +-----------------+-----------------+-----------------+-----------------+
379 | price_type | Java | java.lang.Long | A type for |
381 | | | | unt``/``price`` |
383 +-----------------+-----------------+-----------------+-----------------+
384 | item_ID_type | Java | java.lang.Long | A type for |
385 | | | | ``item_ID`` |
387 +-----------------+-----------------+-----------------+-----------------+
388 | as | Java | java.lang.Long | A type for |
389 | sistant_ID_type | | | ` |
390 | | | | `assistant_ID`` |
392 +-----------------+-----------------+-----------------+-----------------+
393 | quantity_type | Java | ja | A type for |
394 | | | va.lang.Integer | ``quantity`` |
396 +-----------------+-----------------+-----------------+-----------------+
397 | branch_ID_type | Java | java.lang.Long | A type for |
398 | | | | ``branch_ID`` |
400 +-----------------+-----------------+-----------------+-----------------+
401 | notes_type | Java | j | A type for |
402 | | | ava.lang.String | ``notes`` |
404 +-----------------+-----------------+-----------------+-----------------+
405 | authorised_type | Java | ja | A type for |
406 | | | va.lang.Boolean | ``authorised`` |
408 +-----------------+-----------------+-----------------+-----------------+
409 | message_type | Java | j | A type for |
410 | | | ava.lang.String | ``message`` |
412 +-----------------+-----------------+-----------------+-----------------+
414 .. container:: imageblock
416 .. container:: content
418 |Create a new Item Schema|
420 .. container:: paragraph
422 The item schemas can now be seen on the 'Context Item
423 Schemas' tab, and can be updated at any time by
424 right-clicking on the item schemas on the 'Context Item
425 Schemas' tab. Now we can go back to the event definitions
426 for ``SALE_INPUT`` and ``SALE_AUTH`` and add some
431 .. container:: paragraph
433 APEX natively supports schema definitions in ``Java`` and ``Avro``.
434 ``Java`` schema definitions are simply the name of a Java Class. There are some restrictions:
438 - the class must be instantiatable, i.e. not an Java interface or abstract class
440 - primitive types are not supported, i.e. use ``java.lang.Integer`` instead of ``int``, etc.
442 - it must be possible to find the class, i.e. the class must be contained in the Java classpath.
444 .. container:: paragraph
446 ``Avro`` schema definitions can be any valid `Avro <https://avro.apac
447 he.org/docs/current/spec.html>`__ schema. For events using fields defined with
448 Avro schemas, any incoming event containing that field must contain a value that conforms to the Avro schema.
450 .. container:: paragraph
452 Click on the 'Events' tab, then right click the
453 ``SALE_INPUT`` row and select 'Edit Event
454 :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`
455 event add the following event parameters:
457 .. table:: Table 2. Event Parameter Fields for the ``SALE_INPUT`` Event
459 +----------------------+----------------------+-----------------------+
460 | Parameter Name | Parameter Type | Optional |
461 +======================+======================+=======================+
462 | time | timestamp_type | no |
463 +----------------------+----------------------+-----------------------+
464 | sale_ID | sale_ID_type | no |
465 +----------------------+----------------------+-----------------------+
466 | amount | price_type | no |
467 +----------------------+----------------------+-----------------------+
468 | item_ID | item_ID_type | no |
469 +----------------------+----------------------+-----------------------+
470 | quantity | quantity_type | no |
471 +----------------------+----------------------+-----------------------+
472 | assistant_ID | assistant_ID_type | no |
473 +----------------------+----------------------+-----------------------+
474 | branch_ID | branch_ID_type | no |
475 +----------------------+----------------------+-----------------------+
476 | notes | notes_type | *yes* |
477 +----------------------+----------------------+-----------------------+
479 .. container:: paragraph
481 Remember to click the 'Submit' button at the bottom of
482 the event definition pane.
486 .. container:: paragraph
488 Parameter fields can be *optional* in events. If a parameter is not marked as
489 *optional* then by default it is *mandatory*, so it must appear in any input event
490 passed to APEX. If an *optional* field is not set for an output event then value
491 will be set to ``null``.
493 .. container:: imageblock
495 .. container:: content
497 |Add new event parameters to an event|
499 .. container:: paragraph
501 Select the ``SALE_AUTH`` event and add the following
504 .. table:: Table 3. Event Parameter Fields for the ``SALE_AUTH`` Event
506 +----------------------+----------------------+-----------------------+
507 | Parameter Name | Parameter Type | no |
508 +======================+======================+=======================+
509 | sale_ID | sale_ID_type | no |
510 +----------------------+----------------------+-----------------------+
511 | time | timestamp_type | no |
512 +----------------------+----------------------+-----------------------+
513 | authorised | authorised_type | no |
514 +----------------------+----------------------+-----------------------+
515 | message | message_type | *yes* |
516 +----------------------+----------------------+-----------------------+
517 | amount | price_type | no |
518 +----------------------+----------------------+-----------------------+
519 | item_ID | item_ID_type | no |
520 +----------------------+----------------------+-----------------------+
521 | assistant_ID | assistant_ID_type | no |
522 +----------------------+----------------------+-----------------------+
523 | quantity | quantity_type | no |
524 +----------------------+----------------------+-----------------------+
525 | branch_ID | branch_ID_type | no |
526 +----------------------+----------------------+-----------------------+
527 | notes | notes_type | *yes* |
528 +----------------------+----------------------+-----------------------+
530 .. container:: paragraph
532 Remember to click the 'Submit' button at the bottom of
533 the event definition pane.
535 .. container:: paragraph
537 The events for our policy are now defined.
542 .. container:: sectionbody
546 .. rubric:: Create a new Policy and add the *"No Booze
548 :name: create_a_new_policy_and_add_the_em_no_booze_before_11_30_em_check
550 .. container:: paragraph
552 APEX policies are defined using a state-machine model.
553 Each policy comprises one or more *states* that can be
554 individually executed. Where there is more than one
555 *state* the states are chained together to form a
556 `Directed Acyclic Graph
557 (DAG) <https://en.wikipedia.org/wiki/Directed_acyclic_graph>`__
558 of states. A *state* is triggered by passing it a single
559 input (or 'trigger') event and once executed each state
560 then emits an output event. For each *state* the logic
561 for the *state* is embedded in one or more *tasks*. Each
562 *task* contains specific *task logic* that is executed by
563 the APEX execution environment each time the *task* is
564 invoked. Where there is more than one *task* in a *state*
565 then the *state* also defines some *task selection logic*
566 to select an appropriate task each time the *state* is
569 .. container:: paragraph
571 Therefore, to create a new policy we must first define
574 .. container:: paragraph
576 To create a new Task click on the 'Tasks' tab. In the
577 'Tasks' pane, right click and select 'Create new Task'.
578 Create a new Task called ``MorningBoozeCheck``. Use the
579 'Generate UUID' button to create a new unique ID for the
580 task, and fill in a description for the task.
582 .. container:: imageblock
584 .. container:: content
586 |Right click to create a new task|
588 .. container:: paragraph
590 Tasks are configured with a set of *input fields* and a
591 set of *output fields*. To add new input/output fields
592 for a task use the 'Add Task Input Field' and 'Add Task
593 Output Field' button. The list of input and out fields to
594 add for the ``MorningBoozeCheck`` task are given below.
595 The input fields are drawn from the parameters in the
596 state’s input event, and the task’s output fields are
597 used to populate the state’s output event. The task’s
598 input and output fields must be a subset of the event
599 parameters defined for the input and output events for
600 any state that uses that task. (You may have noticed that
601 the input and output fields for the ``MorningBoozeCheck``
602 task have the exact same names and reuse the item schemas
603 that we used for the parameters in the ``SALE_INPUT`` and
604 ``SALE_AUTH`` events respectively).
606 .. table:: Table 1. Input fields for ``MorningBoozeCheck`` task
608 +-----------------------------------+-----------------------------------+
609 | Parameter Name | Parameter Type |
610 +===================================+===================================+
611 | time | timestamp_type |
612 +-----------------------------------+-----------------------------------+
613 | sale_ID | sale_ID_type |
614 +-----------------------------------+-----------------------------------+
615 | amount | price_type |
616 +-----------------------------------+-----------------------------------+
617 | item_ID | item_ID_type |
618 +-----------------------------------+-----------------------------------+
619 | quantity | quantity_type |
620 +-----------------------------------+-----------------------------------+
621 | assistant_ID | assistant_ID_type |
622 +-----------------------------------+-----------------------------------+
623 | branch_ID | branch_ID_type |
624 +-----------------------------------+-----------------------------------+
625 | notes | notes_type |
626 +-----------------------------------+-----------------------------------+
628 .. table:: Table 2. Output fields for ``MorningBoozeCheck`` task
630 +-----------------------------------+-----------------------------------+
631 | Parameter Name | Parameter Type |
632 +===================================+===================================+
633 | sale_ID | sale_ID_type |
634 +-----------------------------------+-----------------------------------+
635 | time | timestamp_type |
636 +-----------------------------------+-----------------------------------+
637 | authorised | authorised_type |
638 +-----------------------------------+-----------------------------------+
639 | message | message_type |
640 +-----------------------------------+-----------------------------------+
641 | amount | price_type |
642 +-----------------------------------+-----------------------------------+
643 | item_ID | item_ID_type |
644 +-----------------------------------+-----------------------------------+
645 | assistant_ID | assistant_ID_type |
646 +-----------------------------------+-----------------------------------+
647 | quantity | quantity_type |
648 +-----------------------------------+-----------------------------------+
649 | branch_ID | branch_ID_type |
650 +-----------------------------------+-----------------------------------+
651 | notes | notes_type |
652 +-----------------------------------+-----------------------------------+
654 .. container:: imageblock
656 .. container:: content
658 |Add input and out fields for the task|
660 .. container:: paragraph
662 Each task must include some 'Task Logic' that implements
663 the behaviour for the task. Task logic can be defined in
664 a number of different ways using a choice of languages.
665 For this task we will author the logic using the
666 Java-like scripting language called
667 ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__.
669 .. container:: paragraph
671 For simplicity use the code for the task logic here(|taskLogicMvel_link|).
672 Paste the script text into the 'Task Logic' box, and use
673 "MVEL" as the 'Task Logic Type / Flavour'.
675 .. container:: paragraph
677 This logic assumes that all items with ``item_ID``
678 between 1000 and 2000 contain alcohol, which is not very
679 realistic, but we will see a better approach for this
680 later. It also uses the standard ``Java`` time utilities
681 to check if the current time is between ``00:00:00 GMT``
682 and ``11:30:00 GMT``. For a detailed guide to how to
683 write your own logic in
684 ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__,
685 ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__ or one
686 of the other supported languages please refer to APEX
690 .. container:: imageblock
692 .. container:: content
694 |Add task logic the task|
696 .. container:: paragraph
698 An alternative version of the same logic is available in
699 JavaScript(|taskLogicJS_link|). Just use "JAVASCRIPT" as the 'Task Logic Type
702 .. container:: paragraph
704 The task definition is now complete so click the 'Submit'
705 button to save the task. The task can now be seen on the
706 'Tasks' tab, and can be updated at any time by
707 right-clicking on the task on the 'Task' tab. Now that we
708 have created our task, we can can create a policy that
711 .. container:: paragraph
713 To create a new Policy click on the 'Policies' tab. In
714 the 'Policies' pane, right click and select 'Create new
717 .. container:: paragraph
719 Create a new Policy called ``MyFirstPolicy``. Use the
720 'Generate UUID' button to create a new unique ID for the
721 policy, and fill in a description for the policy. Use
722 'FREEFORM' as the 'Policy Flavour'.
724 .. container:: paragraph
726 Each policy must have at least one state. Since this is
727 'freeform' policy we can add as many states as we wish.
728 Let’s start with one state. Add a new state called
729 ``BoozeAuthDecide`` to this ``MyFirstPolicy`` policy
730 using the 'Add new State' button after filling in the
731 name of our new state.
733 .. container:: imageblock
735 .. container:: content
737 |Create a new policy|
739 .. container:: paragraph
741 Each state must uses one input event type. For this new
742 state select the ``SALE_INPUT`` event as the input event.
744 .. container:: paragraph
746 Each policy must define a 'First State' and a 'Policy
747 Trigger Event'. The 'Policy Trigger Event' is the input
748 event for the policy as a whole. This event is then
749 passed to the first state in the chain of states in the
750 policy, therefore the 'Policy Trigger Event' will be the
751 input event for the first state. Each policy can only
752 have one 'First State'. For our ``MyFirstPolicy`` policy,
753 select ``BoozeAuthDecide`` as the 'First State'. This
754 will automatically select ``SALE_INPUT`` as the 'Policy
755 Trigger Event' for our policy.
757 .. container:: imageblock
759 .. container:: content
763 .. container:: paragraph
765 In this case we will create a reference the pre-existing
766 ``MorningBoozeCheck`` task that we defined above using
767 the 'Add New Task' button. Select the
768 ``MorningBoozeCheck`` task, and use the name of the task
769 as the 'Local Name' for the task.
771 .. container:: paragraph
773 in the case where a state references more than one task,
774 a 'Default Task' must be selected for the state and some
775 logic ('Task Selection Logic') must be specified to
776 select the appropriate task at execution time. Since our
777 new state ``BoozeAuthDecide`` only has one task the
778 default task is automatically selected and no 'Task
779 Selection Logic' is required.
783 .. container:: paragraph
785 In a 'Policy' 'State' a 'State Output Mapping' has 3 roles: 1) Select which 'State'
786 should be executed next, 2) Select the type of the state’s 'Outgoing Event', and
787 3) Populate the state’s 'Outgoing Event'. This is how states are chained together
788 to form a (`Directed Acyclic Graph (DAG) <https://en.wikipedia.org/wiki/Directed_acyclic_graph>`__)
789 of states. The final state(s) of a policy are those that do not select any 'next'
790 state. Since a 'State' can only accept a single type of event, the type of the
791 event emitted by a previous 'State' must match the incoming event type of the next
792 'State'. This is also how the last state(s) in a policy can emit events of
793 different types. The 'State Output Mapping' is also responsible for taking the
794 fields that are output by the task executed in the state and populating the
795 state’s output populating the state’s output event before it is emitted.
797 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).
799 There are 2 basic types of output mappings:
801 .. container:: olist arabic
803 #. **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.
804 #. **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).
806 .. container:: paragraph
808 Each task reference must also have an associated 'Output
809 State Mapping' so we need an 'Output State Mapping' for
810 the ``BoozeAuthDecide`` state to use when the
811 ``MorningBoozeCheck`` task is executed. The simplest type
812 of output mapping is a 'Direct Output Mapping'.
814 .. container:: paragraph
816 Create a new 'Direct Output Mapping' for the state called
817 ``MorningBoozeCheck_Output_Direct`` using the 'Add New
818 Direct State Output Mapping' button. Select ``SALE_AUTH``
819 as the output event and select ``None`` for the next
820 state value. We can then select this output mapping for
821 use when the the ``MorningBoozeCheck`` task is executed.
822 Since there is only state, and only one task for that
823 state, this output mapping ensures that the
824 ``BoozeAuthDecide`` state is the only state executed and
825 the state (and the policy) can only emit events of type
826 ``SALE_AUTH``. (You may remember that the output fields
827 for the ``MorningBoozeCheck`` task have the exact same
828 names and reuse the item schemas that we used for the
829 parameters in ``SALE_AUTH`` event. The
830 ``MorningBoozeCheck_Output_Direct`` direct output mapping
831 can now automatically copy the values from the
832 ``MorningBoozeCheck`` task directly into outgoing
833 ``SALE_AUTH`` events.)
835 .. container:: imageblock
837 .. container:: content
839 |Add a Task and Output Mapping|
841 .. container:: paragraph
843 Click the 'Submit' button to complete the definition of
844 our ``MyFirstPolicy`` policy. The policy
845 ``MyFirstPolicy`` can now be seen in the list of policies
846 on the 'Policies' tab, and can be updated at any time by
847 right-clicking on the policy on the 'Policies' tab.
849 .. container:: paragraph
851 The ``MyFirstPolicyModel``, including our
852 ``MyFirstPolicy`` policy can now be checked for errors.
853 Click on the 'Model' menu and select 'Validate'. The
854 model should validate without any 'Warning' or 'Error'
855 messages. If you see any 'Error' or 'Warning' messages,
856 carefully read the message as a hint to find where you
857 might have made a mistake when defining some aspect of
860 .. container:: imageblock
862 .. container:: content
864 |Validate the policy model for error using the 'Model'
865 > 'Validate' menu item|
867 .. container:: paragraph
869 Congratulations, you have now completed your first APEX
870 policy. The policy model containing our new policy can
871 now be exported from the editor and saved. Click on the
872 'File' menu and select 'Download' to save the policy
873 model in JSON format. The exported policy model is then
874 available in the directory you selected, for instance
875 ``$APEX_HOME/examples/models/MyFirstPolicy/1/MyFirstPolicyModel_0.0.1.json``.
876 The exported policy can now be loaded into the APEX
877 Policy Engine, or can be re-loaded and edited by the APEX
880 .. container:: imageblock
882 .. container:: content
884 |Download the completed policy model using the 'File'
885 > 'Download' menu item|
890 .. container:: sectionbody
894 .. rubric:: Test Policy Step 1
895 :name: test_policy_step_1
897 .. container:: paragraph
899 To start a new APEX Engine you can use the following
900 |policy1_configuration|. In a full APEX installation you can find
901 this configuration in
902 ``$APEX_HOME/examples/config/MyFirstPolicy/1/MyFirstPolicyConfigStdin2StdoutJsonEvent.json``.
903 This configuration expects incoming events to be in
904 ``JSON`` format and to be passed into the APEX Engine
905 from ``stdin``, and result events will be printed in
906 ``JSON`` format to ``stdout``. This configuration loads
907 the policy model stored in the file
908 'MyFirstPolicyModel_0.0.1.json' as exported from the APEX
909 Editor. Note, you may need to edit this file to provide
910 the full path to wherever you stored the exported policy
913 .. container:: paragraph
915 To test the policy try paste the following events into
916 the console as the APEX engine executes:
918 .. list-table:: Title
922 * - Input Event (JSON)
923 - Output Event (JSON)
925 * - .. literalinclude:: events/1/EventIn_NonBoozeItem_101309GMT.json
927 - .. literalinclude:: events/1/EventOut_NonBoozeItem_101309GMT.json
929 - .. container:: paragraph
931 Request to buy a non-alcoholic item (item_ID=5123) at 10:13:09 on Tuesday, 10 January 2017.
933 * - .. literalinclude:: events/1/EventIn_BoozeItem_084106GMT.json
935 - .. literalinclude:: events/1/EventOut_BoozeItem_084106GMT.json
937 - .. container:: paragraph
939 Request to buy alcohol item (`item_ID=1249`) at 08:41:06 on Monday, 02 January 2017.
940 Sale is not authorized.
941 * - .. literalinclude:: events/1/EventIn_BoozeItem_201713GMT.json
943 - .. literalinclude:: events/1/EventOut_BoozeItem_201713GMT.json
945 - .. container:: paragraph
947 Request to buy alcohol (`item_ID=1943`) at 20:17:13 on Tuesday, 20 December 2016.
954 .. container:: sectionbody
958 .. rubric:: Policy 1 in CLI Editor
959 :name: policy_1_in_cli_editor
961 .. container:: paragraph
963 An equivalent version of the ``MyFirstPolicyModel``
964 policy model can again be generated using the APEX CLI
965 editor. A sample APEX CLI script is shown below:
969 - |policy1ModelMvel_link|
970 - |policy1ModelJs_link|
976 .. container:: sectionbody
981 :name: scenario_policy2
983 .. container:: paragraph
985 *HyperM* have just opened a new branch in a
986 different country, but that country has different
987 rules about when alcohol can be sold! In this
988 section we will go through the necessary steps to
989 extend our policy to enforce this for *HyperM*.
993 - In some branches alcohol cannot be sold before
994 1pm, and not at all on Sundays.
996 .. container:: paragraph
998 Although there are a number of ways to accomplish
999 this the easiest approach for us is to define
1000 another task and then select which task is
1001 appropriate at runtime depending on the branch
1002 identifier in the incoming event.
1007 .. container:: sectionbody
1009 .. container:: sect2
1011 .. rubric:: Extend the Policy with the new Scenario
1012 :name: extend_the_policy_with_the_new_scenario
1014 .. container:: paragraph
1016 To create a new Task click on the 'Tasks' tab. In the
1017 'Tasks' pane, right click and select 'Create new Task':
1019 .. container:: paragraph
1021 Create a new Task called ``MorningBoozeCheckAlt1``. Use
1022 the 'Generate UUID' button to create a new unique ID for
1023 the task, and fill in a description for the task. Select
1024 the same input and output fields that we used earlier
1025 when we defined the ``MorningBoozeCheck`` task earlier.
1027 .. table:: Table 1. Input fields for ``MorningBoozeCheckAlt1`` task
1029 +-----------------------------------+-----------------------------------+
1030 | Parameter Name | Parameter Type |
1031 +===================================+===================================+
1032 | time | timestamp_type |
1033 +-----------------------------------+-----------------------------------+
1034 | sale_ID | sale_ID_type |
1035 +-----------------------------------+-----------------------------------+
1036 | amount | price_type |
1037 +-----------------------------------+-----------------------------------+
1038 | item_ID | item_ID_type |
1039 +-----------------------------------+-----------------------------------+
1040 | quantity | quantity_type |
1041 +-----------------------------------+-----------------------------------+
1042 | assistant_ID | assistant_ID_type |
1043 +-----------------------------------+-----------------------------------+
1044 | branch_ID | branch_ID_type |
1045 +-----------------------------------+-----------------------------------+
1046 | notes | notes_type |
1047 +-----------------------------------+-----------------------------------+
1049 .. table:: Table 2. Output fields for ``MorningBoozeCheckAlt1`` task
1051 +-----------------------------------+-----------------------------------+
1052 | Parameter Name | Parameter Type |
1053 +===================================+===================================+
1054 | sale_ID | sale_ID_type |
1055 +-----------------------------------+-----------------------------------+
1056 | time | timestamp_type |
1057 +-----------------------------------+-----------------------------------+
1058 | authorised | authorised_type |
1059 +-----------------------------------+-----------------------------------+
1060 | message | message_type |
1061 +-----------------------------------+-----------------------------------+
1062 | amount | price_type |
1063 +-----------------------------------+-----------------------------------+
1064 | item_ID | item_ID_type |
1065 +-----------------------------------+-----------------------------------+
1066 | assistant_ID | assistant_ID_type |
1067 +-----------------------------------+-----------------------------------+
1068 | quantity | quantity_type |
1069 +-----------------------------------+-----------------------------------+
1070 | branch_ID | branch_ID_type |
1071 +-----------------------------------+-----------------------------------+
1072 | notes | notes_type |
1073 +-----------------------------------+-----------------------------------+
1075 .. container:: paragraph
1077 This task also requires some 'Task Logic' to implement
1078 the new behaviour for this task.
1080 .. container:: paragraph
1082 For simplicity use the following code for the task logic (|policy2_taskLogic_link|).
1083 It again assumes that all items with ``item_ID`` between
1084 1000 and 2000 contain alcohol. We again use the standard
1085 ``Java`` time utilities to check if the current time is
1086 between ``00:00:00 CET`` and ``13:00:00 CET`` or if it is
1089 .. container:: paragraph
1091 For this task we will again author the logic using the
1092 ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__
1093 scripting language. Sample task logic code (specified in
1094 ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__) is
1095 given below. For a detailed guide to how to write your
1097 ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__,
1098 ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__ or one
1099 of the other supported languages please refer to APEX
1102 .. container:: imageblock
1104 .. container:: content
1106 |Create a new alternative task
1107 \`MorningBoozeCheckAlt1\`|
1109 .. container:: paragraph
1111 The task definition is now complete so click the 'Submit'
1112 button to save the task. Now that we have created our
1113 task, we can can add this task to the single pre-existing
1114 state (``BoozeAuthDecide``) in our policy.
1116 .. container:: paragraph
1118 To edit the ``BoozeAuthDecide`` state in our policy click
1119 on the 'Policies' tab. In the 'Policies' pane, right
1120 click on our ``MyFirstPolicy`` policy and select 'Edit'.
1121 Navigate to the ``BoozeAuthDecide`` state in the 'states'
1122 section at the bottom of the policy definition pane.
1124 .. container:: imageblock
1126 .. container:: content
1128 |Right click to edit a policy|
1130 .. container:: paragraph
1132 To add our new task ``MorningBoozeCheckAlt1``, scroll
1133 down to the ``BoozeAuthDecide`` state in the 'States'
1134 section. In the 'State Tasks' section for
1135 ``BoozeAuthDecide`` use the 'Add new task' button. Select
1136 our new ``MorningBoozeCheckAlt1`` task, and use the name
1137 of the task as the 'Local Name' for the task. The
1138 ``MorningBoozeCheckAlt1`` task can reuse the same
1139 ``MorningBoozeCheck_Output_Direct`` 'Direct State Output
1140 Mapping' that we used for the ``MorningBoozeCheck`` task.
1141 (Recall that the role of the 'State Output Mapping' is to
1142 select the output event for the state, and select the
1143 next state to be executed. These both remain the same as
1146 .. container:: paragraph
1148 Since our state has more than one task we must define
1149 some logic to determine which task should be used each
1150 time the state is executed. This *task selection logic*
1151 is defined in the state definition. For our
1152 ``BoozeAuthDecide`` state we want the choice of which
1153 task to use to be based on the ``branch_ID`` from which
1154 the ``SALE_INPUT`` event originated. For simplicity sake
1155 let us assume that branches with ``branch_ID`` between
1156 ``0`` and ``999`` should use the ``MorningBoozeCheck``
1157 task, and the branches with with ``branch_ID`` between
1158 ``1000`` and ``1999`` should use the
1159 ``MorningBoozeCheckAlt1`` task.
1161 .. container:: paragraph
1163 This time, for variety, we will author the task selection
1165 ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__
1166 scripting language. Sample task selection logic code
1167 is given here (|policy2_taskSelectionLogic_link|). Paste the script text into the 'Task
1168 Selection Logic' box, and use "JAVASCRIPT" as the 'Task
1169 Selection Logic Type / Flavour'. It is necessary to mark
1170 one of the tasks as the 'Default Task' so that the task
1171 selection logic always has a fallback default option in
1172 cases where a particular task cannot be selected. In this
1173 case the ``MorningBoozeCheck`` task can be the default
1177 .. container:: imageblock
1179 .. container:: content
1181 |State definition with 2 Tasks and Task Selection
1184 .. container:: paragraph
1186 When complete don’t forget to click the 'Submit' button
1187 at the bottom of 'Policies' pane for our
1188 ``MyFirstPolicy`` policy after updating the
1189 ``BoozeAuthDecide`` state.
1191 .. container:: paragraph
1193 Congratulations, you have now completed the second step
1194 towards your first APEX policy. The policy model
1195 containing our new policy can again be validated and
1196 exported from the editor and saved as shown in Step 1.
1198 .. container:: paragraph
1200 The exported policy model is then available in the
1201 directory you selected, as
1202 `MyFirstPolicyModel_0.0.1.json <files/mfp-files/2/MyFirstPolicyModel_0.0.1.json>`__.
1203 The exported policy can now be loaded into the APEX
1204 Policy Engine, or can be re-loaded and edited by the APEX
1210 .. container:: sectionbody
1212 .. container:: sect2
1214 .. rubric:: Test Policy Step 2
1215 :name: test_policy_step_2
1217 .. container:: paragraph
1219 To start a new APEX Engine you can use the following
1220 |policy2_configuration_link|. In a full APEX installation you can find
1221 this configuration in
1222 ``$APEX_HOME/examples/config/MyFirstPolicy/2/MyFirstPolicyConfigStdin2StdoutJsonEvent.json``.
1223 Note, this has changed from the configuration file in
1224 Step 1 to enable the ``JAVASCRIPT`` executor for our new
1225 'Task Selection Logic'.
1227 .. container:: paragraph
1229 To test the policy try paste the following events into
1230 the console as the APEX engine executes. Note, all tests
1231 from Step 1 will still work perfectly since none of those
1232 events originate from a branch with ``branch_ID`` between
1233 ``1000`` and ``2000``. The 'Task Selection Logic' will
1234 therefore pick the ``MorningBoozeCheck`` task as
1235 expected, and will therefore give the same results.
1237 .. list-table:: Table 1. Inputs and Outputs when testing *My First Policy*
1241 * - Input Event (JSON)
1242 - Output Event (JSON)
1244 * - .. literalinclude:: events/1/EventIn_BoozeItem_084106GMT.json
1246 - .. literalinclude:: events/1/EventOut_BoozeItem_084106GMT.json
1248 - .. container:: paragraph
1250 Request to buy alcohol item (`item_ID=1249`) at 08:41:06 GMT on Monday, 02 January 2017.
1251 Sale is not authorized. Uses the `MorningBoozeCheck` task.
1253 * - .. literalinclude:: events/2/EventIn_BoozeItem_101433CET_thurs.json
1255 - .. literalinclude:: events/2/EventOut_BoozeItem_101433CET_thurs.json
1257 - .. container:: paragraph
1259 Request to buy alcohol (`item_ID=1047`) at 10:14:33 on Thursday, 22 December 2016.
1260 Sale is not authorized. Uses the `MorningBoozeCheckAlt1` task.
1262 * - .. literalinclude:: events/2/EventIn_BoozeItem_171937CET_sun.json
1264 - .. literalinclude:: events/2/EventOut_BoozeItem_171937CET_sun.json
1266 - .. container:: paragraph
1268 Request to buy alcohol (`item_ID=1443`) at 17:19:37 on Sunday, 18 December 2016.
1269 Sale is not authorized. Uses the `MorningBoozeCheckAlt1` task.
1271 * - .. literalinclude:: events/2/EventIn_NonBoozeItem_111309CET_mon.json
1273 - .. literalinclude:: events/2/EventOut_NonBoozeItem_111309CET_mon.json
1275 - .. container:: paragraph
1277 Request to buy non-alcoholic item (`item_ID=5321`) at 11:13:09 on Monday, 2 January 2017.
1278 Sale is authorized. Uses the `MorningBoozeCheckAlt1` task.
1283 .. container:: sectionbody
1285 .. container:: sect2
1287 .. rubric:: Policy 2 in CLI Editor
1288 :name: policy_2_in_cli_editor
1290 .. container:: paragraph
1292 An equivalent version of the ``MyFirstPolicyModel``
1293 policy model can again be generated using the APEX CLI
1294 editor. A sample APEX CLI script is shown below:
1296 .. container:: ulist
1298 - |policy2_Model_link|
1305 Last updated 2020-04-03 16:04:24 IST
1307 .. |File > New to create a new Policy Model| image:: images/mfp/MyFirstPolicy_P1_newPolicyModel1.png
1308 .. |Create a new Policy Model| image:: images/mfp/MyFirstPolicy_P1_newPolicyModel2.png
1309 .. |ONAP| image:: ../../../images/logos.png
1311 :target: http://www.onap.org/
1312 .. |Right click to create a new event| image:: images/mfp/MyFirstPolicy_P1_newEvent1.png
1313 .. |Fill in the necessary information for the 'SALE_INPUT' event and click 'Submit'| image:: images/mfp/MyFirstPolicy_P1_newEvent2.png
1314 .. |Right click to create a new Item Schema| image:: images/mfp/MyFirstPolicy_P1_newItemSchema1.png
1315 .. |Create a new Item Schema| image:: images/mfp/MyFirstPolicy_P1_newItemSchema2.png
1316 .. |Add new event parameters to an event| image:: images/mfp/MyFirstPolicy_P1_newEvent3.png
1317 .. |Right click to create a new task| image:: images/mfp/MyFirstPolicy_P1_newTask1.png
1318 .. |Add input and out fields for the task| image:: images/mfp/MyFirstPolicy_P1_newTask2.png
1319 .. |Add task logic the task| image:: images/mfp/MyFirstPolicy_P1_newTask3.png
1320 .. |Create a new policy| image:: images/mfp/MyFirstPolicy_P1_newPolicy1.png
1321 .. |Create a state| image:: images/mfp/MyFirstPolicy_P1_newState1.png
1322 .. |Add a Task and Output Mapping| image:: images/mfp/MyFirstPolicy_P1_newState2.png
1323 .. |Validate the policy model for error using the 'Model' > 'Validate' menu item| image:: images/mfp/MyFirstPolicy_P1_validatePolicyModel.png
1324 .. |Download the completed policy model using the 'File' > 'Download' menu item| image:: images/mfp/MyFirstPolicy_P1_exportPolicyModel1.png
1325 .. |Create a new alternative task `MorningBoozeCheckAlt1`| image:: images/mfp/MyFirstPolicy_P2_newTask1.png
1326 .. |Right click to edit a policy| image:: images/mfp/MyFirstPolicy_P2_editPolicy1.png
1327 .. |State definition with 2 Tasks and Task Selection Logic| image:: images/mfp/MyFirstPolicy_P2_editState1.png
1328 .. |taskLogicMvel_link| raw:: html
1330 <a href="https://github.com/onap/policy-apex-pdp/tree/master/examples/examples-myfirstpolicy/src/main/resources/examples/models/MyFirstPolicy/1/MorningBoozeCheck.mvel" target="_blank">Task Logic: MorningBoozeCheck.mvel</a>
1331 .. |taskLogicJs_link| raw:: html
1333 <a href="https://github.com/onap/policy-apex-pdp/tree/master/examples/examples-myfirstpolicy/src/main/resources/examples/models/MyFirstPolicy/1/MorningBoozeCheck.js" target="_blank">Task Logic: MorningBoozeCheck.js</a>
1334 .. |policy1_configuration| raw:: html
1336 <a href="https://github.com/onap/policy-apex-pdp/tree/master/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/1/MyFirstPolicyConfigStdin2StdoutJsonEvent.json" target="_blank">configuration</a>
1337 .. |policy1ModelMvel_link| raw:: html
1339 <a href="https://github.com/onap/policy-apex-pdp/tree/master/examples/examples-myfirstpolicy/src/main/resources/examples/models/MyFirstPolicy/1/MyFirstPolicyModelMvel_0.0.1.apex" target="_blank">APEX CLI Editor code for Policy 1 using .Mvel Task Logic</a>
1340 .. |policy1ModelJs_link| raw:: html
1342 <a href="https://github.com/onap/policy-apex-pdp/tree/master/examples/examples-myfirstpolicy/src/main/resources/examples/models/MyFirstPolicy/1/MyFirstPolicyModelJavascript_0.0.1.apex" target="_blank">APEX CLI Editor code for Policy 1 using .Js Task Logic</a>
1343 .. |policy2_taskLogic_link| raw:: html
1345 <a href="https://github.com/onap/policy-apex-pdp/tree/master/examples/examples-myfirstpolicy/src/main/resources/examples/models/MyFirstPolicy/2/MorningBoozeCheckAlt1.mvel" target="_blank">`MorningBoozeCheckAlt1` task logic (`MVEL`)</a>
1346 .. |policy2_taskSelectionLogic_link| raw:: html
1348 <a href="https://github.com/onap/policy-apex-pdp/tree/master/examples/examples-myfirstpolicy/src/main/resources/examples/models/MyFirstPolicy/2/MyFirstPolicy_BoozeAuthDecideTSL.js" target="_blank">`BoozeAuthDecide` task selection logic (`JavaScript`)</a>
1349 .. |policy2_configuration_link| raw:: html
1351 <a href="https://github.com/onap/policy-apex-pdp/tree/master/examples/examples-myfirstpolicy/src/main/resources/examples/config/MyFirstPolicy/2/MyFirstPolicyConfigStdin2StdoutJsonEvent.json" target="_blank">configuration</a>
1352 .. |policy2_Model_link| raw:: html
1354 <a href="https://github.com/onap/policy-apex-pdp/tree/master/examples/examples-myfirstpolicy/src/main/resources/examples/models/MyFirstPolicy/2/MyFirstPolicyModel_0.0.1.apex" target="_blank">APEX CLI Editor code for Policy 2</a>