Merge "Update mrstub with nginx"
[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 public 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     static class MockApplicationConfig extends ApplicationConfig {
71         @Override
72         public String getLocalConfigurationFilePath() {
73             URL url = MockApplicationConfig.class.getClassLoader().getResource("test_application_configuration.json");
74             return url.getFile();
75         }
76     }
77
78     /**
79      * Overrides the BeanFactory.
80      */
81     @TestConfiguration
82     static class TestBeanFactory {
83
84         private final Rics rics = new Rics();
85         private final Policies policies = new Policies();
86         private final PolicyTypes policyTypes = new PolicyTypes();
87
88         @Bean
89         public ApplicationConfig getApplicationConfig() {
90             return new MockApplicationConfig();
91         }
92
93         @Bean
94         public MockA1ClientFactory getA1ClientFactory() {
95             PolicyTypes ricTypes = new PolicyTypes();
96             loadTypes(ricTypes);
97             return new MockA1ClientFactory(ricTypes);
98         }
99
100         @Bean
101         public Policies getPolicies() {
102             return this.policies;
103         }
104
105         @Bean
106         public PolicyTypes getPolicyTypes() {
107             return this.policyTypes;
108         }
109
110         @Bean
111         public Rics getRics() {
112             return this.rics;
113         }
114
115         private static File[] getResourceFolderFiles(String folder) {
116             return getFile(folder).listFiles();
117         }
118
119         private static String readFile(File file) throws IOException {
120             return new String(Files.readAllBytes(file.toPath()));
121         }
122
123         private void loadTypes(PolicyTypes policyTypes) {
124             File[] files = getResourceFolderFiles("policy_types/");
125             for (File file : files) {
126                 try {
127                     String schema = readFile(file);
128                     String typeName = title(schema);
129                     PolicyType type = ImmutablePolicyType.builder().name(typeName).schema(schema).build();
130                     policyTypes.put(type);
131                 } catch (Exception e) {
132                     logger.error("Could not load json schema ", e);
133                 }
134             }
135             policyTypes.put(ImmutablePolicyType.builder().name("").schema("{}").build());
136         }
137     }
138
139     private static File getFile(String path) {
140         ClassLoader loader = Thread.currentThread().getContextClassLoader();
141         URL url = loader.getResource(path);
142         return new File(url.getPath());
143     }
144
145     @LocalServerPort
146     private int port;
147
148     private void keepServerAlive() throws InterruptedException, IOException {
149         waitForConfigurationToBeLoaded();
150         loadInstances();
151         logger.info("Keeping server alive!");
152         synchronized (this) {
153             this.wait();
154         }
155     }
156
157     private void waitForConfigurationToBeLoaded() throws IOException {
158         String json = getConfigJsonFromFile();
159         try {
160             int noOfRicsInConfigFile = StringUtils.countOccurrencesOf(json, "baseUrl");
161             await().until(() -> rics.size() == noOfRicsInConfigFile);
162         } catch (Exception e) {
163             logger.info("Loaded rics: {}, and no of rics in config file: {} never matched!", rics.size(),
164                 StringUtils.countOccurrencesOf(json, "baseUrl"));
165         }
166     }
167
168     private static String title(String jsonSchema) {
169         JsonObject parsedSchema = (JsonObject) JsonParser.parseString(jsonSchema);
170         String title = parsedSchema.get("title").getAsString();
171         return title;
172     }
173
174     private void loadInstances() throws IOException {
175         PolicyType unnamedPolicyType = policyTypes.get("");
176         Ric ric = rics.get("ric1");
177         String json = getConfigJsonFromFile();
178
179         Policy policy = ImmutablePolicy.builder() //
180             .id("typelessPolicy") //
181             .json(json) //
182             .ownerServiceName("MockPolicyAgent") //
183             .ric(ric) //
184             .type(unnamedPolicyType) //
185             .lastModified("now") //
186             .isTransient(false) //
187             .build();
188         this.policies.put(policy);
189     }
190
191     private String getConfigJsonFromFile() throws IOException {
192         File jsonFile = getFile("test_application_configuration.json");
193         String json = new String(Files.readAllBytes(jsonFile.toPath()));
194         return json;
195     }
196
197     @Test
198     @SuppressWarnings("squid:S2699") // Tests should include assertions. This test is only for keeping the server alive,
199                                      // so it will only be confusing to add an assertion.
200     public void runMock() throws Exception {
201         keepServerAlive();
202     }
203
204 }