aboutsummaryrefslogtreecommitdiffstats
path: root/bpmn/MSOGammaBPMN/src/main/groovy/com/att/bpm/scripts/SDNCAdapter.groovy
blob: 8bd6983cc4d1c926f00c2ff516cfd069c5038232 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/*-
 * ============LICENSE_START=======================================================
 * OPENECOMP - MSO
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package com.att.bpm.scripts;

import org.openecomp.mso.bpmn.core.WorkflowException
import java.text.SimpleDateFormat

import org.camunda.bpm.engine.delegate.BpmnError
import org.camunda.bpm.engine.runtime.Execution
import org.apache.commons.codec.binary.Base64;


// SDNC Adapter Request/Response processing

public class SDNCAdapter extends AbstractServiceTaskProcessor {

	def Prefix="SDNCA_"
	ExceptionUtil exceptionUtil = new ExceptionUtil()

	// Script Task: Process SDNC Workflow Request
	// Params: 	Workflow Execution
	// Assume:	Received SDNCAdapterWorkflowRequest is in variable 'sdncAdapterWorkflowRequest'
	//			Put created SDNCAdapterRequest in variable 'sdncAdapterRequest'
	public void preProcessRequest (Execution execution) {
		def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
		try{

			utils.log("DEBUG", "=========== Begin PreProcess SDNCAdapterRequestScript  ===========", isDebugEnabled)
			utils.log("DEBUG", "Incoming sdncAdapterWorkflowRequest:\n" + execution.getVariable("sdncAdapterWorkflowRequest"), isDebugEnabled)

			// Initialize some variables used throughout the flow
			execution.setVariable("prefix", Prefix)
			execution.setVariable("sdncAdapterResponse", "")
			execution.setVariable("asynchronousResponseTimeout", false)
			execution.setVariable("continueListening", false)
			execution.setVariable("SDNCA_SuccessIndicator", false)

			// Authorization Info
			String basicAuthValue = execution.getVariable("URN_mso_adapters_po_auth")
			utils.log("DEBUG", "Obtained BasicAuth userid password for sdnc adapter:" + basicAuthValue, isDebugEnabled)
			try {
				def encodedString = utils.getBasicAuth(basicAuthValue, execution.getVariable("URN_mso_msoKey"))
				execution.setVariable("BasicAuthHeaderValue",encodedString)
			} catch (IOException ex) {
				utils.log("ERROR", "Unable to encode username password string")
			}

			// TODO Use variables instead of passing xml request - Huh?

			// Get original RequestHeader
			def sdncwfreq= execution.getVariable("sdncAdapterWorkflowRequest")
			def requestHeader = utils.getNodeXml(sdncwfreq, "RequestHeader")
			requestHeader = requestHeader.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", "")
			utils.log("DEBUG", "RequestHeader:\n" + requestHeader, isDebugEnabled)

			// Set Callback URL to use from URN Mapping or jBoss Property
			def origCallbackUrl = utils.getNodeText(requestHeader, "CallbackUrl")
			def callbackUrlToUse = execution.getVariable("URN_mso_workflow_sdncadapter_callback")
			MsoUtils msoUtil = new MsoUtils()
			def useQualifiedHostName = execution.getVariable("URN_mso_use_qualified_host")
			if((useQualifiedHostName!=null) && (useQualifiedHostName.equals("true"))){
				callbackUrlToUse = msoUtil.getQualifiedHostNameForCallback(callbackUrlToUse)
			}
			utils.log("DEBUG", "Callback URL to use:\n" + callbackUrlToUse, isDebugEnabled)
			requestHeader = requestHeader.replace(origCallbackUrl, callbackUrlToUse)

			// Get parameters from request header
			def sdnca_svcInstanceId = utils.getNodeText1(requestHeader, "SvcInstanceId") // optional
			utils.log("DEBUG", "SvcInstanceId: " + sdnca_svcInstanceId, isDebugEnabled)
			def sdnca_msoAction = utils.getNodeText1(requestHeader, "MsoAction") // optional
			utils.log("DEBUG", "MsoAction: " + sdnca_msoAction, isDebugEnabled)
			def sdnca_svcAction = utils.getNodeText(requestHeader, "SvcAction")
			utils.log("DEBUG", "SvcAction: " + sdnca_svcAction, isDebugEnabled)
			def sdnca_svcOperation = utils.getNodeText(requestHeader, "SvcOperation")
			utils.log("DEBUG", "SvcOperation: " + sdnca_svcOperation, isDebugEnabled)
			def sdncRequestData = utils.getChildNodes(sdncwfreq, "SDNCRequestData")
			sdncRequestData = sdncRequestData.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", "")
			sdncRequestData = sdncRequestData.replaceAll('tag0:', '').replaceAll(':tag0', '')
			utils.log("DEBUG", "SDNCRequestData:\n" + sdncRequestData, isDebugEnabled)
			def sdnca_serviceType = ""
			if (utils.nodeExists(sdncwfreq, "service-type")) {
				sdnca_serviceType = utils.getNodeText(sdncwfreq, "service-type")
			}
			utils.log("DEBUG", "service-type: " + sdnca_serviceType, isDebugEnabled)
			def serviceConfigActivate = false
			def source = ''

			execution.setVariable("serviceConfigActivate", serviceConfigActivate)
			utils.log("DEBUG", "serviceConfigActivate: " + serviceConfigActivate, isDebugEnabled)
			execution.setVariable("source", source)
			utils.log("DEBUG", "source: " + source, isDebugEnabled)

			//calling process should pass a generated uuid if sending multiple sdnc requests
			def requestId = utils.getNodeText(requestHeader, "RequestId")
			execution.setVariable(Prefix + "requestId", requestId)

			// Prepare SDNC Request to the SDNC Adapter
			String sdncAdapterRequest = """
			<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
			<SOAP-ENV:Body>
			<aetgt:SDNCAdapterRequest xmlns:aetgt="http://domain2.att.com/workflow/sdnc/adapter/schema/v1" xmlns:sdncadaptersc="http://domain2.att.com/workflow/sdnc/adapter/schema/v1">
			<sdncadapter:RequestHeader xmlns:sdncadapter="http://domain2.att.com/workflow/sdnc/adapter/schema/v1">
			<sdncadapter:RequestId>${requestId}</sdncadapter:RequestId>"""

			if (sdnca_svcInstanceId != null) {
				sdncAdapterRequest += """
			<sdncadapter:SvcInstanceId>${sdnca_svcInstanceId}</sdncadapter:SvcInstanceId>"""
			}

			sdncAdapterRequest += """
			<sdncadapter:SvcAction>${sdnca_svcAction}</sdncadapter:SvcAction>
			<sdncadapter:SvcOperation>${sdnca_svcOperation}</sdncadapter:SvcOperation>
			<sdncadapter:CallbackUrl>${callbackUrlToUse}</sdncadapter:CallbackUrl>"""

			if (sdnca_msoAction != null) {
				sdncAdapterRequest += """
			<sdncadapter:MsoAction>${sdnca_msoAction}</sdncadapter:MsoAction>"""
			}

			sdncAdapterRequest += """
			</sdncadapter:RequestHeader>
			<sdncadaptersc:RequestData>${sdncRequestData}</sdncadaptersc:RequestData></aetgt:SDNCAdapterRequest></SOAP-ENV:Body></SOAP-ENV:Envelope>"""

			utils.logAudit("Outgoing SDNCAdapterRequest:\n" + sdncAdapterRequest)
			execution.setVariable("sdncAdapterRequest", sdncAdapterRequest)

			utils.log("DEBUG", execution.getVariable("sdncAdapterRequest"), isDebugEnabled)
			utils.log("DEBUG", execution.getVariable("URN_mso_adapters_sdnc_endpoint"), isDebugEnabled)
		}catch(Exception e){
			utils.log("DEBUG", 'Internal Error occured during PreProcess Method: ' + e, isDebugEnabled)
			exceptionUtil.buildAndThrowWorkflowException(execution, 9999, 'Internal Error occured during PreProcess Method') // TODO: what message and error code?
		}
		utils.log("DEBUG","=========== End pre Process SDNCRequestScript ===========", isDebugEnabled)
	}

	public void postProcessResponse (Execution execution) {

		def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
		try{
			utils.log("DEBUG","=========== Begin POSTProcess SDNCAdapter ===========", isDebugEnabled)
			utils.log("DEBUG","Incoming sdncAdapterCallbackRequest:\n" + execution.getVariable("sdncAdapterCallbackRequest"), isDebugEnabled)

			// Check the sdnccallback request and get the responsecode
			def sdnccallbackreq = execution.getVariable("sdncAdapterCallbackRequest")
			def callbackRequestData = ""
			def callbackHeader = ""

			if(sdnccallbackreq != null){
				callbackHeader = utils.getNodeXml(sdnccallbackreq, "CallbackHeader")
				callbackRequestData = utils.getNodeXml(sdnccallbackreq, "RequestData")

				callbackHeader = callbackHeader.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", "")
				utils.log("DEBUG","SDNCCallbackHeader is:\n" + callbackHeader, isDebugEnabled)

				callbackRequestData = callbackRequestData.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", "")
				utils.log("DEBUG","DECODED SDNCCallback RequestData is:\n" + callbackRequestData, isDebugEnabled)

				String sdncAdapterWorkflowResponse ="""
						<sdncadapterworkflow:SDNCAdapterWorkflowResponse xmlns:sdncadapterworkflow="http://ecomp.att.com/mso/workflow/schema/v1">
						<sdncadapterworkflow:response-data>
						${callbackHeader}
						${callbackRequestData}
						</sdncadapterworkflow:response-data>
						</sdncadapterworkflow:SDNCAdapterWorkflowResponse>"""


				utils.log("DEBUG","Outgoing sdncAdapterWorkflowResponse:\n" + sdncAdapterWorkflowResponse, isDebugEnabled)
				sdncAdapterWorkflowResponse = utils.formatXml(sdncAdapterWorkflowResponse)
				execution.setVariable("sdncAdapterResponse", sdncAdapterWorkflowResponse)
				// TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead
				execution.setVariable("WorkflowResponse", sdncAdapterWorkflowResponse)

				// Check final indicator to determine if we are to continue listening or not
				def String enhancedCallbackRequestData = callbackRequestData.replaceAll("&amp;", "&")
				enhancedCallbackRequestData = enhancedCallbackRequestData.replaceAll("&lt;", "<")
				enhancedCallbackRequestData = enhancedCallbackRequestData.replaceAll("&gt;", ">")
				// replace the data with '&' (ex: subscriber-name= 'FOUR SEASONS HEATING & COOLING'
				enhancedCallbackRequestData = enhancedCallbackRequestData.replace("&", "&amp;")
				utils.log("DEBUG","EnhancedCallbackRequestData:\n" + enhancedCallbackRequestData, isDebugEnabled)
				execution.setVariable("enhancedCallbackRequestData", enhancedCallbackRequestData)
				def continueListening = false
				if (utils.nodeExists(enhancedCallbackRequestData, "ack-final-indicator")) {
					if (utils.getNodeText(enhancedCallbackRequestData, "ack-final-indicator") == 'N') {
						continueListening = true
					}
				}
				execution.setVariable("continueListening", continueListening)
				utils.log("DEBUG", "Continue Listening: " + continueListening, isDebugEnabled)
			}else{
				// Timed out waiting for asynchronous message, build error response
				exceptionUtil.buildWorkflowException(execution, 500, "SDNC Callback Timeout Error")
				execution.setVariable("asynchronousResponseTimeout", true)
				utils.log("DEBUG", "Timed out waiting for asynchronous message", isDebugEnabled)
			}
		}catch(Exception e){
			utils.log("DEBUG", 'Internal Error occured during PostProcess Method: ' + e, isDebugEnabled)
			exceptionUtil.buildAndThrowWorkflowException(execution, 9999, 'Internal Error occured during PostProcess Method') // TODO: what message and error code?
		}
		utils.log("DEBUG","=========== End POSTProcess SDNCAdapter ===========", isDebugEnabled)
	}

	public void callbackResponsecheck(Execution execution){

		def sdnccallbackreq=execution.getVariable("sdncAdapterCallbackRequest")
		if (sdnccallbackreq==null){
			execution.setVariable("callbackResponseReceived",false);
		}else{
			execution.setVariable("callbackResponseReceived",true);
		}
	}

	public void resetCallbackRequest(Execution execution) {

		def isDebugEnabled=execution.getVariable("isDebugLogEnabled")

		utils.log("DEBUG","=========== Begin Reset Callback Info SDNCAdapter ===========", isDebugEnabled)

		// Clear sdncAdapterCallbackRequest variable
		execution.removeVariable("sdncAdapterCallbackRequest")

		// Determine and set SDNC Timeout Value
		def enhancedCallbackRequestData = execution.getVariable("enhancedCallbackRequestData")
		def interim = false
		if (enhancedCallbackRequestData != null) {
			if (utils.nodeExists(enhancedCallbackRequestData, "ack-final-indicator")) {
				if (utils.getNodeText(enhancedCallbackRequestData, "ack-final-indicator") == 'N') {
					interim = true
				}
			}
		}
		def timeoutValue = execution.getVariable("URN_mso_sdnc_timeout")
		def sdncAdapterWorkflowRequest = execution.getVariable("sdncAdapterWorkflowRequest")
		if (interim && utils.nodeExists(sdncAdapterWorkflowRequest, "InterimSDNCTimeOutValueInHours")) {
			timeoutValue = "PT" + utils.getNodeText(sdncAdapterWorkflowRequest, "InterimSDNCTimeOutValueInHours") + "H"
		} else if (utils.nodeExists(sdncAdapterWorkflowRequest, "SDNCTimeOutValueInMinutes")) {
			timeoutValue = "PT" + utils.getNodeText(sdncAdapterWorkflowRequest, "SDNCTimeOutValueInMinutes") + "M"
		}
		execution.setVariable("sdncTimeoutValue", timeoutValue)
		utils.log("DEBUG", "Setting SDNC Timeout Value to " + timeoutValue, isDebugEnabled)

		utils.log("DEBUG","=========== End Reset Callback Info SDNCAdapter ===========", isDebugEnabled)
	}

	public void prepareCSIMessage(Execution execution) {
	
	}

	public void prepareDBMessage(Execution execution) {

		def isDebugEnabled=execution.getVariable("isDebugLogEnabled")

		utils.log("DEBUG","=========== Begin Prepare DB Message SDNCAdapter ===========", isDebugEnabled)

		// Create DB Message
		def dbRequestId = execution.getVariable("att-mso-request-id")
		String dbUpdateInterimStageCompletion = """
			<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
				<SOAP-ENV:Body>
					<DBAdapter:updateInterimStageCompletion xmlns:DBAdapter="http://com.att.mso/requestsdb">
   						<requestId>${dbRequestId}</requestId>
   						<interimStageCompletion>1</interimStageCompletion>
   						<lastModifiedBy>BPEL</lastModifiedBy>
				</DBAdapter:updateInterimStageCompletion>
				</SOAP-ENV:Body>
			</SOAP-ENV:Envelope>
			"""

		execution.setVariable("dbUpdateInterimStageCompletion", dbUpdateInterimStageCompletion)
		utils.log("DEBUG","DB UpdateInterimStageCompletion:\n" + dbUpdateInterimStageCompletion, isDebugEnabled)

		utils.log("DEBUG","=========== End Prepare DB Message SDNCAdapter ===========", isDebugEnabled)
	}

	public void prepareCCDMessage(Execution execution) {

		def isDebugEnabled=execution.getVariable("isDebugLogEnabled")

		utils.log("DEBUG","=========== Begin Prepare CCD Message SDNCAdapter ===========", isDebugEnabled)

		try {
			def sdncwfreq= execution.getVariable("sdncAdapterWorkflowRequest")
			def sdncRequestData = utils.getNodeXml(sdncwfreq, "SDNCRequestData", false)

			def ccdNotificationUrl = utils.getNodeText(sdncRequestData, 'notification-url')
			execution.setVariable('ccd-notification-url', ccdNotificationUrl)
			utils.log("DEBUG", 'ccd-notification-url: ' + ccdNotificationUrl, isDebugEnabled)

			def requestId = utils.getNodeText(sdncRequestData, 'request-id')
			def requestAction = utils.getNodeText(sdncRequestData, 'request-action')
			String payload ="""
				<ns:status-notification
						xmlns:ns="http://ecomp.att.com/mso/statusnotification/schema/v1"
						xmlns:msoservtypes="http://ecomp.att.com/mso/request/types/v1"
						xmlns:structuredtypes="http://ecomp.att.com/mso/structured/types/v1">
					<msoservtypes:request-id>${requestId}</msoservtypes:request-id>
					<msoservtypes:request-action>${requestAction}</msoservtypes:request-action>
					<msoservtypes:source>CCD</msoservtypes:source>
					<msoservtypes:ack-final-indicator>N</msoservtypes:ack-final-indicator>
					<structuredtypes:parameter-list>
						<structuredtypes:parameter>
							<structuredtypes:name>request-stage</structuredtypes:name>
							<structuredtypes:value>DataStagingComplete</structuredtypes:value>
						</structuredtypes:parameter>
					</structuredtypes:parameter-list>
				</ns:status-notification>
			"""

			payload = utils.formatXml(payload)
			execution.setVariable('ccd-notification-payload', payload)
			utils.log("DEBUG", 'ccd-notification-payload:\n' + payload, isDebugEnabled)

		} catch (BpmnError e) {
			throw e;
		} catch (Exception e) {
			logError('Caught exception in prepareCCDMessage', e)
			exceptionUtil.buildAndThrowWorkflowException(execution, 9999, 'Internal Error') // TODO: what message and error code?
		}

		utils.log("DEBUG","=========== End Prepare CCD Message SDNCAdapter ===========", isDebugEnabled)
	}

	public String generateCurrentTimeInUtc(){
		final  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
		sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
		final String utcTime = sdf.format(new Date());
		return utcTime;
	}

	public void toggleSuccessIndicator(Execution execution){
		def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
		execution.setVariable("SDNCA_SuccessIndicator", true)
		utils.log("DEBUG","Setting SDNCA Success Indicator to True", isDebugEnabled)
	}

	public void assignError(Execution execution){
		def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
		utils.log("DEBUG","=========== Started Assign Error ===========", isDebugEnabled)
		WorkflowException wf = execution.getVariable("WorkflowException")
		if(wf == null){
			exceptionUtil.buildWorkflowException(execution, 5000, "SDNCAdapter Encountered an Internal Error") // TODO: Not sure what message and error code we want here.....
		}else{
			execution.setVariable("WorkflowException", wf)
		}

		utils.log("DEBUG","Outgoing WorkflowException is: " + execution.getVariable("WorkflowException"), isDebugEnabled)
		utils.log("DEBUG","=========== End Assign Error ===========", isDebugEnabled)
	}

}