8f3be34a42a88a5840fa56e216eddb2c8abcee93
[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.onap.ccsdk.oran.a1policymanagementservice.exceptions.InvalidRequestException;
27 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
28 import org.onap.ccsdk.oran.a1policymanagementservice.models.v3.PolicyInformation;
29 import org.onap.ccsdk.oran.a1policymanagementservice.models.v3.PolicyObjectInformation;
30 import org.onap.ccsdk.oran.a1policymanagementservice.models.v3.PolicyTypeInformation;
31 import org.onap.ccsdk.oran.a1policymanagementservice.repository.*;
32 import org.onap.ccsdk.oran.a1policymanagementservice.service.v3.TokenService;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import org.springframework.beans.factory.annotation.Autowired;
36 import org.springframework.http.HttpHeaders;
37 import org.springframework.http.HttpStatus;
38 import org.springframework.stereotype.Component;
39 import reactor.core.publisher.Flux;
40 import org.springframework.web.server.ServerWebExchange;
41 import org.springframework.web.util.UriComponentsBuilder;
42 import reactor.core.publisher.Mono;
43
44 import java.lang.invoke.MethodHandles;
45 import java.time.Instant;
46 import java.util.Collection;
47 import java.util.Set;
48 import java.util.UUID;
49 import java.util.stream.Collectors;
50
51 @Component
52 @RequiredArgsConstructor
53 public class Helper {
54
55     @Autowired
56     private TokenService tokenService;
57
58     private final Services services;
59
60     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
61
62     private static final Gson gson = new GsonBuilder().create();
63
64     public void keepServiceAlive(String name) {
65         Service s = this.services.get(name);
66         if (s != null) {
67             s.keepAlive();
68         }
69     }
70
71     public Mono<Ric> checkRicStateIdle(Ric ric) {
72         if (ric.getState() == Ric.RicState.AVAILABLE) {
73             return Mono.just(ric);
74         } else {
75             logger.debug("Request rejected Near-RT RIC not IDLE, ric: {}", ric);
76             ServiceException e = new ServiceException(
77                     "Near-RT RIC: is not operational, id: " + ric.id() + ", state: " + ric.getState(),
78                     HttpStatus.LOCKED);
79             return Mono.error(e);
80         }
81     }
82
83     public Mono<Ric> checkSupportedType(Ric ric, PolicyType type) {
84         if (!ric.isSupportingType(type.getId())) {
85             logger.debug("Request rejected, type not supported, RIC: {}", ric);
86             ServiceException e = new ServiceException(
87                     "Type: " + type.getId() + " not supported by RIC: " + ric.id(), HttpStatus.BAD_REQUEST);
88             return Mono.error(e);
89         }
90         return Mono.just(ric);
91     }
92
93     public Policy buildPolicy(PolicyObjectInformation policyObjectInformation, PolicyType policyType, Ric ric, String policyId, ServerWebExchange exchange) {
94         return Policy.builder()
95                 .id(policyId)
96                 .json(toJson(policyObjectInformation.getPolicyObject()))
97                 .type(policyType)
98                 .ric(ric)
99                 .ownerServiceId(tokenService.getServiceId(policyObjectInformation, exchange))
100                 .lastModified(Instant.now())
101                 .isTransient(policyObjectInformation.getTransient())
102                 .build();
103     }
104
105     public Boolean jsonSchemaValidation(Object jsonObject) {
106         toJson(jsonObject);
107         return true;
108     }
109
110     public String policyIdGeneration(PolicyObjectInformation policyObjectInfo) {
111         if (policyObjectInfo.getPolicyId() == null || policyObjectInfo.getPolicyId().isEmpty() ||
112                 policyObjectInfo.getPolicyId().isBlank())
113             return UUID.randomUUID().toString();
114         else
115             return policyObjectInfo.getPolicyId().trim();
116     }
117
118     public String toJson(Object jsonObject) {
119         return gson.toJson(jsonObject);
120     }
121
122     public HttpHeaders createHttpHeaders(String headerName, String headerValue) {
123         HttpHeaders httpHeaders = new HttpHeaders();
124         httpHeaders.add(headerName, headerValue);
125         return httpHeaders;
126     }
127
128     public String buildURI(String policyId, ServerWebExchange serverWebExchange) {
129         return UriComponentsBuilder.fromUri(serverWebExchange.getRequest().getURI())
130                 .path("/{id}")
131                 .buildAndExpand(policyId)
132                 .toString();
133     }
134
135     public Mono<Policy> isPolicyAlreadyCreated(Policy policy, Policies policies) {
136         if (policies.get(policy.getId()) != null) {
137             return Mono.error(new ServiceException
138                     ("Policy already created with ID: " + policy.getId(), HttpStatus.CONFLICT));
139         }
140             return Mono.just(policy);
141     }
142
143     public Flux<PolicyInformation> toFluxPolicyInformation(Collection<Policy> policyCollection) {
144         return Flux.fromIterable(policyCollection.stream()
145                 .map(singlePolicy -> new PolicyInformation(singlePolicy.getId(), singlePolicy.getRic().getConfig().getRicId()))
146                 .collect(Collectors.toList()));
147     }
148
149     public Collection<PolicyTypeInformation> toPolicyTypeInfoCollection(Collection<PolicyType> policyTypeCollection, Ric ric) {
150         return policyTypeCollection.stream()
151                 .map(type -> new PolicyTypeInformation(type.getId(), ric.getConfig().getRicId()))
152                 .collect(Collectors.toList());
153     }
154
155
156     public void validateQueryParameters(ServerWebExchange exchange, Set<String> allowedParams) throws InvalidRequestException {
157         Set<String> receivedParams = exchange.getRequest().getQueryParams().keySet();
158
159         Set<String> extraParams = receivedParams.stream()
160                 .filter(param -> !allowedParams.contains(param))
161                 .collect(Collectors.toSet());
162
163         if (!extraParams.isEmpty()) {
164             throw new InvalidRequestException("Unexpected query parameters: " + extraParams);
165         }
166     }
167 }