1 .. This work is licensed under a Creative Commons Attribution 4.0 International License.
2 .. http://creativecommons.org/licenses/by/4.0
6 *****************************
17 .. container:: paragraph
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.
32 .. container:: paragraph
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
39 .. container:: imageblock
41 .. container:: content
47 Figure 1. APEX Policy Matrix
49 .. container:: paragraph
51 The policy can support one of a number of stimuli with an
52 associated purpose/model of the policy, for instance:
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.
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.
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
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
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,
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
94 .. container:: paragraph
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:
103 - No context, nothing but a trigger event, e.g. a string
104 or a number, is required
106 - Event context, the incoming event provides all
107 information (more than a string or number) for the
110 - Policy context (read only), the policy has access to
111 additional information related to its class but cannot
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)
119 - Global context (read only), the policy has access to
120 additional information of any kind but cannot
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)
128 .. container:: paragraph
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,
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
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
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
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.
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
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.
179 .. container:: paragraph
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:
187 - Obligation (deontic for what should happen)
189 - Authorization (e.g. for rule-based or other access
190 control or security systems)
192 - Intent (instead of providing detailed actions the
193 response is an intent statement and a further system
196 - Delegation (hand the problem over to someone else,
197 possibly with some information or instructions)
199 - Fail / Error (the policy has encountered a problem,
202 - Feedback (why did the policy make a certain decision)
210 .. container:: paragraph
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.
220 .. container:: paragraph
222 The figure shows four different views of the policy
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.
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).
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.
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.
258 .. container:: imageblock
260 .. container:: content
262 |APEX Policy Model for Execution|
266 Figure 2. APEX Policy Model for Execution
271 .. container:: paragraph
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
279 .. container:: imageblock
281 .. container:: content
287 Figure 3. Concepts and Keys
291 - ``getKey()`` - gets the unique key for this concept
292 instance in the system
294 - ``validate()`` - validates the structure of this
295 concept, its sub-concepts and its relationships
297 - ``clean()`` - carries out housekeeping on the
298 concept such as trimming strings, remove any
301 - ``clone()`` - creates a deep copy of an instance of
304 - ``equals()`` - checks if two instances of this
307 - ``toString()`` - returns a string representation of
310 - ``hashCode()`` - returns a hash code for the
313 - ``copyTo()`` - carries out a deep copy of one
314 instance of the concept to another instance,
315 overwriting the target fields.
317 .. container:: paragraph
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
330 .. container:: paragraph
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
339 .. container:: paragraph
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.
349 .. container:: paragraph
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``.
361 .. container:: paragraph
363 Each concept in the model is also a JPA (`Java
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/>`__.
376 .. container:: paragraph
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.
389 .. container:: paragraph
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.
400 .. container:: paragraph
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*
418 .. container:: paragraph
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
434 - The *NameSpace* identifies the domain of
435 application of the event
437 - The *Source* of the event identifies the system
438 that emitted the event
440 - The *Target* of the event identifies the system
441 that the event was sent to
443 .. container:: paragraph
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.
453 .. container:: paragraph
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.
469 .. container:: paragraph
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
482 .. container:: paragraph
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``.
488 .. container:: paragraph
490 The *ContextMapType* field of a *ContextMap* defines
491 the type of a context map. The type can have either of
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.
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.
528 .. container:: paragraph
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:
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
541 - *APPLICATION* scope specifies that the context map
542 is owned, used, and modified by a single
543 application, the context map is persistent
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
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
554 .. container:: paragraph
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.
565 .. container:: paragraph
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.
579 Concept: ContextItemTemplate
580 ############################
582 .. container:: paragraph
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.
603 .. container:: paragraph
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.
615 .. container:: paragraph
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
625 .. container:: paragraph
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.
631 .. container:: paragraph
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.
644 .. container:: paragraph
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
651 Concept: TaskParameter
652 ######################
654 .. container:: paragraph
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
670 .. container:: paragraph
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.
680 .. container:: paragraph
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>`__.
693 .. container:: paragraph
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.
703 .. container:: paragraph
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
713 .. container:: paragraph
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
723 - The *MEDA* flavor supports policies written to the
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*.
729 - The *OODA* flavor supports policies written to the
731 pattern <https://en.wikipedia.org/wiki/OODA_loop>`__
732 and require a sequence of four states: namely
733 *Observe*, *Orient*, *Decide* and *Act*.
735 - The *ECA* flavor supports policies written to the
737 pattern <https://en.wikipedia.org/wiki/Event_condition_action>`__
738 and require a sequence of three states: namely
739 *Event*, *Condition* and *Action*
741 - The *XACML* flavor supports policies written in
742 `XACML <https://en.wikipedia.org/wiki/XACML>`__ and
743 require a single state: namely *XACML*
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.
749 .. container:: paragraph
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
760 .. container:: paragraph
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
777 .. container:: paragraph
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
791 .. container:: paragraph
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.
801 .. container:: paragraph
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.
810 .. container:: paragraph
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.
820 .. container:: paragraph
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.
834 Writing APEX Task Logic
835 -----------------------
837 .. container:: paragraph
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:
847 - ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__,
849 - ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__,
851 - ```JRuby`` <https://en.wikipedia.org/wiki/JRuby>`__ or
853 - ```Jython`` <https://en.wikipedia.org/wiki/Jython>`__.
855 .. container:: paragraph
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!
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
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.
885 .. container:: paragraph
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:
892 .. container:: listingblock
896 Javascript code for the ``MorningBoozeCheck`` task
898 .. container:: content
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
911 * http://www.apache.org/licenses/LICENSE-2.0
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.
919 * SPDX-License-Identifier: Apache-2.0
920 * ============LICENSE_END=========================================================
923 var returnValueType = Java.type("java.lang.Boolean");
924 var returnValue = new returnValueType(true);
926 // Load compatibility script for imports etc
927 load("nashorn:mozilla_compat.js");
928 importPackage(java.text);
929 importClass(java.text.SimpleDateFormat);
931 executor.logger.info("Task Execution: '"+executor.subject.id+"'. Input Fields: '"+executor.inFields+"'");
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"));
942 item_id = executor.inFields.get("item_ID");
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")));
947 var midnight_gmt = new Date(Number(executor.inFields.get("time")));
948 midnight_gmt.setUTCHours(0,0,0,0);
950 var eleven30_gmt = new Date(Number(executor.inFields.get("time")));
951 eleven30_gmt.setUTCHours(11,30,0,0);
953 var timeformatter = new java.text.SimpleDateFormat("HH:mm:ss z");
955 var itemisalcohol = false;
956 if(item_id != null && item_id >=1000 && item_id < 2000)
957 itemisalcohol = true;
960 && timenow_gmt.getTime() >= midnight_gmt.getTime()
961 && timenow_gmt.getTime() < eleven30_gmt.getTime()) {
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()));
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()));
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 :-)
983 .. container:: listingblock
987 MVEL code for the ``MorningBoozeCheck`` task
989 .. container:: content
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
1002 * http://www.apache.org/licenses/LICENSE-2.0
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.
1010 * SPDX-License-Identifier: Apache-2.0
1011 * ============LICENSE_END=========================================================
1013 import java.util.Date;
1014 import java.util.Calendar;
1015 import java.util.TimeZone;
1016 import java.text.SimpleDateFormat;
1018 logger.info("Task Execution: '"+subject.id+"'. Input Fields: '"+inFields+"'");
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"));
1029 item_id = inFields.get("item_ID");
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"));
1038 midnight = timenow.clone();
1040 timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
1041 timenow.get(Calendar.DATE),0,0,0);
1042 eleven30 = timenow.clone();
1044 timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
1045 timenow.get(Calendar.DATE),11,30,0);
1047 itemisalcohol = false;
1048 if(item_id != null && item_id >=1000 && item_id < 2000)
1049 itemisalcohol = true;
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()));
1061 outFields.put("authorised", true);
1062 outFields.put("message", "Sale authorised by policy task "+subject.taskName+
1063 " for time "+df.format(timenow.getTime()));
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 :-)
1075 .. container:: paragraph
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``).
1083 .. container:: paragraph
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
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).
1106 .. container:: paragraph
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):
1118 Table 1. The ``executor`` Fields / Methods
1120 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1121 | Name | Type | Java type | Description |
1122 +============+=============+================================+=====================================================================================+
1123 | inFields | Fields | java.util.Map <String,Object> | .. container:: paragraph |
1125 | | | | The incoming task fields. This is implemented as a standard Java |
1126 | | | | Java (unmodifiable) Map |
1128 | | | | .. container:: |
1130 | | | | .. container:: content |
1132 | | | | .. container:: paragraph |
1134 | | | | **Example:** |
1136 | | | | .. code:: javascript |
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 |
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 |
1149 | | | | .. container:: |
1151 | | | | .. container:: content |
1153 | | | | .. container:: paragraph |
1155 | | | | **Example:** |
1157 | | | | .. code:: javascript |
1159 | | | | executor.outFields["authorised"] = false; |
1160 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1161 | logger | Logger | org.slf4j.ext.XLogger | .. container:: paragraph |
1163 | | | | A helpful logger |
1165 | | | | .. container:: |
1167 | | | | .. container:: content |
1169 | | | | .. container:: paragraph |
1171 | | | | **Example:** |
1173 | | | | .. code:: javascript |
1175 | | | | executor.logger.info("Executing task: " |
1176 | | | | +executor.subject.id); |
1177 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1178 | TRUE/FALSE | boolean | java.lang.Boolean | .. container:: paragraph |
1180 | | | | 2 helpful constants. These are useful to retrieve correct return values for the |
1181 | | | | task logic |
1183 | | | | .. container:: |
1185 | | | | .. container:: content |
1187 | | | | .. container:: paragraph |
1189 | | | | **Example:** |
1191 | | | | .. code:: javascript |
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 |
1199 | | | | This provides some useful information about the task that contains this task |
1200 | | | | logic. This object has some useful fields and methods : |
1202 | | | | .. container:: ulist |
1204 | | | | - **AxTask task** to get access to the full task definition of |
1205 | | | | the host task |
1207 | | | | - **String getTaskName()** to get the name of the host task |
1209 | | | | - **String getId()** to get the ID of the host task |
1211 | | | | - **SchemaHelper getInFieldSchemaHelper( String fieldName )** to |
1212 | | | | get a ``SchemaHelper`` helper object to manipulate incoming |
1213 | | | | task fields in a schema-aware manner |
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 |
1221 | | | | .. container:: |
1223 | | | | .. container:: content |
1225 | | | | .. container:: paragraph |
1227 | | | | **Example:** |
1229 | | | | .. code:: javascript |
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 |
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. |
1255 | | .. container:: |
1257 | | .. container:: content |
1259 | | .. container:: paragraph |
1263 | | .. code:: javascript |
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 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1272 Writing APEX Task Selection Logic
1273 ---------------------------------
1275 .. container:: paragraph
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:
1286 .. container:: ulist
1288 - ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__,
1290 - ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__,
1292 - ```JRuby`` <https://en.wikipedia.org/wiki/JRuby>`__ or
1294 - ```Jython`` <https://en.wikipedia.org/wiki/Jython>`__.
1296 .. container:: paragraph
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!
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
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
1327 .. container:: paragraph
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
1334 .. container:: listingblock
1336 .. container:: title
1338 Javascript code for the "My First Policy" Task Selection Logic
1340 .. container:: content
1342 .. code:: javascript
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
1352 * http://www.apache.org/licenses/LICENSE-2.0
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.
1360 * SPDX-License-Identifier: Apache-2.0
1361 * ============LICENSE_END=========================================================
1365 var returnValueType = Java.type("java.lang.Boolean");
1366 var returnValue = new returnValueType(true);
1368 executor.logger.info("Task Selection Execution: '"+executor.subject.id+
1369 "'. Input Event: '"+executor.inFields+"'");
1371 branchid = executor.inFields.get("branch_ID");
1372 taskorig = executor.subject.getTaskKey("MorningBoozeCheck");
1373 taskalt = executor.subject.getTaskKey("MorningBoozeCheckAlt1");
1374 taskdef = executor.subject.getDefaultTaskKey();
1376 if(branchid >=0 && branchid <1000){
1377 taskorig.copyTo(executor.selectedTask);
1379 else if (branchid >=1000 && branchid <2000){
1380 taskalt.copyTo(executor.selectedTask);
1383 taskdef.copyTo(executor.selectedTask);
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"
1393 .. container:: paragraph
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).
1401 .. container:: paragraph
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
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).
1419 .. container:: paragraph
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):
1431 Table 2. The ``executor`` Fields / Methods
1432 +-------------------------------------------------------+--------------------------------------------------------+
1433 | Unix, Cygwin | Windows |
1434 +=======================================================+========================================================+
1435 | .. container:: | .. container:: |
1437 | .. container:: content | .. container:: content |
1439 | .. code:: bash | .. code:: bash |
1440 | :number-lines: | :number-lines: |
1442 | >c: | # cd /usr/local/src/apex-pdp |
1443 | >cd \dev\apex | # mvn clean install -DskipTest |
1444 | >mvn clean install -DskipTests | |
1445 +-------------------------------------------------------+--------------------------------------------------------+
1447 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1448 | Name | Type | Java type | Description |
1449 +============+=============+================================+=====================================================================================+
1450 | inFields | Fields | java.util.Map <String,Object> | .. container:: paragraph |
1452 | | | | All fields in the state’s incoming event. This is implemented as a standard Java |
1453 | | | | Java (unmodifiable) Map |
1455 | | | | .. container:: |
1457 | | | | .. container:: content |
1459 | | | | .. container:: paragraph |
1461 | | | | **Example:** |
1463 | | | | .. code:: javascript |
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 |
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 |
1476 | | | | .. container:: |
1478 | | | | .. container:: content |
1480 | | | | .. container:: paragraph |
1482 | | | | **Example:** |
1484 | | | | .. code:: javascript |
1486 | | | | executor.outFields["authorised"] = false; |
1487 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1488 | logger | Logger | org.slf4j.ext.XLogger | .. container:: paragraph |
1490 | | | | A helpful logger |
1492 | | | | .. container:: |
1494 | | | | .. container:: content |
1496 | | | | .. container:: paragraph |
1498 | | | | **Example:** |
1500 | | | | .. code:: javascript |
1502 | | | | executor.logger.info("Executing task: " |
1503 | | | | +executor.subject.id); |
1504 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1505 | TRUE/FALSE | boolean | java.lang.Boolean | .. container:: paragraph |
1507 | | | | 2 helpful constants. These are useful to retrieve correct return values for the |
1508 | | | | task logic |
1510 | | | | .. container:: |
1512 | | | | .. container:: content |
1514 | | | | .. container:: paragraph |
1516 | | | | **Example:** |
1518 | | | | .. code:: javascript |
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 |
1526 | | | | This provides some useful information about the task that contains this task |
1527 | | | | logic. This object has some useful fields and methods : |
1529 | | | | .. container:: ulist |
1531 | | | | - **AxTask task** to get access to the full task definition of |
1532 | | | | the host task |
1534 | | | | - **String getTaskName()** to get the name of the host task |
1536 | | | | - **String getId()** to get the ID of the host task |
1538 | | | | - **SchemaHelper getInFieldSchemaHelper( String fieldName )** to |
1539 | | | | get a ``SchemaHelper`` helper object to manipulate incoming |
1540 | | | | task fields in a schema-aware manner |
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 |
1548 | | | | .. container:: |
1550 | | | | .. container:: content |
1552 | | | | .. container:: paragraph |
1554 | | | | **Example:** |
1556 | | | | .. code:: javascript |
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 |
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. |
1582 | | .. container:: |
1584 | | .. container:: content |
1586 | | .. container:: paragraph |
1590 | | .. code:: javascript |
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 +------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1602 .. container:: paragraph
1604 Examples given here use Javascript (if not stated otherwise),
1605 other execution environments will be similar.
1610 .. container:: paragraph
1612 First line in the logic use this import.
1614 .. container:: listingblock
1616 .. container:: title
1620 .. container:: content
1622 .. code:: javascript
1624 load("nashorn:mozilla_compat.js");
1626 Finish Logic with Success or Error
1627 ##################################
1629 .. container:: paragraph
1631 To finish logic, i.e. return to APEX, with success use the
1632 following lines close to the end of the logic.
1634 .. container:: listingblock
1636 .. container:: title
1640 .. container:: content
1642 .. code:: javascript
1644 var returnValueType = Java.type("java.lang.Boolean");
1645 var returnValue = new returnValueType(true);
1647 .. container:: paragraph
1649 To notify a problem, finish with an error.
1651 .. container:: listingblock
1653 .. container:: title
1657 .. container:: content
1659 .. code:: javascript
1661 var returnValueType = Java.type("java.lang.Boolean");
1662 var returnValue = new returnValueType(false);
1667 .. container:: paragraph
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.
1673 .. container:: listingblock
1675 .. container:: title
1679 .. container:: content
1681 .. code:: javascript
1683 var logger = executor.logger;
1684 logger.trace("start: " + executor.subject.id);
1685 logger.trace("-- infields: " + executor.inFields);
1687 .. container:: paragraph
1689 For larger logging blocks you can use the standard logging API
1690 to detect log levels, for instance:
1692 .. container:: listingblock
1694 .. container:: title
1698 .. container:: content
1700 .. code:: javascript
1702 if(logger.isTraceEnabled()){
1703 // trace logging block here
1706 .. container:: paragraph
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``.
1713 .. container:: paragraph
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.
1719 .. container:: listingblock
1721 .. container:: title
1725 .. container:: content
1727 .. code:: javascript
1729 importClass(org.slf4j.LoggerFactory);
1730 var rootLogger = LoggerFactory.getLogger(logger.ROOT_LOGGER_NAME);
1732 rootLogger.error("Serious error in logic detected: " + executor.subject.id);
1734 Local Variable for Infields
1735 ###########################
1737 .. container:: paragraph
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``.
1743 .. container:: listingblock
1745 .. container:: title
1747 JS Infields Local Var
1749 .. container:: content
1751 .. code:: javascript
1753 var ifNodeName = executor.inFields["nodeName"];
1754 var ifNodeAlias = executor.inFields["nodeAlias"];
1756 Local Variable for Context Albums
1757 #################################
1759 .. container:: paragraph
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
1767 .. container:: listingblock
1769 .. container:: title
1771 JS Infields Local Var
1773 .. container:: content
1775 .. code:: javascript
1777 var albumTopoNodes = executor.getContextAlbum("albumTopoNodes");
1778 var ctxtNode = albumTopoNodes.get(ifNodeName);
1780 Set Outfields in Logic
1781 ######################
1783 .. container:: paragraph
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.
1789 .. container:: listingblock
1791 .. container:: title
1795 .. container:: content
1797 .. code:: javascript
1799 executor.outFields["report"] = "node ctxt :: added node " + ifNodeName;
1801 Create a instance of an Outfield using Schemas
1802 ##############################################
1804 .. container:: paragraph
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>`__.
1814 .. container:: paragraph
1816 If the backend is Avro, then an import of the Avro schema
1817 library is required:
1819 .. container:: listingblock
1821 .. container:: title
1825 .. container:: content
1827 .. code:: javascript
1829 importClass(org.apache.avro.generic.GenericData.Array);
1830 importClass(org.apache.avro.generic.GenericRecord);
1831 importClass(org.apache.avro.Schema);
1833 .. container:: paragraph
1835 If the backend is Java, then the Java class implementing the
1836 schema needs to be imported.
1838 .. container:: paragraph
1840 The following example assumes an outfield ``situation``. The
1841 ``subject`` method ``getOutFieldSchemaHelper()`` is used to
1842 create a new instance.
1844 .. container:: listingblock
1846 .. container:: title
1848 JS Outfield Instance with Schema
1850 .. container:: content
1852 .. code:: javascript
1854 var situation = executor.subject.getOutFieldSchemaHelper("situation").createNewInstance();
1856 .. container:: paragraph
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.
1865 .. container:: listingblock
1867 .. container:: title
1869 JS Outfield Instance with Schema, set
1871 .. container:: content
1873 .. code:: javascript
1875 situation.put("problemID", "my-problem");
1877 Create a instance of an Context Album entry using Schemas
1878 #########################################################
1880 .. container:: paragraph
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>`__.
1888 .. container:: paragraph
1890 If the backend is Avro, then an import of the Avro schema
1891 library is required:
1893 .. container:: listingblock
1895 .. container:: title
1899 .. container:: content
1901 .. code:: javascript
1903 importClass(org.apache.avro.generic.GenericData.Array);
1904 importClass(org.apache.avro.generic.GenericRecord);
1905 importClass(org.apache.avro.Schema);
1907 .. container:: paragraph
1909 If the backend is Java, then the Java class implementing the
1910 schema needs to be imported.
1912 .. container:: paragraph
1914 The following example creates a new instance of a context album
1915 instance named ``albumProblemMap``.
1917 .. container:: listingblock
1919 .. container:: title
1921 JS Outfield Instance with Schema
1923 .. container:: content
1925 .. code:: javascript
1927 var albumProblemMap = executor.getContextAlbum("albumProblemMap");
1928 var linkProblem = albumProblemMap.getSchemaHelper().createNewInstance();
1930 .. container:: paragraph
1932 This can of course be also done in a single call without the
1933 local variable for the context album.
1935 .. container:: listingblock
1937 .. container:: title
1939 JS Outfield Instance with Schema, one line
1941 .. container:: content
1943 .. code:: javascript
1945 var linkProblem = executor.getContextAlbum("albumProblemMap").getSchemaHelper().createNewInstance();
1947 .. container:: paragraph
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).
1958 .. container:: paragraph
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
1965 .. container:: listingblock
1967 .. container:: title
1969 Avro Enumerate Schema
1971 .. container:: content
1973 .. code:: javascript
1984 .. container:: paragraph
1986 Using a switch over a field initialized with this enumerate in
1987 Javascript will fail. Instead, use the ``toString`` method, for
1990 .. container:: listingblock
1992 .. container:: title
1994 JS Outfield Instance with Schema, one line
1996 .. container:: content
1998 .. code:: javascript
2000 var switchTest = executor.inFields["status"];
2001 switch(switchTest.toString()){
2002 case "UP": ...; break;
2003 case "DOWN": ...; break;
2007 MVEL Initialize Outfields First!
2008 ################################
2010 .. container:: paragraph
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.
2017 .. container:: listingblock
2019 .. container:: title
2021 MVEL Outfield Initialization
2023 .. container:: content
2025 .. code:: javascript
2027 outFields.get("initialize outfields");
2029 Using Java in Scripting Logic
2030 #############################
2032 .. container:: paragraph
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
2039 .. container:: paragraph
2041 The following example imports ``java.util.arraylist`` into a
2042 Javascript logic, and then creates a new list.
2044 .. container:: listingblock
2046 .. container:: title
2050 .. container:: content
2052 .. code:: javascript
2054 importClass(java.util.ArrayList);
2055 var myList = new ArrayList();
2063 .. container:: paragraph
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:
2071 .. container:: ulist
2073 - `My-First-Policy on the APEX
2074 site <https://ericsson.github.io/apex-docs/modules/examples/examples-myfirstpolicy/MyFirstPolicyHowto.html>`__
2077 HTML <https://ericsson.github.io/apex-docs/docs-apex/html/HowTo-MyFirstPolicy.html>`__
2080 PDF <https://ericsson.github.io/apex-docs/docs-apex/pdf/HowTo-MyFirstPolicy.pdf>`__
2085 .. container:: paragraph
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:
2098 .. container:: ulist
2100 - `VPN SLA Policy on the APEX
2101 site <https://ericsson.github.io/apex-docs/modules/examples/examples-pcvs/vpnsla/policy.html>`__
2106 .. container:: paragraph
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:
2116 .. container:: ulist
2118 - `Decision Maker on APEX
2119 site <https://ericsson.github.io/apex-docs/modules/examples/examples-decisionmaker/index.html>`__
2128 Last updated 2018-09-04 16:04:24 IST
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