80d714893de35126bd8204e4130410f433c4491a
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / CreateGenericALaCarteServiceInstance.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
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.openecomp.mso.bpmn.infrastructure.scripts;
22
23 import static org.apache.commons.lang3.StringUtils.*;
24 import groovy.xml.XmlUtil
25 import groovy.json.*
26 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor
27 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil
28 import org.openecomp.mso.bpmn.common.scripts.VidUtils
29 import org.openecomp.mso.bpmn.core.WorkflowException
30 import org.openecomp.mso.bpmn.core.json.JsonUtils
31 import org.openecomp.mso.rest.APIResponse
32
33 import java.util.UUID;
34
35 import org.camunda.bpm.engine.delegate.BpmnError
36 import org.camunda.bpm.engine.runtime.Execution
37 import org.apache.commons.lang3.*
38 import org.apache.commons.codec.binary.Base64;
39 import org.springframework.web.util.UriUtils
40 import org.json.JSONException;
41
42 /**
43  * This groovy class supports the <class>CreateGenericALaCarteServiceInstance.bpmn</class> process.
44  * AlaCarte flow for 1702 ServiceInstance Create
45  *
46  */
47 public class CreateGenericALaCarteServiceInstance extends AbstractServiceTaskProcessor {
48         String Prefix="CRESI_"
49         ExceptionUtil exceptionUtil = new ExceptionUtil()
50         JsonUtils jsonUtil = new JsonUtils()
51         VidUtils vidUtils = new VidUtils()
52
53         public void preProcessRequest (Execution execution) {
54                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
55                 execution.setVariable("prefix",Prefix)
56                 String msg = ""
57                 utils.log("DEBUG", " *** preProcessRequest() *** ", isDebugEnabled)
58
59                 try {
60
61                         String siRequest = execution.getVariable("bpmnRequest")
62                         utils.logAudit(siRequest)
63
64                         String requestId = execution.getVariable("mso-request-id")
65                         execution.setVariable("msoRequestId", requestId)
66                         utils.log("DEBUG", "Input Request:" + siRequest + " reqId:" + requestId, isDebugEnabled)
67
68                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
69                         if (isBlank(serviceInstanceId)) {
70                                 serviceInstanceId = UUID.randomUUID().toString()
71                         }
72                         utils.log("DEBUG", "Generated new Service Instance:" + serviceInstanceId, isDebugEnabled)
73                         serviceInstanceId = UriUtils.encode(serviceInstanceId,"UTF-8")
74                         execution.setVariable("serviceInstanceId", serviceInstanceId)
75
76                         //subscriberInfo
77                         String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "requestDetails.subscriberInfo.globalSubscriberId")
78                         if (isBlank(globalSubscriberId)) {
79                                 msg = "Input globalSubscriberId' is null"
80                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
81                         } else {
82                                 execution.setVariable("globalSubscriberId", globalSubscriberId)
83                         }
84
85                         //requestInfo
86                         execution.setVariable("source", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.source"))
87                         execution.setVariable("serviceInstanceName", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.instanceName"))
88                         execution.setVariable("disableRollback", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.suppressRollback"))
89                         String productFamilyId = null;
90                         try { 
91                                 productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId")
92                         } catch (JSONException e) {
93                                 productFamilyId = null;
94                         }
95                         if (isBlank(productFamilyId))
96                         {
97                                 msg = "Input productFamilyId is null"
98                                 utils.log("DEBUG", msg, isDebugEnabled)
99                                 //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
100                         } else {
101                                 execution.setVariable("productFamilyId", productFamilyId)
102                         }
103
104                         //modelInfo
105                         String serviceModelInfo = jsonUtil.getJsonValue(siRequest, "requestDetails.modelInfo")
106                         if (isBlank(serviceModelInfo)) {
107                                 msg = "Input serviceModelInfo is null"
108                                 utils.log("DEBUG", msg, isDebugEnabled)
109                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
110                         } else
111                         {
112                                 execution.setVariable("serviceModelInfo", serviceModelInfo)
113                         }
114
115                         utils.log("DEBUG", "modelInfo" + serviceModelInfo,  isDebugEnabled)
116
117                         //requestParameters
118                         String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.subscriptionServiceType")
119                         if (isBlank(subscriptionServiceType)) {
120                                 msg = "Input subscriptionServiceType is null"
121                                 utils.log("DEBUG", msg, isDebugEnabled)
122                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
123                         } else {
124                                 execution.setVariable("subscriptionServiceType", subscriptionServiceType)
125                         }
126
127                         
128                         /*
129                          * Extracting User Parameters from incoming Request and converting into a Map
130                          */
131                         def jsonSlurper = new JsonSlurper()
132                         def jsonOutput = new JsonOutput()
133
134                         Map reqMap = jsonSlurper.parseText(siRequest)
135
136                         //InputParams
137                         def userParams = reqMap.requestDetails?.requestParameters?.userParams
138
139                         Map<String, String> inputMap = [:]
140                         if (userParams) {
141                                 userParams.each {
142                                         userParam -> inputMap.put(userParam.name, userParam.value)
143                                 }
144                         }
145                         
146                         utils.log("DEBUG", "User Input Parameters map: " + userParams.toString(), isDebugEnabled)
147                         execution.setVariable("serviceInputParams", inputMap)
148                         
149                         //TODO
150                         //execution.setVariable("failExists", true)
151
152                 } catch (BpmnError e) {
153                         throw e;
154                 } catch (Exception ex){
155                         msg = "Exception in preProcessRequest " + ex.getMessage()
156                         utils.log("DEBUG", msg, isDebugEnabled)
157                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
158                 }
159                 utils.log("DEBUG"," ***** Exit preProcessRequest *****",  isDebugEnabled)
160         }
161
162         public void sendSyncResponse (Execution execution) {
163                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
164                 utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled)
165
166                 try {
167                         String requestId = execution.getVariable("msoRequestId")
168                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
169                         // RESTResponse for API Handler (APIH) Reply Task
170                         String createServiceRestRequest = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim()
171                         utils.log("DEBUG", " sendSyncResponse to APIH:" + "\n" + createServiceRestRequest, isDebugEnabled)
172                         sendWorkflowResponse(execution, 202, createServiceRestRequest)
173                         execution.setVariable("sentSyncResponse", true)
174
175                 } catch (Exception ex) {
176                         String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage()
177                         utils.log("DEBUG", msg, isDebugEnabled)
178                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
179                 }
180                 utils.log("DEBUG"," ***** Exit sendSyncResopnse *****",  isDebugEnabled)
181         }
182
183
184         public void sendSyncError (Execution execution) {
185                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
186                 utils.log("DEBUG", " *** sendSyncError *** ", isDebugEnabled)
187
188                 try {
189                         String errorMessage = ""
190                         if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
191                                 WorkflowException wfe = execution.getVariable("WorkflowException")
192                                 errorMessage = wfe.getErrorMessage()
193                         } else {
194                                 errorMessage = "Sending Sync Error."
195                         }
196
197                         String buildworkflowException =
198                                         """<aetgt:WorkflowException xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1">
199                                         <aetgt:ErrorMessage>${errorMessage}</aetgt:ErrorMessage>
200                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
201                                    </aetgt:WorkflowException>"""
202
203                         utils.logAudit(buildworkflowException)
204                         sendWorkflowResponse(execution, 500, buildworkflowException)
205
206                 } catch (Exception ex) {
207                         utils.log("DEBUG", " Sending Sync Error Activity Failed. " + "\n" + ex.getMessage(), isDebugEnabled)
208                 }
209
210         }
211
212         public void prepareCompletionRequest (Execution execution) {
213                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
214                 utils.log("DEBUG", " *** prepareCompletion *** ", isDebugEnabled)
215
216                 try {
217                         String requestId = execution.getVariable("msoRequestId")
218                         String serviceInstanceId = execution.getVariable("serviceInstanceId")
219                         String source = execution.getVariable("source")
220                         
221                         String msoCompletionRequest =
222                                         """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
223                                                                 xmlns:ns="http://org.openecomp/mso/request/types/v1">
224                                                 <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
225                                                         <request-id>${requestId}</request-id>
226                                                         <action>CREATE</action>
227                                                         <source>${source}</source>
228                                                 </request-info>
229                                                 <status-message>Service Instance was created successfully.</status-message>
230                                                 <serviceInstanceId>${serviceInstanceId}</serviceInstanceId>
231                                                 <mso-bpel-name>CreateGenericALaCarteServiceInstance</mso-bpel-name>
232                                         </aetgt:MsoCompletionRequest>"""
233
234                         // Format Response
235                         String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest)
236
237                         execution.setVariable("completionRequest", xmlMsoCompletionRequest)
238                         utils.log("DEBUG", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled)
239
240                 } catch (Exception ex) {
241                         String msg = " Exception in prepareCompletion:" + ex.getMessage()
242                         utils.log("DEBUG", msg, isDebugEnabled)
243                         exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
244                 }
245                 utils.log("DEBUG", "*** Exit prepareCompletionRequest ***", isDebugEnabled)
246         }
247
248         public void prepareFalloutRequest(Execution execution){
249                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
250                 utils.log("DEBUG", " *** prepareFalloutRequest *** ", isDebugEnabled)
251
252                 try {
253                         WorkflowException wfex = execution.getVariable("WorkflowException")
254                         utils.log("DEBUG", " Input Workflow Exception: " + wfex.toString(), isDebugEnabled)
255                         String requestId = execution.getVariable("msoRequestId")
256                         String source = execution.getVariable("source")
257                         String requestInfo =
258                                         """<request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
259                                         <request-id>${requestId}</request-id>
260                                         <action>CREATE</action>
261                                         <source>${source}</source>
262                                    </request-info>"""
263
264                         String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo)
265                         execution.setVariable("falloutRequest", falloutRequest)
266                 } catch (Exception ex) {
267                         utils.log("DEBUG", "Exception prepareFalloutRequest:" + ex.getMessage(), isDebugEnabled)
268                         String errorException = "  Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. FalloutHandlerRequest,  buildErrorResponse() - " + ex.getMessage()
269                         String requestId = execution.getVariable("msoRequestId")
270                         String falloutRequest =
271                                         """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1"
272                                                                      xmlns:ns="http://org.openecomp/mso/request/types/v1"
273                                                                      xmlns:wfsch="http://org.openecomp/mso/workflow/schema/v1">
274                                            <request-info xmlns="http://org.openecomp/mso/infra/vnf-request/v1">
275                                               <request-id>${requestId}</request-id>
276                                               <action>CREATE</action>
277                                               <source>VID</source>
278                                            </request-info>
279                                                 <aetgt:WorkflowException xmlns:aetgt="http://org.openecomp/mso/workflow/schema/v1">
280                                                         <aetgt:ErrorMessage>${errorException}</aetgt:ErrorMessage>
281                                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
282                                                 </aetgt:WorkflowException>
283                                         </aetgt:FalloutHandlerRequest>"""
284
285                         execution.setVariable("falloutRequest", falloutRequest)
286                 }
287                 utils.log("DEBUG", "*** Exit prepareFalloutRequest ***", isDebugEnabled)
288         }
289 }