Remove Sonar warnings
[nonrtric.git] / policy-agent / src / test / java / org / oransc / policyagent / MockPolicyAgent.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.awaitility.Awaitility.await;
24
25 import com.google.gson.JsonObject;
26 import com.google.gson.JsonParser;
27
28 import java.io.File;
29 import java.io.IOException;
30 import java.net.URL;
31 import java.nio.file.Files;
32
33 import org.junit.jupiter.api.Test;
34 import org.junit.jupiter.api.extension.ExtendWith;
35 import org.oransc.policyagent.configuration.ApplicationConfig;
36 import org.oransc.policyagent.repository.ImmutablePolicy;
37 import org.oransc.policyagent.repository.ImmutablePolicyType;
38 import org.oransc.policyagent.repository.Policies;
39 import org.oransc.policyagent.repository.Policy;
40 import org.oransc.policyagent.repository.PolicyType;
41 import org.oransc.policyagent.repository.PolicyTypes;
42 import org.oransc.policyagent.repository.Ric;
43 import org.oransc.policyagent.repository.Rics;
44 import org.oransc.policyagent.utils.MockA1ClientFactory;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.boot.test.context.SpringBootTest;
49 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
50 import org.springframework.boot.test.context.TestConfiguration;
51 import org.springframework.boot.web.server.LocalServerPort;
52 import org.springframework.context.annotation.Bean;
53 import org.springframework.test.context.junit.jupiter.SpringExtension;
54 import org.springframework.util.StringUtils;
55
56 @ExtendWith(SpringExtension.class)
57 @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
58 class MockPolicyAgent {
59     private static final Logger logger = LoggerFactory.getLogger(MockPolicyAgent.class);
60
61     @Autowired
62     Rics rics;
63
64     @Autowired
65     Policies policies;
66
67     @Autowired
68     PolicyTypes policyTypes;
69
70     @Autowired
71     ApplicationConfig applicationConfig;
72
73     static class MockApplicationConfig extends ApplicationConfig {
74         @Override
75         public String getLocalConfigurationFilePath() {
76             URL url = MockApplicationConfig.class.getClassLoader().getResource("test_application_configuration.json");
77             return url.getFile();
78         }
79     }
80
81     /**
82      * Overrides the BeanFactory.
83      */
84     @TestConfiguration
85     static class TestBeanFactory {
86
87         private final Rics rics = new Rics();
88         private final Policies policies = new Policies();
89         private final PolicyTypes policyTypes = new PolicyTypes();
90
91         @Bean
92         public ApplicationConfig getApplicationConfig() {
93             return new MockApplicationConfig();
94         }
95
96         @Bean
97         public MockA1ClientFactory getA1ClientFactory() {
98             PolicyTypes ricTypes = new PolicyTypes();
99             loadTypes(ricTypes);
100             return new MockA1ClientFactory(ricTypes);
101         }
102
103         @Bean
104         public Policies getPolicies() {
105             return this.policies;
106         }
107
108         @Bean
109         public PolicyTypes getPolicyTypes() {
110             return this.policyTypes;
111         }
112
113         @Bean
114         public Rics getRics() {
115             return this.rics;
116         }
117
118         private static File[] getResourceFolderFiles(String folder) {
119             return getFile(folder).listFiles();
120         }
121
122         private static String readFile(File file) throws IOException {
123             return new String(Files.readAllBytes(file.toPath()));
124         }
125
126         private void loadTypes(PolicyTypes policyTypes) {
127             File[] files = getResourceFolderFiles("policy_types/");
128             for (File file : files) {
129                 try {
130                     String schema = readFile(file);
131                     String typeName = title(schema);
132                     PolicyType type = ImmutablePolicyType.builder().name(typeName).schema(schema).build();
133                     policyTypes.put(type);
134                 } catch (Exception e) {
135                     logger.error("Could not load json schema ", e);
136                 }
137             }
138             policyTypes.put(ImmutablePolicyType.builder().name("").schema("{}").build());
139         }
140     }
141
142     private static File getFile(String path) {
143         ClassLoader loader = Thread.currentThread().getContextClassLoader();
144         URL url = loader.getResource(path);
145         return new File(url.getPath());
146     }
147
148     @LocalServerPort
149     private int port;
150
151     private void keepServerAlive() throws InterruptedException, IOException {
152         waitForConfigurationToBeLoaded();
153         loadInstances();
154         logger.info("Keeping server alive!");
155         synchronized (this) {
156             this.wait();
157         }
158     }
159
160     private void waitForConfigurationToBeLoaded() throws IOException {
161         String json = getConfigJsonFromFile();
162         try {
163             int noOfRicsInConfigFile = StringUtils.countOccurrencesOf(json, "baseUrl");
164             await().until(() -> rics.size() == noOfRicsInConfigFile);
165         } catch (Exception e) {
166             logger.info("Loaded rics: {}, and no of rics in config file: {} never matched!", rics.size(),
167                 StringUtils.countOccurrencesOf(json, "baseUrl"));
168         }
169     }
170
171     private static String title(String jsonSchema) {
172         JsonObject parsedSchema = (JsonObject) JsonParser.parseString(jsonSchema);
173         String title = parsedSchema.get("title").getAsString();
174         return title;
175     }
176
177     private void loadInstances() throws IOException {
178         PolicyType unnamedPolicyType = policyTypes.get("");
179         Ric ric = rics.get("ric1");
180         String json = getConfigJsonFromFile();
181
182         Policy policy = ImmutablePolicy.builder() //
183             .id("typelessPolicy") //
184             .json(json) //
185             .ownerServiceName("MockPolicyAgent") //
186             .ric(ric) //
187             .type(unnamedPolicyType) //
188             .lastModified("now") //
189             .isTransient(false) //
190             .build();
191         this.policies.put(policy);
192     }
193
194     private String getConfigJsonFromFile() throws IOException {
195         File jsonFile = getFile("test_application_configuration.json");
196         String json = new String(Files.readAllBytes(jsonFile.toPath()));
197         return json;
198     }
199
200     @Test
201     @SuppressWarnings("squid:S2699") // Tests should include assertions. This test is only for keeping the server
202                                      // alive, so it will only be confusing to add an assertion.
203     void runMock() throws Exception {
204         keepServerAlive();
205     }
206
207 }