Merge "add queryparam to catalog db api to filter"
[so.git] / bpmn / so-bpmn-infrastructure-common / src / main / groovy / org / onap / so / bpmn / infrastructure / scripts / CreateDeviceResource.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - SO
4  * ================================================================================
5  * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.infrastructure.scripts
24
25 import org.json.JSONObject
26 import org.json.XML;
27
28 import static org.apache.commons.lang3.StringUtils.*;
29 import groovy.xml.XmlUtil
30 import groovy.json.*
31 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
32 import org.onap.so.bpmn.common.scripts.ExceptionUtil
33 import org.onap.so.bpmn.common.recipe.ResourceInput;
34 import org.onap.so.bpmn.common.resource.ResourceRequestBuilder
35 import org.onap.so.bpmn.core.WorkflowException
36 import org.onap.so.bpmn.core.domain.ModelInfo
37 import org.onap.so.bpmn.core.domain.VnfResource
38 import org.onap.so.bpmn.core.json.JsonUtils
39 import org.onap.so.bpmn.core.UrnPropertiesReader
40 import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.builder.AbstractBuilder
41 import org.slf4j.Logger
42 import org.slf4j.LoggerFactory
43 import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils
44
45 import java.util.UUID;
46
47 import org.camunda.bpm.engine.delegate.BpmnError
48 import org.camunda.bpm.engine.delegate.DelegateExecution
49 import org.apache.commons.lang3.*
50 import org.apache.commons.codec.binary.Base64
51
52
53 /**
54  * This groovy class supports the <class>CreateDeviceResource.bpmn</class> process.
55  * flow for Device Resource Create
56  */
57 public class CreateDeviceResource extends AbstractServiceTaskProcessor {
58
59     String Prefix="CREDEVRES_"
60
61     ExceptionUtil exceptionUtil = new ExceptionUtil()
62
63     JsonUtils jsonUtil = new JsonUtils()
64
65     private static final Logger logger = LoggerFactory.getLogger( CreateDeviceResource.class);
66
67     public void preProcessRequest(DelegateExecution execution){
68         logger.info(" ***** Started preProcessRequest *****")
69         String msg = ""
70         try {
71
72             //get bpmn inputs from resource request.
73             String requestId = execution.getVariable("mso-request-id")
74             String requestAction = execution.getVariable("requestAction")
75             logger.info("The requestAction is: " + requestAction)
76             String recipeParamsFromRequest = execution.getVariable("recipeParams")
77             logger.info("The recipeParams is: " + recipeParamsFromRequest)
78             String resourceInput = execution.getVariable("resourceInput")
79             logger.info("The resourceInput is: " + resourceInput)
80             //Get ResourceInput Object
81             ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class)
82             execution.setVariable(Prefix + "ResourceInput", resourceInputObj)
83
84             String resourceInputPrameters = resourceInputObj.getResourceParameters()
85             String inputParametersJson = jsonUtil.getJsonValue(resourceInputPrameters, "requestInputs")
86             JSONObject inputParameters = new JSONObject(inputParametersJson)
87             execution.setVariable(Prefix + "ResourceRequestInputs", inputParameters)
88
89 //            String incomingRequest = resourceInputObj.getRequestsInputs()
90 //            String serviceParameters = JsonUtils.getJsonValue(incomingRequest, "service.parameters")
91 //            String requestInputs = JsonUtils.getJsonValue(serviceParameters, "requestInputs")
92 //            JSONObject serviceInputParameters = new JSONObject(requestInputs)
93 //            execution.setVariable(Prefix + "ServiceParameters", serviceInputParameters)
94
95             //Deal with recipeParams
96             String recipeParamsFromWf = execution.getVariable("recipeParamXsd")
97             String resourceName = resourceInputObj.getResourceInstanceName()
98             if (isBlank(resourceName)) {
99                 msg = "Input resourceName is null"
100                 logger.error(msg)
101             }
102             execution.setVariable("resourceName", resourceName)
103             logger.info("resourceName:" + resourceName)
104
105             String resourceModelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid()
106             if (isBlank(resourceModelInvariantUuid)) {
107                 msg = "Input resourceModelInvariantUuid is null"
108                 logger.error(msg)
109             }
110             execution.setVariable(Prefix + "ResourceModelInvariantUuid", resourceModelInvariantUuid)
111             logger.info("resourceModelInvariantUuid:" + resourceModelInvariantUuid)
112
113             String resourceModelUuid = resourceInputObj.getResourceModelInfo().getModelUuid()
114             if (isBlank(resourceModelUuid)) {
115                 msg = "Input resourceModelUuid is null"
116                 logger.error(msg)
117             }
118             execution.setVariable(Prefix + "ResourceModelUuid", resourceModelUuid)
119             logger.info("resourceModelUuid:" + resourceModelUuid)
120
121             String resourceModelCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid()
122             if (isBlank(resourceModelCustomizationUuid)) {
123                 msg = "Input resourceModelCustomizationUuid is null"
124                 logger.error(msg)
125             }
126             execution.setVariable(Prefix + "ResourceModelCustomizationUuid", resourceModelCustomizationUuid)
127             logger.info("resourceModelCustomizationUuid:" + resourceModelCustomizationUuid)
128
129             execution.setVariable(Prefix + "serviceInstanceId", resourceInputObj.getServiceInstanceId())
130             execution.setVariable("mso-request-id", requestId)
131
132         } catch (Exception ex){
133             msg = "Exception in preProcessRequest " + ex.getMessage()
134             logger.debug(msg)
135 //            exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
136         }
137     }
138
139         public void checkDevType(DelegateExecution execution){
140                 logger.info(" ***** Started checkDevType *****")
141                 try {
142
143                         JSONObject resourceInputParameters = execution.getVariable(Prefix + "ResourceRequestInputs")
144                         String devType = resourceInputParameters.get("device_class")
145
146                         if(StringUtils.isBlank(devType)) {
147                                 devType = "OTHER"
148                         }
149
150                         execution.setVariable("device_class", devType)
151
152                 } catch (Exception ex){
153                         String msg = "Exception in checkDevType " + ex.getMessage()
154                         logger.debug(msg)
155 //                      exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
156                 }
157         }
158
159         private void setProgressUpdateVariables(DelegateExecution execution, String body) {
160                 def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint", execution)
161                 execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint)
162                 execution.setVariable("CVFMI_updateResOperStatusRequest", body)
163         }
164
165         public void prepareUpdateProgress(DelegateExecution execution) {
166                 logger.info(" ***** Started prepareUpdateProgress *****")
167                 ResourceInput resourceInputObj = execution.getVariable(Prefix + "ResourceInput")
168                 String operType = resourceInputObj.getOperationType()
169                 String resourceCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid()
170                 String ServiceInstanceId = resourceInputObj.getServiceInstanceId()
171                 String modelName = resourceInputObj.getResourceModelInfo().getModelName()
172                 String operationId = resourceInputObj.getOperationId()
173                 String progress = execution.getVariable("progress")
174                 String status = execution.getVariable("status")
175                 String statusDescription = execution.getVariable("statusDescription")
176
177                 String body = """
178                 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
179                         xmlns:ns="http://org.onap.so/requestsdb">
180                         <soapenv:Header/>
181                 <soapenv:Body>
182                     <ns:updateResourceOperationStatus>
183                                <operType>${operType}</operType>
184                                <operationId>${operationId}</operationId>
185                                <progress>${progress}</progress>
186                                <resourceTemplateUUID>${resourceCustomizationUuid}</resourceTemplateUUID>
187                                <serviceId>${ServiceInstanceId}</serviceId>
188                                <status>${status}</status>
189                                <statusDescription>${statusDescription}</statusDescription>
190                     </ns:updateResourceOperationStatus>
191                 </soapenv:Body>
192                 </soapenv:Envelope>"""
193
194                 setProgressUpdateVariables(execution, body)
195                 logger.info(" ***** Exit prepareUpdateProgress *****")
196         }
197
198         private void getVNFTemplatefromSDC(DelegateExecution execution){
199                 logger.info(" ***** Started getVNFTemplatefromSDC *****")
200                 try {
201                         // To do
202
203
204                 } catch (Exception ex){
205                         String msg = "Exception in getVNFTemplatefromSDC " + ex.getMessage()
206                         logger.debug(msg)
207 //                      exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
208                 }
209         }
210
211     public void prepareVnfAndModulesCreate(DelegateExecution execution) {
212         try {
213             logger.trace("Inside prepareVnfAndModulesCreate of CreateDeviceResource ")
214             
215             JSONObject resourceInputParameters = execution.getVariable(Prefix + "ResourceRequestInputs")
216             String devType = resourceInputParameters.get("device_type")
217             String devVersion = resourceInputParameters.get("device_version")
218             
219             //get vnf model from SDC
220             getVNFTemplatefromSDC(execution)
221             
222             VnfResource vnf = execution.getVariable("vnfResource")
223             Integer vnfsCreatedCount = execution.getVariable(Prefix + "VnfsCreatedCount")
224             String vnfModelInfoString = null;
225
226             if (vnf != null) {
227                 logger.debug("getting model info for vnf # " + vnfsCreatedCount)
228                 ModelInfo vnfModelInfo = vnf.getModelInfo()
229                 vnfModelInfoString = vnfModelInfo.toString()
230             } else {
231                 logger.debug("vnf is null")
232                 vnfModelInfoString = execution.getVariable("vnfModelInfo")
233             }
234
235             logger.debug(" vnfModelInfoString :" + vnfModelInfoString)
236
237             // extract cloud configuration
238 //            String vimId = jsonUtil.getJsonValue(createVcpeServiceRequest,
239 //                    "requestDetails.cloudConfiguration.lcpCloudRegionId")
240 //            def cloudRegion = vimId.split("_")
241 //            execution.setVariable("cloudOwner", cloudRegion[0])
242 //            logger.debug("cloudOwner: "+ cloudRegion[0])
243 //            execution.setVariable("cloudRegionId", cloudRegion[1])
244 //            logger.debug("cloudRegionId: "+ cloudRegion[1])
245 //            execution.setVariable("lcpCloudRegionId", cloudRegion[1])
246 //            logger.debug("lcpCloudRegionId: "+ cloudRegion[1])
247 //            String tenantId = jsonUtil.getJsonValue(createVcpeServiceRequest,
248 //                    "requestDetails.cloudConfiguration.tenantId")
249 //            execution.setVariable("tenantId", tenantId)
250 //            logger.debug("tenantId: " + tenantId)
251             
252
253            execution.setVariable("cloudOwner", "")
254
255            execution.setVariable("cloudRegionId", "")
256        
257            execution.setVariable("lcpCloudRegionId", "")
258        
259            execution.setVariable("tenantId", "")       
260
261             String sdncVersion = execution.getVariable("sdncVersion")
262             logger.debug("sdncVersion: " + sdncVersion)
263
264             logger.trace("Completed prepareVnfAndModulesCreate of CreateVcpeResCustService ")
265         } catch (Exception ex) {
266             // try error in method block
267             String exceptionMessage = "Bpmn error encountered in CreateDeviceResource flow. Unexpected Error from method prepareVnfAndModulesCreate() - " + ex.getMessage()
268             logger.debug(exceptionMessage)
269         }
270     }
271
272     // *******************************
273     //     Validate Vnf request Section -> increment count
274     // *******************************
275     public void validateVnfCreate(DelegateExecution execution) {
276
277         try {
278             logger.trace("Inside validateVnfCreate of CreateDeviceResource ")
279
280             //Update Relationship between VNF to Device
281             addVNFAAIRelationShip(execution)
282
283             Integer vnfsCreatedCount = execution.getVariable(Prefix + "VnfsCreatedCount")
284             vnfsCreatedCount++
285
286             execution.setVariable(Prefix + "VnfsCreatedCount", vnfsCreatedCount)
287
288             logger.debug(" ***** Completed validateVnfCreate of CreateDeviceResource ***** " + " vnf # " + vnfsCreatedCount)
289         } catch (Exception ex) {
290             // try error in method block
291             String exceptionMessage = "Bpmn error encountered in CreateDeviceResource flow. Unexpected Error from method validateVnfCreate() - " + ex.getMessage()
292             logger.debug(exceptionMessage)
293         }
294     }
295
296     public void addVNFAAIRelationShip(DelegateExecution execution) {
297
298         try {
299             logger.trace("Inside addVNFAAIRelationShip of CreateDeviceResource ")
300
301
302
303             logger.debug(" ***** Completed addVNFAAIRelationShip of CreateDeviceResource ***** ")
304         } catch (Exception ex) {
305             // try error in method block
306             String exceptionMessage = "Bpmn error encountered in CreateDeviceResource flow. Unexpected Error from method addVNFAAIRelationShip() - " + ex.getMessage()
307             logger.debug(exceptionMessage)
308         }
309     }
310
311         public void sendSyncResponse (DelegateExecution execution) {
312                 logger.debug(" *** sendSyncResponse *** ")
313
314                 try {
315                         String operationStatus = "finished"
316                         // RESTResponse for main flow
317                         String resourceOperationResp = """{"operationStatus":"${operationStatus}"}""".trim()
318                         logger.debug(" sendSyncResponse to APIH:" + "\n" + resourceOperationResp)
319                         sendWorkflowResponse(execution, 202, resourceOperationResp)
320                         execution.setVariable("sentSyncResponse", true)
321
322                 } catch (Exception ex) {
323                         String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
324                         logger.debug(msg)
325 //                      exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
326                 }
327                 logger.debug(" ***** Exit sendSyncResopnse *****")
328         }
329 }