Merge "NBI to SO: cloudowner value"
[externalapi/nbi.git] / src / main / java / org / onap / nbi / apis / serviceorder / workflow / PostSoProcessor.java
1 /**
2  * Copyright (c) 2018 Orange
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 package org.onap.nbi.apis.serviceorder.workflow;
15
16 import java.io.IOException;
17 import java.util.ArrayList;
18 import java.util.HashMap;
19 import java.util.Iterator;
20 import java.util.List;
21 import java.util.Map;
22 import org.onap.nbi.apis.serviceorder.SoClient;
23 import org.onap.nbi.apis.serviceorder.model.ServiceCharacteristic;
24 import org.onap.nbi.apis.serviceorder.model.ServiceOrder;
25 import org.onap.nbi.apis.serviceorder.model.ServiceOrderItem;
26 import org.onap.nbi.apis.serviceorder.model.StateType;
27 import org.onap.nbi.apis.serviceorder.model.consumer.CloudConfiguration;
28 import org.onap.nbi.apis.serviceorder.model.consumer.CreateE2EServiceInstanceResponse;
29 import org.onap.nbi.apis.serviceorder.model.consumer.CreateServiceInstanceResponse;
30 import org.onap.nbi.apis.serviceorder.model.consumer.MSOE2EPayload;
31 import org.onap.nbi.apis.serviceorder.model.consumer.MSOPayload;
32 import org.onap.nbi.apis.serviceorder.model.consumer.ModelInfo;
33 import org.onap.nbi.apis.serviceorder.model.consumer.OwningEntity;
34 import org.onap.nbi.apis.serviceorder.model.consumer.ParametersModel;
35 import org.onap.nbi.apis.serviceorder.model.consumer.Project;
36 import org.onap.nbi.apis.serviceorder.model.consumer.RequestDetails;
37 import org.onap.nbi.apis.serviceorder.model.consumer.RequestInfo;
38 import org.onap.nbi.apis.serviceorder.model.consumer.RequestParameters;
39 import org.onap.nbi.apis.serviceorder.model.consumer.ResourceModel;
40 import org.onap.nbi.apis.serviceorder.model.consumer.ServiceModel;
41 import org.onap.nbi.apis.serviceorder.model.consumer.SubscriberInfo;
42 import org.onap.nbi.apis.serviceorder.model.consumer.UserParams;
43 import org.onap.nbi.apis.serviceorder.model.orchestrator.ServiceOrderInfo;
44 import org.onap.nbi.apis.serviceorder.service.ServiceOrderService;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.beans.factory.annotation.Value;
49 import org.springframework.http.ResponseEntity;
50 import org.springframework.stereotype.Service;
51 import org.springframework.util.CollectionUtils;
52 import com.fasterxml.jackson.databind.JsonNode;
53 import com.fasterxml.jackson.databind.ObjectMapper;
54 import com.fasterxml.jackson.databind.node.ArrayNode;
55 import com.fasterxml.jackson.databind.node.ObjectNode;
56
57 @Service
58 public class PostSoProcessor {
59
60   private static final Logger LOGGER = LoggerFactory.getLogger(PostSoProcessor.class);
61
62   @Value("${onap.lcpCloudRegionId}")
63   private String lcpCloudRegionId;
64
65   @Value("${onap.tenantId}")
66   private String tenantId;
67
68   @Value("${so.owning.entity.id}")
69   private String soOwningEntityId;
70
71   @Value("${so.owning.entity.name}")
72   private String soOwningEntityName;
73
74   @Value("${so.project.name}")
75   private String soProjectName;
76
77   @Value("${onap.cloudOwner}")
78   private String cloudOwner;
79
80   @Autowired
81   private ServiceOrderService serviceOrderService;
82
83   @Autowired
84   private SoClient soClient;
85
86
87
88   public ResponseEntity<CreateServiceInstanceResponse> postServiceOrderItem(
89       ServiceOrderInfo serviceOrderInfo, ServiceOrderItem serviceOrderItem) {
90     ResponseEntity<CreateServiceInstanceResponse> response = null;
91     try {
92       response = postSORequest(serviceOrderItem, serviceOrderInfo);
93     } catch (NullPointerException e) {
94       LOGGER.error(
95           "Unable to create service instance for serviceOrderItem.id=" + serviceOrderItem.getId(),
96           e);
97       response = null;
98     }
99     return response;
100   }
101
102   public ResponseEntity<CreateE2EServiceInstanceResponse> postE2EServiceOrderItem(
103       ServiceOrderInfo serviceOrderInfo, ServiceOrderItem serviceOrderItem,
104       ServiceOrder serviceOrder) {
105     ResponseEntity<CreateE2EServiceInstanceResponse> response;
106     try {
107       response = postE2ESORequest(serviceOrderItem, serviceOrderInfo, serviceOrder);
108     } catch (NullPointerException e) {
109       LOGGER.error(
110           "Unable to create service instance for serviceOrderItem.id=" + serviceOrderItem.getId(),
111           e);
112       response = null;
113     }
114     return response;
115   }
116
117   private ResponseEntity<CreateServiceInstanceResponse> postSORequest(
118       ServiceOrderItem serviceOrderItem, ServiceOrderInfo serviceOrderInfo) {
119     RequestDetails requestDetails =
120         buildSoRequest(
121             serviceOrderItem, serviceOrderInfo.getServiceOrderItemInfos()
122                 .get(serviceOrderItem.getId()).getCatalogResponse(),
123             serviceOrderInfo.getSubscriberInfo());
124     MSOPayload msoPayload = new MSOPayload(requestDetails);
125     ResponseEntity<CreateServiceInstanceResponse> response = null;
126
127     switch (serviceOrderItem.getAction()) {
128       case ADD:
129         response = soClient.callCreateServiceInstance(msoPayload);
130         break;
131       case DELETE:
132         response =
133             soClient.callDeleteServiceInstance(msoPayload, serviceOrderItem.getService().getId());
134         break;
135       case MODIFY:
136         if (StateType.INPROGRESS_MODIFY_ITEM_TO_CREATE == serviceOrderItem.getState()) {
137           response = soClient.callCreateServiceInstance(msoPayload);
138         }
139         if (StateType.ACKNOWLEDGED == serviceOrderItem.getState()) {
140           response =
141               soClient.callDeleteServiceInstance(msoPayload, serviceOrderItem.getService().getId());
142         }
143         break;
144       default:
145         break;
146     }
147     return response;
148   }
149
150   private ResponseEntity<CreateE2EServiceInstanceResponse> postE2ESORequest(
151       ServiceOrderItem serviceOrderItem, ServiceOrderInfo serviceOrderInfo,
152       ServiceOrder serviceOrder) {
153     ServiceModel service =
154         buildE2ESoRequest(
155             serviceOrderItem, serviceOrderInfo.getServiceOrderItemInfos()
156                 .get(serviceOrderItem.getId()).getCatalogResponse(),
157             serviceOrderInfo.getSubscriberInfo(), serviceOrder);
158     MSOE2EPayload msoE2EPayload = new MSOE2EPayload(service);
159     ResponseEntity<CreateE2EServiceInstanceResponse> response = null;
160     switch (serviceOrderItem.getAction()) {
161       case ADD:
162         response = soClient.callE2ECreateServiceInstance(msoE2EPayload);
163         break;
164       case DELETE:
165         response = soClient.callE2EDeleteServiceInstance(service.getGlobalSubscriberId(),
166             service.getServiceType(), serviceOrderItem.getService().getId());
167         break;
168       case MODIFY:
169         if (StateType.INPROGRESS_MODIFY_ITEM_TO_CREATE == serviceOrderItem.getState()) {
170           response = soClient.callE2ECreateServiceInstance(msoE2EPayload);
171         }
172         if (StateType.ACKNOWLEDGED == serviceOrderItem.getState()) {
173           response = soClient.callE2EDeleteServiceInstance(service.getGlobalSubscriberId(),
174               service.getServiceType(), serviceOrderItem.getService().getId());
175         }
176         break;
177       default:
178         break;
179     }
180     return response;
181   }
182
183
184
185   /**
186    * Build SO CREATE request from the ServiceOrder and catalog informations from SDC
187    *
188    * @param orderItem
189    * @param sdcInfos
190    * @param subscriberInfo
191    * @return
192    */
193   private RequestDetails buildSoRequest(ServiceOrderItem orderItem, Map<String, Object> sdcInfos,
194       SubscriberInfo subscriberInfo) {
195     RequestDetails requestDetails = new RequestDetails();
196
197     requestDetails.setSubscriberInfo(subscriberInfo);
198
199     ModelInfo modelInfo = new ModelInfo();
200     modelInfo.setModelType("service");
201     modelInfo.setModelInvariantId((String) sdcInfos.get("invariantUUID"));
202     modelInfo.setModelNameVersionId(orderItem.getService().getServiceSpecification().getId());
203     modelInfo.setModelVersionId(orderItem.getService().getServiceSpecification().getId());
204     modelInfo.setModelName((String) sdcInfos.get("name"));
205     modelInfo.setModelVersion((String) sdcInfos.get("version"));
206     requestDetails.setModelInfo(modelInfo);
207
208     RequestInfo requestInfo = new RequestInfo();
209     requestInfo.setInstanceName(orderItem.getService().getName());
210     requestInfo.setSource("VID");
211     requestInfo.setSuppressRollback(false);
212     requestInfo.setRequestorId("NBI");
213     requestDetails.setRequestInfo(requestInfo);
214
215     RequestParameters requestParameters = new RequestParameters();
216     requestParameters.setSubscriptionServiceType((String) sdcInfos.get("name"));
217     requestParameters.setUserParams(retrieveUserParamsFromServiceCharacteristics(
218         orderItem.getService().getServiceCharacteristic()));
219     requestParameters.setaLaCarte(true);
220     requestDetails.setRequestParameters(requestParameters);
221
222     CloudConfiguration cloudConfiguration = new CloudConfiguration(lcpCloudRegionId, tenantId, cloudOwner);
223     requestDetails.setCloudConfiguration(cloudConfiguration);
224
225     OwningEntity owningEntity = new OwningEntity();
226     owningEntity.setOwningEntityId(soOwningEntityId);
227     owningEntity.setOwningEntityName(soOwningEntityName);
228     requestDetails.setOwningEntity(owningEntity);
229
230     Project project = new Project();
231     project.setProjectName(soProjectName);
232
233     requestDetails.setProject(project);
234
235     return requestDetails;
236   }
237
238   /**
239    * Build E2E SO CREATE request from the ServiceOrder and catalog informations from SDC
240    *
241    * @param serviceOrderItem
242    * @param serviceOrder
243    * @param sdcInfos
244    * @return
245    */
246   // ServiceOrderItem serviceOrderItem --> orderItem?
247   private ServiceModel buildE2ESoRequest(ServiceOrderItem serviceOrderItem,
248       Map<String, Object> sdcInfos, SubscriberInfo subscriberInfo, ServiceOrder serviceOrder) {
249
250     subscriberInfo.getGlobalSubscriberId();
251     ServiceModel service = new ServiceModel();
252     service.setName(serviceOrderItem.getService().getName());
253     service.setDescription(serviceOrder.getDescription());
254     service.setServiceUuid(serviceOrderItem.getService().getServiceSpecification().getId());
255     service.setServiceInvariantUuid((String) sdcInfos.get("invariantUUID"));
256     service.setGlobalSubscriberId(subscriberInfo.getGlobalSubscriberId());
257     service.setServiceType((String) sdcInfos.get("name"));
258
259     ParametersModel parameters = new ParametersModel();
260     ArrayList<ResourceModel> resources = new ArrayList();
261
262     ArrayList<Object> resourceObjects = (ArrayList<Object>) sdcInfos.get("resourceSpecification");
263
264     for (int i = 0; i < resourceObjects.size(); i++) {
265
266       ResourceModel resourceModel = new ResourceModel((Map<String, Object>) resourceObjects.get(i));
267       ParametersModel resourceParameters = new ParametersModel();
268       resourceModel.setParameters(resourceParameters);
269       resources.add(resourceModel);
270
271     }
272     parameters.setResources(resources);
273     List<UserParams> userParams = retrieveUserParamsFromServiceCharacteristics(
274         serviceOrderItem.getService().getServiceCharacteristic());
275
276     // If there are ServiceCharacteristics add them to requestInputs
277     if (!userParams.isEmpty()) {
278       Map<String, String> requestInputs = new HashMap<String, String>();
279       for (int i = 0; i < userParams.size(); i++) {
280         requestInputs.put(userParams.get(i).getName(), userParams.get(i).getValue());
281       }
282
283       parameters.setRequestInputs(requestInputs);
284     }
285     service.setParameters(parameters);
286
287     return service;
288   }
289
290   /**
291    * Build a list of UserParams for the SO request by browsing a list of ServiceCharacteristics from
292    * SDC
293    */
294   private List<UserParams> retrieveUserParamsFromServiceCharacteristics(
295       List<ServiceCharacteristic> characteristics) {
296     List<UserParams> userParams = new ArrayList<>();
297     UserParams userParam;
298
299     if (!CollectionUtils.isEmpty(characteristics)) {
300       for (ServiceCharacteristic characteristic : characteristics) {
301         // Check is the characteristic is of type object, if proceed as before to allow for
302         // backwards compatibility.
303         if (characteristic.getValueType() != null && !characteristic.getValueType().isEmpty()
304             && characteristic.getValueType().equals("object")) {
305           ObjectMapper mapper = new ObjectMapper();
306           JsonNode jsonNode = null;
307           try {
308             jsonNode = mapper.readTree(characteristic.getValue().getServiceCharacteristicValue());
309           } catch (IOException e) {
310             LOGGER.error("Failed to read object json {} , exception is ",
311                 characteristic.getValue().getServiceCharacteristicValue(), e.getMessage());
312           }
313           ObjectNode objectNode = (ObjectNode) jsonNode;
314           Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
315           while (iter.hasNext()) {
316             Map.Entry<String, JsonNode> entry = iter.next();
317             if (!entry.getValue().isArray()) {
318               userParam = new UserParams(entry.getKey(), entry.getValue().asText());
319             } else {
320               ArrayNode arrayNode = (ArrayNode) entry.getValue();
321               String arrayNodeValueString = arrayNode.toString();
322               userParam = new UserParams(entry.getKey(), arrayNodeValueString);
323             }
324             userParams.add(userParam);
325           }
326         }
327         // as UserParams for all other types, boolean, string, integer etc
328         else {
329           userParam = new UserParams(characteristic.getName(),
330               characteristic.getValue().getServiceCharacteristicValue());
331           userParams.add(userParam);
332         }
333       }
334     }
335
336     return userParams;
337   }
338
339
340 }