add document for POLICY-1742
[policy/parent.git] / docs / apex / APEX-User-Manual.rst
1 .. This work is licensed under a Creative Commons Attribution 4.0 International License.
2 .. http://creativecommons.org/licenses/by/4.0
3
4
5 APEX User Manual
6 ****************
7
8 .. contents::
9     :depth: 3
10
11 Installation
12 ^^^^^^^^^^^^
13
14 Requirements
15 ------------
16
17             .. container:: paragraph
18
19                APEX is 100% written in Java and runs on any platform
20                that supports a JVM, e.g. Windows, Unix, Cygwin. Some
21                APEX applications (such as the monitoring application)
22                come as web archives, they do require a war-capable web
23                server installed.
24
25 Installation Requirements
26 #########################
27
28                .. container:: ulist
29
30                   -  Downloaded distribution: JAVA runtime environment
31                      (JRE, Java 8 or later, APEX is tested with the
32                      Oracle Java)
33
34                   -  Building from source: JAVA development kit (JDK,
35                      Java 8 or later, APEX is tested with the Oracle
36                      Java)
37
38                   -  A web archive capable webserver, for instance for
39                      the monitoring application
40
41                      .. container:: ulist
42
43                         -  for instance `Apache
44                            Tomcat <https://tomcat.apache.org/>`__
45
46                   -  Sufficient rights to install APEX on the system
47
48                   -  Installation tools depending on the installation
49                      method used:
50
51                      .. container:: ulist
52
53                         -  ZIP to extract from a ZIP distribution
54
55                            .. container:: ulist
56
57                               -  Windows for instance
58                                  `7Zip <http://www.7-zip.org/>`__
59
60                         -  TAR and GZ to extract from that TAR.GZ
61                            distribution
62
63                            .. container:: ulist
64
65                               -  Windows for instance
66                                  `7Zip <http://www.7-zip.org/>`__
67
68                         -  RPM to install from the RPM distribution
69
70                            .. container:: ulist
71
72                               -  Install: ``sudo apt-get install rpm``
73
74                         -  DPKG to install from the DEB distribution
75
76                            .. container:: ulist
77
78                               -  Install: ``sudo apt-get install dpkg``
79
80 Feature Requirements
81 ####################
82
83                .. container:: paragraph
84
85                   APEX supports a number of features that require extra
86                   software being installed.
87
88                .. container:: ulist
89
90                   -  `Apache Kafka <https://kafka.apache.org/>`__ to
91                      connect APEX to a Kafka message bus
92
93                   -  `Hazelcast <https://hazelcast.com/>`__ to use
94                      distributed hash maps for context
95
96                   -  `Infinispan <http://infinispan.org/>`__ for
97                      distributed context and persistence
98
99                   -  `Docker <https://www.docker.com/>`__ to run APEX
100                      inside a Docker container
101
102 Build (Install from Source) Requirements
103 ########################################
104
105                .. container:: paragraph
106
107                   Installation from source requires a few development
108                   tools
109
110                .. container:: ulist
111
112                   -  GIT to retrieve the source code
113
114                   -  Java SDK, Java version 8 or later
115
116                   -  Apache Maven 3 (the APEX build environment)
117
118 Get the APEX Source Code
119 ------------------------
120
121             .. container:: paragraph
122
123                The first APEX source code was hosted on Github in
124                January 2018. By the end of 2018, APEX was added as a
125                project in the ONAP Policy Framework, released later in
126                the ONAP Casablanca release.
127
128             .. container:: paragraph
129
130                The APEX source code is hosted in ONAP as project APEX.
131                The current stable version is in the master branch.
132                Simply clone the master branch from ONAP using HTTPS.
133
134             .. container:: listingblock
135
136                .. container:: content
137
138                   .. code::
139                      :number-lines:
140
141                      git clone https://gerrit.onap.org/r/policy/apex-pdp
142
143 Build APEX
144 ----------
145
146    .. container:: paragraph
147
148       The examples in this document assume that the APEX source
149       repositories are cloned to:
150
151    .. container:: ulist
152
153       -  Unix, Cygwin: ``/usr/local/src/apex-pdp``
154
155       -  Windows: ``C:\dev\apex-pdp``
156
157       -  Cygwin: ``/cygdrive/c/dev/apex-pdp``
158
159    .. important::
160       A Build requires ONAP Nexus
161       APEX has a dependency to ONAP parent projects. You might need to adjust your Maven M2 settings. The most current
162       settings can be found in the ONAP oparent repo: `Settings <https://git.onap.org/oparent/plain/settings.xml>`__.
163
164    .. important::
165       A Build needs Space
166       Building APEX requires approximately 2-3 GB of hard disc space, 1 GB for the actual build with full
167       distribution and 1-2 GB for the downloaded dependencies
168
169    .. important::
170       A Build requires Internet (for first build)
171       During the build, several (a lot) of Maven dependencies will be downloaded and stored in the configured local Maven
172       repository. The first standard build (and any first specific build) requires Internet access to download those
173       dependencies.
174
175    .. important::
176       Building RPM distributions
177       RPM images are only build if the ``rpm`` package is installed (Unix). To install  ``rpm`` run ``sudo apt-get install rpm``,
178       then build APEX.
179
180    .. container:: paragraph
181
182       Use Maven to for a standard build without any tests.
183
184       +-------------------------------------------------------+--------------------------------------------------------+
185       | Unix, Cygwin                                          | Windows                                                |
186       +=======================================================+========================================================+
187       | .. container::                                        | .. container::                                         |
188       |                                                       |                                                        |
189       |    .. container:: content                             |    .. container:: content                              |
190       |                                                       |                                                        |
191       |       .. code::                                       |       .. code::                                        |
192       |         :number-lines:                                |         :number-lines:                                 |
193       |                                                       |                                                        |
194       |         # cd /usr/local/src/apex-pdp                  |          >c:                                           |
195       |         # mvn clean install -DskipTest                |          >cd \dev\apex                                 |
196       |                                                       |          >mvn clean install -DskipTests                |
197       +-------------------------------------------------------+--------------------------------------------------------+
198
199 .. container:: paragraph
200
201    The build takes 2-3 minutes on a standard development laptop. It
202    should run through without errors, but with a lot of messages from
203    the build process.
204
205 .. container:: paragraph
206
207    When Maven is finished with the build, the final screen should look
208    similar to this (omitting some ``success`` lines):
209
210 .. container:: listingblock
211
212    .. container:: content
213
214       .. code::
215         :number-lines:
216
217         [INFO] tools .............................................. SUCCESS [  0.248 s]
218         [INFO] tools-common ....................................... SUCCESS [  0.784 s]
219         [INFO] simple-wsclient .................................... SUCCESS [  3.303 s]
220         [INFO] model-generator .................................... SUCCESS [  0.644 s]
221         [INFO] packages ........................................... SUCCESS [  0.336 s]
222         [INFO] apex-pdp-package-full .............................. SUCCESS [01:10 min]
223         [INFO] Policy APEX PDP - Docker build 2.0.0-SNAPSHOT ...... SUCCESS [ 10.307 s]
224         [INFO] ------------------------------------------------------------------------
225         [INFO] BUILD SUCCESS
226         [INFO] ------------------------------------------------------------------------
227         [INFO] Total time: 03:43 min
228         [INFO] Finished at: 2018-09-03T11:56:01+01:00
229         [INFO] ------------------------------------------------------------------------
230
231 .. container:: paragraph
232
233    The build will have created all artifacts required for an APEX
234    installation. The following example show how to change to the target
235    directory and how it should look like.
236
237 +----------------------------------------------------------------------------------------------------------------------------+
238 | Unix, Cygwin                                                                                                               |
239 +============================================================================================================================+
240 | .. container::                                                                                                             |
241 |                                                                                                                            |
242 |    .. container:: listingblock                                                                                             |
243 |                                                                                                                            |
244 |       .. container:: content                                                                                               |
245 |                                                                                                                            |
246 |          .. code::                                                                                                         |
247 |             :number-lines:                                                                                                 |
248 |                                                                                                                            |
249 |             -rwxrwx---+ 1 esvevan Domain Users       772 Sep  3 11:55 apex-pdp-package-full_2.0.0~SNAPSHOT_all.changes*    |
250 |             -rwxrwx---+ 1 esvevan Domain Users 146328082 Sep  3 11:55 apex-pdp-package-full-2.0.0-SNAPSHOT.deb*            |
251 |             -rwxrwx---+ 1 esvevan Domain Users     15633 Sep  3 11:54 apex-pdp-package-full-2.0.0-SNAPSHOT.jar*            |
252 |             -rwxrwx---+ 1 esvevan Domain Users 146296819 Sep  3 11:55 apex-pdp-package-full-2.0.0-SNAPSHOT-tarball.tar.gz* |
253 |             drwxrwx---+ 1 esvevan Domain Users         0 Sep  3 11:54 archive-tmp/                                         |
254 |             -rwxrwx---+ 1 esvevan Domain Users        89 Sep  3 11:54 checkstyle-cachefile*                                |
255 |             -rwxrwx---+ 1 esvevan Domain Users     10621 Sep  3 11:54 checkstyle-checker.xml*                              |
256 |             -rwxrwx---+ 1 esvevan Domain Users       584 Sep  3 11:54 checkstyle-header.txt*                               |
257 |             -rwxrwx---+ 1 esvevan Domain Users        86 Sep  3 11:54 checkstyle-result.xml*                               |
258 |             drwxrwx---+ 1 esvevan Domain Users         0 Sep  3 11:54 classes/                                             |
259 |             drwxrwx---+ 1 esvevan Domain Users         0 Sep  3 11:54 dependency-maven-plugin-markers/                     |
260 |             drwxrwx---+ 1 esvevan Domain Users         0 Sep  3 11:54 etc/                                                 |
261 |             drwxrwx---+ 1 esvevan Domain Users         0 Sep  3 11:54 examples/                                            |
262 |             drwxrwx---+ 1 esvevan Domain Users         0 Sep  3 11:55 install_hierarchy/                                   |
263 |             drwxrwx---+ 1 esvevan Domain Users         0 Sep  3 11:54 maven-archiver/                                      |
264 +----------------------------------------------------------------------------------------------------------------------------+
265
266 +--------------------------------------------------------------------------------------------------------+
267 | Windows                                                                                                |
268 +========================================================================================================+
269 | .. container::                                                                                         |
270 |                                                                                                        |
271 |    .. container:: listingblock                                                                         |
272 |                                                                                                        |
273 |       .. container:: content                                                                           |
274 |                                                                                                        |
275 |          .. code::                                                                                     |
276 |             :number-lines:                                                                             |
277 |                                                                                                        |
278 |                03/09/2018  11:55    <DIR>          .                                                   |
279 |                03/09/2018  11:55    <DIR>          ..                                                  |
280 |                03/09/2018  11:55       146,296,819 apex-pdp-package-full-2.0.0-SNAPSHOT-tarball.tar.gz |
281 |                03/09/2018  11:55       146,328,082 apex-pdp-package-full-2.0.0-SNAPSHOT.deb            |
282 |                03/09/2018  11:54            15,633 apex-pdp-package-full-2.0.0-SNAPSHOT.jar            |
283 |                03/09/2018  11:55               772 apex-pdp-package-full_2.0.0~SNAPSHOT_all.changes    |
284 |                03/09/2018  11:54    <DIR>          archive-tmp                                         |
285 |                03/09/2018  11:54                89 checkstyle-cachefile                                |
286 |                03/09/2018  11:54            10,621 checkstyle-checker.xml                              |
287 |                03/09/2018  11:54               584 checkstyle-header.txt                               |
288 |                03/09/2018  11:54                86 checkstyle-result.xml                               |
289 |                03/09/2018  11:54    <DIR>          classes                                             |
290 |                03/09/2018  11:54    <DIR>          dependency-maven-plugin-markers                     |
291 |                03/09/2018  11:54    <DIR>          etc                                                 |
292 |                03/09/2018  11:54    <DIR>          examples                                            |
293 |                03/09/2018  11:55    <DIR>          install_hierarchy                                   |
294 |                03/09/2018  11:54    <DIR>          maven-archiver                                      |
295 |                               8 File(s)    292,652,686 bytes                                           |
296 |                               9 Dir(s)  14,138,720,256 bytes free                                      |
297 +--------------------------------------------------------------------------------------------------------+
298
299 Install APEX
300 ------------
301
302    .. container:: paragraph
303
304       APEX can be installed in different ways:
305
306    .. container:: ulist
307
308       -  Unix: automatically using ``rpm`` or ``dpkg`` from ``.rpm`` or
309          ``.deb`` archive
310
311       -  Windows, Unix, Cygwin: manually from a ``.tar.gz`` archive
312
313       -  Windows, Unix, Cygwin: build from source using Maven, then
314          install manually
315
316 Install with RPM and DPKG
317 #########################
318
319       .. container:: paragraph
320
321          The install distributions of APEX automatically install the
322          system. The installation directory is
323          ``/opt/app/policy/apex-pdp``. Log files are located in
324          ``/var/log/onap/policy/apex-pdp``. The latest APEX version will
325          be available as ``/opt/app/policy/apex-pdp/apex-pdp``.
326
327       .. container:: paragraph
328
329          For the installation, a new user ``apexuser`` and a new group
330          ``apexuser`` will be created. This user owns the installation
331          directories and the log file location. The user is also used by
332          the standard APEX start scripts to run APEX with this user’s
333          permissions.
334
335          +-----------------------------------------------------------------------+
336          | RPM Installation                                                      |
337          +=======================================================================+
338          | .. container::                                                        |
339          |                                                                       |
340          |    .. container:: listingblock                                        |
341          |                                                                       |
342          |       .. container:: content                                          |
343          |                                                                       |
344          |          .. code::                                                    |
345          |             :number-lines:                                            |
346          |                                                                       |
347          |             # sudo rpm -i apex-pdp-package-full-2.0.0-SNAPSHOT.rpm    |
348          |             ********************preinst*******************            |
349          |             arguments 1                                               |
350          |             **********************************************            |
351          |             creating group apexuser . . .                             |
352          |             creating user apexuser . . .                              |
353          |             ********************postinst****************              |
354          |             arguments 1                                               |
355          |             ***********************************************           |
356          +-----------------------------------------------------------------------+
357
358 +--------------------------------------------------------------------------------------+
359 | DPKG Installation                                                                    |
360 +======================================================================================+
361 | .. container::                                                                       |
362 |                                                                                      |
363 |    .. container:: listingblock                                                       |
364 |                                                                                      |
365 |       .. container:: content                                                         |
366 |                                                                                      |
367 |          .. code::                                                                   |
368 |             :number-lines:                                                           |
369 |                                                                                      |
370 |             # sudo dpkg -i apex-pdp-package-full-2.0.0-SNAPSHOT.deb                  |       
371 |             Selecting previously unselected package apex-uservice.                   |
372 |             (Reading database ... 288458 files and directories currently installed.) |
373 |             Preparing to unpack apex-pdp-package-full-2.0.0-SNAPSHOT.deb ...         |
374 |             ********************preinst*******************                           |
375 |             arguments install                                                        |
376 |             **********************************************                           |
377 |             creating group apexuser . . .                                            |
378 |             creating user apexuser . . .                                             |
379 |             Unpacking apex-uservice (2.0.0-SNAPSHOT) ...                             |
380 |             Setting up apex-uservice (2.0.0-SNAPSHOT) ...                            |
381 |             ********************postinst****************                             |
382 |             arguments configure                                                      |
383 |             ***********************************************                          |
384 +--------------------------------------------------------------------------------------+
385
386 .. container:: paragraph
387
388    Once the installation is finished, APEX is fully installed and ready
389    to run.
390
391 Install Manually from Archive (Unix, Cygwin)
392 ############################################
393
394    .. container:: paragraph
395
396       Download a ``tar.gz`` archive. Create a directory where APEX
397       should be installed. Extract the ``tar`` archive. The following
398       example shows how to install APEX in ``/opt/apex`` and create a
399       link to ``/opt/apex/apex`` for the most recent installation.
400
401    .. container:: listingblock
402
403       .. container:: content
404
405          .. code::
406             :number-lines:
407
408             # cd /opt
409             # mkdir apex
410             # cd apex
411             # mkdir apex-full-2.0.0-SNAPSHOT
412             # tar xvfz ~/Downloads/apex-pdp-package-full-2.0.0-SNAPSHOT.tar.gz -C apex-full-2.0.0-SNAPSHOT
413             # ln -s apex apex-pdp-package-full-2.0.0-SNAPSHOT
414
415 Install Manually from Archive (Windows, 7Zip, GUI)
416 ##################################################
417
418    .. container:: paragraph
419
420       Download a ``tar.gz`` archive and copy the file into the install
421       folder (in this example ``C:\apex``). Assuming you are using 7Zip,
422       right click on the file and extract the ``tar`` archive. Note: the
423       screenshots might show an older version than you have.
424
425    .. container:: imageblock
426
427       .. container:: content
428
429          |Extract the TAR archive|
430
431    .. container:: paragraph
432
433       The right-click on the new created TAR file and extract the actual
434       APEX distribution.
435
436    .. container:: imageblock
437
438       .. container:: content
439
440          |Extract the APEX distribution|
441
442    .. container:: paragraph
443
444       Inside the new APEX folder you see the main directories: ``bin``,
445       ``etc``, ``examples``, ``lib``, and ``war``
446
447    .. container:: paragraph
448
449       Once extracted, please rename the created folder to
450       ``apex-full-2.0.0-SNAPSHOT``. This will keep the directory name in
451       line with the rest of this documentation.
452
453 Install Manually from Archive (Windows, 7Zip, CMD)
454 ##################################################
455
456    .. container:: paragraph
457
458       Download a ``tar.gz`` archive and copy the file into the install
459       folder (in this example ``C:\apex``). Start ``cmd``, for instance
460       typing ``Windows+R`` and then ``cmd`` in the dialog. Assuming
461       ``7Zip`` is installed in the standard folder, simply run the
462       following commands (for APEX version 2.0.0-SNAPSHOT full
463       distribution)
464
465    .. container:: listingblock
466
467       .. container:: content
468
469          .. code::
470            :number-lines:
471
472             >c:
473             >cd \apex
474             >"\Program Files\7-Zip\7z.exe" x apex-pdp-package-full-2.0.0-SNAPSHOT.tar.gz -so | "\Program Files\7-Zip\7z.exe" x -aoa -si -ttar -o"apex-full-2.0.0-SNAPSHOT"
475
476 .. container:: paragraph
477
478    APEX is now installed in the folder
479    ``C:\apex\apex-full-2.0.0-SNAPSHOT``.
480
481 Build from Source
482 -----------------
483
484 Build and Install Manually (Unix, Windows, Cygwin)
485 ##################################################
486
487       .. container:: paragraph
488
489          Clone the APEX GIT repositories into a directory. Go to that
490          directory. Use Maven to build APEX (all details on building
491          APEX from source can be found in *APEX HowTo: Build*). Install
492          from the created artifacts (``rpm``, ``deb``, ``tar.gz``, or
493          copying manually).
494
495       .. important::
496          Building RPM distributions
497          RPM images are only build if the ``rpm`` package is installed (Unix). To install ``rpm`` run
498          ``sudo apt-get install rpm``, then build APEX.
499
500       .. container:: paragraph
501
502          The following example shows how to build the APEX system,
503          without tests (``-DskipTests``) to safe some time. It assumes
504          that the APX GIT repositories are cloned to:
505
506       .. container:: ulist
507
508          -  Unix, Cygwin: ``/usr/local/src/apex``
509
510          -  Windows: ``C:\dev\apex``
511
512          +-------------------------------------------------------+--------------------------------------------------------+
513          | Unix, Cygwin                                          | Windows                                                |
514          +=======================================================+========================================================+
515          | .. container::                                        | .. container::                                         |
516          |                                                       |                                                        |
517          |    .. container:: content                             |    .. container:: content                              |
518          |                                                       |                                                        |
519          |       .. code::                                       |       .. code::                                        |
520          |         :number-lines:                                |         :number-lines:                                 |
521          |                                                       |                                                        |
522          |         # cd /usr/local/src/apex                      |         >c:                                            |
523          |         # mvn clean install -DskipTests               |         >cd \dev\apex                                  |
524          |                                                       |         >mvn clean install -DskipTests                 |
525          +-------------------------------------------------------+--------------------------------------------------------+
526
527 .. container:: paragraph
528
529    The build takes about 2 minutes without test and about 4-5 minutes
530    with tests on a standard development laptop. It should run through
531    without errors, but with a lot of messages from the build process. If
532    build with tests (i.e. without ``-DskipTests``), there will be error
533    messages and stack trace prints from some tests. This is normal, as
534    long as the build finishes successful.
535
536 .. container:: paragraph
537
538    When Maven is finished with the build, the final screen should look
539    similar to this (omitting some ``success`` lines):
540
541 .. container:: listingblock
542
543    .. container:: content
544
545       .. code::
546          :number-lines:
547
548          [INFO] tools .............................................. SUCCESS [  0.248 s]
549          [INFO] tools-common ....................................... SUCCESS [  0.784 s]
550          [INFO] simple-wsclient .................................... SUCCESS [  3.303 s]
551          [INFO] model-generator .................................... SUCCESS [  0.644 s]
552          [INFO] packages ........................................... SUCCESS [  0.336 s]
553          [INFO] apex-pdp-package-full .............................. SUCCESS [01:10 min]
554          [INFO] Policy APEX PDP - Docker build 2.0.0-SNAPSHOT ...... SUCCESS [ 10.307 s]
555          [INFO] ------------------------------------------------------------------------
556          [INFO] BUILD SUCCESS
557          [INFO] ------------------------------------------------------------------------
558          [INFO] Total time: 03:43 min
559          [INFO] Finished at: 2018-09-03T11:56:01+01:00
560          [INFO] ------------------------------------------------------------------------
561
562 .. container:: paragraph
563
564    The build will have created all artifacts required for an APEX
565    installation. The following example show how to change to the target
566    directory and how it should look like.
567
568 +-----------------------------------------------------------------------------------------------------------------------------+
569 | Unix, Cygwin                                                                                                                |
570 +=============================================================================================================================+
571 | .. container::                                                                                                              |
572 |                                                                                                                             |
573 |    .. container:: listingblock                                                                                              |
574 |                                                                                                                             |
575 |          .. code::                                                                                                          |
576 |            :number-lines:                                                                                                   |
577 |                                                                                                                             |
578 |            # cd packages/apex-pdp-package-full/target                                                                       |
579 |            # ls -l                                                                                                          |
580 |            -rwxrwx---+ 1 esvevan Domain Users       772 Sep  3 11:55 apex-pdp-package-full_2.0.0~SNAPSHOT_all.changes*      |
581 |            -rwxrwx---+ 1 esvevan Domain Users 146328082 Sep  3 11:55 apex-pdp-package-full-2.0.0-SNAPSHOT.deb*              |
582 |            -rwxrwx---+ 1 esvevan Domain Users     15633 Sep  3 11:54 apex-pdp-package-full-2.0.0-SNAPSHOT.jar*              |
583 |            -rwxrwx---+ 1 esvevan Domain Users 146296819 Sep  3 11:55 apex-pdp-package-full-2.0.0-SNAPSHOT-tarball.tar.gz*   |
584 |            drwxrwx---+ 1 esvevan Domain Users         0 Sep  3 11:54 archive-tmp/                                           |
585 |            -rwxrwx---+ 1 esvevan Domain Users        89 Sep  3 11:54 checkstyle-cachefile*                                  |
586 |            -rwxrwx---+ 1 esvevan Domain Users     10621 Sep  3 11:54 checkstyle-checker.xml*                                |
587 |            -rwxrwx---+ 1 esvevan Domain Users       584 Sep  3 11:54 checkstyle-header.txt*                                 |
588 |            -rwxrwx---+ 1 esvevan Domain Users        86 Sep  3 11:54 checkstyle-result.xml*                                 |
589 |            drwxrwx---+ 1 esvevan Domain Users         0 Sep  3 11:54 classes/                                               |
590 |            drwxrwx---+ 1 esvevan Domain Users         0 Sep  3 11:54 dependency-maven-plugin-markers/                       |
591 |            drwxrwx---+ 1 esvevan Domain Users         0 Sep  3 11:54 etc/                                                   |
592 |            drwxrwx---+ 1 esvevan Domain Users         0 Sep  3 11:54 examples/                                              |
593 |            drwxrwx---+ 1 esvevan Domain Users         0 Sep  3 11:55 install_hierarchy/                                     |
594 |            drwxrwx---+ 1 esvevan Domain Users         0 Sep  3 11:54 maven-archiver/                                        |
595 +-----------------------------------------------------------------------------------------------------------------------------+
596
597 +-----------------------------------------------------------------------------------------------------------------------------+
598 | Windows                                                                                                                     |
599 +=============================================================================================================================+
600 | .. container::                                                                                                              |
601 |                                                                                                                             |
602 |    .. container:: listingblock                                                                                              |
603 |                                                                                                                             |
604 |          .. code::                                                                                                          |
605 |            :number-lines:                                                                                                   |
606 |                                                                                                                             |
607 |            >cd packages\apex-pdp-package-full\target                                                                        |
608 |            >dir                                                                                                             |
609 |            03/09/2018  11:55    <DIR>          .                                                                            |
610 |            03/09/2018  11:55    <DIR>          ..                                                                           |
611 |            03/09/2018  11:55       146,296,819 apex-pdp-package-full-2.0.0-SNAPSHOT-tarball.tar.gz                          |
612 |            03/09/2018  11:55       146,328,082 apex-pdp-package-full-2.0.0-SNAPSHOT.deb                                     |
613 |            03/09/2018  11:54            15,633 apex-pdp-package-full-2.0.0-SNAPSHOT.jar                                     |
614 |            03/09/2018  11:55               772 apex-pdp-package-full_2.0.0~SNAPSHOT_all.changes                             |
615 |            03/09/2018  11:54    <DIR>          archive-tmp                                                                  |
616 |            03/09/2018  11:54                89 checkstyle-cachefile                                                         |
617 |            03/09/2018  11:54            10,621 checkstyle-checker.xml                                                       |
618 |            03/09/2018  11:54               584 checkstyle-header.txt                                                        |
619 |            03/09/2018  11:54                86 checkstyle-result.xml                                                        |
620 |            03/09/2018  11:54    <DIR>          classes                                                                      |
621 |            03/09/2018  11:54    <DIR>          dependency-maven-plugin-markers                                              |
622 |            03/09/2018  11:54    <DIR>          etc                                                                          |
623 |            03/09/2018  11:54    <DIR>          examples                                                                     |
624 |            03/09/2018  11:55    <DIR>          install_hierarchy                                                            |
625 |            03/09/2018  11:54    <DIR>          maven-archiver                                                               |
626 |                           8 File(s)    292,652,686 bytes                                                                    |
627 |                           9 Dir(s)  14,138,720,256 bytes free                                                               |
628 +-----------------------------------------------------------------------------------------------------------------------------+
629
630 .. container:: paragraph
631
632    Now, take the ``.deb`` or the ``.tar.gz`` file and install APEX.
633    Alternatively, copy the content of the folder ``install_hierarchy``
634    to your APEX directory.
635
636 Installation Layout
637 -------------------
638
639    .. container:: paragraph
640
641       A full installation of APEX comes with the following layout.
642
643    .. container:: listingblock
644
645       .. container:: content
646
647          ::
648
649             $APEX_HOME
650                 ├───bin             (1)
651                 ├───etc             (2)
652                 │   ├───editor
653                 │   ├───hazelcast
654                 │   ├───infinispan
655                 │   └───META-INF
656                 ├───examples            (3)
657                 │   ├───config          (4)
658                 │   ├───docker          (5)
659                 │   ├───events          (6)
660                 │   ├───html            (7)
661                 │   ├───models          (8)
662                 │   └───scripts         (9)
663                 ├───lib             (10)
664                 │   └───applications        (11)
665                 └───war             (12)
666
667    .. container:: colist arabic
668
669       +-----------------------------------+-----------------------------------+
670       | **1**                             | binaries, mainly scripts (bash    |
671       |                                   | and bat) to start the APEX engine |
672       |                                   | and applications                  |
673       +-----------------------------------+-----------------------------------+
674       | **2**                             | configuration files, such as      |
675       |                                   | logback (logging) and third party |
676       |                                   | library configurations            |
677       +-----------------------------------+-----------------------------------+
678       | **3**                             | example policy models to get      |
679       |                                   | started                           |
680       +-----------------------------------+-----------------------------------+
681       | **4**                             | configurations for the examples   |
682       |                                   | (with sub directories for         |
683       |                                   | individual examples)              |
684       +-----------------------------------+-----------------------------------+
685       | **5**                             | Docker files and additional       |
686       |                                   | Docker instructions for the       |
687       |                                   | exampples                         |
688       +-----------------------------------+-----------------------------------+
689       | **6**                             | example events for the examples   |
690       |                                   | (with sub directories for         |
691       |                                   | individual examples)              |
692       +-----------------------------------+-----------------------------------+
693       | **7**                             | HTML files for some examples,     |
694       |                                   | e.g. the Decisionmaker example    |
695       +-----------------------------------+-----------------------------------+
696       | **8**                             | the policy models, generated for  |
697       |                                   | each example (with sub            |
698       |                                   | directories for individual        |
699       |                                   | examples)                         |
700       +-----------------------------------+-----------------------------------+
701       | **9**                             | additional scripts for the        |
702       |                                   | examples (with sub directories    |
703       |                                   | for individual examples)          |
704       +-----------------------------------+-----------------------------------+
705       | **10**                            | the library folder with all Java  |
706       |                                   | JAR files                         |
707       +-----------------------------------+-----------------------------------+
708       | **11**                            | applications, also known as jar   |
709       |                                   | with dependencies (or fat jars),  |
710       |                                   | individually deployable           |
711       +-----------------------------------+-----------------------------------+
712       | **12**                            | WAR files for web applications    |
713       +-----------------------------------+-----------------------------------+
714
715 System Configuration
716 --------------------
717
718    .. container:: paragraph
719
720       Once APEX is installed, a few configurations need to be done:
721
722    .. container:: ulist
723
724       -  Create an APEX user and an APEX group (optional, if not
725          installed using RPM and DPKG)
726
727       -  Create environment settings for ``APEX_HOME`` and
728          ``APEX_USER``, required by the start scripts
729
730       -  Change settings of the logging framework (optional)
731
732       -  Create directories for logging, required (execution might fail
733          if directories do not exist or cannot be created)
734
735 APEX User and Group
736 ###################
737
738       .. container:: paragraph
739
740          On smaller installations and test systems, APEX can run as any
741          user or group.
742
743       .. container:: paragraph
744
745          However, if APEX is installed in production, we strongly
746          recommend you set up a dedicated user for running APEX. This
747          will isolate the execution of APEX to that user. We recommend
748          you use the userid ``apexuser`` but you may use any user you
749          choose.
750
751       .. container:: paragraph
752
753          The following example, for UNIX, creates a group called
754          ``apexuser``, an APEX user called ``apexuser``, adds the group
755          to the user, and changes ownership of the APEX installation to
756          the user. Substitute ``<apex-dir>`` with the directory where
757          APEX is installed.
758
759          .. container:: listingblock
760
761             .. container:: content
762
763                .. code::
764                   :number-lines:
765
766                   # sudo groupadd apexuser
767                   # sudo useradd -g apexuser apexuser
768                   # sudo chown -R apexuser:apexuser <apex-dir>
769
770 .. container:: paragraph
771
772    For other operating systems please consult your manual or system
773    administrator.
774
775 Environment Settings: APEX_HOME and APEX_USER
776 #############################################
777
778    .. container:: paragraph
779
780       The provided start scripts for APEX require two environment
781       variables being set:
782
783    .. container:: ulist
784
785       -  ``APEX_USER`` with the user under whos name and permission APEX
786          should be started (Unix only)
787
788       -  ``APEX_HOME`` with the directory where APEX is installed (Unix,
789          Windows, Cygwin)
790
791    .. container:: paragraph
792
793       The first row in the following table shows how to set these
794       environment variables temporary (assuming the user is
795       ``apexuser``). The second row shows how to verify the settings.
796       The last row explains how to set those variables permanently.
797
798    +------------------------------------------------+---------------------------------------------------------+
799    | Unix, Cygwin (bash/tcsh)                       | Windows                                                 |
800    +================================================+=========================================================+
801    | .. container::                                 | .. container::                                          |
802    |                                                |                                                         |
803    |    .. container:: content                      |    .. container:: content                               |
804    |                                                |                                                         |
805    |       .. code::                                |       .. code::                                         |
806    |          :number-lines:                        |         :number-lines:                                  |
807    |                                                |                                                         |
808    |          # export APEX_USER=apexuser           |         >set APEX_HOME=C:\apex\apex-full-2.0.0-SNAPSHOT |
809    |          # cd /opt/app/policy/apex-pdp         |                                                         |
810    |          # export APEX_HOME=`pwd`              |                                                         |
811    |                                                |                                                         |
812    +------------------------------------------------+                                                         |
813    | .. container::                                 |                                                         |
814    |                                                |                                                         |
815    |    .. container:: content                      |                                                         |
816    |                                                |                                                         |
817    |       .. code::tcsh                            |                                                         |
818    |          :number-lines:                        |                                                         |
819    |                                                |                                                         |
820    |          # setenv APEX_USER apexuser           |                                                         |
821    |          # cd /opt/app/policy/apex-pdp         |                                                         |
822    |          # setenv APEX_HOME `pwd`              |                                                         |
823    |                                                |                                                         |
824    +------------------------------------------------+---------------------------------------------------------+
825    | .. container::                                 | .. container::                                          |
826    |                                                |                                                         |
827    |    .. container:: content                      |    .. container:: content                               |
828    |                                                |                                                         |
829    |       .. code::                                |       .. code::                                         |
830    |          :number-lines:                        |          :number-lines:                                 |
831    |                                                |                                                         |
832    |          # env | grep APEX                     |          >set APEX_HOME                                 |
833    |          # APEX_USER=apexuser                  |          APEX_HOME=\apex\apex-full-2.0.0-SNAPSHOT       |
834    |          # APEX_HOME=/opt/app/policy/apex-pdp  |                                                         |
835    |                                                |                                                         |
836    +------------------------------------------------+---------------------------------------------------------+
837
838 Making Environment Settings Permanent (Unix, Cygwin)
839 ====================================================
840
841    .. container:: paragraph
842
843       For a per-user setting, edit the a user’s ``bash`` or ``tcsh``
844       settings in ``~/.bashrc`` or ``~/.tcshrc``. For system-wide
845       settings, edit ``/etc/profiles`` (requires permissions).
846
847 Making Environment Settings Permanent (Windows)
848 ===============================================
849
850    .. container:: paragraph
851
852       On Windows 7 do
853
854    .. container:: ulist
855
856       -  Click on the **Start** Menu
857
858       -  Right click on **Computer**
859
860       -  Select **Properties**
861
862    .. container:: paragraph
863
864       On Windows 8/10 do
865
866    .. container:: ulist
867
868       -  Click on the **Start** Menu
869
870       -  Select **System**
871
872    .. container:: paragraph
873
874       Then do the following
875
876    .. container:: ulist
877
878       -  Select **Advanced System Settings**
879
880       -  On the **Advanced** tab, click the **Environment Variables**
881          button
882
883       -  Edit an existing variable, or create a new System variable:
884          'Variable name'="APEX_HOME", 'Variable
885          value'="C:\apex\apex-full-2.0.0-SNAPSHOT"
886
887    .. container:: paragraph
888
889       For the settings to take effect, an application needs to be
890       restarted (e.g. any open ``cmd`` window).
891
892 Edit the APEX Logging Settings
893 ##############################
894
895    .. container:: paragraph
896
897       Configure the APEX logging settings to your requirements, for
898       instance:
899
900    .. container:: ulist
901
902       -  change the directory where logs are written to, or
903
904       -  change the log levels
905
906    .. container:: paragraph
907
908       Edit the file ``$APEX_HOME/etc/logback.xml`` for any required
909       changes. To change the log directory change the line
910
911    .. container:: paragraph
912
913       ``<property name="VAR_LOG" value="/var/log/onap/policy/apex-pdp/" />``
914
915    .. container:: paragraph
916
917       to
918
919    .. container:: paragraph
920
921       ``<property name="VAR_LOG" value="/PATH/TO/LOG/DIRECTORY/" />``
922
923    .. container:: paragraph
924
925       On Windows, it is recommended to change the log directory to:
926
927    .. container:: paragraph
928
929       ``<property name="VAR_LOG" value="C:/apex/apex-full-2.0.0-SNAPSHOT/logs" />``
930
931    .. container:: paragraph
932
933       Note: Be careful about when to use ``\`` vs. ``/`` as the path
934       separator!
935
936 Create Directories for Logging
937 ##############################
938
939    .. container:: paragraph
940
941       Make sure that the log directory exists. This is important when
942       APEX was installed manually or when the log directory was changed
943       in the settings (see above).
944
945    +------------------------------------------------------------------+-------------------------------------------------------+
946    | Unix, Cygwin                                                     | Windows                                               |
947    +==================================================================+=======================================================+
948    | .. container::                                                   | .. container::                                        |
949    |                                                                  |                                                       |
950    |    .. container:: content                                        |    .. container:: content                             |
951    |                                                                  |                                                       |
952    |       .. code::                                                  |       .. code::                                       |
953    |         :number-lines:                                           |         :number-lines:                                |
954    |                                                                  |                                                       |
955    |         mkdir -p /var/log/onap/policy/apex-pdp                   |         >mkdir C:\apex\apex-full-2.0.0-SNAPSHOT\logs  |
956    |         chown -R apexuser:apexuser /var/log/onap/policy/apex-pdp |                                                       |
957    +------------------------------------------------------------------+-------------------------------------------------------+
958
959 Verify the APEX Installation
960 ----------------------------
961
962    .. container:: paragraph
963
964       When APEX is installed and all settings are realized, the
965       installation can be verified.
966
967 Verify Installation - run Engine
968 ################################
969
970       .. container:: paragraph
971
972          A simple verification of an APEX installation can be done by
973          simply starting the APEX engine without any configuration. On
974          Unix (or Cygwin) start the engine using
975          ``$APEX_HOME/bin/apexEngine.sh``. On Windows start the engine
976          using ``%APEX_HOME%\bin\apexEngine.bat``. The engine will fail
977          to fully start. However, if the output looks similar to the
978          following line, the APEX installation is realized.
979
980       .. container:: listingblock
981
982          .. container:: content
983
984             .. code::
985                :number-lines:
986
987                Starting Apex service with parameters [] . . .
988                start of Apex service failed: Apex configuration file was not specified as an argument
989                2018-09-03 13:11:33,914 Apex [main] ERROR o.o.p.a.service.engine.main.ApexMain - start of Apex service failed
990                org.onap.policy.apex.model.basicmodel.concepts.ApexException: Apex configuration file was not specified as an argument
991                        at org.onap.policy.apex.service.engine.main.ApexCommandLineArguments.validateReadableFile(ApexCommandLineArguments.java:267)
992                        at org.onap.policy.apex.service.engine.main.ApexCommandLineArguments.validate(ApexCommandLineArguments.java:161)
993                        at org.onap.policy.apex.service.engine.main.ApexMain.<init>(ApexMain.java:68)
994                        at org.onap.policy.apex.service.engine.main.ApexMain.main(ApexMain.java:165)
995                usage: org.onap.policy.apex.service.engine.main.ApexMain [options...]
996                options
997                -c,--config-file <CONFIG_FILE>the full path to the configuration file to use, the configuration file must be a Json file
998                                              containing the Apex configuration parameters
999                -h,--help                     outputs the usage of this command
1000                -m,--model-file <MODEL_FILE>  the full path to the model file to use, if set it overrides the model file set in the
1001                                              configuration file
1002                -v,--version                  outputs the version of Apex
1003
1004 Verify Installation - run an Example
1005 ####################################
1006
1007    .. container:: paragraph
1008
1009       A full APEX installation comes with several examples. Here, we can
1010       fully verify the installation by running one of the examples.
1011
1012    .. container:: paragraph
1013
1014       We use the example called *SampleDomain* and configure the engine
1015       to use standard in and standard out for events. Run the engine
1016       with the provided configuration. Note: Cygwin executes scripts as
1017       Unix scripts but runs Java as a Windows application, thus the
1018       configuration file must be given as a Windows path.
1019
1020    .. container:: listingblock
1021
1022       .. container:: content
1023
1024          .. code::
1025                 :number-lines:
1026
1027              # $APEX_HOME/bin/apexEngine.sh -c $APEX_HOME/examples/config/SampleDomain/Stdin2StdoutJsonEventJava.json (1)
1028              # $APEX_HOME/bin/apexEngine.sh -c C:/apex/apex-full-2.0.0-SNAPSHOT/examples/config/SampleDomain/Stdin2StdoutJsonEventJava.json (2)
1029              >%APEX_HOME%\bin\apexEngine.bat -c %APEX_HOME%\examples\config\SampleDomain\Stdin2StdoutJsonEventJava.json :: (3)
1030
1031 .. container:: colist arabic
1032
1033    +-------+---------+
1034    | **1** | UNIX    |
1035    +-------+---------+
1036    | **2** | Cygwin  |
1037    +-------+---------+
1038    | **3** | Windows |
1039    +-------+---------+
1040
1041 .. container:: paragraph
1042
1043    The engine should start successfully. Assuming the logging levels are
1044    not change (default level is ``info``), the output should look
1045    similar to this (last few lines)
1046
1047 .. container:: listingblock
1048
1049    .. container:: content
1050
1051       .. code::
1052          :number-lines:
1053
1054          Starting Apex service with parameters [-c, v:/dev/ericsson/apex/onap/apex-pdp/packages/apex-pdp-package-full/target/install_hierarchy/examples/config/SampleDomain/Stdin2StdoutJsonEventJava.json] . . .
1055          2018-09-05 15:16:42,800 Apex [main] INFO o.o.p.a.s.e.r.impl.EngineServiceImpl - Created apex engine MyApexEngine-0:0.0.1 .
1056          2018-09-05 15:16:42,804 Apex [main] INFO o.o.p.a.s.e.r.impl.EngineServiceImpl - Created apex engine MyApexEngine-1:0.0.1 .
1057          2018-09-05 15:16:42,804 Apex [main] INFO o.o.p.a.s.e.r.impl.EngineServiceImpl - Created apex engine MyApexEngine-2:0.0.1 .
1058          2018-09-05 15:16:42,805 Apex [main] INFO o.o.p.a.s.e.r.impl.EngineServiceImpl - Created apex engine MyApexEngine-3:0.0.1 .
1059          2018-09-05 15:16:42,805 Apex [main] INFO o.o.p.a.s.e.r.impl.EngineServiceImpl - APEX service created.
1060          2018-09-05 15:16:43,962 Apex [main] INFO o.o.p.a.s.e.e.EngDepMessagingService - engine<-->deployment messaging starting . . .
1061          2018-09-05 15:16:43,963 Apex [main] INFO o.o.p.a.s.e.e.EngDepMessagingService - engine<-->deployment messaging started
1062          2018-09-05 15:16:44,987 Apex [main] INFO o.o.p.a.s.e.r.impl.EngineServiceImpl - Registering apex model on engine MyApexEngine-0:0.0.1
1063          2018-09-05 15:16:45,112 Apex [main] INFO o.o.p.a.s.e.r.impl.EngineServiceImpl - Registering apex model on engine MyApexEngine-1:0.0.1
1064          2018-09-05 15:16:45,113 Apex [main] INFO o.o.p.a.s.e.r.impl.EngineServiceImpl - Registering apex model on engine MyApexEngine-2:0.0.1
1065          2018-09-05 15:16:45,113 Apex [main] INFO o.o.p.a.s.e.r.impl.EngineServiceImpl - Registering apex model on engine MyApexEngine-3:0.0.1
1066          2018-09-05 15:16:45,120 Apex [main] INFO o.o.p.a.s.e.r.impl.EngineServiceImpl - Added the action listener to the engine
1067          Started Apex service
1068
1069 .. container:: paragraph
1070
1071    Important are the last two line, stating that APEX has added the
1072    final action listener to the engine and that the engine is started.
1073
1074 .. container:: paragraph
1075
1076    The engine is configured to read events from standard input and write
1077    produced events to standard output. The policy model is a very simple
1078    policy.
1079
1080 .. container:: paragraph
1081
1082    The following table shows an input event in the left column and an
1083    output event in the right column. Past the input event into the
1084    console where APEX is running, and the output event should appear in
1085    the console. Pasting the input event multiple times will produce
1086    output events with different values.
1087
1088 +-------------------------------------------------------------+-------------------------------------------------------------+
1089 | Input Event                                                 | Example Output Event                                        |
1090 +=============================================================+=============================================================+
1091 | .. container::                                              | .. container::                                              |
1092 |                                                             |                                                             |
1093 |    .. container:: content                                   |    .. container:: content                                   |
1094 |                                                             |                                                             |
1095 |       .. code::                                             |       .. code::                                             |
1096 |         :number-lines:                                      |         :number-lines:                                      |
1097 |                                                             |                                                             |
1098 |         {                                                   |         {                                                   |
1099 |          "nameSpace": "org.onap.policy.apex.sample.events", |          "name": "Event0004",                               |
1100 |          "name": "Event0000",                               |          "version": "0.0.1",                                |
1101 |          "version": "0.0.1",                                |          "nameSpace": "org.onap.policy.apex.sample.events", |
1102 |          "source": "test",                                  |          "source": "Act",                                   |
1103 |          "target": "apex",                                  |          "target": "Outside",                               |
1104 |          "TestSlogan": "Test slogan for External Event0",   |          "TestActCaseSelected": 2,                          |
1105 |          "TestMatchCase": 0,                                |          "TestActStateTime": 1536157104627,                 |
1106 |          "TestTimestamp": 1469781869269,                    |          "TestDecideCaseSelected": 0,                       |
1107 |          "TestTemperature": 9080.866                        |          "TestDecideStateTime": 1536157104625,              |
1108 |         }                                                   |          "TestEstablishCaseSelected": 0,                    |
1109 |                                                             |          "TestEstablishStateTime": 1536157104623,           |
1110 |                                                             |          "TestMatchCase": 0,                                |
1111 |                                                             |          "TestMatchCaseSelected": 1,                        |
1112 |                                                             |          "TestMatchStateTime": 1536157104620,               |
1113 |                                                             |          "TestSlogan": "Test slogan for External Event0",   |
1114 |                                                             |          "TestTemperature": 9080.866,                       |
1115 |                                                             |          "TestTimestamp": 1469781869269                     |
1116 |                                                             |          }                                                  |
1117 +-------------------------------------------------------------+-------------------------------------------------------------+
1118
1119 .. container:: paragraph
1120
1121    Terminate APEX by simply using ``CTRL+C`` in the console.
1122
1123 Verify a Full Installation - REST Editor
1124 ########################################
1125
1126    .. container:: paragraph
1127
1128       APEX has a REST application for viewing policy models. The
1129       application can also be used to create new policy models close to
1130       the engine native policy language. Start the REST editor as
1131       follows.
1132
1133    .. container:: listingblock
1134
1135       .. container:: content
1136
1137          .. code::
1138             :number-lines:
1139
1140             # $APEX_HOME/bin/apexApps.sh rest-editor
1141
1142 .. container:: listingblock
1143
1144    .. container:: content
1145
1146       .. code::
1147             :number-lines:
1148
1149             >%APEX_HOME%\bin\apexApps.bat rest-editor
1150
1151 .. container:: paragraph
1152
1153    The script will start a simple web server
1154    (`Grizzly <https://javaee.github.io/grizzly/>`__) and deploy a
1155    ``war`` web archive in it. Once the editor is started, it will be
1156    available on ``localhost:18989``. The last few line of the messages
1157    should be:
1158
1159 .. container:: listingblock
1160
1161    .. container:: content
1162
1163       .. code::
1164          :number-lines:
1165
1166          Apex Editor REST endpoint (ApexEditorMain: Config=[ApexEditorParameters: URI=http://localhost:18989/apexservices/, TTL=-1sec], State=READY) starting at http://localhost:18989/apexservices/ . . .
1167          Sep 05, 2018 10:35:57 PM org.glassfish.grizzly.http.server.NetworkListener start
1168          INFO: Started listener bound to [localhost:18989]
1169          Sep 05, 2018 10:35:57 PM org.glassfish.grizzly.http.server.HttpServer start
1170          INFO: [HttpServer] Started.
1171          Apex Editor REST endpoint (ApexEditorMain: Config=[ApexEditorParameters: URI=http://localhost:18989/apexservices/, TTL=-1sec], State=RUNNING) started at http://localhost:18989/apexservices/
1172
1173 .. container:: paragraph
1174
1175    Now open a browser (Firefox, Chrome, Opera, Internet Explorer) and
1176    use the URL ``http://localhost:18989/``. This will connect the
1177    browser to the started REST editor. The start screen should be as
1178    follows.
1179
1180 .. container:: imageblock
1181
1182    .. container:: content
1183
1184       |REST Editor Start Screen|
1185
1186    .. container:: title
1187
1188       Figure 1. REST Editor Start Screen
1189
1190 .. container:: paragraph
1191
1192    Now load a policy model by clicking the menu ``File`` and then
1193    ``Open``. In the opened dialog, go to the directory where APEX is
1194    installed, then ``examples``, ``models``, ``SampleDomain``, and there
1195    select the file ``SamplePolicyModelJAVA.json``. This will load the
1196    policy model used to verify the policy engine (see above). Once
1197    loaded, the screen should look as follows.
1198
1199 .. container:: imageblock
1200
1201    .. container:: content
1202
1203       |REST Editor with loaded SampleDomain Policy Model|
1204
1205    .. container:: title
1206
1207       Figure 2. REST Editor with loaded SampleDomain Policy Model
1208
1209 .. container:: paragraph
1210
1211    Now you can use the REST editor. To finish this verification, simply
1212    terminate your browser (or the tab), and then use ``CTRL+C`` in the
1213    console where you started the REST editor.
1214
1215 Installing WAR Applications
1216 ---------------------------
1217
1218    .. container:: paragraph
1219
1220       APEX comes with a set of WAR files. These are complete
1221       applications that can be installed and run in an application
1222       server. All of these applications are realized as servlets. You
1223       can find the WAR applications in ``$APEX_HOME/war`` (UNIX, Cygwin)
1224       or ``%APEX_HOME%\war`` (Windows).
1225
1226    .. container:: paragraph
1227
1228       Installing and using the WAR applications requires a web server
1229       that can execute ``war`` web archives. We recommend to use `Apache
1230       Tomcat <https://tomcat.apache.org/>`__, however other web servers
1231       can be used as well.
1232
1233    .. container:: paragraph
1234
1235       Install Apache Tomcat including the ``Manager App``, see `V9.0
1236       Docs <https://tomcat.apache.org/tomcat-9.0-doc/manager-howto.html#Configuring_Manager_Application_Access>`__
1237       for details. Start the Tomcat service, or make sure that Tomcat is
1238       running.
1239
1240    .. container:: paragraph
1241
1242       There are multiple ways to install the APEX WAR applications:
1243
1244    .. container:: ulist
1245
1246       -  copy the ``.war`` file into the Tomcat ``webapps`` folder
1247
1248       -  use the Tomcat ``Manager App`` to deploy via the web interface
1249
1250       -  deploy using a REST call to Tomcat
1251
1252    .. container:: paragraph
1253
1254       For details on how to install ``war`` files please consult the
1255       `Tomcat
1256       Documentation <https://tomcat.apache.org/tomcat-9.0-doc/index.html>`__
1257       or the `Manager App
1258       HOW-TO <https://tomcat.apache.org/tomcat-9.0-doc/manager-howto.html>`__.
1259       Once you installed an APEX WAR application (and wait for
1260       sufficient time for Tomcat to finalize the installation), open the
1261       ``Manager App`` in Tomcat. You should see the APEX WAR application
1262       being installed and running.
1263
1264    .. container:: paragraph
1265
1266       In case of errors, examine the log files in the Tomcat log
1267       directory. In a conventional install, those log files are in the
1268       logs directory where Tomcat is installed.
1269
1270    .. container:: paragraph
1271
1272       The current APEX version provides the following WAR applications:
1273
1274    .. container:: ulist
1275
1276       -  client-deployment-2.0.0-SNAPSHOT.war - a client to deploy new
1277          policy models to a running engine
1278
1279       -  client-editor-2.0.0-SNAPSHOT.war - the standard policy REST
1280          editor GUI
1281
1282       -  client-monitoring-2.0.0-SNAPSHOT.war - a client for monitoring
1283          a running APEX engine
1284
1285       -  client-full-2.0.0-SNAPSHOT.war - a full client with a
1286          one-stop-access to deployment, monitoring, and REST editor
1287
1288       -  examples-servlet-2.0.0-SNAPSHOT.war - an example APEX servlet
1289
1290 Running APEX in Docker
1291 ----------------------
1292
1293    .. container:: paragraph
1294
1295       Since APEX is in ONAP, we provide a full virtualization
1296       environment for the engine.
1297
1298 Run in ONAP
1299 ###########
1300
1301       .. container:: paragraph
1302
1303          Running APEX from the ONAP docker repository only requires 2
1304          commands:
1305
1306       .. container:: olist arabic
1307
1308          #. Log into the ONAP docker repo
1309
1310       .. container:: listingblock
1311
1312          .. container:: content
1313
1314             ::
1315
1316                docker login -u docker -p docker nexus3.onap.org:10003
1317
1318       .. container:: olist arabic
1319
1320          #. Run the APEX docker image
1321
1322       .. container:: listingblock
1323
1324          .. container:: content
1325
1326             ::
1327
1328                docker run -it --rm  nexus3.onap.org:10003/onap/policy-apex-pdp:latest
1329
1330 Build a Docker Image
1331 ####################
1332
1333       .. container:: paragraph
1334
1335          Alternatively, one can use the Dockerfile defined in the Docker
1336          package to build an image.
1337
1338       .. container:: listingblock
1339
1340          .. container:: title
1341
1342             APEX Dockerfile
1343
1344          .. container:: content
1345
1346             .. code::
1347                :number-lines:
1348
1349                #
1350                # Docker file to build an image that runs APEX on Java 8 in Ubuntu
1351                #
1352                FROM ubuntu:16.04
1353
1354                RUN apt-get update && \
1355                        apt-get upgrade -y && \
1356                        apt-get install -y software-properties-common && \
1357                        add-apt-repository ppa:openjdk-r/ppa -y && \
1358                        apt-get update && \
1359                        apt-get install -y openjdk-8-jdk
1360
1361                # Create apex user and group
1362                RUN groupadd apexuser
1363                RUN useradd --create-home -g apexuser apexuser
1364
1365                # Add Apex-specific directories and set ownership as the Apex admin user
1366                RUN mkdir -p /opt/app/policy/apex-pdp
1367                RUN mkdir -p /var/log/onap/policy/apex-pdp
1368                RUN chown -R apexuser:apexuser /var/log/onap/policy/apex-pdp
1369
1370                # Unpack the tarball
1371                RUN mkdir /packages
1372                COPY apex-pdp-package-full.tar.gz /packages
1373                RUN tar xvfz /packages/apex-pdp-package-full.tar.gz --directory /opt/app/policy/apex-pdp
1374                RUN rm /packages/apex-pdp-package-full.tar.gz
1375
1376                # Ensure everything has the correct permissions
1377                RUN find /opt/app -type d -perm 755
1378                RUN find /opt/app -type f -perm 644
1379                RUN chmod a+x /opt/app/policy/apex-pdp/bin/*
1380
1381                # Copy examples to Apex user area
1382                RUN cp -pr /opt/app/policy/apex-pdp/examples /home/apexuser
1383
1384                RUN apt-get clean
1385
1386                RUN chown -R apexuser:apexuser /home/apexuser/*
1387
1388                USER apexuser
1389                ENV PATH /opt/app/policy/apex-pdp/bin:$PATH
1390                WORKDIR /home/apexuser
1391
1392 APEX Configurations Explained
1393 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1394
1395 Introduction to APEX Configuration
1396 ----------------------------------
1397
1398          .. container:: paragraph
1399
1400             An APEX engine can be configured to use various combinations
1401             of event input handlers, event output handlers, event
1402             protocols, context handlers, and logic executors. The system
1403             is build using a plugin architecture. Each configuration
1404             option is realized by a plugin, which can be loaded and
1405             configured when the engine is started. New plugins can be
1406             added to the system at any time, though to benefit from a
1407             new plugin an engine will need to be restarted.
1408
1409          .. container:: imageblock
1410
1411             .. container:: content
1412
1413                |APEX Configuration Matrix|
1414
1415             .. container:: title
1416
1417                Figure 3. APEX Configuration Matrix
1418
1419          .. container:: paragraph
1420
1421             The APEX distribution already comes with a number of
1422             plugins. The figure above shows the provided plugins. Any
1423             combination of input, output, event protocol, context
1424             handlers, and executors is possible.
1425
1426 General Configuration Format
1427 ----------------------------
1428
1429          .. container:: paragraph
1430
1431             The APEX configuration file is a JSON file containing a few
1432             main blocks for different parts of the configuration. Each
1433             block then holds the configuration details. The following
1434             code shows the main blocks:
1435
1436          .. container:: listingblock
1437
1438             .. container:: content
1439
1440                .. code::
1441
1442                   {
1443                     "engineServiceParameters":{
1444                       ... (1)
1445                       "engineParameters":{ (2)
1446                         "engineParameters":{...}, (3)
1447                         "contextParameters":{...} (4)
1448                       }
1449                     },
1450                     "eventInputParameters":{ (5)
1451                       "input1":{ (6)
1452                         "carrierTechnologyParameters":{...},
1453                         "eventProtocolParameters":{...}
1454                       },
1455                       "input2":{...}, (7)
1456                         "carrierTechnologyParameters":{...},
1457                         "eventProtocolParameters":{...}
1458                       },
1459                       ... (8)
1460                     },
1461                     "eventOutputParameters":{ (9)
1462                       "output1":{ (10)
1463                         "carrierTechnologyParameters":{...},
1464                         "eventProtocolParameters":{...}
1465                       },
1466                       "output2":{ (11)
1467                         "carrierTechnologyParameters":{...},
1468                         "eventProtocolParameters":{...}
1469                       },
1470                       ... (12)
1471                     }
1472                   }
1473
1474          .. container:: colist arabic
1475
1476             +-----------------------------------+-----------------------------------+
1477             | **1**                             | main engine configuration         |
1478             +-----------------------------------+-----------------------------------+
1479             | **2**                             | engine parameters for plugin      |
1480             |                                   | configurations (execution         |
1481             |                                   | environments and context          |
1482             |                                   | handling)                         |
1483             +-----------------------------------+-----------------------------------+
1484             | **3**                             | engine specific parameters,       |
1485             |                                   | mainly for executor plugins       |
1486             +-----------------------------------+-----------------------------------+
1487             | **4**                             | context specific parameters, e.g. |
1488             |                                   | for context schemas, persistence, |
1489             |                                   | etc.                              |
1490             +-----------------------------------+-----------------------------------+
1491             | **5**                             | configuration of the input        |
1492             |                                   | interface                         |
1493             +-----------------------------------+-----------------------------------+
1494             | **6**                             | an example input called           |
1495             |                                   | ``input1`` with carrier           |
1496             |                                   | technology and event protocol     |
1497             +-----------------------------------+-----------------------------------+
1498             | **7**                             | an example input called           |
1499             |                                   | ``input2`` with carrier           |
1500             |                                   | technology and event protocol     |
1501             +-----------------------------------+-----------------------------------+
1502             | **8**                             | any further input configuration   |
1503             +-----------------------------------+-----------------------------------+
1504             | **9**                             | configuration of the output       |
1505             |                                   | interface                         |
1506             +-----------------------------------+-----------------------------------+
1507             | **10**                            | an example output called          |
1508             |                                   | ``output1`` with carrier          |
1509             |                                   | technology and event protocol     |
1510             +-----------------------------------+-----------------------------------+
1511             | **11**                            | an example output called          |
1512             |                                   | ``output2`` with carrier          |
1513             |                                   | technology and event protocol     |
1514             +-----------------------------------+-----------------------------------+
1515             | **12**                            | any further output configuration  |
1516             +-----------------------------------+-----------------------------------+
1517
1518 Engine Service Parameters
1519 -------------------------
1520
1521          .. container:: paragraph
1522
1523             The configuration provides a number of parameters to
1524             configure the engine. An example configuration with
1525             explanations of all options is shown below.
1526
1527          .. container:: listingblock
1528
1529             .. container:: content
1530
1531                .. code::
1532
1533                   "engineServiceParameters" : {
1534                     "name"          : "AADMApexEngine", (1)
1535                     "version"        : "0.0.1",  (2)
1536                     "id"             :  45,  (3)
1537                     "instanceCount"  : 4,  (4)
1538                     "deploymentPort" : 12345,  (5)
1539                     "policyModelFileName" : "examples/models/VPN/VPNPolicyModelJava.json", (6)
1540                     "periodicEventPeriod": 1000, (7)
1541                     "engineParameters":{ (8)
1542                       "engineParameters":{...}, (9)
1543                       "contextParameters":{...} (10)
1544                     }
1545                   }
1546
1547          .. container:: colist arabic
1548
1549             +-----------------------------------+-----------------------------------+
1550             | **1**                             | a name for the engine. The engine |
1551             |                                   | name is used to create a key in a |
1552             |                                   | runtime engine. An name matching  |
1553             |                                   | the following regular expression  |
1554             |                                   | can be used here:                 |
1555             |                                   | ``[A-Za-z0-9\\-_\\.]+``           |
1556             +-----------------------------------+-----------------------------------+
1557             | **2**                             | a version of the engine, use      |
1558             |                                   | semantic versioning as explained  |
1559             |                                   | here: `Semantic                   |
1560             |                                   | Versioning <http://semver.org/>`_ |
1561             |                                   | _.                                |
1562             |                                   | This version is used in a runtime |
1563             |                                   | engine to create a version of the |
1564             |                                   | engine. For that reason, the      |
1565             |                                   | version must match the following  |
1566             |                                   | regular expression ``[A-Z0-9.]+`` |
1567             +-----------------------------------+-----------------------------------+
1568             | **3**                             | a numeric identifier for the      |
1569             |                                   | engine                            |
1570             +-----------------------------------+-----------------------------------+
1571             | **4**                             | the number of threads (policy     |
1572             |                                   | instances executed in parallel)   |
1573             |                                   | the engine should use, use ``1``  |
1574             |                                   | for single threaded engines       |
1575             +-----------------------------------+-----------------------------------+
1576             | **5**                             | the port for the deployment       |
1577             |                                   | Websocket connection to the       |
1578             |                                   | engine                            |
1579             +-----------------------------------+-----------------------------------+
1580             | **6**                             | the model file to load into the   |
1581             |                                   | engine on startup (optional)      |
1582             +-----------------------------------+-----------------------------------+
1583             | **7**                             | an optional timer for periodic    |
1584             |                                   | policies, in milliseconds (a      |
1585             |                                   | defined periodic policy will be   |
1586             |                                   | executed every ``X``              |
1587             |                                   | milliseconds), not used of not    |
1588             |                                   | set or ``0``                      |
1589             +-----------------------------------+-----------------------------------+
1590             | **8**                             | engine parameters for plugin      |
1591             |                                   | configurations (execution         |
1592             |                                   | environments and context          |
1593             |                                   | handling)                         |
1594             +-----------------------------------+-----------------------------------+
1595             | **9**                             | engine specific parameters,       |
1596             |                                   | mainly for executor plugins       |
1597             +-----------------------------------+-----------------------------------+
1598             | **10**                            | context specific parameters, e.g. |
1599             |                                   | for context schemas, persistence, |
1600             |                                   | etc.                              |
1601             +-----------------------------------+-----------------------------------+
1602
1603          .. container:: paragraph
1604
1605             The model file is optional, it can also be specified via
1606             command line. In any case, make sure all execution and other
1607             required plug-ins for the loaded model are loaded as
1608             required.
1609
1610 Input and Output Interfaces
1611 ---------------------------
1612
1613          .. container:: paragraph
1614
1615             An APEX engine has two main interfaces:
1616
1617          .. container:: ulist
1618
1619             -  An *input* interface to receive events: also known as
1620                ingress interface or consumer, receiving (consuming)
1621                events commonly named triggers, and
1622
1623             -  An *output* interface to publish produced events: also
1624                known as egress interface or producer, sending
1625                (publishing) events commonly named actions or action
1626                events.
1627
1628          .. container:: paragraph
1629
1630             The input and output interface is configured in terms of
1631             inputs and outputs, respectively. Each input and output is a
1632             combination of a carrier technology and an event protocol.
1633             Carrier technologies and event protocols are provided by
1634             plugins, each with its own specific configuration. Most
1635             carrier technologies can be configured for input as well as
1636             output. Most event protocols can be used for all carrier
1637             technologies. One exception is the JMS object event
1638             protocol, which can only be used for the JMS carrier
1639             technology. Some further restrictions apply (for instance
1640             for carrier technologies using bi- or uni-directional
1641             modes).
1642
1643          .. container:: paragraph
1644
1645             Input and output interface can be configured separately, in
1646             isolation, with any number of carrier technologies. The
1647             resulting general configuration options are:
1648
1649          .. container:: ulist
1650
1651             -  Input interface with one or more inputs
1652
1653                .. container:: ulist
1654
1655                   -  each input with a carrier technology and an event
1656                      protocol
1657
1658                   -  some inputs with optional synchronous mode
1659
1660                   -  some event protocols with additional parameters
1661
1662             -  Output interface with one or more outputs
1663
1664                .. container:: ulist
1665
1666                   -  each output with a carrier technology and an event
1667                      encoding
1668
1669                   -  some outputs with optional synchronous mode
1670
1671                   -  some event protocols with additional parameters
1672
1673          .. container:: paragraph
1674
1675             The configuration for input and output is contained in
1676             ``eventInputParameters`` and ``eventOutputParameters``,
1677             respectively. Inside here, one can configure any number of
1678             inputs and outputs. Each of them needs to have a unique
1679             identifier (name), the content of the name is free form. The
1680             example below shows a configuration for two inputs and two
1681             outputs.
1682
1683          .. container:: listingblock
1684
1685             .. container:: content
1686
1687                .. code::
1688
1689                   "eventInputParameters": { (1)
1690                     "FirstConsumer": { (2)
1691                       "carrierTechnologyParameters" : {...}, (3)
1692                       "eventProtocolParameters":{...}, (4)
1693                       ... (5)
1694                     },
1695                     "SecondConsumer": { (6)
1696                       "carrierTechnologyParameters" : {...}, (7)
1697                       "eventProtocolParameters":{...}, (8)
1698                       ... (9)
1699                     },
1700                   },
1701                   "eventOutputParameters": { (10)
1702                     "FirstProducer": { (11)
1703                       "carrierTechnologyParameters":{...}, (12)
1704                       "eventProtocolParameters":{...}, (13)
1705                       ... (14)
1706                     },
1707                     "SecondProducer": { (15)
1708                       "carrierTechnologyParameters":{...}, (16)
1709                       "eventProtocolParameters":{...}, (17)
1710                       ... (18)
1711                     }
1712                   }
1713
1714          .. container:: colist arabic
1715
1716             +--------+--------------------------------------------------------------------+
1717             | **1**  | input interface configuration, APEX input plugins                  |
1718             +--------+--------------------------------------------------------------------+
1719             | **2**  | first input called ``FirstConsumer``                               |
1720             +--------+--------------------------------------------------------------------+
1721             | **3**  | carrier technology for plugin                                      |
1722             +--------+--------------------------------------------------------------------+
1723             | **4**  | event protocol for plugin                                          |
1724             +--------+--------------------------------------------------------------------+
1725             | **5**  | any other input configuration (e.g. event name filter, see below)  |
1726             +--------+--------------------------------------------------------------------+
1727             | **6**  | second input called ``SecondConsumer``                             |
1728             +--------+--------------------------------------------------------------------+
1729             | **7**  | carrier technology for plugin                                      |
1730             +--------+--------------------------------------------------------------------+
1731             | **8**  | event protocol for plugin                                          |
1732             +--------+--------------------------------------------------------------------+
1733             | **9**  | any other plugin configuration                                     |
1734             +--------+--------------------------------------------------------------------+
1735             | **10** | output interface configuration, APEX output plugins                |
1736             +--------+--------------------------------------------------------------------+
1737             | **11** | first output called ``FirstProducer``                              |
1738             +--------+--------------------------------------------------------------------+
1739             | **12** | carrier technology for plugin                                      |
1740             +--------+--------------------------------------------------------------------+
1741             | **13** | event protocol for plugin                                          |
1742             +--------+--------------------------------------------------------------------+
1743             | **14** | any other plugin configuration                                     |
1744             +--------+--------------------------------------------------------------------+
1745             | **15** | second output called ``SecondProducer``                            |
1746             +--------+--------------------------------------------------------------------+
1747             | **16** | carrier technology for plugin                                      |
1748             +--------+--------------------------------------------------------------------+
1749             | **17** | event protocol for plugin                                          |
1750             +--------+--------------------------------------------------------------------+
1751             | **18** | any other output configuration (e.g. event name filter, see below) |
1752             +--------+--------------------------------------------------------------------+
1753
1754 Event Filters
1755 #############
1756
1757             .. container:: paragraph
1758
1759                APEX will always send an event after a policy execution
1760                is finished. For a successful execution, the event sent
1761                is the output event created by the policy. In case the
1762                policy does not create an output event, APEX will create
1763                a new event with all input event fields plus an
1764                additional field ``exceptionMessage`` with an exception
1765                message.
1766
1767             .. container:: paragraph
1768
1769                There are situations in which this auto-generated error
1770                event might not be required or wanted:
1771
1772             .. container:: ulist
1773
1774                -  when a policy failing should not result in an event
1775                   send out via an output interface
1776
1777                -  when the auto-generated event goes back in an APEX
1778                   engine (or the same APEX engine), this can create
1779                   endless loops
1780
1781                -  the auto-generated event should go to a special output
1782                   interface or channel
1783
1784             .. container:: paragraph
1785
1786                All of these situations are supported by a filter option
1787                using a wildecard (regular expression) configuration on
1788                APEX I/O interfaces. The parameter is called
1789                ``eventNameFilter`` and the value are `Java regular
1790                expressions <https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html>`__
1791                (a
1792                `tutorial <http://www.vogella.com/tutorials/JavaRegularExpressions/article.html>`__).
1793                The following code shows some examples:
1794
1795             .. container:: listingblock
1796
1797                .. container:: content
1798
1799                   .. code::
1800
1801                      "eventInputParameters": {
1802                        "Input1": {
1803                          "carrierTechnologyParameters" : {...},
1804                          "eventProtocolParameters":{...},
1805                          "eventNameFilter" : "^E[Vv][Ee][Nn][Tt][0-9]004$" (1)
1806                        }
1807                      },
1808                      "eventOutputParameters": {
1809                        "Output1": {
1810                          "carrierTechnologyParameters":{...},
1811                          "eventProtocolParameters":{...},
1812                          "eventNameFilter" : "^E[Vv][Ee][Nn][Tt][0-9]104$" (2)
1813                        }
1814                      }
1815
1816 Executors
1817 ---------
1818
1819          .. container:: paragraph
1820
1821             Executors are plugins that realize the execution of logic
1822             contained in a policy model. Logic can be in a task
1823             selector, a task, and a state finalizer. Using plugins for
1824             execution environments makes APEX very flexible to support
1825             virtually any executable logic expressions.
1826
1827          .. container:: paragraph
1828
1829             APEX 2.0.0-SNAPSHOT supports the following executors:
1830
1831          .. container:: ulist
1832
1833             -  Java, for Java implemented logic
1834
1835                .. container:: ulist
1836
1837                   -  This executor requires logic implemented using the
1838                      APEX Java interfaces.
1839
1840                   -  Generated JAR files must be in the classpath of the
1841                      APEX engine at start time.
1842
1843             -  Javascript
1844
1845             -  JRuby,
1846
1847             -  Jython,
1848
1849             -  MVEL
1850
1851                .. container:: ulist
1852
1853                   -  This executor uses the latest version of the MVEL
1854                      engine, which can be very hard to debug and can
1855                      produce unwanted side effects during execution
1856
1857 Configure the Javascript Executor
1858 #################################
1859
1860             .. container:: paragraph
1861
1862                The Javascript executor is added to the configuration as
1863                follows:
1864
1865             .. container:: listingblock
1866
1867                .. container:: content
1868
1869                   .. code::
1870
1871                      "engineServiceParameters":{
1872                        "engineParameters":{
1873                          "executorParameters":{
1874                            "JAVASCRIPT":{
1875                              "parameterClassName" :
1876                              "org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters"
1877                            }
1878                          }
1879                        }
1880                      }
1881
1882 Configure the Jython Executor
1883 #############################
1884
1885             .. container:: paragraph
1886
1887                The Jython executor is added to the configuration as
1888                follows:
1889
1890             .. container:: listingblock
1891
1892                .. container:: content
1893
1894                   .. code::
1895
1896                      "engineServiceParameters":{
1897                        "engineParameters":{
1898                          "executorParameters":{
1899                            "JYTHON":{
1900                              "parameterClassName" :
1901                              "org.onap.policy.apex.plugins.executor.jython.JythonExecutorParameters"
1902                            }
1903                          }
1904                        }
1905                      }
1906
1907 Configure the JRuby Executor
1908 ############################
1909
1910             .. container:: paragraph
1911
1912                The JRuby executor is added to the configuration as
1913                follows:
1914
1915             .. container:: listingblock
1916
1917                .. container:: content
1918
1919                   .. code::
1920
1921                      "engineServiceParameters":{
1922                        "engineParameters":{
1923                          "executorParameters":{
1924                            "JRUBY":{
1925                              "parameterClassName" :
1926                              "org.onap.policy.apex.plugins.executor.jruby.JrubyExecutorParameters"
1927                            }
1928                          }
1929                        }
1930                      }
1931
1932 Configure the Java Executor
1933 ###########################
1934
1935             .. container:: paragraph
1936
1937                The Java executor is added to the configuration as
1938                follows:
1939
1940             .. container:: listingblock
1941
1942                .. container:: content
1943
1944                   .. code::
1945
1946                      "engineServiceParameters":{
1947                        "engineParameters":{
1948                          "executorParameters":{
1949                            "JAVA":{
1950                              "parameterClassName" :
1951                              "org.onap.policy.apex.plugins.executor.java.JavaExecutorParameters"
1952                            }
1953                          }
1954                        }
1955                      }
1956
1957 Configure the MVEL Executor
1958 ###########################
1959
1960             .. container:: paragraph
1961
1962                The MVEL executor is added to the configuration as
1963                follows:
1964
1965             .. container:: listingblock
1966
1967                .. container:: content
1968
1969                   .. code::
1970
1971                      "engineServiceParameters":{
1972                        "engineParameters":{
1973                          "executorParameters":{
1974                            "MVEL":{
1975                              "parameterClassName" :
1976                              "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters"
1977                            }
1978                          }
1979                        }
1980                      }
1981
1982 Context Handlers
1983 ----------------
1984
1985          .. container:: paragraph
1986
1987             Context handlers are responsible for all context processing.
1988             There are the following main areas:
1989
1990          .. container:: ulist
1991
1992             -  Context schema: use schema handlers other than Java class
1993                (supported by default without configuration)
1994
1995             -  Context distribution: distribute context across multiple
1996                APEX engines
1997
1998             -  Context locking: mechanisms to lock context elements for
1999                read/write
2000
2001             -  Context persistence: mechanisms to persist context
2002
2003          .. container:: paragraph
2004
2005             APEX provides plugins for each of the main areas.
2006
2007 Configure AVRO Schema Handler
2008 #############################
2009
2010             .. container:: paragraph
2011
2012                The AVRO schema handler is added to the configuration as
2013                follows:
2014
2015             .. container:: listingblock
2016
2017                .. container:: content
2018
2019                   .. code::
2020
2021                      "engineServiceParameters":{
2022                        "engineParameters":{
2023                          "contextParameters":{
2024                            "parameterClassName" : "org.onap.policy.apex.context.parameters.ContextParameters",
2025                            "schemaParameters":{
2026                              "Avro":{
2027                                "parameterClassName" :
2028                                  "org.onap.policy.apex.plugins.context.schema.avro.AvroSchemaHelperParameters"
2029                              }
2030                            }
2031                          }
2032                        }
2033                      }
2034
2035             .. container:: paragraph
2036
2037                Using the AVRO schema handler has one limitation: AVRO
2038                only supports field names that represent valid Java class
2039                names. This means only letters and the character ``_``
2040                are supported. Characters commonly used in field names,
2041                such as ``.`` and ``-``, are not supported by AVRO. for
2042                more information see `Avro Spec:
2043                Names <https://avro.apache.org/docs/1.8.1/spec.html#names>`__.
2044
2045             .. container:: paragraph
2046
2047                To work with this limitation, the APEX Avro plugin will
2048                parse a given AVRO definition and replace *all*
2049                occurrences of ``.`` and ``-`` with a ``_``. This means
2050                that
2051
2052             .. container:: ulist
2053
2054                -  In a policy model, if the AVRO schema defined a field
2055                   as ``my-name`` the policy logic should access it as
2056                   ``my_name``
2057
2058                -  In a policy model, if the AVRO schema defined a field
2059                   as ``my.name`` the policy logic should access it as
2060                   ``my_name``
2061
2062                -  There should be no field names that convert to the
2063                   same internal name
2064
2065                   .. container:: ulist
2066
2067                      -  For instance the simultaneous use of
2068                         ``my_name``, ``my.name``, and ``my-name`` should
2069                         be avoided
2070
2071                      -  If not avoided, the event processing might
2072                         create unwanted side effects
2073
2074                -  If field names use any other not-supported character,
2075                   the AVRO plugin will reject it
2076
2077                   .. container:: ulist
2078
2079                      -  Since AVRO uses lazy initialization, this
2080                         rejection might only become visible at runtime
2081
2082 Carrier Technologies
2083 --------------------
2084
2085          .. container:: paragraph
2086
2087             Carrier technologies define how APEX receives (input) and
2088             sends (output) events. They can be used in any combination,
2089             using asynchronous or synchronous mode. There can also be
2090             any number of carrier technologies for the input (consume)
2091             and the output (produce) interface.
2092
2093          .. container:: paragraph
2094
2095             Supported *input* technologies are:
2096
2097          .. container:: ulist
2098
2099             -  Standard input, read events from the standard input
2100                (console), not suitable for APEX background servers
2101
2102             -  File input, read events from a file
2103
2104             -  Kafka, read events from a Kafka system
2105
2106             -  Websockets, read events from a Websocket
2107
2108             -  JMS,
2109
2110             -  REST (synchronous and asynchronous), additionally as
2111                client or server
2112
2113             -  Event Requestor, allows reading of events that have been
2114                looped back into APEX
2115
2116          .. container:: paragraph
2117
2118             Supported *output* technologies are:
2119
2120          .. container:: ulist
2121
2122             -  Standard output, write events to the standard output
2123                (console), not suitable for APEX background servers
2124
2125             -  File output, write events to a file
2126
2127             -  Kafka, write events to a Kafka system
2128
2129             -  Websockets, write events to a Websocket
2130
2131             -  JMS
2132
2133             -  REST (synchronous and asynchronous), additionally as
2134                client or server
2135
2136             -  Event Requestor, allows events to be looped back into
2137                APEX
2138
2139          .. container:: paragraph
2140
2141             New carrier technologies can be added as plugins to APEX or
2142             developed outside APEX and added to an APEX deployment.
2143
2144 Standard IO
2145 ###########
2146
2147             .. container:: paragraph
2148
2149                Standard IO does not require a specific plugin, it is
2150                supported be default.
2151
2152 Standard Input
2153 ==============
2154                .. container:: paragraph
2155
2156                   APEX will take events from its standard input. This
2157                   carrier is good for testing, but certainly not for a
2158                   use case where APEX runs as a server. The
2159                   configuration is as follows:
2160
2161                .. container:: listingblock
2162
2163                   .. container:: content
2164
2165                      ::
2166
2167                         "carrierTechnologyParameters" : {
2168                           "carrierTechnology" : "FILE", (1)
2169                           "parameters" : {
2170                             "standardIO" : true (2)
2171                           }
2172                         }
2173
2174                .. container:: colist arabic
2175
2176                   +-------+---------------------------------------+
2177                   | **1** | standard input is considered a file   |
2178                   +-------+---------------------------------------+
2179                   | **2** | file descriptor set to standard input |
2180                   +-------+---------------------------------------+
2181
2182 Standard Output
2183 ===============
2184
2185                .. container:: paragraph
2186
2187                   APEX will send events to its standard output. This
2188                   carrier is good for testing, but certainly not for a
2189                   use case where APEX runs as a server. The
2190                   configuration is as follows:
2191
2192                .. container:: listingblock
2193
2194                   .. container:: content
2195
2196                      .. code::
2197
2198                         "carrierTechnologyParameters" : {
2199                           "carrierTechnology" : "FILE", (1)
2200                           "parameters" : {
2201                             "standardIO" : true  (2)
2202                           }
2203                         }
2204
2205                .. container:: colist arabic
2206
2207                   +-------+----------------------------------------+
2208                   | **1** | standard output is considered a file   |
2209                   +-------+----------------------------------------+
2210                   | **2** | file descriptor set to standard output |
2211                   +-------+----------------------------------------+
2212
2213 2.7.2. File IO
2214 ##############
2215
2216             .. container:: paragraph
2217
2218                File IO does not require a specific plugin, it is
2219                supported be default.
2220
2221 File Input
2222 ==========
2223
2224                .. container:: paragraph
2225
2226                   APEX will take events from a file. The same file
2227                   should not be used as an output. The configuration is
2228                   as follows:
2229
2230                .. container:: listingblock
2231
2232                   .. container:: content
2233
2234                      .. code::
2235
2236                         "carrierTechnologyParameters" : {
2237                           "carrierTechnology" : "FILE", (1)
2238                           "parameters" : {
2239                             "fileName" : "examples/events/SampleDomain/EventsIn.xmlfile" (2)
2240                           }
2241                         }
2242
2243                .. container:: colist arabic
2244
2245                   +-------+------------------------------------------+
2246                   | **1** | set file input                           |
2247                   +-------+------------------------------------------+
2248                   | **2** | the name of the file to read events from |
2249                   +-------+------------------------------------------+
2250
2251 File Output
2252 ===========
2253                .. container:: paragraph
2254
2255                   APEX will write events to a file. The same file should
2256                   not be used as an input. The configuration is as
2257                   follows:
2258
2259                .. container:: listingblock
2260
2261                   .. container:: content
2262
2263                      .. code::
2264
2265                         "carrierTechnologyParameters" : {
2266                           "carrierTechnology" : "FILE", (1)
2267                           "parameters" : {
2268                             "fileName"  : "examples/events/SampleDomain/EventsOut.xmlfile" (2)
2269                           }
2270                         }
2271
2272                .. container:: colist arabic
2273
2274                   +-------+-----------------------------------------+
2275                   | **1** | set file output                         |
2276                   +-------+-----------------------------------------+
2277                   | **2** | the name of the file to write events to |
2278                   +-------+-----------------------------------------+
2279
2280 Event Requestor IO
2281 ##################
2282
2283             .. container:: paragraph
2284
2285                Event Requestor IO does not require a specific plugin, it
2286                is supported be default. It should only be used with the
2287                APEX event protocol.
2288
2289 Event Requestor Input
2290 =====================
2291
2292                .. container:: paragraph
2293
2294                   APEX will take events from APEX.
2295
2296                .. container:: listingblock
2297
2298                   .. container:: content
2299
2300                      .. code::
2301
2302                         "carrierTechnologyParameters" : {
2303                           "carrierTechnology": "EVENT_REQUESTOR" (1)
2304                         }
2305
2306                .. container:: colist arabic
2307
2308                   +-------+---------------------------+
2309                   | **1** | set event requestor input |
2310                   +-------+---------------------------+
2311
2312 Event Requestor Output
2313 ======================
2314
2315                .. container:: paragraph
2316
2317                   APEX will write events to APEX.
2318
2319                .. container:: listingblock
2320
2321                   .. container:: content
2322
2323                      .. code::
2324
2325                         "carrierTechnologyParameters" : {
2326                           "carrierTechnology": "EVENT_REQUESTOR" (1)
2327                         }
2328
2329 Peering Event Requestors
2330 ========================
2331
2332                .. container:: paragraph
2333
2334                   When using event requestors, they need to be peered.
2335                   This means an event requestor output needs to be
2336                   peered (associated) with an event requestor input. The
2337                   following example shows the use of an event requestor
2338                   with the APEX event protocol and the peering of output
2339                   and input.
2340
2341                .. container:: listingblock
2342
2343                   .. container:: content
2344
2345                      .. code::
2346
2347                         "eventInputParameters": {
2348                           "EventRequestorConsumer": {
2349                             "carrierTechnologyParameters": {
2350                               "carrierTechnology": "EVENT_REQUESTOR" (1)
2351                             },
2352                             "eventProtocolParameters": {
2353                               "eventProtocol": "APEX" (2)
2354                             },
2355                             "eventNameFilter": "InputEvent", (3)
2356                             "requestorMode": true, (4)
2357                             "requestorPeer": "EventRequestorProducer", (5)
2358                             "requestorTimeout": 500 (6)
2359                           }
2360                         },
2361                         "eventOutputParameters": {
2362                           "EventRequestorProducer": {
2363                             "carrierTechnologyParameters": {
2364                               "carrierTechnology": "EVENT_REQUESTOR" (7)
2365                             },
2366                             "eventProtocolParameters": {
2367                               "eventProtocol": "APEX" (8)
2368                             },
2369                             "eventNameFilter": "EventListEvent", (9)
2370                             "requestorMode": true, (10)
2371                             "requestorPeer": "EventRequestorConsumer", (11)
2372                             "requestorTimeout": 500 (12)
2373                           }
2374                         }
2375
2376                .. container:: colist arabic
2377
2378                   +-----------------------------------+-----------------------------------+
2379                   | **1**                             | event requestor on a consumer     |
2380                   +-----------------------------------+-----------------------------------+
2381                   | **2**                             | with APEX event protocol          |
2382                   +-----------------------------------+-----------------------------------+
2383                   | **3**                             | optional filter (best to use a    |
2384                   |                                   | filter to prevent unwanted events |
2385                   |                                   | on the consumer side)             |
2386                   +-----------------------------------+-----------------------------------+
2387                   | **4**                             | activate requestor mode           |
2388                   +-----------------------------------+-----------------------------------+
2389                   | **5**                             | the peer to the output (must      |
2390                   |                                   | match the output carrier)         |
2391                   +-----------------------------------+-----------------------------------+
2392                   | **6**                             | an optional timeout in            |
2393                   |                                   | milliseconds                      |
2394                   +-----------------------------------+-----------------------------------+
2395                   | **7**                             | event requestor on a producer     |
2396                   +-----------------------------------+-----------------------------------+
2397                   | **8**                             | with APEX event protocol          |
2398                   +-----------------------------------+-----------------------------------+
2399                   | **9**                             | optional filter (best to use a    |
2400                   |                                   | filter to prevent unwanted events |
2401                   |                                   | on the consumer side)             |
2402                   +-----------------------------------+-----------------------------------+
2403                   | **10**                            | activate requestor mode           |
2404                   +-----------------------------------+-----------------------------------+
2405                   | **11**                            | the peer to the output (must      |
2406                   |                                   | match the input carrier)          |
2407                   +-----------------------------------+-----------------------------------+
2408                   | **12**                            | an optional timeout in            |
2409                   |                                   | milliseconds                      |
2410                   +-----------------------------------+-----------------------------------+
2411
2412 Kafka IO
2413 ########
2414
2415             .. container:: paragraph
2416
2417                Kafka IO is supported by the APEX Kafka plugin. The
2418                configurations below are examples. APEX will take any
2419                configuration inside the parameter object and forward it
2420                to Kafka. More information on Kafka specific
2421                configuration parameters can be found in the Kafka
2422                documentation:
2423
2424             .. container:: ulist
2425
2426                -  `Kafka Consumer
2427                   Class <https://kafka.apache.org/090/javadoc/org/apache/kafka/clients/consumer/KafkaConsumer.html>`__
2428
2429                -  `Kafka Producer
2430                   Class <https://kafka.apache.org/090/javadoc/org/apache/kafka/clients/producer/KafkaProducer.html>`__
2431
2432 Kafka Input
2433 ===========
2434                .. container:: paragraph
2435
2436                   APEX will receive events from the Apache Kafka
2437                   messaging system. The input is uni-directional, an
2438                   engine will only receive events from the input but not
2439                   send any event to the input.
2440
2441                .. container:: listingblock
2442
2443                   .. container:: content
2444
2445                      .. code::
2446
2447                         "carrierTechnologyParameters" : {
2448                           "carrierTechnology" : "KAFKA", (1)
2449                           "parameterClassName" :
2450                             "org.onap.policy.apex.plugins.event.carrier.kafka.KAFKACarrierTechnologyParameters",
2451                           "parameters" : {
2452                             "bootstrapServers"  : "localhost:49092", (2)
2453                             "groupId"           : "apex-group-id", (3)
2454                             "enableAutoCommit"  : true, (4)
2455                             "autoCommitTime"    : 1000, (5)
2456                             "sessionTimeout"    : 30000, (6)
2457                             "consumerPollTime"  : 100, (7)
2458                             "consumerTopicList" : ["apex-in-0", "apex-in-1"], (8)
2459                             "keyDeserializer"   :
2460                                 "org.apache.kafka.common.serialization.StringDeserializer", (9)
2461                             "valueDeserializer" :
2462                                 "org.apache.kafka.common.serialization.StringDeserializer" (10)
2463                           }
2464                         }
2465
2466                .. container:: colist arabic
2467
2468                   +--------+-------------------------------------+
2469                   | **1**  | set Kafka as carrier technology     |
2470                   +--------+-------------------------------------+
2471                   | **2**  | bootstrap server and port           |
2472                   +--------+-------------------------------------+
2473                   | **3**  | a group identifier                  |
2474                   +--------+-------------------------------------+
2475                   | **4**  | flag for auto-commit                |
2476                   +--------+-------------------------------------+
2477                   | **5**  | auto-commit timeout in milliseconds |
2478                   +--------+-------------------------------------+
2479                   | **6**  | session timeout in milliseconds     |
2480                   +--------+-------------------------------------+
2481                   | **7**  | consumer poll time in milliseconds  |
2482                   +--------+-------------------------------------+
2483                   | **8**  | consumer topic list                 |
2484                   +--------+-------------------------------------+
2485                   | **9**  | key for the Kafka de-serializer     |
2486                   +--------+-------------------------------------+
2487                   | **10** | value for the Kafka de-serializer   |
2488                   +--------+-------------------------------------+
2489
2490 Kafka Output
2491 ============
2492                .. container:: paragraph
2493
2494                   APEX will send events to the Apache Kafka messaging
2495                   system. The output is uni-directional, an engine will
2496                   send events to the output but not receive any event
2497                   from the output.
2498
2499                .. container:: listingblock
2500
2501                   .. container:: content
2502
2503                      .. code::
2504
2505                         "carrierTechnologyParameters" : {
2506                           "carrierTechnology" : "KAFKA", (1)
2507                           "parameterClassName" :
2508                             "org.onap.policy.apex.plugins.event.carrier.kafka.KAFKACarrierTechnologyParameters",
2509                           "parameters" : {
2510                             "bootstrapServers"  : "localhost:49092", (2)
2511                             "acks"              : "all", (3)
2512                             "retries"           : 0, (4)
2513                             "batchSize"         : 16384, (5)
2514                             "lingerTime"        : 1, (6)
2515                             "bufferMemory"      : 33554432, (7)
2516                             "producerTopic"     : "apex-out", (8)
2517                             "keySerializer"     :
2518                                 "org.apache.kafka.common.serialization.StringSerializer", (9)
2519                             "valueSerializer"   :
2520                                 "org.apache.kafka.common.serialization.StringSerializer" (10)
2521                           }
2522                         }
2523
2524                .. container:: colist arabic
2525
2526                   +--------+---------------------------------+
2527                   | **1**  | set Kafka as carrier technology |
2528                   +--------+---------------------------------+
2529                   | **2**  | bootstrap server and port       |
2530                   +--------+---------------------------------+
2531                   | **3**  | acknowledgement strategy        |
2532                   +--------+---------------------------------+
2533                   | **4**  | number of retries               |
2534                   +--------+---------------------------------+
2535                   | **5**  | batch size                      |
2536                   +--------+---------------------------------+
2537                   | **6**  | time to linger in milliseconds  |
2538                   +--------+---------------------------------+
2539                   | **7**  | buffer memory in byte           |
2540                   +--------+---------------------------------+
2541                   | **8**  | producer topic                  |
2542                   +--------+---------------------------------+
2543                   | **9**  | key for the Kafka serializer    |
2544                   +--------+---------------------------------+
2545                   | **10** | value for the Kafka serializer  |
2546                   +--------+---------------------------------+
2547
2548 JMS IO
2549 #######
2550
2551             .. container:: paragraph
2552
2553                APEX supports the Java Messaging Service (JMS) as input
2554                as well as output. JMS IO is supported by the APEX JMS
2555                plugin. Input and output support an event encoding as
2556                text (JSON string) or object (serialized object). The
2557                input configuration is the same for both encodings, the
2558                output configuration differs.
2559
2560 JMS Input
2561 =========
2562                .. container:: paragraph
2563
2564                   APEX will receive events from a JMS messaging system.
2565                   The input is uni-directional, an engine will only
2566                   receive events from the input but not send any event
2567                   to the input.
2568
2569                .. container:: listingblock
2570
2571                   .. container:: content
2572
2573                      .. code::
2574
2575                         "carrierTechnologyParameters" : {
2576                           "carrierTechnology" : "JMS", (1)
2577                           "parameterClassName" :
2578                               "org.onap.policy.apex.plugins.event.carrier.jms.JMSCarrierTechnologyParameters",
2579                           "parameters" : { (2)
2580                             "initialContextFactory" :
2581                                 "org.jboss.naming.remote.client.InitialContextFactory", (3)
2582                             "connectionFactory" : "ConnectionFactory", (4)
2583                             "providerURL" : "remote://localhost:5445", (5)
2584                             "securityPrincipal" : "guest", (6)
2585                             "securityCredentials" : "IAmAGuest", (7)
2586                             "consumerTopic" : "jms/topic/apexIn" (8)
2587                           }
2588                         }
2589
2590                .. container:: colist arabic
2591
2592                   +-----------------------------------+-----------------------------------+
2593                   | **1**                             | set JMS as carrier technology     |
2594                   +-----------------------------------+-----------------------------------+
2595                   | **2**                             | set all JMS specific parameters   |
2596                   +-----------------------------------+-----------------------------------+
2597                   | **3**                             | the context factory, in this case |
2598                   |                                   | from JBOSS (it requires the       |
2599                   |                                   | dependency                        |
2600                   |                                   | org.jboss:jboss-remote-naming:2.0 |
2601                   |                                   | .4.Final                          |
2602                   |                                   | or a different version to be in   |
2603                   |                                   | the directory ``$APEX_HOME/lib``  |
2604                   |                                   | or ``%APEX_HOME%\lib``            |
2605                   +-----------------------------------+-----------------------------------+
2606                   | **4**                             | a connection factory for the JMS  |
2607                   |                                   | connection                        |
2608                   +-----------------------------------+-----------------------------------+
2609                   | **5**                             | URL with host and port of the JMS |
2610                   |                                   | provider                          |
2611                   +-----------------------------------+-----------------------------------+
2612                   | **6**                             | access credentials, user name     |
2613                   +-----------------------------------+-----------------------------------+
2614                   | **7**                             | access credentials, user password |
2615                   +-----------------------------------+-----------------------------------+
2616                   | **8**                             | the JMS topic to listen to        |
2617                   +-----------------------------------+-----------------------------------+
2618
2619 JMS Output with Text
2620 ====================
2621
2622                .. container:: paragraph
2623
2624                   APEX engine send events to a JMS messaging system. The
2625                   output is uni-directional, an engine will send events
2626                   to the output but not receive any event from output.
2627
2628                .. container:: listingblock
2629
2630                   .. container:: content
2631
2632                      .. code::
2633
2634                         "carrierTechnologyParameters" : {
2635                           "carrierTechnology" : "JMS", (1)
2636                           "parameterClassName" :
2637                               "org.onap.policy.apex.plugins.event.carrier.jms.JMSCarrierTechnologyParameters",
2638                           "parameters" : { (2)
2639                             "initialContextFactory" :
2640                                 "org.jboss.naming.remote.client.InitialContextFactory", (3)
2641                             "connectionFactory" : "ConnectionFactory", (4)
2642                             "providerURL" : "remote://localhost:5445", (5)
2643                             "securityPrincipal" : "guest", (6)
2644                             "securityCredentials" : "IAmAGuest", (7)
2645                             "producerTopic" : "jms/topic/apexOut", (8)
2646                             "objectMessageSending": "false" (9)
2647                           }
2648                         }
2649
2650                .. container:: colist arabic
2651
2652                   +-----------------------------------+-----------------------------------+
2653                   | **1**                             | set JMS as carrier technology     |
2654                   +-----------------------------------+-----------------------------------+
2655                   | **2**                             | set all JMS specific parameters   |
2656                   +-----------------------------------+-----------------------------------+
2657                   | **3**                             | the context factory, in this case |
2658                   |                                   | from JBOSS (it requires the       |
2659                   |                                   | dependency                        |
2660                   |                                   | org.jboss:jboss-remote-naming:2.0 |
2661                   |                                   | .4.Final                          |
2662                   |                                   | or a different version to be in   |
2663                   |                                   | the directory ``$APEX_HOME/lib``  |
2664                   |                                   | or ``%APEX_HOME%\lib``            |
2665                   +-----------------------------------+-----------------------------------+
2666                   | **4**                             | a connection factory for the JMS  |
2667                   |                                   | connection                        |
2668                   +-----------------------------------+-----------------------------------+
2669                   | **5**                             | URL with host and port of the JMS |
2670                   |                                   | provider                          |
2671                   +-----------------------------------+-----------------------------------+
2672                   | **6**                             | access credentials, user name     |
2673                   +-----------------------------------+-----------------------------------+
2674                   | **7**                             | access credentials, user password |
2675                   +-----------------------------------+-----------------------------------+
2676                   | **8**                             | the JMS topic to write to         |
2677                   +-----------------------------------+-----------------------------------+
2678                   | **9**                             | set object messaging to ``false`` |
2679                   |                                   | means it sends JSON text          |
2680                   +-----------------------------------+-----------------------------------+
2681
2682 JMS Output with Object
2683 ======================
2684
2685                .. container:: paragraph
2686
2687                   To configure APEX for JMS objects on the output
2688                   interface use the same configuration as above (for
2689                   output). Simply change the ``objectMessageSending``
2690                   parameter to ``true``.
2691
2692 Websocket (WS) IO
2693 ########################
2694
2695             .. container:: paragraph
2696
2697                APEX supports the Websockets as input as well as output.
2698                WS IO is supported by the APEX Websocket plugin. This
2699                carrier technology does only support uni-directional
2700                communication. APEX will not send events to a Websocket
2701                input and any event sent to a Websocket output will
2702                result in an error log.
2703
2704             .. container:: paragraph
2705
2706                The input can be configured as client (APEX connects to
2707                an existing Websocket server) or server (APEX starts a
2708                Websocket server). The same applies to the output. Input
2709                and output can both use a client or a server
2710                configuration, or separate configurations (input as
2711                client and output as server, input as server and output
2712                as client). Each configuration should use its own
2713                dedicated port to avoid any communication loops. The
2714                configuration of a Websocket client is the same for input
2715                and output. The configuration of a Websocket server is
2716                the same for input and output.
2717
2718 Websocket Client
2719 ================
2720
2721                .. container:: paragraph
2722
2723                   APEX will connect to a given Websocket server. As
2724                   input, it will receive events from the server but not
2725                   send any events. As output, it will send events to the
2726                   server and any event received from the server will
2727                   result in an error log.
2728
2729                .. container:: listingblock
2730
2731                   .. container:: content
2732
2733                      .. code::
2734
2735                         "carrierTechnologyParameters" : {
2736                           "carrierTechnology" : "WEBSOCKET", (1)
2737                           "parameterClassName" :
2738                           "org.onap.policy.apex.plugins.event.carrier.websocket.WEBSOCKETCarrierTechnologyParameters",
2739                           "parameters" : {
2740                             "host" : "localhost", (2)
2741                             "port" : 42451 (3)
2742                           }
2743                         }
2744
2745                .. container:: colist arabic
2746
2747                   +-------+------------------------------------------------------+
2748                   | **1** | set Websocket as carrier technology                  |
2749                   +-------+------------------------------------------------------+
2750                   | **2** | the host name on which a Websocket server is running |
2751                   +-------+------------------------------------------------------+
2752                   | **3** | the port of that Websocket server                    |
2753                   +-------+------------------------------------------------------+
2754
2755 Websocket Server
2756 ================
2757
2758                .. container:: paragraph
2759
2760                   APEX will start a Websocket server, which will accept
2761                   any Websocket clients to connect. As input, it will
2762                   receive events from the server but not send any
2763                   events. As output, it will send events to the server
2764                   and any event received from the server will result in
2765                   an error log.
2766
2767                .. container:: listingblock
2768
2769                   .. container:: content
2770
2771                      .. code::
2772
2773                         "carrierTechnologyParameters" : {
2774                           "carrierTechnology" : "WEBSOCKET", (1)
2775                           "parameterClassName" :
2776                           "org.onap.policy.apex.plugins.event.carrier.websocket.WEBSOCKETCarrierTechnologyParameters",
2777                           "parameters" : {
2778                             "wsClient" : false, (2)
2779                             "port"     : 42450 (3)
2780                           }
2781                         }
2782
2783                .. container:: colist arabic
2784
2785                   +-------+------------------------------------------------------------+
2786                   | **1** | set Websocket as carrier technology                        |
2787                   +-------+------------------------------------------------------------+
2788                   | **2** | disable client, so that APEX will start a Websocket server |
2789                   +-------+------------------------------------------------------------+
2790                   | **3** | the port for the Websocket server APEX will start          |
2791                   +-------+------------------------------------------------------------+
2792
2793 REST Client IO
2794 ##############
2795
2796             .. container:: paragraph
2797
2798                APEX can act as REST client on the input as well as on
2799                the output interface. The media type is
2800                ``application/json``, so this plugin does only work with
2801                the JSON Event protocol.
2802
2803 REST Client Input
2804 =================
2805
2806                .. container:: paragraph
2807
2808                   APEX will connect to a given URL to receive events,
2809                   but not send any events. The server is polled, i.e.
2810                   APEX will do an HTTP GET, take the result, and then do
2811                   the next GET. Any required timing needs to be handled
2812                   by the server configured via the URL. For instance,
2813                   the server could support a wait timeout via the URL as
2814                   ``?timeout=100ms``.
2815                   The httpCodeFilter is used for filtering the status
2816                   code, and it can be configured as a regular expression
2817                   string. The default httpCodeFilter is "[2][0-9][0-9]"
2818                   - for successful response codes.
2819                   The response with HTTP status code that matches the
2820                   given regular expression is forwarded to the task,
2821                   otherwise it is logged as a failure.
2822
2823                .. container:: listingblock
2824
2825                   .. container:: content
2826
2827                      .. code::
2828
2829                         "carrierTechnologyParameters" : {
2830                           "carrierTechnology" : "RESTCLIENT", (1)
2831                           "parameterClassName" :
2832                             "org.onap.policy.apex.plugins.event.carrier.restclient.RESTClientCarrierTechnologyParameters",
2833                           "parameters" : {
2834                             "url" : "http://example.org:8080/triggers/events", (2)
2835                             "httpCodeFilter" : "[2][0-9][0-9]" (3)
2836                           }
2837                         }
2838
2839                .. container:: colist arabic
2840
2841                   +-------+--------------------------------------------------+
2842                   | **1** | set REST client as carrier technology            |
2843                   +-------+--------------------------------------------------+
2844                   | **2** | the URL of the HTTP server for events            |
2845                   +-------+--------------------------------------------------+
2846                   | **3** | use HTTP CODE FILTER for filtering status code   |
2847                   +-------+--------------------------------------------------+
2848
2849 REST Client Output
2850 ==================
2851
2852                .. container:: paragraph
2853
2854                   APEX will connect to a given URL to send events, but
2855                   not receive any events. The default HTTP operation is
2856                   POST (no configuration required). To change it to PUT
2857                   simply add the configuration parameter (as shown in
2858                   the example below).
2859                   The URL can be configured statically or tagged
2860                   as ``?example.{site}.org:8080/{trig}/events``,
2861                   all tags such as ``site`` and ``trig`` in the URL
2862                   need to be set in the properties object available to
2863                   the tasks. In addition, the keys should exactly match
2864                   with the tags defined in url. The scope of the properties
2865                   object is per HTTP call. Hence, key/value pairs set
2866                   in the properties object by task are only available
2867                   for that specific HTTP call.
2868
2869                .. container:: listingblock
2870
2871                   .. container:: content
2872
2873                      .. code::
2874
2875                         "carrierTechnologyParameters" : {
2876                           "carrierTechnology" : "RESTCLIENT", (1)
2877                           "parameterClassName" :
2878                             "org.onap.policy.apex.plugins.event.carrier.restclient.RESTClientCarrierTechnologyParameters",
2879                           "parameters" : {
2880                             "url" : "http://example.com:8888/actions/events", (2)
2881                             "url" : "http://example.{site}.com:8888/{trig}/events", (2')
2882                             "httpMethod" : "PUT" (3)
2883                           }
2884                         }
2885
2886                .. container:: colist arabic
2887
2888                   +-------+--------------------------------------------------+
2889                   | **1** | set REST client as carrier technology            |
2890                   +-------+--------------------------------------------------+
2891                   | **2** | the static URL of the HTTP server for events     |
2892                   +-------+--------------------------------------------------+
2893                   | **2'**| the tagged URL of the HTTP server for events     |
2894                   +-------+--------------------------------------------------+
2895                   | **3** | use HTTP PUT (remove this line to use HTTP POST) |
2896                   +-------+--------------------------------------------------+
2897
2898 REST Server IO
2899 ##############
2900
2901             .. container:: paragraph
2902
2903                APEX supports a REST server for input and output.
2904
2905             .. container:: paragraph
2906
2907                The REST server plugin always uses a synchronous mode. A
2908                client does a HTTP GET on the APEX REST server with the
2909                input event and receives the generated output event in
2910                the server reply. This means that for the REST server
2911                there has to always to be an input with an associated
2912                output. Input or output only are not permitted.
2913
2914             .. container:: paragraph
2915
2916                The plugin will start a Grizzly server as REST server for
2917                a normal APEX engine. If the APEX engine is executed as a
2918                servlet, for instance inside Tomcat, then Tomcat will be
2919                used as REST server (this case requires configuration on
2920                Tomcat as well).
2921
2922             .. container:: paragraph
2923
2924                Some configuration restrictions apply for all scenarios:
2925
2926             .. container:: ulist
2927
2928                -  Minimum port: 1024
2929
2930                -  Maximum port: 65535
2931
2932                -  The media type is ``application/json``, so this plugin
2933                   does only work with the JSON Event protocol.
2934
2935             .. container:: paragraph
2936
2937                The URL the client calls is created using
2938
2939             .. container:: ulist
2940
2941                -  the configured host and port, e.g.
2942                   ``http://localhost:12345``
2943
2944                -  the standard path, e.g. ``/apex/``
2945
2946                -  the name of the input/output, e.g. ``FirstConsumer/``
2947
2948                -  the input or output name, e.g. ``EventIn``.
2949
2950             .. container:: paragraph
2951
2952                The examples above lead to the URL
2953                ``http://localhost:12345/apex/FirstConsumer/EventIn``.
2954
2955             .. container:: paragraph
2956
2957                A client can also get status information of the REST
2958                server using ``/Status``, e.g.
2959                ``http://localhost:12345/apex/FirstConsumer/Status``.
2960
2961 REST Server Stand-alone
2962 =======================
2963
2964                .. container:: paragraph
2965
2966                   We need to configure a REST server input and a REST
2967                   server output. Input and output are associated with
2968                   each other via there name.
2969
2970                .. container:: paragraph
2971
2972                   Timeouts for REST calls need to be set carefully. If
2973                   they are too short, the call might timeout before a
2974                   policy finished creating an event.
2975
2976                .. container:: paragraph
2977
2978                   The following example configures the input named as
2979                   ``MyConsumer`` and associates an output named
2980                   ``MyProducer`` with it.
2981
2982                .. container:: listingblock
2983
2984                   .. container:: content
2985
2986                      .. code::
2987
2988                         "eventInputParameters": {
2989                           "MyConsumer": {
2990                             "carrierTechnologyParameters" : {
2991                               "carrierTechnology" : "RESTSERVER", (1)
2992                               "parameterClassName" :
2993                                 "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters",
2994                               "parameters" : {
2995                                 "standalone" : true, (2)
2996                                 "host" : "localhost", (3)
2997                                 "port" : 12345 (4)
2998                               }
2999                             },
3000                             "eventProtocolParameters":{
3001                               "eventProtocol" : "JSON" (5)
3002                             },
3003                             "synchronousMode"    : true, (6)
3004                             "synchronousPeer"    : "MyProducer", (7)
3005                             "synchronousTimeout" : 500 (8)
3006                           }
3007                         }
3008
3009                .. container:: colist arabic
3010
3011                   +-------+---------------------------------------+
3012                   | **1** | set REST server as carrier technology |
3013                   +-------+---------------------------------------+
3014                   | **2** | set the server as stand-alone         |
3015                   +-------+---------------------------------------+
3016                   | **3** | set the server host                   |
3017                   +-------+---------------------------------------+
3018                   | **4** | set the server listen port            |
3019                   +-------+---------------------------------------+
3020                   | **5** | use JSON event protocol               |
3021                   +-------+---------------------------------------+
3022                   | **6** | activate synchronous mode             |
3023                   +-------+---------------------------------------+
3024                   | **7** | associate an output ``MyProducer``    |
3025                   +-------+---------------------------------------+
3026                   | **8** | set a timeout of 500 milliseconds     |
3027                   +-------+---------------------------------------+
3028
3029                .. container:: paragraph
3030
3031                   The following example configures the output named as
3032                   ``MyProducer`` and associates the input ``MyConsumer``
3033                   with it. Note that for the output there are no more
3034                   paramters (such as host or port), since they are
3035                   already configured in the associated input
3036
3037                .. container:: listingblock
3038
3039                   .. container:: content
3040
3041                      .. code::
3042
3043                         "eventOutputParameters": {
3044                           "MyProducer": {
3045                             "carrierTechnologyParameters":{
3046                               "carrierTechnology" : "RESTSERVER",
3047                               "parameterClassName" :
3048                                 "org.onap.policy.apex.plugins.event.carrier.restserver.RESTServerCarrierTechnologyParameters"
3049                             },
3050                             "eventProtocolParameters":{
3051                               "eventProtocol" : "JSON"
3052                             },
3053                             "synchronousMode"    : true,
3054                             "synchronousPeer"    : "MyConsumer",
3055                             "synchronousTimeout" : 500
3056                           }
3057                         }
3058
3059 REST Server Stand-alone, multi input
3060 ====================================
3061
3062                .. container:: paragraph
3063
3064                   Any number of input/output pairs for REST servers can
3065                   be configured. For instance, we can configure an input
3066                   ``FirstConsumer`` with output ``FirstProducer`` and an
3067                   input ``SecondConsumer`` with output
3068                   ``SecondProducer``. Important is that there is always
3069                   one pair of input/output.
3070
3071 REST Server Stand-alone in Servlet
3072 ==================================
3073
3074                .. container:: paragraph
3075
3076                   If APEX is executed as a servlet, e.g. inside Tomcat,
3077                   the configuration becomes easier since the plugin can
3078                   now use Tomcat as the REST server. In this scenario,
3079                   there are not parameters (port, host, etc.) and the
3080                   key ``standalone`` must not be used (or set to false).
3081
3082                .. container:: paragraph
3083
3084                   For the Tomcat configuration, we need to add the REST
3085                   server plugin, e.g.
3086
3087                .. container:: listingblock
3088
3089                   .. container:: content
3090
3091                      .. code::
3092
3093                         <servlet>
3094                           ...
3095                           <init-param>
3096                             ...
3097                             <param-value>org.onap.policy.apex.plugins.event.carrier.restserver</param-value>
3098                           </init-param>
3099                           ...
3100                         </servlet>
3101
3102 REST Requestor IO
3103 ##################
3104
3105             .. container:: paragraph
3106
3107                APEX can act as REST requestor on the input as well as on
3108                the output interface. The media type is
3109                ``application/json``, so this plugin does only work with
3110                the JSON Event protocol.
3111
3112 REST Requestor Input
3113 ====================
3114
3115                .. container:: paragraph
3116
3117                   APEX will connect to a given URL to request an input.
3118                   The URL can be configured statically or tagged
3119                   as ``?example.{site}.org:8080/{trig}/events``,
3120                   all tags such as ``site`` and ``trig`` in the URL
3121                   need to be set in the properties object available to
3122                   the tasks. In addition, the keys should exactly match
3123                   with the tags defined in url. The scope of the properties
3124                   object is per HTTP call. Hence, key/value pairs set
3125                   in the properties object by task are only available
3126                   for that specific HTTP call.
3127                   The httpCodeFilter is used for filtering the status
3128                   code, and it can be configured as a regular expression
3129                   string. The default httpCodeFilter is "[2][0-9][0-9]"
3130                   - for successful response codes.
3131                   The response with HTTP status code that matches the
3132                   given regular expression is forwarded to the task,
3133                   otherwise it is logged as a failure.
3134
3135                .. container:: listingblock
3136
3137                   .. container:: content
3138
3139                      .. code::
3140
3141                         "carrierTechnologyParameters": {
3142                           "carrierTechnology": "RESTREQUESTOR", (1)
3143                           "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RESTRequestorCarrierTechnologyParameters",
3144                           "parameters": {
3145                             "url": "http://localhost:54321/some/path/to/rest/resource", (2)
3146                             "url": "http://localhost:54321/{site}/path/to/rest/{resValue}", (2')
3147                             "httpMethod": "POST", (3)
3148                             "restRequestTimeout": 2000, (4)
3149                             "httpCodeFilter" : "[2][0-9][0-9]" (5)
3150                           }
3151                         },
3152
3153                .. container:: colist arabic
3154
3155                   +-------+--------------------------------------------------+
3156                   | **1** | set REST requestor as carrier technology         |
3157                   +-------+--------------------------------------------------+
3158                   | **2** | the static URL of the HTTP server for events     |
3159                   +-------+--------------------------------------------------+
3160                   | **2'**| the tagged URL of the HTTP server for events     |
3161                   +-------+--------------------------------------------------+
3162                   | **3** | use HTTP PUT (remove this line to use HTTP POST) |
3163                   +-------+--------------------------------------------------+
3164                   | **4** | request timeout in milliseconds                  |
3165                   +-------+--------------------------------------------------+
3166                   | **5** | use HTTP CODE FILTER for filtering status code   |
3167                   +-------+--------------------------------------------------+
3168
3169                .. container:: paragraph
3170
3171                   Further settings are required on the consumer to
3172                   define the event that is requested, for example:
3173
3174                .. container:: listingblock
3175
3176                   .. container:: content
3177
3178                      .. code::
3179
3180                         "eventName": "GuardResponseEvent", (1)
3181                         "eventNameFilter": "GuardResponseEvent", (2)
3182                         "requestorMode": true, (3)
3183                         "requestorPeer": "GuardRequestorProducer", (4)
3184                         "requestorTimeout": 500 (5)
3185
3186                .. container:: colist arabic
3187
3188                   +-------+---------------------------+
3189                   | **1** | the event name            |
3190                   +-------+---------------------------+
3191                   | **2** | a filter on the event     |
3192                   +-------+---------------------------+
3193                   | **3** | the mode of the requestor |
3194                   +-------+---------------------------+
3195                   | **4** | a peer for the requestor  |
3196                   +-------+---------------------------+
3197                   | **5** | a general request timeout |
3198                   +-------+---------------------------+
3199
3200 REST Requestor Output
3201 =====================
3202
3203                .. container:: paragraph
3204
3205                   APEX will connect to a given URL to send events, but
3206                   not receive any events.
3207
3208                .. container:: listingblock
3209
3210                   .. container:: content
3211
3212                      .. code::
3213
3214                         "carrierTechnologyParameters": {
3215                           "carrierTechnology": "RESTREQUESTOR", (1)
3216                           "parameterClassName": "org.onap.policy.apex.plugins.event.carrier.restrequestor.RESTRequestorCarrierTechnologyParameters"
3217                         },
3218
3219                .. container:: colist arabic
3220
3221                   +-------+------------------------------------------+
3222                   | **1** | set REST requestor as carrier technology |
3223                   +-------+------------------------------------------+
3224
3225                .. container:: paragraph
3226
3227                   Further settings are required on the consumer to
3228                   define the event that is requested, for example:
3229
3230                .. container:: listingblock
3231
3232                   .. container:: content
3233
3234                      .. code::
3235
3236                         "eventNameFilter": "GuardRequestEvent", (1)
3237                         "requestorMode": true, (2)
3238                         "requestorPeer": "GuardRequestorConsumer", (3)
3239                         "requestorTimeout": 500 (4)
3240
3241                .. container:: colist arabic
3242
3243                   +-------+---------------------------+
3244                   | **1** | a filter on the event     |
3245                   +-------+---------------------------+
3246                   | **2** | the mode of the requestor |
3247                   +-------+---------------------------+
3248                   | **3** | a peer for the requestor  |
3249                   +-------+---------------------------+
3250                   | **4** | a general request timeout |
3251                   +-------+---------------------------+
3252
3253 Event Protocols, Format and Encoding
3254 ------------------------------------
3255
3256          .. container:: paragraph
3257
3258             Event protocols define what event formats APEX can receive
3259             (input) and should send (output). They can be used in any
3260             combination for input and output, unless further restricted
3261             by a carrier technology plugin (for instance for JMS
3262             output). There can only be 1 event protocol per event
3263             plugin.
3264
3265          .. container:: paragraph
3266
3267             Supported *input* event protocols are:
3268
3269          .. container:: ulist
3270
3271             -  JSON, the event as a JSON string
3272
3273             -  APEX, an APEX event
3274
3275             -  JMS object, the event as a JMS object,
3276
3277             -  JMS text, the event as a JMS text,
3278
3279             -  XML, the event as an XML string,
3280
3281             -  YAML, the event as YAML text
3282
3283          .. container:: paragraph
3284
3285             Supported *output* event protocols are:
3286
3287          .. container:: ulist
3288
3289             -  JSON, the event as a JSON string
3290
3291             -  APEX, an APEX event
3292
3293             -  JMS object, the event as a JMS object,
3294
3295             -  JMS text, the event as a JMS text,
3296
3297             -  XML, the event as an XML string,
3298
3299             -  YAML, the event as YAML text
3300
3301          .. container:: paragraph
3302
3303             New event protocols can be added as plugins to APEX or
3304             developed outside APEX and added to an APEX deployment.
3305
3306 JSON Event
3307 ##########
3308
3309             .. container:: paragraph
3310
3311                The event protocol for JSON encoding does not require a
3312                specific plugin, it is supported by default. Furthermore,
3313                there is no difference in the configuration for the input
3314                and output interface.
3315
3316             .. container:: paragraph
3317
3318                For an input, APEX requires a well-formed JSON string.
3319                Well-formed here means according to the definitions of a
3320                policy. Any JSON string that is not defined as a trigger
3321                event (consume) will not be consumed (errors will be
3322                thrown). For output JSON events, APEX will always produce
3323                valid JSON strings according to the definition in the
3324                policy model.
3325
3326             .. container:: paragraph
3327
3328                The following JSON shows the configuration.
3329
3330             .. container:: listingblock
3331
3332                .. container:: content
3333
3334                   .. code::
3335
3336                      "eventProtocolParameters":{
3337                        "eventProtocol" : "JSON"
3338                      }
3339
3340             .. container:: paragraph
3341
3342                For JSON events, there are a few more optional
3343                parameters, which allow to define a mapping for standard
3344                event fields. An APEX event must have the fields
3345                ``name``, ``version``, ``source``, and ``target``
3346                defined. Sometimes it is not possible to configure a
3347                trigger or actioning system to use those fields. However,
3348                they might be in an event generated outside APEX (or used
3349                outside APEX) just with different names. To configure
3350                APEX to map between the different event names, simply add
3351                the following parameters to a JSON event:
3352
3353             .. container:: listingblock
3354
3355                .. container:: content
3356
3357                   .. code::
3358
3359                      "eventProtocolParameters":{
3360                        "eventProtocol" : "JSON",
3361                        "nameAlias"     : "policyName", (1)
3362                        "versionAlias"  : "policyVersion", (2)
3363                        "sourceAlias"   : "from", (3)
3364                        "targetAlias"   : "to", (4)
3365                        "nameSpaceAlias": "my.name.space" (5)
3366                      }
3367
3368             .. container:: colist arabic
3369
3370                +-----------------------------------+-----------------------------------+
3371                | **1**                             | mapping for the ``name`` field,   |
3372                |                                   | here from a field called          |
3373                |                                   | ``policyName``                    |
3374                +-----------------------------------+-----------------------------------+
3375                | **2**                             | mapping for the ``version``       |
3376                |                                   | field, here from a field called   |
3377                |                                   | ``policyVersion``                 |
3378                +-----------------------------------+-----------------------------------+
3379                | **3**                             | mapping for the ``source`` field, |
3380                |                                   | here from a field called ``from`` |
3381                |                                   | (only for an input event)         |
3382                +-----------------------------------+-----------------------------------+
3383                | **4**                             | mapping for the ``target`` field, |
3384                |                                   | here from a field called ``to``   |
3385                |                                   | (only for an output event)        |
3386                +-----------------------------------+-----------------------------------+
3387                | **5**                             | mapping for the ``nameSpace``     |
3388                |                                   | field, here from a field called   |
3389                |                                   | ``my.name.space``                 |
3390                +-----------------------------------+-----------------------------------+
3391
3392 APEX Event
3393 ##########
3394             .. container:: paragraph
3395
3396                The event protocol for APEX events does not require a
3397                specific plugin, it is supported by default. Furthermore,
3398                there is no difference in the configuration for the input
3399                and output interface.
3400
3401             .. container:: paragraph
3402
3403                For input and output APEX uses APEX events.
3404
3405             .. container:: paragraph
3406
3407                The following JSON shows the configuration.
3408
3409             .. container:: listingblock
3410
3411                .. container:: content
3412
3413                   .. code::
3414
3415                      "eventProtocolParameters":{
3416                        "eventProtocol" : "APEX"
3417                      }
3418
3419 JMS Event
3420 #########
3421
3422             .. container:: paragraph
3423
3424                The event protocol for JMS is provided by the APEX JMS
3425                plugin. The plugin supports encoding as JSON text or as
3426                object. There is no difference in the configuration for
3427                the input and output interface.
3428
3429 JMS Text
3430 ========
3431                .. container:: paragraph
3432
3433                   If used as input, APEX will take a JMS message and
3434                   extract a JSON string, then proceed as if a JSON event
3435                   was received. If used as output, APEX will take the
3436                   event produced by a policy, create a JSON string, and
3437                   then wrap it into a JMS message.
3438
3439                .. container:: paragraph
3440
3441                   The configuration for JMS text is as follows:
3442
3443                .. container:: listingblock
3444
3445                   .. container:: content
3446
3447                      .. code::
3448
3449                         "eventProtocolParameters":{
3450                           "eventProtocol" : "JMSTEXT",
3451                           "parameterClassName" :
3452                             "org.onap.policy.apex.plugins.event.protocol.jms.JMSTextEventProtocolParameters"
3453                         }
3454
3455 JMS Object
3456 ==========
3457                .. container:: paragraph
3458
3459                   If used as input, APEX will will take a JMS message,
3460                   extract a Java Bean from the ``ObjectMessage``
3461                   message, construct an APEX event and put the bean on
3462                   the APEX event as a parameter. If used as output, APEX
3463                   will take the event produced by a policy, create a
3464                   Java Bean and send it as a JMS message.
3465
3466                .. container:: paragraph
3467
3468                   The configuration for JMS object is as follows:
3469
3470                .. container:: listingblock
3471
3472                   .. container:: content
3473
3474                      .. code::
3475
3476                         "eventProtocolParameters":{
3477                           "eventProtocol" : "JMSOBJECT",
3478                           "parameterClassName" :
3479                             "org.onap.policy.apex.plugins.event.protocol.jms.JMSObjectEventProtocolParameters"
3480                         }
3481
3482 YAML Event
3483 ##########
3484
3485             .. container:: paragraph
3486
3487                The event protocol for YAML is provided by the APEX YAML
3488                plugin. There is no difference in the configuration for
3489                the input and output interface.
3490
3491             .. container:: paragraph
3492
3493                If used as input, APEX will consume events as YAML and
3494                map them to policy trigger events. Not well-formed YAML
3495                and not understood trigger events will be rejected. If
3496                used as output, APEX produce YAML encoded events from the
3497                event a policy produces. Those events will always be
3498                well-formed according to the definition in the policy
3499                model.
3500
3501             .. container:: paragraph
3502
3503                The following code shows the configuration.
3504
3505             .. container:: listingblock
3506
3507                .. container:: content
3508
3509                   .. code::
3510
3511                      "eventProtocolParameters":{
3512                        "eventProtocol" : "XML",
3513                        "parameterClassName" :
3514                            "org.onap.policy.apex.plugins.event.protocol.yaml.YamlEventProtocolParameters"
3515                      }
3516
3517 XML Event
3518 #########
3519             .. container:: paragraph
3520
3521                The event protocol for XML is provided by the APEX XML
3522                plugin. There is no difference in the configuration for
3523                the input and output interface.
3524
3525             .. container:: paragraph
3526
3527                If used as input, APEX will consume events as XML and map
3528                them to policy trigger events. Not well-formed XML and
3529                not understood trigger events will be rejected. If used
3530                as output, APEX produce XML encoded events from the event
3531                a policy produces. Those events will always be
3532                well-formed according to the definition in the policy
3533                model.
3534
3535             .. container:: paragraph
3536
3537                The following code shows the configuration.
3538
3539             .. container:: listingblock
3540
3541                .. container:: content
3542
3543                   .. code::
3544
3545                      "eventProtocolParameters":{
3546                        "eventProtocol" : "XML",
3547                        "parameterClassName" :
3548                            "org.onap.policy.apex.plugins.event.protocol.xml.XMLEventProtocolParameters"
3549                      }
3550
3551 A configuration example
3552 -----------------------
3553
3554          .. container:: paragraph
3555
3556             The following example loads all available plug-ins.
3557
3558          .. container:: paragraph
3559
3560             Events are consumed from a Websocket, APEX as client.
3561             Consumed event format is JSON.
3562
3563          .. container:: paragraph
3564
3565             Events are produced to Kafka. Produced event format is XML.
3566
3567          .. container:: listingblock
3568
3569             .. container:: content
3570
3571                .. code::
3572
3573                   {
3574                     "engineServiceParameters" : {
3575                       "name"          : "MyApexEngine",
3576                       "version"        : "0.0.1",
3577                       "id"             :  45,
3578                       "instanceCount"  : 4,
3579                       "deploymentPort" : 12345,
3580                       "policyModelFileName" : "examples/models/some-model.json",
3581                       "engineParameters"    : {
3582                         "executorParameters" : {
3583                           "JAVASCRIPT" : {
3584                             "parameterClassName" :
3585                                 "org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters"
3586                           },
3587                           "JYTHON" : {
3588                             "parameterClassName" :
3589                                 "org.onap.policy.apex.plugins.executor.jython.JythonExecutorParameters"
3590                           },
3591                           "JRUBY" : {
3592                             "parameterClassName" :
3593                                 "org.onap.policy.apex.plugins.executor.jruby.JrubyExecutorParameters"
3594                           },
3595                           "JAVA" : {
3596                             "parameterClassName" :
3597                                 "org.onap.policy.apex.plugins.executor.java.JavaExecutorParameters"
3598                           },
3599                           "MVEL" : {
3600                             "parameterClassName" :
3601                                 "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters"
3602                           }
3603                         },
3604                         "contextParameters" : {
3605                           "parameterClassName" :
3606                               "org.onap.policy.apex.context.parameters.ContextParameters",
3607                           "schemaParameters" : {
3608                             "Avro":{
3609                                "parameterClassName" :
3610                                    "org.onap.policy.apex.plugins.context.schema.avro.AvroSchemaHelperParameters"
3611                             }
3612                           }
3613                         }
3614                       }
3615                     },
3616                     "producerCarrierTechnologyParameters" : {
3617                       "carrierTechnology" : "KAFKA",
3618                       "parameterClassName" :
3619                           "org.onap.policy.apex.plugins.event.carrier.kafka.KAFKACarrierTechnologyParameters",
3620                       "parameters" : {
3621                         "bootstrapServers"  : "localhost:49092",
3622                         "acks"              : "all",
3623                         "retries"           : 0,
3624                         "batchSize"         : 16384,
3625                         "lingerTime"        : 1,
3626                         "bufferMemory"      : 33554432,
3627                         "producerTopic"     : "apex-out",
3628                         "keySerializer"     : "org.apache.kafka.common.serialization.StringSerializer",
3629                         "valueSerializer"   : "org.apache.kafka.common.serialization.StringSerializer"
3630                       }
3631                     },
3632                     "producerEventProtocolParameters" : {
3633                       "eventProtocol" : "XML",
3634                            "parameterClassName" :
3635                                "org.onap.policy.apex.plugins.event.protocol.xml.XMLEventProtocolParameters"
3636                     },
3637                     "consumerCarrierTechnologyParameters" : {
3638                       "carrierTechnology" : "WEBSOCKET",
3639                       "parameterClassName" :
3640                           "org.onap.policy.apex.plugins.event.carrier.websocket.WEBSOCKETCarrierTechnologyParameters",
3641                       "parameters" : {
3642                         "host" : "localhost",
3643                         "port" : 88888
3644                       }
3645                     },
3646                     "consumerEventProtocolParameters" : {
3647                       "eventProtocol" : "JSON"
3648                     }
3649                   }
3650
3651 Engine and Applications of the APEX System
3652 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3653
3654 Introduction to APEX Engine and Applications
3655 --------------------------------------------
3656
3657          .. container:: paragraph
3658
3659             The core of APEX is the APEX Engine, also known as the APEX
3660             Policy Engine or the APEX PDP (since it is in fact a Policy
3661             Decision Point). Beside this engine, an APEX system comes
3662             with a few applications intended to help with policy
3663             authoring, deployment, and execution.
3664
3665          .. container:: paragraph
3666
3667             The engine itself and most applications are started from the
3668             command line with command line arguments. This is called a
3669             Command Line Interface (CLI). Some applications require an
3670             installation on a webserver, as for instance the REST
3671             Editor. Those applications can be accessed via a web
3672             browser.
3673
3674          .. container:: paragraph
3675
3676             You can also use the available APEX APIs and applications to
3677             develop other applications as required. This includes policy
3678             languages (and associated parsers and compilers /
3679             interpreters), GUIs to access APEX or to define policies,
3680             clients to connect to APEX, etc.
3681
3682          .. container:: paragraph
3683
3684             For this documentation, we assume an installation of APEX as
3685             a full system based on a current ONAP release.
3686
3687 CLI on Unix, Windows, and Cygwin
3688 --------------------------------
3689
3690          .. container:: paragraph
3691
3692             A note on APEX CLI applications: all applications and the
3693             engine itself have been deployed and tested on different
3694             operating systems: Red Hat, Ubuntu, Debian, Mac OSX,
3695             Windows, Cygwin. Each operating system comes with its own
3696             way of configuring and executing Java. The main items here
3697             are:
3698
3699          .. container:: ulist
3700
3701             -  For UNIX systems (RHL, Ubuntu, Debian, Mac OSX), the
3702                provided bash scripts work as expected with absolute
3703                paths (e.g.
3704                ``/opt/app/policy/apex-pdp/apex-pdp-2.0.0-SNAPSHOT/examples``),
3705                indirect and linked paths (e.g. ``../apex/apex``), and
3706                path substitutions using environment settings (e.g.
3707                ``$APEX_HOME/bin/``)
3708
3709             -  For Windows systems, the provided batch files (``.bat``)
3710                work as expected with with absolute paths (e.g.
3711                ``C:\apex\apex-2.0.0-SNAPSHOT\examples``), and path
3712                substitutions using environment settings (e.g.
3713                ``%APEX_HOME%\bin\``)
3714
3715             -  For Cygwin system we assume a standard Cygwin
3716                installation with standard tools (mainly bash) using a
3717                Windows Java installation. This means that the bash
3718                scripts can be used as in UNIX, however any argument
3719                pointing to files and directories need to use either a
3720                DOS path (e.g.
3721                ``C:\apex\apex-2.0.0-SNAPSHOT\examples\config...``) or
3722                the command ``cygpath`` with a mixed option. The reason
3723                for that is: Cygwin executes Java using UNIX paths but
3724                then runs Java as a DOS/WINDOWS process, which requires
3725                DOS paths for file access.
3726
3727 The APEX Engine
3728 ---------------
3729
3730          .. container:: paragraph
3731
3732             The APEX engine can be started in different ways, depending
3733             your requirements. All scripts are located in the APEX *bin*
3734             directory
3735
3736          .. container:: paragraph
3737
3738             On UNIX and Cygwin systems use:
3739
3740          .. container:: ulist
3741
3742             -  ``apexEngine.sh`` - this script will
3743
3744                .. container:: ulist
3745
3746                   -  Test if ``$APEX_USER`` is set and if the user
3747                      exists, terminate with an error otherwise
3748
3749                   -  Test if ``$APEX_HOME`` is set. If not set, it will
3750                      use the default setting as
3751                      ``/opt/app/policy/apex-pdp/apex-pdp``. Then the set
3752                      directory is tested to exist, the script will
3753                      terminate if not.
3754
3755                   -  When all tests are passed successfully, the script
3756                      will call ``apexApps.sh`` with arguments to start
3757                      the APEX engine.
3758
3759             -  ``apexApps.sh engine`` - this is the general APEX
3760                application launcher, which will
3761
3762                .. container:: ulist
3763
3764                   -  Start the engine with the argument ``engine``
3765
3766                   -  Test if ``$APEX_HOME`` is set and points to an
3767                      existing directory. If not set or directory does
3768                      not exist, script terminates.
3769
3770                   -  Not test for any settings of ``$APEX_USER``.
3771
3772          .. container:: paragraph
3773
3774             On Windows systems use ``apexEngine.bat`` and
3775             ``apexApps.bat engine`` respectively. Note: none of the
3776             windows batch files will test for ``%APEX_USER%``.
3777
3778          .. container:: paragraph
3779
3780             Summary of alternatives to start the APEX Engine:
3781
3782          +--------------------------------------------------------+----------------------------------------------------------+
3783          | Unix, Cygwin                                           | Windows                                                  |
3784          +========================================================+==========================================================+
3785          | .. container::                                         | .. container::                                           |
3786          |                                                        |                                                          |
3787          |    .. container:: listingblock                         |    .. container:: listingblock                           |
3788          |                                                        |                                                          |
3789          |       .. container:: content                           |       .. container:: content                             |
3790          |                                                        |                                                          |
3791          |          .. code::                                     |          .. code::                                       |
3792          |                                                        |                                                          |
3793          |             # $APEX_HOME/bin/apexEngine.sh [args]      |             > %APEX_HOME%\bin\apexEngine.bat [args]      |
3794          |             # $APEX_HOME/bin/apexApps.sh engine [args] |             > %APEX_HOME%\bin\apexApps.bat engine [args] |
3795          +--------------------------------------------------------+----------------------------------------------------------+
3796
3797          .. container:: paragraph
3798
3799             The APEX engine comes with a few CLI arguments for setting
3800             configuration and policy model. The configuration file is
3801             always required. The policy model file is only required if
3802             no model file is specified in the configuration, or if the
3803             specified model file should be over written. The option
3804             ``-h`` prints a help screen.
3805
3806          .. container:: listingblock
3807
3808             .. container:: content
3809
3810                .. code::
3811
3812                   usage: org.onap.policy.apex.service.engine.main.ApexMain [options...]
3813                   options
3814                   -c,--config-file <CONFIG_FILE>  the full path to the configuration file to use, the configuration file must be a Json file
3815                                                   containing the Apex configuration parameters
3816                   -h,--help                       outputs the usage of this command
3817                   -m,--model-file <MODEL_FILE>    the full path to the model file to use, if set it overrides the model file set in the
3818                                                   configuration file
3819                   -v,--version                    outputs the version of Apex
3820
3821 The APEX CLI Editor
3822 -------------------
3823
3824          .. container:: paragraph
3825
3826             The CLI Editor allows to define policies from the command
3827             line. The application uses a simple language and supports
3828             all elements of an APEX policy. It can be used in to
3829             different ways:
3830
3831          .. container:: ulist
3832
3833             -  non-interactive, specifying a file with the commands to
3834                create a policy
3835
3836             -  interactive, using the editors CLI to create a policy
3837
3838          .. container:: paragraph
3839
3840             When a policy is fully specified, the editor will generate
3841             the APEX core policy specification in JSON. This core
3842             specification is called the policy model in the APEX engine
3843             and can be used directly with the APEX engine.
3844
3845          .. container:: paragraph
3846
3847             On UNIX and Cygwin systems use:
3848
3849          .. container:: ulist
3850
3851             -  ``apexCLIEditor.sh`` - simply starts the CLI editor,
3852                arguments to the script determine the mode of the editor
3853
3854             -  ``apexApps.sh cli-editor`` - simply starts the CLI
3855                editor, arguments to the script determine the mode of the
3856                editor
3857
3858          .. container:: paragraph
3859
3860             On Windows systems use:
3861
3862          .. container:: ulist
3863
3864             -  ``apexCLIEditor.bat`` - simply starts the CLI editor,
3865                arguments to the script determine the mode of the editor
3866
3867             -  ``apexApps.bat cli-editor`` - simply starts the CLI
3868                editor, arguments to the script determine the mode of the
3869                editor
3870
3871          .. container:: paragraph
3872
3873             Summary of alternatives to start the APEX CLI Editor:
3874
3875          +------------------------------------------------------------+--------------------------------------------------------------+
3876          | Unix, Cygwin                                               | Windows                                                      |
3877          +============================================================+==============================================================+
3878          | .. container::                                             | .. container::                                               |
3879          |                                                            |                                                              |
3880          |    .. container:: listingblock                             |    .. container:: listingblock                               |
3881          |                                                            |                                                              |
3882          |       .. container:: content                               |       .. container:: content                                 |
3883          |                                                            |                                                              |
3884          |          .. code::                                         |          .. code::                                           |
3885          |                                                            |                                                              |
3886          |             # $APEX_HOME/bin/apexCLIEditor.sh.sh [args]    |             > %APEX_HOME%\bin\apexCLIEditor.bat [args]       |
3887          |             # $APEX_HOME/bin/apexApps.sh cli-editor [args] |             > %APEX_HOME%\bin\apexApps.bat cli-editor [args] |
3888          +------------------------------------------------------------+--------------------------------------------------------------+
3889
3890          .. container:: paragraph
3891
3892             The option ``-h`` provides a help screen with all command
3893             line arguments.
3894
3895          .. container:: listingblock
3896
3897             .. container:: content
3898
3899                .. code::
3900
3901                   usage: org.onap.policy.apex.auth.clieditor.ApexCLIEditorMain [options...]
3902                   options
3903                    -a,--model-props-file <MODEL_PROPS_FILE>       name of the apex model properties file to use
3904                    -c,--command-file <COMMAND_FILE>               name of a file containing editor commands to run into the editor
3905                    -h,--help                                      outputs the usage of this command
3906                    -i,--input-model-file <INPUT_MODEL_FILE>       name of a file that contains an input model for the editor
3907                    -if,--ignore-failures <IGNORE_FAILURES_FLAG>   true or false, ignore failures of commands in command files and continue
3908                                                                   executing the command file
3909                    -l,--log-file <LOG_FILE>                       name of a file that will contain command logs from the editor, will log
3910                                                                   to standard output if not specified or suppressed with "-nl" flag
3911                    -m,--metadata-file <CMD_METADATA_FILE>         name of the command metadata file to use
3912                    -nl,--no-log                                   if specified, no logging or output of commands to standard output or log
3913                                                                   file is carried out
3914                    -nm,--no-model-output                          if specified, no output of a model to standard output or model output
3915                                                                   file is carried out, the user can use the "save" command in a script to
3916                                                                   save a model
3917                    -o,--output-model-file <OUTPUT_MODEL_FILE>     name of a file that will contain the output model for the editor, will
3918                                                                   output model to standard output if not specified or suppressed with
3919                                                                   "-nm" flag
3920                    -wd,--working-directory <WORKING_DIRECTORY>    the working directory that is the root for the CLI editor and is the
3921                                                                   root from which to look for included macro files
3922
3923 The APEX REST Editor
3924 --------------------
3925
3926          .. container:: paragraph
3927
3928             The standard way to use the APEX REST Editor is via an
3929             installation of the *war* file on a webserver. However, the
3930             REST editor can also be started via command line. This will
3931             start a Grizzly webserver with the *war* deployed. Access to
3932             the REST Editor is then via the provided URL
3933
3934          .. container:: paragraph
3935
3936             On UNIX and Cygwin systems use:
3937
3938          .. container:: ulist
3939
3940             -  ``apexRESTEditor.sh`` - simply starts the webserver with
3941                the REST editor
3942
3943             -  ``apexApps.sh rest-editor`` - simply starts the webserver
3944                with the REST editor
3945
3946          .. container:: paragraph
3947
3948             On Windows systems use:
3949
3950          .. container:: ulist
3951
3952             -  ``apexRESTEditor.bat`` - simply starts the webserver with
3953                the REST editor
3954
3955             -  ``apexApps.bat rest-editor`` - simply starts the
3956                webserver with the REST editor
3957
3958          .. container:: paragraph
3959
3960             Summary of alternatives to start the APEX REST Editor:
3961
3962          +-------------------------------------------------------------+---------------------------------------------------------------+
3963          | Unix, Cygwin                                                | Windows                                                       |
3964          +=============================================================+===============================================================+
3965          | .. container::                                              | .. container::                                                |
3966          |                                                             |                                                               |
3967          |    .. container:: listingblock                              |    .. container:: listingblock                                |
3968          |                                                             |                                                               |
3969          |       .. container:: content                                |       .. container:: content                                  |
3970          |                                                             |                                                               |
3971          |          .. code::                                          |          .. code::                                            |
3972          |                                                             |                                                               |
3973          |             # $APEX_HOME/bin/apexRESTEditor.sh.sh [args]    |             > %APEX_HOME%\bin\apexRESTEditor.bat [args]       |
3974          |             # $APEX_HOME/bin/apexApps.sh rest-editor [args] |             > %APEX_HOME%\bin\apexApps.bat rest-editor [args] |
3975          +-------------------------------------------------------------+---------------------------------------------------------------+
3976
3977          .. container:: paragraph
3978
3979             The option ``-h`` provides a help screen with all command
3980             line arguments.
3981
3982          .. container:: listingblock
3983
3984             .. container:: content
3985
3986                .. code::
3987
3988                   usage: org.onap.policy.apex.client.editor.rest.ApexEditorMain [options...]
3989                   -h,--help                        outputs the usage of this command
3990                   -l,--listen <ADDRESS>            the IP address to listen on.  Default value is localhost to restrict access to the
3991                                                    local machine only.
3992                   -p,--port <PORT>                 port to use for the Apex RESTful editor REST calls.
3993                   -t,--time-to-live <TIME_TO_LIVE> the amount of time in seconds that the server will run for before terminating. Default
3994                                                    value is -1 to run indefinitely.
3995
3996          .. container:: paragraph
3997
3998             If the REST Editor is started without any arguments the
3999             final messages will look similar to this:
4000
4001          .. container:: listingblock
4002
4003             .. container:: content
4004
4005                .. code::
4006
4007                   Apex Editor REST endpoint (ApexEditorMain: Config=[ApexEditorParameters: URI=http://localhost:18989/apexservices/, TTL=-1sec], State=READY) starting at http://localhost:18989/apexservices/ . . .
4008                   Sep 05, 2018 11:24:30 PM org.glassfish.grizzly.http.server.NetworkListener start
4009                   INFO: Started listener bound to [localhost:18989]
4010                   Sep 05, 2018 11:24:30 PM org.glassfish.grizzly.http.server.HttpServer start
4011                   INFO: [HttpServer] Started.
4012                   Apex Editor REST endpoint (ApexEditorMain: Config=[ApexEditorParameters: URI=http://localhost:18989/apexservices/, TTL=-1sec], State=RUNNING) started at http://localhost:18989/apexservices/
4013
4014          .. container:: paragraph
4015
4016             The last line states the URL on which the REST Editor can be
4017             accessed. The example above stated
4018             ``http://0.0.0.0:18989/apex/``. In a web browser use the URL
4019             ``http://localhost:18989`` and the REST Editor will start.
4020
4021 The APEX Monitoring Client
4022 --------------------------
4023
4024          .. container:: paragraph
4025
4026             The standard way to use the APEX Monitoring Client is via an
4027             installation of the *war* file on a webserver. However, the
4028             Monitoring Client can also be started via command line. This
4029             will start a Grizzly webserver with the *war* deployed.
4030             Access to the Monitoring Client is then via the provided URL
4031
4032          .. container:: paragraph
4033
4034             On UNIX and Cygwin systems use:
4035
4036          .. container:: ulist
4037
4038             -  ``apexApps.sh eng-monitoring`` - simply starts the
4039                webserver with the Monitoring Client
4040
4041          .. container:: paragraph
4042
4043             On Windows systems use:
4044
4045          .. container:: ulist
4046
4047             -  ``apexApps.bat eng-monitoring`` - simply starts the
4048                webserver with the Monitoring Client
4049
4050          .. container:: paragraph
4051
4052             The option ``-h`` provides a help screen with all command
4053             line arguments.
4054
4055          .. container:: listingblock
4056
4057             .. container:: content
4058
4059                .. code::
4060
4061                   usage: org.onap.policy.apex.client.monitoring.rest.ApexMonitoringRestMain [options...]
4062                   -h,--help                        outputs the usage of this command
4063                   -p,--port <PORT>                 port to use for the Apex Services REST calls
4064                   -t,--time-to-live <TIME_TO_LIVE> the amount of time in seconds that the server will run for before terminating
4065
4066          .. container:: paragraph
4067
4068             If the Monitoring Client is started without any arguments
4069             the final messages will look similar to this:
4070
4071          .. container:: listingblock
4072
4073             .. container:: content
4074
4075                .. code::
4076
4077                   Apex Services REST endpoint (ApexMonitoringRestMain: Config=[ApexMonitoringRestParameters: URI=http://localhost:18989/apexservices/, TTL=-1sec], State=READY) starting at http://localhost:18989/apexservices/ . . .
4078                   Sep 05, 2018 11:26:20 PM org.glassfish.grizzly.http.server.NetworkListener start
4079                   INFO: Started listener bound to [localhost:18989]
4080                   Sep 05, 2018 11:26:20 PM org.glassfish.grizzly.http.server.HttpServer start
4081                   INFO: [HttpServer] Started.
4082                   Apex Services REST endpoint (ApexMonitoringRestMain: Config=[ApexMonitoringRestParameters: URI=http://localhost:18989/apexservices/, TTL=-1sec], State=RUNNING) started at http://localhost:18989/apexservices/
4083
4084          .. container:: paragraph
4085
4086             The last line states the URL on which the Monitoring Client
4087             can be accessed. The example above stated
4088             ``http://localhost:18989/apexservices``. In a web browser
4089             use the URL ``http://localhost:18989``.
4090
4091 The APEX Deployment Client
4092 --------------------------
4093
4094          .. container:: paragraph
4095
4096             The standard way to use the APEX Deployment Client is via an
4097             installation of the *war* file on a webserver. However, the
4098             Deployment Client can also be started via command line. This
4099             will start a Grizzly webserver with the *war* deployed.
4100             Access to the Deployment Client is then via the provided URL
4101
4102          .. container:: paragraph
4103
4104             On UNIX and Cygwin systems use:
4105
4106          .. container:: ulist
4107
4108             -  ``apexApps.sh eng-deployment`` - simply starts the
4109                webserver with the Deployment Client
4110
4111          .. container:: paragraph
4112
4113             On Windows systems use:
4114
4115          .. container:: ulist
4116
4117             -  ``apexApps.bat eng-deployment`` - simply starts the
4118                webserver with the Deployment Client
4119
4120          .. container:: paragraph
4121
4122             The option ``-h`` provides a help screen with all command
4123             line arguments.
4124
4125          .. container:: listingblock
4126
4127             .. container:: content
4128
4129                .. code::
4130
4131                   usage: org.onap.policy.apex.client.deployment.rest.ApexDeploymentRestMain [options...]
4132                   -h,--help                        outputs the usage of this command
4133                   -p,--port <PORT>                 port to use for the Apex Services REST calls
4134                   -t,--time-to-live <TIME_TO_LIVE> the amount of time in seconds that the server will run for before terminating
4135
4136          .. container:: paragraph
4137
4138             If the Deployment Client is started without any arguments
4139             the final messages will look similar to this:
4140
4141          .. container:: listingblock
4142
4143             .. container:: content
4144
4145                .. code::
4146
4147                   Apex Services REST endpoint (ApexDeploymentRestMain: Config=[ApexDeploymentRestParameters: URI=http://localhost:18989/apexservices/, TTL=-1sec], State=READY) starting at http://localhost:18989/apexservices/ . . .
4148                   Sep 05, 2018 11:27:09 PM org.glassfish.grizzly.http.server.NetworkListener start
4149                   INFO: Started listener bound to [localhost:18989]
4150                   Sep 05, 2018 11:27:09 PM org.glassfish.grizzly.http.server.HttpServer start
4151                   INFO: [HttpServer] Started.
4152                   Apex Services REST endpoint (ApexDeploymentRestMain: Config=[ApexDeploymentRestParameters: URI=http://localhost:18989/apexservices/, TTL=-1sec], State=RUNNING) started at http://localhost:18989/apexservices/
4153
4154          .. container:: paragraph
4155
4156             The last line states the URL on which the Deployment Client
4157             can be accessed. The example above stated
4158             ``http://localhost:18989/apexservices``. In a web browser
4159             use the URL ``http://localhost:18989``.
4160
4161 The APEX Full Client
4162 --------------------
4163
4164          .. container:: paragraph
4165
4166             The APEX Full Client combines the REST Editor, the
4167             Monitoring Client, and the Deployment Client into a single
4168             application. The standard way to use the APEX Full Client is
4169             via an installation of the *war* file on a webserver.
4170             However, the Full Client can also be started via command
4171             line. This will start a Grizzly webserver with the *war*
4172             deployed. Access to the Full Client is then via the provided
4173             URL
4174
4175          .. container:: paragraph
4176
4177             On UNIX and Cygwin systems use:
4178
4179          .. container:: ulist
4180
4181             -  ``apexApps.sh full-client`` - simply starts the webserver
4182                with the Full Client
4183
4184          .. container:: paragraph
4185
4186             On Windows systems use:
4187
4188          .. container:: ulist
4189
4190             -  ``apexApps.bat full-client`` - simply starts the
4191                webserver with the Full Client
4192
4193          .. container:: paragraph
4194
4195             The option ``-h`` provides a help screen with all command
4196             line arguments.
4197
4198          .. container:: listingblock
4199
4200             .. container:: content
4201
4202                .. code::
4203
4204                   usage: org.onap.policy.apex.client.full.rest.ApexServicesRestMain [options...]
4205                   -h,--help                        outputs the usage of this command
4206                   -p,--port <PORT>                 port to use for the Apex Services REST calls
4207                   -t,--time-to-live <TIME_TO_LIVE> the amount of time in seconds that the server will run for before terminating
4208
4209          .. container:: paragraph
4210
4211             If the Full Client is started without any arguments the
4212             final messages will look similar to this:
4213
4214          .. container:: listingblock
4215
4216             .. container:: content
4217
4218                .. code::
4219
4220                   Apex Editor REST endpoint (ApexServicesRestMain: Config=[ApexServicesRestParameters: URI=http://localhost:18989/apexservices/, TTL=-1sec], State=READY) starting at http://localhost:18989/apexservices/ . . .
4221                   Sep 05, 2018 11:28:28 PM org.glassfish.grizzly.http.server.NetworkListener start
4222                   INFO: Started listener bound to [localhost:18989]
4223                   Sep 05, 2018 11:28:28 PM org.glassfish.grizzly.http.server.HttpServer start
4224                   INFO: [HttpServer] Started.
4225                   Apex Editor REST endpoint (ApexServicesRestMain: Config=[ApexServicesRestParameters: URI=http://localhost:18989/apexservices/, TTL=-1sec], State=RUNNING) started at http://localhost:18989/apexservices/
4226
4227          .. container:: paragraph
4228
4229             The last line states the URL on which the Monitoring Client
4230             can be accessed. The example above stated
4231             ``http://localhost:18989/apexservices``. In a web browser
4232             use the URL ``http://localhost:18989``.
4233
4234  The APEX Application Launcher
4235 ------------------------------
4236
4237          .. container:: paragraph
4238
4239             The standard applications (Engine, CLI Editor, REST Editor)
4240             come with dedicated start scripts. For all other APEX
4241             applications, we provide an application launcher.
4242
4243          .. container:: paragraph
4244
4245             On UNIX and Cygwin systems use:
4246
4247          .. container:: ulist
4248
4249             -  apexApps.sh\` - simply starts the application launcher
4250
4251          .. container:: paragraph
4252
4253             On Windows systems use:
4254
4255          .. container:: ulist
4256
4257             -  ``apexApps.bat`` - simply starts the application launcher
4258
4259          .. container:: paragraph
4260
4261             Summary of alternatives to start the APEX application
4262             launcher:
4263
4264          +-------------------------------------------------+---------------------------------------------------+
4265          | Unix, Cygwin                                    | Windows                                           |
4266          +=================================================+===================================================+
4267          | .. container::                                  | .. container::                                    |
4268          |                                                 |                                                   |
4269          |    .. container:: listingblock                  |    .. container:: listingblock                    |
4270          |                                                 |                                                   |
4271          |       .. container:: content                    |       .. container:: content                      |
4272          |                                                 |                                                   |
4273          |          .. code::                              |          .. code::                                |
4274          |                                                 |                                                   |
4275          |             # $APEX_HOME/bin/apexApps.sh [args] |             > %APEX_HOME%\bin\apexApps.bat [args] |
4276          +-------------------------------------------------+---------------------------------------------------+
4277
4278          .. container:: paragraph
4279
4280             The option ``-h`` provides a help screen with all launcher
4281             command line arguments.
4282
4283          .. container:: listingblock
4284
4285             .. container:: content
4286
4287                .. code::
4288
4289                   apexApps.sh - runs APEX applications
4290
4291                          Usage:  apexApps.sh [options] | [<application> [<application options>]]
4292
4293                          Options
4294                            -d <app>    - describes an application
4295                            -l          - lists all applications supported by this script
4296                            -h          - this help screen
4297
4298          .. container:: paragraph
4299
4300             Using ``-l`` lists all known application the launcher can
4301             start.
4302
4303          .. container:: listingblock
4304
4305             .. container:: content
4306
4307                .. code::
4308
4309                   apexApps.sh: supported applications:
4310                    --> ws-echo engine eng-monitoring full-client eng-deployment tpl-event-json model-2-cli rest-editor cli-editor ws-console
4311
4312          .. container:: paragraph
4313
4314             Using the ``-d <name>`` option describes the named
4315             application, for instance for the ``ws-console``:
4316
4317          .. container:: listingblock
4318
4319             .. container:: content
4320
4321                .. code::
4322
4323                   apexApps.sh: application 'ws-console'
4324                    --> a simple console sending events to APEX, connect to APEX consumer port
4325
4326          .. container:: paragraph
4327
4328             Launching an application is done by calling the script with
4329             only the application name and any CLI arguments for the
4330             application. For instance, starting the ``ws-echo``
4331             application with port ``8888``:
4332
4333          .. container:: listingblock
4334
4335             .. container:: content
4336
4337                .. code::
4338
4339                   apexApps.sh ws-echo -p 8888
4340
4341 Application: Create Event Templates
4342 -----------------------------------
4343
4344          .. container:: paragraph
4345
4346             **Status: Experimental**
4347
4348          .. container:: paragraph
4349
4350             This application takes a policy model (JSON or XML encoded)
4351             and generates templates for events in JSON format. This can
4352             help when a policy defines rather complex trigger or action
4353             events or complex events between states. The application can
4354             produce events for the types: stimuli (policy trigger
4355             events), internal (events between policy states), and
4356             response (action events).
4357
4358          +----------------------------------------------------------------+------------------------------------------------------------------+
4359          | Unix, Cygwin                                                   | Windows                                                          |
4360          +================================================================+==================================================================+
4361          | .. container::                                                 | .. container::                                                   |
4362          |                                                                |                                                                  |
4363          |    .. container:: listingblock                                 |    .. container:: listingblock                                   |
4364          |                                                                |                                                                  |
4365          |       .. container:: content                                   |       .. container:: content                                     |
4366          |                                                                |                                                                  |
4367          |          .. code::                                             |          .. code::                                               |
4368          |                                                                |                                                                  |
4369          |             # $APEX_HOME/bin/apexApps.sh tpl-event-json [args] |             > %APEX_HOME%\bin\apexApps.bat tpl-event-json [args] |
4370          +----------------------------------------------------------------+------------------------------------------------------------------+
4371
4372          .. container:: paragraph
4373
4374             The option ``-h`` provides a help screen.
4375
4376          .. container:: listingblock
4377
4378             .. container:: content
4379
4380                .. code::
4381
4382                   gen-model2event v{release-version} - generates JSON templates for events generated from a policy model
4383                   usage: gen-model2event
4384                    -h,--help                 prints this help and usage screen
4385                    -m,--model <MODEL-FILE>   set the input policy model file
4386                    -t,--type <TYPE>          set the event type for generation, one of:
4387                                              stimuli (trigger events), response (action
4388                                              events), internal (events between states)
4389                    -v,--version              prints the application version
4390
4391          .. container:: paragraph
4392
4393             The created templates are not valid events, instead they use
4394             some markup for values one will need to change to actual
4395             values. For instance, running the tool with the *Sample
4396             Domain* policy model as:
4397
4398          .. container:: listingblock
4399
4400             .. container:: content
4401
4402                .. code::
4403
4404                   apexApps.sh tpl-event-json -m $APEX_HOME/examples/models/SampleDomain/SamplePolicyModelJAVA.json -t stimuli
4405
4406          .. container:: paragraph
4407
4408             will produce the following status messages:
4409
4410          .. container:: listingblock
4411
4412             .. container:: content
4413
4414                .. code::
4415
4416                   gen-model2event: starting Event generator
4417                    --> model file: examples/models/SampleDomain/SamplePolicyModelJAVA.json
4418                    --> type: stimuli
4419
4420          .. container:: paragraph
4421
4422             and then run the generator application producing two event
4423             templates. The first template is called ``Event0000``.
4424
4425          .. container:: listingblock
4426
4427             .. container:: content
4428
4429                .. code::
4430
4431                   {
4432                           "name" : "Event0000",
4433                           "nameSpace" : "org.onap.policy.apex.sample.events",
4434                           "version" : "0.0.1",
4435                           "source" : "Outside",
4436                           "target" : "Match",
4437                           "TestTemperature" : ###double: 0.0###,
4438                           "TestTimestamp" : ###long: 0###,
4439                           "TestMatchCase" : ###integer: 0###,
4440                           "TestSlogan" : "###string###"
4441                   }
4442
4443          .. container:: paragraph
4444
4445             The values for the keys are marked with ``#`` and the
4446             expected type of the value. To create an actual stimuli
4447             event, all these markers need to be change to actual values,
4448             for instance:
4449
4450          .. container:: listingblock
4451
4452             .. container:: content
4453
4454                .. code::
4455
4456                   {
4457                           "name" : "Event0000",
4458                           "nameSpace" : "org.onap.policy.apex.sample.events",
4459                           "version" : "0.0.1",
4460                           "source" : "Outside",
4461                           "target" : "Match",
4462                           "TestTemperature" : 25,
4463                           "TestTimestamp" : 123456789123456789,
4464                           "TestMatchCase" : 1,
4465                           "TestSlogan" : "Testing the Match Case with Temperature 25"
4466                   }
4467
4468 Application: Convert a Policy Model to CLI Editor Commands
4469 ----------------------------------------------------------
4470
4471          .. container:: paragraph
4472
4473             **Status: Experimental**
4474
4475          .. container:: paragraph
4476
4477             This application takes a policy model (JSON or XML encoded)
4478             and generates commands for the APEX CLI Editor. This
4479             effectively reverses a policy specification realized with
4480             the CLI Editor.
4481
4482          +-------------------------------------------------------------+---------------------------------------------------------------+
4483          | Unix, Cygwin                                                | Windows                                                       |
4484          +=============================================================+===============================================================+
4485          | .. container::                                              | .. container::                                                |
4486          |                                                             |                                                               |
4487          |    .. container:: listingblock                              |    .. container:: listingblock                                |
4488          |                                                             |                                                               |
4489          |       .. container:: content                                |       .. container:: content                                  |
4490          |                                                             |                                                               |
4491          |          .. code::                                          |          .. code::                                            |
4492          |                                                             |                                                               |
4493          |             # $APEX_HOME/bin/apexApps.sh model-2-cli [args] |             > %APEX_HOME%\bin\apexApps.bat model-2-cli [args] |
4494          +-------------------------------------------------------------+---------------------------------------------------------------+
4495
4496          .. container:: paragraph
4497
4498             The option ``-h`` provides a help screen.
4499
4500          .. container:: listingblock
4501
4502             .. container:: content
4503
4504                .. code::
4505
4506                   usage: gen-model2cli
4507                    -h,--help                 prints this help and usage screen
4508                    -m,--model <MODEL-FILE>   set the input policy model file
4509                    -sv,--skip-validation     switch of validation of the input file
4510                    -v,--version              prints the application version
4511
4512          .. container:: paragraph
4513
4514             For instance, running the tool with the *Sample Domain*
4515             policy model as:
4516
4517          .. container:: listingblock
4518
4519             .. container:: content
4520
4521                .. code::
4522
4523                   apexApps.sh model-2-cli -m $APEX_HOME/examples/models/SampleDomain/SamplePolicyModelJAVA.json
4524
4525          .. container:: paragraph
4526
4527             will produce the following status messages:
4528
4529          .. container:: listingblock
4530
4531             .. container:: content
4532
4533                .. code::
4534
4535                   gen-model2cli: starting CLI generator
4536                    --> model file: examples/models/SampleDomain/SamplePolicyModelJAVA.json
4537
4538          .. container:: paragraph
4539
4540             and then run the generator application producing all CLI
4541             Editor commands and printing them to standard out.
4542
4543 Application: Websocket Clients (Echo and Console)
4544 -------------------------------------------------
4545
4546          .. container:: paragraph
4547
4548             **Status: Production**
4549
4550          .. container:: paragraph
4551
4552             The application launcher also provides a Websocket echo
4553             client and a Websocket console client. The echo client
4554             connects to APEX and prints all events it receives from
4555             APEX. The console client connects to APEX, reads input from
4556             the command line, and sends this input as events to APEX.
4557
4558          +------------------------------------------------------------+--------------------------------------------------------------+
4559          | Unix, Cygwin                                               | Windows                                                      |
4560          +============================================================+==============================================================+
4561          | .. container::                                             | .. container::                                               |
4562          |                                                            |                                                              |
4563          |    .. container:: listingblock                             |    .. container:: listingblock                               |
4564          |                                                            |                                                              |
4565          |       .. container:: content                               |       .. container:: content                                 |
4566          |                                                            |                                                              |
4567          |          .. code::                                         |          .. code::                                           |
4568          |                                                            |                                                              |
4569          |             # $APEX_HOME/bin/apexApps.sh ws-echo [args]    |             > %APEX_HOME%\bin\apexApps.bat ws-echo [args]    |
4570          |             # $APEX_HOME/bin/apexApps.sh ws-console [args] |             > %APEX_HOME%\bin\apexApps.bat ws-console [args] |
4571          +------------------------------------------------------------+--------------------------------------------------------------+
4572
4573          .. container:: paragraph
4574
4575             The arguments are the same for both applications:
4576
4577          .. container:: ulist
4578
4579             -  ``-p`` defines the Websocket port to connect to (defaults
4580                to ``8887``)
4581
4582             -  ``-s`` defines the host on which a Websocket server is
4583                running (defaults to ``localhost``)
4584
4585          .. container:: paragraph
4586
4587             A discussion on how to use these two applications to build
4588             an APEX system is detailed HowTo-Websockets.
4589
4590 My First Policy
4591 ^^^^^^^^^^^^^^^
4592
4593 Introduction
4594 ------------
4595          .. container:: paragraph
4596
4597             Consider a scenario where a supermarket chain called
4598             *HyperM* controls how it sells items in a policy-based
4599             manner. Each time an item is processed by *HyperM*'s
4600             point-of-sale (PoS) system an event is generated and
4601             published about that item of stock being sold. This event
4602             can then be used to update stock levels, etc..
4603
4604          .. container:: paragraph
4605
4606             *HyperM* want to extend this approach to allow some checks
4607             to be performed before the sale can be completed. This can
4608             be achieved by requesting a policy-controlled decision as
4609             each item is processed by for sale by each PoS system. The
4610             decision process is integrated with *HyperM*'s other IT
4611             systems that manage stock control, sourcing and purchasing,
4612             personnel systems, etc.
4613
4614          .. container:: paragraph
4615
4616             In this document we will show how APEX and APEX Policies can
4617             be used to achieve this, starting with a simple policy,
4618             building up to more complicated policy that demonstrates the
4619             features of APEX.
4620
4621 Data Models
4622 -----------
4623
4624 Sales Input Event
4625 #################
4626
4627             .. container:: paragraph
4628
4629                Each time a PoS system processes a sales item an event
4630                with the following format is emitted:
4631
4632             .. table:: Table 1. Sale Input Event
4633
4634                +----------------------+----------------------+-----------------------+
4635                | Event                | Fields               | Description           |
4636                +======================+======================+=======================+
4637                | SALE_INPUT           | time, sale_ID,       | Event indicating a    |
4638                |                      | amount, item_ID,     | sale of an item is    |
4639                |                      | quantity,            | occurring             |
4640                |                      | assistant_ID,        |                       |
4641                |                      | branch_ID, notes, …​ |                       |
4642                +----------------------+----------------------+-----------------------+
4643
4644             .. container:: paragraph
4645
4646                In each ``SALE_INPUT`` event the ``sale_ID`` field is a
4647                unique ID generated by the PoS system. A timestamp for
4648                the event is stored in the ``time`` field. The ``amount``
4649                field refers to the value of the item(s) to be sold (in
4650                cents). The ``item_ID`` field is a unique identifier for
4651                each item type, and can be used to retrieve more
4652                information about the item from *HyperM*'s stock control
4653                system. The ``quantity`` field refers to the quantity of
4654                the item to be sold. The ``assistant_ID`` field is a
4655                unique identifier for the PoS operator, and can be used
4656                to retrieve more information about the operator from the
4657                *HyperM*'s personnel system. Since *HyperM* has many
4658                branches the ``branch_ID`` identifies the shop. The
4659                ``notes`` field contains arbitrary notes about the sale.
4660
4661 Sales Decision Event
4662 ####################
4663
4664             .. container:: paragraph
4665
4666                After a ``SALE_INPUT`` event is emitted by the PoS system
4667                *HyperM*'s policy-based controlled sales checking system
4668                emits a Sale Authorization Event indicating whether the
4669                sale is authorized or denied. The PoS system can then
4670                listen for this event before continuing with the sale.
4671
4672             .. table:: Table 2. Sale Authorisation Event
4673
4674                +----------------------+----------------------+-----------------------+
4675                | Event                | Fields               | Description           |
4676                +======================+======================+=======================+
4677                | SALE_AUTH            | sale_ID, time,       | Event indicating a    |
4678                |                      | authorized, amount,  | sale of an item is    |
4679                |                      | item_ID, quantity,   | authorized or denied  |
4680                |                      | assistant_ID,        |                       |
4681                |                      | branch_ID, notes,    |                       |
4682                |                      | message…​            |                       |
4683                +----------------------+----------------------+-----------------------+
4684
4685             .. container:: paragraph
4686
4687                In each ``SALE_AUTH`` event the ``sale_ID`` field is
4688                copied from the ``SALE_INPUT`` event that trigger the
4689                decision request. The ``SALE_AUTH`` event is also
4690                timestamped using the ``time`` field, and a field called
4691                ``authorised`` is set to ``true`` or ``false`` depending
4692                on whether the sale is authorized or denied. The
4693                ``message`` field carries an optional message about why a
4694                sale was not authorized. The other fields from the
4695                ``SALE_INPUT`` event are also included for completeness.
4696
4697 Stock Control: Items
4698 ####################
4699
4700             .. container:: paragraph
4701
4702                *HyperM* maintains information about each item for sale
4703                in a database table called ``ITEMS``.
4704
4705             .. table:: Table 3. Items Database
4706
4707                +----------------------+----------------------+-----------------------+
4708                | Table                | Fields               | Description           |
4709                +======================+======================+=======================+
4710                | ITEMS                | item_ID,             | Database table        |
4711                |                      | description,         | describing each item  |
4712                |                      | cost_price, barcode, | for sale              |
4713                |                      | supplier_ID,         |                       |
4714                |                      | category, …​         |                       |
4715                +----------------------+----------------------+-----------------------+
4716
4717             .. container:: paragraph
4718
4719                The database table ``ITEMS`` has a row for each items
4720                that *HyperM* sells. Each item is identified by an
4721                ``item_ID`` value. The ``description`` field stores a
4722                description of the item. The cost price of the item is
4723                given in ``cost_price``. The barcode of the item is
4724                encoded in ``barcode``, while the item supplier is
4725                identified by ``supplier_ID``. Items may also be
4726                classified into categories using the ``category`` field.
4727                Useful categories might include: ``soft drinks``,
4728                ``alcoholic drinks``, ``cigarettes``, ``knives``,
4729                ``confectionery``, ``bakery``, ``fruit&vegetables``,
4730                ``meat``, etc..
4731
4732 Personnel System: Assistants
4733 ############################
4734
4735             .. table:: Table 4. Assistants Database
4736
4737                +----------------------+----------------------+-----------------------+
4738                | Table                | Fields               | Description           |
4739                +======================+======================+=======================+
4740                | ASSISTANTS           | assistant_ID,        | Database table        |
4741                |                      | surname, firstname,  | describing each       |
4742                |                      | middlename, age,     | *HyperM* sales        |
4743                |                      | grade, phone_number, | assistant             |
4744                |                      | …​                   |                       |
4745                +----------------------+----------------------+-----------------------+
4746
4747             .. container:: paragraph
4748
4749                The database table ``ASSISTANTS`` has a row for each
4750                sales assistant employed by *HyperM*. Each assistant is
4751                identified by an ``assistant_ID`` value, with their name
4752                given in the ``firstname``, ``middlename`` and
4753                ``surname`` fields. The assistant’s age in years is given
4754                in ``age``, while their phone number is contained in the
4755                ``phone_number`` field. The assistant’s grade is encoded
4756                in ``grade``. Useful values for ``grade`` might include:
4757                ``trainee``, ``operator``, ``supervisor``, etc..
4758
4759 Locations: Branches
4760 ####################
4761
4762             .. table:: Table 5. Branches Database
4763
4764                +----------------------+----------------------+-----------------------+
4765                | Table                | Fields               | Description           |
4766                +======================+======================+=======================+
4767                | BRANCHES             | branch_ID,           | Database table        |
4768                |                      | branch_Name,         | describing each       |
4769                |                      | category, street,    | *HyperM* branch       |
4770                |                      | city, country,       |                       |
4771                |                      | postcode, …​         |                       |
4772                +----------------------+----------------------+-----------------------+
4773
4774             .. container:: paragraph
4775
4776                *HyperM* operates a number of branches. Each branch is
4777                described in the ``BRANCHES`` database table. Each branch
4778                is identified by a ``branch_ID``, with a branch name
4779                given in ``branch_Name``. The address for the branch is
4780                encoded in ``street``, ``city``, ``country`` and
4781                ``postcode``. The branch category is given in the
4782                ``category`` field. Useful values for ``category`` might
4783                include: ``Small``, ``Large``, ``Super``, ``Hyper``,
4784                etc..
4785
4786 Policy Step 1
4787 -------------
4788
4789 Scenario
4790 #########
4791             .. container:: paragraph
4792
4793                For the first version of our policy, let’s start with
4794                something simple. Let us assume that there exists some
4795                restriction that alcohol products cannot be sold before
4796                11:30am. In this section we will go through the necessary
4797                steps to define a policy that can enforce this for
4798                *HyperM*.
4799
4800             .. container:: ulist
4801
4802                -  Alcohol cannot be sold before 11:30am.
4803
4804 Create the an new empty Policy Model ``MyFirstPolicyModel``
4805 ###########################################################
4806
4807             .. container:: paragraph
4808
4809                Since an organisation like *HyperM* may have many
4810                policies covering many different domains, policies should
4811                be grouped into policy sets. In order to edit or deploy a
4812                policy, or policy set, the definition of the policy(ies)
4813                and all required events, tasks, states, etc., are grouped
4814                together into a 'Policy Model'. An organization might
4815                define many Policy Models, each containing a different
4816                set of policies.
4817
4818             .. container:: paragraph
4819
4820                So the first step is to create a new empty Policy Model
4821                called ``MyFirstPolicyModel``. Using the APEX Policy
4822                Editor, click on the 'File' menus and select 'New'. Then
4823                define our new policy model called
4824                ``MyFirstPolicyModel``. Use the 'Generate UUID' button to
4825                create a new unique ID for the policy model, and fill in
4826                a description for the policy model. Press the ``Submit``
4827                button to save your changes.
4828
4829             .. container:: imageblock
4830
4831                .. container:: content
4832
4833                   |File > New to create a new Policy Model|
4834
4835                .. container:: title
4836
4837                   Figure 4. Create a new Policy Model 1/2
4838
4839             .. container:: imageblock
4840
4841                .. container:: content
4842
4843                   |Create a new Policy Model|
4844
4845                .. container:: title
4846
4847                   Figure 5. Create a new Policy Model 2/2
4848
4849 Create the input event ``SALE_INPUT`` and the output event ``SALE_AUTH``
4850 ########################################################################
4851
4852             .. container:: paragraph
4853
4854                Using the APEX Policy Editor, click on the 'Events' tab.
4855                In the 'Events' pane, right click and select 'New':
4856
4857             .. container:: imageblock
4858
4859                .. container:: content
4860
4861                   |Right click to create a new event|
4862
4863                .. container:: title
4864
4865                   Figure 6. Create a new Event type
4866
4867             .. container:: paragraph
4868
4869                Create a new event type called ``SALE_INPUT``. Use the
4870                'Generate UUID' button to create a new unique ID for the
4871                event type, and fill in a description for the event. Add
4872                a namespace, e.g. ``com.hyperm``. We can add hard-coded
4873                strings for the ``Source`` and ``Target``, e.g. ``POS``
4874                and ``APEX``. At this stage we will not add any parameter
4875                fields, we will leave this until later. Use the
4876                ``Submit`` button to create the event.
4877
4878             .. container:: imageblock
4879
4880                .. container:: content
4881
4882                   |Fill in the necessary information for the
4883                   'SALE_INPUT' event and click 'Submit'|
4884
4885                .. container:: title
4886
4887                   Figure 7. Populate the ``SALE_INPUT`` event
4888
4889             .. container:: paragraph
4890
4891                Repeat the same steps for a new event type called
4892                ``SALE_AUTH``. Just use ``APEX`` as source and ``POS`` as
4893                target, since this is the output event coming from APEX
4894                going to the sales point.
4895
4896             .. container:: paragraph
4897
4898                Before we can add parameter fields to an event we must
4899                first define APEX Context Item Schemas that can be used
4900                by those fields.
4901
4902             .. container:: paragraph
4903
4904                To create new item schemas, click on the 'Context Item
4905                Schemas' tab. In that 'Context Item Schemas' pane, right
4906                click and select 'Create new ContextSchema'.
4907
4908             .. container:: imageblock
4909
4910                .. container:: content
4911
4912                   |Right click to create a new Item Schema|
4913
4914                .. container:: title
4915
4916                   Figure 8. Create new Data Types
4917
4918             .. container:: paragraph
4919
4920                Create item schemas with the following characteristics,
4921                each with its own unique UUID:
4922
4923             .. table:: Table 6. Item Schemas
4924
4925                +-------------------+-----------------+-----------------+----------------------+
4926                | Name              | Schema Flavour  | Schema          | Description          |
4927                |                   |                 | Definition      |                      |
4928                +===================+=================+=================+======================+
4929                | timestamp_type    | Java            | java.lang.Long  | A type for           |
4930                |                   |                 |                 | ``time`` values      |
4931                +-------------------+-----------------+-----------------+----------------------+
4932                | sale_ID_type      | Java            | java.lang.Long  | A type for           |
4933                |                   |                 |                 | ``sale_ID``          |
4934                |                   |                 |                 | values               |
4935                +-------------------+-----------------+-----------------+----------------------+
4936                | price_type        | Java            | java.lang.Long  | A type for           |
4937                |                   |                 |                 | ``amount``/``price`` |
4938                |                   |                 |                 | values               |
4939                +-------------------+-----------------+-----------------+----------------------+
4940                | item_ID_type      | Java            | java.lang.Long  | A type for           |
4941                |                   |                 |                 | ``item_ID``          |
4942                |                   |                 |                 | values               |
4943                +-------------------+-----------------+-----------------+----------------------+
4944                | assistant_ID_type | Java            | java.lang.Long  | A type for           |
4945                |                   |                 |                 | ``assistant_ID``     |
4946                |                   |                 |                 | values               |
4947                +-------------------+-----------------+-----------------+----------------------+
4948                | quantity_type     | Java            | java.lang.Integ | A type for           |
4949                |                   |                 | er              | ``quantity``         |
4950                |                   |                 |                 | values               |
4951                +-------------------+-----------------+-----------------+----------------------+
4952                | branch_ID_type    | Java            | java.lang.Long  | A type for           |
4953                |                   |                 |                 | ``branch_ID``        |
4954                |                   |                 |                 | values               |
4955                +-------------------+-----------------+-----------------+----------------------+
4956                | notes_type        | Java            | java.lang.Strin | A type for           |
4957                |                   |                 | g               | ``notes``            |
4958                |                   |                 |                 | values               |
4959                +-------------------+-----------------+-----------------+----------------------+
4960                | authorised_type   | Java            | java.lang.Boole | A type for           |
4961                |                   |                 | an              | ``authorised``       |
4962                |                   |                 |                 | values               |
4963                +-------------------+-----------------+-----------------+----------------------+
4964                | message_type      | Java            | java.lang.Strin | A type for           |
4965                |                   |                 | g               | ``message``          |
4966                |                   |                 |                 | values               |
4967                +-------------------+-----------------+-----------------+----------------------+
4968
4969             .. container:: imageblock
4970
4971                .. container:: content
4972
4973                   |Create a new Item Schema|
4974
4975                .. container:: title
4976
4977                   Figure 9. Create new Item Schemas
4978
4979             .. container:: paragraph
4980
4981                The item schemas can now be seen on the 'Context Item
4982                Schemas' tab, and can be updated at any time by
4983                right-clicking on the item schemas on the 'Context Item
4984                Schemas' tab. Now we can go back to the event definitions
4985                for ``SALE_INPUT`` and ``SALE_AUTH`` and add some
4986                parameter fields.
4987
4988             .. tip
4989
4990                .. container:: title
4991
4992                   Field Schema types       
4993
4994                .. container:: paragraph
4995
4996                   APEX natively supports schema definitions in ``Java`` and ``Avro``.
4997                                                                             
4998                .. container:: paragraph
4999
5000                   ``Java`` schema definitions are simply the name of a Java Class. There are some restrictions:
5001
5002                .. container:: ulist
5003
5004                   -  the class must be instantiatable, i.e. not an Java interface or abstract class
5005
5006                   -  primitive types are not supported, i.e. use ``java.lang.Integer`` instead of ``int``, etc.
5007
5008                   -  it must be possible to find the class, i.e. the class must be contained in the Java classpath.
5009
5010                .. container:: paragraph
5011
5012                   ``Avro`` schema definitions can be any valid `Avro <https://avro.apache.org/docs/current/spec.html>`__
5013                   schema. For events using fields defined with ``Avro`` schemas, any incoming event containing that field must
5014                   contain a value that conforms to the Avro schema.
5015
5016             .. container:: paragraph
5017
5018                Click on the 'Events' tab, then right click the
5019                ``SALE_INPUT`` row and select 'Edit Event
5020                :literal:`SALE_INPUT’. To add a new event parameter use the 'Add Event Parameter' button at the bottom of the screen. For the `SALE_INPUT`
5021                event add the following event parameters:
5022
5023             .. table:: Table 7. Event Parameter Fields for the ``SALE_INPUT`` Event
5024
5025                +----------------------+----------------------+-----------------------+
5026                | Parameter Name       | Parameter Type       | Optional              |
5027                +======================+======================+=======================+
5028                | time                 | timestamp_type       | no                    |
5029                +----------------------+----------------------+-----------------------+
5030                | sale_ID              | sale_ID_type         | no                    |
5031                +----------------------+----------------------+-----------------------+
5032                | amount               | price_type           | no                    |
5033                +----------------------+----------------------+-----------------------+
5034                | item_ID              | item_ID_type         | no                    |
5035                +----------------------+----------------------+-----------------------+
5036                | quantity             | quantity_type        | no                    |
5037                +----------------------+----------------------+-----------------------+
5038                | assistant_ID         | assistant_ID_type    | no                    |
5039                +----------------------+----------------------+-----------------------+
5040                | branch_ID            | branch_ID_type       | no                    |
5041                +----------------------+----------------------+-----------------------+
5042                | notes                | notes_type           | *yes*                 |
5043                +----------------------+----------------------+-----------------------+
5044
5045             .. container:: paragraph
5046
5047                Remember to click the 'Submit' button at the bottom of
5048                the event definition pane.
5049
5050             .. tip::
5051                Optional Fields in APEX Events
5052                Parameter fields can be *optional* in events. If a parameter is not marked as *optional* then by default it
5053                is *mandatory*, so it must appear in any input event passed to APEX. If an *optional* field is not set
5054                for an output event then value will be set to ``null``.
5055
5056             .. container:: imageblock
5057
5058                .. container:: content
5059
5060                   |Add new event parameters to an event|
5061
5062                .. container:: title
5063
5064                   Figure 10. Add typed parameter fields to an event
5065
5066             .. container:: paragraph
5067
5068                Select the ``SALE_AUTH`` event and add the following
5069                event parameters:
5070
5071             .. table:: Table 8. Event Parameter Fields for the ``SALE_AUTH`` Event
5072
5073                +----------------------+----------------------+-----------------------+
5074                | Parameter Name       | Parameter Type       | no                    |
5075                +======================+======================+=======================+
5076                | sale_ID              | sale_ID_type         | no                    |
5077                +----------------------+----------------------+-----------------------+
5078                | time                 | timestamp_type       | no                    |
5079                +----------------------+----------------------+-----------------------+
5080                | authorised           | authorised_type      | no                    |
5081                +----------------------+----------------------+-----------------------+
5082                | message              | message_type         | *yes*                 |
5083                +----------------------+----------------------+-----------------------+
5084                | amount               | price_type           | no                    |
5085                +----------------------+----------------------+-----------------------+
5086                | item_ID              | item_ID_type         | no                    |
5087                +----------------------+----------------------+-----------------------+
5088                | assistant_ID         | assistant_ID_type    | no                    |
5089                +----------------------+----------------------+-----------------------+
5090                | quantity             | quantity_type        | no                    |
5091                +----------------------+----------------------+-----------------------+
5092                | branch_ID            | branch_ID_type       | no                    |
5093                +----------------------+----------------------+-----------------------+
5094                | notes                | notes_type           | *yes*                 |
5095                +----------------------+----------------------+-----------------------+
5096
5097             .. container:: paragraph
5098
5099                Remember to click the 'Submit' button at the bottom of
5100                the event definition pane.
5101
5102             .. container:: paragraph
5103
5104                The events for our policy are now defined.
5105
5106 Create a new Policy and add the *"No Booze before 11:30"* check
5107 ###############################################################
5108
5109             .. container:: paragraph
5110
5111                APEX policies are defined using a state-machine model.
5112                Each policy comprises one or more *states* that can be
5113                individually executed. Where there is more than one
5114                *state* the states are chained together to form a
5115                `Directed Acyclic Graph
5116                (DAG) <https://en.wikipedia.org/wiki/Directed_acyclic_graph>`__
5117                of states. A *state* is triggered by passing it a single
5118                input (or 'trigger') event and once executed each state
5119                then emits an output event. For each *state* the logic
5120                for the *state* is embedded in one or more *tasks*. Each
5121                *task* contains specific *task logic* that is executed by
5122                the APEX execution environment each time the *task* is
5123                invoked. Where there is more than one *task* in a *state*
5124                then the *state* also defines some *task selection logic*
5125                to select an appropriate task each time the *state* is
5126                executed.
5127
5128             .. container:: paragraph
5129
5130                Therefore, to create a new policy we must first define
5131                one or more tasks.
5132
5133             .. container:: paragraph
5134
5135                To create a new Task click on the 'Tasks' tab. In the
5136                'Tasks' pane, right click and select 'Create new Task'.
5137                Create a new Task called ``MorningBoozeCheck``. Use the
5138                'Generate UUID' button to create a new unique ID for the
5139                task, and fill in a description for the task.
5140
5141             .. container:: imageblock
5142
5143                .. container:: content
5144
5145                   |Right click to create a new task|
5146
5147                .. container:: title
5148
5149                   Figure 11. Create a new Task
5150
5151             .. container:: paragraph
5152
5153                Tasks are configured with a set of *input fields* and a
5154                set of *output fields*. To add new input/output fields
5155                for a task use the 'Add Task Input Field' and 'Add Task
5156                Output Field' button. The list of input and out fields to
5157                add for the ``MorningBoozeCheck`` task are given below.
5158                The input fields are drawn from the parameters in the
5159                state’s input event, and the task’s output fields are
5160                used to populate the state’s output event. The task’s
5161                input and output fields must be a subset of the event
5162                parameters defined for the input and output events for
5163                any state that uses that task. (You may have noticed that
5164                the input and output fields for the ``MorningBoozeCheck``
5165                task have the exact same names and reuse the item schemas
5166                that we used for the parameters in the ``SALE_INPUT`` and
5167                ``SALE_AUTH`` events respectively).
5168
5169             .. table:: Table 9. Input fields for ``MorningBoozeCheck`` task
5170
5171                +-----------------------------------+-----------------------------------+
5172                | Parameter Name                    | Parameter Type                    |
5173                +===================================+===================================+
5174                | time                              | timestamp_type                    |
5175                +-----------------------------------+-----------------------------------+
5176                | sale_ID                           | sale_ID_type                      |
5177                +-----------------------------------+-----------------------------------+
5178                | amount                            | price_type                        |
5179                +-----------------------------------+-----------------------------------+
5180                | item_ID                           | item_ID_type                      |
5181                +-----------------------------------+-----------------------------------+
5182                | quantity                          | quantity_type                     |
5183                +-----------------------------------+-----------------------------------+
5184                | assistant_ID                      | assistant_ID_type                 |
5185                +-----------------------------------+-----------------------------------+
5186                | branch_ID                         | branch_ID_type                    |
5187                +-----------------------------------+-----------------------------------+
5188                | notes                             | notes_type                        |
5189                +-----------------------------------+-----------------------------------+
5190
5191             .. table:: Table 10. Output fields for ``MorningBoozeCheck`` task
5192
5193                +-----------------------------------+-----------------------------------+
5194                | Parameter Name                    | Parameter Type                    |
5195                +===================================+===================================+
5196                | sale_ID                           | sale_ID_type                      |
5197                +-----------------------------------+-----------------------------------+
5198                | time                              | timestamp_type                    |
5199                +-----------------------------------+-----------------------------------+
5200                | authorised                        | authorised_type                   |
5201                +-----------------------------------+-----------------------------------+
5202                | message                           | message_type                      |
5203                +-----------------------------------+-----------------------------------+
5204                | amount                            | price_type                        |
5205                +-----------------------------------+-----------------------------------+
5206                | item_ID                           | item_ID_type                      |
5207                +-----------------------------------+-----------------------------------+
5208                | assistant_ID                      | assistant_ID_type                 |
5209                +-----------------------------------+-----------------------------------+
5210                | quantity                          | quantity_type                     |
5211                +-----------------------------------+-----------------------------------+
5212                | branch_ID                         | branch_ID_type                    |
5213                +-----------------------------------+-----------------------------------+
5214                | notes                             | notes_type                        |
5215                +-----------------------------------+-----------------------------------+
5216
5217             .. container:: imageblock
5218
5219                .. container:: content
5220
5221                   |Add input and out fields for the task|
5222
5223                .. container:: title
5224
5225                   Figure 12. Add input and out fields for the Task
5226
5227             .. container:: paragraph
5228
5229                Each task must include some 'Task Logic' that implements
5230                the behaviour for the task. Task logic can be defined in
5231                a number of different ways using a choice of languages.
5232                For this task we will author the logic using the
5233                Java-like scripting language called
5234                ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__.
5235
5236             .. container:: paragraph
5237
5238                For simplicity use the following code for the task logic.
5239                Paste the script text into the 'Task Logic' box, and use
5240                "MVEL" as the 'Task Logic Type / Flavour'.
5241
5242             .. container:: paragraph
5243
5244                This logic assumes that all items with ``item_ID``
5245                between 1000 and 2000 contain alcohol, which is not very
5246                realistic, but we will see a better approach for this
5247                later. It also uses the standard ``Java`` time utilities
5248                to check if the current time is between ``00:00:00 GMT``
5249                and ``11:30:00 GMT``. For a detailed guide to how to
5250                write your own logic in
5251                ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__,
5252                ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__ or one
5253                of the other supported languages please refer to APEX
5254                Programmers Guide.
5255
5256             .. container:: listingblock
5257
5258                .. container:: title
5259
5260                   MVEL code for the ``MorningBoozeCheck`` task
5261
5262                .. container:: content
5263
5264                   .. code::
5265
5266                      /*
5267                       * ============LICENSE_START=======================================================
5268                       *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
5269                       * ================================================================================
5270                       * Licensed under the Apache License, Version 2.0 (the "License");
5271                       * you may not use this file except in compliance with the License.
5272                       * You may obtain a copy of the License at
5273                       *
5274                       *      http://www.apache.org/licenses/LICENSE-2.0
5275                       *
5276                       * Unless required by applicable law or agreed to in writing, software
5277                       * distributed under the License is distributed on an "AS IS" BASIS,
5278                       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5279                       * See the License for the specific language governing permissions and
5280                       * limitations under the License.
5281                       *
5282                       * SPDX-License-Identifier: Apache-2.0
5283                       * ============LICENSE_END=========================================================
5284                       */
5285                      import java.util.Date;
5286                      import java.util.Calendar;
5287                      import java.util.TimeZone;
5288                      import java.text.SimpleDateFormat;
5289
5290                      logger.info("Task Execution: '"+subject.id+"'. Input Fields: '"+inFields+"'");
5291
5292                      outFields.put("amount"      , inFields.get("amount"));
5293                      outFields.put("assistant_ID", inFields.get("assistant_ID"));
5294                      outFields.put("notes"       , inFields.get("notes"));
5295                      outFields.put("quantity"    , inFields.get("quantity"));
5296                      outFields.put("branch_ID"   , inFields.get("branch_ID"));
5297                      outFields.put("item_ID"     , inFields.get("item_ID"));
5298                      outFields.put("time"        , inFields.get("time"));
5299                      outFields.put("sale_ID"     , inFields.get("sale_ID"));
5300
5301                      item_id = inFields.get("item_ID");
5302
5303                      //The events used later to test this task use GMT timezone!
5304                      gmt = TimeZone.getTimeZone("GMT");
5305                      timenow = Calendar.getInstance(gmt);
5306                      df = new SimpleDateFormat("HH:mm:ss z");
5307                      df.setTimeZone(gmt);
5308                      timenow.setTimeInMillis(inFields.get("time"));
5309
5310                      midnight = timenow.clone();
5311                      midnight.set(
5312                          timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
5313                          timenow.get(Calendar.DATE),0,0,0);
5314                      eleven30 = timenow.clone();
5315                      eleven30.set(
5316                          timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
5317                          timenow.get(Calendar.DATE),11,30,0);
5318
5319                      itemisalcohol = false;
5320                      if(item_id != null && item_id >=1000 && item_id < 2000)
5321                          itemisalcohol = true;
5322
5323                      if( itemisalcohol
5324                          && timenow.after(midnight) && timenow.before(eleven30)){
5325                        outFields.put("authorised", false);
5326                        outFields.put("message", "Sale not authorised by policy task "+subject.taskName+
5327                          " for time "+df.format(timenow.getTime())+
5328                          ". Alcohol can not be sold between "+df.format(midnight.getTime())+
5329                          " and "+df.format(eleven30.getTime()));
5330                        return true;
5331                      }
5332                      else{
5333                        outFields.put("authorised", true);
5334                        outFields.put("message", "Sale authorised by policy task "+subject.taskName+
5335                          " for time "+df.format(timenow.getTime()));
5336                        return true;
5337                      }
5338
5339                      /*
5340                      This task checks if a sale request is for an item that is an alcoholic drink.
5341                      If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
5342                      authorised. Otherwise the sale is authorised.
5343                      In this implementation we assume that items with item_ID value between 1000 and
5344                      2000 are all alcoholic drinks :-)
5345                      */
5346
5347             .. container:: imageblock
5348
5349                .. container:: content
5350
5351                   |Add task logic the task|
5352
5353                .. container:: title
5354
5355                   Figure 13. Add Task Logic the Task
5356
5357             .. container:: paragraph
5358
5359                An alternative version of the same logic is available in
5360                JavaScript. Just use "JAVASCRIPT" as the 'Task Logic Type
5361                / Flavour' instead.
5362
5363             .. container:: listingblock
5364
5365                .. container:: title
5366
5367                   Javascript alternative for the ``MorningBoozeCheck``
5368                   task
5369
5370                .. container:: content
5371
5372                   .. code::
5373
5374                      /*
5375                       * ============LICENSE_START=======================================================
5376                       *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
5377                       * ================================================================================
5378                       * Licensed under the Apache License, Version 2.0 (the "License");
5379                       * you may not use this file except in compliance with the License.
5380                       * You may obtain a copy of the License at
5381                       *
5382                       *      http://www.apache.org/licenses/LICENSE-2.0
5383                       *
5384                       * Unless required by applicable law or agreed to in writing, software
5385                       * distributed under the License is distributed on an "AS IS" BASIS,
5386                       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5387                       * See the License for the specific language governing permissions and
5388                       * limitations under the License.
5389                       *
5390                       * SPDX-License-Identifier: Apache-2.0
5391                       * ============LICENSE_END=========================================================
5392                       */
5393
5394                      var returnValueType = Java.type("java.lang.Boolean");
5395                      var returnValue = new returnValueType(true);
5396
5397                      // Load compatibility script for imports etc
5398                      load("nashorn:mozilla_compat.js");
5399                      importPackage(java.text);
5400                      importClass(java.text.SimpleDateFormat);
5401
5402                      executor.logger.info("Task Execution: '"+executor.subject.id+"'. Input Fields: '"+executor.inFields+"'");
5403
5404                      executor.outFields.put("amount"      , executor.inFields.get("amount"));
5405                      executor.outFields.put("assistant_ID", executor.inFields.get("assistant_ID"));
5406                      executor.outFields.put("notes"       , executor.inFields.get("notes"));
5407                      executor.outFields.put("quantity"    , executor.inFields.get("quantity"));
5408                      executor.outFields.put("branch_ID"   , executor.inFields.get("branch_ID"));
5409                      executor.outFields.put("item_ID"     , executor.inFields.get("item_ID"));
5410                      executor.outFields.put("time"        , executor.inFields.get("time"));
5411                      executor.outFields.put("sale_ID"     , executor.inFields.get("sale_ID"));
5412
5413                      item_id = executor.inFields.get("item_ID");
5414
5415                      //All times in this script are in GMT/UTC since the policy and events assume time is in GMT.
5416                      var timenow_gmt =  new Date(Number(executor.inFields.get("time")));
5417
5418                      var midnight_gmt = new Date(Number(executor.inFields.get("time")));
5419                      midnight_gmt.setUTCHours(0,0,0,0);
5420
5421                      var eleven30_gmt = new Date(Number(executor.inFields.get("time")));
5422                      eleven30_gmt.setUTCHours(11,30,0,0);
5423
5424                      var timeformatter = new java.text.SimpleDateFormat("HH:mm:ss z");
5425
5426                      var itemisalcohol = false;
5427                      if(item_id != null && item_id >=1000 && item_id < 2000)
5428                          itemisalcohol = true;
5429
5430                      if( itemisalcohol
5431                          && timenow_gmt.getTime() >= midnight_gmt.getTime()
5432                          && timenow_gmt.getTime() <  eleven30_gmt.getTime()) {
5433
5434                        executor.outFields.put("authorised", false);
5435                        executor.outFields.put("message", "Sale not authorised by policy task " +
5436                          executor.subject.taskName+ " for time " + timeformatter.format(timenow_gmt.getTime()) +
5437                          ". Alcohol can not be sold between " + timeformatter.format(midnight_gmt.getTime()) +
5438                          " and " + timeformatter.format(eleven30_gmt.getTime()));
5439                      }
5440                      else{
5441                        executor.outFields.put("authorised", true);
5442                        executor.outFields.put("message", "Sale authorised by policy task " +
5443                          executor.subject.taskName + " for time "+timeformatter.format(timenow_gmt.getTime()));
5444                      }
5445
5446                      /*
5447                      This task checks if a sale request is for an item that is an alcoholic drink.
5448                      If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
5449                      authorised. Otherwise the sale is authorised.
5450                      In this implementation we assume that items with item_ID value between 1000 and
5451                      2000 are all alcoholic drinks :-)
5452                      */
5453
5454             .. container:: paragraph
5455
5456                The task definition is now complete so click the 'Submit'
5457                button to save the task. The task can now be seen on the
5458                'Tasks' tab, and can be updated at any time by
5459                right-clicking on the task on the 'Task' tab. Now that we
5460                have created our task, we can can create a policy that
5461                uses that task.
5462
5463             .. container:: paragraph
5464
5465                To create a new Policy click on the 'Policies' tab. In
5466                the 'Policies' pane, right click and select 'Create new
5467                Policy':
5468
5469             .. container:: paragraph
5470
5471                Create a new Policy called ``MyFirstPolicy``. Use the
5472                'Generate UUID' button to create a new unique ID for the
5473                policy, and fill in a description for the policy. Use
5474                'FREEFORM' as the 'Policy Flavour'.
5475
5476             .. container:: paragraph
5477
5478                Each policy must have at least one state. Since this is
5479                'freeform' policy we can add as many states as we wish.
5480                Let’s start with one state. Add a new state called
5481                ``BoozeAuthDecide`` to this ``MyFirstPolicy`` policy
5482                using the 'Add new State' button after filling in the
5483                name of our new state.
5484
5485             .. container:: imageblock
5486
5487                .. container:: content
5488
5489                   |Create a new policy|
5490
5491                .. container:: title
5492
5493                   Figure 14. Create a new Policy
5494
5495             .. container:: paragraph
5496
5497                Each state must uses one input event type. For this new
5498                state select the ``SALE_INPUT`` event as the input event.
5499
5500             .. container:: paragraph
5501
5502                Each policy must define a 'First State' and a 'Policy
5503                Trigger Event'. The 'Policy Trigger Event' is the input
5504                event for the policy as a whole. This event is then
5505                passed to the first state in the chain of states in the
5506                policy, therefore the 'Policy Trigger Event' will be the
5507                input event for the first state. Each policy can only
5508                have one 'First State'. For our ``MyFirstPolicy`` policy,
5509                select ``BoozeAuthDecide`` as the 'First State'. This
5510                will automatically select ``SALE_INPUT`` as the 'Policy
5511                Trigger Event' for our policy.
5512
5513             .. container:: imageblock
5514
5515                .. container:: content
5516
5517                   |Create a state|
5518
5519                .. container:: title
5520
5521                   Figure 15. Create a new State
5522
5523             .. container:: paragraph
5524
5525                In this case we will create a reference the pre-existing
5526                ``MorningBoozeCheck`` task that we defined above using
5527                the 'Add New Task' button. Select the
5528                ``MorningBoozeCheck`` task, and use the name of the task
5529                as the 'Local Name' for the task.
5530
5531             .. container:: paragraph
5532
5533                in the case where a state references more than one task,
5534                a 'Default Task' must be selected for the state and some
5535                logic ('Task Selection Logic') must be specified to
5536                select the appropriate task at execution time. Since our
5537                new state ``BoozeAuthDecide`` only has one task the
5538                default task is automatically selected and no 'Task
5539                Selection Logic' is required.
5540
5541             .. note::
5542                .. container:: title
5543
5544                   State Output Mappings
5545
5546                .. container:: paragraph
5547
5548                   In a 'Policy' 'State' a 'State Output Mapping' has 3 roles:
5549                   1) Select which 'State' should be executed next, 2) Select
5550                   the type of the state’s 'Outgoing Event', and 3)
5551                   Populate the state’s 'Outgoing Event'. This is how states are
5552                   chained together to form a (`Directed Acyclic Graph
5553                   (DAG) <https://en.wikipedia.org/wiki/Directed_acyclic_graph>`__ )
5554                   of states. The final state(s) of a policy are those that do
5555                   not select any 'next' state. Since a 'State' can only
5556                   accept a single type of event, the type of the event emitted
5557                   by a previous 'State' must be match the incoming event type
5558                   of the next 'State'. This is also how the last state(s) in
5559                   a policy can emit events of different types. The 'State
5560                   Output Mapping' is also responsible for taking the
5561                   fields that are output by the task executed in the state and
5562                   populating the state’s output event before it is emitted.
5563
5564                .. container:: paragraph
5565
5566                   Each 'Task' referenced in 'State' must have a defined
5567                   'Output Mapping' to take the output of the task, select an
5568                   'Outgoing Event' type for the state, populate the state’s
5569                   outgoing event, and then select the next state to be
5570                   executed (if any).
5571
5572                .. container:: paragraph
5573
5574                There are 2 basic types of output mappings:
5575
5576                .. container:: olist arabic
5577
5578                #. **Direct Output Mappings** have a single value for
5579                   'Next State' and a single value for 'State Output
5580                   Event'. The outgoing event for the state is
5581                   automatically created, any outgoing event parameters
5582                   that were present in the incoming event are copied
5583                   into the outgoing event, then any task output fields
5584                   that have the same name and type as parameters in the
5585                   outgoing event are automatically copied into
5586                   the outgoing event.
5587
5588                #. **Logic-based State Output Mappings / Finalizers**
5589                   have some logic defined that dynamically selects
5590                   and creates the 'State Outgoing Event', manages
5591                   the population of the outgoing event parameters
5592                   (perhaps changing or adding to the outputs from the
5593                   task), and then dynamically selects the next state to
5594                   be executed (if any).
5595
5596             .. container:: paragraph
5597
5598                Each task reference must also have an associated 'Output
5599                State Mapping' so we need an 'Output State Mapping' for
5600                the ``BoozeAuthDecide`` state to use when the
5601                ``MorningBoozeCheck`` task is executed. The simplest type
5602                of output mapping is a 'Direct Output Mapping'.
5603
5604             .. container:: paragraph
5605
5606                Create a new 'Direct Output Mapping' for the state called
5607                ``MorningBoozeCheck_Output_Direct`` using the 'Add New
5608                Direct State Output Mapping' button. Select ``SALE_AUTH``
5609                as the output event and select ``None`` for the next
5610                state value. We can then select this output mapping for
5611                use when the the ``MorningBoozeCheck`` task is executed.
5612                Since there is only state, and only one task for that
5613                state, this output mapping ensures that the
5614                ``BoozeAuthDecide`` state is the only state executed and
5615                the state (and the policy) can only emit events of type
5616                ``SALE_AUTH``. (You may remember that the output fields
5617                for the ``MorningBoozeCheck`` task have the exact same
5618                names and reuse the item schemas that we used for the
5619                parameters in ``SALE_AUTH`` event. The
5620                ``MorningBoozeCheck_Output_Direct`` direct output mapping
5621                can now automatically copy the values from the
5622                ``MorningBoozeCheck`` task directly into outgoing
5623                ``SALE_AUTH`` events.)
5624
5625             .. container:: imageblock
5626
5627                .. container:: content
5628
5629                   |Add a Task and Output Mapping|
5630
5631                .. container:: title
5632
5633                   Figure 16. Add a Task and Output Mapping
5634
5635             .. container:: paragraph
5636
5637                Click the 'Submit' button to complete the definition of
5638                our ``MyFirstPolicy`` policy. The policy
5639                ``MyFirstPolicy`` can now be seen in the list of policies
5640                on the 'Policies' tab, and can be updated at any time by
5641                right-clicking on the policy on the 'Policies' tab.
5642
5643             .. container:: paragraph
5644
5645                The ``MyFirstPolicyModel``, including our
5646                ``MyFirstPolicy`` policy can now be checked for errors.
5647                Click on the 'Model' menu and select 'Validate'. The
5648                model should validate without any 'Warning' or 'Error'
5649                messages. If you see any 'Error' or 'Warning' messages,
5650                carefully read the message as a hint to find where you
5651                might have made a mistake when defining some aspect of
5652                your policy model.
5653
5654             .. container:: imageblock
5655
5656                .. container:: content
5657
5658                   |Validate the policy model for error using the 'Model'
5659                   > 'Validate' menu item|
5660
5661                .. container:: title
5662
5663                   Figure 17. Validate a Policy Model
5664
5665             .. container:: paragraph
5666
5667                Congratulations, you have now completed your first APEX
5668                policy. The policy model containing our new policy can
5669                now be exported from the editor and saved. Click on the
5670                'File' menu and select 'Download' to save the policy
5671                model in JSON format. The exported policy model is then
5672                available in the directory you selected, for instance
5673                ``$APEX_HOME/examples/models/MyFirstPolicy/1/MyFirstPolicyModel_0.0.1.json``.
5674                The exported policy can now be loaded into the APEX
5675                Policy Engine, or can be re-loaded and edited by the APEX
5676                Policy Editor.
5677
5678             .. container:: imageblock
5679
5680                .. container:: content
5681
5682                   |Download the completed policy model using the 'File'
5683                   > 'Download' menu item|
5684
5685                .. container:: title
5686
5687                   Figure 18. Export a Policy Model
5688
5689 Test Policy Step 1
5690 ##################
5691
5692             .. container:: paragraph
5693
5694                To start a new APEX Engine you can use the following
5695                configuration. In a full APEX installation you can find
5696                this configuration in
5697                ``$APEX_HOME/examples/config/MyFirstPolicy/1/MyFirstPolicyConfigStdin2StdoutJsonEvent.json``.
5698                This configuration expects incoming events to be in
5699                ``JSON`` format and to be passed into the APEX Engine
5700                from ``stdin``, and result events will be printed in
5701                ``JSON`` format to ``stdout``. This configuration loads
5702                the policy model stored in the file
5703                'MyFirstPolicyModel_0.0.1.json' as exported from the APEX
5704                Editor. Note, you may need to edit this file to provide
5705                the full path to wherever you stored the exported policy
5706                model file.
5707
5708             .. container:: listingblock
5709
5710                .. container:: title
5711
5712                   JSON to load and execute *My First Policy*, read input
5713                   JSON events from ``stdin``, and emit output events to
5714                   ``stdout``
5715
5716                .. container:: content
5717
5718                   .. code::
5719
5720                      {
5721                          "engineServiceParameters" : {
5722                              "name"                : "MyFirstPolicyApexEngine",
5723                              "version"             : "0.0.1",
5724                              "id"                  : 101,
5725                              "instanceCount"       : 4,
5726                              "deploymentPort"      : 12345,
5727                              "policyModelFileName" : "examples/models/MyFirstPolicy/1/MyFirstPolicyModel_0.0.1.json",
5728                              "engineParameters"    : {
5729                                  "executorParameters" : {
5730                                      "MVEL" : {
5731                                          "parameterClassName" : "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters"
5732                                      },
5733                                      "JAVASCRIPT" : {
5734                                          "parameterClassName" : "org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters"
5735                                      }
5736                                  }
5737                              }
5738                          },
5739                          "eventOutputParameters": {
5740                              "FirstProducer": {
5741                                  "carrierTechnologyParameters" : {
5742                                      "carrierTechnology" : "FILE",
5743                                      "parameters" : {
5744                                          "standardIO" : true
5745                                      }
5746                                  },
5747                                  "eventProtocolParameters" : {
5748                                      "eventProtocol" : "JSON"
5749                                  }
5750                              }
5751                          },
5752                          "eventInputParameters": {
5753                              "FirstConsumer": {
5754                                  "carrierTechnologyParameters" : {
5755                                      "carrierTechnology" : "FILE",
5756                                      "parameters" : {
5757                                          "standardIO" : true
5758                                      }
5759                                  },
5760                                  "eventProtocolParameters" : {
5761                                      "eventProtocol" : "JSON"
5762                                  }
5763                              }
5764                          }
5765                      }
5766
5767             .. container:: paragraph
5768
5769                To test the policy try paste the following events into
5770                the console as the APEX engine executes:
5771
5772             .. table:: Table 11. Inputs and Outputs when testing *My First Policy*
5773
5774                +------------------------------------------+-------------------------------------------+-----------+
5775                | Input Event (JSON)                       | Output Event (JSON)                       | comment   |
5776                +==========================================+===========================================+===========+
5777                | .. container::                           | .. container::                            | Request   |
5778                |                                          |                                           | to buy a  |
5779                |    .. container:: listingblock           |    .. container:: listingblock            | non-alcoh |
5780                |                                          |                                           | olic      |
5781                |                                          |       .. container:: content              | item      |
5782                |       .. container:: content             |                                           | (``item_I |
5783                |                                          |          .. code::                        | D=5123``) |
5784                |                                          |                                           | at        |
5785                |          .. code::                       |             {                             | *10:13:09 |
5786                |                                          |               "name": "SALE_AUTH",        | *         |
5787                |                                          |                                           | on        |
5788                |             {                            |               "version": "0.0.1",         | *Tuesday, |
5789                |               "nameSpace": "com.hyperm", |               "nameSpace": "com.hyperm",  | 10        |
5790                |               "name" : "SALE_INPUT",     |               "source": "",               | January   |
5791                |               "version": "0.0.1",        |               "target": "",               | 2017*.    |
5792                |               "time" : 1483351989000,    |               "amount": 299,              | Sale is   |
5793                |               "sale_ID": 99999991,       |               "assistant_ID": 23,         | authorize |
5794                |               "amount": 299,             |               "authorised": true,         | d.        |
5795                |               "item_ID": 5123,           |               "branch_ID": 1,             |           |
5796                |               "quantity": 1,             |               "item_ID": 5123,            |           |
5797                |               "assistant_ID": 23,        |               "message": "Sale authorised |           |
5798                |               "branch_ID": 1,            |                by policy task MorningBo   |           |
5799                |               "notes": "Special Offer!!" |                ozeCheck for time 10:13:09 |           |
5800                |              }                           |                GMT",                      |           |
5801                |                                          |               "notes": "Special Offer!!", |           |
5802                |                                          |               "quantity": 1,              |           |
5803                |                                          |               "sale_ID": 99999991,        |           |
5804                |                                          |               "time": 1483351989000       |           |
5805                |                                          |             }                             |           |
5806                |                                          |                                           |           |
5807                |                                          |                                           |           |
5808                |                                          |                                           |           |
5809                +------------------------------------------+-------------------------------------------+-----------+
5810                | .. container::                           | .. container::                            | Request   |
5811                |                                          |                                           | to buy    |
5812                |    .. container:: listingblock           |    .. container:: listingblock            | alcohol   |
5813                |                                          |                                           | item      |
5814                |       .. container:: content             |       .. container:: content              | (``item_I |
5815                |                                          |                                           | D=1249``) |
5816                |          .. code::                       |          .. code::                        | at        |
5817                |                                          |                                           | *08:41:06 |
5818                |             {                            |             {                             | *         |
5819                |               "nameSpace": "com.hyperm", |               "nameSpace": "com.hyperm",  | on        |
5820                |               "name": "SALE_INPUT",      |               "name": "SALE_AUTH",        | *Monday,  |
5821                |               "version": "0.0.1",        |               "source": "",               | 02        |
5822                |                "time": 1483346466000,    |               "target": "",               | January   |
5823                |               "sale_ID": 99999992,       |               "amount": 1249,             | 2017*.    |
5824                |               "version": "0.0.1",        |               "assistant_ID": 12,         |           |
5825                |               "amount": 1249,            |               "authorised": false,        | Sale is   |
5826                |               "item_ID": 1012,           |               "branch_ID": 2,             | not       |
5827                |               "quantity": 1,             |               "item_ID": 1012,            | authorize |
5828                |               "assistant_ID": 12,        |               "message": "Sale not        | d.        |
5829                |               "branch_ID": 2             |                authorised by policy task  |           |
5830                |             }                            |                MorningBoozeCheck for time |           |
5831                |                                          |                08:41:06 GMT. Alcohol can  |           |
5832                |                                          |                not be sold between        |           |
5833                |                                          |                00:00:00 GMT and 11:30:00  |           |
5834                |                                          |                GMT",                      |           |
5835                |                                          |               "notes": null,              |           |
5836                |                                          |               "quantity": 1,              |           |
5837                |                                          |               "sale_ID": 99999992,        |           |
5838                |                                          |               "time": 1483346466000       |           |
5839                |                                          |             }                             |           |
5840                +------------------------------------------+-------------------------------------------+-----------+
5841                | .. container::                           | .. container::                            | Request   |
5842                |                                          |                                           | to buy    |
5843                |    .. container:: listingblock           |    .. container:: listingblock            | alcohol   |
5844                |                                          |                                           | (``item_I |
5845                |                                          |       .. container:: content              | D=1943``) |
5846                |       .. container:: content             |                                           | at        |
5847                |                                          |          .. code::                        | *20:17:13 |
5848                |                                          |                                           | *         |
5849                |          .. code::                       |             {                             | on        |
5850                |                                          |               "name": "SALE_AUTH",        | *Tuesday, |
5851                |             {                            |               "version": "0.0.1",         | 20        |
5852                |               "nameSpace": "com.hyperm", |               "nameSpace": "com.hyperm",  | December  |
5853                |               "name" : "SALE_INPUT",     |               "source": "",               | 2016*.    |
5854                |               "version": "0.0.1",        |               "target": "",               |           |
5855                |               "time" : 1482265033000,    |               "amount": 4799,             | Sale is   |
5856                |               "sale_ID": 99999993,       |               "assistant_ID": 9,          | authorize |
5857                |               "amount": 4799,            |               "authorised": true,         | d.        |
5858                |               "item_ID": 1943,           |               "branch_ID": 3,             |           |
5859                |               "quantity": 2,             |               "item_ID": 1943,            |           |
5860                |               "assistant_ID": 9,         |               "message": "Sale authorised |           |
5861                |               "branch_ID": 3             |                by policy task MorningBo   |           |
5862                |             }                            |                ozeCheck for time 20:17:13 |           |
5863                |                                          |                GMT",                      |           |
5864                |                                          |                "notes": null,             |           |
5865                |                                          |                "quantity": 2,             |           |
5866                |                                          |                "sale_ID": 99999993,       |           |
5867                |                                          |                "time": 1482265033000      |           |
5868                |                                          |             }                             |           |
5869                +------------------------------------------+-------------------------------------------+-----------+
5870
5871 4.3.6. Policy 1 in CLI Editor
5872 #############################
5873
5874             .. container:: paragraph
5875
5876                An equivalent version of the ``MyFirstPolicyModel``
5877                policy model can again be generated using the APEX CLI
5878                editor. A sample APEX CLI script is shown below:
5879
5880             .. container:: listingblock
5881
5882                .. container:: title
5883
5884                   APEX CLI Editor code for Policy 1
5885
5886                .. container:: content
5887
5888                   .. code::
5889
5890                      #-------------------------------------------------------------------------------
5891                      # ============LICENSE_START=======================================================
5892                      #  Copyright (C) 2016-2018 Ericsson. All rights reserved.
5893                      # ================================================================================
5894                      # Licensed under the Apache License, Version 2.0 (the "License");
5895                      # you may not use this file except in compliance with the License.
5896                      # You may obtain a copy of the License at
5897                      #
5898                      #      http://www.apache.org/licenses/LICENSE-2.0
5899                      #
5900                      # Unless required by applicable law or agreed to in writing, software
5901                      # distributed under the License is distributed on an "AS IS" BASIS,
5902                      # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5903                      # See the License for the specific language governing permissions and
5904                      # limitations under the License.
5905                      #
5906                      # SPDX-License-Identifier: Apache-2.0
5907                      # ============LICENSE_END=========================================================
5908                      #-------------------------------------------------------------------------------
5909
5910                      model create name=MyFirstPolicyModel version=0.0.1 uuid=540226fb-55ee-4f0e-a444-983a0494818e description="This is my first Apex Policy Model."
5911
5912                      schema create name=assistant_ID_type version=0.0.1 uuid=36df4c71-9616-4206-8b53-976a5cd4bd87 description="A type for 'assistant_ID' values" flavour=Java schema=java.lang.Long
5913
5914                      schema create name=authorised_type version=0.0.1 uuid=d48b619e-d00d-4008-b884-02d76ea4350b description="A type for 'authorised' values" flavour=Java schema=java.lang.Boolean
5915
5916                      schema create name=branch_ID_type version=0.0.1 uuid=6468845f-4122-4128-8e49-0f52c26078b5 description="A type for 'branch_ID' values" flavour=Java schema=java.lang.Long
5917
5918                      schema create name=item_ID_type version=0.0.1 uuid=4f227ff1-aee0-453a-b6b6-9a4b2e0da932 description="A type for 'item_ID' values" flavour=Java schema=java.lang.Long
5919
5920                      schema create name=message_type version=0.0.1 uuid=ad1431bb-3155-4e73-b5a3-b89bee498749 description="A type for 'message' values" flavour=Java schema=java.lang.String
5921
5922                      schema create name=notes_type version=0.0.1 uuid=eecfde90-896c-4343-8f9c-2603ced94e2d description="A type for 'notes' values" flavour=Java schema=java.lang.String
5923
5924                      schema create name=price_type version=0.0.1 uuid=52c2fc45-fd8c-463c-bd6f-d91b0554aea7 description="A type for 'amount'/'price' values" flavour=Java schema=java.lang.Long
5925
5926                      schema create name=quantity_type version=0.0.1 uuid=ac3d9842-80af-4a98-951c-bd79a431c613 description="A type for 'quantity' values" flavour=Java schema=java.lang.Integer
5927
5928                      schema create name=sale_ID_type version=0.0.1 uuid=cca47d74-7754-4a61-b163-ca31f66b157b description="A type for 'sale_ID' values" flavour=Java schema=java.lang.Long
5929
5930                      schema create name=timestamp_type version=0.0.1 uuid=fd594e88-411d-4a94-b2be-697b3a0d7adf description="A type for 'time' values" flavour=Java schema=java.lang.Long
5931
5932                      task create name=MorningBoozeCheck version=0.0.1 uuid=3351b0f4-cf06-4fa2-8823-edf67bd30223 description=LS
5933                      This task checks if the sales request is for an item that contains alcohol.
5934                      If the local time is between 00:00:00 and 11:30:00 then the sale is not authorised. Otherwise the sale is authorised.
5935                      In this implementation we assume that all items with item_ID values between 1000 and 2000 contain alcohol :-)
5936                      LE
5937                      task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
5938                      task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=amount schemaName=price_type schemaVersion=0.0.1
5939                      task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
5940                      task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
5941                      task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=quantity schemaName=quantity_type schemaVersion=0.0.1
5942                      task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
5943                      task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
5944                      task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=time schemaName=timestamp_type schemaVersion=0.0.1
5945                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
5946                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=amount schemaName=price_type schemaVersion=0.0.1
5947                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
5948                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
5949                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=quantity schemaName=quantity_type schemaVersion=0.0.1
5950                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
5951                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
5952                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=authorised schemaName=authorised_type schemaVersion=0.0.1
5953                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=time schemaName=timestamp_type schemaVersion=0.0.1
5954                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=message schemaName=message_type schemaVersion=0.0.1 optional=true
5955                      task logic create name=MorningBoozeCheck version=0.0.1 logicFlavour=MVEL logic=LS
5956                      /*
5957                       * ============LICENSE_START=======================================================
5958                       *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
5959                       * ================================================================================
5960                       * Licensed under the Apache License, Version 2.0 (the "License");
5961                       * you may not use this file except in compliance with the License.
5962                       * You may obtain a copy of the License at
5963                       *
5964                       *      http://www.apache.org/licenses/LICENSE-2.0
5965                       *
5966                       * Unless required by applicable law or agreed to in writing, software
5967                       * distributed under the License is distributed on an "AS IS" BASIS,
5968                       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5969                       * See the License for the specific language governing permissions and
5970                       * limitations under the License.
5971                       *
5972                       * SPDX-License-Identifier: Apache-2.0
5973                       * ============LICENSE_END=========================================================
5974                       */
5975                      import java.util.Date;
5976                      import java.util.Calendar;
5977                      import java.util.TimeZone;
5978                      import java.text.SimpleDateFormat;
5979
5980                      logger.info("Task Execution: '"+subject.id+"'. Input Fields: '"+inFields+"'");
5981
5982                      outFields.put("amount"      , inFields.get("amount"));
5983                      outFields.put("assistant_ID", inFields.get("assistant_ID"));
5984                      outFields.put("notes"       , inFields.get("notes"));
5985                      outFields.put("quantity"    , inFields.get("quantity"));
5986                      outFields.put("branch_ID"   , inFields.get("branch_ID"));
5987                      outFields.put("item_ID"     , inFields.get("item_ID"));
5988                      outFields.put("time"        , inFields.get("time"));
5989                      outFields.put("sale_ID"     , inFields.get("sale_ID"));
5990
5991                      item_id = inFields.get("item_ID");
5992
5993                      //The events used later to test this task use GMT timezone!
5994                      gmt = TimeZone.getTimeZone("GMT");
5995                      timenow = Calendar.getInstance(gmt);
5996                      df = new SimpleDateFormat("HH:mm:ss z");
5997                      df.setTimeZone(gmt);
5998                      timenow.setTimeInMillis(inFields.get("time"));
5999
6000                      midnight = timenow.clone();
6001                      midnight.set(
6002                          timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
6003                          timenow.get(Calendar.DATE),0,0,0);
6004                      eleven30 = timenow.clone();
6005                      eleven30.set(
6006                          timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
6007                          timenow.get(Calendar.DATE),11,30,0);
6008
6009                      itemisalcohol = false;
6010                      if(item_id != null && item_id >=1000 && item_id < 2000)
6011                          itemisalcohol = true;
6012
6013                      if( itemisalcohol
6014                          && timenow.after(midnight) && timenow.before(eleven30)){
6015                        outFields.put("authorised", false);
6016                        outFields.put("message", "Sale not authorised by policy task "+subject.taskName+
6017                          " for time "+df.format(timenow.getTime())+
6018                          ". Alcohol can not be sold between "+df.format(midnight.getTime())+
6019                          " and "+df.format(eleven30.getTime()));
6020                        return true;
6021                      }
6022                      else{
6023                        outFields.put("authorised", true);
6024                        outFields.put("message", "Sale authorised by policy task "+subject.taskName+
6025                          " for time "+df.format(timenow.getTime()));
6026                        return true;
6027                      }
6028
6029                      /*
6030                      This task checks if a sale request is for an item that is an alcoholic drink.
6031                      If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
6032                      authorised. Otherwise the sale is authorised.
6033                      In this implementation we assume that items with item_ID value between 1000 and
6034                      2000 are all alcoholic drinks :-)
6035                      */
6036                      LE
6037
6038                      event create name=SALE_AUTH version=0.0.1 uuid=c4500941-3f98-4080-a9cc-5b9753ed050b description="An event emitted by the Policy to indicate whether the sale of an item has been authorised" nameSpace=com.hyperm source="APEX" target="POS"
6039                      event parameter create name=SALE_AUTH version=0.0.1 parName=amount schemaName=price_type schemaVersion=0.0.1
6040                      event parameter create name=SALE_AUTH version=0.0.1 parName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
6041                      event parameter create name=SALE_AUTH version=0.0.1 parName=authorised schemaName=authorised_type schemaVersion=0.0.1
6042                      event parameter create name=SALE_AUTH version=0.0.1 parName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
6043                      event parameter create name=SALE_AUTH version=0.0.1 parName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
6044                      event parameter create name=SALE_AUTH version=0.0.1 parName=message schemaName=message_type schemaVersion=0.0.1 optional=true
6045                      event parameter create name=SALE_AUTH version=0.0.1 parName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
6046                      event parameter create name=SALE_AUTH version=0.0.1 parName=quantity schemaName=quantity_type schemaVersion=0.0.1
6047                      event parameter create name=SALE_AUTH version=0.0.1 parName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
6048                      event parameter create name=SALE_AUTH version=0.0.1 parName=time schemaName=timestamp_type schemaVersion=0.0.1
6049
6050                      event create name=SALE_INPUT version=0.0.1 uuid=4f04aa98-e917-4f4a-882a-c75ba5a99374 description="An event raised by the PoS system each time an item is scanned for purchase" nameSpace=com.hyperm source="POS" target="APEX"
6051                      event parameter create name=SALE_INPUT version=0.0.1 parName=amount schemaName=price_type schemaVersion=0.0.1
6052                      event parameter create name=SALE_INPUT version=0.0.1 parName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
6053                      event parameter create name=SALE_INPUT version=0.0.1 parName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
6054                      event parameter create name=SALE_INPUT version=0.0.1 parName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
6055                      event parameter create name=SALE_INPUT version=0.0.1 parName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
6056                      event parameter create name=SALE_INPUT version=0.0.1 parName=quantity schemaName=quantity_type schemaVersion=0.0.1
6057                      event parameter create name=SALE_INPUT version=0.0.1 parName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
6058                      event parameter create name=SALE_INPUT version=0.0.1 parName=time schemaName=timestamp_type schemaVersion=0.0.1
6059
6060
6061                      policy create name=MyFirstPolicy version=0.0.1 uuid=6c5e410f-489a-46ff-964e-982ce6e8b6d0 description="This is my first Apex policy. It checks if a sale should be authorised or not." template=FREEFORM firstState=BoozeAuthDecide
6062                      policy state create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide triggerName=SALE_INPUT triggerVersion=0.0.1 defaultTaskName=MorningBoozeCheck defaultTaskVersion=0.0.1
6063                      policy state output create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide outputName=MorningBoozeCheck_Output_Direct eventName=SALE_AUTH eventVersion=0.0.1 nextState=NULL
6064                      policy state taskref create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide taskLocalName=MorningBoozeCheck taskName=MorningBoozeCheck taskVersion=0.0.1 outputType=DIRECT outputName=MorningBoozeCheck_Output_Direct
6065
6066 Policy Step 2
6067 -------------
6068
6069 Scenario
6070 #########
6071             .. container:: paragraph
6072
6073                *HyperM* have just opened a new branch in a different
6074                country, but that country has different rules about when
6075                alcohol can be sold! In this section we will go through
6076                the necessary steps to extend our policy to enforce this
6077                for *HyperM*.
6078
6079             .. container:: ulist
6080
6081                -  In some branches alcohol cannot be sold before 1pm,
6082                   and not at all on Sundays.
6083
6084             .. container:: paragraph
6085
6086                Although there are a number of ways to accomplish this
6087                the easiest approach for us is to define another task and
6088                then select which task is appropriate at runtime
6089                depending on the branch identifier in the incoming event.
6090
6091 Extend the Policy with the new Scenario
6092 #######################################
6093
6094             .. container:: paragraph
6095
6096                To create a new Task click on the 'Tasks' tab. In the
6097                'Tasks' pane, right click and select 'Create new Task':
6098
6099             .. container:: paragraph
6100
6101                Create a new Task called ``MorningBoozeCheckAlt1``. Use
6102                the 'Generate UUID' button to create a new unique ID for
6103                the task, and fill in a description for the task. Select
6104                the same input and output fields that we used earlier
6105                when we defined the ``MorningBoozeCheck`` task earlier.
6106
6107             .. table:: Table 12. Input fields for ``MorningBoozeCheckAlt1`` task
6108
6109                +-----------------------------------+-----------------------------------+
6110                | Parameter Name                    | Parameter Type                    |
6111                +===================================+===================================+
6112                | time                              | timestamp_type                    |
6113                +-----------------------------------+-----------------------------------+
6114                | sale_ID                           | sale_ID_type                      |
6115                +-----------------------------------+-----------------------------------+
6116                | amount                            | price_type                        |
6117                +-----------------------------------+-----------------------------------+
6118                | item_ID                           | item_ID_type                      |
6119                +-----------------------------------+-----------------------------------+
6120                | quantity                          | quantity_type                     |
6121                +-----------------------------------+-----------------------------------+
6122                | assistant_ID                      | assistant_ID_type                 |
6123                +-----------------------------------+-----------------------------------+
6124                | branch_ID                         | branch_ID_type                    |
6125                +-----------------------------------+-----------------------------------+
6126                | notes                             | notes_type                        |
6127                +-----------------------------------+-----------------------------------+
6128
6129             .. table:: Table 13. Output fields for ``MorningBoozeCheckAlt1`` task
6130
6131                +-----------------------------------+-----------------------------------+
6132                | Parameter Name                    | Parameter Type                    |
6133                +===================================+===================================+
6134                | sale_ID                           | sale_ID_type                      |
6135                +-----------------------------------+-----------------------------------+
6136                | time                              | timestamp_type                    |
6137                +-----------------------------------+-----------------------------------+
6138                | authorised                        | authorised_type                   |
6139                +-----------------------------------+-----------------------------------+
6140                | message                           | message_type                      |
6141                +-----------------------------------+-----------------------------------+
6142                | amount                            | price_type                        |
6143                +-----------------------------------+-----------------------------------+
6144                | item_ID                           | item_ID_type                      |
6145                +-----------------------------------+-----------------------------------+
6146                | assistant_ID                      | assistant_ID_type                 |
6147                +-----------------------------------+-----------------------------------+
6148                | quantity                          | quantity_type                     |
6149                +-----------------------------------+-----------------------------------+
6150                | branch_ID                         | branch_ID_type                    |
6151                +-----------------------------------+-----------------------------------+
6152                | notes                             | notes_type                        |
6153                +-----------------------------------+-----------------------------------+
6154
6155             .. container:: paragraph
6156
6157                This task also requires some 'Task Logic' to implement
6158                the new behaviour for this task.
6159
6160             .. container:: paragraph
6161
6162                For simplicity use the following code for the task logic.
6163                It again assumes that all items with ``item_ID`` between
6164                1000 and 2000 contain alcohol. We again use the standard
6165                ``Java`` time utilities to check if the current time is
6166                between ``00:00:00 CET`` and ``13:00:00 CET`` or if it is
6167                ``Sunday``.
6168
6169             .. container:: paragraph
6170
6171                For this task we will again author the logic using the
6172                ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__
6173                scripting language. Sample task logic code (specified in
6174                ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__) is
6175                given below. For a detailed guide to how to write your
6176                own logic in
6177                ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__,
6178                ```MVEL`` <https://en.wikipedia.org/wiki/MVEL>`__ or one
6179                of the other supported languages please refer to APEX
6180                Programmers Guide.
6181
6182             .. container:: listingblock
6183
6184                .. container:: title
6185
6186                   MVEL code for the ``MorningBoozeCheckAlt1`` task
6187
6188                .. container:: content
6189
6190                   .. code::
6191
6192                      /*
6193                       * ============LICENSE_START=======================================================
6194                       *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
6195                       * ================================================================================
6196                       * Licensed under the Apache License, Version 2.0 (the "License");
6197                       * you may not use this file except in compliance with the License.
6198                       * You may obtain a copy of the License at
6199                       *
6200                       *      http://www.apache.org/licenses/LICENSE-2.0
6201                       *
6202                       * Unless required by applicable law or agreed to in writing, software
6203                       * distributed under the License is distributed on an "AS IS" BASIS,
6204                       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6205                       * See the License for the specific language governing permissions and
6206                       * limitations under the License.
6207                       *
6208                       * SPDX-License-Identifier: Apache-2.0
6209                       * ============LICENSE_END=========================================================
6210                       */
6211                      import java.util.Date;
6212                      import java.util.Calendar;
6213                      import java.util.TimeZone;
6214                      import java.text.SimpleDateFormat;
6215
6216                      logger.info("Task Execution: '"+subject.id+"'. Input Event: '"+inFields+"'");
6217
6218                      outFields.put("amount"      , inFields.get("amount"));
6219                      outFields.put("assistant_ID", inFields.get("assistant_ID"));
6220                      outFields.put("notes"       , inFields.get("notes"));
6221                      outFields.put("quantity"    , inFields.get("quantity"));
6222                      outFields.put("branch_ID"   , inFields.get("branch_ID"));
6223                      outFields.put("item_ID"     , inFields.get("item_ID"));
6224                      outFields.put("time"        , inFields.get("time"));
6225                      outFields.put("sale_ID"     , inFields.get("sale_ID"));
6226
6227                      item_id = inFields.get("item_ID");
6228
6229                      //The events used later to test this task use CET timezone!
6230                      cet = TimeZone.getTimeZone("CET");
6231                      timenow = Calendar.getInstance(cet);
6232                      df = new SimpleDateFormat("HH:mm:ss z");
6233                      df.setTimeZone(cet);
6234                      timenow.setTimeInMillis(inFields.get("time"));
6235
6236                      midnight = timenow.clone();
6237                      midnight.set(
6238                          timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
6239                          timenow.get(Calendar.DATE),0,0,0);
6240                      onepm = timenow.clone();
6241                      onepm.set(
6242                          timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
6243                          timenow.get(Calendar.DATE),13,0,0);
6244
6245                      itemisalcohol = false;
6246                      if(item_id != null && item_id >=1000 && item_id < 2000)
6247                          itemisalcohol = true;
6248
6249                      if( itemisalcohol &&
6250                          ( (timenow.after(midnight) && timenow.before(onepm))
6251                            ||
6252                            (timenow.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
6253                          )){
6254                        outFields.put("authorised", false);
6255                        outFields.put("message", "Sale not authorised by policy task "+subject.taskName+
6256                          " for time "+df.format(timenow.getTime())+
6257                          ". Alcohol can not be sold between "+df.format(midnight.getTime())+
6258                          " and "+df.format(onepm.getTime()) +" or on Sunday");
6259                        return true;
6260                      }
6261                      else{
6262                        outFields.put("authorised", true);
6263                        outFields.put("message", "Sale authorised by policy task "+subject.taskName+
6264                          " for time "+df.format(timenow.getTime()));
6265                        return true;
6266                      }
6267
6268                      /*
6269                      This task checks if a sale request is for an item that is an alcoholic drink.
6270                      If the local time is between 00:00:00 CET and 13:00:00 CET then the sale is not authorised.
6271                      Also alcohol sales are not allowed on Sundays. Otherwise the sale is authorised.
6272                      In this implementation we assume that items with item_ID between 1000 and 2000 are all alcoholic drinks :-)
6273                      */
6274
6275             .. container:: imageblock
6276
6277                .. container:: content
6278
6279                   |Create a new alternative task MorningBoozeCheckAlt1|
6280
6281                .. container:: title
6282
6283                   Figure 19. Create a new Task
6284
6285             .. container:: paragraph
6286
6287                The task definition is now complete so click the 'Submit'
6288                button to save the task. Now that we have created our
6289                task, we can can add this task to the single pre-existing
6290                state (``BoozeAuthDecide``) in our policy.
6291
6292             .. container:: paragraph
6293
6294                To edit the ``BoozeAuthDecide`` state in our policy click
6295                on the 'Policies' tab. In the 'Policies' pane, right
6296                click on our ``MyFirstPolicy`` policy and select 'Edit'.
6297                Navigate to the ``BoozeAuthDecide`` state in the 'states'
6298                section at the bottom of the policy definition pane.
6299
6300             .. container:: imageblock
6301
6302                .. container:: content
6303
6304                   |Right click to edit a policy|
6305
6306                .. container:: title
6307
6308                   Figure 20. Edit a Policy
6309
6310             .. container:: paragraph
6311
6312                To add our new task ``MorningBoozeCheckAlt1``, scroll
6313                down to the ``BoozeAuthDecide`` state in the 'States'
6314                section. In the 'State Tasks' section for
6315                ``BoozeAuthDecide`` use the 'Add new task' button. Select
6316                our new ``MorningBoozeCheckAlt1`` task, and use the name
6317                of the task as the 'Local Name' for the task. The
6318                ``MorningBoozeCheckAlt1`` task can reuse the same
6319                ``MorningBoozeCheck_Output_Direct`` 'Direct State Output
6320                Mapping' that we used for the ``MorningBoozeCheck`` task.
6321                (Recall that the role of the 'State Output Mapping' is to
6322                select the output event for the state, and select the
6323                next state to be executed. These both remain the same as
6324                before.)
6325
6326             .. container:: paragraph
6327
6328                Since our state has more than one task we must define
6329                some logic to determine which task should be used each
6330                time the state is executed. This *task selection logic*
6331                is defined in the state definition. For our
6332                ``BoozeAuthDecide`` state we want the choice of which
6333                task to use to be based on the ``branch_ID`` from which
6334                the ``SALE_INPUT`` event originated. For simplicity sake
6335                let us assume that branches with ``branch_ID`` between
6336                ``0`` and ``999`` should use the ``MorningBoozeCheck``
6337                task, and the branches with with ``branch_ID`` between
6338                ``1000`` and ``1999`` should use the
6339                ``MorningBoozeCheckAlt1`` task.
6340
6341             .. container:: paragraph
6342
6343                This time, for variety, we will author the task selection
6344                logic using the
6345                ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__
6346                scripting language. Sample task selection logic code
6347                (specified in
6348                ```JavaScript`` <https://en.wikipedia.org/wiki/JavaScript>`__)
6349                is given below. Paste the script text into the 'Task
6350                Selection Logic' box, and use "JAVASCRIPT" as the 'Task
6351                Selection Logic Type / Flavour'. It is necessary to mark
6352                one of the tasks as the 'Default Task' so that the task
6353                selection logic always has a fallback default option in
6354                cases where a particular task cannot be selected. In this
6355                case the ``MorningBoozeCheck`` task can be the default
6356                task.
6357
6358             .. container:: listingblock
6359
6360                .. container:: title
6361
6362                   JavaScript code for the ``BoozeAuthDecide`` task
6363                   selection logic
6364
6365                .. container:: content
6366
6367                   .. code::
6368
6369                      /*
6370                       * ============LICENSE_START=======================================================
6371                       *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
6372                       * ================================================================================
6373                       * Licensed under the Apache License, Version 2.0 (the "License");
6374                       * you may not use this file except in compliance with the License.
6375                       * You may obtain a copy of the License at
6376                       *
6377                       *      http://www.apache.org/licenses/LICENSE-2.0
6378                       *
6379                       * Unless required by applicable law or agreed to in writing, software
6380                       * distributed under the License is distributed on an "AS IS" BASIS,
6381                       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6382                       * See the License for the specific language governing permissions and
6383                       * limitations under the License.
6384                       *
6385                       * SPDX-License-Identifier: Apache-2.0
6386                       * ============LICENSE_END=========================================================
6387                       */
6388
6389
6390                      var returnValueType = Java.type("java.lang.Boolean");
6391                      var returnValue = new returnValueType(true);
6392
6393                      executor.logger.info("Task Selection Execution: '"+executor.subject.id+
6394                          "'. Input Event: '"+executor.inFields+"'");
6395
6396                      branchid = executor.inFields.get("branch_ID");
6397                      taskorig = executor.subject.getTaskKey("MorningBoozeCheck");
6398                      taskalt = executor.subject.getTaskKey("MorningBoozeCheckAlt1");
6399                      taskdef = executor.subject.getDefaultTaskKey();
6400
6401                      if(branchid >=0 && branchid <1000){
6402                        taskorig.copyTo(executor.selectedTask);
6403                      }
6404                      else if (branchid >=1000 && branchid <2000){
6405                        taskalt.copyTo(executor.selectedTask);
6406                      }
6407                      else{
6408                        taskdef.copyTo(executor.selectedTask);
6409                      }
6410
6411                      /*
6412                      This task selection logic selects task "MorningBoozeCheck" for branches with
6413                      0<=branch_ID<1000 and selects task "MorningBoozeCheckAlt1" for branches with
6414                      1000<=branch_ID<2000. Otherwise the default task is selected.
6415                      In this case the default task is also "MorningBoozeCheck"
6416                      */
6417
6418             .. container:: imageblock
6419
6420                .. container:: content
6421
6422                   |State definition with 2 Tasks and Task Selection
6423                   Logic|
6424
6425                .. container:: title
6426
6427                   Figure 21. State definition with 2 Tasks and Task
6428                   Selection Logic
6429
6430             .. container:: paragraph
6431
6432                When complete don’t forget to click the 'Submit' button
6433                at the bottom of 'Policies' pane for our
6434                ``MyFirstPolicy`` policy after updating the
6435                ``BoozeAuthDecide`` state.
6436
6437             .. container:: paragraph
6438
6439                Congratulations, you have now completed the second step
6440                towards your first APEX policy. The policy model
6441                containing our new policy can again be validated and
6442                exported from the editor and saved as shown in Step 1.
6443
6444             .. container:: paragraph
6445
6446                The exported policy model is then available in the
6447                directory you selected, as
6448                `MyFirstPolicyModel_0.0.1.json <files/mfp-files/2/MyFirstPolicyModel_0.0.1.json>`__.
6449                The exported policy can now be loaded into the APEX
6450                Policy Engine, or can be re-loaded and edited by the APEX
6451                Policy Editor.
6452
6453 Test Policy Step 2
6454 ##################
6455
6456             .. container:: paragraph
6457
6458                To start a new APEX Engine you can use the following
6459                configuration. In a full APEX installation you can find
6460                this configuration in
6461                ``$APEX_HOME/examples/config/MyFirstPolicy/2/MyFirstPolicyConfigStdin2StdoutJsonEvent.json``.
6462                Note, this has changed from the configuration file in
6463                Step 1 to enable the ``JAVASCRIPT`` executor for our new
6464                'Task Selection Logic'.
6465
6466             .. container:: listingblock
6467
6468                .. container:: title
6469
6470                   JSON to load and execute *My First Policy*, read input
6471                   JSON events from ``stdin``, and emit output events to
6472                   ``stdout``
6473
6474                .. container:: content
6475
6476                   .. code::
6477
6478                      {
6479                          "engineServiceParameters" : {
6480                              "name"                : "MyFirstPolicyApexEngine",
6481                              "version"             : "0.0.1",
6482                              "id"                  : 102,
6483                              "instanceCount"       : 4,
6484                              "deploymentPort"      : 12345,
6485                              "policyModelFileName" : "examples/models/MyFirstPolicy/2/MyFirstPolicyModel_0.0.1.json",
6486                              "engineParameters"    : {
6487                                  "executorParameters" : {
6488                                      "MVEL" : {
6489                                          "parameterClassName" : "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters"
6490                                      },
6491                                      "JAVASCRIPT" : {
6492                                          "parameterClassName" : "org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters"
6493                                      }
6494                                  }
6495                              }
6496                          },
6497                          "eventOutputParameters": {
6498                              "FirstProducer": {
6499                                  "carrierTechnologyParameters" : {
6500                                      "carrierTechnology" : "FILE",
6501                                      "parameters" : {
6502                                          "standardIO" : true
6503                                      }
6504                                  },
6505                                  "eventProtocolParameters" : {
6506                                      "eventProtocol" : "JSON"
6507                                  }
6508                              }
6509                          },
6510                          "eventInputParameters": {
6511                              "FirstConsumer": {
6512                                  "carrierTechnologyParameters" : {
6513                                      "carrierTechnology" : "FILE",
6514                                      "parameters" : {
6515                                          "standardIO" : true
6516                                      }
6517                                  },
6518                                  "eventProtocolParameters" : {
6519                                      "eventProtocol" : "JSON"
6520                                  }
6521                              }
6522                          }
6523                      }
6524
6525             .. container:: paragraph
6526
6527                To test the policy try paste the following events into
6528                the console as the APEX engine executes. Note, all tests
6529                from Step 1 will still work perfectly since none of those
6530                events originate from a branch with ``branch_ID`` between
6531                ``1000`` and ``2000``. The 'Task Selection Logic' will
6532                therefore pick the ``MorningBoozeCheck`` task as
6533                expected, and will therefore give the same results.
6534
6535             .. table:: Table 14. Inputs and Outputs when testing *My First Policy*
6536
6537                +----------------------------------------------+------------------------------------------------------------+---------------------------+
6538                | Input Event (JSON)                           | Output Event (JSON)                                        | comment                   |
6539                +==============================================+============================================================+===========================+
6540                | .. container::                               | .. container::                                             | Request to buy            |
6541                |                                              |                                                            | alcohol item              |
6542                |    .. container:: listingblock               |    .. container:: listingblock                             | (``item_ID=1249``)        |
6543                |                                              |                                                            |                           |
6544                |                                              |                                                            | at *08:41:06              |
6545                |                                              |       .. container:: content                               | GMT* on *Monday,          |
6546                |       .. container:: content                 |                                                            | 02 January                |        
6547                |                                              |          .. code::                                         | 2017*.                    |
6548                |                                              |                                                            |                           |
6549                |                                              |             {                                              | Sale is not               |    
6550                |          .. code::                           |               "nameSpace": "com.hyperm",                   | authorized. Uses          |
6551                |                                              |               "name": "SALE_AUTH",                         | the                       |
6552                |                                              |               "version": "0.0.1",                          | ``MorningBoozeCheck``     |
6553                |             {                                |               "source": "",                                |                           |
6554                |               "nameSpace": "com.hyperm",     |               "target": "",                                | task.                     |     
6555                |               "name": "SALE_INPUT",          |               "amount": 1249,                              |                           |
6556                |                "version": "0.0.1",           |               "assistant_ID":12,                           | Note this test            |
6557                |               "time": 1483346466000,         |               "authorised": false,                         | is copied from            |
6558                |               "sale_ID": 99999992,           |               "branch_ID": 2,                              | Step 1 above,             |
6559                |               "amount": 1249,                |               "item_ID": 1012,                             | and demonstrates          |    
6560                |               "item_ID": 1012,               |               "message": "Sale not authorised by policy ta | that the                  |
6561                |               "quantity": 1,                 |                sk MorningBoozeCheck for time 08:41:06  GMT.| original                  |
6562                |               "assistant_ID": 12,            |                Alcohol can not be sold between 00:00:00    | ``MorningBoozeCheck``     |
6563                |               "branch_ID": 2                 |                GMT and 11:30:00 GMT",                      |                           |
6564                |              }                               |               "notes": null,                               | task is                   |
6565                |                                              |               "quantity": 1,                               | executed.                 |    
6566                |                                              |               "sale_ID": 99999992,                         |                           |
6567                |                                              |               "time": 1483346466000                        |                           |
6568                |                                              |             }                                              |                           |
6569                +----------------------------------------------+------------------------------------------------------------+---------------------------+
6570                | .. container::                               | .. container::                                             | Request to buy            |
6571                |                                              |                                                            | alcohol                   |
6572                |    .. container:: listingblock               |    .. container:: listingblock                             | (``item_ID=1047``)        |
6573                |                                              |                                                            |                           |
6574                |                                              |                                                            | at *10:14:33* on          |
6575                |                                              |       .. container:: content                               | *Thursday, 22             |
6576                |       .. container:: content                 |                                                            | December 2016*.           |
6577                |                                              |          .. code::                                         |                           |
6578                |                                              |                                                            | Sale is not               |
6579                |                                              |             {                                              | authorized. Uses          |
6580                |          .. code::                           |               "nameSpace" : "com.hyperm",                  | the                       |
6581                |                                              |               "name" : "SALE_AUTH",                        | ``MorningBoozeCheckAlt1`` |
6582                |                                              |               "version" : "0.0.1",                         | task.                     |
6583                |             {                                |               "source" : "",                               |                           |
6584                |                                              |               "target" : "",                               |                           |
6585                |               "nameSpace": "com.hyperm",     |               "sale_ID" : 99999981,                        |                           |
6586                |               "name": "SALE_INPUT",          |               "amount" : 299,                              |                           |
6587                |               "version": "0.0.1",            |               "assistant_ID": 1212,                        |                           |
6588                |               "time": 1482398073000,         |               "notes" : null,                              |                           |
6589                |               "sale_ID": 99999981,           |               "quantity" : 1,                              |                           |
6590                |               "amount": 299,                 |               "branch_ID" : 1002,                          |                           |
6591                |               "item_ID": 1047,               |               "item_ID" : 1047,                            |                           |
6592                |               "quantity": 1,                 |               "authorised" : false,                        |                           |
6593                |               "assistant_ID": 1212,          |               "time" : 1482398073000,                      |                           |
6594                |               "branch_ID": 1002              |               "message" : "Sale not authorised by policy t |                           |
6595                |             }                                |                ask MorningBoozeCheckAlt1 fortime           |                           |
6596                |                                              |                10:14:33 CET. Alcohol can not be sold       |                           |
6597                |                                              |                between 00:00:00 CET and 13:00:00 CET or on |                           |
6598                |                                              |                Sunday"                                     |                           |
6599                |                                              |             }                                              |                           |
6600                +----------------------------------------------+------------------------------------------------------------+---------------------------+
6601                | .. container::                               | .. container::                                             | Request to buy            |
6602                |                                              |                                                            | alcohol                   |
6603                |    .. container:: listingblock               |    .. container:: listingblock                             | (``item_ID=1443``)        |
6604                |                                              |                                                            |                           |
6605                |                                              |                                                            | at *17:19:37* on          |
6606                |                                              |       .. container:: content                               | *Sunday, 18               |
6607                |       .. container:: content                 |                                                            | December 2016*.           |
6608                |                                              |          .. code::                                         |                           |
6609                |                                              |                                                            | Sale is not               |
6610                |                                              |             {                                              | authorized. Uses          |
6611                |          .. code::                           |               "nameSpace" : "com.hyperm",                  | the                       |
6612                |                                              |                                                            | ``MorningBoozeCheckAlt1`` |
6613                |                                              |               "name" : "SALE_AUTH",                        | task.                     |
6614                |             {                                |                                                            |                           |
6615                |               "nameSpace": "com.hyperm",     |               "version" : "0.0.1",                         |                           |
6616                |               "name": "SALE_INPUT",          |               "source" : "",                               |                           |
6617                |               "version": "0.0.1",            |               "target" : "",                               |                           |
6618                |               "time": 1482077977000,         |               "sale_ID" : 99999982,                        |                           |
6619                |               "sale_ID": 99999982,           |               "amount" : 2199,                             |                           |
6620                |               "amount": 2199,                |               "assistant_ID" : 94,                         |                           |
6621                |               "item_ID": 1443,               |               "notes" : "Buy 3, get 1 free!!",             |                           |
6622                |               "quantity": 12,                |               "quantity" : 12,                             |                           |
6623                |               "assistant_ID": 94,            |               "branch_ID" : 1003,                          |                           |
6624                |               "branch_ID": 1003,             |               "item_ID" : 1443,                            |                           |
6625                |               "notes": "Buy 3, get 1 free!!" |               "authorised" : false,                        |                           |
6626                |             }                                |               "time" : 1482077977000,                      |                           |
6627                |                                              |               "message" : "Sale not authorised by policy t |                           |
6628                |                                              |                ask MorningBoozeCheckAlt1 for               |                           |
6629                |                                              |                time 17:19:37 CET. Alcohol c                |                           |
6630                |                                              |                an not be sold between 00:00:               |                           |
6631                |                                              |                00 CET and 13:00:00 CET or on               |                           |
6632                |                                              |                Sunday"                                     |                           |
6633                +----------------------------------------------+------------------------------------------------------------+---------------------------+
6634                | .. container::                               | .. container::                                             | Request to buy            |
6635                |                                              |                                                            | non-alcoholic             |
6636                |    .. container:: listingblock               |    .. container:: listingblock                             | item                      |
6637                |                                              |                                                            | (``item_ID=5321``)        |
6638                |                                              |                                                            |                           |
6639                |                                              |       .. container:: content                               | at *11:13:09* on          |
6640                |       .. container:: content                 |                                                            | *Monday, 2                |
6641                |                                              |          .. code::                                         | January 2017*.            |
6642                |                                              |                                                            |                           |
6643                |                                              |             {                                              | Sale is                   |
6644                |          .. code::                           |               "nameSpace" : "com.hyperm",                  | authorized. Uses          |
6645                |                                              |               "name" : "SALE_AUTH",                        | the                       |
6646                |             {                                |               "version" : "0.0.1",                         | ``MorningBoozeCheckAlt1`` |
6647                |                "nameSpace": "com.hyperm",    |               "source" : "",                               | task.                     |
6648                |                "name": "SALE_INPUT",         |               "target" : "",                               |                           |
6649                |                "version": "0.0.1",           |               "sale_ID" : 99999983,                        |                           |
6650                |                "time": 1483351989000,        |               "amount" : 699,                              |                           |
6651                |                "sale_ID": 99999983,          |               "assistant_ID" : 2323,                       |                           |
6652                |                "amount": 699,                |               "notes" : "",                                |                           |
6653                |                "item_ID": 5321,              |               "quantity" : 1,                              |                           |
6654                |                 "quantity": 1,               |               "branch_ID" : 1001,                          |                           |
6655                |                 "assistant_ID": 2323,        |               "item_ID" : 5321,                            |                           |
6656                |                 "branch_ID": 1001,           |               "authorised" : true,                         |                           |
6657                |                 "notes": ""                  |               "time" : 1483351989000,                      |                           |
6658                |              }                               |               "message" : "Sale authorised by policy task  |                           |
6659                |                                              |                MorningBoozeCheckAlt1 for time 11:13:09 CET"|                           |
6660                |                                              |             }                                              |                           |
6661                +----------------------------------------------+------------------------------------------------------------+---------------------------+
6662
6663 Policy 2 in CLI Editor
6664 ######################
6665
6666             .. container:: paragraph
6667
6668                An equivalent version of the ``MyFirstPolicyModel``
6669                policy model can again be generated using the APEX CLI
6670                editor. A sample APEX CLI script is shown below:
6671
6672             .. container:: listingblock
6673
6674                .. container:: title
6675
6676                   APEX CLI Editor code for Policy 2
6677
6678                .. container:: content
6679
6680                   .. code::
6681
6682                      #-------------------------------------------------------------------------------
6683                      # ============LICENSE_START=======================================================
6684                      #  Copyright (C) 2016-2018 Ericsson. All rights reserved.
6685                      # ================================================================================
6686                      # Licensed under the Apache License, Version 2.0 (the "License");
6687                      # you may not use this file except in compliance with the License.
6688                      # You may obtain a copy of the License at
6689                      #
6690                      #      http://www.apache.org/licenses/LICENSE-2.0
6691                      #
6692                      # Unless required by applicable law or agreed to in writing, software
6693                      # distributed under the License is distributed on an "AS IS" BASIS,
6694                      # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6695                      # See the License for the specific language governing permissions and
6696                      # limitations under the License.
6697                      #
6698                      # SPDX-License-Identifier: Apache-2.0
6699                      # ============LICENSE_END=========================================================
6700                      #-------------------------------------------------------------------------------
6701
6702                      model create name=MyFirstPolicyModel version=0.0.1 uuid=540226fb-55ee-4f0e-a444-983a0494818e description="This is my first Apex Policy Model."
6703
6704                      schema create name=assistant_ID_type version=0.0.1 uuid=36df4c71-9616-4206-8b53-976a5cd4bd87 description="A type for 'assistant_ID' values" flavour=Java schema=java.lang.Long
6705
6706                      schema create name=authorised_type version=0.0.1 uuid=d48b619e-d00d-4008-b884-02d76ea4350b description="A type for 'authorised' values" flavour=Java schema=java.lang.Boolean
6707
6708                      schema create name=branch_ID_type version=0.0.1 uuid=6468845f-4122-4128-8e49-0f52c26078b5 description="A type for 'branch_ID' values" flavour=Java schema=java.lang.Long
6709
6710                      schema create name=item_ID_type version=0.0.1 uuid=4f227ff1-aee0-453a-b6b6-9a4b2e0da932 description="A type for 'item_ID' values" flavour=Java schema=java.lang.Long
6711
6712                      schema create name=message_type version=0.0.1 uuid=ad1431bb-3155-4e73-b5a3-b89bee498749 description="A type for 'message' values" flavour=Java schema=java.lang.String
6713
6714                      schema create name=notes_type version=0.0.1 uuid=eecfde90-896c-4343-8f9c-2603ced94e2d description="A type for 'notes' values" flavour=Java schema=java.lang.String
6715
6716                      schema create name=price_type version=0.0.1 uuid=52c2fc45-fd8c-463c-bd6f-d91b0554aea7 description="A type for 'amount'/'price' values" flavour=Java schema=java.lang.Long
6717
6718                      schema create name=quantity_type version=0.0.1 uuid=ac3d9842-80af-4a98-951c-bd79a431c613 description="A type for 'quantity' values" flavour=Java schema=java.lang.Integer
6719
6720                      schema create name=sale_ID_type version=0.0.1 uuid=cca47d74-7754-4a61-b163-ca31f66b157b description="A type for 'sale_ID' values" flavour=Java schema=java.lang.Long
6721
6722                      schema create name=timestamp_type version=0.0.1 uuid=fd594e88-411d-4a94-b2be-697b3a0d7adf description="A type for 'time' values" flavour=Java schema=java.lang.Long
6723
6724                      task create name=MorningBoozeCheck version=0.0.1 uuid=3351b0f4-cf06-4fa2-8823-edf67bd30223 description=LS
6725                      This task checks if the sales request is for an item that contains alcohol.
6726                      If the local time is between 00:00:00 and 11:30:00 then the sale is not authorised. Otherwise the sale is authorised.
6727                      In this implementation we assume that all items with item_ID values between 1000 and 2000 contain alcohol :-)
6728                      LE
6729                      task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
6730                      task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=amount schemaName=price_type schemaVersion=0.0.1
6731                      task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
6732                      task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
6733                      task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=quantity schemaName=quantity_type schemaVersion=0.0.1
6734                      task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
6735                      task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
6736                      task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=time schemaName=timestamp_type schemaVersion=0.0.1
6737                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
6738                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=amount schemaName=price_type schemaVersion=0.0.1
6739                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
6740                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
6741                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=quantity schemaName=quantity_type schemaVersion=0.0.1
6742                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
6743                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
6744                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=authorised schemaName=authorised_type schemaVersion=0.0.1
6745                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=time schemaName=timestamp_type schemaVersion=0.0.1
6746                      task outputfield create name=MorningBoozeCheck version=0.0.1 fieldName=message schemaName=message_type schemaVersion=0.0.1 optional=true
6747                      task logic create name=MorningBoozeCheck version=0.0.1 logicFlavour=MVEL logic=LS
6748                      /*
6749                       * ============LICENSE_START=======================================================
6750                       *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
6751                       * ================================================================================
6752                       * Licensed under the Apache License, Version 2.0 (the "License");
6753                       * you may not use this file except in compliance with the License.
6754                       * You may obtain a copy of the License at
6755                       *
6756                       *      http://www.apache.org/licenses/LICENSE-2.0
6757                       *
6758                       * Unless required by applicable law or agreed to in writing, software
6759                       * distributed under the License is distributed on an "AS IS" BASIS,
6760                       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6761                       * See the License for the specific language governing permissions and
6762                       * limitations under the License.
6763                       *
6764                       * SPDX-License-Identifier: Apache-2.0
6765                       * ============LICENSE_END=========================================================
6766                       */
6767                      import java.util.Date;
6768                      import java.util.Calendar;
6769                      import java.util.TimeZone;
6770                      import java.text.SimpleDateFormat;
6771
6772                      logger.info("Task Execution: '"+subject.id+"'. Input Fields: '"+inFields+"'");
6773
6774                      outFields.put("amount"      , inFields.get("amount"));
6775                      outFields.put("assistant_ID", inFields.get("assistant_ID"));
6776                      outFields.put("notes"       , inFields.get("notes"));
6777                      outFields.put("quantity"    , inFields.get("quantity"));
6778                      outFields.put("branch_ID"   , inFields.get("branch_ID"));
6779                      outFields.put("item_ID"     , inFields.get("item_ID"));
6780                      outFields.put("time"        , inFields.get("time"));
6781                      outFields.put("sale_ID"     , inFields.get("sale_ID"));
6782
6783                      item_id = inFields.get("item_ID");
6784
6785                      //The events used later to test this task use GMT timezone!
6786                      gmt = TimeZone.getTimeZone("GMT");
6787                      timenow = Calendar.getInstance(gmt);
6788                      df = new SimpleDateFormat("HH:mm:ss z");
6789                      df.setTimeZone(gmt);
6790                      timenow.setTimeInMillis(inFields.get("time"));
6791
6792                      midnight = timenow.clone();
6793                      midnight.set(
6794                          timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
6795                          timenow.get(Calendar.DATE),0,0,0);
6796                      eleven30 = timenow.clone();
6797                      eleven30.set(
6798                          timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
6799                          timenow.get(Calendar.DATE),11,30,0);
6800
6801                      itemisalcohol = false;
6802                      if(item_id != null && item_id >=1000 && item_id < 2000)
6803                          itemisalcohol = true;
6804
6805                      if( itemisalcohol
6806                          && timenow.after(midnight) && timenow.before(eleven30)){
6807                        outFields.put("authorised", false);
6808                        outFields.put("message", "Sale not authorised by policy task "+subject.taskName+
6809                          " for time "+df.format(timenow.getTime())+
6810                          ". Alcohol can not be sold between "+df.format(midnight.getTime())+
6811                          " and "+df.format(eleven30.getTime()));
6812                        return true;
6813                      }
6814                      else{
6815                        outFields.put("authorised", true);
6816                        outFields.put("message", "Sale authorised by policy task "+subject.taskName+
6817                          " for time "+df.format(timenow.getTime()));
6818                        return true;
6819                      }
6820
6821                      /*
6822                      This task checks if a sale request is for an item that is an alcoholic drink.
6823                      If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
6824                      authorised. Otherwise the sale is authorised.
6825                      In this implementation we assume that items with item_ID value between 1000 and
6826                      2000 are all alcoholic drinks :-)
6827                      */
6828                      LE
6829
6830                      task create name=MorningBoozeCheckAlt1 version=0.0.1 uuid=bc6d90c9-c902-4686-afd3-925b30e39990 description=LS
6831                      This task checks if a sale request is for an item that is an alcoholic drink.
6832                      If the local time is between 00:00:00 CET and 13:00:00 CET then the sale is not authorised.
6833                      Also alcohol sales are not allowed on Sundays. Otherwise the sale is authorised.
6834                      In this implementation we assume that items with item_ID between 1000 and 2000 are all alcoholic drinks
6835                      LE
6836                      task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
6837                      task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=amount schemaName=price_type schemaVersion=0.0.1
6838                      task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
6839                      task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
6840                      task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=quantity schemaName=quantity_type schemaVersion=0.0.1
6841                      task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
6842                      task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
6843                      task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=time schemaName=timestamp_type schemaVersion=0.0.1
6844                      task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
6845                      task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=amount schemaName=price_type schemaVersion=0.0.1
6846                      task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
6847                      task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
6848                      task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=quantity schemaName=quantity_type schemaVersion=0.0.1
6849                      task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
6850                      task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
6851                      task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=authorised schemaName=authorised_type schemaVersion=0.0.1
6852                      task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=time schemaName=timestamp_type schemaVersion=0.0.1
6853                      task outputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=message schemaName=message_type schemaVersion=0.0.1 optional=true
6854                      task logic create name=MorningBoozeCheckAlt1 version=0.0.1 logicFlavour=MVEL logic=LS
6855                      /*
6856                       * ============LICENSE_START=======================================================
6857                       *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
6858                       * ================================================================================
6859                       * Licensed under the Apache License, Version 2.0 (the "License");
6860                       * you may not use this file except in compliance with the License.
6861                       * You may obtain a copy of the License at
6862                       *
6863                       *      http://www.apache.org/licenses/LICENSE-2.0
6864                       *
6865                       * Unless required by applicable law or agreed to in writing, software
6866                       * distributed under the License is distributed on an "AS IS" BASIS,
6867                       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6868                       * See the License for the specific language governing permissions and
6869                       * limitations under the License.
6870                       *
6871                       * SPDX-License-Identifier: Apache-2.0
6872                       * ============LICENSE_END=========================================================
6873                       */
6874                      import java.util.Date;
6875                      import java.util.Calendar;
6876                      import java.util.TimeZone;
6877                      import java.text.SimpleDateFormat;
6878
6879                      logger.info("Task Execution: '"+subject.id+"'. Input Event: '"+inFields+"'");
6880
6881                      outFields.put("amount"      , inFields.get("amount"));
6882                      outFields.put("assistant_ID", inFields.get("assistant_ID"));
6883                      outFields.put("notes"       , inFields.get("notes"));
6884                      outFields.put("quantity"    , inFields.get("quantity"));
6885                      outFields.put("branch_ID"   , inFields.get("branch_ID"));
6886                      outFields.put("item_ID"     , inFields.get("item_ID"));
6887                      outFields.put("time"        , inFields.get("time"));
6888                      outFields.put("sale_ID"     , inFields.get("sale_ID"));
6889
6890                      item_id = inFields.get("item_ID");
6891
6892                      //The events used later to test this task use CET timezone!
6893                      cet = TimeZone.getTimeZone("CET");
6894                      timenow = Calendar.getInstance(cet);
6895                      df = new SimpleDateFormat("HH:mm:ss z");
6896                      df.setTimeZone(cet);
6897                      timenow.setTimeInMillis(inFields.get("time"));
6898
6899                      midnight = timenow.clone();
6900                      midnight.set(
6901                          timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
6902                          timenow.get(Calendar.DATE),0,0,0);
6903                      onepm = timenow.clone();
6904                      onepm.set(
6905                          timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),
6906                          timenow.get(Calendar.DATE),13,0,0);
6907
6908                      itemisalcohol = false;
6909                      if(item_id != null && item_id >=1000 && item_id < 2000)
6910                          itemisalcohol = true;
6911
6912                      if( itemisalcohol &&
6913                          ( (timenow.after(midnight) && timenow.before(onepm))
6914                            ||
6915                            (timenow.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
6916                          )){
6917                        outFields.put("authorised", false);
6918                        outFields.put("message", "Sale not authorised by policy task "+subject.taskName+
6919                          " for time "+df.format(timenow.getTime())+
6920                          ". Alcohol can not be sold between "+df.format(midnight.getTime())+
6921                          " and "+df.format(onepm.getTime()) +" or on Sunday");
6922                        return true;
6923                      }
6924                      else{
6925                        outFields.put("authorised", true);
6926                        outFields.put("message", "Sale authorised by policy task "+subject.taskName+
6927                          " for time "+df.format(timenow.getTime()));
6928                        return true;
6929                      }
6930
6931                      /*
6932                      This task checks if a sale request is for an item that is an alcoholic drink.
6933                      If the local time is between 00:00:00 CET and 13:00:00 CET then the sale is not authorised.
6934                      Also alcohol sales are not allowed on Sundays. Otherwise the sale is authorised.
6935                      In this implementation we assume that items with item_ID between 1000 and 2000 are all alcoholic drinks :-)
6936                      */
6937                      LE
6938
6939                      event create name=SALE_AUTH version=0.0.1 uuid=c4500941-3f98-4080-a9cc-5b9753ed050b description="An event emitted by the Policy to indicate whether the sale of an item has been authorised" nameSpace=com.hyperm source="APEX" target="POS"
6940                      event parameter create name=SALE_AUTH version=0.0.1 parName=amount schemaName=price_type schemaVersion=0.0.1
6941                      event parameter create name=SALE_AUTH version=0.0.1 parName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
6942                      event parameter create name=SALE_AUTH version=0.0.1 parName=authorised schemaName=authorised_type schemaVersion=0.0.1
6943                      event parameter create name=SALE_AUTH version=0.0.1 parName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
6944                      event parameter create name=SALE_AUTH version=0.0.1 parName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
6945                      event parameter create name=SALE_AUTH version=0.0.1 parName=message schemaName=message_type schemaVersion=0.0.1 optional=true
6946                      event parameter create name=SALE_AUTH version=0.0.1 parName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
6947                      event parameter create name=SALE_AUTH version=0.0.1 parName=quantity schemaName=quantity_type schemaVersion=0.0.1
6948                      event parameter create name=SALE_AUTH version=0.0.1 parName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
6949                      event parameter create name=SALE_AUTH version=0.0.1 parName=time schemaName=timestamp_type schemaVersion=0.0.1
6950
6951                      event create name=SALE_INPUT version=0.0.1 uuid=4f04aa98-e917-4f4a-882a-c75ba5a99374 description="An event raised by the PoS system each time an item is scanned for purchase" nameSpace=com.hyperm source="POS" target="APEX"
6952                      event parameter create name=SALE_INPUT version=0.0.1 parName=amount schemaName=price_type schemaVersion=0.0.1
6953                      event parameter create name=SALE_INPUT version=0.0.1 parName=assistant_ID schemaName=assistant_ID_type schemaVersion=0.0.1
6954                      event parameter create name=SALE_INPUT version=0.0.1 parName=branch_ID schemaName=branch_ID_type schemaVersion=0.0.1
6955                      event parameter create name=SALE_INPUT version=0.0.1 parName=item_ID schemaName=item_ID_type schemaVersion=0.0.1
6956                      event parameter create name=SALE_INPUT version=0.0.1 parName=notes schemaName=notes_type schemaVersion=0.0.1 optional=true
6957                      event parameter create name=SALE_INPUT version=0.0.1 parName=quantity schemaName=quantity_type schemaVersion=0.0.1
6958                      event parameter create name=SALE_INPUT version=0.0.1 parName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
6959                      event parameter create name=SALE_INPUT version=0.0.1 parName=time schemaName=timestamp_type schemaVersion=0.0.1
6960
6961
6962                      policy create name=MyFirstPolicy version=0.0.1 uuid=6c5e410f-489a-46ff-964e-982ce6e8b6d0 description="This is my first Apex policy. It checks if a sale should be authorised or not." template=FREEFORM firstState=BoozeAuthDecide
6963                      policy state create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide triggerName=SALE_INPUT triggerVersion=0.0.1 defaultTaskName=MorningBoozeCheck defaultTaskVersion=0.0.1
6964                      policy state output create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide outputName=MorningBoozeCheck_Output_Direct eventName=SALE_AUTH eventVersion=0.0.1 nextState=NULL
6965                      policy state taskref create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide taskLocalName=MorningBoozeCheckAlt1 taskName=MorningBoozeCheckAlt1 taskVersion=0.0.1 outputType=DIRECT outputName=MorningBoozeCheck_Output_Direct
6966                      policy state taskref create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide taskLocalName=MorningBoozeCheck taskName=MorningBoozeCheck taskVersion=0.0.1 outputType=DIRECT outputName=MorningBoozeCheck_Output_Direct
6967                      policy state selecttasklogic create name=MyFirstPolicy version=0.0.1 stateName=BoozeAuthDecide logicFlavour=JAVASCRIPT logic=LS
6968                      /*
6969                       * ============LICENSE_START=======================================================
6970                       *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
6971                       * ================================================================================
6972                       * Licensed under the Apache License, Version 2.0 (the "License");
6973                       * you may not use this file except in compliance with the License.
6974                       * You may obtain a copy of the License at
6975                       *
6976                       *      http://www.apache.org/licenses/LICENSE-2.0
6977                       *
6978                       * Unless required by applicable law or agreed to in writing, software
6979                       * distributed under the License is distributed on an "AS IS" BASIS,
6980                       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6981                       * See the License for the specific language governing permissions and
6982                       * limitations under the License.
6983                       *
6984                       * SPDX-License-Identifier: Apache-2.0
6985                       * ============LICENSE_END=========================================================
6986                       */
6987
6988                      var returnValueType = Java.type("java.lang.Boolean");
6989                      var returnValue = new returnValueType(true);
6990
6991                      executor.logger.info("Task Selection Execution: '"+executor.subject.id+"'. Input Event: '"+executor.inFields+"'");
6992
6993                      branchid = executor.inFields.get("branch_ID");
6994                      taskorig = executor.subject.getTaskKey("MorningBoozeCheck");
6995                      taskalt = executor.subject.getTaskKey("MorningBoozeCheckAlt1");
6996                      taskdef = executor.subject.getDefaultTaskKey();
6997
6998                      if(branchid >=0 && branchid <1000){
6999                        taskorig.copyTo(executor.selectedTask);
7000                      }
7001                      else if (branchid >=1000 && branchid <2000){
7002                        taskalt.copyTo(executor.selectedTask);
7003                      }
7004                      else{
7005                        taskdef.copyTo(executor.selectedTask);
7006                      }
7007
7008                      /*
7009                      This task selection logic selects task "MorningBoozeCheck" for branches with 0<=branch_ID<1000 and selects task "MorningBoozeCheckAlt1" for branches with 1000<=branch_ID<2000. Otherwise the default task is selected. In this case the default task is also "MorningBoozeCheck"
7010                      */
7011                      LE
7012
7013 APEX Logging
7014 ^^^^^^^^^^^^
7015
7016 Introduction to APEX Logging
7017 ----------------------------
7018
7019          .. container:: paragraph
7020
7021             All APEX components make extensive use of logging using the
7022             logging façade `SLF4J <https://www.slf4j.org/>`__ with the
7023             backend `Logback <https://logback.qos.ch/>`__. Both are used
7024             off-the-shelve, so the standard documentation and
7025             configuration apply to APEX logging. For details on how to
7026             work with logback please see the `logback
7027             manual <https://logback.qos.ch/manual/index.html>`__.
7028
7029          .. container:: paragraph
7030
7031             The APEX applications is the logback configuration file
7032             ``$APEX_HOME/etc/logback.xml`` (Windows:
7033             ``%APEX_HOME%\etc\logback.xml``). The logging backend is set
7034             to no debug, i.e. logs from the logging framework should be
7035             hidden at runtime.
7036
7037          .. container:: paragraph
7038
7039             The configurable log levels work as expected:
7040
7041          .. container:: ulist
7042
7043             -  *error* (or *ERROR*) is used for serious errors in the
7044                APEX runtime engine
7045
7046             -  *warn* (or *WARN*) is used for warnings, which in general
7047                can be ignored but might indicate some deeper problems
7048
7049             -  *info* (or *INFO*) is used to provide generally
7050                interesting messages for startup and policy execution
7051
7052             -  *debug* (or *DEBUG*) provides more details on startup and
7053                policy execution
7054
7055             -  *trace* (or *TRACE*) gives full details on every aspect
7056                of the APEX engine from start to end
7057
7058          .. container:: paragraph
7059
7060             The loggers can also be configured as expected. The standard
7061             configuration (after installing APEX) uses log level *info*
7062             on all APEX classes (components).
7063
7064          .. container:: paragraph
7065
7066             The applications and scripts in ``$APEX_HOME/bin`` (Windows:
7067             ``%APEX_HOME\bin``) are configured to use the logback
7068             configuration ``$APEX_HOME/etc/logback.xml`` (Windows:
7069             ``%APEX_HOME\etc\logback.xml``). There are multiple ways to
7070             use different logback configurations, for instance:
7071
7072          .. container:: ulist
7073
7074             -  Maintain multiple configurations in ``etc``, for instance
7075                a ``logback-debug.xml`` for deep debugging and a
7076                ``logback-production.xml`` for APEX in production mode,
7077                then copy the required configuration file to the used
7078                ``logback.xml`` prior starting APEX
7079
7080             -  Edit the scripts in ``bin`` to use a different logback
7081                configuration file (only recommended if you are familiar
7082                with editing bash scripts or windows batch files)
7083
7084 Standard Logging Configuration
7085 ------------------------------
7086
7087          .. container:: paragraph
7088
7089             The standard logging configuration defines a context *APEX*,
7090             which is used in the standard output pattern. The location
7091             for log files is defined in the property ``VAR_LOG`` and set
7092             to ``/var/log/onap/policy/apex-pdp``. The standard status
7093             listener is set to *NOP* and the overall logback
7094             configuration is set to no debug.
7095
7096          .. container:: listingblock
7097
7098             .. container:: content
7099
7100                .. code::
7101                  :number-lines:
7102
7103                  <configuration debug="false">
7104                    <statusListener class="ch.qos.logback.core.status.NopStatusListener" />
7105
7106                     <contextName>Apex</contextName>
7107                     <property name="VAR_LOG" value="/var/log/onap/policy/apex-pdp/" />
7108
7109                    ...appenders
7110                    ...loggers
7111                  </configuration>
7112
7113 .. container:: paragraph
7114
7115    The first appender defined is called ``STDOUT`` for logs to standard
7116    out.
7117
7118 .. container:: listingblock
7119
7120    .. container:: content
7121
7122       .. code::
7123         :number-lines:
7124
7125         <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
7126          <encoder>
7127             <Pattern>%d %contextName [%t] %level %logger{36} - %msg%n</Pattern>
7128           </encoder>
7129         </appender>
7130
7131 .. container:: paragraph
7132
7133    The root level logger then is set to the level *info* using the
7134    standard out appender.
7135
7136 .. container:: listingblock
7137
7138    .. container:: content
7139
7140       .. code::
7141         :number-lines:
7142
7143         <root level="info">
7144           <appender-ref ref="STDOUT" />
7145         </root>
7146
7147 .. container:: paragraph
7148
7149    The second appender is called ``FILE``. It writes logs to a file
7150    ``apex.log``.
7151
7152 .. container:: listingblock
7153
7154    .. container:: content
7155
7156       .. code::
7157         :number-lines:
7158
7159         <appender name="FILE" class="ch.qos.logback.core.FileAppender">
7160           <file>${VAR_LOG}/apex.log</file>
7161           <encoder>
7162             <pattern>%d %-5relative [procId=${processId}] [%thread] %-5level %logger{26} - %msg %n %ex{full}</pattern>
7163           </encoder>
7164         </appender>
7165
7166 .. container:: paragraph
7167
7168    The third appender is called ``CTXT_FILE``. It writes logs to a file
7169    ``apex_ctxt.log``.
7170
7171 .. container:: listingblock
7172
7173    .. container:: content
7174
7175       .. code::
7176         :number-lines:
7177
7178         <appender name="CTXT_FILE" class="ch.qos.logback.core.FileAppender">
7179           <file>${VAR_LOG}/apex_ctxt.log</file>
7180           <encoder>
7181             <pattern>%d %-5relative [procId=${processId}] [%thread] %-5level %logger{26} - %msg %n %ex{full}</pattern>
7182           </encoder>
7183         </appender>
7184
7185 .. container:: paragraph
7186
7187    The last definitions are for specific loggers. The first logger
7188    captures all standard APEX classes. It is configured for log level
7189    *info* and uses the standard output and file appenders. The second
7190    logger captures APEX context classes responsible for context
7191    monitoring. It is configured for log level *trace* and uses the
7192    context file appender.
7193
7194 .. container:: listingblock
7195
7196    .. container:: content
7197
7198       .. code::
7199         :number-lines:
7200
7201
7202         <logger name="org.onap.policy.apex" level="info" additivity="false">
7203           <appender-ref ref="STDOUT" />
7204           <appender-ref ref="FILE" />
7205         </logger>
7206
7207         <logger name="org.onap.policy.apex.core.context.monitoring" level="TRACE" additivity="false">
7208           <appender-ref ref="CTXT_FILE" />
7209         </logger>
7210
7211 Adding Logback Status and Debug
7212 -------------------------------
7213
7214    .. container:: paragraph
7215
7216       To activate logback status messages change the status listener
7217       from 'NOP' to for instance console.
7218
7219    .. container:: listingblock
7220
7221       .. container:: content
7222
7223          .. code::
7224
7225             <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" />
7226
7227    .. container:: paragraph
7228
7229       To activate all logback debugging, for instance to debug a new
7230       logback configuration, activate the debug attribute in the
7231       configuration.
7232
7233    .. container:: listingblock
7234
7235       .. container:: content
7236
7237          .. code::
7238
7239             <configuration debug="true">
7240             ...
7241             </configuration>
7242
7243 Logging External Components
7244 ---------------------------
7245
7246    .. container:: paragraph
7247
7248       Logback can also be configured to log any other, external
7249       components APEX is using, if they are using the common logging
7250       framework.
7251
7252    .. container:: paragraph
7253
7254       For instance, the context component of APEX is using *Infinispan*
7255       and one can add a logger for this external component. The
7256       following example adds a logger for *Infinispan* using the
7257       standard output appender.
7258
7259    .. container:: listingblock
7260
7261       .. container:: content
7262
7263          .. code::
7264
7265             <logger name="org.infinispan" level="INFO" additivity="false">
7266               <appender-ref ref="STDOUT" />
7267             </logger>
7268
7269    .. container:: paragraph
7270
7271       Another example is Apache Zookeeper. The following example adds a
7272       logger for Zookeeper using the standard outout appender.
7273
7274    .. container:: listingblock
7275
7276       .. container:: content
7277
7278          .. code::
7279
7280             <logger name="org.apache.zookeeper.ClientCnxn" level="INFO" additivity="false">
7281               <appender-ref ref="STDOUT" />
7282             </logger>
7283
7284 Configuring loggers for Policy Logic
7285 ------------------------------------
7286
7287    .. container:: paragraph
7288
7289       The logging for the logic inside a policy (task logic, task
7290       selection logic, state finalizer logic) can be configured separate
7291       from standard logging. The logger for policy logic is
7292       ``org.onap.policy.apex.executionlogging``. The following example
7293       defines
7294
7295    .. container:: ulist
7296
7297       -  a new appender for standard out using a very simple pattern
7298          (simply the actual message)
7299
7300       -  a logger for policy logic to standard out using the new
7301          appender and the already described file appender.
7302
7303    .. container:: listingblock
7304
7305       .. container:: content
7306
7307          .. code::
7308
7309             <appender name="POLICY_APPENDER_STDOUT" class="ch.qos.logback.core.ConsoleAppender">
7310               <encoder>
7311                 <pattern>policy: %msg\n</pattern>
7312               </encoder>
7313             </appender>
7314
7315             <logger name="org.onap.policy.apex.executionlogging" level="info" additivity="false">
7316               <appender-ref ref="POLICY_APPENDER_STDOUT" />
7317               <appender-ref ref="FILE" />
7318             </logger>
7319
7320    .. container:: paragraph
7321
7322       It is also possible to use specific logging for parts of policy
7323       logic. The following example defines a logger for task logic.
7324
7325    .. container:: listingblock
7326
7327       .. container:: content
7328
7329          .. code::
7330
7331             <logger name="org.onap.policy.apex.executionlogging.TaskExecutionLogging" level="TRACE" additivity="false">
7332               <appender-ref ref="POLICY_APPENDER_STDOUT" />
7333             </logger>
7334
7335 Rolling File Appenders
7336 ----------------------
7337
7338    .. container:: paragraph
7339
7340       Rolling file appenders are a good option for more complex logging
7341       of a production or complex testing APEX installation. The standard
7342       logback configuration can be used for these use cases. This
7343       section gives two examples for the standard logging and for
7344       context logging.
7345
7346    .. container:: paragraph
7347
7348       First the standard logging. The following example defines a
7349       rolling file appender. The appender rolls over on a daily basis.
7350       It allows for a file size of 100 MB.
7351
7352    .. container:: listingblock
7353
7354       .. container:: content
7355
7356          .. code::
7357
7358             <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
7359               <file>${VAR_LOG}/apex.log</file>
7360               <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
7361                 <!-- rollover daily -->
7362                 <!-- <fileNamePattern>xstream-%d{yyyy-MM-dd}.%i.txt</fileNamePattern> -->
7363                 <fileNamePattern>${VAR_LOG}/apex_%d{yyyy-MM-dd}.%i.log.gz
7364                 </fileNamePattern>
7365                 <maxHistory>4</maxHistory>
7366                 <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
7367                   <!-- or whenever the file size reaches 100MB -->
7368                   <maxFileSize>100MB</maxFileSize>
7369                 </timeBasedFileNamingAndTriggeringPolicy>
7370               </rollingPolicy>
7371               <encoder>
7372                 <pattern>
7373                   %d %-5relative [procId=${processId}] [%thread] %-5level %logger{26} - %msg %ex{full} %n
7374                 </pattern>
7375               </encoder>
7376             </appender>
7377
7378    .. container:: paragraph
7379
7380       A very similar configuration can be used for a rolling file
7381       appender logging APEX context.
7382
7383    .. container:: listingblock
7384
7385       .. container:: content
7386
7387          .. code::
7388
7389             <appender name="CTXT-FILE"
7390                   class="ch.qos.logback.core.rolling.RollingFileAppender">
7391               <file>${VAR_LOG}/apex_ctxt.log</file>
7392               <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
7393                 <fileNamePattern>${VAR_LOG}/apex_ctxt_%d{yyyy-MM-dd}.%i.log.gz
7394                 </fileNamePattern>
7395                 <maxHistory>4</maxHistory>
7396                 <timeBasedFileNamingAndTriggeringPolicy
7397                     class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
7398                   <maxFileSize>100MB</maxFileSize>
7399                 </timeBasedFileNamingAndTriggeringPolicy>
7400               </rollingPolicy>
7401               <encoder>
7402                 <pattern>
7403                   %d %-5relative [procId=${processId}] [%thread] %-5level %logger{26} - %msg %ex{full} %n
7404                 </pattern>
7405               </encoder>
7406             </appender>
7407
7408 Example Configuration for Logging Logic
7409 ---------------------------------------
7410
7411    .. container:: paragraph
7412
7413       The following example shows a configuration that logs policy logic
7414       to standard out and a file (*info*). All other APEX components are
7415       logging to a file (*debug*).. This configuration an be used in a
7416       pre-production phase with the APEX engine still running in a
7417       separate terminal to monitor policy execution. This logback
7418       configuration is in the APEX installation as
7419       ``etc/logback-logic.xml``.
7420
7421    .. container:: listingblock
7422
7423       .. container:: content
7424
7425          .. code::
7426
7427             <configuration debug="false">
7428                 <statusListener class="ch.qos.logback.core.status.NopStatusListener" />
7429
7430                 <contextName>Apex</contextName>
7431                 <property name="VAR_LOG" value="/var/log/onap/policy/apex-pdp/" />
7432
7433                 <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
7434                     <encoder>
7435                         <Pattern>%d %contextName [%t] %level %logger{36} - %msg%n</Pattern>
7436                     </encoder>
7437                 </appender>
7438
7439                 <appender name="FILE" class="ch.qos.logback.core.FileAppender">
7440                     <file>${VAR_LOG}/apex.log</file>
7441                     <encoder>
7442                         <pattern>
7443                             %d %-5relative [procId=${processId}] [%thread] %-5level%logger{26} - %msg %n %ex{full}
7444                         </pattern>
7445                     </encoder>
7446                 </appender>
7447
7448                 <appender name="POLICY_APPENDER_STDOUT" class="ch.qos.logback.core.ConsoleAppender">
7449                     <encoder>
7450                         <pattern>policy: %msg\n</pattern>
7451                     </encoder>
7452                 </appender>
7453
7454                 <root level="error">
7455                     <appender-ref ref="STDOUT" />
7456                 </root>
7457
7458                 <logger name="org.onap.policy.apex" level="debug" additivity="false">
7459                     <appender-ref ref="FILE" />
7460                 </logger>
7461
7462                 <logger name="org.onap.policy.apex.executionlogging" level="info" additivity="false">
7463                     <appender-ref ref="POLICY_APPENDER_STDOUT" />
7464                     <appender-ref ref="FILE" />
7465                 </logger>
7466             </configuration>
7467
7468 Example Configuration for a Production Server
7469 ---------------------------------------------
7470
7471    .. container:: paragraph
7472
7473       The following example shows a configuration that logs all APEX
7474       components, including policy logic, to a file (*debug*). This
7475       configuration an be used in a production phase with the APEX
7476       engine being executed as a service on a system without console
7477       output. This logback configuration is in the APEX installation as
7478       ``logback-server.xml``
7479
7480    .. container:: listingblock
7481
7482       .. container:: content
7483
7484          .. code::
7485
7486             <configuration debug="false">
7487                 <statusListener class="ch.qos.logback.core.status.NopStatusListener" />
7488
7489                 <contextName>Apex</contextName>
7490                 <property name="VAR_LOG" value="/var/log/onap/policy/apex-pdp/" />
7491
7492                 <appender name="FILE" class="ch.qos.logback.core.FileAppender">
7493                     <file>${VAR_LOG}/apex.log</file>
7494                     <encoder>
7495                         <pattern>
7496                             %d %-5relative [procId=${processId}] [%thread] %-5level%logger{26} - %msg %n %ex{full}
7497                         </pattern>
7498                     </encoder>
7499                 </appender>
7500
7501                 <root level="debug">
7502                     <appender-ref ref="FILE" />
7503                 </root>
7504
7505                 <logger name="org.onap.policy.apex.executionlogging" level="debug" additivity="false">
7506                     <appender-ref ref="FILE" />
7507                 </logger>
7508             </configuration>
7509
7510 Building a System with Websocket Backend
7511 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
7512
7513 Websockets
7514 ----------
7515
7516          .. container:: paragraph
7517
7518             Websocket is a protocol to run sockets of HTTP. Since it in
7519             essence a socket, the connection is realized between a
7520             server (waiting for connections) and a client (connecting to
7521             a server). Server/client separation is only important for
7522             connection establishment, once connected, everyone can
7523             send/receive on the same socket (as any standard socket
7524             would allow).
7525
7526          .. container:: paragraph
7527
7528             Standard Websocket implementations are simple, no
7529             publish/subscribe and no special event handling. Most
7530             servers simply send all incoming messages to all
7531             connections. There is a PubSub definition on top of
7532             Websocket called `WAMP <http://wamp-proto.org/>`__. APEX
7533             does not support WAMP at the moment.
7534
7535 Websocket in Java
7536 -----------------
7537
7538          .. container:: paragraph
7539
7540             In Java, `JSR
7541             356 <http://www.oracle.com/technetwork/articles/java/jsr356-1937161.html>`__
7542             defines the standard Websocket API. This JSR is part of Jave
7543             EE 7 standard. For Java SE, several implementations exist in
7544             open source. Since Websockets are a stable standard and
7545             simple, most implementations are stable and ready to use. A
7546             lot of products support Websockets, like Spring, JBoss,
7547             Netty, … there are also Kafka extensions for Websockets.
7548
7549 Websocket Example Code for Websocket clients (FOSS)
7550 ---------------------------------------------------
7551
7552          .. container:: paragraph
7553
7554             There are a lot of implementations and examples available on
7555             Github for Websocket clients. If one is using Java EE 7,
7556             then one can also use the native Websocket implementation.
7557             Good examples for clients using simply Java SE are here:
7558
7559          .. container:: ulist
7560
7561             -  `Websocket
7562                implementation <https://github.com/TooTallNate/Java-WebSocket>`__
7563
7564             -  `Websocket sending client example, using
7565                AWT <https://github.com/TooTallNate/Java-WebSocket/blob/master/src/main/example/ChatClient.java>`__
7566
7567             -  `Websocket receiving client example (simple echo
7568                client) <https://github.com/TooTallNate/Java-WebSocket/blob/master/src/main/example/ExampleClient.java>`__
7569
7570          .. container:: paragraph
7571
7572             For Java EE, the native Websocket API is explained here:
7573
7574          .. container:: ulist
7575
7576             -  `Oracle
7577                docs <http://www.oracle.com/technetwork/articles/java/jsr356-1937161.html>`__
7578
7579             -  link: `An
7580                example <http://www.programmingforliving.com/2013/08/jsr-356-java-api-for-websocket-client-api.html>`__
7581
7582 BCP: Websocket Configuration
7583 ----------------------------
7584
7585          .. container:: paragraph
7586
7587             The probably best is to configure APEX for Websocket servers
7588             for input (ingress, consume) and output (egress, produce)
7589             interfaces. This means that APEX will start Websocket
7590             servers on named ports and wait for clients to connect.
7591             Advantage: once APEX is running all connectivity
7592             infrastructure is running as well. Consequence: if APEX is
7593             not running, everyone else is in the dark, too.
7594
7595          .. container:: paragraph
7596
7597             The best protocol to be used is JSON string. Each event on
7598             any interface is then a string with a JSON encoding. JSON
7599             string is a little bit slower than byte code, but we doubt
7600             that this will be noticeable. A further advantage of JSON
7601             strings over Websockets with APEX starting the servers: it
7602             is very easy to connect web browsers to such a system.
7603             Simple connect the web browser to the APEX sockets and
7604             send/read JSON strings.
7605
7606          .. container:: paragraph
7607
7608             Once APEX is started you simply connect Websocket clients to
7609             it, and send/receive event. When APEX is terminated, the
7610             Websocket servers go down, and the clients will be
7611             disconnected. APEX does not (yet) support auto-client
7612             reconnect nor WAMP, so clients might need to be restarted or
7613             reconnected manually after an APEX boot.
7614
7615 Demo with VPN Policy Model
7616 --------------------------
7617
7618          .. container:: paragraph
7619
7620             We assume that you have an APEX installation using the full
7621             package, i.e. APEX with all examples, of version ``0.5.6``
7622             or higher. We will use the VPN policy from the APEX examples
7623             here.
7624
7625          .. container:: paragraph
7626
7627             Now, have the following ready to start the demo:
7628
7629          .. container:: ulist
7630
7631             -  3 terminals on the host where APEX is running (we need 1
7632                for APEX and 1 for each client)
7633
7634             -  the events in the file
7635                ``$APEX_HOME/examples/events/VPN/SetupEvents.json`` open
7636                in an editor (we need to send those events to APEX)
7637
7638             -  the events in the file
7639                ``$APEX_HOME/examples/events/VPN/Link09Events.json`` open
7640                in an editor (we need to send those events to APEX)
7641
7642 A Websocket Configuration for the VPN Domain
7643 ############################################
7644
7645             .. container:: paragraph
7646
7647                Create a new APEX configuration using the VPN policy
7648                model and configuring APEX as discussed above for
7649                Websockets. Copy the following configuration into
7650                ``$APEX_HOME/examples/config/VPN/Ws2WsServerAvroContextJsonEvent.json``
7651                (for Windows use
7652                ``%APEX_HOME%\examples\config\VPN\Ws2WsServerAvroContextJsonEvent.json``):
7653
7654             .. container:: listingblock
7655
7656                .. container:: content
7657
7658                   .. code::
7659                     :number-lines:
7660
7661                     {
7662                       "engineServiceParameters" : {
7663                         "name"          : "VPNApexEngine",
7664                         "version"        : "0.0.1",
7665                         "id"             :  45,
7666                         "instanceCount"  : 1,
7667                         "deploymentPort" : 12345,
7668                         "policyModelFileName" : "examples/models/VPN/VPNPolicyModelAvro.json",
7669                         "engineParameters"    : {
7670                           "executorParameters" : {
7671                             "MVEL" : {
7672                               "parameterClassName" : "org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters"
7673                             }
7674                           },
7675                           "contextParameters" : {
7676                             "parameterClassName" : "org.onap.policy.apex.context.parameters.ContextParameters",
7677                             "schemaParameters":{
7678                               "Avro":{
7679                                 "parameterClassName" : "org.onap.policy.apex.plugins.context.schema.avro.AvroSchemaHelperParameters"
7680                               }
7681                             }
7682                           }
7683                         }
7684                       },
7685                       "producerCarrierTechnologyParameters" : {
7686                         "carrierTechnology" : "WEBSOCKET",
7687                         "parameterClassName" : "org.onap.policy.apex.plugins.event.carrier.websocket.WEBSOCKETCarrierTechnologyParameters",
7688                         "parameters" : {
7689                           "wsClient" : false,
7690                           "port"     : 42452
7691                         }
7692                       },
7693                       "producerEventProtocolParameters" : {
7694                         "eventProtocol" : "JSON"
7695                       },
7696                       "consumerCarrierTechnologyParameters" : {
7697                         "carrierTechnology" : "WEBSOCKET",
7698                         "parameterClassName" : "org.onap.policy.apex.plugins.event.carrier.websocket.WEBSOCKETCarrierTechnologyParameters",
7699                         "parameters" : {
7700                          "wsClient" : false,
7701                           "port"     : 42450
7702                         }
7703                       },
7704                       "consumerEventProtocolParameters" : {
7705                         "eventProtocol" : "JSON"
7706                       }
7707                     }
7708
7709 Start APEX Engine
7710 #################
7711
7712    .. container:: paragraph
7713
7714       In a new terminal, start APEX with the new configuration for
7715       Websocket-Server ingress/egress:
7716
7717    .. container:: listingblock
7718
7719       .. container:: content
7720
7721          .. code::
7722             :number-lines:
7723
7724             #: $APEX_HOME/bin/apexEngine.sh -c $APEX_HOME/examples/config/VPN/Ws2WsServerAvroContextJsonEvent.json
7725
7726 .. container:: listingblock
7727
7728    .. container:: content
7729
7730       .. code::
7731         :number-lines:
7732
7733         #: %APEX_HOME%\bin\apexEngine.bat -c %APEX_HOME%\examples\config\VPN\Ws2WsServerAvroContextJsonEvent.json
7734
7735 .. container:: paragraph
7736
7737    Wait for APEX to start, it takes a while to create all Websocket
7738    servers (about 8 seconds on a standard laptop without cached
7739    binaries). depending on your log messages, you will see no (some, a
7740    lot) log messages. If APEX starts correctly, the last few messages
7741    you should see are:
7742
7743 .. container:: listingblock
7744
7745    .. container:: content
7746
7747       .. code::
7748         :number-lines:
7749
7750          2017-07-28 13:17:20,834 Apex [main] INFO c.e.a.s.engine.runtime.EngineService - engine model VPNPolicyModelAvro:0.0.1 added to the engine-AxArtifactKey:(name=VPNApexEngine-0,version=0.0.1)
7751          2017-07-28 13:17:21,057 Apex [Apex-apex-engine-service-0:0] INFO c.e.a.s.engine.runtime.EngineService - Engine AxArtifactKey:(name=VPNApexEngine-0,version=0.0.1) processing ...
7752          2017-07-28 13:17:21,296 Apex [main] INFO c.e.a.s.e.r.impl.EngineServiceImpl - Added the action listener to the engine
7753          Started Apex service
7754
7755 .. container:: paragraph
7756
7757    APEX is running in the new terminal and will produce output when the
7758    policy is triggered/executed.
7759
7760 Run the Websocket Echo Client
7761 #############################
7762
7763    .. container:: paragraph
7764
7765       The echo client is included in an APEX full installation. To run
7766       the client, open a new shell (Unix, Cygwin) or command prompt
7767       (``cmd`` on Windows). Then use the APEX application launcher to
7768       start the client.
7769
7770    .. important::  
7771       APEX engine needs to run first
7772       The example assumes that an APEX engine configured for *produce* carrier technology Websocket and *JSON* event protocol is executed first.
7773
7774    +---------------------------------------------------------+-----------------------------------------------------------+
7775    | Unix, Cygwin                                            | Windows                                                   |
7776    +=========================================================+===========================================================+
7777    | .. container::                                          | .. container::                                            |
7778    |                                                         |                                                           |
7779    |    .. container:: listingblock                          |    .. container:: listingblock                            |
7780    |                                                         |                                                           |
7781    |       .. container:: content                            |       .. container:: content                              |
7782    |                                                         |                                                           |
7783    |          .. code::                                      |          .. code::                                        |
7784    |                                                         |                                                           |
7785    |             # $APEX_HOME/bin/apexApps.sh ws-echo [args] |             > %APEX_HOME%\bin\apexApps.bat ws-echo [args] |
7786    +---------------------------------------------------------+-----------------------------------------------------------+
7787
7788    .. container:: paragraph
7789
7790       Use the following command line arguments for server and port of
7791       the Websocket server. The port should be the same as configured in
7792       the APEX engine. The server host should be the host on which the
7793       APEX engine is running
7794
7795    .. container:: ulist
7796
7797       -  ``-p`` defines the Websocket port to connect to (defaults to
7798          ``8887``)
7799
7800       -  ``-s`` defines the host on which a Websocket server is running
7801          (defaults to ``localhost``)
7802
7803    .. container:: paragraph
7804
7805       Let’s assume that there is an APEX engine running, configured for
7806       produce Websocket carrier technology, as server, for port 42452,
7807       with produce event protocol JSON,. If we start the console client
7808       on the same host, we can omit the ``-s`` options. We start the
7809       console client as:
7810
7811    .. container:: listingblock
7812
7813       .. container:: content
7814
7815          .. code::
7816
7817             # $APEX_HOME/bin/apexApps.sh ws-echo -p 42452 (1)
7818             > %APEX_HOME%\bin\apexApps.bat ws-echo -p 42452 (2)
7819
7820    .. container:: colist arabic
7821
7822       +-------+--------------------------------+
7823       | **1** | Start client on Unix or Cygwin |
7824       +-------+--------------------------------+
7825       | **2** | Start client on Windows        |
7826       +-------+--------------------------------+
7827
7828    .. container:: paragraph
7829
7830       Once started successfully, the client will produce the following
7831       messages (assuming we used ``-p 42452`` and an APEX engine is
7832       running on ``localhost`` with the same port:
7833
7834    .. container:: listingblock
7835
7836       .. container:: content
7837
7838          .. code::
7839
7840             ws-simple-echo: starting simple event echo
7841              --> server: localhost
7842              --> port: 42452
7843
7844             Once started, the application will simply print out all received events to standard out.
7845             Each received event will be prefixed by '---' and suffixed by '===='
7846
7847
7848             ws-simple-echo: opened connection to APEX (Web Socket Protocol Handshake)
7849
7850 Run the Websocket Console Client
7851 ################################
7852
7853    .. container:: paragraph
7854
7855       The console client is included in an APEX full installation. To
7856       run the client, open a new shell (Unix, Cygwin) or command prompt
7857       (``cmd`` on Windows). Then use the APEX application launcher to
7858       start the client.
7859
7860    .. important::  
7861       APEX engine needs to run first
7862       The example assumes that an APEX engine configured for *consume* carrier technology Websocket and *JSON* event
7863       protocol is executed first.
7864
7865    +------------------------------------------------------------+--------------------------------------------------------------+
7866    | Unix, Cygwin                                               | Windows                                                      |
7867    +============================================================+==============================================================+
7868    | .. container::                                             | .. container::                                               |
7869    |                                                            |                                                              |
7870    |    .. container:: listingblock                             |    .. container:: listingblock                               |
7871    |                                                            |                                                              |
7872    |       .. container:: content                               |       .. container:: content                                 |
7873    |                                                            |                                                              |
7874    |          .. code::                                         |          .. code::                                           |
7875    |                                                            |                                                              |
7876    |             # $APEX_HOME/bin/apexApps.sh ws-console [args] |             > %APEX_HOME%\bin\apexApps.bat ws-console [args] |
7877    +------------------------------------------------------------+--------------------------------------------------------------+
7878
7879    .. container:: paragraph
7880
7881       Use the following command line arguments for server and port of
7882       the Websocket server. The port should be the same as configured in
7883       the APEX engine. The server host should be the host on which the
7884       APEX engine is running
7885
7886    .. container:: ulist
7887
7888       -  ``-p`` defines the Websocket port to connect to (defaults to
7889          ``8887``)
7890
7891       -  ``-s`` defines the host on which a Websocket server is running
7892          (defaults to ``localhost``)
7893
7894    .. container:: paragraph
7895
7896       Let’s assume that there is an APEX engine running, configured for
7897       consume Websocket carrier technology, as server, for port 42450,
7898       with consume event protocol JSON,. If we start the console client
7899       on the same host, we can omit the ``-s`` options. We start the
7900       console client as:
7901
7902    .. container:: listingblock
7903
7904       .. container:: content
7905
7906          .. code::
7907
7908             # $APEX_HOME/bin/apexApps.sh ws-console -p 42450 (1)
7909             > %APEX_HOME%\bin\apexApps.sh ws-console -p 42450 (2)
7910
7911    .. container:: colist arabic
7912
7913       +-------+--------------------------------+
7914       | **1** | Start client on Unix or Cygwin |
7915       +-------+--------------------------------+
7916       | **2** | Start client on Windows        |
7917       +-------+--------------------------------+
7918
7919    .. container:: paragraph
7920
7921       Once started successfully, the client will produce the following
7922       messages (assuming we used ``-p 42450`` and an APEX engine is
7923       running on ``localhost`` with the same port:
7924
7925    .. container:: listingblock
7926
7927       .. container:: content
7928
7929          .. code::
7930
7931             ws-simple-console: starting simple event console
7932              --> server: localhost
7933              --> port: 42450
7934
7935              - terminate the application typing 'exit<enter>' or using 'CTRL+C'
7936              - events are created by a non-blank starting line and terminated by a blank line
7937
7938
7939             ws-simple-console: opened connection to APEX (Web Socket Protocol Handshake)
7940
7941 Send Events
7942 ###########
7943
7944    .. container:: paragraph
7945
7946       Now you have the full system up and running:
7947
7948    .. container:: ulist
7949
7950       -  Terminal 1: APEX ready and loaded
7951
7952       -  Terminal 2: an echo client, printing received messages produced
7953          by the VPN policy
7954
7955       -  Terminal 2: a console client, waiting for input on the console
7956          (standard in) and sending text to APEX
7957
7958    .. container:: paragraph
7959
7960       We started the engine with the VPN policy example. So all the
7961       events we are using now are located in files in the following
7962       example directory:
7963
7964    .. container:: listingblock
7965
7966       .. container:: content
7967
7968          .. code::
7969            :number-lines:
7970
7971            #: $APEX_HOME/examples/events/VPN
7972            > %APEX_HOME%\examples\events\VPN
7973
7974 .. container:: paragraph
7975
7976    To sends events, simply copy the content of the event files into
7977    Terminal 3 (the console client). It will read multi-line JSON text
7978    and send the events. So copy the content of ``SetupEvents.json`` into
7979    the client. APEX will trigger a policy and produce some output, the
7980    echo client will also print some events created in the policy. In
7981    Terminal 1 (APEX) you’ll see some status messages from the policy as:
7982
7983 .. container:: listingblock
7984
7985    .. container:: content
7986
7987       .. code::
7988         :number-lines:
7989
7990         {Link=L09, LinkUp=true}
7991         L09     true
7992         outFields: {Link=L09, LinkUp=true}
7993         {Link=L10, LinkUp=true}
7994         L09     true
7995         L10     true
7996         outFields: {Link=L10, LinkUp=true}
7997         {CustomerName=C, LinkList=L09 L10, SlaDT=300, YtdDT=300}
7998         *** Customers ***
7999         C       300     300     [L09, L10]
8000         outFields: {CustomerName=C, LinkList=L09 L10, SlaDT=300, YtdDT=300}
8001         {CustomerName=A, LinkList=L09 L10, SlaDT=300, YtdDT=50}
8002         *** Customers ***
8003         A       300     50      [L09, L10]
8004         C       300     300     [L09, L10]
8005         outFields: {CustomerName=A, LinkList=L09 L10, SlaDT=300, YtdDT=50}
8006         {CustomerName=D, LinkList=L09 L10, SlaDT=300, YtdDT=400}
8007         *** Customers ***
8008         A       300     50      [L09, L10]
8009         C       300     300     [L09, L10]
8010         D       300     400     [L09, L10]
8011         outFields: {CustomerName=D, LinkList=L09 L10, SlaDT=300, YtdDT=400}
8012         {CustomerName=B, LinkList=L09 L10, SlaDT=300, YtdDT=299}
8013         *** Customers ***
8014         A       300     50      [L09, L10]
8015         B       300     299     [L09, L10]
8016         C       300     300     [L09, L10]
8017         D       300     400     [L09, L10]
8018         outFields: {CustomerName=B, LinkList=L09 L10, SlaDT=300, YtdDT=299}
8019
8020 .. container:: paragraph
8021
8022    In Terminal 2 (echo-client) you see the received events, the last two
8023    should look like:
8024
8025 .. container:: listingblock
8026
8027    .. container:: content
8028
8029       .. code::
8030         :number-lines:
8031
8032         ws-simple-echo: received
8033         ---------------------------------
8034         {
8035           "name": "VPNCustomerCtxtActEvent",
8036           "version": "0.0.1",
8037           "nameSpace": "org.onap.policy.apex.domains.vpn.events",
8038           "source": "Source",
8039           "target": "Target",
8040           "CustomerName": "C",
8041           "LinkList": "L09 L10",
8042           "SlaDT": 300,
8043           "YtdDT": 300
8044         }
8045         =================================
8046
8047         ws-simple-echo: received
8048         ---------------------------------
8049         {
8050           "name": "VPNCustomerCtxtActEvent",
8051           "version": "0.0.1",
8052           "nameSpace": "org.onap.policy.apex.domains.vpn.events",
8053           "source": "Source",
8054           "target": "Target",
8055           "CustomerName": "D",
8056           "LinkList": "L09 L10",
8057           "SlaDT": 300,
8058           "YtdDT": 400
8059         }
8060         =================================
8061
8062 .. container:: paragraph
8063
8064    Congratulations, you have triggered a policy in APEX using
8065    Websockets, the policy did run through, created events, picked up by
8066    the echo-client.
8067
8068 .. container:: paragraph
8069
8070    Now you can send the Link 09 and Link 10 events, they will trigger
8071    the actual VPN policy and some calculations are made. Let’s take the
8072    Link 09 events from ``Link09Events.json``, copy them all into
8073    Terminal 3 (the console). APEX will run the policy (with some status
8074    output), and the echo client will receive and print events.
8075
8076 .. container:: paragraph
8077
8078    To terminate the applications, simply press ``CTRL+C`` in Terminal 1
8079    (APEX). This will also terminate the echo-client in Terminal 2. Then
8080    type ``exit<enter>`` in Terminal 3 (or ``CTRL+C``) to terminate the
8081    console-client.
8082
8083 .. container::
8084    :name: footer
8085
8086    .. container::
8087       :name: footer-text
8088
8089       2.0.0-SNAPSHOT
8090       Last updated 2018-09-10 15:38:16 IST
8091
8092 .. |Extract the TAR archive| image:: images/install-guide/win-extract-tar-gz.png
8093 .. |Extract the APEX distribution| image:: images/install-guide/win-extract-tar.png
8094 .. |REST Editor Start Screen| image:: images/install-guide/rest-start.png
8095 .. |REST Editor with loaded SampleDomain Policy Model| image:: images/install-guide/rest-loaded.png
8096 .. |APEX Configuration Matrix| image:: images/apex-intro/ApexEngineConfig.png
8097 .. |File > New to create a new Policy Model| image:: images/mfp/MyFirstPolicy_P1_newPolicyModel1.png
8098 .. |Create a new Policy Model| image:: images/mfp/MyFirstPolicy_P1_newPolicyModel2.png
8099 .. |Right click to create a new event| image:: images/mfp/MyFirstPolicy_P1_newEvent1.png
8100 .. |Fill in the necessary information for the 'SALE_INPUT' event and click 'Submit'| image:: images/mfp/MyFirstPolicy_P1_newEvent2.png
8101 .. |Right click to create a new Item Schema| image:: images/mfp/MyFirstPolicy_P1_newItemSchema1.png
8102 .. |Create a new Item Schema| image:: images/mfp/MyFirstPolicy_P1_newItemSchema2.png
8103 .. |Add new event parameters to an event| image:: images/mfp/MyFirstPolicy_P1_newEvent3.png
8104 .. |Right click to create a new task| image:: images/mfp/MyFirstPolicy_P1_newTask1.png
8105 .. |Add input and out fields for the task| image:: images/mfp/MyFirstPolicy_P1_newTask2.png
8106 .. |Add task logic the task| image:: images/mfp/MyFirstPolicy_P1_newTask3.png
8107 .. |Create a new policy| image:: images/mfp/MyFirstPolicy_P1_newPolicy1.png
8108 .. |Create a state| image:: images/mfp/MyFirstPolicy_P1_newState1.png
8109 .. |Add a Task and Output Mapping| image:: images/mfp/MyFirstPolicy_P1_newState2.png
8110 .. |Validate the policy model for error using the 'Model' > 'Validate' menu item| image:: images/mfp/MyFirstPolicy_P1_validatePolicyModel.png
8111 .. |Download the completed policy model using the 'File' > 'Download' menu item| image:: images/mfp/MyFirstPolicy_P1_exportPolicyModel1.png
8112 .. |Create a new alternative task MorningBoozeCheckAlt1| image:: images/mfp/MyFirstPolicy_P2_newTask1.png
8113 .. |Right click to edit a policy| image:: images/mfp/MyFirstPolicy_P2_editPolicy1.png
8114 .. |State definition with 2 Tasks and Task Selection Logic| image:: images/mfp/MyFirstPolicy_P2_editState1.png
8115