Code changes in BPMN infra for RAN Slice Use case
[so.git] / bpmn / MSOCommonBPMN / src / main / java / org / onap / so / client / cds / NssiCDSRequestProvider.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (c) 2022 Deutsche telekom
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.so.client.cds;
22
23 import com.fasterxml.jackson.core.JsonProcessingException;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import com.google.gson.JsonObject;
26 import java.util.ArrayList;
27 import org.onap.aai.domain.yang.ServiceInstances;
28 import org.onap.aaiclient.client.aai.entities.CustomQuery;
29 import org.onap.aaiclient.client.aai.entities.uri.AAIPluralResourceUri;
30 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri;
31 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory;
32 import org.onap.aaiclient.client.aai.entities.uri.NodesSingleUri;
33 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder;
34 import org.onap.aaiclient.client.graphinventory.Format;
35 import org.onap.so.bpmn.common.BuildingBlockExecution;
36 import org.onap.so.bpmn.common.InjectionHelper;
37 import org.onap.so.bpmn.core.json.JsonUtils;
38 import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance;
39 import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock;
40 import org.onap.so.bpmn.servicedecomposition.entities.ResourceKey;
41 import org.onap.so.bpmn.servicedecomposition.tasks.ExtractPojosForBB;
42 import org.onap.so.client.exception.BBObjectNotFoundException;
43 import org.onap.so.client.exception.PayloadGenerationException;
44 import org.onap.so.moi.Attributes;
45 import org.onap.so.moi.Snssai;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.springframework.beans.factory.annotation.Autowired;
49 import org.springframework.beans.factory.config.ConfigurableBeanFactory;
50 import org.springframework.context.annotation.Scope;
51 import org.springframework.stereotype.Component;
52 import java.util.List;
53 import java.util.Map;
54 import java.util.Optional;
55 import static org.onap.so.client.cds.PayloadConstants.PROPERTIES;
56 import static org.onap.so.client.cds.PayloadConstants.SEPARATOR;
57
58 @Component
59 @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
60 public class NssiCDSRequestProvider implements CDSRequestProvider {
61
62     private static final Logger LOGGER = LoggerFactory.getLogger(NssiCDSRequestProvider.class);
63
64     private String blueprintName;
65     private String blueprintVersion;
66     private BuildingBlockExecution execution;
67
68     private static final String DELETE_SLICE_PROFILE_ACTION = "delete-sliceprofile";
69     private static final String CREATE_SLICE_PROFILE_ACTION = "create-sliceprofile";
70     private static final String MODIFY_SLICE_PROFILE_ACTION = "modify-sliceprofile";
71     private static final String SERVICE_INSTANCE_KEY = "service-instance";
72     private static final String SERVICE_INSTANCE_ID_KEY = "service-instance-id";
73     private static final String NSSI = "nssi";
74     private static final String NSSI_ID = "nssiId";
75     private static final String NSSI_NAME = "nssiName";
76     private static final String NSI_NAME = "nsiName";
77     private static final String NSI_ID = "nsiId";
78     private static final String SLICE_PROFILE_INSTANCE_ID = "sliceProfileInstanceId";
79     private static final String SLICE_INSTANCE_FROM_PROFILE_ID_CUSTOM_QUERY =
80             "related-to?startingNodeType=slice-profile&relatedToNodeType=service-instance";
81     private static final String ENVIRONMENT_CONTEXT_QUERY_PARAM = "environment-context";
82     private static final String AAI_SUPPORTED_SLICE_PROFILE =
83             "latency|maxNumberofUEs|coverageAreaTAList|areaTrafficCapDL|resourceSharingLevel|serviceType|uEMobilityLevel|expDataRateUL|expDataRateDL";
84     private static final ObjectMapper mapper = new ObjectMapper();
85
86     JsonUtils jsonUtil = new JsonUtils();
87
88     @Autowired
89     private ExtractPojosForBB extractPojosForBB;
90
91     @Autowired
92     private InjectionHelper injectionHelper;
93
94     @Override
95     public String getBlueprintName() {
96         return blueprintName;
97     }
98
99     @Override
100     public String getBlueprintVersion() {
101         return blueprintVersion;
102     }
103
104     @Override
105     public <T> void setExecutionObject(T executionObject) {
106         execution = (BuildingBlockExecution) executionObject;
107     }
108
109     @Override
110     public Optional<String> buildRequestPayload(String action) throws PayloadGenerationException {
111         JsonObject cdsPropertyObject = null;
112
113         final GeneralBuildingBlock buildingBlock = execution.getGeneralBuildingBlock();
114         List<Map<String, Object>> userParamsFromRequest =
115                 buildingBlock.getRequestContext().getRequestParameters().getUserParams();
116
117         try {
118             ServiceInstance serviceInstance =
119                     extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
120             // get values from service Instance
121             blueprintName = serviceInstance.getModelInfoServiceInstance().getBlueprintName();
122             blueprintVersion = serviceInstance.getModelInfoServiceInstance().getBlueprintVersion();
123
124         } catch (Exception e) {
125             throw new PayloadGenerationException("Failed to buildPropertyObjectForNssi", e);
126         }
127
128         cdsPropertyObject = setCreateSliceProfileRequestValues(action, buildingBlock);
129
130         return Optional.of(buildRequestJsonObject(cdsPropertyObject, action));
131     }
132
133     private JsonObject setCreateSliceProfileRequestValues(String action, GeneralBuildingBlock buildingBlock) {
134
135         JsonObject cdsRequestObject = new JsonObject();
136
137         ServiceInstance serviceInstance = null;
138         try {
139             serviceInstance = extractPojosForBB.extractByKey(execution, ResourceKey.SERVICE_INSTANCE_ID);
140         } catch (BBObjectNotFoundException e) {
141             e.printStackTrace();
142         }
143
144         List<Map<String, Object>> userParamsFromRequest =
145                 buildingBlock.getRequestContext().getRequestParameters().getUserParams();
146
147         Attributes attributes = null;
148
149         for (Map<String, Object> userParamData : userParamsFromRequest) {
150             if (userParamData.get(NSSI) != null) {
151                 attributes = mapper.convertValue(userParamData.get(NSSI), Attributes.class);
152             }
153         }
154         // Value to come as a request == Hardcoded for now
155         String nssiId = serviceInstance.getServiceInstanceId();
156         String nssiName = getNssiName(nssiId);
157         String nsiId = "nssi-id";
158         String nsiName = "nssi-name";
159
160         cdsRequestObject.addProperty(NSSI_ID, nssiId);
161
162         if (!DELETE_SLICE_PROFILE_ACTION.equals(action)) {
163             cdsRequestObject.addProperty(NSSI_NAME, nssiName);
164             cdsRequestObject.addProperty(NSI_NAME, nsiName);
165         }
166
167         String sliceProfileInstanceId = null;
168         if (CREATE_SLICE_PROFILE_ACTION.equalsIgnoreCase(action)) {
169             Snssai snssai = attributes.getSliceProfileList().get(0).getPlmnInfoList().get(0).getSnssai();
170             String sNssaiString = snssai.getSst() + SEPARATOR + snssai.getSd();
171             sliceProfileInstanceId = getSliceProfileInstanceIdForNssi(sNssaiString);
172         } else {
173             String sliceProfileId = attributes.getSliceProfileList().get(0).getSliceProfileId();
174             sliceProfileInstanceId = getSliceProfileInstanceFromSliceProfileId(sliceProfileId);
175         }
176
177         cdsRequestObject.addProperty(SLICE_PROFILE_INSTANCE_ID, sliceProfileInstanceId);
178
179         cdsRequestObject.addProperty(NSI_ID, nsiId);
180         /*
181          * JsonObject nssiPropertyObject = setSliceProfileProperties(getSliceProfilesFromUserParams(buildingBlock));
182          * cdsRequestObject.add(action + SEPARATOR + PROPERTIES, nssiPropertyObject);
183          */
184         return cdsRequestObject;
185     }
186
187     private Map<String, Object> getSliceProfilesFromUserParams(GeneralBuildingBlock gBB) {
188
189
190         List<Map<String, Object>> mapUserParams = gBB.getRequestContext().getRequestParameters().getUserParams();
191
192         Map<String, Object> sliceProfileMap = null;
193         try {
194             String userParamsJson = mapper.writeValueAsString(mapUserParams.get(0));
195             String rANSliceSubnetProfile =
196                     jsonUtil.getJsonParamValue(userParamsJson, "nssi.sliceProfileList", "RANSliceSubnetProfile");
197
198             if (rANSliceSubnetProfile != null) {
199                 sliceProfileMap = mapper.readValue(rANSliceSubnetProfile, Map.class);
200             }
201         } catch (JsonProcessingException e) {
202             e.printStackTrace();
203         }
204         return sliceProfileMap;
205     }
206
207     // May be needed later
208
209     /*
210      * private JsonObject setSliceProfileProperties(Map<String, Object> userParamsMap) { JsonObject
211      * sliceProfilePropertiesNotPresentInAai = new JsonObject();
212      * 
213      * if (userParamsMap != null) { userParamsMap.forEach((k, v) -> { if (!AAI_SUPPORTED_SLICE_PROFILE.contains((String)
214      * k)) { sliceProfilePropertiesNotPresentInAai.addProperty(k, v.toString()); } }); }
215      * 
216      * return sliceProfilePropertiesNotPresentInAai; }
217      */
218
219     private String getSliceProfileInstanceFromSliceProfileId(String sliceProfileId) {
220
221         List<AAIResourceUri> startNodes = new ArrayList<>();
222         startNodes.add(
223                 AAIUriFactory.createNodesUri(AAIFluentTypeBuilder.Types.SLICE_PROFILE.getFragment(sliceProfileId)));
224
225         CustomQuery customQuery = new CustomQuery(startNodes, SLICE_INSTANCE_FROM_PROFILE_ID_CUSTOM_QUERY);
226
227         String results = injectionHelper.getAaiQueryClient().query(Format.RESOURCE, customQuery);
228
229         if (results == null || results.isEmpty()) {
230             throw new RuntimeException("Slice Profile Instance Not found");
231         }
232
233         Map<String, List<Map<String, Object>>> serviceInstancesMap = null;
234         try {
235             serviceInstancesMap = mapper.readValue(results, Map.class);
236         } catch (JsonProcessingException e) {
237             e.printStackTrace();
238         }
239         Map<String, Object> serviceInstance =
240                 (Map<String, Object>) serviceInstancesMap.get("results").get(0).get(SERVICE_INSTANCE_KEY);
241
242         return (String) serviceInstance.get(SERVICE_INSTANCE_ID_KEY);
243     }
244
245     private String getSliceProfileInstanceIdForNssi(String sNssai) {
246
247         String sliceProfileInstanceId = null;
248
249         try {
250             AAIPluralResourceUri uriSI =
251                     AAIUriFactory.createNodesUri(AAIFluentTypeBuilder.Types.SERVICE_INSTANCES.getFragment())
252                             .queryParam(ENVIRONMENT_CONTEXT_QUERY_PARAM, sNssai);
253             Optional<ServiceInstances> sliceProfileInstancesOptional =
254                     injectionHelper.getAaiClient().get(ServiceInstances.class, uriSI);
255
256             if (sliceProfileInstancesOptional.isPresent()) {
257                 sliceProfileInstanceId =
258                         sliceProfileInstancesOptional.get().getServiceInstance().get(0).getServiceInstanceId();
259             }
260         } catch (Exception e) {
261             LOGGER.error("Error in getting sliceProfile Instance" + e.getMessage());
262         }
263         return sliceProfileInstanceId;
264     }
265
266     private String getNssiName(String nssiId) {
267
268         String nssiName = null;
269
270         try {
271             NodesSingleUri uriSI =
272                     AAIUriFactory.createNodesUri(AAIFluentTypeBuilder.Types.SERVICE_INSTANCE.getFragment(nssiId));
273             Optional<org.onap.aai.domain.yang.ServiceInstance> sliceProfileInstancesOptional =
274                     injectionHelper.getAaiClient().get(org.onap.aai.domain.yang.ServiceInstance.class, uriSI);
275
276             if (sliceProfileInstancesOptional.isPresent()) {
277                 nssiName = sliceProfileInstancesOptional.get().getServiceInstanceName();
278             }
279         } catch (Exception e) {
280             LOGGER.error("Error in getting Nssi Instance" + e.getMessage());
281         }
282         return nssiName;
283     }
284 }