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