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 Decision Event
52 :name: sales_decision_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... container::
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
429 .. container:: admonitionblock tip
433 .. container:: paragraph
435 APEX natively supports schema definitions in ``Java`` and ``Avro``.
436 ``Java`` schema definitions are simply the name of a Java Class. There are some restrictions:
440 - the class must be instantiatable, i.e. not an Java interface or abstract class
442 - primitive types are not supported, i.e. use ``java.lang.Integer`` instead of ``int``, etc.
444 - it must be possible to find the class, i.e. the class must be contained in the Java classpath.
446 .. container:: paragraph
448 ``Avro`` schema definitions can be any valid `Avro <https://avro.apac
449 he.org/docs/current/spec.html>`__ schema. For events using fields defined with
450 Avro schemas, any incoming event containing that field must contain a value that conforms to the Avro schema.
452 .. container:: paragraph
454 Click on the 'Events' tab, then right click the
455 ``SALE_INPUT`` row and select 'Edit Event
456 :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`
457 event add the following event parameters:
459 .. table:: Table 2. Event Parameter Fields for the ``SALE_INPUT`` Event
461 +----------------------+----------------------+-----------------------+
462 | Parameter Name | Parameter Type | Optional |
463 +======================+======================+=======================+
464 | time | timestamp_type | no |
465 +----------------------+----------------------+-----------------------+
466 | sale_ID | sale_ID_type | no |
467 +----------------------+----------------------+-----------------------+
468 | amount | price_type | no |
469 +----------------------+----------------------+-----------------------+
470 | item_ID | item_ID_type | no |
471 +----------------------+----------------------+-----------------------+
472 | quantity | quantity_type | no |
473 +----------------------+----------------------+-----------------------+
474 | assistant_ID | assistant_ID_type | no |
475 +----------------------+----------------------+-----------------------+
476 | branch_ID | branch_ID_type | no |
477 +----------------------+----------------------+-----------------------+
478 | notes | notes_type | *yes* |
479 +----------------------+----------------------+-----------------------+
481 .. container:: paragraph
483 Remember to click the 'Submit' button at the bottom of
484 the event definition pane.
486 .. container:: admonitionblock tip
490 .. container:: paragraph
492 Parameter fields can be *optional* in events. If a parameter is not marked as
493 *optional* then by default it is *mandatory*, so it must appear in any input event
494 passed to APEX. If an *optional* field is not set for an output event then value
495 will be set to ``null``.
497 .. container:: imageblock
499 .. container:: content
501 |Add new event parameters to an event|
503 .. container:: paragraph
505 Select the ``SALE_AUTH`` event and add the following
508 .. table:: Table 3. Event Parameter Fields for the ``SALE_AUTH`` Event
510 +----------------------+----------------------+-----------------------+
511 | Parameter Name | Parameter Type | no |
512 +======================+======================+=======================+
513 | sale_ID | sale_ID_type | no |
514 +----------------------+----------------------+-----------------------+
515 | time | timestamp_type | no |
516 +----------------------+----------------------+-----------------------+
517 | authorised | authorised_type | no |
518 +----------------------+----------------------+-----------------------+
519 | message | message_type | *yes* |
520 +----------------------+----------------------+-----------------------+
521 | amount | price_type | no |
522 +----------------------+----------------------+-----------------------+
523 | item_ID | item_ID_type | no |
524 +----------------------+----------------------+-----------------------+
525 | assistant_ID | assistant_ID_type | no |
526 +----------------------+----------------------+-----------------------+
527 | quantity | quantity_type | no |
528 +----------------------+----------------------+-----------------------+
529 | branch_ID | branch_ID_type | no |
530 +----------------------+----------------------+-----------------------+
531 | notes | notes_type | *yes* |
532 +----------------------+----------------------+-----------------------+
534 .. container:: paragraph
536 Remember to click the 'Submit' button at the bottom of
537 the event definition pane.
539 .. container:: paragraph
541 The events for our policy are now defined.
546 .. container:: sectionbody
550 .. rubric:: Create a new Policy and add the *"No Booze
552 :name: create_a_new_policy_and_add_the_em_no_booze_before_11_30_em_check
554 .. container:: paragraph
556 APEX policies are defined using a state-machine model.
557 Each policy comprises one or more *states* that can be
558 individually executed. Where there is more than one
559 *state* the states are chained together to form a
560 `Directed Acyclic Graph
561 (DAG) <https://en.wikipedia.org/wiki/Directed_acyclic_graph>`__
562 of states. A *state* is triggered by passing it a single
563 input (or 'trigger') event and once executed each state
564 then emits an output event. For each *state* the logic
565 for the *state* is embedded in one or more *tasks*. Each
566 *task* contains specific *task logic* that is executed by
567 the APEX execution environment each time the *task* is
568 invoked. Where there is more than one *task* in a *state*
569 then the *state* also defines some *task selection logic*
570 to select an appropriate task each time the *state* is
573 .. container:: paragraph
575 Therefore, to create a new policy we must first define
578 .. container:: paragraph
580 To create a new Task click on the 'Tasks' tab. In the
581 'Tasks' pane, right click and select 'Create new Task'.
582 Create a new Task called ``MorningBoozeCheck``. Use the
583 'Generate UUID' button to create a new unique ID for the
584 task, and fill in a description for the task.
586 .. container:: imageblock
588 .. container:: content
590 |Right click to create a new task|
592 .. container:: paragraph
594 Tasks are configured with a set of *input fields* and a
595 set of *output fields*. To add new input/output fields
596 for a task use the 'Add Task Input Field' and 'Add Task
597 Output Field' button. The list of input and out fields to
598 add for the ``MorningBoozeCheck`` task are given below.
599 The input fields are drawn from the parameters in the
600 state’s input event, and the task’s output fields are
601 used to populate the state’s output event. The task’s
602 input and output fields must be a subset of the event
603 parameters defined for the input and output events for
604 any state that uses that task. (You may have noticed that
605 the input and output fields for the ``MorningBoozeCheck``
606 task have the exact same names and reuse the item schemas
607 that we used for the parameters in the ``SALE_INPUT`` and
608 ``SALE_AUTH`` events respectively).
610 .. table:: Table 1. Input fields for ``MorningBoozeCheck`` task
612 +-----------------------------------+-----------------------------------+
613 | Parameter Name | Parameter Type |
614 +===================================+===================================+
615 | time | timestamp_type |
616 +-----------------------------------+-----------------------------------+
617 | sale_ID | sale_ID_type |
618 +-----------------------------------+-----------------------------------+
619 | amount | price_type |
620 +-----------------------------------+-----------------------------------+
621 | item_ID | item_ID_type |
622 +-----------------------------------+-----------------------------------+
623 | quantity | quantity_type |
624 +-----------------------------------+-----------------------------------+
625 | assistant_ID | assistant_ID_type |
626 +-----------------------------------+-----------------------------------+
627 | branch_ID | branch_ID_type |
628 +-----------------------------------+-----------------------------------+
629 | notes | notes_type |
630 +-----------------------------------+-----------------------------------+
632 .. table:: Table 2. Output fields for ``MorningBoozeCheck`` task
634 +-----------------------------------+-----------------------------------+
635 | Parameter Name | Parameter Type |
636 +===================================+===================================+
637 | sale_ID | sale_ID_type |
638 +-----------------------------------+-----------------------------------+
639 | time | timestamp_type |
640 +-----------------------------------+-----------------------------------+
641 | authorised | authorised_type |
642 +-----------------------------------+-----------------------------------+
643 | message | message_type |
644 +-----------------------------------+-----------------------------------+
645 | amount | price_type |
646 +-----------------------------------+-----------------------------------+
647 | item_ID | item_ID_type |
648 +-----------------------------------+-----------------------------------+
649 | assistant_ID | assistant_ID_type |
650 +-----------------------------------+-----------------------------------+
651 | quantity | quantity_type |
652 +-----------------------------------+-----------------------------------+
653 | branch_ID | branch_ID_type |
654 +-----------------------------------+-----------------------------------+
655 | notes | notes_type |
656 +-----------------------------------+-----------------------------------+
658 .. container:: imageblock
660 .. container:: content
662 |Add input and out fields for the task|
664 .. container:: paragraph
666 Each task must include some 'Task Logic' that implements
667 the behaviour for the task. Task logic can be defined in
668 a number of different ways using a choice of languages.
669 For this task we will author the logic using the
670 Java-like scripting language called
671 ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__.
673 .. container:: paragraph
675 For simplicity use the following code for the task logic.
676 Paste the script text into the 'Task Logic' box, and use
677 "MVEL" as the 'Task Logic Type / Flavour'.
679 .. container:: paragraph
681 This logic assumes that all items with ``item_ID``
682 between 1000 and 2000 contain alcohol, which is not very
683 realistic, but we will see a better approach for this
684 later. It also uses the standard ``Java`` time utilities
685 to check if the current time is between ``00:00:00 GMT``
686 and ``11:30:00 GMT``. For a detailed guide to how to
687 write your own logic in
688 ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__,
689 ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__ or one
690 of the other supported languages please refer to APEX
693 .. container:: listingblock
695 .. container:: content
700 * ============LICENSE_START=======================================================
701 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
702 * ================================================================================
703 * Licensed under the Apache License, Version 2.0 (the "License");
704 * you may not use this file except in compliance with the License.
705 * You may obtain a copy of the License at
707 * http://www.apache.org/licenses/LICENSE-2.0
709 * Unless required by applicable law or agreed to in writing, software
710 * distributed under the License is distributed on an "AS IS" BASIS,
711 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
712 * See the License for the specific language governing permissions and
713 * limitations under the License.
715 * SPDX-License-Identifier: Apache-2.0
716 * ============LICENSE_END=========================================================
718 import java.util.Date;
719 import java.util.Calendar;
720 import java.util.TimeZone;
721 import java.text.SimpleDateFormat;
723 logger.info("Task Execution: '"+subject.id+"'. Input Fields: '"+inFields+"'");
725 outFields.put("amount" , inFields.get("amount"));
726 outFields.put("assistant_ID", inFields.get("assistant_ID"));
727 outFields.put("notes" , inFields.get("notes"));
728 outFields.put("quantity" , inFields.get("quantity"));
729 outFields.put("branch_ID" , inFields.get("branch_ID"));
730 outFields.put("item_ID" , inFields.get("item_ID"));
731 outFields.put("time" , inFields.get("time"));
732 outFields.put("sale_ID" , inFields.get("sale_ID"));
734 item_id = inFields.get("item_ID");
736 //The events used later to test this task use GMT timezone!
737 gmt = TimeZone.getTimeZone("GMT");
738 timenow = Calendar.getInstance(gmt);
739 df = new SimpleDateFormat("HH:mm:ss z");
741 timenow.setTimeInMillis(inFields.get("time"));
743 midnight = timenow.clone();
745 timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
746 timenow.get(Calendar.DATE),0,0,0);
747 eleven30 = timenow.clone();
749 timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
750 timenow.get(Calendar.DATE),11,30,0);
752 itemisalcohol = false;
753 if(item_id != null && item_id >=1000 && item_id < 2000)
754 itemisalcohol = true;
757 && timenow.after(midnight) && timenow.before(eleven30)){
758 outFields.put("authorised", false);
759 outFields.put("message", "Sale not authorised by policy task "+subject.taskName+
760 " for time "+df.format(timenow.getTime())+
761 ". Alcohol can not be sold between "+df.format(midnight.getTime())+
762 " and "+df.format(eleven30.getTime()));
766 outFields.put("authorised", true);
767 outFields.put("message", "Sale authorised by policy task "+subject.taskName+
768 " for time "+df.format(timenow.getTime()));
773 This task checks if a sale request is for an item that is an alcoholic drink.
774 If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
775 authorised. Otherwise the sale is authorised.
776 In this implementation we assume that items with item_ID value between 1000 and
777 2000 are all alcoholic drinks :-)
780 .. container:: imageblock
782 .. container:: content
784 |Add task logic the task|
786 .. container:: paragraph
788 An alternative version of the same logic is available in
789 JavaScript. Just use "JAVASCRIPT" as the 'Task Logic Type
792 .. container:: listingblock
794 .. container:: content
799 * ============LICENSE_START=======================================================
800 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
801 * ================================================================================
802 * Licensed under the Apache License, Version 2.0 (the "License");
803 * you may not use this file except in compliance with the License.
804 * You may obtain a copy of the License at
806 * http://www.apache.org/licenses/LICENSE-2.0
808 * Unless required by applicable law or agreed to in writing, software
809 * distributed under the License is distributed on an "AS IS" BASIS,
810 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
811 * See the License for the specific language governing permissions and
812 * limitations under the License.
814 * SPDX-License-Identifier: Apache-2.0
815 * ============LICENSE_END=========================================================
818 var returnValueType = Java.type("java.lang.Boolean");
819 var returnValue = new returnValueType(true);
821 // Load compatibility script for imports etc
822 load("nashorn:mozilla_compat.js");
823 importPackage(java.text);
824 importClass(java.text.SimpleDateFormat);
826 executor.logger.info("Task Execution: '"+executor.subject.id+"'. Input Fields: '"+executor.inFields+"'");
828 executor.outFields.put("amount" , executor.inFields.get("amount"));
829 executor.outFields.put("assistant_ID", executor.inFields.get("assistant_ID"));
830 executor.outFields.put("notes" , executor.inFields.get("notes"));
831 executor.outFields.put("quantity" , executor.inFields.get("quantity"));
832 executor.outFields.put("branch_ID" , executor.inFields.get("branch_ID"));
833 executor.outFields.put("item_ID" , executor.inFields.get("item_ID"));
834 executor.outFields.put("time" , executor.inFields.get("time"));
835 executor.outFields.put("sale_ID" , executor.inFields.get("sale_ID"));
837 item_id = executor.inFields.get("item_ID");
839 //All times in this script are in GMT/UTC since the policy and events assume time is in GMT.
840 var timenow_gmt = new Date(Number(executor.inFields.get("time")));
842 var midnight_gmt = new Date(Number(executor.inFields.get("time")));
843 midnight_gmt.setUTCHours(0,0,0,0);
845 var eleven30_gmt = new Date(Number(executor.inFields.get("time")));
846 eleven30_gmt.setUTCHours(11,30,0,0);
848 var timeformatter = new java.text.SimpleDateFormat("HH:mm:ss z");
850 var itemisalcohol = false;
851 if(item_id != null && item_id >=1000 && item_id < 2000)
852 itemisalcohol = true;
855 && timenow_gmt.getTime() >= midnight_gmt.getTime()
856 && timenow_gmt.getTime() < eleven30_gmt.getTime()) {
858 executor.outFields.put("authorised", false);
859 executor.outFields.put("message", "Sale not authorised by policy task " +
860 executor.subject.taskName+ " for time " + timeformatter.format(timenow_gmt.getTime()) +
861 ". Alcohol can not be sold between " + timeformatter.format(midnight_gmt.getTime()) +
862 " and " + timeformatter.format(eleven30_gmt.getTime()));
865 executor.outFields.put("authorised", true);
866 executor.outFields.put("message", "Sale authorised by policy task " +
867 executor.subject.taskName + " for time "+timeformatter.format(timenow_gmt.getTime()));
871 This task checks if a sale request is for an item that is an alcoholic drink.
872 If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
873 authorised. Otherwise the sale is authorised.
874 In this implementation we assume that items with item_ID value between 1000 and
875 2000 are all alcoholic drinks :-)
878 .. container:: paragraph
880 The task definition is now complete so click the 'Submit'
881 button to save the task. The task can now be seen on the
882 'Tasks' tab, and can be updated at any time by
883 right-clicking on the task on the 'Task' tab. Now that we
884 have created our task, we can can create a policy that
887 .. container:: paragraph
889 To create a new Policy click on the 'Policies' tab. In
890 the 'Policies' pane, right click and select 'Create new
893 .. container:: paragraph
895 Create a new Policy called ``MyFirstPolicy``. Use the
896 'Generate UUID' button to create a new unique ID for the
897 policy, and fill in a description for the policy. Use
898 'FREEFORM' as the 'Policy Flavour'.
900 .. container:: paragraph
902 Each policy must have at least one state. Since this is
903 'freeform' policy we can add as many states as we wish.
904 Let’s start with one state. Add a new state called
905 ``BoozeAuthDecide`` to this ``MyFirstPolicy`` policy
906 using the 'Add new State' button after filling in the
907 name of our new state.
909 .. container:: imageblock
911 .. container:: content
913 |Create a new policy|
915 .. container:: paragraph
917 Each state must uses one input event type. For this new
918 state select the ``SALE_INPUT`` event as the input event.
920 .. container:: paragraph
922 Each policy must define a 'First State' and a 'Policy
923 Trigger Event'. The 'Policy Trigger Event' is the input
924 event for the policy as a whole. This event is then
925 passed to the first state in the chain of states in the
926 policy, therefore the 'Policy Trigger Event' will be the
927 input event for the first state. Each policy can only
928 have one 'First State'. For our ``MyFirstPolicy`` policy,
929 select ``BoozeAuthDecide`` as the 'First State'. This
930 will automatically select ``SALE_INPUT`` as the 'Policy
931 Trigger Event' for our policy.
933 .. container:: imageblock
935 .. container:: content
939 .. container:: paragraph
941 In this case we will create a reference the pre-existing
942 ``MorningBoozeCheck`` task that we defined above using
943 the 'Add New Task' button. Select the
944 ``MorningBoozeCheck`` task, and use the name of the task
945 as the 'Local Name' for the task.
947 .. container:: paragraph
949 in the case where a state references more than one task,
950 a 'Default Task' must be selected for the state and some
951 logic ('Task Selection Logic') must be specified to
952 select the appropriate task at execution time. Since our
953 new state ``BoozeAuthDecide`` only has one task the
954 default task is automatically selected and no 'Task
955 Selection Logic' is required.
957 .. container:: admonitionblock note
961 .. container:: paragraph
962 In a 'Policy' 'State' a 'State Output Mapping' has 3 roles: 1) Select which 'State'
963 should be executed next, 2) Select the type of the state’s 'Outgoing Event', and
964 3) Populate the state’s 'Outgoing Event'. This is how states are chained together
965 to form a (`Directed Acyclic Graph (DAG) <https://en.wikipedia.org/wiki/Directed_acyclic_graph>`__)
966 of states. The final state(s) of a policy are those that do not select any 'next'
967 state. Since a 'State' can only accept a single type of event, the type of the
968 event emitted by a previous 'State' must match the incoming event type of the next
969 'State'. This is also how the last state(s) in a policy can emit events of
970 different types. The 'State Output Mapping' is also responsible for taking the
971 fields that are output by the task executed in the state and populating the
972 state’s output populating the state’s output event before it is emitted.
974 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).
976 There are 2 basic types of output mappings:
978 .. container:: olist arabic
980 #. **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.
981 #. **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).
983 .. container:: paragraph
985 Each task reference must also have an associated 'Output
986 State Mapping' so we need an 'Output State Mapping' for
987 the ``BoozeAuthDecide`` state to use when the
988 ``MorningBoozeCheck`` task is executed. The simplest type
989 of output mapping is a 'Direct Output Mapping'.
991 .. container:: paragraph
993 Create a new 'Direct Output Mapping' for the state called
994 ``MorningBoozeCheck_Output_Direct`` using the 'Add New
995 Direct State Output Mapping' button. Select ``SALE_AUTH``
996 as the output event and select ``None`` for the next
997 state value. We can then select this output mapping for
998 use when the the ``MorningBoozeCheck`` task is executed.
999 Since there is only state, and only one task for that
1000 state, this output mapping ensures that the
1001 ``BoozeAuthDecide`` state is the only state executed and
1002 the state (and the policy) can only emit events of type
1003 ``SALE_AUTH``. (You may remember that the output fields
1004 for the ``MorningBoozeCheck`` task have the exact same
1005 names and reuse the item schemas that we used for the
1006 parameters in ``SALE_AUTH`` event. The
1007 ``MorningBoozeCheck_Output_Direct`` direct output mapping
1008 can now automatically copy the values from the
1009 ``MorningBoozeCheck`` task directly into outgoing
1010 ``SALE_AUTH`` events.)
1012 .. container:: imageblock
1014 .. container:: content
1016 |Add a Task and Output Mapping|
1018 .. container:: paragraph
1020 Click the 'Submit' button to complete the definition of
1021 our ``MyFirstPolicy`` policy. The policy
1022 ``MyFirstPolicy`` can now be seen in the list of policies
1023 on the 'Policies' tab, and can be updated at any time by
1024 right-clicking on the policy on the 'Policies' tab.
1026 .. container:: paragraph
1028 The ``MyFirstPolicyModel``, including our
1029 ``MyFirstPolicy`` policy can now be checked for errors.
1030 Click on the 'Model' menu and select 'Validate'. The
1031 model should validate without any 'Warning' or 'Error'
1032 messages. If you see any 'Error' or 'Warning' messages,
1033 carefully read the message as a hint to find where you
1034 might have made a mistake when defining some aspect of
1037 .. container:: imageblock
1039 .. container:: content
1041 |Validate the policy model for error using the 'Model'
1042 > 'Validate' menu item|
1044 .. container:: paragraph
1046 Congratulations, you have now completed your first APEX
1047 policy. The policy model containing our new policy can
1048 now be exported from the editor and saved. Click on the
1049 'File' menu and select 'Download' to save the policy
1050 model in JSON format. The exported policy model is then
1051 available in the directory you selected, for instance
1052 ``$APEX_HOME/examples/models/MyFirstPolicy/1/MyFirstPolicyModel_0.0.1.json``.
1053 The exported policy can now be loaded into the APEX
1054 Policy Engine, or can be re-loaded and edited by the APEX
1057 .. container:: imageblock
1059 .. container:: content
1061 |Download the completed policy model using the 'File'
1062 > 'Download' menu item|
1067 .. container:: sectionbody
1069 .. container:: sect1
1071 .. rubric:: Test Policy Step 1
1072 :name: test_policy_step_1
1074 .. container:: paragraph
1076 To start a new APEX Engine you can use the following
1077 configuration. In a full APEX installation you can find
1078 this configuration in
1079 ``$APEX_HOME/examples/config/MyFirstPolicy/1/MyFirstPolicyConfigStdin2StdoutJsonEvent.json``.
1080 This configuration expects incoming events to be in
1081 ``JSON`` format and to be passed into the APEX Engine
1082 from ``stdin``, and result events will be printed in
1083 ``JSON`` format to ``stdout``. This configuration loads
1084 the policy model stored in the file
1085 'MyFirstPolicyModel_0.0.1.json' as exported from the APEX
1086 Editor. Note, you may need to edit this file to provide
1087 the full path to wherever you stored the exported policy
1090 .. container:: listingblock
1092 .. container:: content
1097 "engineServiceParameters" : {
1098 "name" : "MyFirstPolicyApexEngine",
1099 "version" : "0.0.1",
1101 "instanceCount" : 4,
1102 "deploymentPort" : 12345,
1103 "policyModelFileName" : "examples/models/MyFirstPolicy/1/MyFirstPolicyModel_0.0.1.json",
1104 "engineParameters" : {
1105 "executorParameters" : {
1107 "parameterClassName" : "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters"
1110 "parameterClassName" : "org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters"
1115 "eventOutputParameters": {
1117 "carrierTechnologyParameters" : {
1118 "carrierTechnology" : "FILE",
1123 "eventProtocolParameters" : {
1124 "eventProtocol" : "JSON"
1128 "eventInputParameters": {
1130 "carrierTechnologyParameters" : {
1131 "carrierTechnology" : "FILE",
1136 "eventProtocolParameters" : {
1137 "eventProtocol" : "JSON"
1143 .. container:: paragraph
1145 To test the policy try paste the following events into
1146 the console as the APEX engine executes:
1148 .. list-table:: Title
1152 * - Input Event (JSON)
1153 - Output Event (JSON)
1155 * - .. literalinclude:: events/1/EventIn_NonBoozeItem_101309GMT.json
1157 - .. literalinclude:: events/1/EventOut_NonBoozeItem_101309GMT.json
1159 - .. container:: paragraph
1161 Request to buy a non-alcoholic item (item_ID=5123) at 10:13:09 on Tuesday, 10 January 2017.
1163 * - .. literalinclude:: events/1/EventIn_BoozeItem_084106GMT.json
1165 - .. literalinclude:: events/1/EventOut_BoozeItem_084106GMT.json
1167 - .. container:: paragraph
1169 Request to buy alcohol item (`item_ID=1249`) at _08:41:06_ on _Monday, 02 January 2017_.
1170 Sale is not authorized.
1171 * - .. literalinclude:: events/1/EventIn_BoozeItem_201713GMT.json
1173 - .. literalinclude:: events/1/EventOut_BoozeItem_201713GMT.json
1175 - .. container:: paragraph
1177 Request to buy alcohol (`item_ID=1943`) at _20:17:13_ on _Tuesday, 20 December 2016_.
1184 .. container:: sectionbody
1186 .. container:: sect1
1188 .. rubric:: Policy 1 in CLI Editor
1189 :name: policy_1_in_cli_editor
1191 .. container:: paragraph
1193 An equivalent version of the ``MyFirstPolicyModel``
1194 policy model can again be generated using the APEX CLI
1195 editor. A sample APEX CLI script is shown below:
1197 .. container:: listingblock
1199 .. container:: content
1203 #-------------------------------------------------------------------------------
1204 # ============LICENSE_START=======================================================
1205 # Copyright (C) 2016-2018 Ericsson. All rights reserved.
1206 # ================================================================================
1207 # Licensed under the Apache License, Version 2.0 (the "License");
1208 # you may not use this file except in compliance with the License.
1209 # You may obtain a copy of the License at
1211 # http://www.apache.org/licenses/LICENSE-2.0
1213 # Unless required by applicable law or agreed to in writing, software
1214 # distributed under the License is distributed on an "AS IS" BASIS,
1215 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1216 # See the License for the specific language governing permissions and
1217 # limitations under the License.
1219 # SPDX-License-Identifier: Apache-2.0
1220 # ============LICENSE_END=========================================================
1221 #-------------------------------------------------------------------------------
1223 model create name=MyFirstPolicyModel version=0.0.1 uuid=540226fb-55ee-4f0e-a444-983a0494818e description="This is my first Apex Policy Model."
1225 schema create name=assistant_ID_type version=0.0.1 uuid=36df4c71-9616-4206-8b53-976a5cd4bd87 description="A type for 'assistant_ID' values" flavour=Java schema=java.lang.Long
1227 schema create name=authorised_type version=0.0.1 uuid=d48b619e-d00d-4008-b884-02d76ea4350b description="A type for 'authorised' values" flavour=Java schema=java.lang.Boolean
1229 schema create name=branch_ID_type version=0.0.1 uuid=6468845f-4122-4128-8e49-0f52c26078b5 description="A type for 'branch_ID' values" flavour=Java schema=java.lang.Long
1231 schema create name=item_ID_type version=0.0.1 uuid=4f227ff1-aee0-453a-b6b6-9a4b2e0da932 description="A type for 'item_ID' values" flavour=Java schema=java.lang.Long
1233 schema create name=message_type version=0.0.1 uuid=ad1431bb-3155-4e73-b5a3-b89bee498749 description="A type for 'message' values" flavour=Java schema=java.lang.String
1235 schema create name=notes_type version=0.0.1 uuid=eecfde90-896c-4343-8f9c-2603ced94e2d description="A type for 'notes' values" flavour=Java schema=java.lang.String
1237 schema create name=price_type version=0.0.1 uuid=52c2fc45-fd8c-463c-bd6f-d91b0554aea7 description="A type for 'amount'/'price' values" flavour=Java schema=java.lang.Long
1239 schema create name=quantity_type version=0.0.1 uuid=ac3d9842-80af-4a98-951c-bd79a431c613 description="A type for 'quantity' values" flavour=Java schema=java.lang.Integer
1241 schema create name=sale_ID_type version=0.0.1 uuid=cca47d74-7754-4a61-b163-ca31f66b157b description="A type for 'sale_ID' values" flavour=Java schema=java.lang.Long
1243 schema create name=timestamp_type version=0.0.1 uuid=fd594e88-411d-4a94-b2be-697b3a0d7adf description="A type for 'time' values" flavour=Java schema=java.lang.Long
1245 task create name=MorningBoozeCheck version=0.0.1 uuid=3351b0f4-cf06-4fa2-8823-edf67bd30223 description=LS
1246 This task checks if the sales request is for an item that contains alcohol.
1247 If the local time is between 00:00:00 and 11:30:00 then the sale is not authorised. Otherwise the sale is authorised.
1248 In this implementation we assume that all items with item_ID values between 1000 and 2000 contain alcohol :-)
1250 task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
1251 task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=amount schemaName=price_type schemaVersion=0.0.1
1252 task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
1253 task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
1254 task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=quantity schemaName=quantity_type schemaVersion=0.0.1
1255 task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
1256 task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
1257 task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=time schemaName=timestamp_type schemaVersion=0.0.1
1258 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
1259 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=amount schemaName=price_type schemaVersion=0.0.1
1260 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
1261 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
1262 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=quantity schemaName=quantity_type schemaVersion=0.0.1
1263 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
1264 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
1265 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=authorised schemaName=authorised_type schemaVersion=0.0.1
1266 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=time schemaName=timestamp_type schemaVersion=0.0.1
1267 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=message schemaName=message_type schemaVersion=0.0.1 optional=true
1268 task logic create name=MorningBoozeCheck version=0.0.1 logicFlavour=MVEL logic=LS
1270 * ============LICENSE_START=======================================================
1271 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
1272 * ================================================================================
1273 * Licensed under the Apache License, Version 2.0 (the "License");
1274 * you may not use this file except in compliance with the License.
1275 * You may obtain a copy of the License at
1277 * http://www.apache.org/licenses/LICENSE-2.0
1279 * Unless required by applicable law or agreed to in writing, software
1280 * distributed under the License is distributed on an "AS IS" BASIS,
1281 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1282 * See the License for the specific language governing permissions and
1283 * limitations under the License.
1285 * SPDX-License-Identifier: Apache-2.0
1286 * ============LICENSE_END=========================================================
1288 import java.util.Date;
1289 import java.util.Calendar;
1290 import java.util.TimeZone;
1291 import java.text.SimpleDateFormat;
1293 logger.info("Task Execution: '"+subject.id+"'. Input Fields: '"+inFields+"'");
1295 outFields.put("amount" , inFields.get("amount"));
1296 outFields.put("assistant_ID", inFields.get("assistant_ID"));
1297 outFields.put("notes" , inFields.get("notes"));
1298 outFields.put("quantity" , inFields.get("quantity"));
1299 outFields.put("branch_ID" , inFields.get("branch_ID"));
1300 outFields.put("item_ID" , inFields.get("item_ID"));
1301 outFields.put("time" , inFields.get("time"));
1302 outFields.put("sale_ID" , inFields.get("sale_ID"));
1304 item_id = inFields.get("item_ID");
1306 //The events used later to test this task use GMT timezone!
1307 gmt = TimeZone.getTimeZone("GMT");
1308 timenow = Calendar.getInstance(gmt);
1309 df = new SimpleDateFormat("HH:mm:ss z");
1310 df.setTimeZone(gmt);
1311 timenow.setTimeInMillis(inFields.get("time"));
1313 midnight = timenow.clone();
1315 timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
1316 timenow.get(Calendar.DATE),0,0,0);
1317 eleven30 = timenow.clone();
1319 timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
1320 timenow.get(Calendar.DATE),11,30,0);
1322 itemisalcohol = false;
1323 if(item_id != null && item_id >=1000 && item_id < 2000)
1324 itemisalcohol = true;
1327 && timenow.after(midnight) && timenow.before(eleven30)){
1328 outFields.put("authorised", false);
1329 outFields.put("message", "Sale not authorised by policy task "+subject.taskName+
1330 " for time "+df.format(timenow.getTime())+
1331 ". Alcohol can not be sold between "+df.format(midnight.getTime())+
1332 " and "+df.format(eleven30.getTime()));
1336 outFields.put("authorised", true);
1337 outFields.put("message", "Sale authorised by policy task "+subject.taskName+
1338 " for time "+df.format(timenow.getTime()));
1343 This task checks if a sale request is for an item that is an alcoholic drink.
1344 If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
1345 authorised. Otherwise the sale is authorised.
1346 In this implementation we assume that items with item_ID value between 1000 and
1347 2000 are all alcoholic drinks :-)
1351 event create name=SALE_AUTH version=0.0.1 uuid=c4500941-3f98-4080-a9cc-5b9753ed050b description="An event emitted by the Policy to indicate whether the sale of an item has been authorised" nameSpace=com.hyperm source="APEX" target="POS"
1352 event parameter create name=SALE_AUTH version=0.0.1 parName=amount schemaName=price_type schemaVersion=0.0.1
1353 event parameter create name=SALE_AUTH version=0.0.1 parName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
1354 event parameter create name=SALE_AUTH version=0.0.1 parName=authorised schemaName=authorised_type schemaVersion=0.0.1
1355 event parameter create name=SALE_AUTH version=0.0.1 parName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
1356 event parameter create name=SALE_AUTH version=0.0.1 parName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
1357 event parameter create name=SALE_AUTH version=0.0.1 parName=message schemaName=message_type schemaVersion=0.0.1 optional=true
1358 event parameter create name=SALE_AUTH version=0.0.1 parName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
1359 event parameter create name=SALE_AUTH version=0.0.1 parName=quantity schemaName=quantity_type schemaVersion=0.0.1
1360 event parameter create name=SALE_AUTH version=0.0.1 parName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
1361 event parameter create name=SALE_AUTH version=0.0.1 parName=time schemaName=timestamp_type schemaVersion=0.0.1
1363 event create name=SALE_INPUT version=0.0.1 uuid=4f04aa98-e917-4f4a-882a-c75ba5a99374 description="An event raised by the PoS system each time an item is scanned for purchase" nameSpace=com.hyperm source="POS" target="APEX"
1364 event parameter create name=SALE_INPUT version=0.0.1 parName=amount schemaName=price_type schemaVersion=0.0.1
1365 event parameter create name=SALE_INPUT version=0.0.1 parName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
1366 event parameter create name=SALE_INPUT version=0.0.1 parName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
1367 event parameter create name=SALE_INPUT version=0.0.1 parName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
1368 event parameter create name=SALE_INPUT version=0.0.1 parName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
1369 event parameter create name=SALE_INPUT version=0.0.1 parName=quantity schemaName=quantity_type schemaVersion=0.0.1
1370 event parameter create name=SALE_INPUT version=0.0.1 parName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
1371 event parameter create name=SALE_INPUT version=0.0.1 parName=time schemaName=timestamp_type schemaVersion=0.0.1
1374 policy create name=MyFirstPolicy version=0.0.1 uuid=6c5e410f-489a-46ff-964e-982ce6e8b6d0 description="This is my first Apex policy. It checks if a sale should be authorised or not." template=FREEFORM firstState=BoozeAuthDecide
1375 policy state create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide triggerName=SALE_INPUT triggerVersion=0.0.1 defaultTaskName=MorningBoozeCheck defaultTaskVersion=0.0.1
1376 policy state output create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide outputName=MorningBoozeCheck_Output_Direct eventName=SALE_AUTH eventVersion=0.0.1 nextState=NULL
1377 policy state taskref create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide taskLocalName=MorningBoozeCheck taskName=MorningBoozeCheck taskVersion=0.0.1 outputType=DIRECT outputName=MorningBoozeCheck_Output_Direct
1382 .. container:: sectionbody
1384 .. container:: sect1
1386 .. rubric:: Scenario
1389 .. container:: paragraph
1391 *HyperM* have just opened a new branch in a
1392 different country, but that country has different
1393 rules about when alcohol can be sold! In this
1394 section we will go through the necessary steps to
1395 extend our policy to enforce this for *HyperM*.
1397 .. container:: ulist
1399 - In some branches alcohol cannot be sold before
1400 1pm, and not at all on Sundays.
1402 .. container:: paragraph
1404 Although there are a number of ways to accomplish
1405 this the easiest approach for us is to define
1406 another task and then select which task is
1407 appropriate at runtime depending on the branch
1408 identifier in the incoming event.
1413 .. container:: sectionbody
1415 .. container:: sect2
1417 .. rubric:: Extend the Policy with the new Scenario
1418 :name: extend_the_policy_with_the_new_scenario
1420 .. container:: paragraph
1422 To create a new Task click on the 'Tasks' tab. In the
1423 'Tasks' pane, right click and select 'Create new Task':
1425 .. container:: paragraph
1427 Create a new Task called ``MorningBoozeCheckAlt1``. Use
1428 the 'Generate UUID' button to create a new unique ID for
1429 the task, and fill in a description for the task. Select
1430 the same input and output fields that we used earlier
1431 when we defined the ``MorningBoozeCheck`` task earlier.
1433 .. table:: Table 1. Input fields for
1434 ``MorningBoozeCheckAlt1`` task
1436 +-----------------------------------+-----------------------------------+
1437 | Parameter Name | Parameter Type |
1438 +===================================+===================================+
1439 | time | timestamp_type |
1440 +-----------------------------------+-----------------------------------+
1441 | sale_ID | sale_ID_type |
1442 +-----------------------------------+-----------------------------------+
1443 | amount | price_type |
1444 +-----------------------------------+-----------------------------------+
1445 | item_ID | item_ID_type |
1446 +-----------------------------------+-----------------------------------+
1447 | quantity | quantity_type |
1448 +-----------------------------------+-----------------------------------+
1449 | assistant_ID | assistant_ID_type |
1450 +-----------------------------------+-----------------------------------+
1451 | branch_ID | branch_ID_type |
1452 +-----------------------------------+-----------------------------------+
1453 | notes | notes_type |
1454 +-----------------------------------+-----------------------------------+
1456 .. table:: Table 2. Output fields for
1457 ``MorningBoozeCheckAlt1`` task
1459 +-----------------------------------+-----------------------------------+
1460 | Parameter Name | Parameter Type |
1461 +===================================+===================================+
1462 | sale_ID | sale_ID_type |
1463 +-----------------------------------+-----------------------------------+
1464 | time | timestamp_type |
1465 +-----------------------------------+-----------------------------------+
1466 | authorised | authorised_type |
1467 +-----------------------------------+-----------------------------------+
1468 | message | message_type |
1469 +-----------------------------------+-----------------------------------+
1470 | amount | price_type |
1471 +-----------------------------------+-----------------------------------+
1472 | item_ID | item_ID_type |
1473 +-----------------------------------+-----------------------------------+
1474 | assistant_ID | assistant_ID_type |
1475 +-----------------------------------+-----------------------------------+
1476 | quantity | quantity_type |
1477 +-----------------------------------+-----------------------------------+
1478 | branch_ID | branch_ID_type |
1479 +-----------------------------------+-----------------------------------+
1480 | notes | notes_type |
1481 +-----------------------------------+-----------------------------------+
1483 .. container:: paragraph
1485 This task also requires some 'Task Logic' to implement
1486 the new behaviour for this task.
1488 .. container:: paragraph
1490 For simplicity use the following code for the task logic.
1491 It again assumes that all items with ``item_ID`` between
1492 1000 and 2000 contain alcohol. We again use the standard
1493 ``Java`` time utilities to check if the current time is
1494 between ``00:00:00 CET`` and ``13:00:00 CET`` or if it is
1497 .. container:: paragraph
1499 For this task we will again author the logic using the
1500 ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__
1501 scripting language. Sample task logic code (specified in
1502 ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__) is
1503 given below. For a detailed guide to how to write your
1505 ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__,
1506 ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__ or one
1507 of the other supported languages please refer to APEX
1510 .. container:: listingblock
1512 .. container:: content
1517 * ============LICENSE_START=======================================================
1518 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
1519 * ================================================================================
1520 * Licensed under the Apache License, Version 2.0 (the "License");
1521 * you may not use this file except in compliance with the License.
1522 * You may obtain a copy of the License at
1524 * http://www.apache.org/licenses/LICENSE-2.0
1526 * Unless required by applicable law or agreed to in writing, software
1527 * distributed under the License is distributed on an "AS IS" BASIS,
1528 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1529 * See the License for the specific language governing permissions and
1530 * limitations under the License.
1532 * SPDX-License-Identifier: Apache-2.0
1533 * ============LICENSE_END=========================================================
1535 import java.util.Date;
1536 import java.util.Calendar;
1537 import java.util.TimeZone;
1538 import java.text.SimpleDateFormat;
1540 logger.info("Task Execution: '"+subject.id+"'. Input Event: '"+inFields+"'");
1542 outFields.put("amount" , inFields.get("amount"));
1543 outFields.put("assistant_ID", inFields.get("assistant_ID"));
1544 outFields.put("notes" , inFields.get("notes"));
1545 outFields.put("quantity" , inFields.get("quantity"));
1546 outFields.put("branch_ID" , inFields.get("branch_ID"));
1547 outFields.put("item_ID" , inFields.get("item_ID"));
1548 outFields.put("time" , inFields.get("time"));
1549 outFields.put("sale_ID" , inFields.get("sale_ID"));
1551 item_id = inFields.get("item_ID");
1553 //The events used later to test this task use CET timezone!
1554 cet = TimeZone.getTimeZone("CET");
1555 timenow = Calendar.getInstance(cet);
1556 df = new SimpleDateFormat("HH:mm:ss z");
1557 df.setTimeZone(cet);
1558 timenow.setTimeInMillis(inFields.get("time"));
1560 midnight = timenow.clone();
1562 timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
1563 timenow.get(Calendar.DATE),0,0,0);
1564 onepm = timenow.clone();
1566 timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
1567 timenow.get(Calendar.DATE),13,0,0);
1569 itemisalcohol = false;
1570 if(item_id != null && item_id >=1000 && item_id < 2000)
1571 itemisalcohol = true;
1573 if( itemisalcohol &&
1574 ( (timenow.after(midnight) && timenow.before(onepm))
1576 (timenow.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
1578 outFields.put("authorised", false);
1579 outFields.put("message", "Sale not authorised by policy task "+subject.taskName+
1580 " for time "+df.format(timenow.getTime())+
1581 ". Alcohol can not be sold between "+df.format(midnight.getTime())+
1582 " and "+df.format(onepm.getTime()) +" or on Sunday");
1586 outFields.put("authorised", true);
1587 outFields.put("message", "Sale authorised by policy task "+subject.taskName+
1588 " for time "+df.format(timenow.getTime()));
1593 This task checks if a sale request is for an item that is an alcoholic drink.
1594 If the local time is between 00:00:00 CET and 13:00:00 CET then the sale is not authorised.
1595 Also alcohol sales are not allowed on Sundays. Otherwise the sale is authorised.
1596 In this implementation we assume that items with item_ID between 1000 and 2000 are all alcoholic drinks :-)
1599 .. container:: imageblock
1601 .. container:: content
1603 |Create a new alternative task
1604 \`MorningBoozeCheckAlt1\`|
1606 .. container:: paragraph
1608 The task definition is now complete so click the 'Submit'
1609 button to save the task. Now that we have created our
1610 task, we can can add this task to the single pre-existing
1611 state (``BoozeAuthDecide``) in our policy.
1613 .. container:: paragraph
1615 To edit the ``BoozeAuthDecide`` state in our policy click
1616 on the 'Policies' tab. In the 'Policies' pane, right
1617 click on our ``MyFirstPolicy`` policy and select 'Edit'.
1618 Navigate to the ``BoozeAuthDecide`` state in the 'states'
1619 section at the bottom of the policy definition pane.
1621 .. container:: imageblock
1623 .. container:: content
1625 |Right click to edit a policy|
1627 .. container:: paragraph
1629 To add our new task ``MorningBoozeCheckAlt1``, scroll
1630 down to the ``BoozeAuthDecide`` state in the 'States'
1631 section. In the 'State Tasks' section for
1632 ``BoozeAuthDecide`` use the 'Add new task' button. Select
1633 our new ``MorningBoozeCheckAlt1`` task, and use the name
1634 of the task as the 'Local Name' for the task. The
1635 ``MorningBoozeCheckAlt1`` task can reuse the same
1636 ``MorningBoozeCheck_Output_Direct`` 'Direct State Output
1637 Mapping' that we used for the ``MorningBoozeCheck`` task.
1638 (Recall that the role of the 'State Output Mapping' is to
1639 select the output event for the state, and select the
1640 next state to be executed. These both remain the same as
1643 .. container:: paragraph
1645 Since our state has more than one task we must define
1646 some logic to determine which task should be used each
1647 time the state is executed. This *task selection logic*
1648 is defined in the state definition. For our
1649 ``BoozeAuthDecide`` state we want the choice of which
1650 task to use to be based on the ``branch_ID`` from which
1651 the ``SALE_INPUT`` event originated. For simplicity sake
1652 let us assume that branches with ``branch_ID`` between
1653 ``0`` and ``999`` should use the ``MorningBoozeCheck``
1654 task, and the branches with with ``branch_ID`` between
1655 ``1000`` and ``1999`` should use the
1656 ``MorningBoozeCheckAlt1`` task.
1658 .. container:: paragraph
1660 This time, for variety, we will author the task selection
1662 ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__
1663 scripting language. Sample task selection logic code
1665 ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__)
1666 is given below. Paste the script text into the 'Task
1667 Selection Logic' box, and use "JAVASCRIPT" as the 'Task
1668 Selection Logic Type / Flavour'. It is necessary to mark
1669 one of the tasks as the 'Default Task' so that the task
1670 selection logic always has a fallback default option in
1671 cases where a particular task cannot be selected. In this
1672 case the ``MorningBoozeCheck`` task can be the default
1675 .. container:: listingblock
1677 .. container:: content
1682 * ============LICENSE_START=======================================================
1683 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
1684 * ================================================================================
1685 * Licensed under the Apache License, Version 2.0 (the "License");
1686 * you may not use this file except in compliance with the License.
1687 * You may obtain a copy of the License at
1689 * http://www.apache.org/licenses/LICENSE-2.0
1691 * Unless required by applicable law or agreed to in writing, software
1692 * distributed under the License is distributed on an "AS IS" BASIS,
1693 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1694 * See the License for the specific language governing permissions and
1695 * limitations under the License.
1697 * SPDX-License-Identifier: Apache-2.0
1698 * ============LICENSE_END=========================================================
1702 var returnValueType = Java.type("java.lang.Boolean");
1703 var returnValue = new returnValueType(true);
1705 executor.logger.info("Task Selection Execution: '"+executor.subject.id+
1706 "'. Input Event: '"+executor.inFields+"'");
1708 branchid = executor.inFields.get("branch_ID");
1709 taskorig = executor.subject.getTaskKey("MorningBoozeCheck");
1710 taskalt = executor.subject.getTaskKey("MorningBoozeCheckAlt1");
1711 taskdef = executor.subject.getDefaultTaskKey();
1713 if(branchid >=0 && branchid <1000){
1714 taskorig.copyTo(executor.selectedTask);
1716 else if (branchid >=1000 && branchid <2000){
1717 taskalt.copyTo(executor.selectedTask);
1720 taskdef.copyTo(executor.selectedTask);
1724 This task selection logic selects task "MorningBoozeCheck" for branches with
1725 0<=branch_ID<1000 and selects task "MorningBoozeCheckAlt1" for branches with
1726 1000<=branch_ID<2000. Otherwise the default task is selected.
1727 In this case the default task is also "MorningBoozeCheck"
1730 .. container:: imageblock
1732 .. container:: content
1734 |State definition with 2 Tasks and Task Selection
1737 .. container:: paragraph
1739 When complete don’t forget to click the 'Submit' button
1740 at the bottom of 'Policies' pane for our
1741 ``MyFirstPolicy`` policy after updating the
1742 ``BoozeAuthDecide`` state.
1744 .. container:: paragraph
1746 Congratulations, you have now completed the second step
1747 towards your first APEX policy. The policy model
1748 containing our new policy can again be validated and
1749 exported from the editor and saved as shown in Step 1.
1751 .. container:: paragraph
1753 The exported policy model is then available in the
1754 directory you selected, as
1755 `MyFirstPolicyModel_0.0.1.json <files/mfp-files/2/MyFirstPolicyModel_0.0.1.json>`__.
1756 The exported policy can now be loaded into the APEX
1757 Policy Engine, or can be re-loaded and edited by the APEX
1763 .. container:: sectionbody
1765 .. container:: sect2
1767 .. rubric:: Test Policy Step 2
1768 :name: test_policy_step_2
1770 .. container:: paragraph
1772 To start a new APEX Engine you can use the following
1773 configuration. In a full APEX installation you can find
1774 this configuration in
1775 ``$APEX_HOME/examples/config/MyFirstPolicy/2/MyFirstPolicyConfigStdin2StdoutJsonEvent.json``.
1776 Note, this has changed from the configuration file in
1777 Step 1 to enable the ``JAVASCRIPT`` executor for our new
1778 'Task Selection Logic'.
1780 .. container:: listingblock
1782 .. container:: content
1787 "engineServiceParameters" : {
1788 "name" : "MyFirstPolicyApexEngine",
1789 "version" : "0.0.1",
1791 "instanceCount" : 4,
1792 "deploymentPort" : 12345,
1793 "policyModelFileName" : "examples/models/MyFirstPolicy/2/MyFirstPolicyModel_0.0.1.json",
1794 "engineParameters" : {
1795 "executorParameters" : {
1797 "parameterClassName" : "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters"
1800 "parameterClassName" : "org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters"
1805 "eventOutputParameters": {
1807 "carrierTechnologyParameters" : {
1808 "carrierTechnology" : "FILE",
1813 "eventProtocolParameters" : {
1814 "eventProtocol" : "JSON"
1818 "eventInputParameters": {
1820 "carrierTechnologyParameters" : {
1821 "carrierTechnology" : "FILE",
1826 "eventProtocolParameters" : {
1827 "eventProtocol" : "JSON"
1833 .. container:: paragraph
1835 To test the policy try paste the following events into
1836 the console as the APEX engine executes. Note, all tests
1837 from Step 1 will still work perfectly since none of those
1838 events originate from a branch with ``branch_ID`` between
1839 ``1000`` and ``2000``. The 'Task Selection Logic' will
1840 therefore pick the ``MorningBoozeCheck`` task as
1841 expected, and will therefore give the same results.
1843 .. list-table:: Table 1. Inputs and Outputs when testing *My First Policy*
1847 * - Input Event (JSON)
1848 - Output Event (JSON)
1850 * - .. literalinclude:: events/1/EventIn_BoozeItem_084106GMT.json
1852 - .. literalinclude:: events/1/EventOut_BoozeItem_084106GMT.json
1854 - .. container:: paragraph
1856 Request to buy alcohol item (`item_ID=1249`) at _08:41:06 GMT_ on _Monday, 02 January 2017_.
1857 Sale is not authorized. Uses the `MorningBoozeCheck` task.
1859 * - .. literalinclude:: events/2/EventIn_BoozeItem_101433CET_thurs.json
1861 - .. literalinclude:: events/2/EventOut_BoozeItem_101433CET_thurs.json
1863 - .. container:: paragraph
1865 Request to buy alcohol (`item_ID=1047`) at _10:14:33_ on _Thursday, 22 December 2016_.
1866 Sale is not authorized. Uses the `MorningBoozeCheckAlt1` task.
1868 * - .. literalinclude:: events/2/EventIn_BoozeItem_171937CET_sun.json
1870 - .. literalinclude:: events/2/EventOut_BoozeItem_171937CET_sun.json
1872 - .. container:: paragraph
1874 Request to buy alcohol (`item_ID=1443`) at _17:19:37_ on _Sunday, 18 December 2016_.
1875 Sale is not authorized. Uses the `MorningBoozeCheckAlt1` task.
1877 * - .. literalinclude:: events/2/EventIn_NonBoozeItem_111309CET_mon.json
1879 - .. literalinclude:: events/2/EventOut_NonBoozeItem_111309CET_mon.json
1881 - .. container:: paragraph
1883 Request to buy non-alcoholic item (`item_ID=5321`) at _11:13:09_ on _Monday, 2 January 2017_.
1884 Sale is authorized. Uses the `MorningBoozeCheckAlt1` task.
1889 .. container:: sectionbody
1891 .. container:: sect2
1893 .. rubric:: Policy 2 in CLI Editor
1894 :name: policy_2_in_cli_editor
1896 .. container:: paragraph
1898 An equivalent version of the ``MyFirstPolicyModel``
1899 policy model can again be generated using the APEX CLI
1900 editor. A sample APEX CLI script is shown below:
1902 .. container:: listingblock
1904 .. container:: content
1908 #-------------------------------------------------------------------------------
1909 # ============LICENSE_START=======================================================
1910 # Copyright (C) 2016-2018 Ericsson. All rights reserved.
1911 # ================================================================================
1912 # Licensed under the Apache License, Version 2.0 (the "License");
1913 # you may not use this file except in compliance with the License.
1914 # You may obtain a copy of the License at
1916 # http://www.apache.org/licenses/LICENSE-2.0
1918 # Unless required by applicable law or agreed to in writing, software
1919 # distributed under the License is distributed on an "AS IS" BASIS,
1920 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1921 # See the License for the specific language governing permissions and
1922 # limitations under the License.
1924 # SPDX-License-Identifier: Apache-2.0
1925 # ============LICENSE_END=========================================================
1926 #-------------------------------------------------------------------------------
1928 model create name=MyFirstPolicyModel version=0.0.1 uuid=540226fb-55ee-4f0e-a444-983a0494818e description="This is my first Apex Policy Model."
1930 schema create name=assistant_ID_type version=0.0.1 uuid=36df4c71-9616-4206-8b53-976a5cd4bd87 description="A type for 'assistant_ID' values" flavour=Java schema=java.lang.Long
1932 schema create name=authorised_type version=0.0.1 uuid=d48b619e-d00d-4008-b884-02d76ea4350b description="A type for 'authorised' values" flavour=Java schema=java.lang.Boolean
1934 schema create name=branch_ID_type version=0.0.1 uuid=6468845f-4122-4128-8e49-0f52c26078b5 description="A type for 'branch_ID' values" flavour=Java schema=java.lang.Long
1936 schema create name=item_ID_type version=0.0.1 uuid=4f227ff1-aee0-453a-b6b6-9a4b2e0da932 description="A type for 'item_ID' values" flavour=Java schema=java.lang.Long
1938 schema create name=message_type version=0.0.1 uuid=ad1431bb-3155-4e73-b5a3-b89bee498749 description="A type for 'message' values" flavour=Java schema=java.lang.String
1940 schema create name=notes_type version=0.0.1 uuid=eecfde90-896c-4343-8f9c-2603ced94e2d description="A type for 'notes' values" flavour=Java schema=java.lang.String
1942 schema create name=price_type version=0.0.1 uuid=52c2fc45-fd8c-463c-bd6f-d91b0554aea7 description="A type for 'amount'/'price' values" flavour=Java schema=java.lang.Long
1944 schema create name=quantity_type version=0.0.1 uuid=ac3d9842-80af-4a98-951c-bd79a431c613 description="A type for 'quantity' values" flavour=Java schema=java.lang.Integer
1946 schema create name=sale_ID_type version=0.0.1 uuid=cca47d74-7754-4a61-b163-ca31f66b157b description="A type for 'sale_ID' values" flavour=Java schema=java.lang.Long
1948 schema create name=timestamp_type version=0.0.1 uuid=fd594e88-411d-4a94-b2be-697b3a0d7adf description="A type for 'time' values" flavour=Java schema=java.lang.Long
1950 task create name=MorningBoozeCheck version=0.0.1 uuid=3351b0f4-cf06-4fa2-8823-edf67bd30223 description=LS
1951 This task checks if the sales request is for an item that contains alcohol.
1952 If the local time is between 00:00:00 and 11:30:00 then the sale is not authorised. Otherwise the sale is authorised.
1953 In this implementation we assume that all items with item_ID values between 1000 and 2000 contain alcohol :-)
1955 task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
1956 task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=amount schemaName=price_type schemaVersion=0.0.1
1957 task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
1958 task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
1959 task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=quantity schemaName=quantity_type schemaVersion=0.0.1
1960 task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
1961 task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
1962 task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=time schemaName=timestamp_type schemaVersion=0.0.1
1963 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
1964 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=amount schemaName=price_type schemaVersion=0.0.1
1965 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
1966 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
1967 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=quantity schemaName=quantity_type schemaVersion=0.0.1
1968 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
1969 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
1970 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=authorised schemaName=authorised_type schemaVersion=0.0.1
1971 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=time schemaName=timestamp_type schemaVersion=0.0.1
1972 task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=message schemaName=message_type schemaVersion=0.0.1 optional=true
1973 task logic create name=MorningBoozeCheck version=0.0.1 logicFlavour=MVEL logic=LS
1975 * ============LICENSE_START=======================================================
1976 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
1977 * ================================================================================
1978 * Licensed under the Apache License, Version 2.0 (the "License");
1979 * you may not use this file except in compliance with the License.
1980 * You may obtain a copy of the License at
1982 * http://www.apache.org/licenses/LICENSE-2.0
1984 * Unless required by applicable law or agreed to in writing, software
1985 * distributed under the License is distributed on an "AS IS" BASIS,
1986 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1987 * See the License for the specific language governing permissions and
1988 * limitations under the License.
1990 * SPDX-License-Identifier: Apache-2.0
1991 * ============LICENSE_END=========================================================
1993 import java.util.Date;
1994 import java.util.Calendar;
1995 import java.util.TimeZone;
1996 import java.text.SimpleDateFormat;
1998 logger.info("Task Execution: '"+subject.id+"'. Input Fields: '"+inFields+"'");
2000 outFields.put("amount" , inFields.get("amount"));
2001 outFields.put("assistant_ID", inFields.get("assistant_ID"));
2002 outFields.put("notes" , inFields.get("notes"));
2003 outFields.put("quantity" , inFields.get("quantity"));
2004 outFields.put("branch_ID" , inFields.get("branch_ID"));
2005 outFields.put("item_ID" , inFields.get("item_ID"));
2006 outFields.put("time" , inFields.get("time"));
2007 outFields.put("sale_ID" , inFields.get("sale_ID"));
2009 item_id = inFields.get("item_ID");
2011 //The events used later to test this task use GMT timezone!
2012 gmt = TimeZone.getTimeZone("GMT");
2013 timenow = Calendar.getInstance(gmt);
2014 df = new SimpleDateFormat("HH:mm:ss z");
2015 df.setTimeZone(gmt);
2016 timenow.setTimeInMillis(inFields.get("time"));
2018 midnight = timenow.clone();
2020 timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
2021 timenow.get(Calendar.DATE),0,0,0);
2022 eleven30 = timenow.clone();
2024 timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
2025 timenow.get(Calendar.DATE),11,30,0);
2027 itemisalcohol = false;
2028 if(item_id != null && item_id >=1000 && item_id < 2000)
2029 itemisalcohol = true;
2032 && timenow.after(midnight) && timenow.before(eleven30)){
2033 outFields.put("authorised", false);
2034 outFields.put("message", "Sale not authorised by policy task "+subject.taskName+
2035 " for time "+df.format(timenow.getTime())+
2036 ". Alcohol can not be sold between "+df.format(midnight.getTime())+
2037 " and "+df.format(eleven30.getTime()));
2041 outFields.put("authorised", true);
2042 outFields.put("message", "Sale authorised by policy task "+subject.taskName+
2043 " for time "+df.format(timenow.getTime()));
2048 This task checks if a sale request is for an item that is an alcoholic drink.
2049 If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
2050 authorised. Otherwise the sale is authorised.
2051 In this implementation we assume that items with item_ID value between 1000 and
2052 2000 are all alcoholic drinks :-)
2056 task create name=MorningBoozeCheckAlt1 version=0.0.1 uuid=bc6d90c9-c902-4686-afd3-925b30e39990 description=LS
2057 This task checks if a sale request is for an item that is an alcoholic drink.
2058 If the local time is between 00:00:00 CET and 13:00:00 CET then the sale is not authorised.
2059 Also alcohol sales are not allowed on Sundays. Otherwise the sale is authorised.
2060 In this implementation we assume that items with item_ID between 1000 and 2000 are all alcoholic drinks
2062 task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
2063 task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=amount schemaName=price_type schemaVersion=0.0.1
2064 task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
2065 task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
2066 task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=quantity schemaName=quantity_type schemaVersion=0.0.1
2067 task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
2068 task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
2069 task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=time schemaName=timestamp_type schemaVersion=0.0.1
2070 task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
2071 task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=amount schemaName=price_type schemaVersion=0.0.1
2072 task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
2073 task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
2074 task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=quantity schemaName=quantity_type schemaVersion=0.0.1
2075 task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
2076 task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
2077 task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=authorised schemaName=authorised_type schemaVersion=0.0.1
2078 task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=time schemaName=timestamp_type schemaVersion=0.0.1
2079 task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=message schemaName=message_type schemaVersion=0.0.1 optional=true
2080 task logic create name=MorningBoozeCheckAlt1 version=0.0.1 logicFlavour=MVEL logic=LS
2082 * ============LICENSE_START=======================================================
2083 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
2084 * ================================================================================
2085 * Licensed under the Apache License, Version 2.0 (the "License");
2086 * you may not use this file except in compliance with the License.
2087 * You may obtain a copy of the License at
2089 * http://www.apache.org/licenses/LICENSE-2.0
2091 * Unless required by applicable law or agreed to in writing, software
2092 * distributed under the License is distributed on an "AS IS" BASIS,
2093 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2094 * See the License for the specific language governing permissions and
2095 * limitations under the License.
2097 * SPDX-License-Identifier: Apache-2.0
2098 * ============LICENSE_END=========================================================
2100 import java.util.Date;
2101 import java.util.Calendar;
2102 import java.util.TimeZone;
2103 import java.text.SimpleDateFormat;
2105 logger.info("Task Execution: '"+subject.id+"'. Input Event: '"+inFields+"'");
2107 outFields.put("amount" , inFields.get("amount"));
2108 outFields.put("assistant_ID", inFields.get("assistant_ID"));
2109 outFields.put("notes" , inFields.get("notes"));
2110 outFields.put("quantity" , inFields.get("quantity"));
2111 outFields.put("branch_ID" , inFields.get("branch_ID"));
2112 outFields.put("item_ID" , inFields.get("item_ID"));
2113 outFields.put("time" , inFields.get("time"));
2114 outFields.put("sale_ID" , inFields.get("sale_ID"));
2116 item_id = inFields.get("item_ID");
2118 //The events used later to test this task use CET timezone!
2119 cet = TimeZone.getTimeZone("CET");
2120 timenow = Calendar.getInstance(cet);
2121 df = new SimpleDateFormat("HH:mm:ss z");
2122 df.setTimeZone(cet);
2123 timenow.setTimeInMillis(inFields.get("time"));
2125 midnight = timenow.clone();
2127 timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
2128 timenow.get(Calendar.DATE),0,0,0);
2129 onepm = timenow.clone();
2131 timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
2132 timenow.get(Calendar.DATE),13,0,0);
2134 itemisalcohol = false;
2135 if(item_id != null && item_id >=1000 && item_id < 2000)
2136 itemisalcohol = true;
2138 if( itemisalcohol &&
2139 ( (timenow.after(midnight) && timenow.before(onepm))
2141 (timenow.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
2143 outFields.put("authorised", false);
2144 outFields.put("message", "Sale not authorised by policy task "+subject.taskName+
2145 " for time "+df.format(timenow.getTime())+
2146 ". Alcohol can not be sold between "+df.format(midnight.getTime())+
2147 " and "+df.format(onepm.getTime()) +" or on Sunday");
2151 outFields.put("authorised", true);
2152 outFields.put("message", "Sale authorised by policy task "+subject.taskName+
2153 " for time "+df.format(timenow.getTime()));
2158 This task checks if a sale request is for an item that is an alcoholic drink.
2159 If the local time is between 00:00:00 CET and 13:00:00 CET then the sale is not authorised.
2160 Also alcohol sales are not allowed on Sundays. Otherwise the sale is authorised.
2161 In this implementation we assume that items with item_ID between 1000 and 2000 are all alcoholic drinks :-)
2165 event create name=SALE_AUTH version=0.0.1 uuid=c4500941-3f98-4080-a9cc-5b9753ed050b description="An event emitted by the Policy to indicate whether the sale of an item has been authorised" nameSpace=com.hyperm source="APEX" target="POS"
2166 event parameter create name=SALE_AUTH version=0.0.1 parName=amount schemaName=price_type schemaVersion=0.0.1
2167 event parameter create name=SALE_AUTH version=0.0.1 parName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
2168 event parameter create name=SALE_AUTH version=0.0.1 parName=authorised schemaName=authorised_type schemaVersion=0.0.1
2169 event parameter create name=SALE_AUTH version=0.0.1 parName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
2170 event parameter create name=SALE_AUTH version=0.0.1 parName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
2171 event parameter create name=SALE_AUTH version=0.0.1 parName=message schemaName=message_type schemaVersion=0.0.1 optional=true
2172 event parameter create name=SALE_AUTH version=0.0.1 parName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
2173 event parameter create name=SALE_AUTH version=0.0.1 parName=quantity schemaName=quantity_type schemaVersion=0.0.1
2174 event parameter create name=SALE_AUTH version=0.0.1 parName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
2175 event parameter create name=SALE_AUTH version=0.0.1 parName=time schemaName=timestamp_type schemaVersion=0.0.1
2177 event create name=SALE_INPUT version=0.0.1 uuid=4f04aa98-e917-4f4a-882a-c75ba5a99374 description="An event raised by the PoS system each time an item is scanned for purchase" nameSpace=com.hyperm source="POS" target="APEX"
2178 event parameter create name=SALE_INPUT version=0.0.1 parName=amount schemaName=price_type schemaVersion=0.0.1
2179 event parameter create name=SALE_INPUT version=0.0.1 parName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
2180 event parameter create name=SALE_INPUT version=0.0.1 parName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
2181 event parameter create name=SALE_INPUT version=0.0.1 parName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
2182 event parameter create name=SALE_INPUT version=0.0.1 parName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
2183 event parameter create name=SALE_INPUT version=0.0.1 parName=quantity schemaName=quantity_type schemaVersion=0.0.1
2184 event parameter create name=SALE_INPUT version=0.0.1 parName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
2185 event parameter create name=SALE_INPUT version=0.0.1 parName=time schemaName=timestamp_type schemaVersion=0.0.1
2188 policy create name=MyFirstPolicy version=0.0.1 uuid=6c5e410f-489a-46ff-964e-982ce6e8b6d0 description="This is my first Apex policy. It checks if a sale should be authorised or not." template=FREEFORM firstState=BoozeAuthDecide
2189 policy state create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide triggerName=SALE_INPUT triggerVersion=0.0.1 defaultTaskName=MorningBoozeCheck defaultTaskVersion=0.0.1
2190 policy state output create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide outputName=MorningBoozeCheck_Output_Direct eventName=SALE_AUTH eventVersion=0.0.1 nextState=NULL
2191 policy state taskref create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide taskLocalName=MorningBoozeCheckAlt1 taskName=MorningBoozeCheckAlt1 taskVersion=0.0.1 outputType=DIRECT outputName=MorningBoozeCheck_Output_Direct
2192 policy state taskref create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide taskLocalName=MorningBoozeCheck taskName=MorningBoozeCheck taskVersion=0.0.1 outputType=DIRECT outputName=MorningBoozeCheck_Output_Direct
2193 policy state selecttasklogic create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide logicFlavour=JAVASCRIPT logic=LS
2195 * ============LICENSE_START=======================================================
2196 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
2197 * ================================================================================
2198 * Licensed under the Apache License, Version 2.0 (the "License");
2199 * you may not use this file except in compliance with the License.
2200 * You may obtain a copy of the License at
2202 * http://www.apache.org/licenses/LICENSE-2.0
2204 * Unless required by applicable law or agreed to in writing, software
2205 * distributed under the License is distributed on an "AS IS" BASIS,
2206 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2207 * See the License for the specific language governing permissions and
2208 * limitations under the License.
2210 * SPDX-License-Identifier: Apache-2.0
2211 * ============LICENSE_END=========================================================
2214 var returnValueType = Java.type("java.lang.Boolean");
2215 var returnValue = new returnValueType(true);
2217 executor.logger.info("Task Selection Execution: '"+executor.subject.id+"'. Input Event: '"+executor.inFields+"'");
2219 branchid = executor.inFields.get("branch_ID");
2220 taskorig = executor.subject.getTaskKey("MorningBoozeCheck");
2221 taskalt = executor.subject.getTaskKey("MorningBoozeCheckAlt1");
2222 taskdef = executor.subject.getDefaultTaskKey();
2224 if(branchid >=0 && branchid <1000){
2225 taskorig.copyTo(executor.selectedTask);
2227 else if (branchid >=1000 && branchid <2000){
2228 taskalt.copyTo(executor.selectedTask);
2231 taskdef.copyTo(executor.selectedTask);
2235 This task selection logic selects task "MorningBoozeCheck" for branches with 0<=branch_ID<1000 and selects task "MorningBoozeCheckAlt1" for branches with 1000<=branch_ID<2000. Otherwise the default task is selected. In this case the default task is also "MorningBoozeCheck"
2244 Last updated 2020-04-03 16:04:24 IST
2246 .. |File > New to create a new Policy Model| image:: images/mfp/MyFirstPolicy_P1_newPolicyModel1.png
2247 .. |Create a new Policy Model| image:: images/mfp/MyFirstPolicy_P1_newPolicyModel2.png
2248 .. |ONAP| image:: ../../../images/logos.png
2250 :target: http://www.onap.org/
2251 .. |Right click to create a new event| image:: images/mfp/MyFirstPolicy_P1_newEvent1.png
2252 .. |Fill in the necessary information for the 'SALE_INPUT' event and click 'Submit'| image:: images/mfp/MyFirstPolicy_P1_newEvent2.png
2253 .. |Right click to create a new Item Schema| image:: images/mfp/MyFirstPolicy_P1_newItemSchema1.png
2254 .. |Create a new Item Schema| image:: images/mfp/MyFirstPolicy_P1_newItemSchema2.png
2255 .. |Add new event parameters to an event| image:: images/mfp/MyFirstPolicy_P1_newEvent3.png
2256 .. |Right click to create a new task| image:: images/mfp/MyFirstPolicy_P1_newTask1.png
2257 .. |Add input and out fields for the task| image:: images/mfp/MyFirstPolicy_P1_newTask2.png
2258 .. |Add task logic the task| image:: images/mfp/MyFirstPolicy_P1_newTask3.png
2259 .. |Create a new policy| image:: images/mfp/MyFirstPolicy_P1_newPolicy1.png
2260 .. |Create a state| image:: images/mfp/MyFirstPolicy_P1_newState1.png
2261 .. |Add a Task and Output Mapping| image:: images/mfp/MyFirstPolicy_P1_newState2.png
2262 .. |Validate the policy model for error using the 'Model' > 'Validate' menu item| image:: images/mfp/MyFirstPolicy_P1_validatePolicyModel.png
2263 .. |Download the completed policy model using the 'File' > 'Download' menu item| image:: images/mfp/MyFirstPolicy_P1_exportPolicyModel1.png
2264 .. |Create a new alternative task \`MorningBoozeCheckAlt1\`| image:: images/mfp/MyFirstPolicy_P2_newTask1.png
2265 .. |Right click to edit a policy| image:: images/mfp/MyFirstPolicy_P2_editPolicy1.png
2266 .. |State definition with 2 Tasks and Task Selection Logic| image:: images/mfp/MyFirstPolicy_P2_editState1.png