Changes for checkstyle 8.32
[policy/apex-pdp.git] / examples / examples-onap-vcpe / src / test / java / org / onap / policy / apex / domains / onap / vcpe / OnapVCpeSimEndpoint.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019-2020 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.domains.onap.vcpe;
23
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertTrue;
26
27 import com.google.gson.Gson;
28 import com.google.gson.GsonBuilder;
29 import com.google.gson.JsonElement;
30 import com.google.gson.JsonParser;
31 import java.io.IOException;
32 import java.time.Instant;
33 import java.util.Map;
34 import java.util.Random;
35 import java.util.concurrent.BlockingQueue;
36 import java.util.concurrent.LinkedBlockingQueue;
37 import java.util.concurrent.TimeUnit;
38 import java.util.concurrent.atomic.AtomicInteger;
39 import javax.ws.rs.GET;
40 import javax.ws.rs.POST;
41 import javax.ws.rs.PUT;
42 import javax.ws.rs.Path;
43 import javax.ws.rs.QueryParam;
44 import javax.ws.rs.core.Response;
45 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
46 import org.onap.policy.common.utils.resources.TextFileUtils;
47 import org.onap.policy.controlloop.util.Serialization;
48 import org.slf4j.ext.XLogger;
49 import org.slf4j.ext.XLoggerFactory;
50
51 /**
52  * The Class AaiAndGuardSimEndpoint.
53  */
54 @Path("/sim")
55 public class OnapVCpeSimEndpoint {
56     private static final XLogger LOGGER = XLoggerFactory.getXLogger(OnapVCpeSimEndpoint.class);
57
58     private static BlockingQueue<String> appcResponseQueue = new LinkedBlockingQueue<>();
59
60     private static AtomicInteger guardMessagesReceived = new AtomicInteger();
61     private static AtomicInteger postMessagesReceived = new AtomicInteger();
62     private static AtomicInteger putMessagesReceived = new AtomicInteger();
63     private static AtomicInteger statMessagesReceived = new AtomicInteger();
64     private static AtomicInteger getMessagesReceived = new AtomicInteger();
65
66     private static final Random randomDelayInc = new Random();
67
68     private static final Gson gson = new GsonBuilder()
69             .registerTypeAdapter(Instant.class, new Serialization.GsonInstantAdapter()).setPrettyPrinting().create();
70
71     private static final AtomicInteger nextVnfId = new AtomicInteger(0);
72     private static Boolean nextControlLoopMessageIsOnset = true;
73
74     /**
75      * Service get stats.
76      *
77      * @return the response
78      */
79     @Path("/pdp/api/Stats")
80     @GET
81     public Response serviceGetStats() {
82         statMessagesReceived.incrementAndGet();
83         String returnString = "{\"GET\": " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived + ",\"POST\": "
84                 + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}";
85
86         return Response.status(200).entity(prettifyJsonString(returnString)).build();
87     }
88
89     /**
90      * Service guard post request.
91      *
92      * @param jsonString the json string
93      * @return the response
94      */
95     @Path("/pdp/api/getDecision")
96     @POST
97     public Response serviceGuardPostRequest(final String jsonString) {
98         LOGGER.info("\n*** GUARD REQUEST START ***\n" + jsonString + "\n *** GUARD REQUEST END ***");
99
100         String target = jsonString.substring(jsonString.indexOf("00000000"));
101         target = target.substring(0, target.indexOf('"'));
102
103         int thisGuardMessageNumber = guardMessagesReceived.incrementAndGet();
104         postMessagesReceived.incrementAndGet();
105
106         String responseJsonString = null;
107         if (thisGuardMessageNumber % 2 == 0) {
108             responseJsonString = "{\"decision\": \"PERMIT\", \"details\": \"Decision Permit. OK!\"}";
109         } else {
110             responseJsonString = "{\"decision\": \"DENY\", \"details\": \"Decision Denied. NOK :-(\"}";
111         }
112
113         responseJsonString = prettifyJsonString(responseJsonString);
114
115         LOGGER.info("\n*** GUARD RESPONSE START ***\n" + target + "\n" + responseJsonString
116                 + "\n*** GUARD RESPONSE END ***");
117
118         return Response.status(200).entity(responseJsonString).build();
119     }
120
121     /**
122      * AAI named query search request.
123      * http://localhost:54321/aai/v16/search/nodes-query?search-node-type=vserver&filter=vserver-name:EQUALS:
124      *
125      * @param searchNodeType the node type to search for
126      * @param filter the filter to apply in the search
127      * @return the response
128      * @throws IOException on I/O errors
129      */
130     @Path("aai/v16/search/nodes-query")
131     @GET
132     public Response aaiNamedQuerySearchRequest(@QueryParam("search-node-type") final String searchNodeType,
133             @QueryParam("filter") final String filter) throws IOException {
134         getMessagesReceived.incrementAndGet();
135
136         LOGGER.info("\n*** AAI NODE QUERY GET START ***\nsearchNodeType=" + searchNodeType + "\nfilter=" + filter
137                 + "\n *** AAI REQUEST END ***");
138
139         String adjustedVserverUuid =
140                 "b4fe00ac-1da6-4b00-ac0d-8e8300db" + String.format("%04d", nextVnfId.getAndIncrement());
141
142         String responseJsonString =
143                 TextFileUtils.getTextFileAsString("src/test/resources/aai/SearchNodeTypeResponse.json")
144                         .replaceAll("b4fe00ac-1da6-4b00-ac0d-8e8300db0007", adjustedVserverUuid);
145
146         responseJsonString = prettifyJsonString(responseJsonString);
147
148         LOGGER.info("\n*** AAI RESPONSE START ***\n" + responseJsonString + "\n *** AAI RESPONSE END ***");
149
150         return Response.status(200).entity(responseJsonString).build();
151     }
152
153     /**
154      * AAI named query request on a particular resource.
155      * http://localhost:54321/OnapVCpeSim/sim/aai/v16/query?format=resource
156      *
157      * @param format the format of the request
158      * @param jsonString the body of the request
159      * @return the response
160      * @throws IOException on I/O errors
161      */
162     @Path("aai/v16/query")
163     @PUT
164     public Response aaiNamedQueryResourceRequest(@QueryParam("format") final String format, final String jsonString)
165             throws IOException {
166         putMessagesReceived.incrementAndGet();
167
168         LOGGER.info("\n*** AAI NODE RESOURE POST QUERY START ***\\nformat=" + format + "\njson=" + jsonString
169                 + "\n *** AAI REQUEST END ***");
170
171         int beginIndex =
172                 jsonString.indexOf("b4fe00ac-1da6-4b00-ac0d-8e8300db") + "b4fe00ac-1da6-4b00-ac0d-8e8300db".length();
173         String nextVnfIdUrlEnding = jsonString.substring(beginIndex, beginIndex + 4);
174         String responseJsonString = TextFileUtils.getTextFileAsString("src/test/resources/aai/NodeQueryResponse.json")
175                 .replaceAll("bbb3cefd-01c8-413c-9bdd-2b92f9ca3d38",
176                         "00000000-0000-0000-0000-00000000" + nextVnfIdUrlEnding);
177
178         responseJsonString = prettifyJsonString(responseJsonString);
179
180         LOGGER.info("\n*** AAI RESPONSE START ***\n" + responseJsonString + "\n *** AAI RESPONSE END ***");
181
182         return Response.status(200).entity(responseJsonString).build();
183     }
184
185     /**
186      * DCAE input of events (simulation of DMaaP).
187      *
188      * @param timeout the timeout to wait for
189      * @return the response
190      * @throws IOException on I/O errors
191      */
192     @Path("events/unauthenticated.DCAE_CL_OUTPUT/APEX/1")
193     @GET
194     public Response dcaeClOutput(@QueryParam("timeout") final int timeout) throws IOException {
195         getMessagesReceived.incrementAndGet();
196
197         ThreadUtilities.sleep(timeout - 500);
198
199         if (nextControlLoopMessageIsOnset) {
200             nextControlLoopMessageIsOnset = false;
201
202             String clOnsetEvent = TextFileUtils
203                     .getTextFileAsString("src/main/resources/examples/events/ONAPvCPEStandalone/CLOnsetEvent.json");
204             LOGGER.info("\n*** CONTROL LOOP ONSET START ***\n" + clOnsetEvent + "\n *** CONTROL LOOP ONSET END ***");
205
206             return Response.status(200).entity(clOnsetEvent).build();
207         } else {
208             nextControlLoopMessageIsOnset = true;
209
210             String clAbatedEvent = TextFileUtils
211                     .getTextFileAsString("src/main/resources/examples/events/ONAPvCPEStandalone/CLAbatedEvent.json");
212             LOGGER.info("\n*** CONTROL LOOP ABATED START ***\n" + clAbatedEvent + "\n *** CONTROL LOOP ABATED END ***");
213
214             return Response.status(200).entity(clAbatedEvent).build();
215         }
216     }
217
218     /**
219      * APPC response events (simulation of DMaaP).
220      *
221      * @param timeout the timeout to wait for
222      * @return the response
223      * @throws InterruptedException on queue interrupts
224      */
225     @Path("events/APPC_LCM_WRITE/APEX/1")
226     @GET
227     public Response appcResponseOutput(@QueryParam("timeout") final int timeout) throws InterruptedException {
228         getMessagesReceived.incrementAndGet();
229
230         int timeLeft = timeout - 500;
231
232         do {
233             String appcResponse = appcResponseQueue.poll(100, TimeUnit.MILLISECONDS);
234
235             if (appcResponse != null) {
236                 LOGGER.info("\n*** CONTROLLER RESPONSE START ***");
237                 System.err.println(appcResponse);
238                 LOGGER.info("\n*** CONTROLLER RESPONSE END ***");
239
240                 return Response.status(200).entity(appcResponse).build();
241             }
242             timeLeft -= 100;
243         } while (timeLeft > 0);
244
245         return Response.status(200).build();
246     }
247
248     /**
249      * Post to Policy management log (Simulation of DMaaP).
250      *
251      * @param jsonString the json string
252      * @return the response
253      */
254     @Path("/events/POLICY_CL_MGT")
255     @POST
256     public Response policyLogRequest(final String jsonString) {
257         postMessagesReceived.incrementAndGet();
258
259         String logJsonString = prettifyJsonString(jsonString);
260
261         LOGGER.info("\n*** POLICY LOG ENTRY START ***\n" + logJsonString + "\n *** POLICY LOG ENTRY END ***");
262
263         return Response.status(200).build();
264     }
265
266     /**
267      * Post to APPC LCM (Simulation of DMaaP).
268      *
269      * @param jsonString the json string
270      * @return the response
271      */
272     @Path("/events/APPC-LCM-READ")
273     @POST
274     public Response appcRequest(final String jsonString) {
275         postMessagesReceived.incrementAndGet();
276
277         String appcJsonString = prettifyJsonString(jsonString);
278
279         LOGGER.info("\n*** CONTROLLER REQUEST START ***\n" + appcJsonString + "\n *** CONTROLLER REQUEST END ***");
280
281         new AppcResponseCreator(appcResponseQueue, appcJsonString, 10000 + randomDelayInc.nextInt(10000));
282
283         return Response.status(200).build();
284     }
285
286     /**
287      * Post to BLACK WHITE LIST READ (Simulation of DMaaP).
288      *
289      * @param jsonString the json string
290      * @return the response
291      */
292     @Path("/events/BLACK-WHITE-LIST-READ")
293     @POST
294     public Response blackWhiteListRead(final String jsonString) {
295         postMessagesReceived.incrementAndGet();
296
297         String bwJsonString = prettifyJsonString(jsonString);
298
299         LOGGER.info("\n*** BLACK WHITE LIST START ***\n" + bwJsonString + "\n *** BLACK WHITE LIST END ***");
300
301         return Response.status(200).build();
302     }
303
304     /**
305      * Service get event.
306      *
307      * @return the response
308      */
309     @Path("/event/GetEvent")
310     @GET
311     public Response serviceGetEvent() {
312         final Random rand = new Random();
313         final int nextMatchCase = rand.nextInt(4);
314         final String nextEventName = "Event0" + rand.nextInt(2) + "00";
315
316         final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \""
317                 + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + getMessagesReceived
318                 + "\",\n" + "\"target\": \"apex\",\n" + "\"TestSlogan\": \"Test slogan for External Event0\",\n"
319                 + "\"TestMatchCase\": " + nextMatchCase + ",\n" + "\"TestTimestamp\": " + System.currentTimeMillis()
320                 + ",\n" + "\"TestTemperature\": 9080.866\n" + "}";
321
322         getMessagesReceived.incrementAndGet();
323
324         return Response.status(200).entity(eventString).build();
325     }
326
327     /**
328      * Service get empty event.
329      *
330      * @return the response
331      */
332     @Path("/event/GetEmptyEvent")
333     @GET
334     public Response serviceGetEmptyEvent() {
335         return Response.status(200).build();
336     }
337
338     /**
339      * Service get event bad response.
340      *
341      * @return the response
342      */
343     @Path("/event/GetEventBadResponse")
344     @GET
345     public Response serviceGetEventBadResponse() {
346         return Response.status(400).build();
347     }
348
349     /**
350      * Service post request.
351      *
352      * @param jsonString the json string
353      * @return the response
354      */
355     @Path("/event/PostEvent")
356     @POST
357     public Response servicePostRequest(final String jsonString) {
358         postMessagesReceived.incrementAndGet();
359
360         @SuppressWarnings("unchecked")
361         final Map<String, Object> jsonMap = gson.fromJson(jsonString, Map.class);
362         assertTrue(jsonMap.containsKey("name"));
363         assertEquals("0.0.1", jsonMap.get("version"));
364         assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
365         assertEquals("Act", jsonMap.get("source"));
366         assertEquals("Outside", jsonMap.get("target"));
367
368         return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived
369                 + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build();
370     }
371
372     /**
373      * Service post request bad response.
374      *
375      * @param jsonString the json string
376      * @return the response
377      */
378     @Path("/event/PostEventBadResponse")
379     @POST
380     public Response servicePostRequestBadResponse(final String jsonString) {
381         return Response.status(400).build();
382     }
383
384     /**
385      * Service put request.
386      *
387      * @param jsonString the json string
388      * @return the response
389      */
390     @Path("/event/PutEvent")
391     @PUT
392     public Response servicePutRequest(final String jsonString) {
393         putMessagesReceived.incrementAndGet();
394
395         @SuppressWarnings("unchecked")
396         final Map<String, Object> jsonMap = gson.fromJson(jsonString, Map.class);
397         assertTrue(jsonMap.containsKey("name"));
398         assertEquals("0.0.1", jsonMap.get("version"));
399         assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
400         assertEquals("Act", jsonMap.get("source"));
401         assertEquals("Outside", jsonMap.get("target"));
402
403         return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived
404                 + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build();
405     }
406
407     private static final String prettifyJsonString(final String uglyJsonString) {
408         JsonElement je = JsonParser.parseString(uglyJsonString);
409         return gson.toJson(je);
410     }
411 }