update install and configure document
[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\"serviceSpecification\": { \n" +
67                 "\t\t\t\t\"id\": <serviceUuId> \n" +
68             "\t\t\t},\n" +
69             "\t\t\t\"serviceCharacteristic\": [ \n" +
70             "<_requestInputs_> \n" +
71             "\t\t\t]  \n" +
72         "\t\t}\n" +   
73     "\t}]\n" +
74         "}"
75         
76         public static final String RequestInputsTemplate =
77         "{ \n" +
78     "\t\"name\": <inputName>, \n" +
79     "\t\"value\": { \n" +
80         "\t\t\"serviceCharacteristicValue\": <inputValue> \n" +
81     "\t} \n" + 
82     "}"
83
84         public ExternalAPIUtil(AbstractServiceTaskProcessor taskProcessor) {
85                 this.taskProcessor = taskProcessor
86         }
87
88 //      public String getUri(DelegateExecution execution, resourceName) {
89 //
90 //              def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled')
91 //              def uri = execution.getVariable("ExternalAPIURi")
92 //              if(uri) {
93 //                      taskProcessor.logDebug("ExternalAPIUtil.getUri: " + uri, isDebugLogEnabled)
94 //                      return uri
95 //              }
96 //              
97 //              exceptionUtil.buildAndThrowWorkflowException(execution, 9999, 'ExternalAPI URI not find')
98 //      }
99         
100         public String setTemplate(String template, Map<String, String> valueMap) {              
101                 taskProcessor.logDebug("ExternalAPIUtil setTemplate", true);
102                 StringBuffer result = new StringBuffer();
103
104                 String pattern = "<.*>";
105                 Pattern r = Pattern.compile(pattern);
106                 Matcher m = r.matcher(template);
107
108                 taskProcessor.logDebug("ExternalAPIUtil template:" + template, true);
109                 while (m.find()) {
110                         String key = template.substring(m.start() + 1, m.end() - 1);
111                         taskProcessor.logDebug("ExternalAPIUtil key:" + key + " contains key? " + valueMap.containsKey(key), true);
112                         m.appendReplacement(result, valueMap.getOrDefault(key, "\"TBD\""));
113                 }
114                 m.appendTail(result);
115                 taskProcessor.logDebug("ExternalAPIUtil return:" + result.toString(), true);
116                 return result.toString();
117         }
118
119         /**
120          * This reusable method can be used for making ExternalAPI Get Calls. The url should
121          * be passed as a parameter along with the execution.  The method will
122          * return an APIResponse.
123          *
124          * @param execution
125          * @param url
126          *
127          * @return APIResponse
128          *
129          */
130         public APIResponse executeExternalAPIGetCall(DelegateExecution execution, String url){
131                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
132                 taskProcessor.logDebug(" ======== STARTED Execute ExternalAPI Get Process ======== ", isDebugEnabled)
133                 APIResponse apiResponse = null
134                 try{
135                         String uuid = utils.getRequestID()
136                         taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled)
137                         taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled)
138
139                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_externalapi_auth"),execution.getVariable("URN_mso_msoKey"))
140
141                         RESTConfig config = new RESTConfig(url);
142                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/json");
143
144                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
145                                 client.addAuthorizationHeader(basicAuthCred)
146                         }
147                         apiResponse = client.get()
148
149                         taskProcessor.logDebug( "======== COMPLETED Execute ExternalAPI Get Process ======== ", isDebugEnabled)
150                 }catch(Exception e){
151                         taskProcessor.logDebug("Exception occured while executing ExternalAPI Get Call. Exception is: \n" + e, isDebugEnabled)
152                         exceptionUtil.buildAndThrowWorkflowException(execution, 9999, e.getMessage())
153                 }
154                 return apiResponse
155         }
156
157         /**
158          * This reusable method can be used for making ExternalAPI Post Calls. The url
159          * and payload should be passed as a parameters along with the execution.
160          * The method will return an APIResponse.
161          *
162          * @param execution
163          * @param url
164          * @param payload
165          *
166          * @return APIResponse
167          *
168          */
169         public APIResponse executeExternalAPIPostCall(DelegateExecution execution, String url, String payload){
170                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
171                 taskProcessor.logDebug( " ======== Started Execute ExternalAPI Post Process ======== ", isDebugEnabled)
172                 APIResponse apiResponse = null
173                 try{
174                         String uuid = utils.getRequestID()
175                         taskProcessor.logDebug( "Generated uuid is: " + uuid, isDebugEnabled)
176                         taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled)
177
178                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_externalapi_auth"),execution.getVariable("URN_mso_msoKey"))
179                         RESTConfig config = new RESTConfig(url);
180                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/json").addHeader("Accept","application/json");
181
182                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
183                                 client.addAuthorizationHeader(basicAuthCred)
184                         }
185                         apiResponse = client.httpPost(payload)
186
187                         taskProcessor.logDebug( "======== Completed Execute ExternalAPI Post Process ======== ", isDebugEnabled)
188                 }catch(Exception e){
189                         taskProcessor.utils.log("ERROR", "Exception occured while executing ExternalAPI Post Call. Exception is: \n" + e, isDebugEnabled)
190                         exceptionUtil.buildAndThrowWorkflowException(execution, 9999, e.getMessage())
191                 }
192                 return apiResponse
193         }
194
195         /**
196          * This reusable method can be used for making ExternalAPI Post Calls. The url
197          * and payload should be passed as a parameters along with the execution.
198          * The method will return an APIResponse.
199          *
200          * @param execution
201          * @param url
202          * @param payload
203          * @param authenticationHeader - addAuthenticationHeader value
204          * @param headerName - name of header you want to add, i.e. addHeader(headerName, headerValue)
205          * @param headerValue - the header's value, i.e. addHeader(headerName, headerValue)
206          *
207          * @return APIResponse
208          *
209          */
210         public APIResponse executeExternalAPIPostCall(DelegateExecution execution, String url, String payload, String authenticationHeaderValue, String headerName, String headerValue){
211                 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
212                 taskProcessor.logDebug( " ======== Started Execute ExternalAPI Post Process ======== ", isDebugEnabled)
213                 APIResponse apiResponse = null
214                 try{
215                         taskProcessor.logDebug( "URL to be used is: " + url, isDebugEnabled)
216
217                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_externalapi_auth"),execution.getVariable("URN_mso_msoKey"))
218
219                         RESTConfig config = new RESTConfig(url);
220                         RESTClient client = new RESTClient(config).addAuthorizationHeader(authenticationHeaderValue).addHeader(headerName, headerValue)
221                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
222                                 client.addAuthorizationHeader(basicAuthCred)
223                         }
224                         apiResponse = client.httpPost(payload)
225
226                         taskProcessor.logDebug( "======== Completed Execute ExternalAPI Post Process ======== ", isDebugEnabled)
227                 }catch(Exception e){
228                         taskProcessor.utils.log("ERROR", "Exception occured while executing ExternalAPI Post Call. Exception is: \n" + e, isDebugEnabled)
229                         exceptionUtil.buildAndThrowWorkflowException(execution, 9999, e.getMessage())
230                 }
231                 return apiResponse
232         }
233
234 }