Initial OpenECOMP MSO commit
[so.git] / bpmn / MSOGammaBPMN / src / main / groovy / com / att / bpm / scripts / GenericGetService.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 static org.apache.commons.lang3.StringUtils.*;
24
25 import org.camunda.bpm.engine.delegate.BpmnError
26 import org.camunda.bpm.engine.runtime.Execution;
27 import org.apache.commons.codec.binary.Base64
28 import org.apache.commons.lang3.*
29
30 import org.openecomp.mso.bpmn.core.WorkflowException
31 import org.openecomp.mso.rest.APIResponse
32 import org.openecomp.mso.rest.RESTClient
33 import org.openecomp.mso.rest.RESTConfig
34
35 import org.springframework.web.util.UriUtils
36
37
38 /**
39  * This class supports the GenericGetService Sub Flow.
40  * This Generic sub flow can be used by any flow for accomplishing
41  * the goal of getting a Service-Instance or Service-Subscription (from AAI).
42  * The calling flow must set the GENGS_type variable as "service-instance"
43  * or "service-subscription".
44  *
45  * When using to Get a Service-Instance:
46  * If the global-customer-id and service-type are not provided
47  * this flow executes a query to get the service- Url using the
48  * Service  Id or Name (whichever is provided).
49  *
50  * When using to Get a Service-Subscription:
51  * The global-customer-id and service-type must be
52  * provided.
53  *
54  * Upon successful completion of this sub flow the
55  * GENGS_SuccessIndicator will be true and the query response payload
56  * will be set to GENGS_service.  An MSOWorkflowException will
57  * be thrown upon unsuccessful completion or if an error occurs
58  * at any time during this sub flow. Please map variables
59  * to the corresponding variable names below.
60  *
61  * Note - If this sub flow receives a Not Found (404) response
62  * from AAI at any time this will be considered an acceptable
63  * successful response however the GENGS_FoundIndicator
64  * will be set to false. This variable will allow the calling flow
65  * to distinguish between the two Success scenarios,
66  * "Success where service- is found" and
67  * "Success where service- is NOT found".
68  *
69  *
70  * Incoming Variables (Service-Instance):
71  * @param - GENGS_serviceInstanceId or @param - GENGS_serviceInstanceName
72  * @param - GENGS_type
73  * @param (Optional) - GENGS_serviceType
74  * @param (Optional) - GENGS_globalCustomerId
75  *
76  * Incoming Variables (Service-Subscription):
77  * @param - GENGS_type
78  * @param - GENGS_serviceType
79  * @param - GENGS_globalCustomerId
80  *
81  *
82  * Outgoing Variables:
83  * @param - GENGS_service
84  * @param - GENGS_SuccessIndicator
85  * @param - GENGS_FoundIndicator
86  * @param - WorkflowException
87  */
88 class GenericGetService extends AbstractServiceTaskProcessor{
89
90         String Prefix = "GENGS_"
91         ExceptionUtil exceptionUtil = new ExceptionUtil()
92
93         /**
94          * This method validates the incoming variables and
95          * determines the subsequent event based on which
96          * variables the calling flow provided.
97          *
98          * @param - execution
99          */
100         public void preProcessRequest(Execution execution) {
101                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
102                 execution.setVariable("prefix",Prefix)
103                 utils.log("DEBUG", " *** STARTED GenericGetService PreProcessRequest Process*** ", isDebugEnabled)
104
105                 execution.setVariable("GENGS_obtainServiceInstanceUrl", false)
106                 execution.setVariable("GENGS_obtainServiceInstanceUrlByName", false)
107                 execution.setVariable("GENGS_SuccessIndicator", false)
108                 execution.setVariable("GENGS_FoundIndicator", false)
109                 execution.setVariable("GENGS_siResourceLink", null)
110
111                 try{
112                         // Get Variables
113                         String serviceInstanceId = execution.getVariable("GENGS_serviceInstanceId")
114                         String serviceInstanceName = execution.getVariable("GENGS_serviceInstanceName")
115                         String serviceType = execution.getVariable("GENGS_serviceType")
116                         String globalCustomerId = execution.getVariable("GENGS_globalCustomerId")
117                         String type = execution.getVariable("GENGS_type")
118
119                         if(type != null){
120                                 utils.log("DEBUG", "Incoming GENGS_type is: " + type, isDebugEnabled)
121                                 if(type.equalsIgnoreCase("service-instance")){
122                                         if(isBlank(serviceInstanceId) && isBlank(serviceInstanceName)){
123                                                 utils.log("DEBUG", "Incoming serviceInstanceId and serviceInstanceName are null. ServiceInstanceId or ServiceInstanceName is required to Get a service-instance.", isDebugEnabled)
124                                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming serviceInstanceId and serviceInstanceName are null. ServiceInstanceId or ServiceInstanceName is required to Get a service-instance.")
125                                         }else{
126                                                 utils.log("DEBUG", "Incoming Service Instance Id is: " + serviceInstanceId, isDebugEnabled)
127                                                 utils.log("DEBUG", "Incoming Service Instance Name is: " + serviceInstanceName, isDebugEnabled)
128                                                 if(isBlank(globalCustomerId) || isBlank(serviceType)){
129                                                         execution.setVariable("GENGS_obtainServiceInstanceUrl", true)
130                                                         if(isBlank(serviceInstanceId)){
131                                                                 execution.setVariable("GENGS_obtainServiceInstanceUrlByName", true)
132                                                         }
133                                                 }else{
134                                                         utils.log("DEBUG", "Incoming Global Customer Id is: " + globalCustomerId, isDebugEnabled)
135                                                         utils.log("DEBUG", "Incoming Service Type is: " + serviceType, isDebugEnabled)
136                                                 }
137                                         }
138                                 }else if(type.equalsIgnoreCase("service-subscription")){
139                                         if(isBlank(serviceType) || isBlank(globalCustomerId)){
140                                                 utils.log("DEBUG", "Incoming ServiceType or GlobalCustomerId is null. These variables are required to Get a service-subscription.", isDebugEnabled)
141                                                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming ServiceType or GlobalCustomerId is null. These variables are required to Get a service-subscription.")
142                                         }else{
143                                                 utils.log("DEBUG", "Incoming Service Type is: " + serviceType, isDebugEnabled)
144                                                 utils.log("DEBUG", "Incoming Global Customer Id is: " + globalCustomerId, isDebugEnabled)
145                                         }
146                                 }else{
147                                         exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Type is Invalid. Please Specify Type as service-instance or service-subscription")
148                                 }
149                         }else{
150                                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Incoming GENGS_type is null. Variable is Required.")
151                         }
152
153                 }catch(BpmnError b){
154                         utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled)
155                         throw b
156                 }catch(Exception e){
157                         utils.log("DEBUG", "Internal Error encountered within GenericGetService PreProcessRequest method!" + e, isDebugEnabled)
158                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in GenericGetService PreProcessRequest")
159
160                 }
161                 utils.log("DEBUG", "*** COMPLETED GenericGetService PreProcessRequest Process ***", isDebugEnabled)
162         }
163
164         /**
165          * This method obtains the Url to the provided service instance
166          * using the Service Instance Id.
167          *
168          * @param - execution
169          */
170         public void obtainServiceInstanceUrlById(Execution execution){
171                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
172                 execution.setVariable("prefix",Prefix)
173                 utils.log("DEBUG", " *** STARTED GenericGetService ObtainServiceInstanceUrlById Process*** ", isDebugEnabled)
174                 try {
175                         String serviceInstanceId = execution.getVariable("GENGS_serviceInstanceId")
176                         utils.log("DEBUG", " Querying Node for Service-Instance URL by using Service-Instance Id: " + serviceInstanceId, isDebugEnabled)
177
178                         AaiUtil aaiUriUtil = new AaiUtil(this)
179                         String aai_uri = aaiUriUtil.getSearchNodesQueryEndpoint(execution)
180                         String aai_endpoint = execution.getVariable("URN_aai_endpoint")
181                         String path = "${aai_uri}?search-node-type=service-instance&filter=service-instance-id:EQUALS:${serviceInstanceId}"
182
183                         //String url = "${aai_endpoint}${path}"  host name needs to be removed from property
184                         String url = "${path}"
185                         execution.setVariable("GENGS_obtainSIUrlPath", url)
186
187                         APIResponse response = aaiUriUtil.executeAAIGetCall(execution, url)
188                         int responseCode = response.getStatusCode()
189                         execution.setVariable("GENGS_obtainSIUrlResponseCode", responseCode)
190                         utils.log("DEBUG", "  DELETE Service Instance response code is: " + responseCode, isDebugEnabled)
191
192                         String aaiResponse = response.getResponseBodyAsString()
193                         aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse)
194                         execution.setVariable("GENGS_obtainSIUrlResponse", aaiResponse)
195
196                         //Process Response
197                         if(responseCode == 200){
198                                 utils.log("DEBUG", "  Query for Service Instance Url Received a Good Response Code", isDebugEnabled)
199                                 execution.setVariable("GENGS_SuccessIndicator", true)
200                                 if(utils.nodeExists(aaiResponse, "result-data")){
201                                         utils.log("DEBUG", "Query for Service Instance Url Response Does Contain Data" , isDebugEnabled)
202                                         execution.setVariable("GENGS_FoundIndicator", true)
203                                         String resourceLink = utils.getNodeText1(aaiResponse, "resource-link")
204                                         execution.setVariable("GENGS_siResourceLink", resourceLink)
205                                 }else{
206                                         utils.log("DEBUG", "Query for Service Instance Url Response Does NOT Contains Data" , isDebugEnabled)
207                                         execution.setVariable("WorkflowResponse", "  ") //for junits
208                                 }
209                         }else if(responseCode == 404){
210                                 utils.log("DEBUG", "  Query for Service Instance Received a Not Found (404) Response", isDebugEnabled)
211                                 execution.setVariable("GENGS_SuccessIndicator", true)
212                                 execution.setVariable("WorkflowResponse", "  ") //for junits
213                         }else{
214                                 utils.log("DEBUG", "Query for Service Instance Received a BAD REST Response: \n" + aaiResponse, isDebugEnabled)
215                                 exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode)
216                                 throw new BpmnError("MSOWorkflowException")
217                         }
218                 }catch(BpmnError b){
219                         utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled)
220                         throw b
221                 }catch(Exception e){
222                         utils.log("ERROR", " Error encountered within GenericGetService ObtainServiceInstanceUrlById method!" + e, isDebugEnabled)
223                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During ObtainServiceInstanceUrlById")
224                 }
225                 utils.log("DEBUG", " *** COMPLETED GenericGetService ObtainServiceInstanceUrlById Process*** ", isDebugEnabled)
226         }
227
228         /**
229          * This method obtains the Url to the provided service instance
230          * using the Service Instance Name.
231          *
232          * @param - execution
233          */
234         public void obtainServiceInstanceUrlByName(Execution execution){
235                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
236                 execution.setVariable("prefix",Prefix)
237                 utils.log("DEBUG", " *** STARTED GenericGetService ObtainServiceInstanceUrlByName Process*** ", isDebugEnabled)
238                 try {
239                         String serviceInstanceName = execution.getVariable("GENGS_serviceInstanceName")
240                         utils.log("DEBUG", " Querying Node for Service-Instance URL by using Service-Instance Name " + serviceInstanceName, isDebugEnabled)
241
242                         AaiUtil aaiUriUtil = new AaiUtil(this)
243                         String aai_uri = aaiUriUtil.getSearchNodesQueryEndpoint(execution)
244                         String aai_endpoint = execution.getVariable("URN_aai_endpoint")
245                         String path = "${aai_uri}?search-node-type=service-instance&filter=service-instance-name:EQUALS:${serviceInstanceName}"
246
247                         //String url = "${aai_endpoint}${path}"  host name needs to be removed from property
248                         String url = "${path}"
249                         execution.setVariable("GENGS_obtainSIUrlPath", url)
250
251                         APIResponse response = aaiUriUtil.executeAAIGetCall(execution, url)
252                         int responseCode = response.getStatusCode()
253                         execution.setVariable("GENGS_obtainSIUrlResponseCode", responseCode)
254                         utils.log("DEBUG", "  DELETE Service Instance response code is: " + responseCode, isDebugEnabled)
255
256                         String aaiResponse = response.getResponseBodyAsString()
257                         aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse)
258                         execution.setVariable("GENGS_obtainSIUrlResponse", aaiResponse)
259
260                         //Process Response
261                         if(responseCode == 200){
262                                 utils.log("DEBUG", "  Query for Service Instance Url Received a Good Response Code", isDebugEnabled)
263                                 execution.setVariable("GENGS_SuccessIndicator", true)
264                                 if(utils.nodeExists(aaiResponse, "result-data")){
265                                         utils.log("DEBUG", "Query for Service Instance Url Response Does Contain Data" , isDebugEnabled)
266                                         execution.setVariable("GENGS_FoundIndicator", true)
267                                         String resourceLink = utils.getNodeText1(aaiResponse, "resource-link")
268                                         execution.setVariable("GENGS_siResourceLink", resourceLink)
269                                 }else{
270                                         utils.log("DEBUG", "Query for Service Instance Url Response Does NOT Contains Data" , isDebugEnabled)
271                                         execution.setVariable("WorkflowResponse", "  ") //for junits
272                                 }
273                         }else if(responseCode == 404){
274                                 utils.log("DEBUG", "  Query for Service Instance Received a Not Found (404) Response", isDebugEnabled)
275                                 execution.setVariable("GENGS_SuccessIndicator", true)
276                                 execution.setVariable("WorkflowResponse", "  ") //for junits
277                         }else{
278                                 utils.log("DEBUG", "Query for Service Instance Received a BAD REST Response: \n" + aaiResponse, isDebugEnabled)
279                                 exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode)
280                                 throw new BpmnError("MSOWorkflowException")
281                         }
282                 }catch(BpmnError b){
283                         utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled)
284                         throw b
285                 }catch(Exception e){
286                         utils.log("ERROR", " Error encountered within GenericGetService ObtainServiceInstanceUrlByName method!" + e, isDebugEnabled)
287                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During ObtainServiceInstanceUrlByName")
288                 }
289                 utils.log("DEBUG", " *** COMPLETED GenericGetService ObtainServiceInstanceUrlByName Process*** ", isDebugEnabled)
290         }
291
292
293         /**
294          * This method executes a GET call to AAI to obtain the
295          * service-instance or service-subscription
296          *
297          * @param - execution
298          */
299         public void getServiceObject(Execution execution){
300                 def isDebugEnabled=execution.getVariable("isDebugLogEnabled")
301                 execution.setVariable("prefix",Prefix)
302                 utils.log("DEBUG", " *** STARTED GenericGetService GetServiceObject Process*** ", isDebugEnabled)
303                 try {
304                         String type = execution.getVariable("GENGS_type")
305                         AaiUtil aaiUriUtil = new AaiUtil(this)
306                         String aai_endpoint = execution.getVariable("URN_aai_endpoint")
307                         String serviceEndpoint = ""
308
309                         if(type.equalsIgnoreCase("service-instance")){
310                                 String siResourceLink = execution.getVariable("GENGS_siResourceLink")
311                                 if(isBlank(siResourceLink)){
312                                         String serviceInstanceId = execution.getVariable("GENGS_serviceInstanceId")
313                                         utils.log("DEBUG", " Incoming GENGS_serviceInstanceId is: " + serviceInstanceId, isDebugEnabled)
314                                         String serviceType = execution.getVariable("GENGS_serviceType")
315                                         utils.log("DEBUG", " Incoming GENGS_serviceType is: " + serviceType, isDebugEnabled)
316                                         String globalCustomerId = execution.getVariable("GENGS_globalCustomerId")
317                                         utils.log("DEBUG", "Incoming Global Customer Id is: " + globalCustomerId, isDebugEnabled)
318
319                                         String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution)
320                                         logDebug('AAI URI is: ' + aai_uri, isDebugEnabled)
321                                         serviceEndpoint = "${aai_uri}/" + UriUtils.encode(globalCustomerId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8") + "/service-instances/service-instance/" + UriUtils.encode(serviceInstanceId,"UTF-8")
322                                 }else{
323                                         utils.log("DEBUG", "Incoming Service Instance Resource Link is: " + siResourceLink, isDebugEnabled)
324                                         String[] split = siResourceLink.split("/aai/")
325                                         serviceEndpoint = "/aai/" + split[1]
326                                 }
327                         }else if(type.equalsIgnoreCase("service-subscription")){
328                                 String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution)
329                                 String globalCustomerId = execution.getVariable("GENGS_globalCustomerId")
330                                 String serviceType = execution.getVariable("GENGS_serviceType")
331                                 serviceEndpoint = "${aai_uri}/" + UriUtils.encode(globalCustomerId,"UTF-8") + "/service-subscriptions/service-subscription/" + UriUtils.encode(serviceType,"UTF-8")
332                         }
333
334                         String serviceUrl = "${aai_endpoint}" + serviceEndpoint
335
336                         execution.setVariable("GENGS_getServiceUrl", serviceUrl)
337                         utils.log("DEBUG", "GET Service AAI Path is: \n" + serviceUrl, isDebugEnabled)
338
339                         APIResponse response = aaiUriUtil.executeAAIGetCall(execution, serviceUrl)
340                         int responseCode = response.getStatusCode()
341                         execution.setVariable("GENGS_getServiceResponseCode", responseCode)
342                         utils.log("DEBUG", "  GET Service response code is: " + responseCode, isDebugEnabled)
343
344                         String aaiResponse = response.getResponseBodyAsString()
345                         aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse)
346                         execution.setVariable("GENGS_getServiceResponse", aaiResponse)
347
348                         //Process Response
349                         if(responseCode == 200 || responseCode == 202){
350                                 utils.log("DEBUG", "GET Service Received a Good Response Code", isDebugEnabled)
351                                 if(utils.nodeExists(aaiResponse, "service-instance") || utils.nodeExists(aaiResponse, "service-subscription")){
352                                         utils.log("DEBUG", "GET Service Response Contains a service-instance" , isDebugEnabled)
353                                         execution.setVariable("GENGS_FoundIndicator", true)
354                                         execution.setVariable("GENGS_service", aaiResponse)
355                                         execution.setVariable("WorkflowResponse", aaiResponse)
356
357                                 }else{
358                                         utils.log("DEBUG", "GET Service Response Does NOT Contain Data" , isDebugEnabled)
359                                 }
360                         }else if(responseCode == 404){
361                                 utils.log("DEBUG", "GET Service Received a Not Found (404) Response", isDebugEnabled)
362                                 execution.setVariable("WorkflowResponse", "  ") //for junits
363                         }
364                         else{
365                                 utils.log("DEBUG", "  GET Service Received a Bad Response: \n" + aaiResponse, isDebugEnabled)
366                                 exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode)
367                                 throw new BpmnError("MSOWorkflowException")
368                         }
369                 }catch(BpmnError b){
370                         utils.log("DEBUG", "Rethrowing MSOWorkflowException", isDebugEnabled)
371                         throw b
372                 }catch(Exception e){
373                         utils.log("DEBUG", " Error encountered within GenericGetService GetServiceObject method!" + e, isDebugEnabled)
374                         exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured During GenericGetService")
375                 }
376                 utils.log("DEBUG", " *** COMPLETED GenericGetService GetServiceObject Process*** ", isDebugEnabled)
377         }
378
379 }