5eb8fd338df89b89417f7980b39d2951f4df77a5
[policy/apex-pdp.git] /
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.domains.onap.vcpe;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertTrue;
25
26 import com.google.gson.Gson;
27 import com.google.gson.GsonBuilder;
28
29 import java.io.IOException;
30 import java.time.Instant;
31 import java.util.Map;
32 import java.util.Random;
33 import java.util.concurrent.BlockingQueue;
34 import java.util.concurrent.LinkedBlockingQueue;
35 import java.util.concurrent.TimeUnit;
36 import java.util.concurrent.atomic.AtomicInteger;
37
38 import javax.ws.rs.GET;
39 import javax.ws.rs.POST;
40 import javax.ws.rs.PUT;
41 import javax.ws.rs.Path;
42 import javax.ws.rs.QueryParam;
43 import javax.ws.rs.core.Response;
44
45 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
46 import org.onap.policy.apex.model.utilities.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 Gson gson = new GsonBuilder()
67                     .registerTypeAdapter(Instant.class, new Serialization.GsonInstantAdapter()).create();
68
69     private static final AtomicInteger nextVnfId = new AtomicInteger(0);
70
71     /**
72      * Service get stats.
73      *
74      * @return the response
75      */
76     @Path("/pdp/api/Stats")
77     @GET
78     public Response serviceGetStats() {
79         statMessagesReceived.incrementAndGet();
80
81         return Response.status(200).entity("{\"GET\": " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived
82                         + ",\"POST\": " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build();
83     }
84
85     /**
86      * Service guard post request.
87      *
88      * @param jsonString the json string
89      * @return the response
90      */
91     @Path("/pdp/api/getDecision")
92     @POST
93     public Response serviceGuardPostRequest(final String jsonString) {
94         LOGGER.info("\n*** GUARD REQUEST START ***\n" + jsonString + "\n *** GUARD REQUEST END ***");
95
96         String target = jsonString.substring(jsonString.indexOf("00000000"));
97         target = target.substring(0, target.indexOf('"'));
98
99         int thisGuardMessageNumber = guardMessagesReceived.incrementAndGet();
100         postMessagesReceived.incrementAndGet();
101
102         String responseJsonString = null;
103         if (thisGuardMessageNumber % 2 == 0) {
104             responseJsonString = "{\"decision\": \"PERMIT\", \"details\": \"Decision Permit. OK!\"}";
105         } else {
106             responseJsonString = "{\"decision\": \"DENY\", \"details\": \"Decision Denied. NOK :-(\"}";
107         }
108
109         LOGGER.info("\n*** GUARD RESPONSE START ***\n" + target + "\n" + responseJsonString
110                         + "\n*** GUARD RESPONSE END ***");
111
112         return Response.status(200).entity(responseJsonString).build();
113     }
114
115     /**
116      * AAI named query search request.
117      * http://localhost:54321/aai/v16/search/nodes-query?search-node-type=vserver&filter=vserver-name:EQUALS:
118      *
119      * @param searchNodeType the node type to search for
120      * @param filter the filter to apply in the search
121      * @return the response
122      * @throws IOException on I/O errors
123      */
124     @Path("aai/v16/search/nodes-query")
125     @GET
126     public Response aaiNamedQuerySearchRequest(@QueryParam("search-node-type") final String searchNodeType,
127                     @QueryParam("filter") final String filter) throws IOException {
128         getMessagesReceived.incrementAndGet();
129
130         LOGGER.info("\n*** AAI NODE QUERY GET START ***\nsearchNodeType=" + searchNodeType + "\nfilter=" + filter
131                         + "\n *** AAI REQUEST END ***");
132
133         String adjustedVserverUuid = "b4fe00ac-1da6-4b00-ac0d-8e8300db"
134                         + String.format("%04d", nextVnfId.getAndIncrement());
135
136         String responseJsonString = TextFileUtils
137                         .getTextFileAsString("src/test/resources/aai/SearchNodeTypeResponse.json")
138                         .replaceAll("b4fe00ac-1da6-4b00-ac0d-8e8300db0007", adjustedVserverUuid);
139
140         LOGGER.info("\n*** AAI RESPONSE START ***\n" + responseJsonString + "\n *** AAI RESPONSE END ***");
141
142         return Response.status(200).entity(responseJsonString).build();
143     }
144
145     /**
146      * AAI named query request on a particular resource.
147      * http://localhost:54321/OnapVCpeSim/sim/aai/v16/query?format=resource
148      *
149      * @param format the format of the request
150      * @param jsonString the body of the request
151      * @return the response
152      * @throws IOException on I/O errors
153      */
154     @Path("aai/v16/query")
155     @PUT
156     public Response aaiNamedQueryResourceRequest(@QueryParam("format") final String format, final String jsonString)
157                     throws IOException {
158         putMessagesReceived.incrementAndGet();
159
160         LOGGER.info("\n*** AAI NODE RESOURE POST QUERY START ***\\nformat=" + format + "\njson=" + jsonString
161                         + "\n *** AAI REQUEST END ***");
162
163         int beginIndex = jsonString.indexOf("b4fe00ac-1da6-4b00-ac0d-8e8300db")
164                         + "b4fe00ac-1da6-4b00-ac0d-8e8300db".length();
165         String nextVnfIdUrlEnding = jsonString.substring(beginIndex, beginIndex + 4);
166         String responseJsonString = TextFileUtils.getTextFileAsString("src/test/resources/aai/NodeQueryResponse.json")
167                         .replaceAll("bbb3cefd-01c8-413c-9bdd-2b92f9ca3d38",
168                                         "00000000-0000-0000-0000-00000000" + nextVnfIdUrlEnding);
169
170         LOGGER.info("\n*** AAI RESPONSE START ***\n" + responseJsonString + "\n *** AAI RESPONSE END ***");
171
172         return Response.status(200).entity(responseJsonString).build();
173     }
174
175     /**
176      * DCAE input of events (simulation of DMaaP).
177      *
178      * @param timeout the timeout to wait for
179      * @return the response
180      */
181     @Path("events/unauthenticated.DCAE_CL_OUTPUT/APEX/1")
182     @GET
183     public Response dcaeClOutput(@QueryParam("timeout") final int timeout) {
184         getMessagesReceived.incrementAndGet();
185
186         ThreadUtilities.sleep(timeout - 500);
187
188         return Response.status(200).build();
189     }
190
191     /**
192      * APPC response events (simulation of DMaaP).
193      *
194      * @param timeout the timeout to wait for
195      * @return the response
196      * @throws InterruptedException on queue interrupts
197      */
198     @Path("events/APPC_LCM_WRITE/APEX/1")
199     @GET
200     public Response appcResponseOutput(@QueryParam("timeout") final int timeout) throws InterruptedException {
201         getMessagesReceived.incrementAndGet();
202
203         int timeLeft = timeout - 500;
204
205         do {
206             String appcResponse = appcResponseQueue.poll(100, TimeUnit.MILLISECONDS);
207
208             if (appcResponse != null) {
209                 LOGGER.info("\n*** APPC RESPONSE START ***");
210                 System.err.println(appcResponse);
211                 LOGGER.info("\n*** APPC RESPONSE END ***");
212
213                 return Response.status(200).entity(appcResponse).build();
214             }
215             timeLeft -= 100;
216         }
217         while (timeLeft > 0);
218
219         return Response.status(200).build();
220     }
221
222     /**
223      * Post to Policy management log (Simulation of DMaaP).
224      *
225      * @param jsonString the json string
226      * @return the response
227      */
228     @Path("/events/POLICY_CL_MGT")
229     @POST
230     public Response policyLogRequest(final String jsonString) {
231         postMessagesReceived.incrementAndGet();
232
233         LOGGER.info("\n*** POLICY LOG ENTRY START ***\n" + jsonString + "\n *** POLICY LOG ENTRY END ***");
234
235         return Response.status(200).build();
236     }
237
238     /**
239      * Post to APPC LCM (Simulation of DMaaP).
240      *
241      * @param jsonString the json string
242      * @return the response
243      */
244     @Path("/events/APPC-LCM-READ")
245     @POST
246     public Response appcRequest(final String jsonString) {
247         postMessagesReceived.incrementAndGet();
248
249         LOGGER.info("\n*** APPC REQUEST START ***\n" + jsonString + "\n *** APPC REQUEST END ***");
250
251         new AppcResponseCreator(appcResponseQueue, jsonString, 10000);
252
253         return Response.status(200).build();
254     }
255
256     /**
257      * Service get event.
258      *
259      * @return the response
260      */
261     @Path("/event/GetEvent")
262     @GET
263     public Response serviceGetEvent() {
264         final Random rand = new Random();
265         final int nextMatchCase = rand.nextInt(4);
266         final String nextEventName = "Event0" + rand.nextInt(2) + "00";
267
268         final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \""
269                         + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_"
270                         + getMessagesReceived + "\",\n" + "\"target\": \"apex\",\n"
271                         + "\"TestSlogan\": \"Test slogan for External Event0\",\n" + "\"TestMatchCase\": "
272                         + nextMatchCase + ",\n" + "\"TestTimestamp\": " + System.currentTimeMillis() + ",\n"
273                         + "\"TestTemperature\": 9080.866\n" + "}";
274
275         getMessagesReceived.incrementAndGet();
276
277         return Response.status(200).entity(eventString).build();
278     }
279
280     /**
281      * Service get empty event.
282      *
283      * @return the response
284      */
285     @Path("/event/GetEmptyEvent")
286     @GET
287     public Response serviceGetEmptyEvent() {
288         return Response.status(200).build();
289     }
290
291     /**
292      * Service get event bad response.
293      *
294      * @return the response
295      */
296     @Path("/event/GetEventBadResponse")
297     @GET
298     public Response serviceGetEventBadResponse() {
299         return Response.status(400).build();
300     }
301
302     /**
303      * Service post request.
304      *
305      * @param jsonString the json string
306      * @return the response
307      */
308     @Path("/event/PostEvent")
309     @POST
310     public Response servicePostRequest(final String jsonString) {
311         postMessagesReceived.incrementAndGet();
312
313         @SuppressWarnings("unchecked")
314         final Map<String, Object> jsonMap = gson.fromJson(jsonString, Map.class);
315         assertTrue(jsonMap.containsKey("name"));
316         assertEquals("0.0.1", jsonMap.get("version"));
317         assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
318         assertEquals("Act", jsonMap.get("source"));
319         assertEquals("Outside", jsonMap.get("target"));
320
321         return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived
322                         + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build();
323     }
324
325     /**
326      * Service post request bad response.
327      *
328      * @param jsonString the json string
329      * @return the response
330      */
331     @Path("/event/PostEventBadResponse")
332     @POST
333     public Response servicePostRequestBadResponse(final String jsonString) {
334         return Response.status(400).build();
335     }
336
337     /**
338      * Service put request.
339      *
340      * @param jsonString the json string
341      * @return the response
342      */
343     @Path("/event/PutEvent")
344     @PUT
345     public Response servicePutRequest(final String jsonString) {
346         putMessagesReceived.incrementAndGet();
347
348         @SuppressWarnings("unchecked")
349         final Map<String, Object> jsonMap = gson.fromJson(jsonString, Map.class);
350         assertTrue(jsonMap.containsKey("name"));
351         assertEquals("0.0.1", jsonMap.get("version"));
352         assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
353         assertEquals("Act", jsonMap.get("source"));
354         assertEquals("Outside", jsonMap.get("target"));
355
356         return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived
357                         + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build();
358     }
359 }