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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.apex.domains.onap.vcpe;
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertTrue;
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;
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;
52 * The Class AaiAndGuardSimEndpoint.
55 public class OnapVCpeSimEndpoint {
56 private static final XLogger LOGGER = XLoggerFactory.getXLogger(OnapVCpeSimEndpoint.class);
58 private static BlockingQueue<String> appcResponseQueue = new LinkedBlockingQueue<>();
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();
66 private static final Random randomDelayInc = new Random();
68 private static final Gson gson = new GsonBuilder()
69 .registerTypeAdapter(Instant.class, new Serialization.GsonInstantAdapter()).setPrettyPrinting().create();
71 private static final AtomicInteger nextVnfId = new AtomicInteger(0);
72 private static Boolean nextControlLoopMessageIsOnset = true;
77 * @return the response
79 @Path("/pdp/api/Stats")
81 public Response serviceGetStats() {
82 statMessagesReceived.incrementAndGet();
83 String returnString = "{\"GET\": " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived + ",\"POST\": "
84 + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}";
86 return Response.status(200).entity(prettifyJsonString(returnString)).build();
90 * Service guard post request.
92 * @param jsonString the json string
93 * @return the response
95 @Path("/pdp/api/getDecision")
97 public Response serviceGuardPostRequest(final String jsonString) {
98 LOGGER.info("\n*** GUARD REQUEST START ***\n" + jsonString + "\n *** GUARD REQUEST END ***");
100 String target = jsonString.substring(jsonString.indexOf("00000000"));
101 target = target.substring(0, target.indexOf('"'));
103 int thisGuardMessageNumber = guardMessagesReceived.incrementAndGet();
104 postMessagesReceived.incrementAndGet();
106 String responseJsonString = null;
107 if (thisGuardMessageNumber % 2 == 0) {
108 responseJsonString = "{\"decision\": \"PERMIT\", \"details\": \"Decision Permit. OK!\"}";
110 responseJsonString = "{\"decision\": \"DENY\", \"details\": \"Decision Denied. NOK :-(\"}";
113 responseJsonString = prettifyJsonString(responseJsonString);
115 LOGGER.info("\n*** GUARD RESPONSE START ***\n" + target + "\n" + responseJsonString
116 + "\n*** GUARD RESPONSE END ***");
118 return Response.status(200).entity(responseJsonString).build();
122 * AAI named query search request.
123 * http://localhost:54321/aai/v16/search/nodes-query?search-node-type=vserver&filter=vserver-name:EQUALS:
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
130 @Path("aai/v16/search/nodes-query")
132 public Response aaiNamedQuerySearchRequest(@QueryParam("search-node-type") final String searchNodeType,
133 @QueryParam("filter") final String filter) throws IOException {
134 getMessagesReceived.incrementAndGet();
136 LOGGER.info("\n*** AAI NODE QUERY GET START ***\nsearchNodeType=" + searchNodeType + "\nfilter=" + filter
137 + "\n *** AAI REQUEST END ***");
139 String adjustedVserverUuid =
140 "b4fe00ac-1da6-4b00-ac0d-8e8300db" + String.format("%04d", nextVnfId.getAndIncrement());
142 String responseJsonString =
143 TextFileUtils.getTextFileAsString("src/test/resources/aai/SearchNodeTypeResponse.json")
144 .replaceAll("b4fe00ac-1da6-4b00-ac0d-8e8300db0007", adjustedVserverUuid);
146 responseJsonString = prettifyJsonString(responseJsonString);
148 LOGGER.info("\n*** AAI RESPONSE START ***\n" + responseJsonString + "\n *** AAI RESPONSE END ***");
150 return Response.status(200).entity(responseJsonString).build();
154 * AAI named query request on a particular resource.
155 * http://localhost:54321/OnapVCpeSim/sim/aai/v16/query?format=resource
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
162 @Path("aai/v16/query")
164 public Response aaiNamedQueryResourceRequest(@QueryParam("format") final String format, final String jsonString)
166 putMessagesReceived.incrementAndGet();
168 LOGGER.info("\n*** AAI NODE RESOURE POST QUERY START ***\\nformat=" + format + "\njson=" + jsonString
169 + "\n *** AAI REQUEST END ***");
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);
178 responseJsonString = prettifyJsonString(responseJsonString);
180 LOGGER.info("\n*** AAI RESPONSE START ***\n" + responseJsonString + "\n *** AAI RESPONSE END ***");
182 return Response.status(200).entity(responseJsonString).build();
186 * DCAE input of events (simulation of DMaaP).
188 * @param timeout the timeout to wait for
189 * @return the response
190 * @throws IOException on I/O errors
192 @Path("events/unauthenticated.DCAE_CL_OUTPUT/APEX/1")
194 public Response dcaeClOutput(@QueryParam("timeout") final int timeout) throws IOException {
195 getMessagesReceived.incrementAndGet();
197 ThreadUtilities.sleep(timeout - 500);
199 if (nextControlLoopMessageIsOnset) {
200 nextControlLoopMessageIsOnset = false;
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 ***");
206 return Response.status(200).entity(clOnsetEvent).build();
208 nextControlLoopMessageIsOnset = true;
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 ***");
214 return Response.status(200).entity(clAbatedEvent).build();
219 * APPC response events (simulation of DMaaP).
221 * @param timeout the timeout to wait for
222 * @return the response
223 * @throws InterruptedException on queue interrupts
225 @Path("events/APPC_LCM_WRITE/APEX/1")
227 public Response appcResponseOutput(@QueryParam("timeout") final int timeout) throws InterruptedException {
228 getMessagesReceived.incrementAndGet();
230 int timeLeft = timeout - 500;
233 String appcResponse = appcResponseQueue.poll(100, TimeUnit.MILLISECONDS);
235 if (appcResponse != null) {
236 LOGGER.info("\n*** CONTROLLER RESPONSE START ***");
237 System.err.println(appcResponse);
238 LOGGER.info("\n*** CONTROLLER RESPONSE END ***");
240 return Response.status(200).entity(appcResponse).build();
243 } while (timeLeft > 0);
245 return Response.status(200).build();
249 * Post to Policy management log (Simulation of DMaaP).
251 * @param jsonString the json string
252 * @return the response
254 @Path("/events/POLICY_CL_MGT")
256 public Response policyLogRequest(final String jsonString) {
257 postMessagesReceived.incrementAndGet();
259 String logJsonString = prettifyJsonString(jsonString);
261 LOGGER.info("\n*** POLICY LOG ENTRY START ***\n" + logJsonString + "\n *** POLICY LOG ENTRY END ***");
263 return Response.status(200).build();
267 * Post to APPC LCM (Simulation of DMaaP).
269 * @param jsonString the json string
270 * @return the response
272 @Path("/events/APPC-LCM-READ")
274 public Response appcRequest(final String jsonString) {
275 postMessagesReceived.incrementAndGet();
277 String appcJsonString = prettifyJsonString(jsonString);
279 LOGGER.info("\n*** CONTROLLER REQUEST START ***\n" + appcJsonString + "\n *** CONTROLLER REQUEST END ***");
281 new AppcResponseCreator(appcResponseQueue, appcJsonString, 10000 + randomDelayInc.nextInt(10000));
283 return Response.status(200).build();
287 * Post to BLACK WHITE LIST READ (Simulation of DMaaP).
289 * @param jsonString the json string
290 * @return the response
292 @Path("/events/BLACK-WHITE-LIST-READ")
294 public Response blackWhiteListRead(final String jsonString) {
295 postMessagesReceived.incrementAndGet();
297 String bwJsonString = prettifyJsonString(jsonString);
299 LOGGER.info("\n*** BLACK WHITE LIST START ***\n" + bwJsonString + "\n *** BLACK WHITE LIST END ***");
301 return Response.status(200).build();
307 * @return the response
309 @Path("/event/GetEvent")
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";
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" + "}";
322 getMessagesReceived.incrementAndGet();
324 return Response.status(200).entity(eventString).build();
328 * Service get empty event.
330 * @return the response
332 @Path("/event/GetEmptyEvent")
334 public Response serviceGetEmptyEvent() {
335 return Response.status(200).build();
339 * Service get event bad response.
341 * @return the response
343 @Path("/event/GetEventBadResponse")
345 public Response serviceGetEventBadResponse() {
346 return Response.status(400).build();
350 * Service post request.
352 * @param jsonString the json string
353 * @return the response
355 @Path("/event/PostEvent")
357 public Response servicePostRequest(final String jsonString) {
358 postMessagesReceived.incrementAndGet();
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"));
368 return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived
369 + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build();
373 * Service post request bad response.
375 * @param jsonString the json string
376 * @return the response
378 @Path("/event/PostEventBadResponse")
380 public Response servicePostRequestBadResponse(final String jsonString) {
381 return Response.status(400).build();
385 * Service put request.
387 * @param jsonString the json string
388 * @return the response
390 @Path("/event/PutEvent")
392 public Response servicePutRequest(final String jsonString) {
393 putMessagesReceived.incrementAndGet();
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"));
403 return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived
404 + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build();
407 private static final String prettifyJsonString(final String uglyJsonString) {
408 JsonElement je = JsonParser.parseString(uglyJsonString);
409 return gson.toJson(je);