f76ed138af500121dbc3567d6dd42056833c3b8b
[policy/parent.git] / docs / apex / APEX-Policy-Guide.rst
1 .. This work is licensed under a Creative Commons Attribution 4.0 International License.
2 .. http://creativecommons.org/licenses/by/4.0
3
4
5 APEX Policy Guide
6 *****************************
7
8 .. contents::
9     :depth: 3
10
11 APEX Policy Matrix
12 ^^^^^^^^^^^^^^^^^^
13
14 APEX Policy Matrix
15 ------------------
16
17             .. container:: paragraph
18
19                APEX offers a lot of flexibility for defining, deploying,
20                and executing policies. Based on a theoretic model, it
21                supports virtually any policy model and supports
22                translation of legacy policies into the APEX execution format.
23                However, the most important aspect for using APEX is to
24                decide what policy is needed, what underlying policy
25                concepts should be used, and how the decision logic
26                should be realized. Once these aspects are decided, APEX
27                can be used to execute the policies. If the policy
28                evolves, say from a simple decision table to a fully
29                adaptable policy, only the policy definition requires
30                change. APEX supports all of that.
31
32             .. container:: paragraph
33
34                The figure below shows a (non-exhaustive) matrix, which
35                will help to decide what policy is required to solve your
36                problem. Read the matrix from left to right choosing one
37                cell in each column.
38
39             .. container:: imageblock
40
41                .. container:: content
42
43                   |APEX Policy Matrix|
44
45                .. container:: title
46
47                   Figure 1. APEX Policy Matrix
48
49             .. container:: paragraph
50
51                The policy can support one of a number of stimuli with an
52                associated purpose/model of the policy, for instance:
53
54             .. container:: ulist
55
56                -  Configuration, i.e. what should happen. An example is
57                   an event that states an intended network configuration
58                   and the policy should provide the detailed actions for
59                   it. The policy can be realized for instance as an
60                   obligation policy, a promise or an intent.
61
62                -  Report, i.e. something did happen. An example is an
63                   event about an error or fault and the policy needs to
64                   repair that problem. The policy would usually be an
65                   obligation, utility function, or goal policy.
66
67                -  Monitoring, i.e. something does happen. An example is
68                   a notification about certain network conditions, to
69                   which the policy might (or might not) react. The
70                   policy will mitigate the monitored events or permit
71                   (deny) related actions as an obligation or
72                   authorization.
73
74                -  Analysis, i.e. why did something happen. An example is
75                   an analytic component sends insights of a situation
76                   requiring a policy to act on it. The policy can solve
77                   the problem, escalate it, or delegate it as a refrain
78                   or delegation policy.
79
80                -  Prediction, i.e. what will happen next. An example are
81                   events that a policy uses to predict a future network
82                   condition. The policy can prevent or enforce the
83                   prediction as an adaptive policy, a utility function,
84                   or a goal.
85
86                -  Feedback, i.e. why did something happen or not happen.
87                   Similar to analysis, but here the feedback will be in
88                   the input event and the policy needs to something with
89                   that information. Feedback can be related to history
90                   or experience, for instance a previous policy
91                   execution. The policy needs to be context-aware or be
92                   a meta-policy.
93
94             .. container:: paragraph
95
96                Once the purpose of the policy is decided, the next step
97                is to look into what context information the policy will
98                require to do its job. This can range from very simple to
99                a lot of different information, for instance:
100
101             .. container:: ulist
102
103                -  No context, nothing but a trigger event, e.g. a string
104                   or a number, is required
105
106                -  Event context, the incoming event provides all
107                   information (more than a string or number) for the
108                   policy
109
110                -  Policy context (read only), the policy has access to
111                   additional information related to its class but cannot
112                   change/alter them
113
114                -  Policy context (read and write), the policy has access
115                   to additional information related to its class and can
116                   alter this information (for instance to record
117                   historic information)
118
119                -  Global context (read only), the policy has access to
120                   additional information of any kind but cannot
121                   change/alter them
122
123                -  Global context (read and write), the policy the policy
124                   has access to additional information of any kind and
125                   can alter this information (for instance to record
126                   historic information)
127
128             .. container:: paragraph
129
130                The next step is to decide how the policy should do its
131                job, i.e. what flavor it has, how many states are needed,
132                and how many tasks. There are many possible combinations,
133                for instance:
134
135             .. container:: ulist
136
137                -  Simple / God: a simple policy with 1 state and 1 task,
138                   which is doing everything for the decision-making.
139                   This is the ideal policy for simple situation, e.g.
140                   deciding on configuration parameters or simple access
141                   control.
142
143                -  Simple sequence: a simple policy with a number of
144                   states each having a single task. This is a very good
145                   policy for simple decision-making with different
146                   steps. For instance, a classic action policy (ECA)
147                   would have 3 states (E, C, and A) with some logic (1
148                   task) in each state.
149
150                -  Simple selective: a policy with 1 state but more than
151                   one task. Here, the appropriate task (and it’s logic)
152                   will be selected at execution time. This policy is
153                   very good for dealing with similar (or the same)
154                   situation in different contexts. For instance, the
155                   tasks can be related to available external software,
156                   or to current work load on the compute node, or to
157                   time of day.
158
159                -  Selective: any number of states having any number of
160                   tasks (usually more than 1 task). This is a
161                   combination of the two policies above, for instance an
162                   ECA policy with more than one task in E, C, and A.
163
164                -  Classic directed: a policy with more than one state,
165                   each having one task, but a non-sequential execution.
166                   This means that the sequence of the states is not
167                   pre-defined in the policy (as would be for all cases
168                   above) but calculated at runtime. This can be good to
169                   realize decision trees based on contextual
170                   information.
171
172                -  Super Adaptive: using the full potential of the APEX
173                   policy model, states and tasks and state execution are
174                   fully flexible and calculated at runtime (per policy
175                   execution). This policy is very close to a general
176                   programming system (with only a few limitations), but
177                   can solve very hard problems.
178
179             .. container:: paragraph
180
181                The final step is to select a response that the policy
182                creates. Possible responses have been discussed in the
183                literature for a very long time. A few examples are:
184
185             .. container:: ulist
186
187                -  Obligation (deontic for what should happen)
188
189                -  Authorization (e.g. for rule-based or other access
190                   control or security systems)
191
192                -  Intent (instead of providing detailed actions the
193                   response is an intent statement and a further system
194                   processes that)
195
196                -  Delegation (hand the problem over to someone else,
197                   possibly with some information or instructions)
198
199                -  Fail / Error (the policy has encountered a problem,
200                   and reports it)
201
202                -  Feedback (why did the policy make a certain decision)
203
204 APEX Policy Model
205 ^^^^^^^^^^^^^^^^^
206
207 Introduction
208 ------------
209
210             .. container:: paragraph
211
212                The APEX policy model is shown in UML notation in the
213                figure below. A policy model can be stored in JSON or XML
214                format in a file or can be held in a database. The APEX
215                editor creates and modifies APEX policy models. APEX
216                deployment deploys policy models, and a policy model is
217                loaded into APEX engines so that the engines can run the
218                policies in the policy model.
219
220             .. container:: paragraph
221
222                The figure shows four different views of the policy
223                model:
224
225             .. container:: ulist
226
227                -  The general model view shows the main parts of a
228                   policy: state, state output, event, and task. A task
229                   can also have parameters. Data types can be defined on
230                   a per-model basis using either standard atomic types
231                   (such as character, string, numbers) or complex types
232                   from a policy domain.
233
234                -  The logic model view emphasizes how decision-making
235                   logic is injected into a policy. There are essentially
236                   three different types of logic: task logic (for
237                   decision making in a task), task selection logic (to
238                   select a task if more than one is defined in a state),
239                   and state finalizer logic (to compute the final output
240                   event of a state and select an appropriate next state
241                   from the policy model).
242
243                -  The context model view shows how context is injected
244                   into a policy. States collect all context from their
245                   tasks. A task can define what context it requires for
246                   the decision making, i.e. what context the task logic
247                   will process. Context itself is a collection of items
248                   (individual context information) with data types.
249                   Context can be templated.
250
251                -  The event and field model view shows the events in the
252                   policy model. Tasks define what information they
253                   consume (input) and produce (output). This information
254                   is modeled as fields, essentially a key/type tuple in
255                   the model and a key/type/value triple at execution.
256                   Events then are collection of fields.
257
258             .. container:: imageblock
259
260                .. container:: content
261
262                   |APEX Policy Model for Execution|
263
264                .. container:: title
265
266                   Figure 2. APEX Policy Model for Execution
267
268 Concepts and Keys
269 #################
270
271                .. container:: paragraph
272
273                   Each element of the policy model is called a
274                   *concept*. Each *concept* is a subclass of the
275                   abstract *Concept* class, as shown in the next figure.
276                   Every concept implements the following abstract
277                   methods:
278
279                .. container:: imageblock
280
281                   .. container:: content
282
283                      |Concepts and Keys|
284
285                   .. container:: title
286
287                      Figure 3. Concepts and Keys
288
289                .. container:: ulist
290
291                   -  ``getKey()`` - gets the unique key for this concept
292                      instance in the system
293
294                   -  ``validate()`` - validates the structure of this
295                      concept, its sub-concepts and its relationships
296
297                   -  ``clean()`` - carries out housekeeping on the
298                      concept such as trimming strings, remove any
299                      hanging references
300
301                   -  ``clone()`` - creates a deep copy of an instance of
302                      this concept
303
304                   -  ``equals()`` - checks if two instances of this
305                      concept are equal
306
307                   -  ``toString()`` - returns a string representation of
308                      the concept
309
310                   -  ``hashCode()`` - returns a hash code for the
311                      concept
312
313                   -  ``copyTo()`` - carries out a deep copy of one
314                      instance of the concept to another instance,
315                      overwriting the target fields.
316
317                .. container:: paragraph
318
319                   All concepts must have a *key*, which uniquely
320                   identifies a concept instance. The *key* of a subclass
321                   of an *Concept* must either be an ``ArtifactKey`` or
322                   an ``ReferenceKey``. Concepts that have a stand-alone
323                   independent existence such as *Policy*, *Task*, and
324                   *Event* must have an ``ArtifctKey`` key. Concepts that
325                   are contained in other concepts, that do not exist as
326                   stand-alone concepts must have an ``ReferenceKey``
327                   key. Examples of such concepts are *State* and
328                   *EventParameter*.
329
330                .. container:: paragraph
331
332                   An ``ArticactKey`` has two fields; the *Name* of the
333                   concept it is the key for and the concept’s *Version*.
334                   A concept’s name must be unique in a given
335                   PolicyModel. A concept version is represented using
336                   the well known *major.minor.path* scheme as used in
337                   semantic versioning.
338
339                .. container:: paragraph
340
341                   A ``ReferenceKey`` has three fields. The *UserKeyName*
342                   and *UserKeyVersion* fields identify the
343                   ``ArtifactKey`` of the concept in which the concept
344                   keyed by the ``ReferenceKey`` is contained. The
345                   *LocalName* field identifies the contained concept
346                   instance. The *LocalName* must be unique in the
347                   concepts of a given type contained by a parent.
348
349                .. container:: paragraph
350
351                   For example, a policy called ``SalesPolicy`` with a
352                   Version of ``1.12.4`` has a state called ``Decide``.
353                   The ``Decide`` state is linked to the ``SalesPolicy``
354                   with a ``ReferenceKey`` with fields *UserKeyName* of
355                   ``SalesPolicy``, *UserKeyVersion* of ``1.12.4``, and
356                   *LocalName* of ``Decide``. There must not be another
357                   state called ``Decide`` in the policy ``SalesPolicy``.
358                   However, there may well be a state called ``Decide``
359                   in some other policy called ``PurchasingPolicy``.
360
361                .. container:: paragraph
362
363                   Each concept in the model is also a JPA (`Java
364                   Persistence
365                   API <https://en.wikipedia.org/wiki/Java_Persistence_API>`__)
366                   Entity. This means that every concept can be
367                   individually persisted or the entire model can be
368                   persisted en-bloc to any persistence mechanism using
369                   an JPA framework such as
370                   `Hibernate <http://hibernate.org/>`__ or
371                   `EclipseLink <http://www.eclipse.org/eclipselink/>`__.
372
373 Concept: PolicyModel
374 ####################
375
376                .. container:: paragraph
377
378                   The *PolicyModel* concept is a container that holds
379                   the definition of a set of policies and their
380                   associated events, context maps, and tasks. A
381                   *PolicyModel* is implemented as four maps for
382                   policies, events, context maps, and tasks. Each map is
383                   indexed by the key of the policy, event, context map,
384                   or task. Any non-empty policy model must have at least
385                   one entry in its policy, event, and task map because
386                   all policies must have at least one input and output
387                   event and must execute at least one task.
388
389                .. container:: paragraph
390
391                   A *PolicyModel* concept is keyed with an
392                   ``ArtifactKey key``. Because a *PolicyModel* is an
393                   ``AxConcept``, calling the ``validate()`` method on a
394                   policy model validates the concepts, structure, and
395                   relationships of the entire policy model.
396
397 Concept: DataType
398 #################
399
400                .. container:: paragraph
401
402                   Data types are tightly controlled in APEX in order to
403                   provide a very high degree of consistency in policies
404                   and to facilitate tracking of changes to context as
405                   policies execute. All context is modeled as a
406                   *DataType* concept. Each DataType concept instance is
407                   keyed with an ``ArtifactKey`` key. The DataType field
408                   identifies the Java class of objects that is used to
409                   represent concept instances that use this data type.
410                   All context has a *DataType*; incoming and outgoing
411                   context is represented by *EventField* concepts and
412                   all other context is represented by *ContextItem*
413                   concepts.
414
415 Concept: Event
416 ##############
417
418                .. container:: paragraph
419
420                   An *Event* defines the structure of a message that
421                   passes into or out of an APEX engine or that passes
422                   between two states in an APEX engine. APEX supports
423                   message reception and sending in many formats and all
424                   messages are translated into an *Event* prior to
425                   processing by an APEX engine. Event concepts are keyed
426                   with an ``ArtifactKey`` key. The parameters of an
427                   event are held as a map of *EventField* concept
428                   instances with each parameter indexed by the
429                   *LocalName* of its ``ReferenceKey``. An *Event* has
430                   three fields:
431
432                .. container:: ulist
433
434                   -  The *NameSpace* identifies the domain of
435                      application of the event
436
437                   -  The *Source* of the event identifies the system
438                      that emitted the event
439
440                   -  The *Target* of the event identifies the system
441                      that the event was sent to
442
443                .. container:: paragraph
444
445                   A *PolicyModel* contains a map of all the events known
446                   to a given policy model. Although an empty model may
447                   have no events in its event map, any sane policy model
448                   must have at least one *Event* defined.
449
450 Concept: EventField
451 ###################
452
453                .. container:: paragraph
454
455                   The incoming context and outgoing context of an event
456                   are the fields of the event. Each field representing a
457                   single piece of incoming or outgoing context. Each
458                   field of an *Event* is represented by an instance of
459                   the *EventField* concept. Each *EventField* concept
460                   instance in an event is keyed with a ``ReferenceKey``
461                   key, which references the event. The *LocalName* field
462                   of the ``ReferenceKey`` holds the name of the field A
463                   reference to a *DataType* concept defines the data
464                   type that values of this parameter have at run time.
465
466 Concept: ContextMap
467 ###################
468
469                .. container:: paragraph
470
471                   The set of context that is available for use by the
472                   policies of a *PolicyModel* is defined as *ContextMap*
473                   concept instances. The *PolicyModel* holds a map of
474                   all the *ContextMap* definitions. A *ContextMap* is
475                   itself a container for a group of related context
476                   items, each of which is represented by a *ContextItem*
477                   concept instance. *ContextMap* concepts are keyed with
478                   an ``ArtifactKey`` key. A developer can use the APEX
479                   Policy Editor to create context maps for their
480                   application domain.
481
482                .. container:: paragraph
483
484                   A *ContextMap* uses a map to hold the context items.
485                   The ContextItem concept instances in the map are
486                   indexed by the *LocalName* of their ``ReferenceKey``.
487
488                .. container:: paragraph
489
490                   The *ContextMapType* field of a *ContextMap* defines
491                   the type of a context map. The type can have either of
492                   two values:
493
494                .. container:: ulist
495
496                   -  A *BAG* context map is a context map with fixed
497                      content. Each possible context item in the context
498                      map is defined at design time and is held in the
499                      *ContextMap* context instance as *ContextItem*
500                      concept definitions and only the values of the
501                      context items in the context map can be changed at
502                      run time. The context items in a *BAG* context map
503                      have mixed types and distinct *ContextItem* concept
504                      instances of the same type can be defined. A *BAG*
505                      context map is convenient for defining a group of
506                      context items that are diverse but are related by
507                      domain, such as the characteristics of a device. A
508                      fully defined *BAG* context map has a fully
509                      populated *ContextItem* map but its
510                      *ContextItemTemplate* reference is not defined.
511
512                   -  A *SAMETYPE* context map is used to represent a
513                      group of *ContextItem* instances of the same type.
514                      Unlike a *BAG* context map, the *ContextItem*
515                      concept instances of a *SAMETYPE* context map can
516                      be added, modified, and deleted at runtime. All
517                      *ContextItem* concept instances in a *SAMETYPE*
518                      context map must be of the same type, and that
519                      context item is defined as a single
520                      *ContextItemTemplate* concept instances at design
521                      time. At run time, the *ContextItemTemplate*
522                      definition is used to create new *ContextItem*
523                      concept instances for the context map on demand. A
524                      fully defined *SAMETYPE context map has an empty
525                      ContextItem map and its ContextItemTemplate\_*
526                      reference is defined.
527
528                .. container:: paragraph
529
530                   The *Scope* of a *ContextMap* defines the range of
531                   applicability of a context map in APEX. The following
532                   scopes of applicability are defined:
533
534                .. container:: ulist
535
536                   -  *EPHEMERAL* scope means that the context map is
537                      owned, used, and modified by a single application,
538                      but the context map only exists while that
539                      application is running
540
541                   -  *APPLICATION* scope specifies that the context map
542                      is owned, used, and modified by a single
543                      application, the context map is persistent
544
545                   -  *GLOBAL* scope specifies that the context map is
546                      globally owned and is used and modified by any
547                      application, the context map is persistent
548
549                   -  *EXTERNAL* scope specifies that the context map is
550                      owned by an external system and may be used in a
551                      read-only manner by any application, the context
552                      map is persistent
553
554                .. container:: paragraph
555
556                   A much more sophisticated scoping mechanism for
557                   context maps is envisaged for Apex in future work. In
558                   such a mechanism, the scope of a context map would
559                   work somewhat like the way roles work in security
560                   authentication systems.
561
562 Concept: ContextItem
563 ####################
564
565                .. container:: paragraph
566
567                   Each piece of context in a *ContextMap* is represented
568                   by an instance of the *ContextItem* concept. Each
569                   *ContextItem* concept instance in a context map keyed
570                   with a ``ReferenceKey`` key, which references the
571                   context map of the context item. The *LocalName* field
572                   of the ``ReferenceKey`` holds the name of the context
573                   item in the context map A reference to a *DataType*
574                   concept defines the data type that values of this
575                   context item have at run time. The *WritableFlag*
576                   indicates if the context item is read only or
577                   read-write at run time.
578
579 Concept: ContextItemTemplate
580 ############################
581
582                .. container:: paragraph
583
584                   In a *SAMETYPE* *ContextMap*, the
585                   *ContextItemTemplate* definition provides a template
586                   for the *ContextItem* instances that will be created
587                   on the context map at run time. Each *ContextItem*
588                   concept instance in the context map is created using
589                   the *ContextItemTemplate* template. It is keyed with a
590                   ``ReferenceKey`` key, which references the context map
591                   of the context item. The *LocalName* field of the
592                   ``ReferenceKey``, supplied by the creator of the
593                   context item at run time, holds the name of the
594                   context item in the context map. A reference to a
595                   *DataType* concept defines the data type that values
596                   of this context item have at run time. The
597                   *WritableFlag* indicates if the context item is read
598                   only or read-write at run time.
599
600 Concept: Task
601 #############
602
603                .. container:: paragraph
604
605                   The smallest unit of logic in a policy is a *Task*. A
606                   task encapsulates a single atomic unit of logic, and
607                   is designed to be a single indivisible unit of
608                   execution. A task may be invoked by a single policy or
609                   by many policies. A task has a single trigger event,
610                   which is sent to the task when it is invoked. Tasks
611                   emit one or more outgoing events, which carry the
612                   result of the task execution. Tasks may use or modify
613                   context as they execute.
614
615                .. container:: paragraph
616
617                   The Task concept definition captures the definition of
618                   an APEX task. Task concepts are keyed with an
619                   ``ArtifactKey`` key. The Trigger of the task is a
620                   reference to the *Event* concept that triggers the
621                   task. The *OutgoingEvents* of a task are a set of
622                   references to *Event* concepts that may be emitted by
623                   the task.
624
625                .. container:: paragraph
626
627                   All tasks have logic, some code that is programmed to
628                   execute the work of the task. The *Logic* concept of
629                   the task holds the definition of that logic.
630
631                .. container:: paragraph
632
633                   The *Task* definition holds a set of *ContextItem* and
634                   *ContextItemTemplate* context items that the task is
635                   allow to access, as defined by the task developer at
636                   design time. The type of access (read-only or read
637                   write) that a task has is determined by the
638                   *WritableFlag* flag on the individual context item
639                   definitions. At run time, a task may only access the
640                   context items specified in its context item set, the
641                   APEX engine makes only the context items in the task
642                   context item set is available to the task.
643
644                .. container:: paragraph
645
646                   A task can be configured with startup parameters. The
647                   set of parameters that can be configured on a task are
648                   defined as a set of *TaskParameter* concept
649                   definitions.
650
651 Concept: TaskParameter
652 ######################
653
654                .. container:: paragraph
655
656                   Each configuration parameter of a task are represented
657                   as a *Taskparameter* concept keyed with a
658                   ``ReferenceKey`` key, which references the task. The
659                   *LocalName* field of the ``ReferenceKey`` holds the
660                   name of the parameter. The *DefaultValue* field
661                   defines the default value that the task parameter is
662                   set to. The value of *TaskParameter* instances can be
663                   overridden at deployment time by specifying their
664                   values in the configuration information passed to APEX
665                   engines.
666
667 Concept: Logic
668 ##############
669
670                .. container:: paragraph
671
672                   The *Logic* concept instance holds the actual
673                   programmed task logic for a task defined in a *Task*
674                   concept or the programmed task selection logic for a
675                   state defined in a *State* concept. It is keyed with a
676                   ``ReferenceKey`` key, which references the task or
677                   state that owns the logic. The *LocalName* field of
678                   the Logic concept is the name of the logic.
679
680                .. container:: paragraph
681
682                   The *LogicCode* field of a Logic concept definition is
683                   a string that holds the program code that is to be
684                   executed at run time. The *LogicType* field defines
685                   the language of the code. The standard values are the
686                   logic languages supported by APEX:
687                   `JAVASCRIPT <https://en.wikipedia.org/wiki/JavaScript>`__,
688                   `JAVA <https://java.com/en/>`__,
689                   `JYTHON <http://www.jython.org/>`__,
690                   `JRUBY <http://jruby.org/>`__, or
691                   `MVEL <https://en.wikibooks.org/wiki/Transwiki:MVEL_Language_Guide>`__.
692
693                .. container:: paragraph
694
695                   The APEX engine uses the *LogicType* field value to
696                   decide which language interpreter to use for a task
697                   and then sends the logic defined in the *LogicCode*
698                   field to that interpreter.
699
700 Concept: Policy
701 ###############
702
703                .. container:: paragraph
704
705                   The *Policy* concept defines a policy in APEX. The
706                   definition is rather straightforward. A policy is made
707                   up of a set of states with the flavor of the policy
708                   determining the structure of the policy states and the
709                   first state defining what state in the policy executes
710                   first. *Policy* concepts are keyed with an
711                   ``ArtifactKey`` key.
712
713                .. container:: paragraph
714
715                   The *PolicyFlavour* of a *Policy* concept specifies
716                   the structure that will be used for the states in the
717                   policy. A number of commonly used policy patterns are
718                   supported as APEX policy flavors. The standard policy
719                   flavors are:
720
721                .. container:: ulist
722
723                   -  The *MEDA* flavor supports policies written to the
724                      `MEDA policy
725                      pattern <https://www.researchgate.net/publication/282576518_Dynamically_Adaptive_Policies_for_Dynamically_Adaptive_Telecommunications_Networks>`__
726                      and require a sequence of four states: namely
727                      *Match*, *Establish*, *Decide* and *Act*.
728
729                   -  The *OODA* flavor supports policies written to the
730                      `OODA loop
731                      pattern <https://en.wikipedia.org/wiki/OODA_loop>`__
732                      and require a sequence of four states: namely
733                      *Observe*, *Orient*, *Decide* and *Act*.
734
735                   -  The *ECA* flavor supports policies written to the
736                      `ECA active rule
737                      pattern <https://en.wikipedia.org/wiki/Event_condition_action>`__
738                      and require a sequence of three states: namely
739                      *Event*, *Condition* and *Action*
740
741                   -  The *XACML* flavor supports policies written in
742                      `XACML <https://en.wikipedia.org/wiki/XACML>`__ and
743                      require a single state: namely *XACML*
744
745                   -  The *FREEFORM* flavor supports policies written in
746                      an arbitrary style. A user can define a *FREEFORM*
747                      policy as an arbitrarily long chain of states.
748
749                .. container:: paragraph
750
751                   The *FirstState* field of a *Policy* definition is the
752                   starting point for execution of a policy. Therefore,
753                   the trigger event of the state referenced in the
754                   *FirstState* field is also the trigger event for the
755                   entire policy.
756
757 Concept: State
758 ##############
759
760                .. container:: paragraph
761
762                   The *State* concept represents a phase or a stage in a
763                   policy, with a policy being composed of a series of
764                   states. Each state has at least one but may have many
765                   tasks and, on each run of execution, a state executes
766                   one and only one of its tasks. If a state has more
767                   than one task, then its task selection logic is used
768                   to select which task to execute. Task selection logic
769                   is programmable logic provided by the state designer.
770                   That logic can use incoming, policy, global, and
771                   external context to select which task best
772                   accomplishes the purpose of the state in a give
773                   situation if more than one task has been specified on
774                   a state. A state calls one and only one task when it
775                   is executed.
776
777                .. container:: paragraph
778
779                   Each state is triggered by an event, which means that
780                   all tasks of a state must also be triggered by that
781                   same event. The set of output events for a state is
782                   the union of all output events from all tasks for that
783                   task. In practice at the moment, because a state can
784                   only have a single input event, a state that is not
785                   the final state of a policy may only output a single
786                   event and all tasks of that state may also only output
787                   that single event. In future work, the concept of
788                   having a less restrictive trigger pattern will be
789                   examined.
790
791                .. container:: paragraph
792
793                   A *State* concept is keyed with a ``ReferenceKey``
794                   key, which references the *Policy* concept that owns
795                   the state. The *LocalName* field of the
796                   ``ReferenceKey`` holds the name of the state. As a
797                   state is part of a chain of states, the *NextState*
798                   field of a state holds the ``ReferenceKey`` key of the
799                   state in the policy to execute after this state.
800
801                .. container:: paragraph
802
803                   The *Trigger* field of a state holds the
804                   ``ArtifactKey`` of the event that triggers this state.
805                   The *OutgoingEvents* field holds the ``ArtifactKey``
806                   references of all possible events that may be output
807                   from the state. This is a set that is the union of all
808                   output events of all tasks of the state.
809
810                .. container:: paragraph
811
812                   The *Task* concepts that hold the definitions of the
813                   task for the state are held as a set of
814                   ``ArtifactKey`` references in the state. The
815                   *DefaultTask* field holds a reference to the default
816                   task for the state, a task that is executed if no task
817                   selection logic is specified. If the state has only
818                   one task, that task is the default task.
819
820                .. container:: paragraph
821
822                   The *Logic* concept referenced by a state holds the
823                   task selection logic for a state. The task selection
824                   logic uses the incoming context (parameters of the
825                   incoming event) and other context to determine the
826                   best task to use to execute its goals. The state holds
827                   a set of references to *ContextItem* and
828                   *ContextItemTemplate* definitions for the context used
829                   by its task selection logic.
830
831 Writing Logic
832 ^^^^^^^^^^^^^
833
834 Writing APEX Task Logic
835 -----------------------
836
837             .. container:: paragraph
838
839                Task logic specifies the behavior of an Apex Task. This
840                logic can be specified in a number of ways, exploiting
841                Apex’s plug-in architecture to support a range of logic
842                executors. In Apex scripted Task Logic can be written in
843                any of these languages:
844
845             .. container:: ulist
846
847                -  ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__,
848
849                -  ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__,
850
851                -  ```JRuby`` <https://en.wikipedia.org/wiki/JRuby>`__ or
852
853                -  ```Jython`` <https://en.wikipedia.org/wiki/Jython>`__.
854
855             .. container:: paragraph
856
857                These languages were chosen because the scripts can be
858                compiled into Java bytecode at runtime and then
859                efficiently executed natively in the JVM. Task Logic an
860                also be written directly in Java but needs to be
861                compiled, with the resulting classes added to the
862                classpath. There are also a number of other Task Logic
863                types (e.g. Fuzzy Logic), but these are not supported as
864                yet. This guide will focus on the scripted Task Logic
865                approaches, with MVEL and JavaScript being our favorite
866                languages. In particular this guide will focus on the
867                Apex aspects of the scripts. However, this guide does not
868                attempt to teach you about the scripting languages
869                themselves â€¦â€‹ that is up to you!
870
871             .. tip::
872                JVM-based scripting languages
873                For more more information on scripting for the Java platform see: https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/index.html
874
875             .. note::
876                What do Tasks do?
877                The function of an Apex Task is to provide the logic that can be executed for an Apex State as one of the steps in
878                an Apex Policy. Each task receives some *incoming fields*, executes some logic (e.g: make a decision based on
879                *shared state* or *context*, *incoming fields*, *external context*, etc.), perhaps set some *shared state* or
880                *context* and then emits *outgoing fields*. The state that uses the task is responsible for extracting the
881                *incoming fields* from the state input event. The state also has an *output mapper* associated with the task, and
882                this *output mapper* is responsible for mapping the *outgoing fields* from the task into an appropriate
883                output event for the state.
884
885             .. container:: paragraph
886
887                First lets start with a sample task, drawn from the "My
888                First Apex Policy" example: The task "MorningBoozeCheck"
889                from the "My First Apex Policy" example is available in
890                both MVEL and JavaScript:
891
892             .. container:: listingblock
893
894                .. container:: title
895
896                   Javascript code for the ``MorningBoozeCheck`` task
897
898                .. container:: content
899
900                   .. code:: javascript
901                      :number-lines:
902
903                      /*
904                       * ============LICENSE_START=======================================================
905                       *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
906                       * ================================================================================
907                       * Licensed under the Apache License, Version 2.0 (the "License");
908                       * you may not use this file except in compliance with the License.
909                       * You may obtain a copy of the License at
910                       *
911                       *      http://www.apache.org/licenses/LICENSE-2.0
912                       *
913                       * Unless required by applicable law or agreed to in writing, software
914                       * distributed under the License is distributed on an "AS IS" BASIS,
915                       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
916                       * See the License for the specific language governing permissions and
917                       * limitations under the License.
918                       *
919                       * SPDX-License-Identifier: Apache-2.0
920                       * ============LICENSE_END=========================================================
921                       */
922
923                      var returnValueType = Java.type("java.lang.Boolean");
924                      var returnValue = new returnValueType(true);
925
926                      // Load compatibility script for imports etc
927                      load("nashorn:mozilla_compat.js");
928                      importPackage(java.text);
929                      importClass(java.text.SimpleDateFormat);
930
931                      executor.logger.info("Task Execution: '"+executor.subject.id+"'. Input Fields: '"+executor.inFields+"'");
932
933                      executor.outFields.put("amount"      , executor.inFields.get("amount"));
934                      executor.outFields.put("assistant_ID", executor.inFields.get("assistant_ID"));
935                      executor.outFields.put("notes"       , executor.inFields.get("notes"));
936                      executor.outFields.put("quantity"    , executor.inFields.get("quantity"));
937                      executor.outFields.put("branch_ID"   , executor.inFields.get("branch_ID"));
938                      executor.outFields.put("item_ID"     , executor.inFields.get("item_ID"));
939                      executor.outFields.put("time"        , executor.inFields.get("time"));
940                      executor.outFields.put("sale_ID"     , executor.inFields.get("sale_ID"));
941
942                      item_id = executor.inFields.get("item_ID");
943
944                      //All times in this script are in GMT/UTC since the policy and events assume time is in GMT.
945                      var timenow_gmt =  new Date(Number(executor.inFields.get("time")));
946
947                      var midnight_gmt = new Date(Number(executor.inFields.get("time")));
948                      midnight_gmt.setUTCHours(0,0,0,0);
949
950                      var eleven30_gmt = new Date(Number(executor.inFields.get("time")));
951                      eleven30_gmt.setUTCHours(11,30,0,0);
952
953                      var timeformatter = new java.text.SimpleDateFormat("HH:mm:ss z");
954
955                      var itemisalcohol = false;
956                      if(item_id != null && item_id >=1000 && item_id < 2000)
957                          itemisalcohol = true;
958
959                      if( itemisalcohol
960                          && timenow_gmt.getTime() >= midnight_gmt.getTime()
961                          && timenow_gmt.getTime() <  eleven30_gmt.getTime()) {
962
963                        executor.outFields.put("authorised", false);
964                        executor.outFields.put("message", "Sale not authorised by policy task " +
965                          executor.subject.taskName+ " for time " + timeformatter.format(timenow_gmt.getTime()) +
966                          ". Alcohol can not be sold between " + timeformatter.format(midnight_gmt.getTime()) +
967                          " and " + timeformatter.format(eleven30_gmt.getTime()));
968                      }
969                      else{
970                        executor.outFields.put("authorised", true);
971                        executor.outFields.put("message", "Sale authorised by policy task " +
972                          executor.subject.taskName + " for time "+timeformatter.format(timenow_gmt.getTime()));
973                      }
974
975                      /*
976                      This task checks if a sale request is for an item that is an alcoholic drink.
977                      If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
978                      authorised. Otherwise the sale is authorised.
979                      In this implementation we assume that items with item_ID value between 1000 and
980                      2000 are all alcoholic drinks :-)
981                      */
982
983             .. container:: listingblock
984
985                .. container:: title
986
987                   MVEL code for the ``MorningBoozeCheck`` task
988
989                .. container:: content
990
991                   .. code:: javascript
992                      :number-lines:
993
994                      /*
995                       * ============LICENSE_START=======================================================
996                       *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
997                       * ================================================================================
998                       * Licensed under the Apache License, Version 2.0 (the "License");
999                       * you may not use this file except in compliance with the License.
1000                       * You may obtain a copy of the License at
1001                       *
1002                       *      http://www.apache.org/licenses/LICENSE-2.0
1003                       *
1004                       * Unless required by applicable law or agreed to in writing, software
1005                       * distributed under the License is distributed on an "AS IS" BASIS,
1006                       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1007                       * See the License for the specific language governing permissions and
1008                       * limitations under the License.
1009                       *
1010                       * SPDX-License-Identifier: Apache-2.0
1011                       * ============LICENSE_END=========================================================
1012                       */
1013                      import java.util.Date;
1014                      import java.util.Calendar;
1015                      import java.util.TimeZone;
1016                      import java.text.SimpleDateFormat;
1017
1018                      logger.info("Task Execution: '"+subject.id+"'. Input Fields: '"+inFields+"'");
1019
1020                      outFields.put("amount"      , inFields.get("amount"));
1021                      outFields.put("assistant_ID", inFields.get("assistant_ID"));
1022                      outFields.put("notes"       , inFields.get("notes"));
1023                      outFields.put("quantity"    , inFields.get("quantity"));
1024                      outFields.put("branch_ID"   , inFields.get("branch_ID"));
1025                      outFields.put("item_ID"     , inFields.get("item_ID"));
1026                      outFields.put("time"        , inFields.get("time"));
1027                      outFields.put("sale_ID"     , inFields.get("sale_ID"));
1028
1029                      item_id = inFields.get("item_ID");
1030
1031                      //The events used later to test this task use GMT timezone!
1032                      gmt = TimeZone.getTimeZone("GMT");
1033                      timenow = Calendar.getInstance(gmt);
1034                      df = new SimpleDateFormat("HH:mm:ss z");
1035                      df.setTimeZone(gmt);
1036                      timenow.setTimeInMillis(inFields.get("time"));
1037
1038                      midnight = timenow.clone();
1039                      midnight.set(
1040                          timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
1041                          timenow.get(Calendar.DATE),0,0,0);
1042                      eleven30 = timenow.clone();
1043                      eleven30.set(
1044                          timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
1045                          timenow.get(Calendar.DATE),11,30,0);
1046
1047                      itemisalcohol = false;
1048                      if(item_id != null && item_id >=1000 && item_id < 2000)
1049                          itemisalcohol = true;
1050
1051                      if( itemisalcohol
1052                          && timenow.after(midnight) && timenow.before(eleven30)){
1053                        outFields.put("authorised", false);
1054                        outFields.put("message", "Sale not authorised by policy task "+subject.taskName+
1055                          " for time "+df.format(timenow.getTime())+
1056                          ". Alcohol can not be sold between "+df.format(midnight.getTime())+
1057                          " and "+df.format(eleven30.getTime()));
1058                        return true;
1059                      }
1060                      else{
1061                        outFields.put("authorised", true);
1062                        outFields.put("message", "Sale authorised by policy task "+subject.taskName+
1063                          " for time "+df.format(timenow.getTime()));
1064                        return true;
1065                      }
1066
1067                      /*
1068                      This task checks if a sale request is for an item that is an alcoholic drink.
1069                      If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
1070                      authorised. Otherwise the sale is authorised.
1071                      In this implementation we assume that items with item_ID value between 1000 and
1072                      2000 are all alcoholic drinks :-)
1073                      */
1074
1075             .. container:: paragraph
1076
1077                The role of the task in this simple example is to copy
1078                the values in the incoming fields into the outgoing
1079                fields, then examine the values in some incoming fields
1080                (``item_id`` and ``time``), then set the values in some
1081                other outgoing fields (``authorised`` and ``message``).
1082
1083             .. container:: paragraph
1084
1085                Both MVEL and JavaScript like most JVM-based scripting
1086                languages can use standard Java libraries to perform
1087                complex tasks. Towards the top of the scripts you will
1088                see how to import Java classes and packages to be used
1089                directly in the logic. Another thing to notice is that
1090                Task Logic should return a ``java.lang.Boolean`` value
1091                ``true`` if the logic executed correctly. If the logic
1092                fails for some reason then ``false`` can be returned, but
1093                this will cause the policy invoking this task will fail
1094                and exit.
1095
1096             .. note::
1097                How to return a value from task logic
1098                Some languages explicitly support returning values from the script (e.g. MVEL and JRuby) using an explicit
1099                return statement (e.g. ``return true``), other languages do not (e.g. JavaScript and Jython). For
1100                languages that do not support the ``return`` statement, a special field called ``returnValue`` must be
1101                created to hold the result of the task logic operation (i.e. assign a ``java.lang.Boolean``
1102                value to the ``returnValue`` field before completing the task).
1103                Also, in MVEL if there is no explicit return statement then the return value of the last executed statement will return
1104                (e.g. the statement a=(1+2) will return the value 3).
1105
1106             .. container:: paragraph
1107
1108                Besides these imported classes and normal language
1109                features Apex provides some natively available parameters
1110                and functions that can be used directly. At run-time
1111                these parameters are populated by the Apex execution
1112                environment and made natively available to logic scripts
1113                each time the logic script is invoked. (These can be
1114                accessed using the ``executor`` keyword for most
1115                languages, or can be accessed directly without the
1116                ``executor`` keyword in MVEL):
1117
1118             Table 1. The ``executor`` Fields / Methods
1119
1120 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1121 | Name       | Type        | Java type                      | Description                                                                         |
1122 +============+=============+================================+=====================================================================================+
1123 | inFields   | Fields      | java.util.Map <String,Object>  | .. container:: paragraph                                                            |
1124 |            |             |                                |                                                                                     |
1125 |            |             |                                |    The incoming task fields. This is implemented as a standard Java                 |
1126 |            |             |                                |    Java (unmodifiable) Map                                                          |
1127 |            |             |                                |                                                                                     |
1128 |            |             |                                | .. container::                                                                      |
1129 |            |             |                                |                                                                                     |
1130 |            |             |                                |    .. container:: content                                                           |
1131 |            |             |                                |                                                                                     |
1132 |            |             |                                |       .. container:: paragraph                                                      |
1133 |            |             |                                |                                                                                     |
1134 |            |             |                                |          **Example:**                                                               |
1135 |            |             |                                |                                                                                     |
1136 |            |             |                                |       .. code:: javascript                                                          |
1137 |            |             |                                |                                                                                     |
1138 |            |             |                                |          executor.logger.debug("Incoming fields: "                                  |
1139 |            |             |                                |             +executor.inFields.entrySet());                                         |
1140 |            |             |                                |          var item_id = executor.incomingFields["item_ID"];                          |
1141 |            |             |                                |          if (item_id >=1000) { ... }                                                |
1142 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1143 | outFields  | Fields      | java.util.Map <String,Object>  | .. container:: paragraph                                                            |
1144 |            |             |                                |                                                                                     |
1145 |            |             |                                |    The outgoing task fields. This is implemented as a standard initially empty Java |
1146 |            |             |                                |    (modifiable) Map. To create a new schema-compliant instance of a field object    |
1147 |            |             |                                |    see the utility method subject.getOutFieldSchemaHelper() below                   |
1148 |            |             |                                |                                                                                     |
1149 |            |             |                                | .. container::                                                                      |
1150 |            |             |                                |                                                                                     |
1151 |            |             |                                |    .. container:: content                                                           |
1152 |            |             |                                |                                                                                     |
1153 |            |             |                                |       .. container:: paragraph                                                      |
1154 |            |             |                                |                                                                                     |
1155 |            |             |                                |          **Example:**                                                               |
1156 |            |             |                                |                                                                                     |
1157 |            |             |                                |       .. code:: javascript                                                          |
1158 |            |             |                                |                                                                                     |
1159 |            |             |                                |          executor.outFields["authorised"] = false;                                  |
1160 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1161 | logger     | Logger      | org.slf4j.ext.XLogger          | .. container:: paragraph                                                            |
1162 |            |             |                                |                                                                                     |
1163 |            |             |                                |    A helpful logger                                                                 |
1164 |            |             |                                |                                                                                     |
1165 |            |             |                                | .. container::                                                                      |
1166 |            |             |                                |                                                                                     |
1167 |            |             |                                |    .. container:: content                                                           |
1168 |            |             |                                |                                                                                     |
1169 |            |             |                                |       .. container:: paragraph                                                      |
1170 |            |             |                                |                                                                                     |
1171 |            |             |                                |          **Example:**                                                               |
1172 |            |             |                                |                                                                                     |
1173 |            |             |                                |       .. code:: javascript                                                          |
1174 |            |             |                                |                                                                                     |
1175 |            |             |                                |          executor.logger.info("Executing task: "                                    |
1176 |            |             |                                |             +executor.subject.id);                                                  |
1177 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1178 | TRUE/FALSE | boolean     | java.lang.Boolean              | .. container:: paragraph                                                            |
1179 |            |             |                                |                                                                                     |
1180 |            |             |                                |    2 helpful constants. These are useful to retrieve correct return  values for the |
1181 |            |             |                                |    task logic                                                                       |
1182 |            |             |                                |                                                                                     |
1183 |            |             |                                | .. container::                                                                      |
1184 |            |             |                                |                                                                                     |
1185 |            |             |                                |    .. container:: content                                                           |
1186 |            |             |                                |                                                                                     |
1187 |            |             |                                |       .. container:: paragraph                                                      |
1188 |            |             |                                |                                                                                     |
1189 |            |             |                                |          **Example:**                                                               |
1190 |            |             |                                |                                                                                     |
1191 |            |             |                                |       .. code:: javascript                                                          |
1192 |            |             |                                |                                                                                     |
1193 |            |             |                                |          var returnValue = executor.isTrue;                                         |
1194 |            |             |                                |          var returnValueType = Java.type("java.lang.Boolean");                      |
1195 |            |             |                                |          var returnValue = new returnValueType(true);                               |
1196 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1197 | subject    | Task        | TaskFacade                     | .. container:: paragraph                                                            |
1198 |            |             |                                |                                                                                     |
1199 |            |             |                                |    This provides some useful information about the task that contains this task     |
1200 |            |             |                                |    logic. This object has some useful fields and methods :                          |
1201 |            |             |                                |                                                                                     |
1202 |            |             |                                | .. container:: ulist                                                                |
1203 |            |             |                                |                                                                                     |
1204 |            |             |                                |    -  **AxTask task** to get access to the full task definition of                  |
1205 |            |             |                                |       the host task                                                                 |
1206 |            |             |                                |                                                                                     |
1207 |            |             |                                |    -  **String getTaskName()** to get the name of the host task                     |
1208 |            |             |                                |                                                                                     |
1209 |            |             |                                |    -  **String getId()** to get the ID of the host task                             |
1210 |            |             |                                |                                                                                     |
1211 |            |             |                                |    -  **SchemaHelper getInFieldSchemaHelper( String fieldName )** to                |
1212 |            |             |                                |       get a ``SchemaHelper`` helper object to manipulate incoming                   |
1213 |            |             |                                |       task fields in a schema-aware manner                                          |
1214 |            |             |                                |                                                                                     |
1215 |            |             |                                |    -  **SchemaHelper getOutFieldSchemaHelper( String fieldName )** to               |
1216 |            |             |                                |       get a ``SchemaHelper`` helper object to manipulate outgoing                   |
1217 |            |             |                                |       task fields in a schema-aware manner, e.g. to instantiate new                 |
1218 |            |             |                                |       schema-compliant field objects to populate the                                |
1219 |            |             |                                |       ``executor.outFields`` outgoing fields map                                    |
1220 |            |             |                                |                                                                                     |
1221 |            |             |                                | .. container::                                                                      |
1222 |            |             |                                |                                                                                     |
1223 |            |             |                                |    .. container:: content                                                           |
1224 |            |             |                                |                                                                                     |
1225 |            |             |                                |       .. container:: paragraph                                                      |
1226 |            |             |                                |                                                                                     |
1227 |            |             |                                |          **Example:**                                                               |
1228 |            |             |                                |                                                                                     |
1229 |            |             |                                |       .. code:: javascript                                                          |
1230 |            |             |                                |                                                                                     |
1231 |            |             |                                |          executor.logger.info("Task name: "                                         |
1232 |            |             |                                |             +executor.subject.getTaskName());                                       |
1233 |            |             |                                |          executor.logger.info("Task id: "                                           |
1234 |            |             |                                |             +executor.subject.getId());                                             |
1235 |            |             |                                |          executor.logger.info("Task inputs definitions: "                           |
1236 |            |             |                                |             +"executor.subject.task.getInputFieldSet());                            |
1237 |            |             |                                |          executor.logger.info("Task outputs definitions: "                          |
1238 |            |             |                                |             +"executor.subject.task.getOutputFieldSet());                           |
1239 |            |             |                                |          executor.outFields["authorised"] = executor.subject                        |
1240 |            |             |                                |                .getOutFieldSchemaHelper("authorised")                               |
1241 |            |             |                                |               .createNewInstance("false");                                          |
1242 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1243 | ContextAlbum getContextAlbum(String ctxtAlbumName )       | .. container:: paragraph                                                            |
1244 |                                                           |                                                                                     |
1245 |                                                           |    A utility method to retrieve a ``ContextAlbum`` for use in the task.             |
1246 |                                                           |    This is how you access the context used by the task. The returned                |
1247 |                                                           |    ``ContextAlbum`` implements the ``java.util.Map <String,Object>``                |
1248 |                                                           |    interface to get and set context as appropriate. The returned                    |
1249 |                                                           |    ``ContextAlbum`` also has methods to lock context albums, get                    |
1250 |                                                           |    information about the schema of the items to be stored in a context              |
1251 |                                                           |    album, and get a ``SchemaHelper`` to manipulate context album items. How         |
1252 |                                                           |    to define and use context in a task is described in the Apex                     |
1253 |                                                           |    Programmer’s Guide and in the My First Apex Policy guide.                        |
1254 |                                                           |                                                                                     |
1255 |                                                           | .. container::                                                                      |
1256 |                                                           |                                                                                     |
1257 |                                                           |    .. container:: content                                                           |
1258 |                                                           |                                                                                     |
1259 |                                                           |       .. container:: paragraph                                                      |
1260 |                                                           |                                                                                     |
1261 |                                                           |          **Example:**                                                               |
1262 |                                                           |                                                                                     |
1263 |                                                           |       .. code:: javascript                                                          |
1264 |                                                           |                                                                                     |
1265 |                                                           |          var bkey = executor.inFields.get("branch_ID");                             |
1266 |                                                           |          var cnts = executor.getContextMap("BranchCounts");                         |
1267 |                                                           |          cnts.lockForWriting(bkey);                                                 |
1268 |                                                           |          cnts.put(bkey, cnts.get(bkey) + 1);                                        |
1269 |                                                           |          cnts.unlockForWriting(bkey);                                               |
1270 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1271
1272 Writing APEX Task Selection Logic
1273 ---------------------------------
1274
1275    .. container:: paragraph
1276
1277       The function of Task Selection Logic is to choose which task
1278       should be executed for an Apex State as one of the steps in an
1279       Apex Policy. Since each state must define a default task there is
1280       no need for Task Selection Logic unless the state uses more than
1281       one task. This logic can be specified in a number of ways,
1282       exploiting Apex’s plug-in architecture to support a range of logic
1283       executors. In Apex scripted Task Selection Logic can be written in
1284       any of these languages:
1285
1286    .. container:: ulist
1287
1288       -  ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__,
1289
1290       -  ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__,
1291
1292       -  ```JRuby`` <https://en.wikipedia.org/wiki/JRuby>`__ or
1293
1294       -  ```Jython`` <https://en.wikipedia.org/wiki/Jython>`__.
1295
1296    .. container:: paragraph
1297
1298       These languages were chosen because the scripts can be compiled
1299       into Java bytecode at runtime and then efficiently executed
1300       natively in the JVM. Task Selection Logic an also be written
1301       directly in Java but needs to be compiled, with the resulting
1302       classes added to the classpath. There are also a number of other
1303       Task Selection Logic types but these are not supported as yet.
1304       This guide will focus on the scripted Task Selection Logic
1305       approaches, with MVEL and JavaScript being our favorite languages.
1306       In particular this guide will focus on the Apex aspects of the
1307       scripts. However, this guide does not attempt to teach you about
1308       the scripting languages themselves â€¦â€‹ that is up to you!
1309
1310    .. tip::
1311       JVM-based scripting languages
1312       For more more information on Scripting for the Java platform see:
1313       https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/index.html
1314
1315    .. note::
1316       What does Task Selection Logic do?
1317       When an Apex state references multiple tasks, there must be a way to dynamically decide
1318       which task should be chosen and executed. This can depend on the many factors, e.g. the
1319       *incoming event for the state*, *shared state* or *context*, *external context*,
1320       etc.. This is the function of a state’s Task Selection Logic. Obviously, if there is
1321       only one task then Task only one task then Task Selection Logic is not needed.
1322       Each state must also select one of the tasks a the *default state*. If the Task
1323       Selection Logic is unable to select an appropriate task, then it should select the
1324       *default task*. Once the task has been selected the Apex Engine will then execute that
1325       task.
1326
1327    .. container:: paragraph
1328
1329       First lets start with some simple Task Selection Logic, drawn from
1330       the "My First Apex Policy" example: The Task Selection Logic from
1331       the "My First Apex Policy" example is specified in JavaScript
1332       here:
1333
1334    .. container:: listingblock
1335
1336       .. container:: title
1337
1338          Javascript code for the "My First Policy" Task Selection Logic
1339
1340       .. container:: content
1341
1342          .. code:: javascript
1343
1344             /*
1345              * ============LICENSE_START=======================================================
1346              *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
1347              * ================================================================================
1348              * Licensed under the Apache License, Version 2.0 (the "License");
1349              * you may not use this file except in compliance with the License.
1350              * You may obtain a copy of the License at
1351              *
1352              *      http://www.apache.org/licenses/LICENSE-2.0
1353              *
1354              * Unless required by applicable law or agreed to in writing, software
1355              * distributed under the License is distributed on an "AS IS" BASIS,
1356              * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1357              * See the License for the specific language governing permissions and
1358              * limitations under the License.
1359              *
1360              * SPDX-License-Identifier: Apache-2.0
1361              * ============LICENSE_END=========================================================
1362              */
1363
1364
1365             var returnValueType = Java.type("java.lang.Boolean");
1366             var returnValue = new returnValueType(true);
1367
1368             executor.logger.info("Task Selection Execution: '"+executor.subject.id+
1369                 "'. Input Event: '"+executor.inFields+"'");
1370
1371             branchid = executor.inFields.get("branch_ID");
1372             taskorig = executor.subject.getTaskKey("MorningBoozeCheck");
1373             taskalt = executor.subject.getTaskKey("MorningBoozeCheckAlt1");
1374             taskdef = executor.subject.getDefaultTaskKey();
1375
1376             if(branchid >=0 && branchid <1000){
1377               taskorig.copyTo(executor.selectedTask);
1378             }
1379             else if (branchid >=1000 && branchid <2000){
1380               taskalt.copyTo(executor.selectedTask);
1381             }
1382             else{
1383               taskdef.copyTo(executor.selectedTask);
1384             }
1385
1386             /*
1387             This task selection logic selects task "MorningBoozeCheck" for branches with
1388             0<=branch_ID<1000 and selects task "MorningBoozeCheckAlt1" for branches with
1389             1000<=branch_ID<2000. Otherwise the default task is selected.
1390             In this case the default task is also "MorningBoozeCheck"
1391             */
1392
1393    .. container:: paragraph
1394
1395       The role of the Task Selection Logic in this simple example is to
1396       examine the value in one incoming field (``branchid``), then
1397       depending on that field’s value set the value for the selected
1398       task to the appropriate task (``MorningBoozeCheck``,
1399       ``MorningBoozeCheckAlt1``, or the default task).
1400
1401    .. container:: paragraph
1402
1403       Another thing to notice is that Task Selection Logic should return
1404       a ``java.lang.Boolean`` value ``true`` if the logic executed
1405       correctly. If the logic fails for some reason then ``false`` can
1406       be returned, but this will cause the policy invoking this task
1407       will fail and exit.
1408
1409    .. note::
1410       How to return a value from Task Selection Logic
1411       Some languages explicitly support returning values from the script (e.g. MVEL and
1412       JRuby) using an explicit return statement (e.g. ``return true``), other languages do not (e.g.
1413       JavaScript and Jython). For languages that do not support the ``return`` statement, a special field called
1414       ``returnValue`` must be created to hold the result of the task logic operation (i.e. assign a ``java.lang.Boolean``
1415       value to the ``returnValue`` field before completing the task).
1416       Also, in MVEL if there is not explicit return statement then the return value of the last executed statement will
1417       return (e.g. the statement a=(1+2) will return the value 3).
1418
1419    .. container:: paragraph
1420
1421       Each of the scripting languages used in Apex can import and use
1422       standard Java libraries to perform complex tasks. Besides imported
1423       classes and normal language features Apex provides some natively
1424       available parameters and functions that can be used directly. At
1425       run-time these parameters are populated by the Apex execution
1426       environment and made natively available to logic scripts each time
1427       the logic script is invoked. (These can be accessed using the
1428       ``executor`` keyword for most languages, or can be accessed
1429       directly without the ``executor`` keyword in MVEL):
1430
1431    Table 2. The ``executor`` Fields / Methods
1432       +-------------------------------------------------------+--------------------------------------------------------+
1433       | Unix, Cygwin                                          | Windows                                                |
1434       +=======================================================+========================================================+
1435       | .. container::                                        | .. container::                                         |
1436       |                                                       |                                                        |
1437       |    .. container:: content                             |    .. container:: content                              |
1438       |                                                       |                                                        |
1439       |       .. code:: bash                                  |       .. code:: bash                                   |
1440       |         :number-lines:                                |         :number-lines:                                 |
1441       |                                                       |                                                        |
1442       |         >c:                                           |         # cd /usr/local/src/apex-pdp                   |
1443       |         >cd \dev\apex                                 |         # mvn clean install -DskipTests                |
1444       |         >mvn clean install -DskipTests                |                                                        |
1445       +-------------------------------------------------------+--------------------------------------------------------+
1446
1447 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1448 | Name       | Type        | Java type                      | Description                                                                         |
1449 +============+=============+================================+=====================================================================================+
1450 | inFields   | Fields      | java.util.Map <String,Object>  | .. container:: paragraph                                                            |
1451 |            |             |                                |                                                                                     |
1452 |            |             |                                |    All fields in the state’s incoming event. This is implemented as a standard Java |
1453 |            |             |                                |    Java (unmodifiable) Map                                                          |
1454 |            |             |                                |                                                                                     |
1455 |            |             |                                | .. container::                                                                      |
1456 |            |             |                                |                                                                                     |
1457 |            |             |                                |    .. container:: content                                                           |
1458 |            |             |                                |                                                                                     |
1459 |            |             |                                |       .. container:: paragraph                                                      |
1460 |            |             |                                |                                                                                     |
1461 |            |             |                                |          **Example:**                                                               |
1462 |            |             |                                |                                                                                     |
1463 |            |             |                                |       .. code:: javascript                                                          |
1464 |            |             |                                |                                                                                     |
1465 |            |             |                                |          executor.logger.debug("Incoming fields: "                                  |
1466 |            |             |                                |             +executor.inFields.entrySet());                                         |
1467 |            |             |                                |          var item_id = executor.incomingFields["item_ID"];                          |
1468 |            |             |                                |          if (item_id >=1000) { ... }                                                |
1469 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1470 | outFields  | Fields      | java.util.Map <String,Object>  | .. container:: paragraph                                                            |
1471 |            |             |                                |                                                                                     |
1472 |            |             |                                |    The outgoing task fields. This is implemented as a standard initially empty Java |
1473 |            |             |                                |    (modifiable) Map. To create a new schema-compliant instance of a field object    |
1474 |            |             |                                |    see the utility method subject.getOutFieldSchemaHelper() below                   |
1475 |            |             |                                |                                                                                     |
1476 |            |             |                                | .. container::                                                                      |
1477 |            |             |                                |                                                                                     |
1478 |            |             |                                |    .. container:: content                                                           |
1479 |            |             |                                |                                                                                     |
1480 |            |             |                                |       .. container:: paragraph                                                      |
1481 |            |             |                                |                                                                                     |
1482 |            |             |                                |          **Example:**                                                               |
1483 |            |             |                                |                                                                                     |
1484 |            |             |                                |       .. code:: javascript                                                          |
1485 |            |             |                                |                                                                                     |
1486 |            |             |                                |          executor.outFields["authorised"] = false;                                  |
1487 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1488 | logger     | Logger      | org.slf4j.ext.XLogger          | .. container:: paragraph                                                            |
1489 |            |             |                                |                                                                                     |
1490 |            |             |                                |    A helpful logger                                                                 |
1491 |            |             |                                |                                                                                     |
1492 |            |             |                                | .. container::                                                                      |
1493 |            |             |                                |                                                                                     |
1494 |            |             |                                |    .. container:: content                                                           |
1495 |            |             |                                |                                                                                     |
1496 |            |             |                                |       .. container:: paragraph                                                      |
1497 |            |             |                                |                                                                                     |
1498 |            |             |                                |          **Example:**                                                               |
1499 |            |             |                                |                                                                                     |
1500 |            |             |                                |       .. code:: javascript                                                          |
1501 |            |             |                                |                                                                                     |
1502 |            |             |                                |          executor.logger.info("Executing task: "                                    |
1503 |            |             |                                |             +executor.subject.id);                                                  |
1504 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1505 | TRUE/FALSE | boolean     | java.lang.Boolean              | .. container:: paragraph                                                            |
1506 |            |             |                                |                                                                                     |
1507 |            |             |                                |    2 helpful constants. These are useful to retrieve correct return  values for the |
1508 |            |             |                                |    task logic                                                                       |
1509 |            |             |                                |                                                                                     |
1510 |            |             |                                | .. container::                                                                      |
1511 |            |             |                                |                                                                                     |
1512 |            |             |                                |    .. container:: content                                                           |
1513 |            |             |                                |                                                                                     |
1514 |            |             |                                |       .. container:: paragraph                                                      |
1515 |            |             |                                |                                                                                     |
1516 |            |             |                                |          **Example:**                                                               |
1517 |            |             |                                |                                                                                     |
1518 |            |             |                                |       .. code:: javascript                                                          |
1519 |            |             |                                |                                                                                     |
1520 |            |             |                                |          var returnValue = executor.isTrue;                                         |
1521 |            |             |                                |          var returnValueType = Java.type("java.lang.Boolean");                      |
1522 |            |             |                                |          var returnValue = new returnValueType(true);                               |
1523 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1524 | subject    | Task        | TaskFacade                     | .. container:: paragraph                                                            |
1525 |            |             |                                |                                                                                     |
1526 |            |             |                                |    This provides some useful information about the task that contains this task     |
1527 |            |             |                                |    logic. This object has some useful fields and methods :                          |
1528 |            |             |                                |                                                                                     |
1529 |            |             |                                | .. container:: ulist                                                                |
1530 |            |             |                                |                                                                                     |
1531 |            |             |                                |    -  **AxTask task** to get access to the full task definition of                  |
1532 |            |             |                                |       the host task                                                                 |
1533 |            |             |                                |                                                                                     |
1534 |            |             |                                |    -  **String getTaskName()** to get the name of the host task                     |
1535 |            |             |                                |                                                                                     |
1536 |            |             |                                |    -  **String getId()** to get the ID of the host task                             |
1537 |            |             |                                |                                                                                     |
1538 |            |             |                                |    -  **SchemaHelper getInFieldSchemaHelper( String fieldName )** to                |
1539 |            |             |                                |       get a ``SchemaHelper`` helper object to manipulate incoming                   |
1540 |            |             |                                |       task fields in a schema-aware manner                                          |
1541 |            |             |                                |                                                                                     |
1542 |            |             |                                |    -  **SchemaHelper getOutFieldSchemaHelper( String fieldName )** to               |
1543 |            |             |                                |       get a ``SchemaHelper`` helper object to manipulate outgoing                   |
1544 |            |             |                                |       task fields in a schema-aware manner, e.g. to instantiate new                 |
1545 |            |             |                                |       schema-compliant field objects to populate the                                |
1546 |            |             |                                |       ``executor.outFields`` outgoing fields map                                    |
1547 |            |             |                                |                                                                                     |
1548 |            |             |                                | .. container::                                                                      |
1549 |            |             |                                |                                                                                     |
1550 |            |             |                                |    .. container:: content                                                           |
1551 |            |             |                                |                                                                                     |
1552 |            |             |                                |       .. container:: paragraph                                                      |
1553 |            |             |                                |                                                                                     |
1554 |            |             |                                |          **Example:**                                                               |
1555 |            |             |                                |                                                                                     |
1556 |            |             |                                |       .. code:: javascript                                                          |
1557 |            |             |                                |                                                                                     |
1558 |            |             |                                |          executor.logger.info("Task name: "                                         |
1559 |            |             |                                |             +executor.subject.getTaskName());                                       |
1560 |            |             |                                |          executor.logger.info("Task id: "                                           |
1561 |            |             |                                |             +executor.subject.getId());                                             |
1562 |            |             |                                |          executor.logger.info("Task inputs definitions: "                           |
1563 |            |             |                                |             +"executor.subject.task.getInputFieldSet());                            |
1564 |            |             |                                |          executor.logger.info("Task outputs definitions: "                          |
1565 |            |             |                                |             +"executor.subject.task.getOutputFieldSet());                           |
1566 |            |             |                                |          executor.outFields["authorised"] = executor.subject                        |
1567 |            |             |                                |                .getOutFieldSchemaHelper("authorised")                               |
1568 |            |             |                                |               .createNewInstance("false");                                          |
1569 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1570 | ContextAlbum getContextAlbum(String ctxtAlbumName )       | .. container:: paragraph                                                            |
1571 |                                                           |                                                                                     |
1572 |                                                           |    A utility method to retrieve a ``ContextAlbum`` for use in the task.             |
1573 |                                                           |    This is how you access the context used by the task. The returned                |
1574 |                                                           |    ``ContextAlbum`` implements the ``java.util.Map <String,Object>``                |
1575 |                                                           |    interface to get and set context as appropriate. The returned                    |
1576 |                                                           |    ``ContextAlbum`` also has methods to lock context albums, get                    |
1577 |                                                           |    information about the schema of the items to be stored in a context              |
1578 |                                                           |    album, and get a ``SchemaHelper`` to manipulate context album items. How         |
1579 |                                                           |    to define and use context in a task is described in the Apex                     |
1580 |                                                           |    Programmer’s Guide and in the My First Apex Policy guide.                        |
1581 |                                                           |                                                                                     |
1582 |                                                           | .. container::                                                                      |
1583 |                                                           |                                                                                     |
1584 |                                                           |    .. container:: content                                                           |
1585 |                                                           |                                                                                     |
1586 |                                                           |       .. container:: paragraph                                                      |
1587 |                                                           |                                                                                     |
1588 |                                                           |          **Example:**                                                               |
1589 |                                                           |                                                                                     |
1590 |                                                           |       .. code:: javascript                                                          |
1591 |                                                           |                                                                                     |
1592 |                                                           |          var bkey = executor.inFields.get("branch_ID");                             |
1593 |                                                           |          var cnts = executor.getContextMap("BranchCounts");                         |
1594 |                                                           |          cnts.lockForWriting(bkey);                                                 |
1595 |                                                           |          cnts.put(bkey, cnts.get(bkey) + 1);                                        |
1596 |                                                           |          cnts.unlockForWriting(bkey);                                               |
1597 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1598
1599 Logic Cheatsheet
1600 ----------------
1601
1602    .. container:: paragraph
1603
1604       Examples given here use Javascript (if not stated otherwise),
1605       other execution environments will be similar.
1606
1607 Add Nashorn
1608 ###########
1609
1610       .. container:: paragraph
1611
1612          First line in the logic use this import.
1613
1614       .. container:: listingblock
1615
1616          .. container:: title
1617
1618             JS Nashorn
1619
1620          .. container:: content
1621
1622             .. code:: javascript
1623
1624                load("nashorn:mozilla_compat.js");
1625
1626 Finish Logic with Success or Error
1627 ##################################
1628
1629       .. container:: paragraph
1630
1631          To finish logic, i.e. return to APEX, with success use the
1632          following lines close to the end of the logic.
1633
1634       .. container:: listingblock
1635
1636          .. container:: title
1637
1638             JS Success
1639
1640          .. container:: content
1641
1642             .. code:: javascript
1643
1644                var returnValueType = Java.type("java.lang.Boolean");
1645                var returnValue = new returnValueType(true);
1646
1647       .. container:: paragraph
1648
1649          To notify a problem, finish with an error.
1650
1651       .. container:: listingblock
1652
1653          .. container:: title
1654
1655             JS Fail
1656
1657          .. container:: content
1658
1659             .. code:: javascript
1660
1661                var returnValueType = Java.type("java.lang.Boolean");
1662                var returnValue = new returnValueType(false);
1663
1664 Logic Logging
1665 #############
1666
1667       .. container:: paragraph
1668
1669          Logging can be made easy using a local variable for the logger.
1670          Line 1 below does that. Then we start with a trace log with the
1671          task (or task logic) identifier followed by the infields.
1672
1673       .. container:: listingblock
1674
1675          .. container:: title
1676
1677             JS Logging
1678
1679          .. container:: content
1680
1681             .. code:: javascript
1682
1683                var logger = executor.logger;
1684                logger.trace("start: " + executor.subject.id);
1685                logger.trace("-- infields: " + executor.inFields);
1686
1687       .. container:: paragraph
1688
1689          For larger logging blocks you can use the standard logging API
1690          to detect log levels, for instance:
1691
1692       .. container:: listingblock
1693
1694          .. container:: title
1695
1696             JS Logging Blocks
1697
1698          .. container:: content
1699
1700             .. code:: javascript
1701
1702                if(logger.isTraceEnabled()){
1703                    // trace logging block here
1704                }
1705
1706       .. container:: paragraph
1707
1708          Note: the shown logger here logs to
1709          ``org.onap.policy.apex.executionlogging``. The behavior of the
1710          actual logging can be specified in the
1711          ``$APEX_HOME/etc/logback.xml``.
1712
1713       .. container:: paragraph
1714
1715          If you want to log into the APEX root logger (which is
1716          sometimes necessary to report serious logic errors to the top),
1717          then import the required class and use this logger.
1718
1719       .. container:: listingblock
1720
1721          .. container:: title
1722
1723             JS Root Logger
1724
1725          .. container:: content
1726
1727             .. code:: javascript
1728
1729                importClass(org.slf4j.LoggerFactory);
1730                var rootLogger = LoggerFactory.getLogger(logger.ROOT_LOGGER_NAME);
1731
1732                rootLogger.error("Serious error in logic detected: " + executor.subject.id);
1733
1734 Local Variable for Infields
1735 ###########################
1736
1737       .. container:: paragraph
1738
1739          It is a good idea to use local variables for ``infields``. This
1740          avoids long code lines and policy evolution. The following
1741          example assumes infields named ``nodeName`` and ``nodeAlias``.
1742
1743       .. container:: listingblock
1744
1745          .. container:: title
1746
1747             JS Infields Local Var
1748
1749          .. container:: content
1750
1751             .. code:: javascript
1752
1753                var ifNodeName = executor.inFields["nodeName"];
1754                var ifNodeAlias = executor.inFields["nodeAlias"];
1755
1756 Local Variable for Context Albums
1757 #################################
1758
1759       .. container:: paragraph
1760
1761          Similar to the ``infields`` it is good practice to use local
1762          variables for context albums as well. The following example
1763          assumes that a task can access a context album
1764          ``albumTopoNodes``. The second line gets a particular node from
1765          this context album.
1766
1767       .. container:: listingblock
1768
1769          .. container:: title
1770
1771             JS Infields Local Var
1772
1773          .. container:: content
1774
1775             .. code:: javascript
1776
1777                var albumTopoNodes = executor.getContextAlbum("albumTopoNodes");
1778                var ctxtNode = albumTopoNodes.get(ifNodeName);
1779
1780 Set Outfields in Logic
1781 ######################
1782
1783       .. container:: paragraph
1784
1785          The task logic needs to set outfields with content generated.
1786          The exception are outfields that are a direct copy from an
1787          infield of the same name, APEX does that autmatically.
1788
1789       .. container:: listingblock
1790
1791          .. container:: title
1792
1793             JS Set Outfields
1794
1795          .. container:: content
1796
1797             .. code:: javascript
1798
1799                executor.outFields["report"] = "node ctxt :: added node " + ifNodeName;
1800
1801 Create a instance of an Outfield using Schemas
1802 ##############################################
1803
1804       .. container:: paragraph
1805
1806          If an outfield is not an atomic type (string, integer, etc.)
1807          but uses a complex schema (with a Java or Avro backend), APEX
1808          can help to create new instances. The ``executor`` provides a
1809          field called ``subject``, which provides a schem helper with an
1810          API for this. The complete API of the schema helper is
1811          documented here: `API Doc:
1812          SchemaHelper <https://ericsson.github.io/apex-docs/javadocs/index.html>`__.
1813
1814       .. container:: paragraph
1815
1816          If the backend is Avro, then an import of the Avro schema
1817          library is required:
1818
1819       .. container:: listingblock
1820
1821          .. container:: title
1822
1823             JS Import Avro
1824
1825          .. container:: content
1826
1827             .. code:: javascript
1828
1829                importClass(org.apache.avro.generic.GenericData.Array);
1830                importClass(org.apache.avro.generic.GenericRecord);
1831                importClass(org.apache.avro.Schema);
1832
1833       .. container:: paragraph
1834
1835          If the backend is Java, then the Java class implementing the
1836          schema needs to be imported.
1837
1838       .. container:: paragraph
1839
1840          The following example assumes an outfield ``situation``. The
1841          ``subject`` method ``getOutFieldSchemaHelper()`` is used to
1842          create a new instance.
1843
1844       .. container:: listingblock
1845
1846          .. container:: title
1847
1848             JS Outfield Instance with Schema
1849
1850          .. container:: content
1851
1852             .. code:: javascript
1853
1854                var situation = executor.subject.getOutFieldSchemaHelper("situation").createNewInstance();
1855
1856       .. container:: paragraph
1857
1858          If the schema backend is Java, the new instance will be as
1859          implemented in the Java class. If the schema backend is Avro,
1860          the new instance will have all fields from the Avro schema
1861          specification, but set to ``null``. So any entry here needs to
1862          be done separately. For instance, the ``situation`` schema has
1863          a field ``problemID`` which we set.
1864
1865       .. container:: listingblock
1866
1867          .. container:: title
1868
1869             JS Outfield Instance with Schema, set
1870
1871          .. container:: content
1872
1873             .. code:: javascript
1874
1875                situation.put("problemID", "my-problem");
1876
1877 Create a instance of an Context Album entry using Schemas
1878 #########################################################
1879
1880       .. container:: paragraph
1881
1882          Context album instances can be created using very similar to
1883          the outfields. Here, the schema helper comes from the context
1884          album directly. The API of the schema helper is the same as for
1885          outfields, see `API Doc:
1886          SchemaHelper <https://ericsson.github.io/apex-docs/javadocs/index.html>`__.
1887
1888       .. container:: paragraph
1889
1890          If the backend is Avro, then an import of the Avro schema
1891          library is required:
1892
1893       .. container:: listingblock
1894
1895          .. container:: title
1896
1897             JS Import Avro
1898
1899          .. container:: content
1900
1901             .. code:: javascript
1902
1903                importClass(org.apache.avro.generic.GenericData.Array);
1904                importClass(org.apache.avro.generic.GenericRecord);
1905                importClass(org.apache.avro.Schema);
1906
1907       .. container:: paragraph
1908
1909          If the backend is Java, then the Java class implementing the
1910          schema needs to be imported.
1911
1912       .. container:: paragraph
1913
1914          The following example creates a new instance of a context album
1915          instance named ``albumProblemMap``.
1916
1917       .. container:: listingblock
1918
1919          .. container:: title
1920
1921             JS Outfield Instance with Schema
1922
1923          .. container:: content
1924
1925             .. code:: javascript
1926
1927                var albumProblemMap = executor.getContextAlbum("albumProblemMap");
1928                var linkProblem = albumProblemMap.getSchemaHelper().createNewInstance();
1929
1930       .. container:: paragraph
1931
1932          This can of course be also done in a single call without the
1933          local variable for the context album.
1934
1935       .. container:: listingblock
1936
1937          .. container:: title
1938
1939             JS Outfield Instance with Schema, one line
1940
1941          .. container:: content
1942
1943             .. code:: javascript
1944
1945                var linkProblem = executor.getContextAlbum("albumProblemMap").getSchemaHelper().createNewInstance();
1946
1947       .. container:: paragraph
1948
1949          If the schema backend is Java, the new instance will be as
1950          implemented in the Java class. If the schema backend is Avro,
1951          the new instance will have all fields from the Avro schema
1952          specification, but set to ``null``. So any entry here needs to
1953          be done separately (see above in outfields for an example).
1954
1955 Enumerates
1956 ##########
1957
1958       .. container:: paragraph
1959
1960          When dealing with enumerates (Avro or Java defined), it is
1961          sometimes and in some execution environments necessary to
1962          convert them to a string. For example, assume an Avro enumerate
1963          schema as:
1964
1965       .. container:: listingblock
1966
1967          .. container:: title
1968
1969             Avro Enumerate Schema
1970
1971          .. container:: content
1972
1973             .. code:: javascript
1974
1975                {
1976                  "type": "enum",
1977                  "name": "Status",
1978                  "symbols" : [
1979                    "UP",
1980                    "DOWN"
1981                  ]
1982                }
1983
1984       .. container:: paragraph
1985
1986          Using a switch over a field initialized with this enumerate in
1987          Javascript will fail. Instead, use the ``toString`` method, for
1988          example:
1989
1990       .. container:: listingblock
1991
1992          .. container:: title
1993
1994             JS Outfield Instance with Schema, one line
1995
1996          .. container:: content
1997
1998             .. code:: javascript
1999
2000                var switchTest = executor.inFields["status"];
2001                switch(switchTest.toString()){
2002                  case "UP": ...; break;
2003                  case "DOWN": ...; break;
2004                  default: ...;
2005                }
2006
2007 MVEL Initialize Outfields First!
2008 ################################
2009
2010       .. container:: paragraph
2011
2012          In MVEL, we observed a problem when accessing (setting)
2013          outfields without a prior access to them. So in any MVEL task
2014          logic, before setting any outfield, simply do a get (with any
2015          string), to load the outfields into the MVEL cache.
2016
2017       .. container:: listingblock
2018
2019          .. container:: title
2020
2021             MVEL Outfield Initialization
2022
2023          .. container:: content
2024
2025             .. code:: javascript
2026
2027                outFields.get("initialize outfields");
2028
2029 Using Java in Scripting Logic
2030 #############################
2031
2032       .. container:: paragraph
2033
2034          Since APEX executes the logic inside a JVM, most scripting
2035          languages provide access to all standard Java classes. Simply
2036          add an import for the required class and then use it as in
2037          actual Java.
2038
2039       .. container:: paragraph
2040
2041          The following example imports ``java.util.arraylist`` into a
2042          Javascript logic, and then creates a new list.
2043
2044       .. container:: listingblock
2045
2046          .. container:: title
2047
2048             JS Import ArrayList
2049
2050          .. container:: content
2051
2052             .. code:: javascript
2053
2054                importClass(java.util.ArrayList);
2055                var myList = new ArrayList();
2056
2057 Policy Examples
2058 ^^^^^^^^^^^^^^^
2059
2060 My First Policy
2061 ---------------
2062
2063          .. container:: paragraph
2064
2065             A good starting point is the ``My First Policy`` example. It
2066             describes a sales problem, to which policy can be applied.
2067             The example details the policy background, shows how to use
2068             the REST Editor to create a policy, and provides details for
2069             running the policies. The documentation can be found:
2070
2071          .. container:: ulist
2072
2073             -  `My-First-Policy on the APEX
2074                site <https://ericsson.github.io/apex-docs/modules/examples/examples-myfirstpolicy/MyFirstPolicyHowto.html>`__
2075
2076             -  `Stand-alone
2077                HTML <https://ericsson.github.io/apex-docs/docs-apex/html/HowTo-MyFirstPolicy.html>`__
2078
2079             -  `Stand-alone
2080                PDF <https://ericsson.github.io/apex-docs/docs-apex/pdf/HowTo-MyFirstPolicy.pdf>`__
2081
2082 VPN SLA
2083 -------
2084
2085          .. container:: paragraph
2086
2087             The domain Policy-controlled Video Streaming (PCVS) contains
2088             a policy for controlling video streams with different
2089             strategies. It also provides details for installing an
2090             actual testbed with off-the-shelve software (Mininet,
2091             Floodlight, Kafka, Zookeeper). The policy model here
2092             demonstrates virtually all APEX features: local context and
2093             policies controlling it, task selection logic and multiple
2094             tasks in a single state, AVRO schemas for context, AVOR
2095             schemas for events (trigger and local), and a CLI editor
2096             specification of the policy. The documentation can be found:
2097
2098          .. container:: ulist
2099
2100             -  `VPN SLA Policy on the APEX
2101                site <https://ericsson.github.io/apex-docs/modules/examples/examples-pcvs/vpnsla/policy.html>`__
2102
2103 Decision Maker
2104 --------------
2105
2106          .. container:: paragraph
2107
2108             The domain Decision Maker shows a very simple policy for
2109             decisions. Interesting here is that the it creates a Docker
2110             image to run the policy and that it uses the APEX REST
2111             applications to update the policy on the-fly. It also has
2112             local context to remember past decisions, and shows how to
2113             use that to no make the same decision twice in a row. The
2114             documentation can be found:
2115
2116          .. container:: ulist
2117
2118             -  `Decision Maker on APEX
2119                site <https://ericsson.github.io/apex-docs/modules/examples/examples-decisionmaker/index.html>`__
2120
2121 .. container::
2122    :name: footer
2123
2124    .. container::
2125       :name: footer-text
2126
2127       2.0.0-SNAPSHOT
2128       Last updated 2018-09-04 16:04:24 IST
2129
2130 .. |APEX Policy Matrix| image:: images/apex-intro/ApexPolicyMatrix.png
2131 .. |APEX Policy Model for Execution| image:: images/apex-policy-model/UmlPolicyModels.png
2132 .. |Concepts and Keys| image:: images/apex-policy-model/ConceptsKeys.png
2133