aboutsummaryrefslogtreecommitdiffstats
path: root/services/services-engine/src/main/java/org/onap/policy/apex/service/engine/runtime/impl/EngineWorker.java
blob: a7d17995957efbe44ae3de54d1a28ccd999259e0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.apex.service.engine.runtime.impl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.BlockingQueue;

import org.onap.policy.apex.context.ContextException;
import org.onap.policy.apex.context.ContextRuntimeException;
import org.onap.policy.apex.context.SchemaHelper;
import org.onap.policy.apex.context.impl.schema.SchemaHelperFactory;
import org.onap.policy.apex.core.engine.engine.ApexEngine;
import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory;
import org.onap.policy.apex.core.engine.event.EnEvent;
import org.onap.policy.apex.core.infrastructure.threading.ApplicationThreadFactory;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
import org.onap.policy.apex.model.basicmodel.handling.ApexModelException;
import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader;
import org.onap.policy.apex.model.basicmodel.handling.ApexModelWriter;
import org.onap.policy.apex.model.basicmodel.service.ModelService;
import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum;
import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums;
import org.onap.policy.apex.model.enginemodel.concepts.AxEngineModel;
import org.onap.policy.apex.model.enginemodel.concepts.AxEngineState;
import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
import org.onap.policy.apex.service.engine.event.ApexEvent;
import org.onap.policy.apex.service.engine.event.impl.enevent.ApexEvent2EnEventConverter;
import org.onap.policy.apex.service.engine.runtime.ApexEventListener;
import org.onap.policy.apex.service.engine.runtime.EngineService;
import org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;

/**
 * The Class EngineWorker encapsulates a core {@link ApexEngine} instance, which runs policies
 * defined in the {@link org.onap.policy.apex.model.basicmodel.concepts.AxModelAxModel}. Each policy
 * is triggered by an Apex event, and when the policy is triggered it runs through to completion in
 * the ApexEngine.
 *
 * <p>This class acts as a container for an {@link ApexEngine}, running it in a thread, sending it
 * events, and receiving events from it.
 *
 * @author Liam Fallon (liam.fallon@ericsson.com)
 */
