Remove unnecessary use of Calendar.getInstance()
[so.git] / bpmn / MSOGammaBPMN / src / main / groovy / com / att / bpm / scripts / CommonExceptionUtil.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.camunda.bpm.engine.runtime.Execution
24 import org.apache.commons.lang3.*
25
26 class CommonExceptionUtil {
27         
28         
29         
30         public static enum Error {
31                 SVC_GENERAL_SERVICE_ERROR("SVC0001","Internal Error"),
32                 SVC_BAD_PARAMETER("SVC0002", "Invalid input value for message part %1"),
33                 SVC_NO_SERVER_RESOURCES("SVC1000", "No server resources available to process the request"),
34                 SVC_DETAILED_SERVICE_ERROR("SVC2000", "The following service error occurred: %1. Error code is %2."),
35                 POL_GENERAL_POLICY_ERROR("POL0001", "A policy error occurred."),
36                 POL_USER_NOT_PROVISIONED("POL1009", "User has not been provisioned for service"),
37                 POL_USER_SUSPENDED("POL1010", "User has been suspended from service"),
38                 POL_DETAILED_POLICY_ERROR("POL2000", "The following policy error occurred: %1. Error code is %2."),
39                 POL_MSG_SIZE_EXCEEDS_LIMIT("POL9003", "Message content size exceeds the allowable limit")
40         
41
42                 private final String msgId
43                 private final String msgTxt
44
45                 private Error(String msgId, String msgTxt) {
46                         this.msgId = msgId
47                         this.msgTxt = msgTxt
48                 }
49
50                 public String getMsgId() {
51                      return msgId
52                   }
53
54                 public String getMsgTxt() {
55                         return msgTxt
56                 }
57
58         }
59
60
61         
62         
63         String mapAdapterExecptionToCommonException(String response, Execution execution)
64         {
65                 def utils=new MsoUtils()
66                 def method = getClass().getSimpleName() + '.mapAdapterExecptionToCommonException(' +
67                         'execution=' + execution.getId() +
68                         ')'
69
70                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
71                 utils.log("DEBUG",'Entered ' + method, isDebugLogEnabled)
72
73                 
74                 def errorCode
75
76                 
77                 try {
78                           errorCode = MapCategoryToErrorCode(utils.getNodeText(response, "category")) 
79                           execution.setVariable(prefix+"err",errorCode)
80                           String message = buildException(response, execution)
81                           utils.log("DEBUG","=========== End MapAdapterExecptionToWorkflowException ===========",isDebugLogEnabled)
82                           return message
83                 }catch (Exception ex) {
84                         //Ignore the exception - cases include non xml payload
85                         utils.log("DEBUG","error mapping error, ignoring: " + ex,isDebugLogEnabled)
86                         utils.log("DEBUG","=========== End MapAdapterExecptionToWorkflowException ===========",isDebugLogEnabled)
87                         return buildException(response, execution)
88                 } 
89         }
90         
91         /**
92          * @param response
93          * @param execution
94          * @return mapped exception
95          */
96         String mapAOTSExecptionToCommonException(String response, Execution execution)
97         {
98                 def utils=new MsoUtils()
99
100                 def prefix=execution.getVariable("prefix")
101                 def method = getClass().getSimpleName() + '.mapAOTSExecptionToCommonException(' +
102                         'execution=' + execution.getId() +
103                         ')'
104
105                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
106                 utils.log("DEBUG",'Entered ' + method, isDebugLogEnabled)
107                 
108                 
109                 try {
110                           def errorCode = utils.getNodeText(response,"code")
111                           def descr = utils.getNodeText(response, "description")
112                           def mappedErr = mapErrorCodetoError(errorCode, descr)
113                           if(mappedErr == Error.SVC_DETAILED_SERVICE_ERROR || mappedError == Error.POL_DETAILED_POLICY_ERROR){
114                                   ArrayList myVars = new ArrayList()
115                                   myVars.add(descr)
116                                   myVars.add(errorCode)
117                                   execution.setVariable(prefix+"errVariables", myVars)
118                           }
119                           execution.setVariable(prefix+"err",mappedErr)
120                           def message = buildException("Received error from AOTS: " + descr, execution)
121                           utils.log("DEBUG","=========== End MapAOTSExecptionToCommonException ===========",isDebugLogEnabled)
122                           return message
123                 }catch (Exception ex) {
124                         //Ignore the exception - cases include non xml payload
125                         utils.log("DEBUG","error mapping error, ignoring: " + ex,isDebugLogEnabled)
126                         utils.log("DEBUG","=========== End MapAOTSExecptionToCommonException ===========",isDebugLogEnabled)
127                         return buildException(response, execution)
128                 }
129         }
130         
131         String mapSDNCAdapterExceptionToErrorResponse(String sdncAdapterCallbackRequest, Execution execution) {
132                 def utils=new MsoUtils()
133                 def prefix=execution.getVariable("prefix")
134                 def method = getClass().getSimpleName() + '.mapSDNCAdapterExceptionToErrorResponse(' +
135                         'execution=' + execution.getId() +
136                         ')'
137
138                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
139                 utils.log("DEBUG",'Entered ' + method, isDebugLogEnabled)
140                 
141                 def sdncResponseCode
142                 String responseCode = execution.getVariable(prefix+"ResponseCode")
143                 utils.log("DEBUG",'responseCode to map: ' + responseCode, isDebugLogEnabled)
144                 def errorMessage
145                 
146                 try {
147                         
148                         if(utils.nodeExists(sdncAdapterCallbackRequest, "RequestData")) {
149                                 def reqDataXml = StringEscapeUtils.unescapeXml(utils.getNodeXml(sdncAdapterCallbackRequest, "RequestData"))
150                                 errorMessage = utils.getNodeText(reqDataXml, "response-message")
151                                 sdncResponseCode = utils.getNodeText(reqDataXml, "response-code")
152                         }else{
153                                 errorMessage = utils.getNodeText(sdncAdapterCallbackRequest, "ResponseMessage")
154                                 sdncResponseCode = responseCode
155                     }
156                         def mappedErr = mapErrorCodetoError(responseCode, errorMessage)
157                         errorMessage = errorMessage.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
158                         def modifiedErrorMessage = "Received error from SDN-C: " + errorMessage
159                         if(mappedErr == Error.SVC_DETAILED_SERVICE_ERROR || mappedErr == Error.POL_DETAILED_POLICY_ERROR){
160                                 ArrayList myVars = new ArrayList()
161                                 myVars.add(errorMessage)
162                                 myVars.add(sdncResponseCode)
163                                 execution.setVariable(prefix+"errVariables", myVars)
164                         }
165                         execution.setVariable(prefix+"err",mappedErr)
166                         def message = buildException(modifiedErrorMessage, execution)
167
168                         
169                         utils.log("DEBUG","=========== End MapSDNCAdapterException ===========",isDebugLogEnabled)
170                     return message
171                 }catch (Exception ex) {
172                         //Ignore the exception - cases include non xml payload
173                         utils.log("DEBUG","error mapping sdnc error, ignoring: " + ex,isDebugLogEnabled)
174                         utils.log("DEBUG","=========== End MapSDNCAdapterException ===========",isDebugLogEnabled)
175                         return null
176                 } 
177                 
178         }
179         
180         /**
181          * @param response message from called component (ex: AAI)
182          * @param execution
183          * @return an error response conforming to the common 
184          */
185         String mapAAIExceptionTCommonException(String response, Execution execution)
186         {
187                 def utils=new MsoUtils()
188                 def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled")
189                 def prefix=execution.getVariable("prefix")
190                 def method = getClass().getSimpleName() + '.mapAAIExceptionTCommonException(' +
191                         'execution=' + execution.getId() +
192                         ')'
193
194                 utils.log("DEBUG",'Entered ' + method, isDebugLogEnabled)
195                 def variables
196                 def message
197                 String errorCode = 'SVC0001'
198                 utils.log("DEBUG","response: " + response, isDebugLogEnabled)
199                 //they use the same format we do, pass their error along
200                 //TODO add Received error from A&AI at beg of text
201                 try {
202                          message = utils.getNodeXml(response, "requestError")
203                          message = utils.removeXmlNamespaces(message)
204                 } catch (Exception ex) {
205                         //Ignore the exception - cases include non xml payload
206                                 message = buildException("Received error from A&AI, unable to parse",execution)
207                         utils.log("DEBUG","error mapping error, ignoring: " + ex,isDebugLogEnabled)
208                 }
209                 
210                 if(message != null) { 
211                          execution.setVariable(prefix+"ErrorResponse",message)
212                          utils.log("ERROR","Fault:"+ execution.getVariable(prefix+"ErrorResponse"))
213                          return message
214                 } else {
215                         
216                                 return null
217                         
218                 }
219         }
220         
221         /**
222          * @param execution
223          * @return an error response conforming to the common API with default text msg
224          */
225         String buildException(execution){
226                 return buildException(null, execution)
227         }
228         
229         /**
230          * @param response message from called component (ex: AAI)
231          * @param execution
232          * @return an error response conforming to the common
233          */
234         String buildException(response, execution){
235                 def utils=new MsoUtils()
236                 def method = getClass().getSimpleName() + '.buildException(' +
237                         'execution=' + execution.getId() +
238                         ')'
239
240                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
241                 utils.log("DEBUG",'Entered ' + method, isDebugLogEnabled)
242                 def prefix=execution.getVariable("prefix")
243                 def responseCode = String.valueOf(execution.getVariable(prefix+"ResponseCode"))
244                 def variables
245                 utils.log("DEBUG","response: " + response, isDebugLogEnabled)
246                 
247                         try {
248                                 utils.log("DEBUG","formatting error message" ,isDebugLogEnabled)
249                                 def msgVars = execution.getVariable(prefix+"errVariables")
250                                 def myErr = execution.getVariable(prefix+"err")
251                                 def messageTxt = execution.getVariable(prefix+"errTxt")
252                                 def messageId = null
253                                 
254                                 if(myErr == null){
255                                         utils.log("DEBUG","mapping response code: " + responseCode, isDebugLogEnabled)
256                                         myErr = mapErrorCodetoError(responseCode, response)
257                                         if(myErr == null){
258                                                 //not a service or policy error, just return error code
259                                                 return ""
260                                         }
261                                 }
262                                 messageId = myErr.getMsgId()
263                                 
264                                 if(messageTxt == null){
265                                         if(myErr!=null){
266                                                 messageTxt = myErr.getMsgTxt()
267                                         }else{
268                                                 messageTxt = response
269                                         }
270                                 }
271                                 
272                                 if(msgVars==null && (myErr == Error.SVC_DETAILED_SERVICE_ERROR || myErr == Error.POL_DETAILED_POLICY_ERROR)){
273                                         msgVars = new ArrayList()
274                                         msgVars.add(response)
275                                         msgVars.add(responseCode)
276                                 }
277                                 
278                                 def msgVarsXML=""
279                                 StringBuffer msgVarsBuff = new StringBuffer()
280                                 if(msgVars!=null){
281                                         for(String msgVar : msgVars){
282                                                 msgVarsBuff.append(
283                                                         """
284                         <tns:variables>${msgVar}</tns:variables>""")
285                                         }
286                                         
287                                 }
288                                 def message = ""
289                                 if(messageId.startsWith("SVC")){
290                                         message = """<tns:requestError xmlns:tns="http://ecomp.att.com/mso/request/types/v1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://ecomp.att.com/mso/request/types/v1 MsoServiceInstanceTypesV1.xsd">
291         <tns:serviceException>
292                 <tns:messageId>${messageId}</tns:messageId>
293                 <tns:text>${messageTxt}</tns:text>${msgVarsBuff}
294         </tns:serviceException>
295 </tns:requestError>""" 
296                                 }else{
297                                         message ="""<tns:requestError xmlns:tns="http://ecomp.att.com/mso/request/types/v1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://ecomp.att.com/mso/request/types/v1 MsoServiceInstanceTypesV1.xsd">
298         <tns:policyException>
299                 <tns:messageId>${messageId}</tns:messageId>
300                 <tns:text>${messageTxt}</tns:text>${msgVarsBuff}
301         </tns:policyException>
302 </tns:requestError>""" 
303                                 }
304                                  utils.log("DEBUG", "message " + message, isDebugLogEnabled)
305                                  execution.setVariable(prefix+"ErrorResponse",message)
306                                  execution.setVariable(prefix+"err", myErr)
307                                  execution.setVariable(prefix+"errTxt", messageTxt)
308                                  execution.setVariable(prefix+"errVariables", msgVars)
309                                  utils.log("ERROR","Fault:"+ execution.getVariable(prefix+"ErrorResponse"))
310                                  return message
311                         }catch(Exception ex) {
312                                 utils.log("DEBUG","error mapping error, return null: " + ex,isDebugLogEnabled)
313                                 return null
314                         }
315
316         }
317         
318         String parseError(Execution execution){
319                 def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
320                 def utils=new MsoUtils()
321                 def prefix=execution.getVariable("prefix")
322                 def text = execution.getVariable(prefix+"errTxt")
323                 def msgVars = execution.getVariable(prefix+"errVariables")
324                 utils.log("DEBUG",'parsing message: ' + text, isDebugLogEnabled)
325                 if(text == null){
326                         return 'failed'
327                 }
328                 if(msgVars!=null && !msgVars.isEmpty()){
329                         for(int i=0; i<msgVars.size(); i++){
330                                 text = text.replaceFirst("%"+(i+1), msgVars[i])
331                         }
332                 }
333                 utils.log("DEBUG",'parsed message is: ' + text, isDebugLogEnabled)
334                 return text
335         }
336         
337         
338
339         Error mapErrorCodetoError(responseCode, descr)
340         {
341                 
342                 if(responseCode==null || responseCode=='0' || responseCode=='500' || responseCode =='408'){
343                         return Error.SVC_NO_SERVER_RESOURCES
344                 }else if(responseCode == '401' || responseCode == '405' || responseCode == '409' || responseCode == '503'){
345                         return null
346                 }else if(responseCode == '400'){
347                         if(descr==null){
348                                 return Error.SVC_GENERAL_SERVICE_ERROR
349                         }else{
350                                 return Error.SVC_DETAILED_SERVICE_ERROR
351                         }
352                 }else if(responseCode == '401'){
353                         if(descr==null){
354                                 return Error.POL_GENERAL_POLICY_ERROR
355                         }else{
356                                 return Error.POL_DETAILED_POLICY_ERROR
357                         }
358                 }else{
359                         return Error.SVC_NO_SERVER_RESOURCES
360                 }
361         }
362         
363         String mapCategoryToErrorCode(String errorCategory)
364         {
365                 if(errorCategory.equals('OPENSTACK'))
366                         return Error.SVC_NO_SERVER_RESOURCES
367                 else if (errorCategory.equals('IO'))
368                         return Error.SVC_NO_SERVER_RESOURCES
369                 else if (errorCategory.equals('INTERNAL'))
370                         return Error.SVC_NO_SERVER_RESOURCES
371                 else if (errorCategory.equals('USERDATA'))
372                         return Error.SVC_GENERAL_SERVICE_ERROR
373                 else
374                         return Error.SVC_GENERAL_SERVICE_ERROR
375         }
376         
377         
378         
379
380         
381         
382 }