61100d4f4287d94ffa41e24ad34263408f10dd83
[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     /**
70      * Service get stats.
71      *
72      * @return the response
73      */
74     @Path("/pdp/api/Stats")
75     @GET
76     public Response serviceGetStats() {
77         statMessagesReceived.incrementAndGet();
78
79         return Response.status(200).entity("{\"GET\": " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived
80                         + ",\"POST\": " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build();
81     }
82
83     /**
84      * Service guard post request.
85      *
86      * @param jsonString the json string
87      * @return the response
88      */
89     @Path("/pdp/api/getDecision")
90     @POST
91     public Response serviceGuardPostRequest(final String jsonString) {
92         LOGGER.info("\n*** GUARD REQUEST START ***\n" + jsonString + "\n *** GUARD REQUEST END ***");
93
94         String target = jsonString.substring(jsonString.indexOf("b4fe00ac"));
95         target = target.substring(0, target.indexOf('"'));
96
97         int thisGuardMessageNumber = guardMessagesReceived.incrementAndGet();
98         postMessagesReceived.incrementAndGet();
99
100         String responseJsonString = null;
101         if (thisGuardMessageNumber % 2 == 0) {
102             responseJsonString = "{\"decision\": \"PERMIT\", \"details\": \"Decision Permit. OK!\"}";
103         } else {
104             responseJsonString = "{\"decision\": \"DENY\", \"details\": \"Decision Denied. NOK :-(\"}";
105         }
106
107         LOGGER.info("\n*** GUARD RESPONSE START ***\n" + target + "\n" + responseJsonString
108                         + "\n*** GUARD RESPONSE END ***");
109
110         return Response.status(200).entity(responseJsonString).build();
111     }
112
113     /**
114      * AAI named query search request.
115      * http://localhost:54321/aai/v16/search/nodes-query?search-node-type=vserver&filter=vserver-name:EQUALS:
116      *
117      * @param searchNodeType the node type to search for
118      * @param filter the filter to apply in the search
119      * @return the response
120      * @throws IOException on I/O errors
121      */
122     @Path("aai/v16/search/nodes-query")
123     @GET
124     public Response aaiNamedQuerySearchRequest(@QueryParam("search-node-type") final String searchNodeType,
125                     @QueryParam("filter") final String filter) throws IOException {
126         getMessagesReceived.incrementAndGet();
127
128         LOGGER.info("\n*** AAI NODE QUERY GET START ***\nsearchNodeType=" + searchNodeType + "\nfilter=" + filter
129                         + "\n *** AAI REQUEST END ***");
130
131         String responseJsonString = TextFileUtils
132                         .getTextFileAsString("src/test/resources/aai/SearchNodeTypeResponse.json");
133
134         LOGGER.info("\n*** AAI RESPONSE START ***\n" + responseJsonString + "\n *** AAI RESPONSE END ***");
135
136         return Response.status(200).entity(responseJsonString).build();
137     }
138
139     /**
140      * AAI named query request on a particular resource.
141      * http://localhost:54321/OnapVCpeSim/sim/aai/v16/query?format=resource
142      *
143      * @param format the format of the request
144      * @param jsonString the body of the request
145      * @return the response
146      * @throws IOException on I/O errors
147      */
148     @Path("aai/v16/query")
149     @PUT
150     public Response aaiNamedQueryResourceRequest(@QueryParam("format") final String format, final String jsonString)
151                     throws IOException {
152         putMessagesReceived.incrementAndGet();
153
154         LOGGER.info("\n*** AAI NODE RESOURE POST QUERY START ***\\nformat=" + format + "\njson=" + jsonString
155                         + "\n *** AAI REQUEST END ***");
156
157         String responseJsonString = TextFileUtils.getTextFileAsString("src/test/resources/aai/NodeQueryResponse.json");
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 }