6f624d042f05c1bdfe9cb5fd2c6d1571eb3e7689
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2019-2023 Nordix Foundation. All rights reserved.
6  * Copyright (C) 2024 OpenInfra Foundation Europe. All rights reserved.
7  * ======================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ========================LICENSE_END===================================
20  */
21
22 package org.onap.ccsdk.oran.a1policymanagementservice.controllers.v2;
23
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26
27 import io.swagger.v3.oas.annotations.Operation;
28 import io.swagger.v3.oas.annotations.Parameter;
29 import io.swagger.v3.oas.annotations.media.Content;
30 import io.swagger.v3.oas.annotations.media.Schema;
31 import io.swagger.v3.oas.annotations.responses.ApiResponse;
32 import io.swagger.v3.oas.annotations.responses.ApiResponses;
33 import io.swagger.v3.oas.annotations.tags.Tag;
34
35 import java.lang.invoke.MethodHandles;
36 import java.time.Instant;
37 import java.util.ArrayList;
38 import java.util.Collection;
39 import java.util.List;
40 import java.util.Map;
41
42 import lombok.Getter;
43
44 import lombok.RequiredArgsConstructor;
45 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
46 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.VoidResponse;
47 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.authorization.AuthorizationCheck;
48 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.authorization.PolicyAuthorizationRequest.Input.AccessType;
49 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.EntityNotFoundException;
50 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
51 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock;
52 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
53 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
54 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
55 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
56 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
57 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
58 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
59 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service;
60 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
63 import org.springframework.http.HttpStatus;
64 import org.springframework.http.MediaType;
65 import org.springframework.http.ResponseEntity;
66 import org.springframework.web.bind.annotation.DeleteMapping;
67 import org.springframework.web.bind.annotation.GetMapping;
68 import org.springframework.web.bind.annotation.PathVariable;
69 import org.springframework.web.bind.annotation.PutMapping;
70 import org.springframework.web.bind.annotation.RequestBody;
71 import org.springframework.web.bind.annotation.RequestHeader;
72 import org.springframework.web.bind.annotation.RequestParam;
73 import org.springframework.web.bind.annotation.RestController;
74 import org.springframework.web.reactive.function.client.WebClientException;
75 import org.springframework.web.reactive.function.client.WebClientResponseException;
76
77 import reactor.core.publisher.Flux;
78 import reactor.core.publisher.Mono;
79
80 @RestController("policyControllerV2")
81 @RequiredArgsConstructor
82 @Tag(//
83         name = PolicyController.API_NAME, //
84         description = PolicyController.API_DESCRIPTION //
85 )
86 public class PolicyController {
87
88     public static final String API_NAME = "A1 Policy Management";
89     public static final String API_DESCRIPTION = "";
90
91     public static class RejectionException extends Exception {
92         private static final long serialVersionUID = 1L;
93
94         @Getter
95         private final HttpStatus status;
96
97         public RejectionException(String message, HttpStatus status) {
98             super(message);
99             this.status = status;
100         }
101     }
102
103     private final Rics rics;
104     private final PolicyTypes policyTypes;
105     private final Policies policies;
106     private final A1ClientFactory a1ClientFactory;
107     private final Services services;
108     private final AuthorizationCheck authorization;
109
110     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
111     private static final Gson gson = new GsonBuilder().create();
112
113     @GetMapping(path = Consts.V2_API_ROOT + "/policy-types/{policytype_id:.+}") //
114     @Operation(summary = "Returns a policy type definition") //
115     @ApiResponses(value = { //
116             @ApiResponse(responseCode = "200", //
117                     description = "Policy type", //
118                     content = @Content(schema = @Schema(implementation = PolicyTypeInfo.class))), //
119             @ApiResponse(responseCode = "404", //
120                     description = "Policy type is not found", //
121                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class)))//
122     })
123     public ResponseEntity<Object> getPolicyType( //
124             @PathVariable("policytype_id") String policyTypeId) throws EntityNotFoundException {
125         PolicyType type = policyTypes.getType(policyTypeId);
126         PolicyTypeInfo info = new PolicyTypeInfo(type.getSchema());
127         return new ResponseEntity<>(gson.toJson(info), HttpStatus.OK);
128     }
129
130     @GetMapping(path = Consts.V2_API_ROOT + "/policy-types", produces = MediaType.APPLICATION_JSON_VALUE)
131     @Operation(summary = "Query policy type identities")
132     @ApiResponses(value = { //
133             @ApiResponse(responseCode = "200", //
134                     description = "Policy type IDs", //
135                     content = @Content(schema = @Schema(implementation = PolicyTypeIdList.class))), //
136             @ApiResponse(responseCode = "404", //
137                     description = "Near-RT RIC is not found", //
138                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
139     })
140     public ResponseEntity<Object> getPolicyTypes( //
141             @Parameter(name = Consts.RIC_ID_PARAM, required = false, //
142                     description = "Select types for the given Near-RT RIC identity.") //
143             @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId,
144
145             @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
146                     description = "Select types with the given type name (type identity has the format <typename_version>)") //
147             @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName,
148
149             @Parameter(name = Consts.COMPATIBLE_WITH_VERSION_PARAM, required = false, //
150                     description = "Select types that are compatible with the given version. This parameter is only applicable in conjunction with "
151                             + Consts.TYPE_NAME_PARAM
152                             + ". As an example version 1.9.1 is compatible with 1.0.0 but not the other way around."
153                             + " Matching types will be returned sorted in ascending order.") //
154             @RequestParam(name = Consts.COMPATIBLE_WITH_VERSION_PARAM, required = false) String compatibleWithVersion
155
156     ) throws ServiceException {
157
158         if (compatibleWithVersion != null && typeName == null) {
159             throw new ServiceException("Parameter " + Consts.COMPATIBLE_WITH_VERSION_PARAM + " can only be used when "
160                     + Consts.TYPE_NAME_PARAM + " is given", HttpStatus.BAD_REQUEST);
161         }
162
163         Collection<PolicyType> types =
164                 ricId != null ? rics.getRic(ricId).getSupportedPolicyTypes() : this.policyTypes.getAll();
165
166         types = PolicyTypes.filterTypes(types, typeName, compatibleWithVersion);
167         return new ResponseEntity<>(toPolicyTypeIdsJson(types), HttpStatus.OK);
168     }
169
170     @GetMapping(path = Consts.V2_API_ROOT + "/policies/{policy_id:.+}", produces = MediaType.APPLICATION_JSON_VALUE)
171     @Operation(summary = "Returns a policy") //
172     @ApiResponses(value = { //
173             @ApiResponse(responseCode = "200", //
174                     description = "Policy found", //
175                     content = @Content(schema = @Schema(implementation = PolicyInfo.class))), //
176             @ApiResponse(responseCode = "404", //
177                     description = "Policy is not found", //
178                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
179     })
180     public Mono<ResponseEntity<Object>> getPolicy( //
181             @PathVariable(name = Consts.POLICY_ID_PARAM, required = true) String id,
182             @RequestHeader Map<String, String> headers) throws EntityNotFoundException {
183         Policy policy = policies.getPolicy(id);
184         return authorization.doAccessControl(headers, policy, AccessType.READ) //
185                 .map(x -> new ResponseEntity<>((Object) gson.toJson(toPolicyInfo(policy)), HttpStatus.OK)) //
186                 .onErrorResume(this::handleException);
187     }
188
189     @DeleteMapping(Consts.V2_API_ROOT + "/policies/{policy_id:.+}")
190     @Operation(summary = "Delete a policy")
191     @ApiResponses(value = { //
192             @ApiResponse(responseCode = "200", //
193                     description = "Not used", //
194                     content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
195             @ApiResponse(responseCode = "204", //
196                     description = "Policy deleted", //
197                     content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
198             @ApiResponse(responseCode = "404", //
199                     description = "Policy is not found", //
200                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
201             @ApiResponse(responseCode = "423", //
202                     description = "Near-RT RIC is not operational", //
203                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
204     })
205     public Mono<ResponseEntity<Object>> deletePolicy( //
206             @PathVariable(Consts.POLICY_ID_PARAM) String policyId, @RequestHeader Map<String, String> headers)
207             throws EntityNotFoundException {
208         Policy policy = policies.getPolicy(policyId);
209         keepServiceAlive(policy.getOwnerServiceId());
210
211         return authorization.doAccessControl(headers, policy, AccessType.WRITE)
212                 .flatMap(x -> policy.getRic().getLock().lock(LockType.SHARED, "deletePolicy")) //
213                 .flatMap(grant -> deletePolicy(grant, policy)) //
214                 .onErrorResume(this::handleException);
215     }
216
217     Mono<ResponseEntity<Object>> deletePolicy(Lock.Grant grant, Policy policy) {
218         return assertRicStateIdle(policy.getRic()) //
219                 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.getRic())) //
220                 .doOnNext(notUsed -> policies.remove(policy)) //
221                 .doFinally(x -> grant.unlockBlocking()) //
222                 .flatMap(client -> client.deletePolicy(policy)) //
223                 .map(notUsed -> new ResponseEntity<>(HttpStatus.NO_CONTENT)) //
224                 .onErrorResume(this::handleException);
225     }
226
227     @PutMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE)
228     @Operation(summary = "Create or update a policy")
229     @ApiResponses(value = { //
230             @ApiResponse(responseCode = "201", //
231                     description = "Policy created", //
232                     content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
233             @ApiResponse(responseCode = "200", //
234                     description = "Policy updated", //
235                     content = @Content(schema = @Schema(implementation = VoidResponse.class))), //
236             @ApiResponse(responseCode = "423", //
237                     description = "Near-RT RIC is not operational", //
238                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))), //
239             @ApiResponse(responseCode = "404", //
240                     description = "Near-RT RIC or policy type is not found", //
241                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
242     })
243     public Mono<ResponseEntity<Object>> putPolicy(@RequestBody PolicyInfo policyInfo,
244             @RequestHeader Map<String, String> headers) throws EntityNotFoundException {
245
246         if (!policyInfo.validate()) {
247             return ErrorResponse.createMono("Missing required parameter in body", HttpStatus.BAD_REQUEST);
248         }
249         String jsonString = gson.toJson(policyInfo.policyData);
250         Ric ric = rics.get(policyInfo.ricId);
251         PolicyType type = policyTypes.get(policyInfo.policyTypeId);
252         keepServiceAlive(policyInfo.serviceId);
253         if (ric == null || type == null) {
254             throw new EntityNotFoundException("Near-RT RIC or policy type not found");
255         }
256         Policy policy = Policy.builder() //
257                 .id(policyInfo.policyId) //
258                 .json(jsonString) //
259                 .type(type) //
260                 .ric(ric) //
261                 .ownerServiceId(policyInfo.serviceId) //
262                 .lastModified(Instant.now()) //
263                 .isTransient(policyInfo.isTransient) //
264                 .statusNotificationUri(policyInfo.statusNotificationUri == null ? "" : policyInfo.statusNotificationUri) //
265                                 .build();
266
267         return authorization.doAccessControl(headers, policy, AccessType.WRITE) //
268                 .flatMap(x -> ric.getLock().lock(LockType.SHARED, "putPolicy")) //
269                 .flatMap(grant -> putPolicy(grant, policy)) //
270                 .onErrorResume(this::handleException);
271     }
272
273     private Mono<ResponseEntity<Object>> putPolicy(Lock.Grant grant, Policy policy) {
274         final boolean isCreate = this.policies.get(policy.getId()) == null;
275         final Ric ric = policy.getRic();
276
277         return assertRicStateIdle(ric) //
278                 .flatMap(notUsed -> checkSupportedType(ric, policy.getType())) //
279                 .flatMap(notUsed -> validateModifiedPolicy(policy)) //
280                 .flatMap(notUsed -> a1ClientFactory.createA1Client(ric)) //
281                 .flatMap(client -> client.putPolicy(policy)) //
282                 .doOnNext(notUsed -> policies.put(policy)) //
283                 .doFinally(x -> grant.unlockBlocking()) //
284                 .flatMap(notUsed -> Mono.just(new ResponseEntity<>(isCreate ? HttpStatus.CREATED : HttpStatus.OK))) //
285                 .onErrorResume(this::handleException);
286
287     }
288
289     private Mono<ResponseEntity<Object>> handleException(Throwable throwable) {
290         if (throwable instanceof WebClientResponseException e) {
291             return ErrorResponse.createMono(e.getResponseBodyAsString(), e.getStatusCode());
292         } else if (throwable instanceof WebClientException e) {
293             return ErrorResponse.createMono(e.getMessage(), HttpStatus.BAD_GATEWAY);
294         } else if (throwable instanceof RejectionException e) {
295             return ErrorResponse.createMono(e.getMessage(), e.getStatus());
296         } else if (throwable instanceof ServiceException e) {
297             return ErrorResponse.createMono(e.getMessage(), e.getHttpStatus());
298         } else {
299             return ErrorResponse.createMono(throwable.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
300         }
301     }
302
303     private Mono<Object> validateModifiedPolicy(Policy policy) {
304         // Check that ric is not updated
305         Policy current = this.policies.get(policy.getId());
306         if (current != null && !current.getRic().id().equals(policy.getRic().id())) {
307             RejectionException e = new RejectionException("Policy cannot change RIC, policyId: " + current.getId() + //
308                     ", RIC ID: " + current.getRic().id() + //
309                     ", new ID: " + policy.getRic().id(), HttpStatus.CONFLICT);
310             logger.debug("Request rejected, {}", e.getMessage());
311             return Mono.error(e);
312         }
313         return Mono.just("{}");
314     }
315
316     private Mono<Object> checkSupportedType(Ric ric, PolicyType type) {
317         if (!ric.isSupportingType(type.getId())) {
318             logger.debug("Request rejected, type not supported, RIC: {}", ric);
319             RejectionException e = new RejectionException(
320                     "Type: " + type.getId() + " not supported by RIC: " + ric.id(), HttpStatus.NOT_FOUND);
321             return Mono.error(e);
322         }
323         return Mono.just("{}");
324     }
325
326     private Mono<Object> assertRicStateIdle(Ric ric) {
327         if (ric.getState() == Ric.RicState.AVAILABLE) {
328             return Mono.just("{}");
329         } else {
330             logger.debug("Request rejected Near-RT RIC not IDLE, ric: {}", ric);
331             RejectionException e = new RejectionException(
332                     "Near-RT RIC: is not operational, id: " + ric.id() + ", state: " + ric.getState(),
333                     HttpStatus.LOCKED);
334             return Mono.error(e);
335         }
336     }
337
338     static final String GET_POLICIES_QUERY_DETAILS =
339             "Returns a list of A1 policies matching given search criteria. <br>" //
340                     + "If several query parameters are defined, the policies matching all conditions are returned.";
341
342     @GetMapping(path = Consts.V2_API_ROOT + "/policy-instances", produces = MediaType.APPLICATION_JSON_VALUE)
343     @Operation(summary = "Query for A1 policy instances", description = GET_POLICIES_QUERY_DETAILS)
344     @ApiResponses(value = { //
345             @ApiResponse(responseCode = "200", //
346                     description = "Policies", //
347                     content = @Content(schema = @Schema(implementation = PolicyInfoList.class))), //
348             @ApiResponse(responseCode = "404", //
349                     description = "Near-RT RIC, policy type or service not found", //
350                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
351     })
352     public Mono<ResponseEntity<Object>> getPolicyInstances( //
353             @Parameter(name = Consts.POLICY_TYPE_ID_PARAM, required = false,
354                     description = "Select policies with a given type identity.") //
355             @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String typeId, //
356             @Parameter(name = Consts.RIC_ID_PARAM, required = false,
357                     description = "Select policies for a given Near-RT RIC identity.") //
358             @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ric, //
359             @Parameter(name = Consts.SERVICE_ID_PARAM, required = false,
360                     description = "Select policies owned by a given service.") //
361             @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String service,
362             @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
363                     description = "Select policies of a given type name (type identity has the format <typename_version>)") //
364             @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName,
365             @RequestHeader Map<String, String> headers) throws EntityNotFoundException //
366     {
367         if ((typeId != null && this.policyTypes.get(typeId) == null)) {
368             throw new EntityNotFoundException("Policy type identity not found");
369         }
370         if ((ric != null && this.rics.get(ric) == null)) {
371             throw new EntityNotFoundException("Near-RT RIC not found");
372         }
373
374         Collection<Policy> filtered = policies.filterPolicies(typeId, ric, service, typeName);
375         return Flux.fromIterable(filtered) //
376                 .flatMap(policy -> authorization.doAccessControl(headers, policy, AccessType.READ)) //
377                 .doOnError(e -> logger.debug("Unauthorized to read policy: {}", e.getMessage())) //
378                 .onErrorResume(e -> Mono.empty()) //
379                 .collectList() //
380                 .map(authPolicies -> policiesToJson(authPolicies)) //
381                 .map(str -> new ResponseEntity<>(str, HttpStatus.OK));
382     }
383
384     @GetMapping(path = Consts.V2_API_ROOT + "/policies", produces = MediaType.APPLICATION_JSON_VALUE) //
385     @Operation(summary = "Query policy identities", description = GET_POLICIES_QUERY_DETAILS) //
386     @ApiResponses(value = { //
387             @ApiResponse(responseCode = "200", //
388                     description = "Policy identities", //
389                     content = @Content(schema = @Schema(implementation = PolicyIdList.class))), //
390             @ApiResponse(responseCode = "404", //
391                     description = "Near-RT RIC or type not found", //
392                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
393     })
394     public Mono<ResponseEntity<Object>> getPolicyIds( //
395             @Parameter(name = Consts.POLICY_TYPE_ID_PARAM, required = false, //
396                     description = "Select policies of a given policy type identity.") //
397             @RequestParam(name = Consts.POLICY_TYPE_ID_PARAM, required = false) String policyTypeId, //
398             @Parameter(name = Consts.RIC_ID_PARAM, required = false, //
399                     description = "Select policies of a given Near-RT RIC identity.") //
400             @RequestParam(name = Consts.RIC_ID_PARAM, required = false) String ricId, //
401             @Parameter(name = Consts.SERVICE_ID_PARAM, required = false, //
402                     description = "Select policies owned by a given service.") //
403             @RequestParam(name = Consts.SERVICE_ID_PARAM, required = false) String serviceId,
404             @Parameter(name = Consts.TYPE_NAME_PARAM, required = false, //
405                     description = "Select policies of types with the given type name (type identity has the format <typename_version>)") //
406             @RequestParam(name = Consts.TYPE_NAME_PARAM, required = false) String typeName,
407             @RequestHeader Map<String, String> headers) throws EntityNotFoundException //
408     {
409         if ((policyTypeId != null && this.policyTypes.get(policyTypeId) == null)) {
410             throw new EntityNotFoundException("Policy type not found");
411         }
412         if ((ricId != null && this.rics.get(ricId) == null)) {
413             throw new EntityNotFoundException("Near-RT RIC not found");
414         }
415
416         Collection<Policy> filtered = policies.filterPolicies(policyTypeId, ricId, serviceId, typeName);
417         return Flux.fromIterable(filtered) //
418                 .flatMap(policy -> authorization.doAccessControl(headers, policy, AccessType.READ)) //
419                 .doOnError(e -> logger.debug("Unauthorized to read policy: {}", e.getMessage())) //
420                 .onErrorResume(e -> Mono.empty()) //
421                 .collectList() //
422                 .map(authPolicies -> toPolicyIdsJson(authPolicies)) //
423                 .map(policyIdsJson -> new ResponseEntity<>(policyIdsJson, HttpStatus.OK));
424     }
425
426     @GetMapping(path = Consts.V2_API_ROOT + "/policies/{policy_id}/status", produces = MediaType.APPLICATION_JSON_VALUE)
427     @Operation(summary = "Returns a policy status") //
428     @ApiResponses(value = { //
429             @ApiResponse(responseCode = "200", //
430                     description = "Policy status", //
431                     content = @Content(schema = @Schema(implementation = PolicyStatusInfo.class))), //
432             @ApiResponse(responseCode = "404", //
433                     description = "Policy is not found", //
434                     content = @Content(schema = @Schema(implementation = ErrorResponse.ErrorInfo.class))) //
435     })
436     public Mono<ResponseEntity<Object>> getPolicyStatus( //
437             @PathVariable(Consts.POLICY_ID_PARAM) String policyId, @RequestHeader Map<String, String> headers)
438             throws EntityNotFoundException {
439         Policy policy = policies.getPolicy(policyId);
440
441         return authorization.doAccessControl(headers, policy, AccessType.READ) //
442                 .flatMap(notUsed -> a1ClientFactory.createA1Client(policy.getRic())) //
443                 .flatMap(client -> client.getPolicyStatus(policy).onErrorResume(e -> Mono.just("{}"))) //
444                 .flatMap(status -> createPolicyStatus(policy, status)) //
445                 .onErrorResume(this::handleException);
446
447     }
448
449     private Mono<ResponseEntity<Object>> createPolicyStatus(Policy policy, String statusFromNearRic) {
450         PolicyStatusInfo info = new PolicyStatusInfo(policy.getLastModified(), fromJson(statusFromNearRic));
451         String str = gson.toJson(info);
452         return Mono.just(new ResponseEntity<>(str, HttpStatus.OK));
453     }
454
455     private void keepServiceAlive(String name) {
456         Service s = this.services.get(name);
457         if (s != null) {
458             s.keepAlive();
459         }
460     }
461
462     private PolicyInfo toPolicyInfo(Policy p) {
463         PolicyInfo policyInfo = new PolicyInfo();
464         policyInfo.policyId = p.getId();
465         policyInfo.policyData = fromJson(p.getJson());
466         policyInfo.ricId = p.getRic().id();
467         policyInfo.policyTypeId = p.getType().getId();
468         policyInfo.serviceId = p.getOwnerServiceId();
469         policyInfo.isTransient = p.isTransient();
470         if (!p.getStatusNotificationUri().isEmpty()) {
471             policyInfo.statusNotificationUri = p.getStatusNotificationUri();
472             }
473         if (!policyInfo.validate()) {
474             logger.error("BUG, all mandatory fields must be set");
475         }
476
477             return policyInfo;
478     }
479
480     private String policiesToJson(Collection<Policy> policies) {
481         List<PolicyInfo> v = new ArrayList<>(policies.size());
482         for (Policy p : policies) {
483             v.add(toPolicyInfo(p));
484         }
485         PolicyInfoList list = new PolicyInfoList(v);
486         return gson.toJson(list);
487     }
488
489     private Object fromJson(String jsonStr) {
490         return gson.fromJson(jsonStr, Object.class);
491     }
492
493     private String toPolicyTypeIdsJson(Collection<PolicyType> types) {
494         List<String> v = new ArrayList<>(types.size());
495         for (PolicyType t : types) {
496             v.add(t.getId());
497         }
498         PolicyTypeIdList ids = new PolicyTypeIdList(v);
499         return gson.toJson(ids);
500     }
501
502     private String toPolicyIdsJson(Collection<Policy> policies) {
503         List<String> v = new ArrayList<>(policies.size());
504         for (Policy p : policies) {
505             v.add(p.getId());
506         }
507         return gson.toJson(new PolicyIdList(v));
508     }
509 }