Save sppartner to AAI and call ExternalAPI bug fix
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / onap / so / bpmn / common / scripts / ExternalAPIUtil.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2018 Huawei Technologies Co., Ltd. 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 org.onap.so.bpmn.common.scripts
22 import org.camunda.bpm.engine.delegate.BpmnError
23 import org.camunda.bpm.engine.delegate.DelegateExecution
24 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor;
25 import org.onap.so.rest.APIResponse
26 import org.onap.so.rest.RESTClient
27 import org.onap.so.rest.RESTConfig
28 import org.apache.commons.lang3.StringEscapeUtils
29 import java.util.regex.Matcher
30 import java.util.regex.Pattern
31
32 class ExternalAPIUtil {
33         
34         String Prefix="EXTAPI_"
35
36         public MsoUtils utils = new MsoUtils()
37         
38         ExceptionUtil exceptionUtil = new ExceptionUtil()
39
40         private AbstractServiceTaskProcessor taskProcessor
41         
42         public static final String PostServiceOrderRequestsTemplate =
43         "{\n" +
44         "\t\"externalId\": <externalId>,\n" +
45         "\t\"category\": <category>,\n" +
46         "\t\"description\": <description>,\n" +
47         "\t\"requestedStartDate\": <requestedStartDate>,\n" +
48         "\t\"requestedCompletionDate\": <requestedCompletionDate>,\n" +
49         "\t\"priority\": <priority>,\n" +
50         "\t\"@type\": null,\n" +
51         "\t\"@baseType\": null,\n" +
52         "\t\"@schemaLocation\": null,\n" +
53         "\t\"relatedParty\": [{\n" +
54         "\t\t\"id\": <subscriberId>, \n" +
55         "\t\t\"href\": null, \n" +
56         "\t\t\"role\": <customerRole>, \n" +
57         "\t\t\"name\": <subscriberName>, \n" +
58         "\t\t\"@referredType\": <referredType> \n" +
59         "}], \n" +
60         "\t\"orderItem\": [{\n" +
61         "\t\t\"id\": <orderItemId>,\n" +
62         "\t\t\"action\": <action>,\n" +
63         "\t\t\"service\": {\n" +
64             "\t\t\t\"serviceState\": <serviceState>,\n" +
65             "\t\t\t\"name\": <serviceName>,\n" +
66             "\t\t\t\"serviceType\": <serviceType>,\n" +
67             "\t\t\t\"serviceSpecification\": { \n" +
68                 "\t\t\t\t\"id\": <serviceUuId> \n" +
69             "\t\t\t},\n" +
70             "\t\t\t\"serviceCharacteristic\": [ \n" +
71             "<_requestInputs_> \n" +
72             "\t\t\t]  \n" +
73         "\t\t}\n" +   
74     "\t}]\n" +
75         "}"
76         
77         public static final String RequestInputsTemplate =
78         "{ \n" +
79     "\t\"name\": <inputName>, \n" +
80     "\t\"value\": { \n" +
81         "\t\t\"serviceCharacteristicValue\": <inputValue> \n" +
82     "\t} \n" + 
83     "}"
84
85         public ExternalAPIUtil(AbstractServiceTaskProcessor taskProcessor) {
86                 this.taskProcessor = taskProcessor
87         }
88
89 //      public String getUri(DelegateExecution execution, resourceName) {
90 //
91 //              def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
92 //              def uri = execution.getVariable("ExternalAPIURi")
93 //              if(uri) {
94 //                      taskProcessor.logDebug("ExternalAPIUtil.getUri: " + uri, isDebugLogEnabled)
95 //                      return uri
96 //              }
97 //              
98 //              exceptionUtil.buildAndThrowWorkflowException(execution, 9999, 'ExternalAPI URI not find')
99 //      }
100         
101         public String setTemplate(String template, Map<String, String> valueMap) {              
102                 taskProcessor.logDebug("ExternalAPIUtil setTemplate", true);
103                 StringBuffer result = new StringBuffer();
104
105                 String pattern = "<.*>";
106                 Pattern r = Pattern.compile(pattern);
107                 Matcher m = r.matcher(template);
108
109                 taskProcessor.logDebug("ExternalAPIUtil template:" + template, true);
110                 while (m.find()) {
111                         String key = template.substring(m.start() + 1, m.end() - 1);
112                         taskProcessor.logDebug("ExternalAPIUtil key:" + key + " contains key? " + valueMap.containsKey(key), true);
113                         m.appendReplacement(result, valueMap.getOrDefault(key, "\"TBD\""));
114                 }
115                 m.appendTail(result);
116                 taskProcessor.logDebug("ExternalAPIUtil return:" + result.toString(), true);
117                 return result.toString();
118         }
119
120         /**
121          * This reusable method can be used for making ExternalAPI Get Calls. The url should
122          * be passed as a parameter along with the execution.  The method will
123          * return an APIResponse.
124          *
125          * @param execution
126          * @param url
127          *
128          * @return APIResponse
129          *
130          */
131         public APIResponse executeExternalAPIGetCall(DelegateExecution execution, String url){
132                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
133                 taskProcessor.logDebug(" ======== STARTED Execute ExternalAPI Get Process ======== ", isDebugEnabled)
134                 APIResponse apiResponse = null
135                 try{
136                         String uuid = utils.getRequestID()
137                         taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled)
138                         taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled)
139
140                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_externalapi_auth"),execution.getVariable("URN_mso_msoKey"))
141
142                         RESTConfig config = new RESTConfig(url);
143                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/json");
144
145                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
146                                 client.addAuthorizationHeader(basicAuthCred)
147                         }
148                         apiResponse = client.get()
149
150                         taskProcessor.logDebug( "======== COMPLETED Execute ExternalAPI Get Process ======== ", isDebugEnabled)
151                 }catch(Exception e){
152                         taskProcessor.logDebug("Exception occured while executing ExternalAPI Get Call. Exception is: \n" + e, isDebugEnabled)
153                         exceptionUtil.buildAndThrowWorkflowException(execution, 9999, e.getMessage())
154                 }
155                 return apiResponse
156         }
157
158         /**
159          * This reusable method can be used for making ExternalAPI Post Calls. The url
160          * and payload should be passed as a parameters along with the execution.
161          * The method will return an APIResponse.
162          *
163          * @param execution
164          * @param url
165          * @param payload
166          *
167          * @return APIResponse
168          *
169          */
170         public APIResponse executeExternalAPIPostCall(DelegateExecution execution, String url, String payload){
171                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
172                 taskProcessor.logDebug( " ======== Started Execute ExternalAPI Post Process ======== ", isDebugEnabled)
173                 APIResponse apiResponse = null
174                 try{
175                         String uuid = utils.getRequestID()
176                         taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled)
177                         taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled)
178
179                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_externalapi_auth"),execution.getVariable("URN_mso_msoKey"))
180                         RESTConfig config = new RESTConfig(url);
181                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/json").addHeader("Accept","application/json");
182
183                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
184                                 client.addAuthorizationHeader(basicAuthCred)
185                         }
186                         apiResponse = client.httpPost(payload)
187
188                         taskProcessor.logDebug( "======== Completed Execute ExternalAPI Post Process ======== ", isDebugEnabled)
189                 }catch(Exception e){
190                         taskProcessor.utils.log("ERROR", "Exception occured while executing ExternalAPI Post Call. Exception is: \n" + e, isDebugEnabled)
191                         exceptionUtil.buildAndThrowWorkflowException(execution, 9999, e.getMessage())
192                 }
193                 return apiResponse
194         }
195
196         /**
197          * This reusable method can be used for making ExternalAPI Post Calls. The url
198          * and payload should be passed as a parameters along with the execution.
199          * The method will return an APIResponse.
200          *
201          * @param execution
202          * @param url
203          * @param payload
204          * @param authenticationHeader - addAuthenticationHeader value
205          * @param headerName - name of header you want to add, i.e. addHeader(headerName, headerValue)
206          * @param headerValue - the header's value, i.e. addHeader(headerName, headerValue)
207          *
208          * @return APIResponse
209          *
210          */
211         public APIResponse executeExternalAPIPostCall(DelegateExecution execution, String url, String payload, String authenticationHeaderValue, String headerName, String headerValue){
212                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
213                 taskProcessor.logDebug( " ======== Started Execute ExternalAPI Post Process ======== ", isDebugEnabled)
214                 APIResponse apiResponse = null
215                 try{
216                         taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled)
217
218                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_externalapi_auth"),execution.getVariable("URN_mso_msoKey"))
219
220                         RESTConfig config = new RESTConfig(url);
221                         RESTClient client = new RESTClient(config).addAuthorizationHeader(authenticationHeaderValue).addHeader(headerName, headerValue)
222                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
223                                 client.addAuthorizationHeader(basicAuthCred)
224                         }
225                         apiResponse = client.httpPost(payload)
226
227                         taskProcessor.logDebug( "======== Completed Execute ExternalAPI Post Process ======== ", isDebugEnabled)
228                 }catch(Exception e){
229                         taskProcessor.utils.log("ERROR", "Exception occured while executing ExternalAPI Post Call. Exception is: \n" + e, isDebugEnabled)
230                         exceptionUtil.buildAndThrowWorkflowException(execution, 9999, e.getMessage())
231                 }
232                 return apiResponse
233         }
234
235 }