1859838f29b00806d495d8f3f07739251897bd1c
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / openecomp / mso / bpmn / common / scripts / SDNCAdapterRestV1.groovy
1 package org.openecomp.mso.bpmn.common.scripts
2
3 import java.text.SimpleDateFormat
4 import java.net.URLEncoder
5
6 import org.apache.commons.codec.binary.Base64
7 import org.apache.commons.lang3.*
8 import org.camunda.bpm.engine.delegate.BpmnError
9 import org.camunda.bpm.engine.runtime.Execution
10
11 import groovy.json.*
12
13 import org.json.JSONObject
14
15 import org.openecomp.mso.bpmn.core.WorkflowException
16 import org.openecomp.mso.bpmn.core.json.JsonUtils
17 import org.openecomp.mso.rest.APIResponse
18 import org.openecomp.mso.rest.RESTClient
19 import org.openecomp.mso.rest.RESTConfig
20
21
22 class SDNCAdapterRestV1 extends AbstractServiceTaskProcessor {
23
24         ExceptionUtil exceptionUtil = new ExceptionUtil()
25         JsonUtils jsonUtil = new JsonUtils()
26
27         /**
28          * Processes the incoming request.
29          */
30         public void preProcessRequest (Execution execution) {
31                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
32                         'execution=' + execution.getId() +
33                         ')'
34                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
35                 logDebug('Entered ' + method, isDebugLogEnabled)
36
37                 def prefix="SDNCREST_"
38                 execution.setVariable("prefix", prefix)
39                 setSuccessIndicator(execution, false)
40
41                 try {
42                         // Determine the request type and log the request
43
44                         String request = validateRequest(execution, "mso-request-id")
45                         String requestType = jsonUtil.getJsonRootProperty(request)
46                         execution.setVariable(prefix + 'requestType', requestType)
47                         logDebug(getProcessKey(execution) + ': ' + prefix + 'requestType = ' + requestType, isDebugLogEnabled)
48                         utils.logAudit('SDNCAdapterRestV1, request: ' + request)
49
50                         // Determine the SDNCAdapter endpoint
51
52                         String sdncAdapterEndpoint = execution.getVariable("URN_mso_adapters_sdnc_rest_endpoint")
53
54                         if (sdncAdapterEndpoint == null || sdncAdapterEndpoint.isEmpty()) {
55                                 String msg = getProcessKey(execution) + ': mso:adapters:sdnc:rest:endpoint URN mapping is not defined'
56                                 logDebug(msg, isDebugLogEnabled)
57                                 logError(msg)
58                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
59                         }
60
61                         while (sdncAdapterEndpoint.endsWith('/')) {
62                                 sdncAdapterEndpoint = sdncAdapterEndpoint.substring(0, sdncAdapterEndpoint.length()-1)
63                         }
64
65                         String sdncAdapterMethod = null
66                         String sdncAdapterUrl = null
67                         String sdncAdapterRequest = request
68
69                         if ('SDNCServiceRequest'.equals(requestType)) {
70                                 // Get the sdncRequestId from the request
71
72                                 String sdncRequestId = jsonUtil.getJsonValue(request, requestType + ".sdncRequestId")
73
74                                 if (sdncRequestId == null || sdncRequestId.isEmpty()) {
75                                         String msg = getProcessKey(execution) + ': no sdncRequestId in ' + requestType
76                                         logDebug(msg, isDebugLogEnabled)
77                                         logError(msg)
78                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
79                                 }
80
81                                 execution.setVariable('SDNCAResponse_CORRELATOR', sdncRequestId)
82                                 logDebug(getProcessKey(execution) + ': SDNCAResponse_CORRELATOR = ' + sdncRequestId, isDebugLogEnabled)
83
84                                 // Get the bpNotificationUrl from the request (just to make sure it's there)
85
86                                 String bpNotificationUrl = jsonUtil.getJsonValue(request, requestType + ".bpNotificationUrl")
87
88                                 if (bpNotificationUrl == null || bpNotificationUrl.isEmpty()) {
89                                         String msg = getProcessKey(execution) + ': no bpNotificationUrl in ' + requestType
90                                         logDebug(msg, isDebugLogEnabled)
91                                         logError(msg)
92                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
93                                 }
94
95                                 sdncAdapterMethod = 'POST'
96                                 sdncAdapterUrl = sdncAdapterEndpoint + '/services'
97
98                         } else {
99                                 String msg = getProcessKey(execution) + ': Unsupported request type: ' + requestType
100                                 logDebug(msg, isDebugLogEnabled)
101                                 logError(msg)
102                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
103                         }
104
105                         execution.setVariable(prefix + 'sdncAdapterMethod', sdncAdapterMethod)
106                         logDebug(getProcessKey(execution) + ': ' + prefix + 'sdncAdapterMethod = ' + sdncAdapterMethod, isDebugLogEnabled)
107                         execution.setVariable(prefix + 'sdncAdapterUrl', sdncAdapterUrl)
108                         logDebug(getProcessKey(execution) + ': ' + prefix + 'sdncAdapterUrl = ' + sdncAdapterUrl, isDebugLogEnabled)
109                         execution.setVariable(prefix + 'sdncAdapterRequest', sdncAdapterRequest)
110                         logDebug(getProcessKey(execution) + ': ' + prefix + 'sdncAdapterRequest = \n' + sdncAdapterRequest, isDebugLogEnabled)
111
112                         // Get the Basic Auth credentials for the SDNCAdapter (yes... we ARE using the PO adapters credentials)
113
114                         String basicAuthValue = execution.getVariable("URN_mso_adapters_po_auth")
115
116                         if (basicAuthValue == null || basicAuthValue.isEmpty()) {
117                                 logDebug(getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined", isDebugLogEnabled)
118                                 logError(getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined")
119                         } else {
120                                 logDebug(getProcessKey(execution) + ": Obtained BasicAuth credentials for SDNCAdapter:" +
121                                         basicAuthValue, isDebugLogEnabled)
122                                 try {
123                                         def encodedString = utils.getBasicAuth(basicAuthValue, execution.getVariable("URN_mso_msoKey"))
124                                         execution.setVariable(prefix + 'basicAuthHeaderValue', encodedString)
125                                 } catch (IOException ex) {
126                                         logDebug(getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter", isDebugLogEnabled)
127                                         logError(getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter")
128                                 }
129                         }
130
131                         // Set the timeout value, e.g. PT5M. It may be specified in the request as the
132                         // bpTimeout value.  If it's not in the request, use the URN mapping value.
133
134                         String timeout = jsonUtil.getJsonValue(request, requestType + ".bpTimeout")
135
136                         if (timeout == null || timeout.isEmpty()) {
137                                 timeout = execution.getVariable("URN_mso_sdnc_timeout")
138                         }
139
140                         execution.setVariable(prefix + 'timeout', timeout)
141                         logDebug(getProcessKey(execution) + ': ' + prefix + 'timeout = ' + timeout, isDebugLogEnabled)
142                 } catch (BpmnError e) {
143                         throw e
144                 } catch (Exception e) {
145                         String msg = 'Caught exception in ' + method + ": " + e
146                         logDebug(msg, isDebugLogEnabled)
147                         logError(msg)
148                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
149                 }
150         }
151
152         /**
153          * Sends the request to the SDNC adapter.
154          */
155         public void sendRequestToSDNCAdapter(Execution execution) {
156                 def method = getClass().getSimpleName() + '.sendRequestToSDNCAdapter(' +
157                         'execution=' + execution.getId() +
158                         ')'
159                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
160                 logDebug('Entered ' + method, isDebugLogEnabled)
161
162                 String prefix = execution.getVariable('prefix')
163
164                 try {
165                         String sdncAdapterMethod = execution.getVariable(prefix + 'sdncAdapterMethod')
166                         String sdncAdapterUrl = execution.getVariable(prefix + 'sdncAdapterUrl')
167                         String sdncAdapterRequest = execution.getVariable(prefix + 'sdncAdapterRequest')
168                         utils.logAudit("Outgoing SDNC Rest Request is: " + sdncAdapterRequest)
169
170                         RESTConfig config = new RESTConfig(sdncAdapterUrl)
171                         RESTClient client = new RESTClient(config).
172                                 addHeader("Content-Type", "application/json").
173                                 addAuthorizationHeader(execution.getVariable(prefix + "basicAuthHeaderValue"))
174
175                         APIResponse response
176
177                         if ("GET".equals(sdncAdapterMethod)) {
178                                 response = client.httpGet()
179                         } else if ("PUT".equals(sdncAdapterMethod)) {
180                                 response = client.httpPut(sdncAdapterRequest)
181                         } else if ("POST".equals(sdncAdapterMethod)) {
182                                 response = client.httpPost(sdncAdapterRequest)
183                         } else if ("DELETE".equals(sdncAdapterMethod)) {
184                                 response = client.httpDelete(sdncAdapterRequest)
185                         } else {
186                                 String msg = 'Unsupported HTTP method "' + sdncAdapterMethod + '" in ' + method + ": " + e
187                                 logDebug(msg, isDebugLogEnabled)
188                                 logError(msg)
189                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
190                         }
191
192                         execution.setVariable(prefix + "sdncAdapterStatusCode", response.getStatusCode())
193                         execution.setVariable(prefix + "sdncAdapterResponse", response.getResponseBodyAsString())
194                 } catch (BpmnError e) {
195                         throw e
196                 } catch (Exception e) {
197                         String msg = 'Caught exception in ' + method + ": " + e
198                         logDebug(msg, isDebugLogEnabled)
199                         logError(msg)
200                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
201                 }
202         }
203
204         /**
205          * Processes a callback.
206          */
207         public void processCallback(Execution execution){
208                 def method = getClass().getSimpleName() + '.processCallback(' +
209                         'execution=' + execution.getId() +
210                         ')'
211                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
212                 logDebug('Entered ' + method, isDebugLogEnabled)
213
214                 String prefix = execution.getVariable('prefix')
215                 String callback = execution.getVariable('SDNCAResponse_MESSAGE')
216                 utils.logAudit("Incoming SDNC Rest Callback is: " + callback)
217
218                 try {
219                         logDebug(getProcessKey(execution) + ": received callback:\n" + callback, isDebugLogEnabled)
220
221                         int callbackNumber = 1
222                         while (execution.getVariable(prefix + 'callback' + callbackNumber) != null) {
223                                 ++callbackNumber
224                         }
225
226                         execution.setVariable(prefix + 'callback' + callbackNumber, callback)
227                         execution.removeVariable('SDNCAResponse_MESSAGE')
228
229                         String responseType = jsonUtil.getJsonRootProperty(callback)
230
231                         // Get the ackFinalIndicator and make sure it's either Y or N.  Default to Y.
232                         String ackFinalIndicator = jsonUtil.getJsonValue(callback, responseType + ".ackFinalIndicator")
233
234                         if (!'N'.equals(ackFinalIndicator)) {
235                                 ackFinalIndicator = 'Y'
236                         }
237
238                         execution.setVariable(prefix + "ackFinalIndicator", ackFinalIndicator)
239
240                         if (responseType.endsWith('Error')) {
241                                 sdncAdapterBuildWorkflowException(execution, callback)
242                         }
243                 } catch (Exception e) {
244                         callback = callback == null || String.valueOf(callback).isEmpty() ? "NONE" : callback
245                         String msg = "Received error from SDNCAdapter: " + callback
246                         logDebug(getProcessKey(execution) + ': ' + msg, isDebugLogEnabled)
247                         exceptionUtil.buildWorkflowException(execution, 5300, msg)
248                 }
249         }
250
251         /**
252          * Tries to parse the response as XML to extract the information to create
253          * a WorkflowException.  If the response cannot be parsed, a more generic
254          * WorkflowException is created.
255          */
256         public void sdncAdapterBuildWorkflowException(Execution execution, String response) {
257                 try {
258                         String responseType = jsonUtil.getJsonRootProperty(response)
259                         String responseCode = jsonUtil.getJsonValue(response, responseType + ".responseCode")
260                         String responseMessage = jsonUtil.getJsonValue(response, responseType + ".responseMessage")
261
262                         String info = ""
263
264                         if (responseCode != null && !responseCode.isEmpty()) {
265                                  info += " responseCode='" + responseCode + "'"
266                         }
267
268                         if (responseMessage != null && !responseMessage.isEmpty()) {
269                                  info += " responseMessage='" + responseMessage + "'"
270                         }
271
272                         // Note: the mapping function handles a null or empty responseCode
273                         int mappedResponseCode = Integer.parseInt(exceptionUtil.MapSDNCResponseCodeToErrorCode(responseCode));
274                         exceptionUtil.buildWorkflowException(execution, mappedResponseCode, "Received " + responseType +
275                                 " from SDNCAdapter:" + info)
276                 } catch (Exception e) {
277                         response = response == null || String.valueOf(response).isEmpty() ? "NONE" : response
278                         exceptionUtil.buildWorkflowException(execution, 5300, "Received error from SDNCAdapter: " + response)
279                 }
280         }
281
282         /**
283          * Gets the last callback request from the execution, or null if there was no callback.
284          */
285         public String getLastCallback(Execution execution) {
286                 def method = getClass().getSimpleName() + '.getLastCallback(' +
287                         'execution=' + execution.getId() +
288                         ')'
289                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
290                 logDebug('Entered ' + method, isDebugLogEnabled)
291
292                 String prefix = execution.getVariable('prefix')
293
294                 try {
295                         int callbackNumber = 1
296                         String callback = null
297
298                         while (true) {
299                                 String thisCallback = (String) execution.getVariable(prefix + 'callback' + callbackNumber)
300
301                                 if (thisCallback == null) {
302                                         break
303                                 }
304
305                                 callback = thisCallback
306                                 ++callbackNumber
307                         }
308
309                         return callback
310                 } catch (Exception e) {
311                         String msg = 'Caught exception in ' + method + ": " + e
312                         logDebug(msg, isDebugLogEnabled)
313                         logError(msg)
314                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
315                 }
316         }
317
318         /**
319          * Sets the timeout value to wait for the next notification.
320          */
321         public void setTimeoutValue(Execution execution) {
322                 def method = getClass().getSimpleName() + '.setTimeoutValue(' +
323                         'execution=' + execution.getId() +
324                         ')'
325                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
326                 logDebug('Entered ' + method, isDebugLogEnabled)
327
328                 String prefix = execution.getVariable('prefix')
329
330                 try {
331                         def timeoutValue = execution.getVariable("URN_mso_sdnc_timeout")
332
333                         if (execution.getVariable(prefix + 'callback1') != null) {
334                                 // Waiting for subsequent notifications
335                         }
336                 } catch (Exception e) {
337                         String msg = 'Caught exception in ' + method + ": " + e
338                         logDebug(msg, isDebugLogEnabled)
339                         logError(msg)
340                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
341                 }
342         }
343 }