240dd1df4d14188c810c6329614be57b7dfc50f7
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2019-2020 Nordix Foundation. All rights reserved.
6  * ======================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20
21 package org.onap.ccsdk.oran.a1policymanagementservice.controllers.v1;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.awaitility.Awaitility.await;
25 import static org.junit.jupiter.api.Assertions.assertEquals;
26 import static org.junit.jupiter.api.Assertions.assertTrue;
27 import static org.mockito.ArgumentMatchers.any;
28 import static org.mockito.Mockito.doReturn;
29
30 import com.google.gson.Gson;
31 import com.google.gson.GsonBuilder;
32 import com.google.gson.JsonArray;
33 import com.google.gson.JsonElement;
34 import com.google.gson.JsonParser;
35
36 import java.nio.charset.StandardCharsets;
37 import java.time.Duration;
38 import java.time.Instant;
39 import java.util.ArrayList;
40 import java.util.List;
41
42 import org.junit.jupiter.api.AfterEach;
43 import org.junit.jupiter.api.Test;
44 import org.junit.jupiter.api.extension.ExtendWith;
45 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
46 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
47 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
48 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
49 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ImmutableRicConfig;
50 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ImmutableWebClientConfig;
51 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig;
52 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.WebClientConfig;
53 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
54 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
55 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
56 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
57 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
58 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
59 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
60 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric.RicState;
61 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
62 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
63 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.RicSupervision;
64 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.ServiceSupervision;
65 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1Client;
66 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1ClientFactory;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
69 import org.springframework.beans.factory.annotation.Autowired;
70 import org.springframework.boot.test.context.SpringBootTest;
71 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
72 import org.springframework.boot.test.context.TestConfiguration;
73 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
74 import org.springframework.boot.web.server.LocalServerPort;
75 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
76 import org.springframework.context.ApplicationContext;
77 import org.springframework.context.annotation.Bean;
78 import org.springframework.http.HttpStatus;
79 import org.springframework.http.ResponseEntity;
80 import org.springframework.test.context.TestPropertySource;
81 import org.springframework.test.context.junit.jupiter.SpringExtension;
82 import org.springframework.web.reactive.function.client.WebClientResponseException;
83
84 import reactor.core.publisher.Mono;
85 import reactor.test.StepVerifier;
86 import reactor.util.annotation.Nullable;
87
88 @ExtendWith(SpringExtension.class)
89 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
90 @TestPropertySource(properties = { //
91         "server.ssl.key-store=./config/keystore.jks", //
92         "app.webclient.trust-store=./config/truststore.jks", //
93         "app.vardata-directory=./target"})
94 class ApplicationTest {
95     private static final Logger logger = LoggerFactory.getLogger(ApplicationTest.class);
96
97     @Autowired
98     ApplicationContext context;
99
100     @Autowired
101     private Rics rics;
102
103     @Autowired
104     private Policies policies;
105
106     @Autowired
107     private PolicyTypes policyTypes;
108
109     @Autowired
110     MockA1ClientFactory a1ClientFactory;
111
112     @Autowired
113     RicSupervision supervision;
114
115     @Autowired
116     ApplicationConfig applicationConfig;
117
118     @Autowired
119     Services services;
120
121     private static Gson gson = new GsonBuilder().create();
122
123     public static class MockApplicationConfig extends ApplicationConfig {
124         @Override
125         public String getLocalConfigurationFilePath() {
126             return ""; // No config file loaded for the test
127         }
128
129     }
130
131     /**
132      * Overrides the BeanFactory.
133      */
134     @TestConfiguration
135     static class TestBeanFactory {
136
137         @Bean
138         public ApplicationConfig getApplicationConfig() {
139             return new MockApplicationConfig();
140         }
141
142         @Bean
143         MockA1ClientFactory getA1ClientFactory(@Autowired ApplicationConfig appConfig, @Autowired PolicyTypes types) {
144             return new MockA1ClientFactory(appConfig, types);
145         }
146
147         @Bean
148         public ServiceSupervision getServiceSupervision(@Autowired Services services,
149                 @Autowired A1ClientFactory a1ClientFactory, @Autowired Policies policies) {
150             Duration checkInterval = Duration.ofMillis(1);
151             return new ServiceSupervision(services, policies, a1ClientFactory, checkInterval);
152         }
153
154         @Bean
155         public ServletWebServerFactory servletContainer() {
156             return new TomcatServletWebServerFactory();
157         }
158
159     }
160
161     @LocalServerPort
162     private int port;
163
164     @AfterEach
165     void reset() {
166         rics.clear();
167         policies.clear();
168         policyTypes.clear();
169         services.clear();
170         a1ClientFactory.reset();
171     }
172
173     @AfterEach
174     void verifyNoRicLocks() {
175         for (Ric ric : this.rics.getRics()) {
176             ric.getLock().lockBlocking(LockType.EXCLUSIVE);
177             ric.getLock().unlockBlocking();
178             assertThat(ric.getLock().getLockCounter()).isZero();
179             assertThat(ric.getState()).isEqualTo(Ric.RicState.AVAILABLE);
180         }
181     }
182
183     @Test
184     void testGetRics() throws Exception {
185         addRic("ric1");
186         this.addPolicyType("type1", "ric1");
187         String url = "/rics?policyType=type1";
188         String rsp = restClient().get(url).block();
189         assertThat(rsp).contains("ric1");
190
191         // nameless type for ORAN A1 1.1
192         addRic("ric2");
193         this.addPolicyType("", "ric2");
194         url = "/rics?policyType=";
195
196         rsp = restClient().get(url).block();
197         assertThat(rsp).contains("ric2") //
198                 .doesNotContain("ric1") //
199                 .contains("AVAILABLE");
200
201         // All RICs
202         rsp = restClient().get("/rics").block();
203         assertThat(rsp).contains("ric2") //
204                 .contains("ric1");
205
206         // Non existing policy type
207         url = "/rics?policyType=XXXX";
208         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
209     }
210
211     @Test
212     void testSynchronization() throws Exception {
213         // Two polictypes will be put in the NearRT RICs
214         PolicyTypes nearRtRicPolicyTypes = new PolicyTypes(this.applicationConfig);
215         nearRtRicPolicyTypes.put(createPolicyType("typeName"));
216         nearRtRicPolicyTypes.put(createPolicyType("typeName2"));
217         this.a1ClientFactory.setPolicyTypes(nearRtRicPolicyTypes);
218
219         // One type and one instance added to the Policy Management Service's storage
220         final String ric1Name = "ric1";
221         Ric ric1 = addRic(ric1Name);
222         Policy policy2 = addPolicy("policyId2", "typeName", "service", ric1Name);
223         Ric ric2 = addRic("ric2");
224
225         getA1Client(ric1Name).putPolicy(policy2); // put it in the RIC
226         policies.remove(policy2); // Remove it from the repo -> should be deleted in the RIC
227
228         String policyId = "policyId";
229         Policy policy = addPolicy(policyId, "typeName", "service", ric1Name); // This should be created in the RIC
230         supervision.checkAllRics(); // The created policy should be put in the RIC
231
232         // Wait until synch is completed
233         await().untilAsserted(() -> RicState.SYNCHRONIZING.equals(rics.getRic(ric1Name).getState()));
234         await().untilAsserted(() -> RicState.AVAILABLE.equals(rics.getRic(ric1Name).getState()));
235         await().untilAsserted(() -> RicState.AVAILABLE.equals(rics.getRic("ric2").getState()));
236
237         Policies ricPolicies = getA1Client(ric1Name).getPolicies();
238         assertThat(ricPolicies.size()).isEqualTo(1);
239         Policy ricPolicy = ricPolicies.get(policyId);
240         assertThat(ricPolicy.getJson()).isEqualTo(policy.getJson());
241
242         // Both types should be in the Policy Management Service's storage after the
243         // synch
244         assertThat(ric1.getSupportedPolicyTypes()).hasSize(2);
245         assertThat(ric2.getSupportedPolicyTypes()).hasSize(2);
246     }
247
248     @Test
249     void testGetRicForManagedElement_thenReturnCorrectRic() throws Exception {
250         String ricName = "ric1";
251         String managedElementId = "kista_1";
252         addRic(ricName, managedElementId);
253
254         String url = "/ric?managedElementId=" + managedElementId;
255         String rsp = restClient().get(url).block();
256         assertThat(rsp).isEqualTo(ricName);
257
258         // test GET RIC for ManagedElement that does not exist
259         url = "/ric?managedElementId=" + "junk";
260         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
261     }
262
263     private String putPolicyUrl(String serviceName, String ricName, String policyTypeName, String policyInstanceId,
264             boolean isTransient) {
265         String url;
266         if (policyTypeName.isEmpty()) {
267             url = "/policy?id=" + policyInstanceId + "&ric=" + ricName + "&service=" + serviceName;
268         } else {
269             url = "/policy?id=" + policyInstanceId + "&ric=" + ricName + "&service=" + serviceName + "&type="
270                     + policyTypeName;
271         }
272         if (isTransient) {
273             url += "&transient=true";
274         }
275         return url;
276     }
277
278     private String putPolicyUrl(String serviceName, String ricName, String policyTypeName, String policyInstanceId) {
279         return putPolicyUrl(serviceName, ricName, policyTypeName, policyInstanceId, false);
280     }
281
282     @Test
283     void testPutPolicy() throws Exception {
284         String serviceName = "service1";
285         String ricName = "ric1";
286         String policyTypeName = "type1";
287         String policyInstanceId = "instance1";
288
289         putService(serviceName);
290         addPolicyType(policyTypeName, ricName);
291
292         // PUT a transient policy
293         String url = putPolicyUrl(serviceName, ricName, policyTypeName, policyInstanceId, true);
294         final String policyBody = jsonString();
295         this.rics.getRic(ricName).setState(Ric.RicState.AVAILABLE);
296
297         restClient().put(url, policyBody).block();
298
299         Policy policy = policies.getPolicy(policyInstanceId);
300         assertThat(policy).isNotNull();
301         assertThat(policy.getId()).isEqualTo(policyInstanceId);
302         assertThat(policy.getOwnerServiceId()).isEqualTo(serviceName);
303         assertThat(policy.getRic().id()).isEqualTo("ric1");
304         assertThat(policy.isTransient()).isTrue();
305
306         // Put a non transient policy
307         url = putPolicyUrl(serviceName, ricName, policyTypeName, policyInstanceId);
308         restClient().put(url, policyBody).block();
309         policy = policies.getPolicy(policyInstanceId);
310         assertThat(policy.isTransient()).isFalse();
311
312         url = "/policies";
313         String rsp = restClient().get(url).block();
314         assertThat(rsp).as("Response contains policy instance ID.").contains(policyInstanceId);
315
316         url = "/policy?id=" + policyInstanceId;
317         rsp = restClient().get(url).block();
318         assertThat(rsp).isEqualTo(policyBody);
319
320         // Test of error codes
321         url = putPolicyUrl(serviceName, ricName + "XX", policyTypeName, policyInstanceId);
322         testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
323
324         url = putPolicyUrl(serviceName, ricName, policyTypeName + "XX", policyInstanceId);
325         addPolicyType(policyTypeName + "XX", "otherRic");
326         testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
327
328         url = putPolicyUrl(serviceName, ricName, policyTypeName, policyInstanceId);
329         this.rics.getRic(ricName).setState(Ric.RicState.SYNCHRONIZING);
330         testErrorCode(restClient().put(url, policyBody), HttpStatus.LOCKED);
331         this.rics.getRic(ricName).setState(Ric.RicState.AVAILABLE);
332     }
333
334     @Test
335     /**
336      * Test that HttpStatus and body from failing REST call to A1 is passed on to
337      * the caller.
338      *
339      * @throws ServiceException
340      */
341     void testErrorFromRic() throws ServiceException {
342         putService("service1");
343         addPolicyType("type1", "ric1");
344
345         String url = putPolicyUrl("service1", "ric1", "type1", "id1");
346         MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
347         HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
348         String responseBody = "Refused";
349         byte[] responseBodyBytes = responseBody.getBytes(StandardCharsets.UTF_8);
350
351         WebClientResponseException a1Exception = new WebClientResponseException(httpStatus.value(), "statusText", null,
352                 responseBodyBytes, StandardCharsets.UTF_8, null);
353         doReturn(Mono.error(a1Exception)).when(a1Client).putPolicy(any());
354
355         // PUT Policy
356         testErrorCode(restClient().put(url, "{}"), httpStatus, responseBody);
357
358         // DELETE POLICY
359         this.addPolicy("instance1", "type1", "service1", "ric1");
360         doReturn(Mono.error(a1Exception)).when(a1Client).deletePolicy(any());
361         testErrorCode(restClient().delete("/policy?id=instance1"), httpStatus, responseBody);
362
363         // GET STATUS
364         this.addPolicy("instance1", "type1", "service1", "ric1");
365         doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
366         testErrorCode(restClient().get("/policy_status?id=instance1"), httpStatus, responseBody);
367
368         // Check that empty response body is OK
369         a1Exception = new WebClientResponseException(httpStatus.value(), "", null, null, null, null);
370         doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
371         testErrorCode(restClient().get("/policy_status?id=instance1"), httpStatus);
372     }
373
374     @Test
375     void testPutTypelessPolicy() throws Exception {
376         putService("service1");
377         addPolicyType("", "ric1");
378         String url = putPolicyUrl("service1", "ric1", "", "id1");
379         restClient().put(url, jsonString()).block();
380
381         String rsp = restClient().get("/policies").block();
382         List<PolicyInfo> info = parseList(rsp, PolicyInfo.class);
383         assertThat(info).hasSize(1);
384         PolicyInfo policyInfo = info.get(0);
385         assertThat(policyInfo.id).isEqualTo("id1");
386         assertThat(policyInfo.type).isEmpty();
387     }
388
389     @Test
390     void testRefuseToUpdatePolicy() throws Exception {
391         // Test that only the json can be changed for a already created policy
392         // In this case service is attempted to be changed
393         this.addRic("ric1");
394         this.addRic("ricXXX");
395         this.addPolicy("instance1", "type1", "service1", "ric1");
396         this.addPolicy("instance2", "type1", "service1", "ricXXX");
397
398         // Try change ric1 -> ricXXX
399         String urlWrongRic = putPolicyUrl("service1", "ricXXX", "type1", "instance1");
400         testErrorCode(restClient().put(urlWrongRic, jsonString()), HttpStatus.CONFLICT);
401     }
402
403     @Test
404     void testGetPolicy() throws Exception {
405         String url = "/policy?id=id";
406         Policy policy = addPolicy("id", "typeName", "service1", "ric1");
407         {
408             String rsp = restClient().get(url).block();
409             assertThat(rsp).isEqualTo(policy.getJson());
410         }
411         {
412             policies.remove(policy);
413             testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
414         }
415     }
416
417     @Test
418     void testDeletePolicy() throws Exception {
419         addPolicy("id", "typeName", "service1", "ric1");
420         assertThat(policies.size()).isEqualTo(1);
421
422         String url = "/policy?id=id";
423         ResponseEntity<String> entity = restClient().deleteForEntity(url).block();
424
425         assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
426         assertThat(policies.size()).isZero();
427
428         // Delete a non existing policy
429         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
430     }
431
432     @Test
433     void testGetPolicySchemas() throws Exception {
434         addPolicyType("type1", "ric1");
435         addPolicyType("type2", "ric2");
436
437         String url = "/policy_schemas";
438         String rsp = this.restClient().get(url).block();
439         assertThat(rsp).contains("type1") //
440                 .contains("{\"title\":\"type2\"}");
441
442         List<String> info = parseSchemas(rsp);
443         assertThat(info).hasSize(2);
444
445         url = "/policy_schemas?ric=ric1";
446         rsp = restClient().get(url).block();
447         assertThat(rsp).contains("type1");
448         info = parseSchemas(rsp);
449         assertThat(info).hasSize(1);
450
451         // Get schema for non existing RIC
452         url = "/policy_schemas?ric=ric1XXX";
453         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
454     }
455
456     @Test
457     void testGetPolicySchema() throws Exception {
458         addPolicyType("type1", "ric1");
459         addPolicyType("type2", "ric2");
460
461         String url = "/policy_schema?id=type1";
462         String rsp = restClient().get(url).block();
463         logger.info(rsp);
464         assertThat(rsp).contains("type1") //
465                 .contains("title");
466
467         // Get non existing schema
468         url = "/policy_schema?id=type1XX";
469         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
470     }
471
472     @Test
473     void testGetPolicyTypes() throws Exception {
474         addPolicyType("type1", "ric1");
475         addPolicyType("type2", "ric2");
476
477         String url = "/policy_types";
478         String rsp = restClient().get(url).block();
479         assertThat(rsp).isEqualTo("[\"type2\",\"type1\"]");
480
481         url = "/policy_types?ric=ric1";
482         rsp = restClient().get(url).block();
483         assertThat(rsp).isEqualTo("[\"type1\"]");
484
485         // Get policy types for non existing RIC
486         url = "/policy_types?ric=ric1XXX";
487         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
488     }
489
490     @Test
491     void testGetPolicies() throws Exception {
492         addPolicy("id1", "type1", "service1");
493
494         String url = "/policies";
495         String rsp = restClient().get(url).block();
496         logger.info(rsp);
497         List<PolicyInfo> info = parseList(rsp, PolicyInfo.class);
498         assertThat(info).hasSize(1);
499         PolicyInfo policyInfo = info.get(0);
500         assert (policyInfo.validate());
501         assertThat(policyInfo.id).isEqualTo("id1");
502         assertThat(policyInfo.type).isEqualTo("type1");
503         assertThat(policyInfo.service).isEqualTo("service1");
504     }
505
506     @Test
507     void testGetPoliciesFilter() throws Exception {
508         addPolicy("id1", "type1", "service1");
509         addPolicy("id2", "type1", "service2");
510         addPolicy("id3", "type2", "service1");
511
512         String url = "/policies?type=type1";
513         String rsp = restClient().get(url).block();
514         logger.info(rsp);
515         assertThat(rsp).contains("id1") //
516                 .contains("id2") //
517                 .doesNotContain("id3");
518
519         url = "/policies?type=type1&service=service2";
520         rsp = restClient().get(url).block();
521         logger.info(rsp);
522         assertThat(rsp).doesNotContain("id1") //
523                 .contains("id2") //
524                 .doesNotContain("id3");
525
526         // Test get policies for non existing type
527         url = "/policies?type=type1XXX";
528         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
529
530         // Test get policies for non existing RIC
531         url = "/policies?ric=XXX";
532         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
533     }
534
535     @Test
536     void testGetPolicyIdsFilter() throws Exception {
537         addPolicy("id1", "type1", "service1", "ric1");
538         addPolicy("id2", "type1", "service2", "ric1");
539         addPolicy("id3", "type2", "service1", "ric1");
540
541         String url = "/policy_ids?type=type1";
542         String rsp = restClient().get(url).block();
543         logger.info(rsp);
544         assertThat(rsp).contains("id1") //
545                 .contains("id2") //
546                 .doesNotContain("id3");
547
548         url = "/policy_ids?type=type1&service=service1&ric=ric1";
549         rsp = restClient().get(url).block();
550         assertThat(rsp).isEqualTo("[\"id1\"]");
551
552         // Test get policy ids for non existing type
553         url = "/policy_ids?type=type1XXX";
554         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
555
556         // Test get policy ids for non existing RIC
557         url = "/policy_ids?ric=XXX";
558         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
559     }
560
561     @Test
562     void testPutAndGetService() throws Exception {
563         // PUT
564         String serviceName = "name";
565         putService(serviceName, 0, HttpStatus.CREATED);
566         putService(serviceName, 0, HttpStatus.OK);
567
568         // GET one service
569         String url = "/services?name=name";
570         String rsp = restClient().get(url).block();
571         List<ServiceStatus> info = parseList(rsp, ServiceStatus.class);
572         assertThat(info).hasSize(1);
573         ServiceStatus status = info.iterator().next();
574         assertThat(status.keepAliveIntervalSeconds).isZero();
575         assertThat(status.serviceName).isEqualTo(serviceName);
576
577         // GET (all)
578         url = "/services";
579         rsp = restClient().get(url).block();
580         assertThat(rsp).as("Response contains service name").contains(serviceName);
581         logger.info(rsp);
582
583         // Keep alive
584         url = "/services/keepalive?name=name";
585         ResponseEntity<String> entity = restClient().putForEntity(url).block();
586         assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
587
588         // DELETE service
589         assertThat(services.size()).isEqualTo(1);
590         url = "/services?name=name";
591         restClient().delete(url).block();
592         assertThat(services.size()).isZero();
593
594         // Keep alive, no registered service
595         testErrorCode(restClient().put("/services/keepalive?name=name", ""), HttpStatus.NOT_FOUND);
596
597         // PUT servive with bad payload
598         testErrorCode(restClient().put("/service", "crap"), HttpStatus.BAD_REQUEST);
599         testErrorCode(restClient().put("/service", "{}"), HttpStatus.BAD_REQUEST);
600         testErrorCode(restClient().put("/service", createServiceJson(serviceName, -123)), HttpStatus.BAD_REQUEST);
601         testErrorCode(restClient().put("/service", createServiceJson(serviceName, 0, "missing.portandprotocol.com")),
602                 HttpStatus.BAD_REQUEST);
603
604         // GET non existing service
605         testErrorCode(restClient().get("/services?name=XXX"), HttpStatus.NOT_FOUND);
606     }
607
608     @Test
609     void testServiceSupervision() throws Exception {
610         putService("service1", 1, HttpStatus.CREATED);
611         addPolicyType("type1", "ric1");
612
613         String url = putPolicyUrl("service1", "ric1", "type1", "instance1");
614         final String policyBody = jsonString();
615         restClient().put(url, policyBody).block();
616
617         assertThat(policies.size()).isEqualTo(1);
618         assertThat(services.size()).isEqualTo(1);
619
620         // Timeout after ~1 second
621         await().untilAsserted(() -> assertThat(policies.size()).isZero());
622         assertThat(services.size()).isZero();
623     }
624
625     @Test
626     void testGetPolicyStatus() throws Exception {
627         addPolicy("id", "typeName", "service1", "ric1");
628         assertThat(policies.size()).isEqualTo(1);
629
630         String url = "/policy_status?id=id";
631         String rsp = restClient().get(url).block();
632         assertThat(rsp).isEqualTo("OK");
633
634         // GET non existing policy status
635         url = "/policy_status?id=XXX";
636         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
637     }
638
639     private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
640         addRic(ric);
641         Policy policy = Policy.builder() //
642                 .id(id) //
643                 .json(jsonString()) //
644                 .ownerServiceId(service) //
645                 .ric(rics.getRic(ric)) //
646                 .type(addPolicyType(typeName, ric)) //
647                 .lastModified(Instant.now()) //
648                 .isTransient(false) //
649                 .statusNotificationUri("/policy_status?id=XXX") //
650                 .build();
651         policies.put(policy);
652         return policy;
653     }
654
655     private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
656         return addPolicy(id, typeName, service, "ric");
657     }
658
659     private String createServiceJson(String name, long keepAliveIntervalSeconds) {
660         return createServiceJson(name, keepAliveIntervalSeconds, "https://examples.javacodegeeks.com/core-java/");
661     }
662
663     private String createServiceJson(String name, long keepAliveIntervalSeconds, String url) {
664         ServiceRegistrationInfo service = new ServiceRegistrationInfo(name, keepAliveIntervalSeconds, url);
665
666         String json = gson.toJson(service);
667         return json;
668     }
669
670     private void putService(String name) {
671         putService(name, 0, null);
672     }
673
674     private void putService(String name, long keepAliveIntervalSeconds, @Nullable HttpStatus expectedStatus) {
675         String url = "/service";
676         String body = createServiceJson(name, keepAliveIntervalSeconds);
677         ResponseEntity<String> resp = restClient().putForEntity(url, body).block();
678         if (expectedStatus != null) {
679             assertEquals(expectedStatus, resp.getStatusCode(), "");
680         }
681     }
682
683     private String baseUrl() {
684         return "https://localhost:" + port;
685     }
686
687     private String jsonString() {
688         return "{\"servingCellNrcgi\":\"1\"}";
689     }
690
691     private AsyncRestClient restClient(boolean useTrustValidation) {
692         WebClientConfig config = this.applicationConfig.getWebClientConfig();
693         config = ImmutableWebClientConfig.builder() //
694                 .keyStoreType(config.keyStoreType()) //
695                 .keyStorePassword(config.keyStorePassword()) //
696                 .keyStore(config.keyStore()) //
697                 .keyPassword(config.keyPassword()) //
698                 .isTrustStoreUsed(useTrustValidation) //
699                 .trustStore(config.trustStore()) //
700                 .trustStorePassword(config.trustStorePassword()) //
701                 .httpProxyConfig(config.httpProxyConfig()) //
702                 .build();
703
704         AsyncRestClientFactory f = new AsyncRestClientFactory(config);
705         return f.createRestClientNoHttpProxy(baseUrl());
706     }
707
708     private AsyncRestClient restClient() {
709         return restClient(false);
710     }
711
712     private void testErrorCode(Mono<?> request, HttpStatus expStatus) {
713         testErrorCode(request, expStatus, "");
714     }
715
716     private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
717         StepVerifier.create(request) //
718                 .expectSubscription() //
719                 .expectErrorMatches(t -> checkWebClientError(t, expStatus, responseContains)) //
720                 .verify();
721     }
722
723     private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains) {
724         assertTrue(throwable instanceof WebClientResponseException);
725         WebClientResponseException responseException = (WebClientResponseException) throwable;
726         assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
727         assertThat(responseException.getResponseBodyAsString()).contains(responseContains);
728         return true;
729     }
730
731     private MockA1Client getA1Client(String ricName) throws ServiceException {
732         return a1ClientFactory.getOrCreateA1Client(ricName);
733     }
734
735     private PolicyType createPolicyType(String policyTypeName) {
736         return PolicyType.builder() //
737                 .id(policyTypeName) //
738                 .schema("{\"title\":\"" + policyTypeName + "\"}") //
739                 .build();
740     }
741
742     private PolicyType addPolicyType(String policyTypeName, String ricName) {
743         PolicyType type = createPolicyType(policyTypeName);
744         policyTypes.put(type);
745         addRic(ricName).addSupportedPolicyType(type);
746         return type;
747     }
748
749     private Ric addRic(String ricName) {
750         return addRic(ricName, null);
751     }
752
753     private Ric addRic(String ricName, String managedElement) {
754         if (rics.get(ricName) != null) {
755             return rics.get(ricName);
756         }
757         List<String> mes = new ArrayList<>();
758         if (managedElement != null) {
759             mes.add(managedElement);
760         }
761         RicConfig conf = ImmutableRicConfig.builder() //
762                 .ricId(ricName) //
763                 .baseUrl(ricName) //
764                 .managedElementIds(mes) //
765                 .controllerName("") //
766                 .build();
767         Ric ric = new Ric(conf);
768         ric.setState(Ric.RicState.AVAILABLE);
769         this.rics.put(ric);
770         return ric;
771     }
772
773     private static <T> List<T> parseList(String jsonString, Class<T> clazz) {
774         List<T> result = new ArrayList<>();
775         JsonArray jsonArr = JsonParser.parseString(jsonString).getAsJsonArray();
776         for (JsonElement jsonElement : jsonArr) {
777             T json = gson.fromJson(jsonElement.toString(), clazz);
778             result.add(json);
779         }
780         return result;
781     }
782
783     private static List<String> parseSchemas(String jsonString) {
784         JsonArray arrayOfSchema = JsonParser.parseString(jsonString).getAsJsonArray();
785         List<String> result = new ArrayList<>();
786         for (JsonElement schemaObject : arrayOfSchema) {
787             result.add(schemaObject.toString());
788         }
789         return result;
790     }
791 }