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