Initial OpenECOMP MSO commit
[so.git] / bpmn / MSOGammaBPMN / src / main / groovy / com / att / bpm / scripts / SDNCAdapter.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 com.att.bpm.scripts;
22
23 import org.openecomp.mso.bpmn.core.WorkflowException
24 import java.text.SimpleDateFormat
25
26 import org.camunda.bpm.engine.delegate.BpmnError
27 import org.camunda.bpm.engine.runtime.Execution
28 import org.apache.commons.codec.binary.Base64;
29
30
31 // SDNC Adapter Request/Response processing
32
33 public class SDNCAdapter extends AbstractServiceTaskProcessor {
34
35         def Prefix="SDNCA_"
36         ExceptionUtil exceptionUtil = new ExceptionUtil()
37
38         // Script Task: Process SDNC Workflow Request
39         // Params:      Workflow Execution
40         // Assume:      Received SDNCAdapterWorkflowRequest is in variable 'sdncAdapterWorkflowRequest'
41         //                      Put created SDNCAdapterRequest in variable 'sdncAdapterRequest'
42         public void preProcessRequest (Execution execution) {
43                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
44                 try{
45
46                         utils.log("DEBUG", "=========== Begin PreProcess SDNCAdapterRequestScript  ===========", isDebugEnabled)
47                         utils.log("DEBUG", "Incoming sdncAdapterWorkflowRequest:\n" + execution.getVariable("sdncAdapterWorkflowRequest"), isDebugEnabled)
48
49                         // Initialize some variables used throughout the flow
50                         execution.setVariable("prefix", Prefix)
51                         execution.setVariable("sdncAdapterResponse", "")
52                         execution.setVariable("asynchronousResponseTimeout", false)
53                         execution.setVariable("continueListening", false)
54                         execution.setVariable("SDNCA_SuccessIndicator", false)
55
56                         // Authorization Info
57                         String basicAuthValue = execution.getVariable("URN_mso_adapters_po_auth")
58                         utils.log("DEBUG", "Obtained BasicAuth userid password for sdnc adapter:" + basicAuthValue, isDebugEnabled)
59                         try {
60                                 def encodedString = utils.getBasicAuth(basicAuthValue, execution.getVariable("URN_mso_msoKey"))
61                                 execution.setVariable("BasicAuthHeaderValue",encodedString)
62                         } catch (IOException ex) {
63                                 utils.log("ERROR", "Unable to encode username password string")
64                         }
65
66                         // TODO Use variables instead of passing xml request - Huh?
67
68                         // Get original RequestHeader
69                         def sdncwfreq= execution.getVariable("sdncAdapterWorkflowRequest")
70                         def requestHeader = utils.getNodeXml(sdncwfreq, "RequestHeader")
71                         requestHeader = requestHeader.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", "")
72                         utils.log("DEBUG", "RequestHeader:\n" + requestHeader, isDebugEnabled)
73
74                         // Set Callback URL to use from URN Mapping or jBoss Property
75                         def origCallbackUrl = utils.getNodeText(requestHeader, "CallbackUrl")
76                         def callbackUrlToUse = execution.getVariable("URN_mso_workflow_sdncadapter_callback")
77                         MsoUtils msoUtil = new MsoUtils()
78                         def useQualifiedHostName = execution.getVariable("URN_mso_use_qualified_host")
79                         if((useQualifiedHostName!=null) && (useQualifiedHostName.equals("true"))){
80                                 callbackUrlToUse = msoUtil.getQualifiedHostNameForCallback(callbackUrlToUse)
81                         }
82                         utils.log("DEBUG", "Callback URL to use:\n" + callbackUrlToUse, isDebugEnabled)
83                         requestHeader = requestHeader.replace(origCallbackUrl, callbackUrlToUse)
84
85                         // Get parameters from request header
86                         def sdnca_svcInstanceId = utils.getNodeText1(requestHeader, "SvcInstanceId") // optional
87                         utils.log("DEBUG", "SvcInstanceId: " + sdnca_svcInstanceId, isDebugEnabled)
88                         def sdnca_msoAction = utils.getNodeText1(requestHeader, "MsoAction") // optional
89                         utils.log("DEBUG", "MsoAction: " + sdnca_msoAction, isDebugEnabled)
90                         def sdnca_svcAction = utils.getNodeText(requestHeader, "SvcAction")
91                         utils.log("DEBUG", "SvcAction: " + sdnca_svcAction, isDebugEnabled)
92                         def sdnca_svcOperation = utils.getNodeText(requestHeader, "SvcOperation")
93                         utils.log("DEBUG", "SvcOperation: " + sdnca_svcOperation, isDebugEnabled)
94                         def sdncRequestData = utils.getChildNodes(sdncwfreq, "SDNCRequestData")
95                         sdncRequestData = sdncRequestData.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", "")
96                         sdncRequestData = sdncRequestData.replaceAll('tag0:', '').replaceAll(':tag0', '')
97                         utils.log("DEBUG", "SDNCRequestData:\n" + sdncRequestData, isDebugEnabled)
98                         def sdnca_serviceType = ""
99                         if (utils.nodeExists(sdncwfreq, "service-type")) {
100                                 sdnca_serviceType = utils.getNodeText(sdncwfreq, "service-type")
101                         }
102                         utils.log("DEBUG", "service-type: " + sdnca_serviceType, isDebugEnabled)
103                         def serviceConfigActivate = false
104                         def source = ''
105
106                         execution.setVariable("serviceConfigActivate", serviceConfigActivate)
107                         utils.log("DEBUG", "serviceConfigActivate: " + serviceConfigActivate, isDebugEnabled)
108                         execution.setVariable("source", source)
109                         utils.log("DEBUG", "source: " + source, isDebugEnabled)
110
111                         //calling process should pass a generated uuid if sending multiple sdnc requests
112                         def requestId = utils.getNodeText(requestHeader, "RequestId")
113                         execution.setVariable(Prefix + "requestId", requestId)
114
115                         // Prepare SDNC Request to the SDNC Adapter
116                         String sdncAdapterRequest = """
117                         <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
118                         <SOAP-ENV:Body>
119                         <aetgt:SDNCAdapterRequest xmlns:aetgt="http://domain2.att.com/workflow/sdnc/adapter/schema/v1" xmlns:sdncadaptersc="http://domain2.att.com/workflow/sdnc/adapter/schema/v1">
120                         <sdncadapter:RequestHeader xmlns:sdncadapter="http://domain2.att.com/workflow/sdnc/adapter/schema/v1">
121                         <sdncadapter:RequestId>${requestId}</sdncadapter:RequestId>"""
122
123                         if (sdnca_svcInstanceId != null) {
124                                 sdncAdapterRequest += """
125                         <sdncadapter:SvcInstanceId>${sdnca_svcInstanceId}</sdncadapter:SvcInstanceId>"""
126                         }
127
128                         sdncAdapterRequest += """
129                         <sdncadapter:SvcAction>${sdnca_svcAction}</sdncadapter:SvcAction>
130                         <sdncadapter:SvcOperation>${sdnca_svcOperation}</sdncadapter:SvcOperation>
131                         <sdncadapter:CallbackUrl>${callbackUrlToUse}</sdncadapter:CallbackUrl>"""
132
133                         if (sdnca_msoAction != null) {
134                                 sdncAdapterRequest += """
135                         <sdncadapter:MsoAction>${sdnca_msoAction}</sdncadapter:MsoAction>"""
136                         }
137
138                         sdncAdapterRequest += """
139                         </sdncadapter:RequestHeader>
140                         <sdncadaptersc:RequestData>${sdncRequestData}</sdncadaptersc:RequestData></aetgt:SDNCAdapterRequest></SOAP-ENV:Body></SOAP-ENV:Envelope>"""
141
142                         utils.logAudit("Outgoing SDNCAdapterRequest:\n" + sdncAdapterRequest)
143                         execution.setVariable("sdncAdapterRequest", sdncAdapterRequest)
144
145                         utils.log("DEBUG", execution.getVariable("sdncAdapterRequest"), isDebugEnabled)
146                         utils.log("DEBUG", execution.getVariable("URN_mso_adapters_sdnc_endpoint"), isDebugEnabled)
147                 }catch(Exception e){
148                         utils.log("DEBUG", 'Internal Error occured during PreProcess Method: ' + e, isDebugEnabled)
149                         exceptionUtil.buildAndThrowWorkflowException(execution, 9999, 'Internal Error occured during PreProcess Method') // TODO: what message and error code?
150                 }
151                 utils.log("DEBUG","=========== End pre Process SDNCRequestScript ===========", isDebugEnabled)
152         }
153
154         public void postProcessResponse (Execution execution) {
155
156                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
157                 try{
158                         utils.log("DEBUG","=========== Begin POSTProcess SDNCAdapter ===========", isDebugEnabled)
159                         utils.log("DEBUG","Incoming sdncAdapterCallbackRequest:\n" + execution.getVariable("sdncAdapterCallbackRequest"), isDebugEnabled)
160
161                         // Check the sdnccallback request and get the responsecode
162                         def sdnccallbackreq = execution.getVariable("sdncAdapterCallbackRequest")
163                         def callbackRequestData = ""
164                         def callbackHeader = ""
165
166                         if(sdnccallbackreq != null){
167                                 callbackHeader = utils.getNodeXml(sdnccallbackreq, "CallbackHeader")
168                                 callbackRequestData = utils.getNodeXml(sdnccallbackreq, "RequestData")
169
170                                 callbackHeader = callbackHeader.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", "")
171                                 utils.log("DEBUG","SDNCCallbackHeader is:\n" + callbackHeader, isDebugEnabled)
172
173                                 callbackRequestData = callbackRequestData.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", "")
174                                 utils.log("DEBUG","DECODED SDNCCallback RequestData is:\n" + callbackRequestData, isDebugEnabled)
175
176                                 String sdncAdapterWorkflowResponse ="""
177                                                 <sdncadapterworkflow:SDNCAdapterWorkflowResponse xmlns:sdncadapterworkflow="http://ecomp.att.com/mso/workflow/schema/v1">
178                                                 <sdncadapterworkflow:response-data>
179                                                 ${callbackHeader}
180                                                 ${callbackRequestData}
181                                                 </sdncadapterworkflow:response-data>
182                                                 </sdncadapterworkflow:SDNCAdapterWorkflowResponse>"""
183
184
185                                 utils.log("DEBUG","Outgoing sdncAdapterWorkflowResponse:\n" + sdncAdapterWorkflowResponse, isDebugEnabled)
186                                 sdncAdapterWorkflowResponse = utils.formatXml(sdncAdapterWorkflowResponse)
187                                 execution.setVariable("sdncAdapterResponse", sdncAdapterWorkflowResponse)
188                                 // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead
189                                 execution.setVariable("WorkflowResponse", sdncAdapterWorkflowResponse)
190
191                                 // Check final indicator to determine if we are to continue listening or not
192                                 def String enhancedCallbackRequestData = callbackRequestData.replaceAll("&amp;", "&")
193                                 enhancedCallbackRequestData = enhancedCallbackRequestData.replaceAll("&lt;", "<")
194                                 enhancedCallbackRequestData = enhancedCallbackRequestData.replaceAll("&gt;", ">")
195                                 // replace the data with '&' (ex: subscriber-name= 'FOUR SEASONS HEATING & COOLING'
196                                 enhancedCallbackRequestData = enhancedCallbackRequestData.replace("&", "&amp;")
197                                 utils.log("DEBUG","EnhancedCallbackRequestData:\n" + enhancedCallbackRequestData, isDebugEnabled)
198                                 execution.setVariable("enhancedCallbackRequestData", enhancedCallbackRequestData)
199                                 def continueListening = false
200                                 if (utils.nodeExists(enhancedCallbackRequestData, "ack-final-indicator")) {
201                                         if (utils.getNodeText(enhancedCallbackRequestData, "ack-final-indicator") == 'N') {
202                                                 continueListening = true
203                                         }
204                                 }
205                                 execution.setVariable("continueListening", continueListening)
206                                 utils.log("DEBUG", "Continue Listening: " + continueListening, isDebugEnabled)
207                         }else{
208                                 // Timed out waiting for asynchronous message, build error response
209                                 exceptionUtil.buildWorkflowException(execution, 500, "SDNC Callback Timeout Error")
210                                 execution.setVariable("asynchronousResponseTimeout", true)
211                                 utils.log("DEBUG", "Timed out waiting for asynchronous message", isDebugEnabled)
212                         }
213                 }catch(Exception e){
214                         utils.log("DEBUG", 'Internal Error occured during PostProcess Method: ' + e, isDebugEnabled)
215                         exceptionUtil.buildAndThrowWorkflowException(execution, 9999, 'Internal Error occured during PostProcess Method') // TODO: what message and error code?
216                 }
217                 utils.log("DEBUG","=========== End POSTProcess SDNCAdapter ===========", isDebugEnabled)
218         }
219
220         public void callbackResponsecheck(Execution execution){
221
222                 def sdnccallbackreq=execution.getVariable("sdncAdapterCallbackRequest")
223                 if (sdnccallbackreq==null){
224                         execution.setVariable("callbackResponseReceived",false);
225                 }else{
226                         execution.setVariable("callbackResponseReceived",true);
227                 }
228         }
229
230         public void resetCallbackRequest(Execution execution) {
231
232                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
233
234                 utils.log("DEBUG","=========== Begin Reset Callback Info SDNCAdapter ===========", isDebugEnabled)
235
236                 // Clear sdncAdapterCallbackRequest variable
237                 execution.removeVariable("sdncAdapterCallbackRequest")
238
239                 // Determine and set SDNC Timeout Value
240                 def enhancedCallbackRequestData = execution.getVariable("enhancedCallbackRequestData")
241                 def interim = false
242                 if (enhancedCallbackRequestData != null) {
243                         if (utils.nodeExists(enhancedCallbackRequestData, "ack-final-indicator")) {
244                                 if (utils.getNodeText(enhancedCallbackRequestData, "ack-final-indicator") == 'N') {
245                                         interim = true
246                                 }
247                         }
248                 }
249                 def timeoutValue = execution.getVariable("URN_mso_sdnc_timeout")
250                 def sdncAdapterWorkflowRequest = execution.getVariable("sdncAdapterWorkflowRequest")
251                 if (interim && utils.nodeExists(sdncAdapterWorkflowRequest, "InterimSDNCTimeOutValueInHours")) {
252                         timeoutValue = "PT" + utils.getNodeText(sdncAdapterWorkflowRequest, "InterimSDNCTimeOutValueInHours") + "H"
253                 } else if (utils.nodeExists(sdncAdapterWorkflowRequest, "SDNCTimeOutValueInMinutes")) {
254                         timeoutValue = "PT" + utils.getNodeText(sdncAdapterWorkflowRequest, "SDNCTimeOutValueInMinutes") + "M"
255                 }
256                 execution.setVariable("sdncTimeoutValue", timeoutValue)
257                 utils.log("DEBUG", "Setting SDNC Timeout Value to " + timeoutValue, isDebugEnabled)
258
259                 utils.log("DEBUG","=========== End Reset Callback Info SDNCAdapter ===========", isDebugEnabled)
260         }
261
262         public void prepareCSIMessage(Execution execution) {
263         
264         }
265
266         public void prepareDBMessage(Execution execution) {
267
268                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
269
270                 utils.log("DEBUG","=========== Begin Prepare DB Message SDNCAdapter ===========", isDebugEnabled)
271
272                 // Create DB Message
273                 def dbRequestId = execution.getVariable("att-mso-request-id")
274                 String dbUpdateInterimStageCompletion = """
275                         <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
276                                 <SOAP-ENV:Body>
277                                         <DBAdapter:updateInterimStageCompletion xmlns:DBAdapter="http://com.att.mso/requestsdb">
278                                                 <requestId>${dbRequestId}</requestId>
279                                                 <interimStageCompletion>1</interimStageCompletion>
280                                                 <lastModifiedBy>BPEL</lastModifiedBy>
281                                 </DBAdapter:updateInterimStageCompletion>
282                                 </SOAP-ENV:Body>
283                         </SOAP-ENV:Envelope>
284                         """
285
286                 execution.setVariable("dbUpdateInterimStageCompletion", dbUpdateInterimStageCompletion)
287                 utils.log("DEBUG","DB UpdateInterimStageCompletion:\n" + dbUpdateInterimStageCompletion, isDebugEnabled)
288
289                 utils.log("DEBUG","=========== End Prepare DB Message SDNCAdapter ===========", isDebugEnabled)
290         }
291
292         public void prepareCCDMessage(Execution execution) {
293
294                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
295
296                 utils.log("DEBUG","=========== Begin Prepare CCD Message SDNCAdapter ===========", isDebugEnabled)
297
298                 try {
299                         def sdncwfreq= execution.getVariable("sdncAdapterWorkflowRequest")
300                         def sdncRequestData = utils.getNodeXml(sdncwfreq, "SDNCRequestData", false)
301
302                         def ccdNotificationUrl = utils.getNodeText(sdncRequestData, 'notification-url')
303                         execution.setVariable('ccd-notification-url', ccdNotificationUrl)
304                         utils.log("DEBUG", 'ccd-notification-url: ' + ccdNotificationUrl, isDebugEnabled)
305
306                         def requestId = utils.getNodeText(sdncRequestData, 'request-id')
307                         def requestAction = utils.getNodeText(sdncRequestData, 'request-action')
308                         String payload ="""
309                                 <ns:status-notification
310                                                 xmlns:ns="http://ecomp.att.com/mso/statusnotification/schema/v1"
311                                                 xmlns:msoservtypes="http://ecomp.att.com/mso/request/types/v1"
312                                                 xmlns:structuredtypes="http://ecomp.att.com/mso/structured/types/v1">
313                                         <msoservtypes:request-id>${requestId}</msoservtypes:request-id>
314                                         <msoservtypes:request-action>${requestAction}</msoservtypes:request-action>
315                                         <msoservtypes:source>CCD</msoservtypes:source>
316                                         <msoservtypes:ack-final-indicator>N</msoservtypes:ack-final-indicator>
317                                         <structuredtypes:parameter-list>
318                                                 <structuredtypes:parameter>
319                                                         <structuredtypes:name>request-stage</structuredtypes:name>
320                                                         <structuredtypes:value>DataStagingComplete</structuredtypes:value>
321                                                 </structuredtypes:parameter>
322                                         </structuredtypes:parameter-list>
323                                 </ns:status-notification>
324                         """
325
326                         payload = utils.formatXml(payload)
327                         execution.setVariable('ccd-notification-payload', payload)
328                         utils.log("DEBUG", 'ccd-notification-payload:\n' + payload, isDebugEnabled)
329
330                 } catch (BpmnError e) {
331                         throw e;
332                 } catch (Exception e) {
333                         logError('Caught exception in prepareCCDMessage', e)
334                         exceptionUtil.buildAndThrowWorkflowException(execution, 9999, 'Internal Error') // TODO: what message and error code?
335                 }
336
337                 utils.log("DEBUG","=========== End Prepare CCD Message SDNCAdapter ===========", isDebugEnabled)
338         }
339
340         public String generateCurrentTimeInUtc(){
341                 final  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
342                 sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
343                 final String utcTime = sdf.format(new Date());
344                 return utcTime;
345         }
346
347         public void toggleSuccessIndicator(Execution execution){
348                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
349                 execution.setVariable("SDNCA_SuccessIndicator", true)
350                 utils.log("DEBUG","Setting SDNCA Success Indicator to True", isDebugEnabled)
351         }
352
353         public void assignError(Execution execution){
354                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
355                 utils.log("DEBUG","=========== Started Assign Error ===========", isDebugEnabled)
356                 WorkflowException wf = execution.getVariable("WorkflowException")
357                 if(wf == null){
358                         exceptionUtil.buildWorkflowException(execution, 5000, "SDNCAdapter Encountered an Internal Error") // TODO: Not sure what message and error code we want here.....
359                 }else{
360                         execution.setVariable("WorkflowException", wf)
361                 }
362
363                 utils.log("DEBUG","Outgoing WorkflowException is: " + execution.getVariable("WorkflowException"), isDebugEnabled)
364                 utils.log("DEBUG","=========== End Assign Error ===========", isDebugEnabled)
365         }
366
367 }
368