1202c0ff6dbcc04d5e7cb2bee959cd95b9e14b1d
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2024-2025 OpenInfra Foundation Europe. 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.util.v3;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import lombok.RequiredArgsConstructor;
26 import org.everit.json.schema.loader.SchemaLoader;
27 import org.json.JSONObject;
28 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
29 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
30 import org.onap.ccsdk.oran.a1policymanagementservice.models.v3.PolicyInformation;
31 import org.onap.ccsdk.oran.a1policymanagementservice.models.v3.PolicyObjectInformation;
32 import org.onap.ccsdk.oran.a1policymanagementservice.models.v3.PolicyTypeInformation;
33 import org.onap.ccsdk.oran.a1policymanagementservice.repository.*;
34 import org.onap.ccsdk.oran.a1policymanagementservice.service.v3.TokenService;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.springframework.beans.factory.annotation.Autowired;
38 import org.springframework.http.HttpHeaders;
39 import org.springframework.http.HttpStatus;
40 import org.springframework.stereotype.Component;
41 import reactor.core.publisher.Flux;
42 import org.springframework.web.server.ServerWebExchange;
43 import org.springframework.web.util.UriComponentsBuilder;
44 import reactor.core.publisher.Mono;
45
46 import java.lang.invoke.MethodHandles;
47 import java.time.Instant;
48 import java.util.Collection;
49 import java.util.UUID;
50 import java.util.stream.Collectors;
51
52 @Component
53 @RequiredArgsConstructor
54 public class Helper {
55
56     private final ApplicationConfig applicationConfig;
57
58     @Autowired
59     private TokenService tokenService;
60
61     private final Services services;
62
63     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
64
65     private static final Gson gson = new GsonBuilder().create();
66
67     public void keepServiceAlive(String name) {
68         Service s = this.services.get(name);
69         if (s != null) {
70             s.keepAlive();
71         }
72     }
73
74     public Mono<Ric> checkRicStateIdle(Ric ric) {
75         if (ric.getState() == Ric.RicState.AVAILABLE) {
76             return Mono.just(ric);
77         } else {
78             logger.debug("Request rejected Near-RT RIC not IDLE, ric: {}", ric);
79             ServiceException e = new ServiceException(
80                     "Near-RT RIC: is not operational, id: " + ric.id() + ", state: " + ric.getState(),
81                     HttpStatus.LOCKED);
82             return Mono.error(e);
83         }
84     }
85
86     public Mono<Ric> checkSupportedType(Ric ric, PolicyType type) {
87         if (!ric.isSupportingType(type.getId())) {
88             logger.debug("Request rejected, type not supported, RIC: {}", ric);
89             ServiceException e = new ServiceException(
90                     "Type: " + type.getId() + " not supported by RIC: " + ric.id(), HttpStatus.BAD_REQUEST);
91             return Mono.error(e);
92         }
93         return Mono.just(ric);
94     }
95
96     public Policy buildPolicy(PolicyObjectInformation policyObjectInformation, PolicyType policyType, Ric ric, String policyId, ServerWebExchange exchange) {
97         return Policy.builder()
98                 .id(policyId)
99                 .json(toJson(policyObjectInformation.getPolicyObject()))
100                 .type(policyType)
101                 .ric(ric)
102                 .ownerServiceId(tokenService.getServiceId(policyObjectInformation, exchange))
103                 .lastModified(Instant.now())
104                 .isTransient(policyObjectInformation.getTransient())
105                 .build();
106     }
107
108     public Boolean jsonSchemaValidation(Object jsonObject) {
109         toJson(jsonObject);
110         return true;
111     }
112
113     private boolean policyTypeSchemaValidation(Policy policy, PolicyType policyType) {
114         try {
115             JSONObject schemaJson = new JSONObject(policyType.getSchema());
116             var schema = SchemaLoader.load(schemaJson);
117             JSONObject policyJson = new JSONObject(policy.getJson());
118
119             // PUT request body is not automatically deserialized - so we manually extract the desired policy object
120             if (policyJson.has("policyObject")) {
121                 policyJson = policyJson.getJSONObject("policyObject");
122             }
123
124             schema.validate(policyJson);
125             logger.info("Policy type schema validation successful");
126             return true; // Validation passed
127         } catch (Exception e) {
128             logger.error("Policy type schema validation failed", e);
129             return false; // Validation failed
130         }
131     }
132
133     public Boolean performPolicySchemaValidation(Policy policy, PolicyType policyType) {
134
135         switch (applicationConfig.getValidatePolicyInstanceSchema()) {
136             case INFO:
137                 if (policyTypeSchemaValidation(policy, policyType)) {
138                     return true;
139                 }
140                 logger.info("Policy Schema validation failed but not enforced.");
141                 return true;
142             case WARN:
143                 if (policyTypeSchemaValidation(policy, policyType)) {
144                     return true;
145                 }
146                 logger.warn("Policy Schema validation failed but not enforced.");
147                 return true;
148             case FAIL:
149                 if (policyTypeSchemaValidation(policy, policyType)) {
150                     return true;
151                 }
152                 logger.error("Policy Schema validation failed.");
153                 return false;
154             default:
155                 logger.info("Policy schema validation disabled.");
156                 return true;
157         }
158     }
159
160     public String policyIdGeneration(PolicyObjectInformation policyObjectInfo) {
161         if (policyObjectInfo.getPolicyId() == null || policyObjectInfo.getPolicyId().isEmpty() ||
162                 policyObjectInfo.getPolicyId().isBlank())
163             return UUID.randomUUID().toString();
164         else
165             return policyObjectInfo.getPolicyId().trim();
166     }
167
168     public String toJson(Object jsonObject) {
169         return gson.toJson(jsonObject);
170     }
171
172     public HttpHeaders createHttpHeaders(String headerName, String headerValue) {
173         HttpHeaders httpHeaders = new HttpHeaders();
174         httpHeaders.add(headerName, headerValue);
175         return httpHeaders;
176     }
177
178     public String buildURI(String policyId, ServerWebExchange serverWebExchange) {
179         return UriComponentsBuilder.fromUri(serverWebExchange.getRequest().getURI())
180                 .path("/{id}")
181                 .buildAndExpand(policyId)
182                 .toString();
183     }
184
185     public Mono<Policy> isPolicyAlreadyCreated(Policy policy, Policies policies) {
186         if (policies.get(policy.getId()) != null) {
187             return Mono.error(new ServiceException
188                     ("Policy already created with ID: " + policy.getId(), HttpStatus.CONFLICT));
189         }
190             return Mono.just(policy);
191     }
192
193     public Flux<PolicyInformation> toFluxPolicyInformation(Collection<Policy> policyCollection) {
194         return Flux.fromIterable(policyCollection.stream()
195                 .map(singlePolicy -> new PolicyInformation(singlePolicy.getId(), singlePolicy.getRic().getConfig().getRicId()))
196                 .collect(Collectors.toList()));
197     }
198
199     public Collection<PolicyTypeInformation> toPolicyTypeInfoCollection(Collection<PolicyType> policyTypeCollection, Ric ric) {
200         return policyTypeCollection.stream()
201                 .map(type -> new PolicyTypeInformation(type.getId(), ric.getConfig().getRicId()))
202                 .collect(Collectors.toList());
203     }
204 }