Merge "Update SO request to use GR_API instead of VNF_API"
[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(serviceOrderItem,serviceOrderInfo);
121     MSOPayload msoPayload = new MSOPayload(requestDetails);
122     ResponseEntity<CreateServiceInstanceResponse> response = null;
123
124     switch (serviceOrderItem.getAction()) {
125       case ADD:
126         response = soClient.callCreateServiceInstance(msoPayload);
127         break;
128       case DELETE:
129         response =
130             soClient.callDeleteServiceInstance(msoPayload, serviceOrderItem.getService().getId());
131         break;
132       case MODIFY:
133         if (StateType.INPROGRESS_MODIFY_ITEM_TO_CREATE == serviceOrderItem.getState()) {
134           response = soClient.callCreateServiceInstance(msoPayload);
135         }
136         if (StateType.ACKNOWLEDGED == serviceOrderItem.getState()) {
137           response =
138               soClient.callDeleteServiceInstance(msoPayload, serviceOrderItem.getService().getId());
139         }
140         break;
141       default:
142         break;
143     }
144     return response;
145   }
146
147   private ResponseEntity<CreateE2EServiceInstanceResponse> postE2ESORequest(
148       ServiceOrderItem serviceOrderItem, ServiceOrderInfo serviceOrderInfo,
149       ServiceOrder serviceOrder) {
150     ServiceModel service =
151         buildE2ESoRequest(
152             serviceOrderItem, serviceOrderInfo.getServiceOrderItemInfos()
153                 .get(serviceOrderItem.getId()).getCatalogResponse(),
154             serviceOrderInfo.getSubscriberInfo(), serviceOrder);
155     MSOE2EPayload msoE2EPayload = new MSOE2EPayload(service);
156     ResponseEntity<CreateE2EServiceInstanceResponse> response = null;
157     switch (serviceOrderItem.getAction()) {
158       case ADD:
159         response = soClient.callE2ECreateServiceInstance(msoE2EPayload);
160         break;
161       case DELETE:
162         response = soClient.callE2EDeleteServiceInstance(service.getGlobalSubscriberId(),
163             service.getServiceType(), serviceOrderItem.getService().getId());
164         break;
165       case MODIFY:
166         if (StateType.INPROGRESS_MODIFY_ITEM_TO_CREATE == serviceOrderItem.getState()) {
167           response = soClient.callE2ECreateServiceInstance(msoE2EPayload);
168         }
169         if (StateType.ACKNOWLEDGED == serviceOrderItem.getState()) {
170           response = soClient.callE2EDeleteServiceInstance(service.getGlobalSubscriberId(),
171               service.getServiceType(), serviceOrderItem.getService().getId());
172         }
173         break;
174       default:
175         break;
176     }
177     return response;
178   }
179
180
181
182   /**
183    * Build SO CREATE request from the ServiceOrder and catalog informations from SDC
184    *
185    * @param orderItem
186    * @param serviceOrderInfo
187    * @return
188    */
189   private RequestDetails buildSoRequest(ServiceOrderItem orderItem,ServiceOrderInfo serviceOrderInfo) {
190     RequestDetails requestDetails = new RequestDetails();
191
192     requestDetails.setSubscriberInfo( serviceOrderInfo.getSubscriberInfo());
193     Map<String, Object> sdcInfos=serviceOrderInfo.getServiceOrderItemInfos()
194         .get(orderItem.getId()).getCatalogResponse();
195     ModelInfo modelInfo = new ModelInfo();
196     modelInfo.setModelType("service");
197     modelInfo.setModelInvariantId((String) sdcInfos.get("invariantUUID"));
198     modelInfo.setModelNameVersionId(orderItem.getService().getServiceSpecification().getId());
199     modelInfo.setModelVersionId(orderItem.getService().getServiceSpecification().getId());
200     modelInfo.setModelName((String) sdcInfos.get("name"));
201     modelInfo.setModelVersion((String) sdcInfos.get("version"));
202     requestDetails.setModelInfo(modelInfo);
203
204     RequestInfo requestInfo = new RequestInfo();
205     requestInfo.setInstanceName(orderItem.getService().getName());
206     requestInfo.setSource("VID");
207     requestInfo.setSuppressRollback(false);
208     requestInfo.setRequestorId("NBI");
209     requestDetails.setRequestInfo(requestInfo);
210
211     RequestParameters requestParameters = new RequestParameters();
212     requestParameters.setSubscriptionServiceType((String) sdcInfos.get("name"));
213     requestParameters.setUserParams(retrieveUserParamsFromServiceCharacteristics(
214         orderItem.getService().getServiceCharacteristic()));
215     requestParameters.setaLaCarte(true);
216     requestParameters.setTestApi("GR_API");
217     requestDetails.setRequestParameters(requestParameters);
218
219     CloudConfiguration cloudConfiguration = new CloudConfiguration(lcpCloudRegionId, tenantId, cloudOwner);
220     requestDetails.setCloudConfiguration(cloudConfiguration);
221
222     OwningEntity owningEntity = new OwningEntity();
223     owningEntity.setOwningEntityId(serviceOrderInfo.getOwningEntityId());
224     owningEntity.setOwningEntityName(soOwningEntityName);
225     requestDetails.setOwningEntity(owningEntity);
226
227     Project project = new Project();
228     project.setProjectName(soProjectName);
229
230     requestDetails.setProject(project);
231
232     return requestDetails;
233   }
234
235   /**
236    * Build E2E SO CREATE request from the ServiceOrder and catalog informations from SDC
237    *
238    * @param serviceOrderItem
239    * @param serviceOrder
240    * @param sdcInfos
241    * @return
242    */
243   // ServiceOrderItem serviceOrderItem --> orderItem?
244   private ServiceModel buildE2ESoRequest(ServiceOrderItem serviceOrderItem,
245       Map<String, Object> sdcInfos, SubscriberInfo subscriberInfo, ServiceOrder serviceOrder) {
246
247     subscriberInfo.getGlobalSubscriberId();
248     ServiceModel service = new ServiceModel();
249     service.setName(serviceOrderItem.getService().getName());
250     service.setDescription(serviceOrder.getDescription());
251     service.setServiceUuid(serviceOrderItem.getService().getServiceSpecification().getId());
252     service.setServiceInvariantUuid((String) sdcInfos.get("invariantUUID"));
253     service.setGlobalSubscriberId(subscriberInfo.getGlobalSubscriberId());
254     service.setServiceType((String) sdcInfos.get("name"));
255
256     ParametersModel parameters = new ParametersModel();
257     ArrayList<ResourceModel> resources = new ArrayList();
258
259     ArrayList<Object> resourceObjects = (ArrayList<Object>) sdcInfos.get("resourceSpecification");
260
261     for (int i = 0; i < resourceObjects.size(); i++) {
262
263       ResourceModel resourceModel = new ResourceModel((Map<String, Object>) resourceObjects.get(i));
264       ParametersModel resourceParameters = new ParametersModel();
265       resourceModel.setParameters(resourceParameters);
266       resources.add(resourceModel);
267
268     }
269     parameters.setResources(resources);
270     List<UserParams> userParams = retrieveUserParamsFromServiceCharacteristics(
271         serviceOrderItem.getService().getServiceCharacteristic());
272
273     // If there are ServiceCharacteristics add them to requestInputs
274     if (!userParams.isEmpty()) {
275       Map<String, String> requestInputs = new HashMap<String, String>();
276       for (int i = 0; i < userParams.size(); i++) {
277         requestInputs.put(userParams.get(i).getName(), userParams.get(i).getValue());
278       }
279
280       parameters.setRequestInputs(requestInputs);
281     }
282     service.setParameters(parameters);
283
284     return service;
285   }
286
287   /**
288    * Build a list of UserParams for the SO request by browsing a list of ServiceCharacteristics from
289    * SDC
290    */
291   private List<UserParams> retrieveUserParamsFromServiceCharacteristics(
292       List<ServiceCharacteristic> characteristics) {
293     List<UserParams> userParams = new ArrayList<>();
294     UserParams userParam;
295
296     if (!CollectionUtils.isEmpty(characteristics)) {
297       for (ServiceCharacteristic characteristic : characteristics) {
298         // Check is the characteristic is of type object, if proceed as before to allow for
299         // backwards compatibility.
300         if (characteristic.getValueType() != null && !characteristic.getValueType().isEmpty()
301             && characteristic.getValueType().equals("object")) {
302           ObjectMapper mapper = new ObjectMapper();
303           JsonNode jsonNode = null;
304           try {
305             jsonNode = mapper.readTree(characteristic.getValue().getServiceCharacteristicValue());
306           } catch (IOException e) {
307             LOGGER.error("Failed to read object json {} , exception is ",
308                 characteristic.getValue().getServiceCharacteristicValue(), e.getMessage());
309           }
310           ObjectNode objectNode = (ObjectNode) jsonNode;
311           Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
312           while (iter.hasNext()) {
313             Map.Entry<String, JsonNode> entry = iter.next();
314             if (!entry.getValue().isArray()) {
315               userParam = new UserParams(entry.getKey(), entry.getValue().asText());
316             } else {
317               ArrayNode arrayNode = (ArrayNode) entry.getValue();
318               String arrayNodeValueString = arrayNode.toString();
319               userParam = new UserParams(entry.getKey(), arrayNodeValueString);
320             }
321             userParams.add(userParam);
322           }
323         }
324         // as UserParams for all other types, boolean, string, integer etc
325         else {
326           userParam = new UserParams(characteristic.getName(),
327               characteristic.getValue().getServiceCharacteristicValue());
328           userParams.add(userParam);
329         }
330       }
331     }
332
333     return userParams;
334   }
335
336
337 }