Removed MsoLogger class
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / onap / so / bpmn / common / scripts / SDNCAdapterRestV2.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.common.scripts
24
25 import org.onap.so.logger.ErrorCode
26
27 import java.text.SimpleDateFormat
28 import java.net.URLEncoder
29
30 import org.apache.commons.codec.binary.Base64
31 import org.apache.commons.lang3.*
32 import org.camunda.bpm.engine.delegate.BpmnError
33 import org.camunda.bpm.engine.delegate.DelegateExecution
34
35 import groovy.json.*
36
37 import org.json.JSONObject
38
39 import org.onap.so.bpmn.core.WorkflowException
40 import org.onap.so.bpmn.core.json.JsonUtils
41 import org.onap.so.bpmn.core.UrnPropertiesReader
42 import org.onap.so.logger.MessageEnum
43 import org.slf4j.Logger
44 import org.slf4j.LoggerFactory
45
46
47
48 /**
49  * This version of SDNCAdapterRest allows for interim notifications to be sent for
50  * any non-final response received from SDNC.
51  */
52 class SDNCAdapterRestV2 extends SDNCAdapterRestV1 {
53     private static final Logger logger = LoggerFactory.getLogger( SDNCAdapterRestV2.class);
54
55
56         ExceptionUtil exceptionUtil = new ExceptionUtil()
57         JsonUtils jsonUtil = new JsonUtils()
58
59         /**
60          * Processes the incoming request.
61          */
62         public void preProcessRequest (DelegateExecution execution) {
63                 def method = getClass().getSimpleName() + '.preProcessRequest(' +
64                         'execution=' + execution.getId() +
65                         ')'
66                 logger.trace('Entered ' + method)
67
68                 def prefix="SDNCREST_"
69                 execution.setVariable("prefix", prefix)
70                 setSuccessIndicator(execution, false)
71
72                 try {
73                         // Determine the request type and log the request
74
75                         String request = validateRequest(execution, "mso-request-id")
76                         String requestType = jsonUtil.getJsonRootProperty(request)
77                         execution.setVariable(prefix + 'requestType', requestType)
78                         logger.debug(getProcessKey(execution) + ': ' + prefix + 'requestType = ' + requestType)
79                         logger.debug('SDNCAdapterRestV2, request: ' + request)
80
81                         // Determine the SDNCAdapter endpoint
82
83                         String sdncAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.sdnc.rest.endpoint",execution)
84
85                         if (sdncAdapterEndpoint == null || sdncAdapterEndpoint.isEmpty()) {
86                                 String msg = getProcessKey(execution) + ': mso:adapters:sdnc:rest:endpoint URN mapping is not defined'
87                                 logger.debug(msg)
88                                 logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
89                                                 ErrorCode.UnknownError.getValue());
90                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
91                         }
92
93                         while (sdncAdapterEndpoint.endsWith('/')) {
94                                 sdncAdapterEndpoint = sdncAdapterEndpoint.substring(0, sdncAdapterEndpoint.length()-1)
95                         }
96
97                         String sdncAdapterMethod = null
98                         String sdncAdapterUrl = null
99                         String sdncAdapterRequest = request
100
101                         if ('SDNCServiceRequest'.equals(requestType)) {
102                                 // Get the sdncRequestId from the request
103
104                                 String sdncRequestId = jsonUtil.getJsonValue(request, requestType + ".sdncRequestId")
105
106                                 if (sdncRequestId == null || sdncRequestId.isEmpty()) {
107                                         String msg = getProcessKey(execution) + ': no sdncRequestId in ' + requestType
108                                         logger.debug(msg)
109                                         logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
110                                                         ErrorCode.UnknownError.getValue());
111                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
112                                 }
113
114                                 execution.setVariable('SDNCAResponse_CORRELATOR', sdncRequestId)
115                                 logger.debug(getProcessKey(execution) + ': SDNCAResponse_CORRELATOR = ' + sdncRequestId)
116
117                                 // Get the bpNotificationUrl from the request (just to make sure it's there)
118
119                                 String bpNotificationUrl = jsonUtil.getJsonValue(request, requestType + ".bpNotificationUrl")
120
121                                 if (bpNotificationUrl == null || bpNotificationUrl.isEmpty()) {
122                                         String msg = getProcessKey(execution) + ': no bpNotificationUrl in ' + requestType
123                                         logger.debug(msg)
124                                         logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
125                                                         ErrorCode.UnknownError.getValue());
126                                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
127                                 }
128
129                                 sdncAdapterMethod = 'POST'
130                                 sdncAdapterUrl = sdncAdapterEndpoint
131
132                         } else {
133                                 String msg = getProcessKey(execution) + ': Unsupported request type: ' + requestType
134                                 logger.debug(msg)
135                                 logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
136                                                 ErrorCode.UnknownError.getValue());
137                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
138                         }
139
140                         execution.setVariable(prefix + 'sdncAdapterMethod', sdncAdapterMethod)
141                         logger.debug(getProcessKey(execution) + ': ' + prefix + 'sdncAdapterMethod = ' + sdncAdapterMethod)
142                         execution.setVariable(prefix + 'sdncAdapterUrl', sdncAdapterUrl)
143                         logger.debug(getProcessKey(execution) + ': ' + prefix + 'sdncAdapterUrl = ' + sdncAdapterUrl)
144                         execution.setVariable(prefix + 'sdncAdapterRequest', sdncAdapterRequest)
145                         logger.debug(getProcessKey(execution) + ': ' + prefix + 'sdncAdapterRequest = \n' + sdncAdapterRequest)
146
147                         // Get the Basic Auth credentials for the SDNCAdapter (yes... we ARE using the PO adapters credentials)
148
149                         String basicAuthValue = UrnPropertiesReader.getVariable("mso.adapters.po.auth",execution)
150
151                         if (basicAuthValue == null || basicAuthValue.isEmpty()) {
152                                 logger.debug(getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined")
153                                 logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
154                                                 getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined", "BPMN",
155                                                 ErrorCode.UnknownError.getValue());
156                         } else {
157                                 try {
158                                         def encodedString = utils.getBasicAuth(basicAuthValue, UrnPropertiesReader.getVariable("mso.msoKey", execution))
159                                         execution.setVariable(prefix + 'basicAuthHeaderValue', encodedString)
160                                 } catch (IOException ex) {
161                                         logger.debug(getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter")
162                                         logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
163                                                         getProcessKey(execution) + ": Unable to encode BasicAuth credentials for SDNCAdapter",
164                                                         "BPMN", ErrorCode.UnknownError.getValue());
165                                 }
166                         }
167
168                         // Set the timeout value, e.g. PT5M. It may be specified in the request as the
169                         // bpTimeout value.  If it's not in the request, use the URN mapping value.
170
171                         String timeout = jsonUtil.getJsonValue(request, requestType + ".bpTimeout")
172
173                         // in addition to null/empty, also need to verify that the timer value is a valid duration "P[n]T[n]H|M|S"
174                         String timerRegex = "PT[0-9]+[HMS]";
175                         if (timeout == null || timeout.isEmpty() || !timeout.matches(timerRegex)) {
176                                 logger.debug(getProcessKey(execution) + ': preProcessRequest(): null/empty/invalid bpTimeout value. Using "mso.adapters.sdnc.timeout"')
177                                 timeout = UrnPropertiesReader.getVariable("mso.adapters.sdnc.timeout", execution)
178                         }
179
180                         // the timeout could still be null at this point if the config parm is missing/undefined
181                         // forced to log (so OPs can fix the config) and temporarily use a hard coded value of 10 seconds
182                         if (timeout == null) {
183                                 logger.warn("Service Name: {} Error: {}", 'preProcessRequest()', 'property "mso.adapters.sdnc.timeout" is missing/undefined. Using "PT10S"')
184                                 timeout = "PT10S"
185                         }
186
187                         execution.setVariable(prefix + 'timeout', timeout)
188                         logger.debug(getProcessKey(execution) + ': ' + prefix + 'timeout = ' + timeout)
189                 } catch (BpmnError e) {
190                         throw e
191                 } catch (Exception e) {
192                         String msg = 'Caught exception in ' + method + ": " + e
193                         logger.debug(msg)
194                         logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN",
195                                         ErrorCode.UnknownError.getValue());
196                         exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg)
197                 }
198         }
199
200         /**
201          * Processes a callback. Check for possible interim notification.
202          */
203         public void processCallback(DelegateExecution execution){
204                 def method = getClass().getSimpleName() + '.processCallback(' +
205                         'execution=' + execution.getId() +
206                         ')'
207                 logger.trace('Entered ' + method)
208
209                 String prefix = execution.getVariable('prefix')
210                 String callback = execution.getVariable('SDNCAResponse_MESSAGE')
211                 logger.debug("Incoming SDNC Rest Callback is: " + callback)
212
213                 try {
214                         logger.debug(getProcessKey(execution) + ": received callback:\n" + callback)
215
216                         int callbackNumber = 1
217                         while (execution.getVariable(prefix + 'callback' + callbackNumber) != null) {
218                                 ++callbackNumber
219                         }
220
221                         execution.setVariable(prefix + 'callback' + callbackNumber, callback)
222                         execution.removeVariable('SDNCAResponse_MESSAGE')
223
224                         String responseType = jsonUtil.getJsonRootProperty(callback)
225
226                         // Get the ackFinalIndicator and make sure it's either Y or N.  Default to Y.
227                         String ackFinalIndicator = jsonUtil.getJsonValue(callback, responseType + ".ackFinalIndicator")
228
229                         if (!'N'.equals(ackFinalIndicator)) {
230                                 ackFinalIndicator = 'Y'
231                         }
232
233                         execution.setVariable(prefix + "ackFinalIndicator", ackFinalIndicator)
234
235                         if (responseType.endsWith('Error')) {
236                                 sdncAdapterBuildWorkflowException(execution, callback)
237                         }
238
239                         // Check for possible interim notification
240                         execution.setVariable(prefix + "interimNotification", null)
241                         execution.setVariable(prefix + "doInterimNotification", false)
242                         if ('N'.equals(ackFinalIndicator)) {
243                                 def interimNotification = execution.getVariable(prefix + "InterimNotification" + callbackNumber)
244                                 if (interimNotification != null) {
245                                         execution.setVariable(prefix + "interimNotification", interimNotification)
246                                         execution.setVariable(prefix + "doInterimNotification", true)
247                                 }
248                         }
249
250                 } catch (Exception e) {
251                         callback = callback == null || String.valueOf(callback).isEmpty() ? "NONE" : callback
252                         String msg = "Received error from SDNCAdapter: " + callback
253                         logger.debug(getProcessKey(execution) + ': ' + msg)
254                         exceptionUtil.buildWorkflowException(execution, 5300, msg)
255                 }
256         }
257
258         /**
259          * Prepare to send an interim notification by extracting the variable/value definitions
260          * in the interimNotification JSON object and placing them in the execution.  These
261          * variable/value definitions will be passed to the notification service.
262          */
263         public void prepareInterimNotification(DelegateExecution execution) {
264                 def method = getClass().getSimpleName() + '.prepareInterimNotification(' +
265                         'execution=' + execution.getId() +
266                         ')'
267                 logger.trace('Entered ' + method)
268
269                 String prefix = execution.getVariable('prefix')
270                 logger.debug("Preparing Interim Notification")
271
272                 try {
273                         def interimNotification = execution.getVariable(prefix + "interimNotification")
274                         logger.debug("Preparing Interim Notification:\n" + JsonUtils.prettyJson(interimNotification))
275
276                         for (int i = 0; ; i++) {
277                                 def variable = JsonUtils.getJsonParamValue(interimNotification, 'variableList', 'variable', i)
278
279                                 if (variable == null) {
280                                         break
281                                 }
282
283                                 def String variableName = JsonUtils.getJsonValue(variable, "name")
284                                 if ((variableName != null) && !variableName.isEmpty()) {
285                                         def variableValue = JsonUtils.getJsonValue(variable, "value")
286                                         execution.setVariable(variableName, variableValue)
287                                         logger.debug("Setting "+ variableName + "=" + variableValue)
288                                 }
289                         }
290
291                 } catch (Exception e) {
292                         String msg = "Error preparing interim notification"
293                         logger.debug(getProcessKey(execution) + ': ' + msg)
294                         exceptionUtil.buildWorkflowException(execution, 5300, msg)
295                 }
296         }
297 }