Merge "Add period after inheritDoc for Sonar"
[policy/apex-pdp.git] / testsuites / integration / integration-uservice-test / src / test / java / org / onap / policy / apex / testsuites / integration / uservice / engdep / EngineTestServer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  * 
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  * 
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * 
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.testsuites.integration.uservice.engdep;
22
23 import java.util.Date;
24
25 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
26 import org.onap.policy.apex.service.engine.engdep.EngDepMessagingService;
27 import org.onap.policy.apex.service.engine.event.ApexEvent;
28 import org.onap.policy.apex.service.engine.runtime.ApexEventListener;
29 import org.onap.policy.apex.service.engine.runtime.EngineService;
30 import org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface;
31 import org.onap.policy.apex.service.engine.runtime.impl.EngineServiceImpl;
32 import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters;
33 import org.slf4j.ext.XLogger;
34 import org.slf4j.ext.XLoggerFactory;
35
36 /**
37  * The Class EngineTestServer is a test Apex service used to test the performance of Apex engines.
38  *
39  * @author Liam Fallon (liam.fallon@ericsson.com)
40  */
41 public class EngineTestServer implements Runnable, EngineServiceEventInterface {
42     private static final XLogger LOGGER = XLoggerFactory.getXLogger(EngineTestServer.class);
43
44     private static final int TEST_SERVER_WAIT_TIME = 200;
45
46     // The engine service for sending events to the Apex engines and the EngDEp service for engine
47     // administration
48     private EngineService engineService = null;
49     private EngDepMessagingService messageService = null;
50
51     // The inner class used to receive and process events
52     private TestApexListener testApexListener = null;
53
54     // Status flags
55     private boolean starting = true;
56     private boolean interrupted = false;
57
58     // Parameters for the test
59     private final EngineServiceParameters parameters;
60
61     // Apex performance statistics
62     private Date statsStartDate = null;
63     private long actionEventsReceivedCount = 0;
64     private long accumulatedExecutionTime = 0;
65     private long totalActionEventsReceivedCount = 0;
66
67     private ApexEvent lastEventReceived = null;
68
69     /**
70      * Instantiates a new engine test server to test Apex performance.
71      *
72      * @param parameters the parameters
73      */
74     public EngineTestServer(final EngineServiceParameters parameters) {
75         this.parameters = parameters;
76     }
77
78     /*
79      * (non-Javadoc)
80      *
81      * @see java.lang.Runnable#run()
82      */
83     @Override
84     public void run() {
85         LOGGER.debug("engine<-->deployment  test server starting . . .");
86
87         // Set the name of the test server thread
88         Thread.currentThread().setName(EngineTestServer.class.getName());
89
90         try {
91             // Create the engine service and set the listener for events emitted by the Apex service
92             engineService = EngineServiceImpl.create(parameters);
93             testApexListener = new TestApexListener();
94             engineService.registerActionListener("testApexListener", testApexListener);
95
96             // Create the EngDep messaging service and start it
97             messageService = new EngDepMessagingService(engineService, parameters.getDeploymentPort());
98             messageService.start();
99
100             // Record the start date for statistics
101             statsStartDate = new Date();
102         } catch (final Exception e) {
103             LOGGER.error("engine<-->deployment test server exception", e);
104             e.printStackTrace();
105             return;
106         }
107         LOGGER.debug("engine<-->deployment test server started");
108
109         starting = false;
110
111         while (!interrupted) {
112             if (!ThreadUtilities.sleep(TEST_SERVER_WAIT_TIME)) {
113                 interrupted = true;
114             }
115         }
116     }
117
118     /**
119      * Stop the test server.
120      */
121     public void stopServer() {
122         LOGGER.debug("engine<-->deployment test server stopping . . .");
123
124         interrupted = true;
125         messageService.stop();
126
127         LOGGER.debug("engine<-->deployment test server stopped");
128     }
129
130     /**
131      * Checks if the test server is interrupted.
132      *
133      * @return true, if is interrupted
134      */
135     public boolean isInterrupted() {
136         return interrupted;
137     }
138
139     /**
140      * Gets the total action events received.
141      *
142      * @return the total action events received
143      */
144     public long getTotalActionEventsReceived() {
145         return totalActionEventsReceivedCount;
146     }
147
148     /**
149      * Gets the last action events received.
150      *
151      * @return the last action event received
152      */
153     public ApexEvent getLastActionEvent() {
154         return lastEventReceived;
155     }
156
157     /**
158      * Gets the Apex statistics and resets them.
159      *
160      * @return the statistics
161      */
162     public long[] getAndResetStats() {
163         // Check if we have statistics
164         if (statsStartDate == null || actionEventsReceivedCount == 0) {
165             return null;
166         }
167
168         // Calculate, save, and reset the statistics
169         final long[] stats = new long[2];
170         synchronized (statsStartDate) {
171             final long averageExecutionTime = accumulatedExecutionTime / actionEventsReceivedCount;
172             final long measuringTime = new Date().getTime() - statsStartDate.getTime();
173             final long transactionsPerMillisecond = actionEventsReceivedCount / measuringTime;
174             stats[0] = averageExecutionTime;
175             stats[1] = transactionsPerMillisecond;
176             statsStartDate = new Date();
177
178             actionEventsReceivedCount = 0;
179             accumulatedExecutionTime = 0;
180         }
181
182         // Return the statistics
183         return stats;
184     }
185
186     /**
187      * Checks if the test server is starting.
188      *
189      * @return true, if the server is starting
190      */
191     public boolean isStarting() {
192         return starting;
193     }
194
195     /*
196      * (non-Javadoc)
197      * 
198      * @see
199      * org.onap.policy.apex.service.engine.runtime.EngineServiceEventInterface#sendEvent(org.onap.
200      * policy.apex.service.engine.event.ApexEvent)
201      */
202     @Override
203     public void sendEvent(final ApexEvent event) {
204         // Send the event onto the service being tested
205         engineService.getEngineServiceEventInterface().sendEvent(event);
206     }
207
208     /**
209      * The listener interface for receiving testApex events. The class that is interested in
210      * processing a testApex event implements this interface, and the object created with that class
211      * is registered with a component using the component's {@code addTestApexListener} method. When
212      * the testApex event occurs, that object's appropriate method is invoked.
213      *
214      * <p>This class listens for events from the Apex engine
215      *
216      * @see TestApexEvent
217      */
218     private final class TestApexListener implements ApexEventListener {
219
220         /*
221          * (non-Javadoc)
222          *
223          * @see
224          * org.onap.policy.apex.service.engine.runtime.ApexEventListener#onApexEvent(org.onap.policy
225          * .apex.service.engine.event.ApexEvent)
226          */
227         @Override
228         public synchronized void onApexEvent(final ApexEvent apexEvent) {
229             LOGGER.debug("result is:" + apexEvent);
230
231             // Check the result event is correct
232             checkResult(apexEvent);
233
234             // Calculate the performance of the Apex engine service on this policy execution run and
235             // accumulate the total statistics
236             final Date testStartTime = new Date((Long) apexEvent.get("TestTimestamp"));
237             final Date testEndTime = new Date();
238             final long testTime = testEndTime.getTime() - testStartTime.getTime();
239             LOGGER.debug("policy execution time: " + testTime + "ms");
240             synchronized (statsStartDate) {
241                 actionEventsReceivedCount++;
242                 totalActionEventsReceivedCount++;
243                 accumulatedExecutionTime += testTime;
244             }
245             lastEventReceived = apexEvent;
246         }
247
248         /**
249          * Check that a reply event from the Apex engine is valid.
250          *
251          * @param result the result event from the Apex engine
252          */
253         private void checkResult(final ApexEvent result) {
254             assert result.getName().startsWith("Event0004") || result.getName().startsWith("Event0104");
255
256             // CHECKSTYLE:OFF: checkstyle:magicNumber
257             assert result.get("TestSlogan").equals("This is a test slogan");
258             assert result.get("TestMatchCase").equals(new Byte((byte) 123));
259             assert result.get("TestTemperature").equals(34.5445667);
260             assert ((byte) result.get("TestMatchCaseSelected") >= 0 && (byte) result.get("TestMatchCaseSelected") <= 3);
261             assert ((byte) result.get("TestEstablishCaseSelected") >= 0
262                     && (byte) result.get("TestEstablishCaseSelected") <= 3);
263             assert ((byte) result.get("TestDecideCaseSelected") >= 0
264                     && (byte) result.get("TestDecideCaseSelected") <= 3);
265             assert ((byte) result.get("TestActCaseSelected") >= 0 && (byte) result.get("TestActCaseSelected") <= 3);
266             // CHECKSTYLE:ON: checkstyle:magicNumber
267         }
268     }
269 }