Merge "Added check of callback URL in service registration"
[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
359         // Try change ric1 -> ricXXX
360         String urlWrongRic = putPolicyUrl("service1", "ricXXX", "type1", "instance1");
361         testErrorCode(restClient().put(urlWrongRic, jsonString()), HttpStatus.CONFLICT);
362     }
363
364     @Test
365     public void testGetPolicy() throws Exception {
366         String url = "/policy?id=id";
367         Policy policy = addPolicy("id", "typeName", "service1", "ric1");
368         {
369             String rsp = restClient().get(url).block();
370             assertThat(rsp).isEqualTo(policy.json());
371         }
372         {
373             policies.remove(policy);
374             testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
375         }
376     }
377
378     @Test
379     public void testDeletePolicy() throws Exception {
380         addPolicy("id", "typeName", "service1", "ric1");
381         assertThat(policies.size()).isEqualTo(1);
382
383         String url = "/policy?id=id";
384         ResponseEntity<String> entity = restClient().deleteForEntity(url).block();
385
386         assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
387         assertThat(policies.size()).isEqualTo(0);
388
389         // Delete a non existing policy
390         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
391     }
392
393     @Test
394     public void testGetPolicySchemas() throws Exception {
395         addPolicyType("type1", "ric1");
396         addPolicyType("type2", "ric2");
397
398         String url = "/policy_schemas";
399         String rsp = this.restClient().get(url).block();
400         assertThat(rsp).contains("type1");
401         assertThat(rsp).contains("[{\"title\":\"type2\"}");
402
403         List<String> info = parseSchemas(rsp);
404         assertThat(info.size()).isEqualTo(2);
405
406         url = "/policy_schemas?ric=ric1";
407         rsp = restClient().get(url).block();
408         assertThat(rsp).contains("type1");
409         info = parseSchemas(rsp);
410         assertThat(info.size()).isEqualTo(1);
411
412         // Get schema for non existing RIC
413         url = "/policy_schemas?ric=ric1XXX";
414         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
415     }
416
417     @Test
418     public void testGetPolicySchema() throws Exception {
419         addPolicyType("type1", "ric1");
420         addPolicyType("type2", "ric2");
421
422         String url = "/policy_schema?id=type1";
423         String rsp = restClient().get(url).block();
424         logger.info(rsp);
425         assertThat(rsp).contains("type1");
426         assertThat(rsp).contains("title");
427
428         // Get non existing schema
429         url = "/policy_schema?id=type1XX";
430         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
431     }
432
433     @Test
434     public void testGetPolicyTypes() throws Exception {
435         addPolicyType("type1", "ric1");
436         addPolicyType("type2", "ric2");
437
438         String url = "/policy_types";
439         String rsp = restClient().get(url).block();
440         assertThat(rsp).isEqualTo("[\"type2\",\"type1\"]");
441
442         url = "/policy_types?ric=ric1";
443         rsp = restClient().get(url).block();
444         assertThat(rsp).isEqualTo("[\"type1\"]");
445
446         // Get policy types for non existing RIC
447         url = "/policy_types?ric=ric1XXX";
448         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
449     }
450
451     @Test
452     public void testGetPolicies() throws Exception {
453         addPolicy("id1", "type1", "service1");
454
455         String url = "/policies";
456         String rsp = restClient().get(url).block();
457         logger.info(rsp);
458         List<PolicyInfo> info = parseList(rsp, PolicyInfo.class);
459         assertThat(info).size().isEqualTo(1);
460         PolicyInfo policyInfo = info.get(0);
461         assert (policyInfo.validate());
462         assertThat(policyInfo.id).isEqualTo("id1");
463         assertThat(policyInfo.type).isEqualTo("type1");
464         assertThat(policyInfo.service).isEqualTo("service1");
465     }
466
467     @Test
468     public void testGetPoliciesFilter() throws Exception {
469         addPolicy("id1", "type1", "service1");
470         addPolicy("id2", "type1", "service2");
471         addPolicy("id3", "type2", "service1");
472
473         String url = "/policies?type=type1";
474         String rsp = restClient().get(url).block();
475         logger.info(rsp);
476         assertThat(rsp).contains("id1");
477         assertThat(rsp).contains("id2");
478         assertThat(rsp.contains("id3")).isFalse();
479
480         url = "/policies?type=type1&service=service2";
481         rsp = restClient().get(url).block();
482         logger.info(rsp);
483         assertThat(rsp.contains("id1")).isFalse();
484         assertThat(rsp).contains("id2");
485         assertThat(rsp.contains("id3")).isFalse();
486
487         // Test get policies for non existing type
488         url = "/policies?type=type1XXX";
489         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
490
491         // Test get policies for non existing RIC
492         url = "/policies?ric=XXX";
493         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
494     }
495
496     @Test
497     public void testGetPolicyIdsFilter() throws Exception {
498         addPolicy("id1", "type1", "service1", "ric1");
499         addPolicy("id2", "type1", "service2", "ric1");
500         addPolicy("id3", "type2", "service1", "ric1");
501
502         String url = "/policy_ids?type=type1";
503         String rsp = restClient().get(url).block();
504         logger.info(rsp);
505         assertThat(rsp).contains("id1");
506         assertThat(rsp).contains("id2");
507         assertThat(rsp.contains("id3")).isFalse();
508
509         url = "/policy_ids?type=type1&service=service1&ric=ric1";
510         rsp = restClient().get(url).block();
511         assertThat(rsp).isEqualTo("[\"id1\"]");
512
513         // Test get policy ids for non existing type
514         url = "/policy_ids?type=type1XXX";
515         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
516
517         // Test get policy ids for non existing RIC
518         url = "/policy_ids?ric=XXX";
519         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
520     }
521
522     @Test
523     public void testPutAndGetService() throws Exception {
524         // PUT
525         putService("name", 0, HttpStatus.CREATED);
526         putService("name", 0, HttpStatus.OK);
527
528         // GET one service
529         String url = "/services?name=name";
530         String rsp = restClient().get(url).block();
531         List<ServiceStatus> info = parseList(rsp, ServiceStatus.class);
532         assertThat(info.size()).isEqualTo(1);
533         ServiceStatus status = info.iterator().next();
534         assertThat(status.keepAliveIntervalSeconds).isEqualTo(0);
535         assertThat(status.serviceName).isEqualTo("name");
536
537         // GET (all)
538         url = "/services";
539         rsp = restClient().get(url).block();
540         assertThat(rsp.contains("name")).isTrue();
541         logger.info(rsp);
542
543         // Keep alive
544         url = "/services/keepalive?name=name";
545         ResponseEntity<String> entity = restClient().putForEntity(url).block();
546         assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
547
548         // DELETE service
549         assertThat(services.size()).isEqualTo(1);
550         url = "/services?name=name";
551         restClient().delete(url).block();
552         assertThat(services.size()).isEqualTo(0);
553
554         // Keep alive, no registerred service
555         testErrorCode(restClient().put("/services/keepalive?name=name", ""), HttpStatus.NOT_FOUND);
556
557         // PUT servive with bad payload
558         testErrorCode(restClient().put("/service", "crap"), HttpStatus.BAD_REQUEST);
559         testErrorCode(restClient().put("/service", "{}"), HttpStatus.BAD_REQUEST);
560         testErrorCode(restClient().put("/service", createServiceJson("name", -123)), HttpStatus.BAD_REQUEST);
561         testErrorCode(restClient().put("/service", createServiceJson("name", 0, "missing.portandprotocol.com")),
562             HttpStatus.BAD_REQUEST);
563
564         // GET non existing servive
565         testErrorCode(restClient().get("/services?name=XXX"), HttpStatus.NOT_FOUND);
566     }
567
568     @Test
569     public void testServiceSupervision() throws Exception {
570         putService("service1", 1, HttpStatus.CREATED);
571         addPolicyType("type1", "ric1");
572
573         String url = putPolicyUrl("service1", "ric1", "type1", "instance1");
574         final String policyBody = jsonString();
575         restClient().put(url, policyBody).block();
576
577         assertThat(policies.size()).isEqualTo(1);
578         assertThat(services.size()).isEqualTo(1);
579
580         // Timeout after ~1 second
581         await().untilAsserted(() -> assertThat(policies.size()).isEqualTo(0));
582         assertThat(services.size()).isEqualTo(0);
583     }
584
585     @Test
586     public void testGetPolicyStatus() throws Exception {
587         addPolicy("id", "typeName", "service1", "ric1");
588         assertThat(policies.size()).isEqualTo(1);
589
590         String url = "/policy_status?id=id";
591         String rsp = restClient().get(url).block();
592         assertThat(rsp.equals("OK")).isTrue();
593
594         // GET non existing policy status
595         url = "/policy_status?id=XXX";
596         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
597     }
598
599     private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
600         addRic(ric);
601         Policy p = ImmutablePolicy.builder().id(id) //
602             .json(jsonString()) //
603             .ownerServiceName(service) //
604             .ric(rics.getRic(ric)) //
605             .type(addPolicyType(typeName, ric)) //
606             .lastModified("lastModified").build();
607         policies.put(p);
608         return p;
609     }
610
611     private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
612         return addPolicy(id, typeName, service, "ric");
613     }
614
615     private String createServiceJson(String name, long keepAliveIntervalSeconds) {
616         return createServiceJson(name, keepAliveIntervalSeconds, "https://examples.javacodegeeks.com/core-java/");
617     }
618
619     private String createServiceJson(String name, long keepAliveIntervalSeconds, String url) {
620         ServiceRegistrationInfo service = new ServiceRegistrationInfo(name, keepAliveIntervalSeconds, url);
621
622         String json = gson.toJson(service);
623         return json;
624     }
625
626     private void putService(String name) {
627         putService(name, 0, null);
628     }
629
630     private void putService(String name, long keepAliveIntervalSeconds, @Nullable HttpStatus expectedStatus) {
631         String url = "/service";
632         String body = createServiceJson(name, keepAliveIntervalSeconds);
633         ResponseEntity<String> resp = restClient().putForEntity(url, body).block();
634         if (expectedStatus != null) {
635             assertEquals(expectedStatus, resp.getStatusCode(), "");
636         }
637     }
638
639     private String baseUrl() {
640         return "http://localhost:" + port;
641     }
642
643     private String jsonString() {
644         return "{\n  \"servingCellNrcgi\": \"1\"\n }";
645     }
646
647     @Test
648     public void testConcurrency() throws Exception {
649         final Instant startTime = Instant.now();
650         List<Thread> threads = new ArrayList<>();
651         a1ClientFactory.setResponseDelay(Duration.ofMillis(1));
652         addRic("ric");
653         addPolicyType("type1", "ric");
654         addPolicyType("type2", "ric");
655
656         for (int i = 0; i < 100; ++i) {
657             Thread t =
658                 new Thread(new ConcurrencyTestRunnable(baseUrl(), supervision, a1ClientFactory, rics, policyTypes),
659                     "TestThread_" + i);
660             t.start();
661             threads.add(t);
662         }
663         for (Thread t : threads) {
664             t.join();
665         }
666         assertThat(policies.size()).isEqualTo(0);
667         logger.info("Concurrency test took " + Duration.between(startTime, Instant.now()));
668     }
669
670     private AsyncRestClient restClient() {
671         return new AsyncRestClient(baseUrl());
672     }
673
674     private void testErrorCode(Mono<?> request, HttpStatus expStatus) {
675         testErrorCode(request, expStatus, "");
676     }
677
678     private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
679         StepVerifier.create(request) //
680             .expectSubscription() //
681             .expectErrorMatches(t -> checkWebClientError(t, expStatus, responseContains)) //
682             .verify();
683     }
684
685     private boolean checkWebClientError(Throwable t, HttpStatus expStatus, String responseContains) {
686         assertTrue(t instanceof WebClientResponseException);
687         WebClientResponseException e = (WebClientResponseException) t;
688         assertThat(e.getStatusCode()).isEqualTo(expStatus);
689         assertThat(e.getResponseBodyAsString()).contains(responseContains);
690         return true;
691     }
692
693     private MockA1Client getA1Client(String ricName) throws ServiceException {
694         return a1ClientFactory.getOrCreateA1Client(ricName);
695     }
696
697     private PolicyType addPolicyType(String policyTypeName, String ricName) {
698         PolicyType type = ImmutablePolicyType.builder() //
699             .name(policyTypeName) //
700             .schema("{\"title\":\"" + policyTypeName + "\"}") //
701             .build();
702
703         policyTypes.put(type);
704         addRic(ricName).addSupportedPolicyType(type);
705         return type;
706     }
707
708     private Ric addRic(String ricName) {
709         return addRic(ricName, null);
710     }
711
712     private Ric addRic(String ricName, String managedElement) {
713         if (rics.get(ricName) != null) {
714             return rics.get(ricName);
715         }
716         List<String> mes = new ArrayList<>();
717         if (managedElement != null) {
718             mes.add(managedElement);
719         }
720         RicConfig conf = ImmutableRicConfig.builder() //
721             .name(ricName) //
722             .baseUrl(ricName) //
723             .managedElementIds(mes) //
724             .controllerName("") //
725             .build();
726         Ric ric = new Ric(conf);
727         ric.setState(Ric.RicState.AVAILABLE);
728         this.rics.put(ric);
729         return ric;
730     }
731
732     private static <T> List<T> parseList(String jsonString, Class<T> clazz) {
733         List<T> result = new ArrayList<>();
734         JsonArray jsonArr = JsonParser.parseString(jsonString).getAsJsonArray();
735         for (JsonElement jsonElement : jsonArr) {
736             T o = gson.fromJson(jsonElement.toString(), clazz);
737             result.add(o);
738         }
739         return result;
740     }
741
742     private static List<String> parseSchemas(String jsonString) {
743         JsonArray arrayOfSchema = JsonParser.parseString(jsonString).getAsJsonArray();
744         List<String> result = new ArrayList<>();
745         for (JsonElement schemaObject : arrayOfSchema) {
746             result.add(schemaObject.toString());
747         }
748         return result;
749     }
750 }