blob: cb2388e01b3e9b40e283a0bbd21d907396831a7b [file] [log] [blame]
ramverma3b71c972019-07-10 11:25:37 +00001.. This work is licensed under a Creative Commons Attribution 4.0 International License.
2.. http://creativecommons.org/licenses/by/4.0
3
4
5APEX Policy Guide
6*****************************
7
8.. contents::
9 :depth: 3
10
11APEX Policy Matrix
12^^^^^^^^^^^^^^^^^^
13
14APEX 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
ramverma760cce92019-07-11 12:57:49 +000021 supports virtually any policy model and supports
22 translation of legacy policies into the APEX execution format.
ramverma3b71c972019-07-10 11:25:37 +000023 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 its 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
204APEX Policy Model
205^^^^^^^^^^^^^^^^^
206
207Introduction
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
268Concepts 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 concepts *Version*.
334 A concepts 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
373Concept: 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
397Concept: 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
415Concept: 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
450Concept: 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
466Concept: 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
562Concept: 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
579Concept: 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
600Concept: 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
651Concept: 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
a.sreekumarcc0e9172020-03-16 13:36:45 +0000667 .. container:: paragraph
668
669 The *taskParameters* field is specified under *engineParameters*
670 in the ApexConfig. It can contain one or more task parameters, where each
671 item can contain the parameter key, value as well as the taskId to which it is associated.
672 If the taskId is not specified, then the parameters are added to all tasks.
673
ramverma3b71c972019-07-10 11:25:37 +0000674Concept: Logic
675##############
676
677 .. container:: paragraph
678
679 The *Logic* concept instance holds the actual
680 programmed task logic for a task defined in a *Task*
681 concept or the programmed task selection logic for a
682 state defined in a *State* concept. It is keyed with a
683 ``ReferenceKey`` key, which references the task or
684 state that owns the logic. The *LocalName* field of
685 the Logic concept is the name of the logic.
686
687 .. container:: paragraph
688
689 The *LogicCode* field of a Logic concept definition is
690 a string that holds the program code that is to be
691 executed at run time. The *LogicType* field defines
692 the language of the code. The standard values are the
693 logic languages supported by APEX:
694 `JAVASCRIPT <https://en.wikipedia.org/wiki/JavaScript>`__,
695 `JAVA <https://java.com/en/>`__,
696 `JYTHON <http://www.jython.org/>`__,
697 `JRUBY <http://jruby.org/>`__, or
698 `MVEL <https://en.wikibooks.org/wiki/Transwiki:MVEL_Language_Guide>`__.
699
700 .. container:: paragraph
701
702 The APEX engine uses the *LogicType* field value to
703 decide which language interpreter to use for a task
704 and then sends the logic defined in the *LogicCode*
705 field to that interpreter.
706
707Concept: Policy
708###############
709
710 .. container:: paragraph
711
712 The *Policy* concept defines a policy in APEX. The
713 definition is rather straightforward. A policy is made
714 up of a set of states with the flavor of the policy
715 determining the structure of the policy states and the
716 first state defining what state in the policy executes
717 first. *Policy* concepts are keyed with an
718 ``ArtifactKey`` key.
719
720 .. container:: paragraph
721
722 The *PolicyFlavour* of a *Policy* concept specifies
723 the structure that will be used for the states in the
724 policy. A number of commonly used policy patterns are
725 supported as APEX policy flavors. The standard policy
726 flavors are:
727
728 .. container:: ulist
729
730 - The *MEDA* flavor supports policies written to the
731 `MEDA policy
732 pattern <https://www.researchgate.net/publication/282576518_Dynamically_Adaptive_Policies_for_Dynamically_Adaptive_Telecommunications_Networks>`__
733 and require a sequence of four states: namely
734 *Match*, *Establish*, *Decide* and *Act*.
735
736 - The *OODA* flavor supports policies written to the
737 `OODA loop
738 pattern <https://en.wikipedia.org/wiki/OODA_loop>`__
739 and require a sequence of four states: namely
740 *Observe*, *Orient*, *Decide* and *Act*.
741
742 - The *ECA* flavor supports policies written to the
743 `ECA active rule
744 pattern <https://en.wikipedia.org/wiki/Event_condition_action>`__
745 and require a sequence of three states: namely
746 *Event*, *Condition* and *Action*
747
748 - The *XACML* flavor supports policies written in
749 `XACML <https://en.wikipedia.org/wiki/XACML>`__ and
750 require a single state: namely *XACML*
751
752 - The *FREEFORM* flavor supports policies written in
753 an arbitrary style. A user can define a *FREEFORM*
754 policy as an arbitrarily long chain of states.
755
756 .. container:: paragraph
757
758 The *FirstState* field of a *Policy* definition is the
759 starting point for execution of a policy. Therefore,
760 the trigger event of the state referenced in the
761 *FirstState* field is also the trigger event for the
762 entire policy.
763
764Concept: State
765##############
766
767 .. container:: paragraph
768
769 The *State* concept represents a phase or a stage in a
770 policy, with a policy being composed of a series of
771 states. Each state has at least one but may have many
772 tasks and, on each run of execution, a state executes
773 one and only one of its tasks. If a state has more
774 than one task, then its task selection logic is used
775 to select which task to execute. Task selection logic
776 is programmable logic provided by the state designer.
777 That logic can use incoming, policy, global, and
778 external context to select which task best
779 accomplishes the purpose of the state in a give
780 situation if more than one task has been specified on
781 a state. A state calls one and only one task when it
782 is executed.
783
784 .. container:: paragraph
785
786 Each state is triggered by an event, which means that
787 all tasks of a state must also be triggered by that
788 same event. The set of output events for a state is
789 the union of all output events from all tasks for that
790 task. In practice at the moment, because a state can
791 only have a single input event, a state that is not
792 the final state of a policy may only output a single
793 event and all tasks of that state may also only output
794 that single event. In future work, the concept of
795 having a less restrictive trigger pattern will be
796 examined.
797
798 .. container:: paragraph
799
800 A *State* concept is keyed with a ``ReferenceKey``
801 key, which references the *Policy* concept that owns
802 the state. The *LocalName* field of the
803 ``ReferenceKey`` holds the name of the state. As a
804 state is part of a chain of states, the *NextState*
805 field of a state holds the ``ReferenceKey`` key of the
806 state in the policy to execute after this state.
807
808 .. container:: paragraph
809
810 The *Trigger* field of a state holds the
811 ``ArtifactKey`` of the event that triggers this state.
812 The *OutgoingEvents* field holds the ``ArtifactKey``
813 references of all possible events that may be output
814 from the state. This is a set that is the union of all
815 output events of all tasks of the state.
816
817 .. container:: paragraph
818
819 The *Task* concepts that hold the definitions of the
820 task for the state are held as a set of
821 ``ArtifactKey`` references in the state. The
822 *DefaultTask* field holds a reference to the default
823 task for the state, a task that is executed if no task
824 selection logic is specified. If the state has only
825 one task, that task is the default task.
826
827 .. container:: paragraph
828
829 The *Logic* concept referenced by a state holds the
830 task selection logic for a state. The task selection
831 logic uses the incoming context (parameters of the
832 incoming event) and other context to determine the
833 best task to use to execute its goals. The state holds
834 a set of references to *ContextItem* and
835 *ContextItemTemplate* definitions for the context used
836 by its task selection logic.
837
838Writing Logic
839^^^^^^^^^^^^^
840
841Writing APEX Task Logic
842-----------------------
843
844 .. container:: paragraph
845
846 Task logic specifies the behavior of an Apex Task. This
847 logic can be specified in a number of ways, exploiting
848 Apexs plug-in architecture to support a range of logic
849 executors. In Apex scripted Task Logic can be written in
850 any of these languages:
851
852 .. container:: ulist
853
854 - ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__,
855
856 - ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__,
857
858 - ```JRuby`` <https://en.wikipedia.org/wiki/JRuby>`__ or
859
860 - ```Jython`` <https://en.wikipedia.org/wiki/Jython>`__.
861
862 .. container:: paragraph
863
864 These languages were chosen because the scripts can be
865 compiled into Java bytecode at runtime and then
866 efficiently executed natively in the JVM. Task Logic an
867 also be written directly in Java but needs to be
868 compiled, with the resulting classes added to the
869 classpath. There are also a number of other Task Logic
870 types (e.g. Fuzzy Logic), but these are not supported as
871 yet. This guide will focus on the scripted Task Logic
872 approaches, with MVEL and JavaScript being our favorite
873 languages. In particular this guide will focus on the
874 Apex aspects of the scripts. However, this guide does not
875 attempt to teach you about the scripting languages
876 themselves …​ that is up to you!
877
ramverma760cce92019-07-11 12:57:49 +0000878 .. tip::
879 JVM-based scripting languages
880 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
ramverma3b71c972019-07-10 11:25:37 +0000881
ramverma760cce92019-07-11 12:57:49 +0000882 .. note::
883 What do Tasks do?
884 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
885 an Apex Policy. Each task receives some *incoming fields*, executes some logic (e.g: make a decision based on
886 *shared state* or *context*, *incoming fields*, *external context*, etc.), perhaps set some *shared state* or
887 *context* and then emits *outgoing fields*. The state that uses the task is responsible for extracting the
888 *incoming fields* from the state input event. The state also has an *output mapper* associated with the task, and
889 this *output mapper* is responsible for mapping the *outgoing fields* from the task into an appropriate
890 output event for the state.
ramverma3b71c972019-07-10 11:25:37 +0000891
892 .. container:: paragraph
893
894 First lets start with a sample task, drawn from the "My
895 First Apex Policy" example: The task "MorningBoozeCheck"
896 from the "My First Apex Policy" example is available in
897 both MVEL and JavaScript:
898
899 .. container:: listingblock
900
901 .. container:: title
902
903 Javascript code for the ``MorningBoozeCheck`` task
904
905 .. container:: content
906
907 .. code:: javascript
908 :number-lines:
909
910 /*
911 * ============LICENSE_START=======================================================
912 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
913 * ================================================================================
914 * Licensed under the Apache License, Version 2.0 (the "License");
915 * you may not use this file except in compliance with the License.
916 * You may obtain a copy of the License at
917 *
918 * http://www.apache.org/licenses/LICENSE-2.0
919 *
920 * Unless required by applicable law or agreed to in writing, software
921 * distributed under the License is distributed on an "AS IS" BASIS,
922 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
923 * See the License for the specific language governing permissions and
924 * limitations under the License.
925 *
926 * SPDX-License-Identifier: Apache-2.0
927 * ============LICENSE_END=========================================================
928 */
929
930 var returnValueType = Java.type("java.lang.Boolean");
931 var returnValue = new returnValueType(true);
932
933 // Load compatibility script for imports etc
934 load("nashorn:mozilla_compat.js");
935 importPackage(java.text);
936 importClass(java.text.SimpleDateFormat);
937
938 executor.logger.info("Task Execution: '"+executor.subject.id+"'. Input Fields: '"+executor.inFields+"'");
939
940 executor.outFields.put("amount" , executor.inFields.get("amount"));
941 executor.outFields.put("assistant_ID", executor.inFields.get("assistant_ID"));
942 executor.outFields.put("notes" , executor.inFields.get("notes"));
943 executor.outFields.put("quantity" , executor.inFields.get("quantity"));
944 executor.outFields.put("branch_ID" , executor.inFields.get("branch_ID"));
945 executor.outFields.put("item_ID" , executor.inFields.get("item_ID"));
946 executor.outFields.put("time" , executor.inFields.get("time"));
947 executor.outFields.put("sale_ID" , executor.inFields.get("sale_ID"));
948
949 item_id = executor.inFields.get("item_ID");
950
951 //All times in this script are in GMT/UTC since the policy and events assume time is in GMT.
952 var timenow_gmt = new Date(Number(executor.inFields.get("time")));
953
954 var midnight_gmt = new Date(Number(executor.inFields.get("time")));
955 midnight_gmt.setUTCHours(0,0,0,0);
956
957 var eleven30_gmt = new Date(Number(executor.inFields.get("time")));
958 eleven30_gmt.setUTCHours(11,30,0,0);
959
960 var timeformatter = new java.text.SimpleDateFormat("HH:mm:ss z");
961
962 var itemisalcohol = false;
963 if(item_id != null && item_id >=1000 && item_id < 2000)
964 itemisalcohol = true;
965
966 if( itemisalcohol
967 && timenow_gmt.getTime() >= midnight_gmt.getTime()
968 && timenow_gmt.getTime() < eleven30_gmt.getTime()) {
969
970 executor.outFields.put("authorised", false);
971 executor.outFields.put("message", "Sale not authorised by policy task " +
972 executor.subject.taskName+ " for time " + timeformatter.format(timenow_gmt.getTime()) +
973 ". Alcohol can not be sold between " + timeformatter.format(midnight_gmt.getTime()) +
974 " and " + timeformatter.format(eleven30_gmt.getTime()));
975 }
976 else{
977 executor.outFields.put("authorised", true);
978 executor.outFields.put("message", "Sale authorised by policy task " +
979 executor.subject.taskName + " for time "+timeformatter.format(timenow_gmt.getTime()));
980 }
981
982 /*
983 This task checks if a sale request is for an item that is an alcoholic drink.
984 If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
985 authorised. Otherwise the sale is authorised.
986 In this implementation we assume that items with item_ID value between 1000 and
987 2000 are all alcoholic drinks :-)
988 */
989
990 .. container:: listingblock
991
992 .. container:: title
993
994 MVEL code for the ``MorningBoozeCheck`` task
995
996 .. container:: content
997
ramverma760cce92019-07-11 12:57:49 +0000998 .. code:: javascript
ramverma3b71c972019-07-10 11:25:37 +0000999 :number-lines:
1000
1001 /*
1002 * ============LICENSE_START=======================================================
1003 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
1004 * ================================================================================
1005 * Licensed under the Apache License, Version 2.0 (the "License");
1006 * you may not use this file except in compliance with the License.
1007 * You may obtain a copy of the License at
1008 *
1009 * http://www.apache.org/licenses/LICENSE-2.0
1010 *
1011 * Unless required by applicable law or agreed to in writing, software
1012 * distributed under the License is distributed on an "AS IS" BASIS,
1013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1014 * See the License for the specific language governing permissions and
1015 * limitations under the License.
1016 *
1017 * SPDX-License-Identifier: Apache-2.0
1018 * ============LICENSE_END=========================================================
1019 */
1020 import java.util.Date;
1021 import java.util.Calendar;
1022 import java.util.TimeZone;
1023 import java.text.SimpleDateFormat;
1024
1025 logger.info("Task Execution: '"+subject.id+"'. Input Fields: '"+inFields+"'");
1026
1027 outFields.put("amount" , inFields.get("amount"));
1028 outFields.put("assistant_ID", inFields.get("assistant_ID"));
1029 outFields.put("notes" , inFields.get("notes"));
1030 outFields.put("quantity" , inFields.get("quantity"));
1031 outFields.put("branch_ID" , inFields.get("branch_ID"));
1032 outFields.put("item_ID" , inFields.get("item_ID"));
1033 outFields.put("time" , inFields.get("time"));
1034 outFields.put("sale_ID" , inFields.get("sale_ID"));
1035
1036 item_id = inFields.get("item_ID");
1037
1038 //The events used later to test this task use GMT timezone!
1039 gmt = TimeZone.getTimeZone("GMT");
1040 timenow = Calendar.getInstance(gmt);
1041 df = new SimpleDateFormat("HH:mm:ss z");
1042 df.setTimeZone(gmt);
1043 timenow.setTimeInMillis(inFields.get("time"));
1044
1045 midnight = timenow.clone();
1046 midnight.set(
1047 timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
1048 timenow.get(Calendar.DATE),0,0,0);
1049 eleven30 = timenow.clone();
1050 eleven30.set(
1051 timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
1052 timenow.get(Calendar.DATE),11,30,0);
1053
1054 itemisalcohol = false;
1055 if(item_id != null && item_id >=1000 && item_id < 2000)
1056 itemisalcohol = true;
1057
1058 if( itemisalcohol
1059 && timenow.after(midnight) && timenow.before(eleven30)){
1060 outFields.put("authorised", false);
1061 outFields.put("message", "Sale not authorised by policy task "+subject.taskName+
1062 " for time "+df.format(timenow.getTime())+
1063 ". Alcohol can not be sold between "+df.format(midnight.getTime())+
1064 " and "+df.format(eleven30.getTime()));
1065 return true;
1066 }
1067 else{
1068 outFields.put("authorised", true);
1069 outFields.put("message", "Sale authorised by policy task "+subject.taskName+
1070 " for time "+df.format(timenow.getTime()));
1071 return true;
1072 }
1073
1074 /*
1075 This task checks if a sale request is for an item that is an alcoholic drink.
1076 If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
1077 authorised. Otherwise the sale is authorised.
1078 In this implementation we assume that items with item_ID value between 1000 and
1079 2000 are all alcoholic drinks :-)
1080 */
1081
1082 .. container:: paragraph
1083
1084 The role of the task in this simple example is to copy
1085 the values in the incoming fields into the outgoing
1086 fields, then examine the values in some incoming fields
1087 (``item_id`` and ``time``), then set the values in some
1088 other outgoing fields (``authorised`` and ``message``).
1089
1090 .. container:: paragraph
1091
1092 Both MVEL and JavaScript like most JVM-based scripting
1093 languages can use standard Java libraries to perform
1094 complex tasks. Towards the top of the scripts you will
1095 see how to import Java classes and packages to be used
1096 directly in the logic. Another thing to notice is that
1097 Task Logic should return a ``java.lang.Boolean`` value
1098 ``true`` if the logic executed correctly. If the logic
1099 fails for some reason then ``false`` can be returned, but
1100 this will cause the policy invoking this task will fail
1101 and exit.
1102
1103 .. note::
ramverma760cce92019-07-11 12:57:49 +00001104 How to return a value from task logic
1105 Some languages explicitly support returning values from the script (e.g. MVEL and JRuby) using an explicit
1106 return statement (e.g. ``return true``), other languages do not (e.g. JavaScript and Jython). For
1107 languages that do not support the ``return`` statement, a special field called ``returnValue`` must be
1108 created to hold the result of the task logic operation (i.e. assign a ``java.lang.Boolean``
1109 value to the ``returnValue`` field before completing the task).
1110 Also, in MVEL if there is no explicit return statement then the return value of the last executed statement will return
1111 (e.g. the statement a=(1+2) will return the value 3).
ramverma3b71c972019-07-10 11:25:37 +00001112
1113 .. container:: paragraph
1114
1115 Besides these imported classes and normal language
1116 features Apex provides some natively available parameters
1117 and functions that can be used directly. At run-time
1118 these parameters are populated by the Apex execution
1119 environment and made natively available to logic scripts
1120 each time the logic script is invoked. (These can be
1121 accessed using the ``executor`` keyword for most
1122 languages, or can be accessed directly without the
1123 ``executor`` keyword in MVEL):
1124
1125 Table 1. The ``executor`` Fields / Methods
ramverma760cce92019-07-11 12:57:49 +00001126
ramverma3b71c972019-07-10 11:25:37 +00001127+------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1128| Name | Type | Java type | Description |
1129+============+=============+================================+=====================================================================================+
1130| inFields | Fields | java.util.Map <String,Object> | .. container:: paragraph |
1131| | | | |
1132| | | | The incoming task fields. This is implemented as a standard Java |
1133| | | | Java (unmodifiable) Map |
1134| | | | |
1135| | | | .. container:: |
1136| | | | |
1137| | | | .. container:: content |
1138| | | | |
1139| | | | .. container:: paragraph |
1140| | | | |
1141| | | | **Example:** |
1142| | | | |
1143| | | | .. code:: javascript |
1144| | | | |
1145| | | | executor.logger.debug("Incoming fields: " |
1146| | | | +executor.inFields.entrySet()); |
1147| | | | var item_id = executor.incomingFields["item_ID"]; |
1148| | | | if (item_id >=1000) { ... } |
1149+------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1150| outFields | Fields | java.util.Map <String,Object> | .. container:: paragraph |
1151| | | | |
1152| | | | The outgoing task fields. This is implemented as a standard initially empty Java |
1153| | | | (modifiable) Map. To create a new schema-compliant instance of a field object |
1154| | | | see the utility method subject.getOutFieldSchemaHelper() below |
1155| | | | |
1156| | | | .. container:: |
1157| | | | |
1158| | | | .. container:: content |
1159| | | | |
1160| | | | .. container:: paragraph |
1161| | | | |
1162| | | | **Example:** |
1163| | | | |
1164| | | | .. code:: javascript |
1165| | | | |
1166| | | | executor.outFields["authorised"] = false; |
1167+------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1168| logger | Logger | org.slf4j.ext.XLogger | .. container:: paragraph |
1169| | | | |
1170| | | | A helpful logger |
1171| | | | |
1172| | | | .. container:: |
1173| | | | |
1174| | | | .. container:: content |
1175| | | | |
1176| | | | .. container:: paragraph |
1177| | | | |
1178| | | | **Example:** |
1179| | | | |
1180| | | | .. code:: javascript |
1181| | | | |
1182| | | | executor.logger.info("Executing task: " |
1183| | | | +executor.subject.id); |
1184+------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1185| TRUE/FALSE | boolean | java.lang.Boolean | .. container:: paragraph |
1186| | | | |
1187| | | | 2 helpful constants. These are useful to retrieve correct return values for the |
1188| | | | task logic |
1189| | | | |
1190| | | | .. container:: |
1191| | | | |
1192| | | | .. container:: content |
1193| | | | |
1194| | | | .. container:: paragraph |
1195| | | | |
1196| | | | **Example:** |
1197| | | | |
1198| | | | .. code:: javascript |
1199| | | | |
1200| | | | var returnValue = executor.isTrue; |
1201| | | | var returnValueType = Java.type("java.lang.Boolean"); |
1202| | | | var returnValue = new returnValueType(true); |
1203+------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1204| subject | Task | TaskFacade | .. container:: paragraph |
1205| | | | |
1206| | | | This provides some useful information about the task that contains this task |
1207| | | | logic. This object has some useful fields and methods : |
1208| | | | |
1209| | | | .. container:: ulist |
1210| | | | |
1211| | | | - **AxTask task** to get access to the full task definition of |
1212| | | | the host task |
1213| | | | |
1214| | | | - **String getTaskName()** to get the name of the host task |
1215| | | | |
1216| | | | - **String getId()** to get the ID of the host task |
1217| | | | |
1218| | | | - **SchemaHelper getInFieldSchemaHelper( String fieldName )** to |
1219| | | | get a ``SchemaHelper`` helper object to manipulate incoming |
1220| | | | task fields in a schema-aware manner |
1221| | | | |
1222| | | | - **SchemaHelper getOutFieldSchemaHelper( String fieldName )** to |
1223| | | | get a ``SchemaHelper`` helper object to manipulate outgoing |
1224| | | | task fields in a schema-aware manner, e.g. to instantiate new |
1225| | | | schema-compliant field objects to populate the |
1226| | | | ``executor.outFields`` outgoing fields map |
1227| | | | |
1228| | | | .. container:: |
1229| | | | |
1230| | | | .. container:: content |
1231| | | | |
1232| | | | .. container:: paragraph |
1233| | | | |
1234| | | | **Example:** |
1235| | | | |
1236| | | | .. code:: javascript |
1237| | | | |
1238| | | | executor.logger.info("Task name: " |
1239| | | | +executor.subject.getTaskName()); |
1240| | | | executor.logger.info("Task id: " |
1241| | | | +executor.subject.getId()); |
1242| | | | executor.logger.info("Task inputs definitions: " |
1243| | | | +"executor.subject.task.getInputFieldSet()); |
1244| | | | executor.logger.info("Task outputs definitions: " |
1245| | | | +"executor.subject.task.getOutputFieldSet()); |
1246| | | | executor.outFields["authorised"] = executor.subject |
1247| | | | .getOutFieldSchemaHelper("authorised") |
1248| | | | .createNewInstance("false"); |
1249+------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1250| ContextAlbum getContextAlbum(String ctxtAlbumName ) | .. container:: paragraph |
1251| | |
1252| | A utility method to retrieve a ``ContextAlbum`` for use in the task. |
1253| | This is how you access the context used by the task. The returned |
1254| | ``ContextAlbum`` implements the ``java.util.Map <String,Object>`` |
1255| | interface to get and set context as appropriate. The returned |
1256| | ``ContextAlbum`` also has methods to lock context albums, get |
1257| | information about the schema of the items to be stored in a context |
1258| | album, and get a ``SchemaHelper`` to manipulate context album items. How |
1259| | to define and use context in a task is described in the Apex |
1260| | Programmers Guide and in the My First Apex Policy guide. |
1261| | |
1262| | .. container:: |
1263| | |
1264| | .. container:: content |
1265| | |
1266| | .. container:: paragraph |
1267| | |
1268| | **Example:** |
1269| | |
1270| | .. code:: javascript |
1271| | |
1272| | var bkey = executor.inFields.get("branch_ID"); |
1273| | var cnts = executor.getContextMap("BranchCounts"); |
1274| | cnts.lockForWriting(bkey); |
1275| | cnts.put(bkey, cnts.get(bkey) + 1); |
1276| | cnts.unlockForWriting(bkey); |
1277+------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1278
1279Writing APEX Task Selection Logic
1280---------------------------------
1281
1282 .. container:: paragraph
1283
1284 The function of Task Selection Logic is to choose which task
1285 should be executed for an Apex State as one of the steps in an
1286 Apex Policy. Since each state must define a default task there is
1287 no need for Task Selection Logic unless the state uses more than
1288 one task. This logic can be specified in a number of ways,
1289 exploiting Apexs plug-in architecture to support a range of logic
1290 executors. In Apex scripted Task Selection Logic can be written in
1291 any of these languages:
1292
1293 .. container:: ulist
1294
1295 - ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__,
1296
1297 - ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__,
1298
1299 - ```JRuby`` <https://en.wikipedia.org/wiki/JRuby>`__ or
1300
1301 - ```Jython`` <https://en.wikipedia.org/wiki/Jython>`__.
1302
1303 .. container:: paragraph
1304
1305 These languages were chosen because the scripts can be compiled
1306 into Java bytecode at runtime and then efficiently executed
1307 natively in the JVM. Task Selection Logic an also be written
1308 directly in Java but needs to be compiled, with the resulting
1309 classes added to the classpath. There are also a number of other
1310 Task Selection Logic types but these are not supported as yet.
1311 This guide will focus on the scripted Task Selection Logic
1312 approaches, with MVEL and JavaScript being our favorite languages.
1313 In particular this guide will focus on the Apex aspects of the
1314 scripts. However, this guide does not attempt to teach you about
1315 the scripting languages themselves …​ that is up to you!
1316
1317 .. tip::
ramverma760cce92019-07-11 12:57:49 +00001318 JVM-based scripting languages
1319 For more more information on Scripting for the Java platform see:
1320 https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/index.html
ramverma3b71c972019-07-10 11:25:37 +00001321
ramverma760cce92019-07-11 12:57:49 +00001322 .. note::
1323 What does Task Selection Logic do?
1324 When an Apex state references multiple tasks, there must be a way to dynamically decide
1325 which task should be chosen and executed. This can depend on the many factors, e.g. the
1326 *incoming event for the state*, *shared state* or *context*, *external context*,
1327 etc.. This is the function of a states Task Selection Logic. Obviously, if there is
1328 only one task then Task only one task then Task Selection Logic is not needed.
1329 Each state must also select one of the tasks a the *default state*. If the Task
1330 Selection Logic is unable to select an appropriate task, then it should select the
1331 *default task*. Once the task has been selected the Apex Engine will then execute that
1332 task.
ramverma3b71c972019-07-10 11:25:37 +00001333
1334 .. container:: paragraph
1335
1336 First lets start with some simple Task Selection Logic, drawn from
1337 the "My First Apex Policy" example: The Task Selection Logic from
1338 the "My First Apex Policy" example is specified in JavaScript
1339 here:
1340
1341 .. container:: listingblock
1342
1343 .. container:: title
1344
1345 Javascript code for the "My First Policy" Task Selection Logic
1346
1347 .. container:: content
1348
1349 .. code:: javascript
1350
1351 /*
1352 * ============LICENSE_START=======================================================
1353 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
1354 * ================================================================================
1355 * Licensed under the Apache License, Version 2.0 (the "License");
1356 * you may not use this file except in compliance with the License.
1357 * You may obtain a copy of the License at
1358 *
1359 * http://www.apache.org/licenses/LICENSE-2.0
1360 *
1361 * Unless required by applicable law or agreed to in writing, software
1362 * distributed under the License is distributed on an "AS IS" BASIS,
1363 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1364 * See the License for the specific language governing permissions and
1365 * limitations under the License.
1366 *
1367 * SPDX-License-Identifier: Apache-2.0
1368 * ============LICENSE_END=========================================================
1369 */
1370
1371
1372 var returnValueType = Java.type("java.lang.Boolean");
1373 var returnValue = new returnValueType(true);
1374
1375 executor.logger.info("Task Selection Execution: '"+executor.subject.id+
1376 "'. Input Event: '"+executor.inFields+"'");
1377
1378 branchid = executor.inFields.get("branch_ID");
1379 taskorig = executor.subject.getTaskKey("MorningBoozeCheck");
1380 taskalt = executor.subject.getTaskKey("MorningBoozeCheckAlt1");
1381 taskdef = executor.subject.getDefaultTaskKey();
1382
1383 if(branchid >=0 && branchid <1000){
1384 taskorig.copyTo(executor.selectedTask);
1385 }
1386 else if (branchid >=1000 && branchid <2000){
1387 taskalt.copyTo(executor.selectedTask);
1388 }
1389 else{
1390 taskdef.copyTo(executor.selectedTask);
1391 }
1392
1393 /*
1394 This task selection logic selects task "MorningBoozeCheck" for branches with
1395 0<=branch_ID<1000 and selects task "MorningBoozeCheckAlt1" for branches with
1396 1000<=branch_ID<2000. Otherwise the default task is selected.
1397 In this case the default task is also "MorningBoozeCheck"
1398 */
1399
1400 .. container:: paragraph
1401
1402 The role of the Task Selection Logic in this simple example is to
1403 examine the value in one incoming field (``branchid``), then
1404 depending on that fields value set the value for the selected
1405 task to the appropriate task (``MorningBoozeCheck``,
1406 ``MorningBoozeCheckAlt1``, or the default task).
1407
1408 .. container:: paragraph
1409
1410 Another thing to notice is that Task Selection Logic should return
1411 a ``java.lang.Boolean`` value ``true`` if the logic executed
1412 correctly. If the logic fails for some reason then ``false`` can
1413 be returned, but this will cause the policy invoking this task
1414 will fail and exit.
1415
ramverma760cce92019-07-11 12:57:49 +00001416 .. note::
ramverma3b71c972019-07-10 11:25:37 +00001417 How to return a value from Task Selection Logic
ramverma760cce92019-07-11 12:57:49 +00001418 Some languages explicitly support returning values from the script (e.g. MVEL and
1419 JRuby) using an explicit return statement (e.g. ``return true``), other languages do not (e.g.
1420 JavaScript and Jython). For languages that do not support the ``return`` statement, a special field called
1421 ``returnValue`` must be created to hold the result of the task logic operation (i.e. assign a ``java.lang.Boolean``
1422 value to the ``returnValue`` field before completing the task).
1423 Also, in MVEL if there is not explicit return statement then the return value of the last executed statement will
1424 return (e.g. the statement a=(1+2) will return the value 3).
ramverma3b71c972019-07-10 11:25:37 +00001425
1426 .. container:: paragraph
1427
1428 Each of the scripting languages used in Apex can import and use
1429 standard Java libraries to perform complex tasks. Besides imported
1430 classes and normal language features Apex provides some natively
1431 available parameters and functions that can be used directly. At
1432 run-time these parameters are populated by the Apex execution
1433 environment and made natively available to logic scripts each time
1434 the logic script is invoked. (These can be accessed using the
1435 ``executor`` keyword for most languages, or can be accessed
1436 directly without the ``executor`` keyword in MVEL):
1437
1438 Table 2. The ``executor`` Fields / Methods
1439 +-------------------------------------------------------+--------------------------------------------------------+
1440 | Unix, Cygwin | Windows |
1441 +=======================================================+========================================================+
1442 | .. container:: | .. container:: |
1443 | | |
1444 | .. container:: content | .. container:: content |
1445 | | |
1446 | .. code:: bash | .. code:: bash |
1447 | :number-lines: | :number-lines: |
1448 | | |
1449 | >c: | # cd /usr/local/src/apex-pdp |
liamfallon1540e472019-11-28 15:14:07 +00001450 | >cd \dev\apex | # mvn clean install -DskipTests |
ramverma3b71c972019-07-10 11:25:37 +00001451 | >mvn clean install -DskipTests | |
1452 +-------------------------------------------------------+--------------------------------------------------------+
1453
1454+------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1455| Name | Type | Java type | Description |
1456+============+=============+================================+=====================================================================================+
1457| inFields | Fields | java.util.Map <String,Object> | .. container:: paragraph |
1458| | | | |
1459| | | | All fields in the states incoming event. This is implemented as a standard Java |
1460| | | | Java (unmodifiable) Map |
1461| | | | |
1462| | | | .. container:: |
1463| | | | |
1464| | | | .. container:: content |
1465| | | | |
1466| | | | .. container:: paragraph |
1467| | | | |
1468| | | | **Example:** |
1469| | | | |
1470| | | | .. code:: javascript |
1471| | | | |
1472| | | | executor.logger.debug("Incoming fields: " |
1473| | | | +executor.inFields.entrySet()); |
1474| | | | var item_id = executor.incomingFields["item_ID"]; |
1475| | | | if (item_id >=1000) { ... } |
1476+------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1477| outFields | Fields | java.util.Map <String,Object> | .. container:: paragraph |
1478| | | | |
1479| | | | The outgoing task fields. This is implemented as a standard initially empty Java |
1480| | | | (modifiable) Map. To create a new schema-compliant instance of a field object |
1481| | | | see the utility method subject.getOutFieldSchemaHelper() below |
1482| | | | |
1483| | | | .. container:: |
1484| | | | |
1485| | | | .. container:: content |
1486| | | | |
1487| | | | .. container:: paragraph |
1488| | | | |
1489| | | | **Example:** |
1490| | | | |
1491| | | | .. code:: javascript |
1492| | | | |
1493| | | | executor.outFields["authorised"] = false; |
1494+------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1495| logger | Logger | org.slf4j.ext.XLogger | .. container:: paragraph |
1496| | | | |
1497| | | | A helpful logger |
1498| | | | |
1499| | | | .. container:: |
1500| | | | |
1501| | | | .. container:: content |
1502| | | | |
1503| | | | .. container:: paragraph |
1504| | | | |
1505| | | | **Example:** |
1506| | | | |
1507| | | | .. code:: javascript |
1508| | | | |
1509| | | | executor.logger.info("Executing task: " |
1510| | | | +executor.subject.id); |
1511+------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1512| TRUE/FALSE | boolean | java.lang.Boolean | .. container:: paragraph |
1513| | | | |
1514| | | | 2 helpful constants. These are useful to retrieve correct return values for the |
1515| | | | task logic |
1516| | | | |
1517| | | | .. container:: |
1518| | | | |
1519| | | | .. container:: content |
1520| | | | |
1521| | | | .. container:: paragraph |
1522| | | | |
1523| | | | **Example:** |
1524| | | | |
1525| | | | .. code:: javascript |
1526| | | | |
1527| | | | var returnValue = executor.isTrue; |
1528| | | | var returnValueType = Java.type("java.lang.Boolean"); |
1529| | | | var returnValue = new returnValueType(true); |
1530+------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1531| subject | Task | TaskFacade | .. container:: paragraph |
1532| | | | |
1533| | | | This provides some useful information about the task that contains this task |
1534| | | | logic. This object has some useful fields and methods : |
1535| | | | |
1536| | | | .. container:: ulist |
1537| | | | |
1538| | | | - **AxTask task** to get access to the full task definition of |
1539| | | | the host task |
1540| | | | |
1541| | | | - **String getTaskName()** to get the name of the host task |
1542| | | | |
1543| | | | - **String getId()** to get the ID of the host task |
1544| | | | |
1545| | | | - **SchemaHelper getInFieldSchemaHelper( String fieldName )** to |
1546| | | | get a ``SchemaHelper`` helper object to manipulate incoming |
1547| | | | task fields in a schema-aware manner |
1548| | | | |
1549| | | | - **SchemaHelper getOutFieldSchemaHelper( String fieldName )** to |
1550| | | | get a ``SchemaHelper`` helper object to manipulate outgoing |
1551| | | | task fields in a schema-aware manner, e.g. to instantiate new |
1552| | | | schema-compliant field objects to populate the |
1553| | | | ``executor.outFields`` outgoing fields map |
1554| | | | |
1555| | | | .. container:: |
1556| | | | |
1557| | | | .. container:: content |
1558| | | | |
1559| | | | .. container:: paragraph |
1560| | | | |
1561| | | | **Example:** |
1562| | | | |
1563| | | | .. code:: javascript |
1564| | | | |
1565| | | | executor.logger.info("Task name: " |
1566| | | | +executor.subject.getTaskName()); |
1567| | | | executor.logger.info("Task id: " |
1568| | | | +executor.subject.getId()); |
1569| | | | executor.logger.info("Task inputs definitions: " |
1570| | | | +"executor.subject.task.getInputFieldSet()); |
1571| | | | executor.logger.info("Task outputs definitions: " |
1572| | | | +"executor.subject.task.getOutputFieldSet()); |
1573| | | | executor.outFields["authorised"] = executor.subject |
1574| | | | .getOutFieldSchemaHelper("authorised") |
1575| | | | .createNewInstance("false"); |
1576+------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
a.sreekumarcc0e9172020-03-16 13:36:45 +00001577| parameters | Fields | java.util.Map <String,String> | .. container:: paragraph |
1578| | | | |
1579| | | | All parameters in the current task. This is implemented as a standard Java Map. |
1580| | | | |
1581| | | | .. container:: |
1582| | | | |
1583| | | | .. container:: content |
1584| | | | |
1585| | | | .. container:: paragraph |
1586| | | | |
1587| | | | **Example:** |
1588| | | | |
1589| | | | .. code:: javascript |
1590| | | | |
1591| | | | executor.parameters.get("ParameterKey1")) |
1592+------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
ramverma3b71c972019-07-10 11:25:37 +00001593| ContextAlbum getContextAlbum(String ctxtAlbumName ) | .. container:: paragraph |
1594| | |
1595| | A utility method to retrieve a ``ContextAlbum`` for use in the task. |
1596| | This is how you access the context used by the task. The returned |
1597| | ``ContextAlbum`` implements the ``java.util.Map <String,Object>`` |
1598| | interface to get and set context as appropriate. The returned |
1599| | ``ContextAlbum`` also has methods to lock context albums, get |
1600| | information about the schema of the items to be stored in a context |
1601| | album, and get a ``SchemaHelper`` to manipulate context album items. How |
1602| | to define and use context in a task is described in the Apex |
1603| | Programmers Guide and in the My First Apex Policy guide. |
1604| | |
1605| | .. container:: |
1606| | |
1607| | .. container:: content |
1608| | |
1609| | .. container:: paragraph |
1610| | |
1611| | **Example:** |
1612| | |
1613| | .. code:: javascript |
1614| | |
1615| | var bkey = executor.inFields.get("branch_ID"); |
1616| | var cnts = executor.getContextMap("BranchCounts"); |
1617| | cnts.lockForWriting(bkey); |
1618| | cnts.put(bkey, cnts.get(bkey) + 1); |
1619| | cnts.unlockForWriting(bkey); |
1620+------------+-------------+--------------------------------+-------------------------------------------------------------------------------------+
1621
1622Logic Cheatsheet
1623----------------
1624
1625 .. container:: paragraph
1626
1627 Examples given here use Javascript (if not stated otherwise),
1628 other execution environments will be similar.
1629
ramverma3b71c972019-07-10 11:25:37 +00001630Finish Logic with Success or Error
1631##################################
1632
1633 .. container:: paragraph
1634
1635 To finish logic, i.e. return to APEX, with success use the
a.sreekumarcc0e9172020-03-16 13:36:45 +00001636 following line close to the end of the logic.
ramverma3b71c972019-07-10 11:25:37 +00001637
1638 .. container:: listingblock
1639
1640 .. container:: title
1641
1642 JS Success
1643
1644 .. container:: content
1645
1646 .. code:: javascript
1647
a.sreekumarcc0e9172020-03-16 13:36:45 +00001648 true;
ramverma3b71c972019-07-10 11:25:37 +00001649
1650 .. container:: paragraph
1651
1652 To notify a problem, finish with an error.
1653
1654 .. container:: listingblock
1655
1656 .. container:: title
1657
1658 JS Fail
1659
1660 .. container:: content
1661
1662 .. code:: javascript
1663
a.sreekumarcc0e9172020-03-16 13:36:45 +00001664 false;
ramverma3b71c972019-07-10 11:25:37 +00001665
1666Logic Logging
1667#############
1668
1669 .. container:: paragraph
1670
1671 Logging can be made easy using a local variable for the logger.
1672 Line 1 below does that. Then we start with a trace log with the
1673 task (or task logic) identifier followed by the infields.
1674
1675 .. container:: listingblock
1676
1677 .. container:: title
1678
1679 JS Logging
1680
1681 .. container:: content
1682
1683 .. code:: javascript
1684
1685 var logger = executor.logger;
1686 logger.trace("start: " + executor.subject.id);
1687 logger.trace("-- infields: " + executor.inFields);
1688
1689 .. container:: paragraph
1690
1691 For larger logging blocks you can use the standard logging API
1692 to detect log levels, for instance:
1693
1694 .. container:: listingblock
1695
1696 .. container:: title
1697
1698 JS Logging Blocks
1699
1700 .. container:: content
1701
1702 .. code:: javascript
1703
1704 if(logger.isTraceEnabled()){
1705 // trace logging block here
1706 }
1707
1708 .. container:: paragraph
1709
1710 Note: the shown logger here logs to
1711 ``org.onap.policy.apex.executionlogging``. The behavior of the
1712 actual logging can be specified in the
1713 ``$APEX_HOME/etc/logback.xml``.
1714
1715 .. container:: paragraph
1716
1717 If you want to log into the APEX root logger (which is
1718 sometimes necessary to report serious logic errors to the top),
1719 then import the required class and use this logger.
1720
1721 .. container:: listingblock
1722
1723 .. container:: title
1724
1725 JS Root Logger
1726
1727 .. container:: content
1728
1729 .. code:: javascript
1730
1731 importClass(org.slf4j.LoggerFactory);
1732 var rootLogger = LoggerFactory.getLogger(logger.ROOT_LOGGER_NAME);
1733
1734 rootLogger.error("Serious error in logic detected: " + executor.subject.id);
1735
a.sreekumarcc0e9172020-03-16 13:36:45 +00001736Accessing TaskParameters
1737########################
1738
1739 .. container:: paragraph
1740
1741 TaskParameters available in a Task can be accessed in the logic.
1742 The parameters in each task are made available at the executor level.
1743 This example assumes a parameter with key ``ParameterKey1``.
1744
1745 .. container:: listingblock
1746
1747 .. container:: title
1748
1749 JS TaskParameter value
1750
1751 .. container:: content
1752
1753 .. code:: javascript
1754
1755 executor.parameters.get("ParameterKey1"))
1756
1757 .. container:: paragraph
1758
1759 Alternatively, the task parameters can also be accessed from the task object.
1760
1761 .. container:: listingblock
1762
1763 .. container:: title
1764
1765 JS TaskParameter value using task object
1766
1767 .. container:: content
1768
1769 .. code:: javascript
1770
1771 executor.subject.task.getTaskParameters.get("ParameterKey1").getTaskParameterValue()
1772
ramverma3b71c972019-07-10 11:25:37 +00001773Local Variable for Infields
1774###########################
1775
1776 .. container:: paragraph
1777
1778 It is a good idea to use local variables for ``infields``. This
1779 avoids long code lines and policy evolution. The following
1780 example assumes infields named ``nodeName`` and ``nodeAlias``.
1781
1782 .. container:: listingblock
1783
1784 .. container:: title
1785
1786 JS Infields Local Var
1787
1788 .. container:: content
1789
1790 .. code:: javascript
1791
1792 var ifNodeName = executor.inFields["nodeName"];
1793 var ifNodeAlias = executor.inFields["nodeAlias"];
1794
1795Local Variable for Context Albums
1796#################################
1797
1798 .. container:: paragraph
1799
1800 Similar to the ``infields`` it is good practice to use local
1801 variables for context albums as well. The following example
1802 assumes that a task can access a context album
1803 ``albumTopoNodes``. The second line gets a particular node from
1804 this context album.
1805
1806 .. container:: listingblock
1807
1808 .. container:: title
1809
1810 JS Infields Local Var
1811
1812 .. container:: content
1813
1814 .. code:: javascript
1815
1816 var albumTopoNodes = executor.getContextAlbum("albumTopoNodes");
1817 var ctxtNode = albumTopoNodes.get(ifNodeName);
1818
1819Set Outfields in Logic
1820######################
1821
1822 .. container:: paragraph
1823
1824 The task logic needs to set outfields with content generated.
1825 The exception are outfields that are a direct copy from an
1826 infield of the same name, APEX does that autmatically.
1827
1828 .. container:: listingblock
1829
1830 .. container:: title
1831
1832 JS Set Outfields
1833
1834 .. container:: content
1835
1836 .. code:: javascript
1837
1838 executor.outFields["report"] = "node ctxt :: added node " + ifNodeName;
1839
1840Create a instance of an Outfield using Schemas
1841##############################################
1842
1843 .. container:: paragraph
1844
1845 If an outfield is not an atomic type (string, integer, etc.)
1846 but uses a complex schema (with a Java or Avro backend), APEX
1847 can help to create new instances. The ``executor`` provides a
1848 field called ``subject``, which provides a schem helper with an
1849 API for this. The complete API of the schema helper is
1850 documented here: `API Doc:
1851 SchemaHelper <https://ericsson.github.io/apex-docs/javadocs/index.html>`__.
1852
1853 .. container:: paragraph
1854
1855 If the backend is Avro, then an import of the Avro schema
1856 library is required:
1857
1858 .. container:: listingblock
1859
1860 .. container:: title
1861
1862 JS Import Avro
1863
1864 .. container:: content
1865
1866 .. code:: javascript
1867
1868 importClass(org.apache.avro.generic.GenericData.Array);
1869 importClass(org.apache.avro.generic.GenericRecord);
1870 importClass(org.apache.avro.Schema);
1871
1872 .. container:: paragraph
1873
1874 If the backend is Java, then the Java class implementing the
1875 schema needs to be imported.
1876
1877 .. container:: paragraph
1878
1879 The following example assumes an outfield ``situation``. The
1880 ``subject`` method ``getOutFieldSchemaHelper()`` is used to
1881 create a new instance.
1882
1883 .. container:: listingblock
1884
1885 .. container:: title
1886
1887 JS Outfield Instance with Schema
1888
1889 .. container:: content
1890
1891 .. code:: javascript
1892
1893 var situation = executor.subject.getOutFieldSchemaHelper("situation").createNewInstance();
1894
1895 .. container:: paragraph
1896
1897 If the schema backend is Java, the new instance will be as
1898 implemented in the Java class. If the schema backend is Avro,
1899 the new instance will have all fields from the Avro schema
1900 specification, but set to ``null``. So any entry here needs to
1901 be done separately. For instance, the ``situation`` schema has
1902 a field ``problemID`` which we set.
1903
1904 .. container:: listingblock
1905
1906 .. container:: title
1907
1908 JS Outfield Instance with Schema, set
1909
1910 .. container:: content
1911
1912 .. code:: javascript
1913
1914 situation.put("problemID", "my-problem");
1915
1916Create a instance of an Context Album entry using Schemas
1917#########################################################
1918
1919 .. container:: paragraph
1920
1921 Context album instances can be created using very similar to
1922 the outfields. Here, the schema helper comes from the context
1923 album directly. The API of the schema helper is the same as for
1924 outfields, see `API Doc:
1925 SchemaHelper <https://ericsson.github.io/apex-docs/javadocs/index.html>`__.
1926
1927 .. container:: paragraph
1928
1929 If the backend is Avro, then an import of the Avro schema
1930 library is required:
1931
1932 .. container:: listingblock
1933
1934 .. container:: title
1935
1936 JS Import Avro
1937
1938 .. container:: content
1939
1940 .. code:: javascript
1941
1942 importClass(org.apache.avro.generic.GenericData.Array);
1943 importClass(org.apache.avro.generic.GenericRecord);
1944 importClass(org.apache.avro.Schema);
1945
1946 .. container:: paragraph
1947
1948 If the backend is Java, then the Java class implementing the
1949 schema needs to be imported.
1950
1951 .. container:: paragraph
1952
1953 The following example creates a new instance of a context album
1954 instance named ``albumProblemMap``.
1955
1956 .. container:: listingblock
1957
1958 .. container:: title
1959
1960 JS Outfield Instance with Schema
1961
1962 .. container:: content
1963
ramverma760cce92019-07-11 12:57:49 +00001964 .. code:: javascript
ramverma3b71c972019-07-10 11:25:37 +00001965
1966 var albumProblemMap = executor.getContextAlbum("albumProblemMap");
1967 var linkProblem = albumProblemMap.getSchemaHelper().createNewInstance();
1968
1969 .. container:: paragraph
1970
1971 This can of course be also done in a single call without the
1972 local variable for the context album.
1973
1974 .. container:: listingblock
1975
1976 .. container:: title
1977
1978 JS Outfield Instance with Schema, one line
1979
1980 .. container:: content
1981
ramverma760cce92019-07-11 12:57:49 +00001982 .. code:: javascript
ramverma3b71c972019-07-10 11:25:37 +00001983
1984 var linkProblem = executor.getContextAlbum("albumProblemMap").getSchemaHelper().createNewInstance();
1985
1986 .. container:: paragraph
1987
1988 If the schema backend is Java, the new instance will be as
1989 implemented in the Java class. If the schema backend is Avro,
1990 the new instance will have all fields from the Avro schema
1991 specification, but set to ``null``. So any entry here needs to
1992 be done separately (see above in outfields for an example).
1993
1994Enumerates
1995##########
1996
1997 .. container:: paragraph
1998
1999 When dealing with enumerates (Avro or Java defined), it is
2000 sometimes and in some execution environments necessary to
2001 convert them to a string. For example, assume an Avro enumerate
2002 schema as:
2003
2004 .. container:: listingblock
2005
2006 .. container:: title
2007
2008 Avro Enumerate Schema
2009
2010 .. container:: content
2011
2012 .. code:: javascript
2013
2014 {
2015 "type": "enum",
2016 "name": "Status",
2017 "symbols" : [
2018 "UP",
2019 "DOWN"
2020 ]
2021 }
2022
2023 .. container:: paragraph
2024
2025 Using a switch over a field initialized with this enumerate in
2026 Javascript will fail. Instead, use the ``toString`` method, for
2027 example:
2028
2029 .. container:: listingblock
2030
2031 .. container:: title
2032
2033 JS Outfield Instance with Schema, one line
2034
2035 .. container:: content
2036
2037 .. code:: javascript
2038
2039 var switchTest = executor.inFields["status"];
2040 switch(switchTest.toString()){
2041 case "UP": ...; break;
2042 case "DOWN": ...; break;
2043 default: ...;
2044 }
2045
2046MVEL Initialize Outfields First!
2047################################
2048
2049 .. container:: paragraph
2050
2051 In MVEL, we observed a problem when accessing (setting)
2052 outfields without a prior access to them. So in any MVEL task
2053 logic, before setting any outfield, simply do a get (with any
2054 string), to load the outfields into the MVEL cache.
2055
2056 .. container:: listingblock
2057
2058 .. container:: title
2059
2060 MVEL Outfield Initialization
2061
2062 .. container:: content
2063
2064 .. code:: javascript
2065
2066 outFields.get("initialize outfields");
2067
2068Using Java in Scripting Logic
2069#############################
2070
2071 .. container:: paragraph
2072
2073 Since APEX executes the logic inside a JVM, most scripting
2074 languages provide access to all standard Java classes. Simply
2075 add an import for the required class and then use it as in
2076 actual Java.
2077
2078 .. container:: paragraph
2079
2080 The following example imports ``java.util.arraylist`` into a
2081 Javascript logic, and then creates a new list.
2082
2083 .. container:: listingblock
2084
2085 .. container:: title
2086
2087 JS Import ArrayList
2088
2089 .. container:: content
2090
2091 .. code:: javascript
2092
2093 importClass(java.util.ArrayList);
2094 var myList = new ArrayList();
2095
ramverma3b71c972019-07-10 11:25:37 +00002096
2097.. container::
2098 :name: footer
2099
2100 .. container::
2101 :name: footer-text
2102
a.sreekumarcc0e9172020-03-16 13:36:45 +00002103 2.3.0-SNAPSHOT
2104 Last updated 2020-03-16 16:04:24 GMT
ramverma3b71c972019-07-10 11:25:37 +00002105
2106.. |APEX Policy Matrix| image:: images/apex-intro/ApexPolicyMatrix.png
2107.. |APEX Policy Model for Execution| image:: images/apex-policy-model/UmlPolicyModels.png
2108.. |Concepts and Keys| image:: images/apex-policy-model/ConceptsKeys.png
2109