Passing Instance params for SO Macro request
[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
15 package org.onap.nbi.apis.serviceorder.workflow;
16
17 import java.io.IOException;
18 import java.util.ArrayList;
19 import java.util.HashMap;
20 import java.util.Iterator;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Map.Entry;
24 import java.util.stream.Collectors;
25
26 import org.onap.nbi.apis.servicecatalog.ServiceSpecificationService;
27 import org.onap.nbi.apis.serviceorder.SoClient;
28 import org.onap.nbi.apis.serviceorder.model.ServiceCharacteristic;
29 import org.onap.nbi.apis.serviceorder.model.ServiceOrder;
30 import org.onap.nbi.apis.serviceorder.model.ServiceOrderItem;
31 import org.onap.nbi.apis.serviceorder.model.StateType;
32 import org.onap.nbi.apis.serviceorder.model.consumer.CloudConfiguration;
33 import org.onap.nbi.apis.serviceorder.model.consumer.CreateE2EServiceInstanceResponse;
34 import org.onap.nbi.apis.serviceorder.model.consumer.CreateMacroServiceInstanceResponse;
35 import org.onap.nbi.apis.serviceorder.model.consumer.CreateServiceInstanceResponse;
36 import org.onap.nbi.apis.serviceorder.model.consumer.MSOE2EPayload;
37 import org.onap.nbi.apis.serviceorder.model.consumer.MSOPayload;
38 import org.onap.nbi.apis.serviceorder.model.consumer.ModelInfo;
39 import org.onap.nbi.apis.serviceorder.model.consumer.OwningEntity;
40 import org.onap.nbi.apis.serviceorder.model.consumer.ParametersModel;
41 import org.onap.nbi.apis.serviceorder.model.consumer.Project;
42 import org.onap.nbi.apis.serviceorder.model.consumer.RequestDetails;
43 import org.onap.nbi.apis.serviceorder.model.consumer.RequestInfo;
44 import org.onap.nbi.apis.serviceorder.model.consumer.RequestParameters;
45 import org.onap.nbi.apis.serviceorder.model.consumer.ResourceModel;
46 import org.onap.nbi.apis.serviceorder.model.consumer.ServiceModel;
47 import org.onap.nbi.apis.serviceorder.model.consumer.SubscriberInfo;
48 import org.onap.nbi.apis.serviceorder.model.consumer.UserParams;
49 import org.onap.nbi.apis.serviceorder.model.consumer.VFModelInfo;
50 import org.onap.nbi.apis.serviceorder.model.orchestrator.ServiceOrderInfo;
51 import org.onap.nbi.apis.serviceorder.service.ServiceOrderService;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.springframework.beans.factory.annotation.Autowired;
55 import org.springframework.beans.factory.annotation.Value;
56 import org.springframework.http.ResponseEntity;
57 import org.springframework.stereotype.Service;
58 import org.springframework.util.CollectionUtils;
59 import com.fasterxml.jackson.databind.JsonNode;
60 import com.fasterxml.jackson.databind.ObjectMapper;
61 import com.fasterxml.jackson.databind.node.ArrayNode;
62 import com.fasterxml.jackson.databind.node.ObjectNode;
63
64 @Service
65 public class PostSoProcessor {
66
67     private static final Logger LOGGER = LoggerFactory.getLogger(PostSoProcessor.class);
68
69     @Value("${onap.lcpCloudRegionId}")
70     private String lcpCloudRegionId;
71
72     @Value("${onap.tenantId}")
73     private String tenantId;
74
75     @Value("${so.owning.entity.id}")
76     private String soOwningEntityId;
77
78     @Value("${so.owning.entity.name}")
79     private String soOwningEntityName;
80
81     @Value("${so.project.name}")
82     private String soProjectName;
83
84     @Value("${onap.cloudOwner}")
85     private String cloudOwner;
86     
87     @Value("${onap.k8sCloudOwner}")
88         private String k8sCloudOwner;
89
90         @Value("${onap.k8sCloudRegionId}")
91         private String k8sCloudRegionId;
92
93         @Value("${k8s-rb-profile-name}")
94         private String k8sRbProfileName;
95
96     @Autowired
97     private ServiceOrderService serviceOrderService;
98
99     @Autowired
100     private SoClient soClient;
101     
102     @Autowired
103     ServiceSpecificationService serviceSpecificationService;
104
105     public ResponseEntity<CreateServiceInstanceResponse> postServiceOrderItem(ServiceOrderInfo serviceOrderInfo,
106             ServiceOrderItem serviceOrderItem) {
107         ResponseEntity<CreateServiceInstanceResponse> response = null;
108         try {
109             response = postSORequest(serviceOrderItem, serviceOrderInfo);
110         } catch (NullPointerException e) {
111             LOGGER.error("Unable to create service instance for serviceOrderItem.id=" + serviceOrderItem.getId(), e);
112             response = null;
113         }
114         return response;
115     }
116
117     public ResponseEntity<CreateE2EServiceInstanceResponse> postE2EServiceOrderItem(ServiceOrderInfo serviceOrderInfo,
118             ServiceOrderItem serviceOrderItem, ServiceOrder serviceOrder) {
119         ResponseEntity<CreateE2EServiceInstanceResponse> response;
120         try {
121             response = postE2ESORequest(serviceOrderItem, serviceOrderInfo, serviceOrder);
122         } catch (NullPointerException e) {
123             LOGGER.error("Unable to create service instance for serviceOrderItem.id=" + serviceOrderItem.getId(), e);
124             response = null;
125         }
126         return response;
127     }
128
129     public ResponseEntity<CreateMacroServiceInstanceResponse> postMacroServiceOrderItem(ServiceOrderInfo serviceOrderInfo,
130             ServiceOrderItem serviceOrderItem) {
131         ResponseEntity<CreateMacroServiceInstanceResponse> response = null;
132         try {
133             // For Macro Flow
134             response = postSOMacroRequest(serviceOrderItem, serviceOrderInfo);
135         } catch (NullPointerException e) {
136             LOGGER.error("Unable to create service instance for serviceOrderItem.id=" + serviceOrderItem.getId(), e);
137             response = null;
138         }
139         return response;
140     }
141     
142     private ResponseEntity<CreateServiceInstanceResponse> postSORequest(ServiceOrderItem serviceOrderItem,
143             ServiceOrderInfo serviceOrderInfo) {
144         RequestDetails requestDetails = buildSoRequest(serviceOrderItem, serviceOrderInfo);
145         MSOPayload msoPayload = new MSOPayload(requestDetails);
146         ResponseEntity<CreateServiceInstanceResponse> response = null;
147
148         switch (serviceOrderItem.getAction()) {
149             case ADD:
150                 response = soClient.callCreateServiceInstance(msoPayload);
151                 break;
152             case DELETE:
153                 response = soClient.callDeleteServiceInstance(msoPayload, serviceOrderItem.getService().getId());
154                 break;
155             case MODIFY:
156                 if (StateType.INPROGRESS_MODIFY_ITEM_TO_CREATE == serviceOrderItem.getState()) {
157                     response = soClient.callCreateServiceInstance(msoPayload);
158                 }
159                 if (StateType.ACKNOWLEDGED == serviceOrderItem.getState()) {
160                     response = soClient.callDeleteServiceInstance(msoPayload, serviceOrderItem.getService().getId());
161                 }
162                 break;
163             default:
164                 break;
165         }
166         return response;
167     }
168
169     private ResponseEntity<CreateE2EServiceInstanceResponse> postE2ESORequest(ServiceOrderItem serviceOrderItem,
170             ServiceOrderInfo serviceOrderInfo, ServiceOrder serviceOrder) {
171         ServiceModel service = buildE2ESoRequest(serviceOrderItem,
172                 serviceOrderInfo.getServiceOrderItemInfos().get(serviceOrderItem.getId()).getCatalogResponse(),
173                 serviceOrderInfo.getSubscriberInfo(), serviceOrder);
174         MSOE2EPayload msoE2EPayload = new MSOE2EPayload(service);
175         ResponseEntity<CreateE2EServiceInstanceResponse> response = null;
176         switch (serviceOrderItem.getAction()) {
177             case ADD:
178                 response = soClient.callE2ECreateServiceInstance(msoE2EPayload);
179                 break;
180             case DELETE:
181                 response = soClient.callE2EDeleteServiceInstance(service.getGlobalSubscriberId(),
182                         service.getServiceType(), serviceOrderItem.getService().getId());
183                 break;
184             case MODIFY:
185                 if (StateType.INPROGRESS_MODIFY_ITEM_TO_CREATE == serviceOrderItem.getState()) {
186                     response = soClient.callE2ECreateServiceInstance(msoE2EPayload);
187                 }
188                 if (StateType.ACKNOWLEDGED == serviceOrderItem.getState()) {
189                     response = soClient.callE2EDeleteServiceInstance(service.getGlobalSubscriberId(),
190                             service.getServiceType(), serviceOrderItem.getService().getId());
191                 }
192                 break;
193             default:
194                 break;
195         }
196         return response;
197     }
198     
199     private ResponseEntity<CreateMacroServiceInstanceResponse> postSOMacroRequest(ServiceOrderItem serviceOrderItem,
200                             ServiceOrderInfo serviceOrderInfo) {
201       
202       String serviceModuleName = (String) serviceOrderInfo.getServiceOrderItemInfos().get(serviceOrderItem.getId())
203             .getCatalogResponse().get("name");
204
205       RequestDetails requestDetails = buildSoMacroRequest(serviceOrderItem, serviceOrderInfo);
206       MSOPayload msoMacroPayload = new MSOPayload(requestDetails);
207       ResponseEntity<CreateMacroServiceInstanceResponse> response = null;
208
209       switch (serviceOrderItem.getAction()) {
210         case ADD:
211           response = soClient.callMacroCreateServiceInstance(msoMacroPayload);
212           break;
213         case DELETE:
214           // response = soClient.callDeleteServiceInstance(msoPayload,
215           // serviceOrderItem.getService().getId());
216           break;
217         case MODIFY:
218           if (StateType.INPROGRESS_MODIFY_ITEM_TO_CREATE == serviceOrderItem.getState()) {
219             // response = soClient.callCreateServiceInstance(msoPayload);
220           }
221           if (StateType.ACKNOWLEDGED == serviceOrderItem.getState()) {
222             // response = soClient.callDeleteServiceInstance(msoPayload,
223             // serviceOrderItem.getService().getId());
224           }
225           break;
226         default:
227           break;
228       }
229       return response;
230     }
231     
232     /**
233      * Build SO MACRO CREATE request from the ServiceOrder and catalog informations from SDC
234      *
235      * @param orderItem
236      * @param serviceOrderInfo
237      * @param subscriberInfo
238      * @return
239      */
240     private RequestDetails buildSoMacroRequest(ServiceOrderItem orderItem, ServiceOrderInfo serviceOrderInfo) {
241       
242         RequestDetails requestDetails = new RequestDetails();
243                 Map<String, Object> sdcInfos = serviceOrderInfo.getServiceOrderItemInfos().get(orderItem.getId())
244                                 .getCatalogResponse();
245
246                 String id = orderItem.getService().getServiceSpecification().getId();
247                 Map responseChildRes = serviceSpecificationService.get(id);
248                 ArrayList<Map<String, Object>> resourseSpecificationArray = (ArrayList<Map<String, Object>>) responseChildRes
249                                 .get("resourceSpecification");
250
251                 Map<String, Object> resourseSpecificationMap = resourseSpecificationArray.get(0);
252
253                 Map serviceInstanceParam = (Map) resourseSpecificationMap.get("serviceInstanceParams");
254                 Map instanceSpecification = (Map) resourseSpecificationMap.get("InstanceSpecification");
255                 ArrayList<VFModelInfo> childResourceSpecification = (ArrayList<VFModelInfo>) resourseSpecificationMap
256                                 .get("childResourceSpecification");
257                 
258                 HashMap<String, Object> instanceParamsFromServiceCharacteristics = retrieveInstanceParamsFromServiceCharacteristics(
259                                 orderItem.getService().getServiceCharacteristic());
260                 
261                 HashMap<String, Object> instanceParams = (HashMap<String, Object>) buildAndDistinguishServiceAndVnfLevelParams(
262                                 instanceParamsFromServiceCharacteristics, instanceSpecification, serviceInstanceParam);
263
264                 HashMap<String, Object> vnfInstanceParams = (HashMap<String, Object>) instanceParams.get("vnf");
265                 List<Object> serviceObject = new ArrayList<>();
266
267                 ArrayList<Object> vnfInstanceParam = new ArrayList<>();
268
269                 //Differentiating vnf with cnf(Can be discussed and improved)
270                 if (instanceSpecification.get("public_net_id") != null) {
271                         Map<String, Object> instanceParam = new HashMap<>();
272                         //Merge instanceSpecification with vnfInstanceParams
273                         instanceSpecification.putAll(vnfInstanceParams);
274                         vnfInstanceParam.add(instanceSpecification);
275                 } else {
276                         vnfInstanceParams.put("k8s-rb-profile-name", k8sRbProfileName);
277                         vnfInstanceParam.add(vnfInstanceParams);
278                 }
279
280                 List resSpec = (ArrayList) sdcInfos.get("resourceSpecification");
281                 Map resSpecMap = (Map) resSpec.get(0);
282
283                 Map<String, String> vnfInfoObject = new HashMap<>();
284                 vnfInfoObject.put("modelName", (String) resSpecMap.get("name"));
285                 vnfInfoObject.put("modelVersionId", (String) resSpecMap.get("id"));
286                 vnfInfoObject.put("modelInvariantUuid", (String) resSpecMap.get("resourceInvariantUUID"));
287                 vnfInfoObject.put("modelVersion", (String) resSpecMap.get("version"));
288                 vnfInfoObject.put("modelCustomizationId", (String) resSpecMap.get("modelCustomizationId"));
289                 vnfInfoObject.put("modelInstanceName", (String) resSpecMap.get("resourceInstanceName"));
290
291                 //initialization
292                 CloudConfiguration cloudConfiguration = null;
293
294                 //Differentiating vnf with cnf(Can be discussed and improved)
295                 if (instanceSpecification.get("public_net_id") != null) {
296                         cloudConfiguration = new CloudConfiguration(lcpCloudRegionId, tenantId, cloudOwner);
297                 } else {
298                         cloudConfiguration = new CloudConfiguration(k8sCloudRegionId, tenantId, k8sCloudOwner);
299                 }
300
301                 Map<String, String> platformName = new HashMap<>();
302                 platformName.put("platformName", "test");
303
304                 Map<String, String> lob = new HashMap<>();
305                 lob.put("lineOfBusinessName", "LOB-Demonstration");
306
307                 Map<String, Object> vnfModel = new HashMap<>();
308                 vnfModel.put("modelInfo", vnfInfoObject);
309                 vnfModel.put("cloudConfiguration", cloudConfiguration);
310                 vnfModel.put("platform", platformName);
311                 vnfModel.put("lineOfBusiness", lob);
312                 vnfModel.put("productFamilyId", "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb");
313                 vnfModel.put("instanceName", (String) resSpecMap.get("resourceInstanceName"));
314                 vnfModel.put("instanceParams", vnfInstanceParam);
315
316                 List<Object> vfModulesObjects = new ArrayList<>();
317                 ArrayList<Map<String, Object>> vfInstanceParam = new ArrayList<>();
318
319                 //Differentiate CNF from VNF
320                 if (instanceSpecification.get("public_net_id") != null) {
321                         vfInstanceParam.add(instanceSpecification);
322                         
323                 } else {
324                         Map<String, Object> instanceParam = new HashMap<>();
325                         instanceParam.put("k8s-rb-profile-name", k8sRbProfileName);
326                         vfInstanceParam.add(instanceParam);
327                 }
328                 
329                 for (VFModelInfo crsObject : childResourceSpecification) {
330                         Map<String, Object> vfModuleObject = new HashMap<>();
331                         Map<String, String> vfModuleInfo = new HashMap<>();
332
333                         vfModuleInfo.put("modelName", crsObject.getModelName());
334                         vfModuleInfo.put("modelVersionId", crsObject.getModelUuid());
335                         vfModuleInfo.put("modelInvariantUuid", crsObject.getModelInvariantUuid());
336                         vfModuleInfo.put("modelVersion", crsObject.getModelVersion());
337                         vfModuleInfo.put("modelCustomizationId", crsObject.getModelCustomizationUuid());
338                         vfModuleObject.put("modelInfo", vfModuleInfo);
339                         vfModuleObject.put("instanceName", crsObject.getModelName());
340                         vfModuleObject.put("instanceParams", vfInstanceParam);
341
342                         vfModulesObjects.add(vfModuleObject);
343                 }
344                 vnfModel.put("vfModules", vfModulesObjects);
345
346                 List<Object> vnfObjects = new ArrayList<>();
347                 vnfObjects.add(vnfModel);
348
349                 Map<String, Object> vnfData = new HashMap<>();
350                 vnfData.put("vnfs", vnfObjects);
351
352                 ModelInfo serviceModelInfo = new ModelInfo();
353                 serviceModelInfo.setModelType("service");
354                 serviceModelInfo.setModelInvariantId((String) sdcInfos.get("invariantUUID"));
355                 serviceModelInfo.setModelVersionId(orderItem.getService().getServiceSpecification().getId());
356                 serviceModelInfo.setModelName((String) sdcInfos.get("name"));
357                 serviceModelInfo.setModelVersion((String) sdcInfos.get("version"));
358
359                 // Adding List of instanceParams for service
360                 // We can add instanceParams Key Value in Map Object and add it to the List, for
361                 // For now it is empty to comply with so request
362
363                 List<Map<String, String>> listOfServiceLevelInstanceParams = new ArrayList<>();
364                 Map<String, String> serviceInstanceParams = (HashMap<String, String>) instanceParams.get("service");
365                 listOfServiceLevelInstanceParams.add(serviceInstanceParams);
366                 
367                 Map<String, Object> serviceData = new HashMap<>();
368                 serviceData.put("instanceParams", listOfServiceLevelInstanceParams);
369                 serviceData.put("instanceName", orderItem.getService().getName());
370                 serviceData.put("resources", vnfData);
371                 serviceData.put("modelInfo", serviceModelInfo);
372
373                 Map<String, String> homingObject = new HashMap<>();
374                 homingObject.put("Homing_Solution", "none");
375                 serviceObject.add(homingObject);
376
377                 Map<String, Object> serviceObject1 = new HashMap<>();
378                 serviceObject1.put("service", serviceData);
379                 serviceObject.add(serviceObject1);
380                 requestDetails.setSubscriberInfo(serviceOrderInfo.getSubscriberInfo());
381
382                 ModelInfo modelInfo = new ModelInfo();
383                 modelInfo.setModelType("service");
384                 modelInfo.setModelInvariantId((String) sdcInfos.get("invariantUUID"));
385                 modelInfo.setModelVersionId(orderItem.getService().getServiceSpecification().getId());
386                 modelInfo.setModelName((String) sdcInfos.get("name"));
387                 modelInfo.setModelVersion((String) sdcInfos.get("version"));
388                 requestDetails.setModelInfo(modelInfo);
389
390                 RequestInfo requestInfo = new RequestInfo();
391                 requestInfo.setInstanceName(orderItem.getService().getName());
392                 requestInfo.setSource("VID");
393                 requestInfo.setSuppressRollback(false);
394                 requestInfo.setRequestorId("NBI");
395                 requestInfo.setProductFamilyId("a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb");
396                 requestDetails.setRequestInfo(requestInfo);
397
398                 // We are taking RequestParameters as map because it has UserParams which gives value as
399                 // "name" : "service"
400                 // "value" : "", which SO is not accepting
401                 Map<String, Object> requestParameters = new HashMap<>();
402
403                 // Get value from serviceOrder request or generate one
404                 String serviceTypeFromJson = orderItem.getService().getServicetype();
405                 requestParameters.put("subscriptionServiceType",
406                                 serviceTypeFromJson != null ? serviceTypeFromJson : (String) sdcInfos.get("name"));
407                 requestParameters.put("userParams", serviceObject);
408                 requestParameters.put("aLaCarte", false);
409                 requestDetails.setRequestParameters(requestParameters);
410                 requestDetails.setCloudConfiguration(cloudConfiguration);
411
412                 OwningEntity owningEntity = new OwningEntity();
413                 owningEntity.setOwningEntityId(soOwningEntityId);
414                 owningEntity.setOwningEntityName(soOwningEntityName);
415                 requestDetails.setOwningEntity(owningEntity);
416
417                 Project project = new Project();
418                 project.setProjectName(soProjectName);
419
420                 requestDetails.setProject(project);
421         return requestDetails;
422         }
423
424     /**
425      * Build SO CREATE request from the ServiceOrder and catalog informations from SDC
426      *
427      * @param orderItem
428      * @param serviceOrderInfo
429      * @return
430      */
431     private RequestDetails buildSoRequest(ServiceOrderItem orderItem, ServiceOrderInfo serviceOrderInfo) {
432         RequestDetails requestDetails = new RequestDetails();
433
434         requestDetails.setSubscriberInfo(serviceOrderInfo.getSubscriberInfo());
435         Map<String, Object> sdcInfos =
436                 serviceOrderInfo.getServiceOrderItemInfos().get(orderItem.getId()).getCatalogResponse();
437         ModelInfo modelInfo = new ModelInfo();
438         modelInfo.setModelType("service");
439         modelInfo.setModelInvariantId((String) sdcInfos.get("invariantUUID"));
440         modelInfo.setModelNameVersionId(orderItem.getService().getServiceSpecification().getId());
441         modelInfo.setModelVersionId(orderItem.getService().getServiceSpecification().getId());
442         modelInfo.setModelName((String) sdcInfos.get("name"));
443         modelInfo.setModelVersion((String) sdcInfos.get("version"));
444         requestDetails.setModelInfo(modelInfo);
445
446         RequestInfo requestInfo = new RequestInfo();
447         requestInfo.setInstanceName(orderItem.getService().getName());
448         requestInfo.setSource("VID");
449         requestInfo.setSuppressRollback(false);
450         requestInfo.setRequestorId("NBI");
451         requestDetails.setRequestInfo(requestInfo);
452
453         RequestParameters requestParameters = new RequestParameters();
454         
455         String serviceTypeFromJson = orderItem.getService().getServicetype();
456         requestParameters.setSubscriptionServiceType(serviceTypeFromJson != null ? serviceTypeFromJson:(String) sdcInfos.get("name"));
457         requestParameters.setUserParams(
458                 retrieveUserParamsFromServiceCharacteristics(orderItem.getService().getServiceCharacteristic()));
459         requestParameters.setaLaCarte(true);
460         requestParameters.setTestApi("GR_API");
461         requestDetails.setRequestParameters(requestParameters);
462
463         CloudConfiguration cloudConfiguration = new CloudConfiguration(lcpCloudRegionId, tenantId, cloudOwner);
464         requestDetails.setCloudConfiguration(cloudConfiguration);
465
466         OwningEntity owningEntity = new OwningEntity();
467         owningEntity.setOwningEntityId(serviceOrderInfo.getOwningEntityId());
468         owningEntity.setOwningEntityName(soOwningEntityName);
469         requestDetails.setOwningEntity(owningEntity);
470
471         Project project = new Project();
472         project.setProjectName(soProjectName);
473
474         requestDetails.setProject(project);
475
476         return requestDetails;
477     }
478
479     /**
480      * Build E2E SO CREATE request from the ServiceOrder and catalog informations from SDC
481      *
482      * @param serviceOrderItem
483      * @param serviceOrder
484      * @param sdcInfos
485      * @return
486      */
487     // ServiceOrderItem serviceOrderItem --> orderItem?
488     private ServiceModel buildE2ESoRequest(ServiceOrderItem serviceOrderItem, Map<String, Object> sdcInfos,
489             SubscriberInfo subscriberInfo, ServiceOrder serviceOrder) {
490
491         subscriberInfo.getGlobalSubscriberId();
492         ServiceModel service = new ServiceModel();
493         service.setName(serviceOrderItem.getService().getName());
494         service.setDescription(serviceOrder.getDescription());
495         service.setServiceUuid(serviceOrderItem.getService().getServiceSpecification().getId());
496         service.setServiceInvariantUuid((String) sdcInfos.get("invariantUUID"));
497         service.setGlobalSubscriberId(subscriberInfo.getGlobalSubscriberId());
498         String serviceTypeFromJson = serviceOrderItem.getService().getServicetype();
499         service.setServiceType(serviceTypeFromJson != null ? serviceTypeFromJson : (String) sdcInfos.get("name"));
500         ParametersModel parameters = new ParametersModel();
501         ArrayList<ResourceModel> resources = new ArrayList();
502
503         ArrayList<Object> resourceObjects = (ArrayList<Object>) sdcInfos.get("resourceSpecification");
504
505         for (int i = 0; i < resourceObjects.size(); i++) {
506
507             ResourceModel resourceModel = new ResourceModel((Map<String, Object>) resourceObjects.get(i));
508             ParametersModel resourceParameters = new ParametersModel();
509             resourceModel.setParameters(resourceParameters);
510             resources.add(resourceModel);
511
512         }
513         parameters.setResources(resources);
514         List<UserParams> userParams =
515                 retrieveUserParamsFromServiceCharacteristics(serviceOrderItem.getService().getServiceCharacteristic());
516
517         // If there are ServiceCharacteristics add them to requestInputs
518         if (!userParams.isEmpty()) {
519             Map<String, String> requestInputs = new HashMap<String, String>();
520             for (int i = 0; i < userParams.size(); i++) {
521                 requestInputs.put(userParams.get(i).getName(), (String) userParams.get(i).getValue());
522             }
523
524             parameters.setRequestInputs(requestInputs);
525         }
526         service.setParameters(parameters);
527
528         return service;
529     }
530
531     /**
532      * Build a list of UserParams for the SO request by browsing a list of ServiceCharacteristics from
533      * SDC
534      */
535     private List<UserParams> retrieveUserParamsFromServiceCharacteristics(List<ServiceCharacteristic> characteristics) {
536         List<UserParams> userParams = new ArrayList<>();
537         UserParams userParam;
538
539         if (!CollectionUtils.isEmpty(characteristics)) {
540             for (ServiceCharacteristic characteristic : characteristics) {
541                 // Check is the characteristic is of type object, if proceed as before to allow for
542                 // backwards compatibility.
543                 if (characteristic.getValueType() != null && !characteristic.getValueType().isEmpty()
544                         && characteristic.getValueType().equals("object")) {
545                     ObjectMapper mapper = new ObjectMapper();
546                     JsonNode jsonNode = null;
547                     try {
548                         jsonNode = mapper.readTree(characteristic.getValue().getServiceCharacteristicValue());
549                     } catch (IOException e) {
550                         LOGGER.error("Failed to read object json {} , exception is ",
551                                 characteristic.getValue().getServiceCharacteristicValue(), e.getMessage());
552                     }
553                     ObjectNode objectNode = (ObjectNode) jsonNode;
554                     Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
555                     while (iter.hasNext()) {
556                         Map.Entry<String, JsonNode> entry = iter.next();
557                         if (!entry.getValue().isArray()) {
558                             userParam = new UserParams(entry.getKey(), entry.getValue().asText());
559                         } else {
560                             ArrayNode arrayNode = (ArrayNode) entry.getValue();
561                             String arrayNodeValueString = arrayNode.toString();
562                             userParam = new UserParams(entry.getKey(), arrayNodeValueString);
563                         }
564                         userParams.add(userParam);
565                     }
566                 }
567                 // as UserParams for all other types, boolean, string, integer etc
568                 else {
569                     userParam = new UserParams(characteristic.getName(),
570                             characteristic.getValue().getServiceCharacteristicValue());
571                     userParams.add(userParam);
572                 }
573             }
574         }
575
576         return userParams;
577     }
578     
579     /**
580          * Build a list of InstanceParams for the SO Macro request by browsing a list of
581          * ServiceCharacteristics
582          */
583         private HashMap<String, Object> retrieveInstanceParamsFromServiceCharacteristics(
584                         List<ServiceCharacteristic> characteristics) {
585
586                 HashMap<String, Object> instanceParams = new HashMap<>();
587
588                 if (!CollectionUtils.isEmpty(characteristics)) {
589                         for (ServiceCharacteristic characteristic : characteristics) {
590                                 // Check is the characteristic is of type object, if proceed as before to allow
591                                 // for
592                                 // backwards compatibility.
593                                 if (characteristic.getValueType() != null && !characteristic.getValueType().isEmpty()
594                                                 && characteristic.getValueType().equals("object")) {
595                                         ObjectMapper mapper = new ObjectMapper();
596                                         JsonNode jsonNode = null;
597                                         try {
598                                                 jsonNode = mapper.readTree(characteristic.getValue().getServiceCharacteristicValue());
599                                         } catch (IOException e) {
600                                                 LOGGER.error("Failed to read object json {} , exception is ",
601                                                                 characteristic.getValue().getServiceCharacteristicValue(), e.getMessage());
602                                         }
603                                         ObjectNode objectNode = (ObjectNode) jsonNode;
604                                         Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
605                                         while (iter.hasNext()) {
606                                                 Map.Entry<String, JsonNode> entry = iter.next();
607                                                 if (!entry.getValue().isArray()) {
608                                                         instanceParams.put(entry.getKey(), entry.getValue().asText());
609                                                 } else {
610                                                         ArrayNode arrayNode = (ArrayNode) entry.getValue();
611                                                         String arrayNodeValueString = arrayNode.toString();
612                                                         instanceParams.put(entry.getKey(), arrayNodeValueString);
613                                                 }
614                                         }
615                                 } else {
616                                         instanceParams.put(characteristic.getName(),
617                                                         characteristic.getValue().getServiceCharacteristicValue());
618                                 }
619                         }
620                 }
621
622                 return instanceParams;
623         }
624         
625         /**
626          * Build and distinguish InstanceParams at VNF Level and Service level and overwrite values from ServiceOrder JSON Request.
627          * Can be used as buildAndDistinguishServiceAndVnfLevelParams.get("vnf"); or buildAndDistinguishServiceAndVnfLevelParams.get("cnf");
628          */
629         private Map<String, Object> buildAndDistinguishServiceAndVnfLevelParams(
630                         Map<String, Object> instanceParamsFromServiceCharacteristic, Map<String, Object> existingVNFParams,
631                         Map<String, Object> existingServiceParams) {
632
633                 //To be used by passing key as "vnf" or "service" for respective instanceParams
634                 Map<String, Object> serviceAndVNFLevelInstanceParams = new HashMap<>();
635
636                 Map<String, Object> resultVNFParams = new HashMap<>();
637                 Map<String, Object> resultServiceParams = new HashMap<>();
638
639                 // First Filter VNF level Params From Service Characteristics and overwrite
640                 // values
641                 resultVNFParams = instanceParamsFromServiceCharacteristic.entrySet().stream()
642                                 .filter(entry -> existingVNFParams.containsKey(entry.getKey()))
643                                 .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
644
645                 //Add it as VNF level Params
646                 serviceAndVNFLevelInstanceParams.put("vnf", resultVNFParams);
647
648                 // Filter VNF level Params From Service Level
649                 existingServiceParams.entrySet().removeIf(e -> existingVNFParams.containsKey(e.getKey()));
650
651                 // Filter Service level Params From Service Characteristics and overwrite values
652                 resultServiceParams = instanceParamsFromServiceCharacteristic.entrySet().stream()
653                                 .filter(entry -> existingServiceParams.containsKey(entry.getKey()))
654                                 .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
655
656                 //Add it as Service level params
657                 serviceAndVNFLevelInstanceParams.put("service", resultServiceParams);
658
659                 return serviceAndVNFLevelInstanceParams;
660
661         }
662
663 }