final class EngineWorker implements EngineService {
    // Logger for this class
    private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngineService.class);

    // Recurring string constants
    private static final String ENGINE_FOR_KEY_PREFIX = "apex engine for engine key ";
    private static final String ENGINE_SUFFIX = " of this engine";
    private static final String BAD_KEY_MATCH_TAG = " does not match the key";
    private static final String ENGINE_KEY_PREFIX = "engine key ";

    // The ID of this engine
    private final AxArtifactKey engineWorkerKey;

    // The Apex engine which is running the policies in this worker
    private final ApexEngine engine;

    // The event processor is an inner class, an instance of which runs as a thread that reads
    // incoming events from a queue and forwards them to the Apex engine
    private EventProcessor processor = null;

    // Thread handling for the worker
    private final ApplicationThreadFactory threadFactory;
    private Thread processorThread;

    // Converts ApexEvent instances to and from EnEvent instances
    private ApexEvent2EnEventConverter apexEnEventConverter = null;

    /**
     * Constructor that creates an Apex engine, an event processor for events to be sent to that
     * engine, and an {@link ApexModelReader} instance to read Apex models using JAXB.
     *
     * @param engineWorkerKey the engine worker key
     * @param queue the queue on which events for this Apex worker will come
     * @param threadFactory the thread factory to use for creating the event processing thread
     * @throws ApexException thrown on errors on worker instantiation
     */
    protected EngineWorker(final AxArtifactKey engineWorkerKey, final BlockingQueue<ApexEvent> queue,
            final ApplicationThreadFactory threadFactory) {
        LOGGER.entry(engineWorkerKey);

        this.engineWorkerKey = engineWorkerKey;
        this.threadFactory = threadFactory;

        // Create the Apex engine
        engine = new ApexEngineFactory().createApexEngine(engineWorkerKey);

        // Create and run the event processor
        processor = new EventProcessor(queue);

        // Set the Event converter up
        apexEnEventConverter = new ApexEvent2EnEventConverter(engine);

        LOGGER.exit();
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.onap.policy.apex.service.engine.runtime.EngineService#registerActionListener(java.lang.
     * String, org.onap.policy.apex.service.engine.runtime.ApexEventListener)
     */
    @Override
    public void registerActionListener(final String listenerName, final ApexEventListener apexEventListener) {
        engine.addEventListener(listenerName, new EnEventListenerImpl(apexEventListener, apexEnEventConverter));
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.onap.policy.apex.service.engine.runtime.EngineService#deregisterActionListener(java.lang.
     * String)
     */
    @Override
    public void deregisterActionListener(final String listenerName) {
        engine.removeEventListener(listenerName);
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.onap.policy.apex.service.engine.runtime.EngineService#getEngineServiceEventInterface()
     */
    @Override
    public EngineServiceEventInterface getEngineServiceEventInterface() {
        throw new UnsupportedOperationException(
                "getEngineServiceEventInterface() call is not allowed on an Apex Engine Worker");
    }

    /*
     * (non-Javadoc)
     *
     * @see org.onap.policy.apex.service.engine.runtime.EngineService#getKey()
     */
    @Override
    public AxArtifactKey getKey() {
        return engineWorkerKey;
    }

    /*
     * (non-Javadoc)
     *
     * @see org.onap.policy.apex.service.engine.runtime.EngineService#getInfo()
     */
    @Override
    public Collection<AxArtifactKey> getEngineKeys() {
        return Arrays.asList(engineWorkerKey);
    }

    /*
     * (non-Javadoc)
     *
     * @see org.onap.policy.apex.service.engine.runtime.EngineService#getApexModelKey()
     */
    @Override
    public AxArtifactKey getApexModelKey() {
        if (ModelService.existsModel(AxPolicyModel.class)) {
            return ModelService.getModel(AxPolicyModel.class).getKey();
        } else {
            return null;
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.onap.policy.apex.service.engine.runtime.EngineService#updateModel(org.onap.policy.apex.
     * model. basicmodel.concepts.AxArtifactKey, java.lang.String, boolean)
     */
    @Override
    public void updateModel(final AxArtifactKey engineKey, final String engineModel, final boolean forceFlag)
            throws ApexException {
        LOGGER.entry(engineKey);

        // Read the Apex model into memory using the Apex Model Reader
        AxPolicyModel apexPolicyModel = null;
        try {
            final ApexModelReader<AxPolicyModel> modelReader = new ApexModelReader<>(AxPolicyModel.class);
            apexPolicyModel = modelReader.read(new ByteArrayInputStream(engineModel.getBytes()));
        } catch (final ApexModelException e) {
            LOGGER.error("failed to unmarshal the apex model on engine " + engineKey.getId(), e);
            throw new ApexException("failed to unmarshal the apex model on engine " + engineKey.getId(), e);
        }

        // Update the Apex model in the Apex engine
        updateModel(engineKey, apexPolicyModel, forceFlag);

        LOGGER.exit();
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.onap.policy.apex.service.engine.runtime.EngineService#updateModel(org.onap.policy.apex.
     * model. basicmodel.concepts.AxArtifactKey,
     * org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel, boolean)
     */
    @Override
    public void updateModel(final AxArtifactKey engineKey, final AxPolicyModel apexModel, final boolean forceFlag)
            throws ApexException {
        LOGGER.entry(engineKey);

        // Check if the key on the update request is correct
        if (!engineWorkerKey.equals(engineKey)) {
            String message = ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId()
                    + ENGINE_SUFFIX;
            LOGGER.warn(message);
            throw new ApexException(message);
        }

        // Check model compatibility
        if (ModelService.existsModel(AxPolicyModel.class)) {
            // The current policy model may or may not be defined
            final AxPolicyModel currentModel = ModelService.getModel(AxPolicyModel.class);
            if (!currentModel.getKey().isCompatible(apexModel.getKey())) {
                if (forceFlag) {
                    LOGGER.warn("apex model update forced, supplied model with key \"" + apexModel.getKey().getId()
                            + "\" is not a compatible model update from the existing engine model with key \""
                            + currentModel.getKey().getId() + "\"");
                } else {
                    throw new ContextException(
                            "apex model update failed, supplied model with key \"" + apexModel.getKey().getId()
                                    + "\" is not a compatible model update from the existing engine model with key \""
                                    + currentModel.getKey().getId() + "\"");
                }
            }
        }

        // Update the Apex model in the Apex engine
        engine.clear();
        engine.updateModel(apexModel);

        LOGGER.debug("engine model {} added to the engine-{}", apexModel.getKey().getId(), engineWorkerKey);
        LOGGER.exit();
    }

    /*
     * (non-Javadoc)
     *
     * @see org.onap.policy.apex.service.engine.runtime.EngineService#getState()
     */
    @Override
    public AxEngineState getState() {
        return engine.getState();
    }

    /*
     * (non-Javadoc)
     *
     * @see org.onap.policy.apex.service.engine.runtime.EngineService#startAll()
     */
    @Override
    public void startAll() throws ApexException {
        start(this.getKey());
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.onap.policy.apex.service.engine.runtime.EngineService#start(org.onap.policy.apex.core.
     * model. concepts.AxArtifactKey)
     */
    @Override
    public void start(final AxArtifactKey engineKey) throws ApexException {
        LOGGER.entry(engineKey);

        // Check if the key on the start request is correct
        if (!engineWorkerKey.equals(engineKey)) {
            LOGGER.warn(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId()
                    + ENGINE_SUFFIX);
            throw new ApexException(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG
                    + engineWorkerKey.getId() + ENGINE_SUFFIX);
        }

        // Starts the event processing thread that handles incoming events
        if (processorThread != null && processorThread.isAlive()) {
            String message = ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is already running with state "
                    + getState();
            LOGGER.error(message);
            throw new ApexException(message);
        }

        // Start the engine
        engine.start();

        // Start a thread to process events for the engine
        processorThread = threadFactory.newThread(processor);
        processorThread.start();

        LOGGER.exit(engineKey);
    }

    /*
     * (non-Javadoc)
     *
     * @see org.onap.policy.apex.service.engine.runtime.EngineService#stop()
     */
    @Override
    public void stop() throws ApexException {
        stop(this.getKey());
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.onap.policy.apex.service.engine.runtime.EngineService#stop(org.onap.policy.apex.core.
     * model. concepts.AxArtifactKey)
     */
    @Override
    public void stop(final AxArtifactKey engineKey) throws ApexException {
        // Check if the key on the start request is correct
        if (!engineWorkerKey.equals(engineKey)) {
            LOGGER.warn(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId()
                    + ENGINE_SUFFIX);
            throw new ApexException(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG
                    + engineWorkerKey.getId() + ENGINE_SUFFIX);
        }

        // Interrupt the worker to stop its thread
        if (processorThread == null || !processorThread.isAlive()) {
            processorThread = null;

            LOGGER.warn(ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is already stopped with state "
                    + getState());
            return;
        }

        // Interrupt the thread that is handling events toward the engine
        processorThread.interrupt();
        processorThread = null;

        // Stop the engine
        engine.stop();

        LOGGER.exit(engineKey);
    }

    /*
     * (non-Javadoc)
     *
     * @see org.onap.policy.apex.service.engine.runtime.EngineService#clear()
     */
    @Override
    public void clear() throws ApexException {
        clear(this.getKey());
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.onap.policy.apex.service.engine.runtime.EngineService#clear(org.onap.policy.apex.core.
     * model. concepts.AxArtifactKey)
     */
    @Override
    public void clear(final AxArtifactKey engineKey) throws ApexException {
        // Check if the key on the start request is correct
        if (!engineWorkerKey.equals(engineKey)) {
            LOGGER.warn(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG + engineWorkerKey.getId()
                    + ENGINE_SUFFIX);
            throw new ApexException(ENGINE_KEY_PREFIX + engineKey.getId() + BAD_KEY_MATCH_TAG
                    + engineWorkerKey.getId() + ENGINE_SUFFIX);
        }

        // Interrupt the worker to stop its thread
        if (processorThread != null && !processorThread.isAlive()) {
            LOGGER.warn(ENGINE_FOR_KEY_PREFIX + engineWorkerKey.getId() + " is not stopped with state "
                    + getState());
            return;
        }

        // Clear the engine
        engine.clear();

        LOGGER.exit(engineKey);
    }

    /*
     * (non-Javadoc)
     *
     * @see org.onap.policy.apex.service.engine.runtime.EngineService#isStarted()
     */
    @Override
    public boolean isStarted() {
        return isStarted(this.getKey());
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.onap.policy.apex.service.engine.runtime.EngineService#isStarted(org.onap.policy.apex.
     * model. basicmodel.concepts.AxArtifactKey)
     */
    @Override
    public boolean isStarted(final AxArtifactKey engineKey) {
        final AxEngineState engstate = getState();
        switch (engstate) {
            case STOPPED:
            case STOPPING:
            case UNDEFINED:
                return false;
            case EXECUTING:
            case READY:
                return processorThread != null && processorThread.isAlive() && !processorThread.isInterrupted();
            default:
                break;
        }
        return false;
    }

    /*
     * (non-Javadoc)
     *
     * @see org.onap.policy.apex.service.engine.runtime.EngineService#isStopped()
     */
    @Override
    public boolean isStopped() {
        return isStopped(this.getKey());
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.onap.policy.apex.service.engine.runtime.EngineService#isStopped(org.onap.policy.apex.
     * model. basicmodel.concepts.AxArtifactKey)
     */
    @Override
    public boolean isStopped(final AxArtifactKey engineKey) {
        final AxEngineState engstate = getState();
        switch (engstate) {
            case STOPPING:
            case UNDEFINED:
            case EXECUTING:
            case READY:
                return false;
            case STOPPED:
                return processorThread == null || !processorThread.isAlive();
            default:
                break;
        }
        return false;
    }

    /*
     * (non-Javadoc)
     *
     * @see org.onap.policy.apex.service.engine.runtime.EngineService#startPeriodicEvents(long)
     */
    @Override
    public void startPeriodicEvents(final long period) {
        throw new UnsupportedOperationException("startPeriodicEvents() call is not allowed on an Apex Engine Worker");
    }

    /*
     * (non-Javadoc)
     *
     * @see org.onap.policy.apex.service.engine.runtime.EngineService#stopPeriodicEvents()
     */
    @Override
    public void stopPeriodicEvents() {
        throw new UnsupportedOperationException("stopPeriodicEvents() call is not allowed on an Apex Engine Worker");
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.onap.policy.apex.service.engine.runtime.EngineService#getStatus(org.onap.policy.apex.core
     * .model .concepts.AxArtifactKey)
     */
    @Override
    public String getStatus(final AxArtifactKey engineKey) {
        // Get the information from the engine that we want to return
        final AxEngineModel apexEngineModel = engine.getEngineStatus();
        apexEngineModel.getKeyInformation().generateKeyInfo(apexEngineModel);

        // Convert that information into a string
        try {
            final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream();
            final ApexModelWriter<AxEngineModel> modelWriter = new ApexModelWriter<>(AxEngineModel.class);
            modelWriter.setJsonOutput(true);
            modelWriter.write(apexEngineModel, baOutputStream);
            return baOutputStream.toString();
        } catch (final Exception e) {
            LOGGER.warn("error outputting runtime information for engine {}", engineWorkerKey, e);
            return null;
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see
     * org.onap.policy.apex.service.engine.runtime.EngineService#getRuntimeInfo(org.onap.policy.apex
     * .core.model.concepts.AxArtifactKey)
     */
    @Override
    public String getRuntimeInfo(final AxArtifactKey engineKey) {
        // We'll build up the JSON string for runtime information bit by bit
        final StringBuilder runtimeJsonStringBuilder = new StringBuilder();

        // Get the engine information
        final AxEngineModel engineModel = engine.getEngineStatus();
        final Map<AxArtifactKey, Map<String, Object>> engineContextAlbums = engine.getEngineContext();

        // Use GSON to convert our context information into JSON
        final Gson gson = new GsonBuilder().setPrettyPrinting().create();

        // Get context into a JSON string
        runtimeJsonStringBuilder.append("{\"TimeStamp\":");
        runtimeJsonStringBuilder.append(engineModel.getTimestamp());
        runtimeJsonStringBuilder.append(",\"State\":");
        runtimeJsonStringBuilder.append(engineModel.getState());
        runtimeJsonStringBuilder.append(",\"Stats\":");
        runtimeJsonStringBuilder.append(gson.toJson(engineModel.getStats()));

        // Get context into a JSON string
        runtimeJsonStringBuilder.append(",\"ContextAlbums\":[");

        boolean firstAlbum = true;
        for (final Entry<AxArtifactKey, Map<String, Object>> contextAlbumEntry : engineContextAlbums.entrySet()) {
            if (firstAlbum) {
                firstAlbum = false;
            } else {
                runtimeJsonStringBuilder.append(",");
            }

            runtimeJsonStringBuilder.append("{\"AlbumKey\":");
            runtimeJsonStringBuilder.append(gson.toJson(contextAlbumEntry.getKey()));
            runtimeJsonStringBuilder.append(",\"AlbumContent\":[");


            // Get the schema helper to use to marshal context album objects to JSON
            final AxContextAlbum axContextAlbum =
                    ModelService.getModel(AxContextAlbums.class).get(contextAlbumEntry.getKey());
            SchemaHelper schemaHelper = null;

            try {
                // Get a schema helper to manage the translations between objects on the album map
                // for this album
                schemaHelper = new SchemaHelperFactory().createSchemaHelper(axContextAlbum.getKey(),
                        axContextAlbum.getItemSchema());
            } catch (final ContextRuntimeException e) {
                final String resultString =
                        "could not find schema helper to marshal context album \"" + axContextAlbum + "\" to JSON";
                LOGGER.warn(resultString, e);

                // End of context album entry
                runtimeJsonStringBuilder.append(resultString);
                runtimeJsonStringBuilder.append("]}");

                continue;
            }

            boolean firstEntry = true;
            for (final Entry<String, Object> contextEntry : contextAlbumEntry.getValue().entrySet()) {
                if (firstEntry) {
                    firstEntry = false;
                } else {
                    runtimeJsonStringBuilder.append(",");
                }
                runtimeJsonStringBuilder.append("{\"EntryName\":");
                runtimeJsonStringBuilder.append(gson.toJson(contextEntry.getKey()));
                runtimeJsonStringBuilder.append(",\"EntryContent\":");
                runtimeJsonStringBuilder.append(gson.toJson(schemaHelper.marshal2String(contextEntry.getValue())));

                // End of context entry
                runtimeJsonStringBuilder.append("}");
            }

            // End of context album entry
            runtimeJsonStringBuilder.append("]}");
        }

        runtimeJsonStringBuilder.append("]}");

        // Tidy up the JSON string
        final JsonParser jsonParser = new JsonParser();
        final JsonElement jsonElement = jsonParser.parse(runtimeJsonStringBuilder.toString());
        final String tidiedRuntimeString = gson.toJson(jsonElement);

        LOGGER.debug("runtime information={}", tidiedRuntimeString);

        return tidiedRuntimeString;
    }

    /**
     * This is an event processor thread, this class decouples the events handling logic from core
     * business logic. This class runs its own thread and continuously querying the blocking queue
     * for the events that have been sent to the worker for processing by the Apex engine.
     *
     * @author Liam Fallon (liam.fallon@ericsson.com)
     */
    private class EventProcessor implements Runnable {
        private final boolean debugEnabled = LOGGER.isDebugEnabled();
        // the events queue
        private BlockingQueue<ApexEvent> eventProcessingQueue = null;

        /**
         * Constructor accepts {@link ApexEngine} and {@link BlockingQueue} type objects.
         *
         * @param eventProcessingQueue is reference of {@link BlockingQueue} which contains trigger
         *        events.
         */
        EventProcessor(final BlockingQueue<ApexEvent> eventProcessingQueue) {
            this.eventProcessingQueue = eventProcessingQueue;
        }

        /*
         * (non-Javadoc)
         *
         * @see java.lang.Runnable#run()
         */
        @Override
        public void run() {
            LOGGER.debug("Engine {} processing ... ", engineWorkerKey);

            // Take events from the event processing queue of the worker and pass them to the engine
            // for processing
            boolean stopFlag = false;
            while (!processorThread.isInterrupted() && ! stopFlag) {
                ApexEvent event = null;
                try {
                    event = eventProcessingQueue.take();
                } catch (final InterruptedException e) {
                    // restore the interrupt status
                    Thread.currentThread().interrupt();
                    LOGGER.debug("Engine {} processing interrupted ", engineWorkerKey);
                    break;
                }

                try {
                    if (event != null) {
                        debugEventIfDebugEnabled(event);
                        
                        final EnEvent enevent = apexEnEventConverter.fromApexEvent(event);
                        engine.handleEvent(enevent);
                    }
                } catch (final ApexException e) {
                    LOGGER.warn("Engine {} failed to process event {}", engineWorkerKey, event.toString(), e);
                } catch (final Exception e) {
                    LOGGER.warn("Engine {} terminated processing event {}", engineWorkerKey, event.toString(), e);
                    stopFlag = true;
                }
            }
            LOGGER.debug("Engine {} completed processing", engineWorkerKey);
        }

        /**
         * Debug the event if debug is enabled.
         * 
         * @param event the event to debug
         */
        private void debugEventIfDebugEnabled(ApexEvent event) {
            if (debugEnabled) {
                LOGGER.debug("Trigger Event {} forwarded to the Apex engine", event);
            }
        }
    }
}