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