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