f08bf010c9d9f68cfbcccd434d19e40cf15177b7
[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.time.Instant;
30 import java.util.Map;
31 import java.util.Random;
32 import java.util.concurrent.BlockingQueue;
33 import java.util.concurrent.LinkedBlockingQueue;
34 import java.util.concurrent.TimeUnit;
35 import java.util.concurrent.atomic.AtomicInteger;
36
37 import javax.ws.rs.GET;
38 import javax.ws.rs.POST;
39 import javax.ws.rs.PUT;
40 import javax.ws.rs.Path;
41 import javax.ws.rs.QueryParam;
42 import javax.ws.rs.core.Response;
43
44 import org.onap.policy.aai.AaiNqGenericVnf;
45 import org.onap.policy.aai.AaiNqInventoryResponseItem;
46 import org.onap.policy.aai.AaiNqRequest;
47 import org.onap.policy.aai.AaiNqResponse;
48 import org.onap.policy.aai.AaiNqVfModule;
49 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
50 import org.onap.policy.controlloop.util.Serialization;
51 import org.slf4j.ext.XLogger;
52 import org.slf4j.ext.XLoggerFactory;
53
54 /**
55  * The Class AaiAndGuardSimEndpoint.
56  */
57 @Path("/sim")
58 public class OnapVCpeSimEndpoint {
59     private static final XLogger LOGGER = XLoggerFactory.getXLogger(OnapVCpeSimEndpoint.class);
60
61     private static BlockingQueue<String> appcResponseQueue = new LinkedBlockingQueue<>();
62
63     private static AtomicInteger guardMessagesReceived = new AtomicInteger();
64     private static AtomicInteger postMessagesReceived = new AtomicInteger();
65     private static AtomicInteger putMessagesReceived = new AtomicInteger();
66     private static AtomicInteger statMessagesReceived = new AtomicInteger();
67     private static AtomicInteger getMessagesReceived = new AtomicInteger();
68
69     private static final Gson gson = new GsonBuilder()
70                     .registerTypeAdapter(Instant.class, new Serialization.GsonInstantAdapter()).create();
71
72     /**
73      * Service get stats.
74      *
75      * @return the response
76      */
77     @Path("/pdp/api/Stats")
78     @GET
79     public Response serviceGetStats() {
80         statMessagesReceived.incrementAndGet();
81
82         return Response.status(200).entity("{\"GET\": " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived
83                         + ",\"POST\": " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build();
84     }
85
86     /**
87      * Service guard post request.
88      *
89      * @param jsonString the json string
90      * @return the response
91      */
92     @Path("/pdp/api/getDecision")
93     @POST
94     public Response serviceGuardPostRequest(final String jsonString) {
95         LOGGER.info("\n*** GUARD REQUEST START ***\n" + jsonString + "\n *** GUARD REQUEST END ***");
96
97         String target = jsonString.substring(jsonString.indexOf("b4fe00ac"));
98         target = target.substring(0, target.indexOf('"'));
99
100         int thisGuardMessageNumber = guardMessagesReceived.incrementAndGet();
101         postMessagesReceived.incrementAndGet();
102
103         String responseJsonString = null;
104         if (thisGuardMessageNumber % 2 == 0) {
105             responseJsonString = "{\"decision\": \"PERMIT\", \"details\": \"Decision Permit. OK!\"}";
106         } else {
107             responseJsonString = "{\"decision\": \"DENY\", \"details\": \"Decision Denied. NOK :-(\"}";
108         }
109
110         LOGGER.info("\n*** GUARD RESPONSE START ***\n" + target + "\n" + responseJsonString
111                         + "\n*** GUARD RESPONSE END ***");
112
113         return Response.status(200).entity(responseJsonString).build();
114     }
115
116     /**
117      * AAI named query request.
118      *
119      * @param jsonString the json string
120      * @return the response
121      */
122     @Path("aai/search/named-query")
123     @POST
124     public Response aaiNamedQueryRequest(final String jsonString) {
125         postMessagesReceived.incrementAndGet();
126
127         LOGGER.info("\n*** AAI REQUEST START ***\n" + jsonString + "\n *** AAI REQUEST END ***");
128
129         AaiNqRequest request = gson.fromJson(jsonString, AaiNqRequest.class);
130         String vnfId = request.getInstanceFilters().getInstanceFilter().iterator().next().get("generic-vnf")
131                         .get("vnf-id");
132         String vnfSuffix = vnfId.substring(vnfId.length() - 4);
133
134         AaiNqInventoryResponseItem responseItem = new AaiNqInventoryResponseItem();
135         responseItem.setModelName("vCPE");
136
137         AaiNqGenericVnf genericVnf = new AaiNqGenericVnf();
138         genericVnf.setResourceVersion("1");
139         genericVnf.setVnfName("vCPEInfraVNF" + vnfSuffix);
140         genericVnf.setProvStatus("PREPROV");
141         genericVnf.setIsClosedLoopDisabled(false);
142         genericVnf.setVnfType("vCPEInfraService10/vCPEInfraService10 0");
143         genericVnf.setInMaint(false);
144         genericVnf.setServiceId("5585fd2c-ad0d-4050-b0cf-dfe4a03bd01f");
145         genericVnf.setVnfId(vnfId);
146
147         responseItem.setGenericVnf(genericVnf);
148
149         AaiNqVfModule vfModule = new AaiNqVfModule();
150         vfModule.setOrchestrationStatus("Created");
151
152         responseItem.setVfModule(vfModule);
153
154         AaiNqResponse response = new AaiNqResponse();
155         response.getInventoryResponseItems().add(responseItem);
156
157         String responseJsonString = new GsonBuilder().setPrettyPrinting().create().toJson(response);
158
159         LOGGER.info("\n*** AAI RESPONSE START ***\n" + responseJsonString + "\n *** AAI RESPONSE END ***");
160
161         return Response.status(200).entity(responseJsonString).build();
162     }
163
164     /**
165      * DCAE input of events (simulation of DMaaP).
166      *
167      * @param timeout the timeout to wait for
168      * @return the response
169      */
170     @Path("events/unauthenticated.DCAE_CL_OUTPUT/APEX/1")
171     @GET
172     public Response dcaeClOutput(@QueryParam("timeout") final int timeout) {
173         getMessagesReceived.incrementAndGet();
174
175         ThreadUtilities.sleep(timeout - 500);
176
177         return Response.status(200).build();
178     }
179
180     /**
181      * APPC response events (simulation of DMaaP).
182      *
183      * @param timeout the timeout to wait for
184      * @return the response
185      * @throws InterruptedException on queue interrupts
186      */
187     @Path("events/APPC_LCM_WRITE/APEX/1")
188     @GET
189     public Response appcResponseOutput(@QueryParam("timeout") final int timeout) throws InterruptedException {
190         getMessagesReceived.incrementAndGet();
191
192         int timeLeft = timeout - 500;
193
194         do {
195             String appcResponse = appcResponseQueue.poll(100, TimeUnit.MILLISECONDS);
196
197             if (appcResponse != null) {
198                 LOGGER.info("\n*** APPC RESPONSE START ***");
199                 System.err.println(appcResponse);
200                 LOGGER.info("\n*** APPC RESPONSE END ***");
201
202                 return Response.status(200).entity(appcResponse).build();
203             }
204             timeLeft -= 100;
205         }
206         while (timeLeft > 0);
207
208         return Response.status(200).build();
209     }
210
211     /**
212      * Post to Policy management log (Simulation of DMaaP).
213      *
214      * @param jsonString the json string
215      * @return the response
216      */
217     @Path("/events/POLICY_CL_MGT")
218     @POST
219     public Response policyLogRequest(final String jsonString) {
220         postMessagesReceived.incrementAndGet();
221
222         LOGGER.info("\n*** POLICY LOG ENTRY START ***\n" + jsonString + "\n *** POLICY LOG ENTRY END ***");
223
224         return Response.status(200).build();
225     }
226
227     /**
228      * Post to APPC LCM (Simulation of DMaaP).
229      *
230      * @param jsonString the json string
231      * @return the response
232      */
233     @Path("/events/APPC-LCM-READ")
234     @POST
235     public Response appcRequest(final String jsonString) {
236         postMessagesReceived.incrementAndGet();
237
238         LOGGER.info("\n*** APPC REQUEST START ***\n" + jsonString + "\n *** APPC REQUEST END ***");
239
240         new AppcResponseCreator(appcResponseQueue, jsonString, 10000);
241
242         return Response.status(200).build();
243     }
244
245     /**
246      * Service get event.
247      *
248      * @return the response
249      */
250     @Path("/event/GetEvent")
251     @GET
252     public Response serviceGetEvent() {
253         final Random rand = new Random();
254         final int nextMatchCase = rand.nextInt(4);
255         final String nextEventName = "Event0" + rand.nextInt(2) + "00";
256
257         final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \""
258                         + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_"
259                         + getMessagesReceived + "\",\n" + "\"target\": \"apex\",\n"
260                         + "\"TestSlogan\": \"Test slogan for External Event0\",\n" + "\"TestMatchCase\": "
261                         + nextMatchCase + ",\n" + "\"TestTimestamp\": " + System.currentTimeMillis() + ",\n"
262                         + "\"TestTemperature\": 9080.866\n" + "}";
263
264         getMessagesReceived.incrementAndGet();
265
266         return Response.status(200).entity(eventString).build();
267     }
268
269     /**
270      * Service get empty event.
271      *
272      * @return the response
273      */
274     @Path("/event/GetEmptyEvent")
275     @GET
276     public Response serviceGetEmptyEvent() {
277         return Response.status(200).build();
278     }
279
280     /**
281      * Service get event bad response.
282      *
283      * @return the response
284      */
285     @Path("/event/GetEventBadResponse")
286     @GET
287     public Response serviceGetEventBadResponse() {
288         return Response.status(400).build();
289     }
290
291     /**
292      * Service post request.
293      *
294      * @param jsonString the json string
295      * @return the response
296      */
297     @Path("/event/PostEvent")
298     @POST
299     public Response servicePostRequest(final String jsonString) {
300         postMessagesReceived.incrementAndGet();
301
302         @SuppressWarnings("unchecked")
303         final Map<String, Object> jsonMap = gson.fromJson(jsonString, Map.class);
304         assertTrue(jsonMap.containsKey("name"));
305         assertEquals("0.0.1", jsonMap.get("version"));
306         assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
307         assertEquals("Act", jsonMap.get("source"));
308         assertEquals("Outside", jsonMap.get("target"));
309
310         return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived
311                         + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build();
312     }
313
314     /**
315      * Service post request bad response.
316      *
317      * @param jsonString the json string
318      * @return the response
319      */
320     @Path("/event/PostEventBadResponse")
321     @POST
322     public Response servicePostRequestBadResponse(final String jsonString) {
323         return Response.status(400).build();
324     }
325
326     /**
327      * Service put request.
328      *
329      * @param jsonString the json string
330      * @return the response
331      */
332     @Path("/event/PutEvent")
333     @PUT
334     public Response servicePutRequest(final String jsonString) {
335         putMessagesReceived.incrementAndGet();
336
337         @SuppressWarnings("unchecked")
338         final Map<String, Object> jsonMap = gson.fromJson(jsonString, Map.class);
339         assertTrue(jsonMap.containsKey("name"));
340         assertEquals("0.0.1", jsonMap.get("version"));
341         assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
342         assertEquals("Act", jsonMap.get("source"));
343         assertEquals("Outside", jsonMap.get("target"));
344
345         return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived
346                         + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build();
347     }
348 }