2 * ========================LICENSE_START=================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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===================================
21 package org.onap.ccsdk.oran.a1policymanagementservice.util.v3;
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;
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;
53 @RequiredArgsConstructor
56 private final ApplicationConfig applicationConfig;
59 private TokenService tokenService;
61 private final Services services;
63 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
65 private static final Gson gson = new GsonBuilder().create();
67 public void keepServiceAlive(String name) {
68 Service s = this.services.get(name);
74 public Mono<Ric> checkRicStateIdle(Ric ric) {
75 if (ric.getState() == Ric.RicState.AVAILABLE) {
76 return Mono.just(ric);
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(),
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);
93 return Mono.just(ric);
96 public Policy buildPolicy(PolicyObjectInformation policyObjectInformation, PolicyType policyType, Ric ric, String policyId, ServerWebExchange exchange) {
97 return Policy.builder()
99 .json(toJson(policyObjectInformation.getPolicyObject()))
102 .ownerServiceId(tokenService.getServiceId(policyObjectInformation, exchange))
103 .lastModified(Instant.now())
104 .isTransient(policyObjectInformation.getTransient())
108 public Boolean jsonSchemaValidation(Object jsonObject) {
113 private boolean policyTypeSchemaValidation(Policy policy, PolicyType policyType) {
115 JSONObject schemaJson = new JSONObject(policyType.getSchema());
116 var schema = SchemaLoader.load(schemaJson);
117 JSONObject policyJson = new JSONObject(policy.getJson());
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");
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
133 public Boolean performPolicySchemaValidation(Policy policy, PolicyType policyType) {
135 switch (applicationConfig.getValidatePolicyInstanceSchema()) {
137 if (policyTypeSchemaValidation(policy, policyType)) {
140 logger.info("Policy Schema validation failed but not enforced.");
143 if (policyTypeSchemaValidation(policy, policyType)) {
146 logger.warn("Policy Schema validation failed but not enforced.");
149 if (policyTypeSchemaValidation(policy, policyType)) {
152 logger.error("Policy Schema validation failed.");
155 logger.info("Policy schema validation disabled.");
160 public String policyIdGeneration(PolicyObjectInformation policyObjectInfo) {
161 if (policyObjectInfo.getPolicyId() == null || policyObjectInfo.getPolicyId().isEmpty() ||
162 policyObjectInfo.getPolicyId().isBlank())
163 return UUID.randomUUID().toString();
165 return policyObjectInfo.getPolicyId().trim();
168 public String toJson(Object jsonObject) {
169 return gson.toJson(jsonObject);
172 public HttpHeaders createHttpHeaders(String headerName, String headerValue) {
173 HttpHeaders httpHeaders = new HttpHeaders();
174 httpHeaders.add(headerName, headerValue);
178 public String buildURI(String policyId, ServerWebExchange serverWebExchange) {
179 return UriComponentsBuilder.fromUri(serverWebExchange.getRequest().getURI())
181 .buildAndExpand(policyId)
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));
190 return Mono.just(policy);
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()));
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());