7d4adaea5868a5b68b7fb3974fa64052b35cf27c
[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.logger.MsoLogger
26 import org.onap.so.rest.APIResponse
27 import org.onap.so.rest.RESTClient
28 import org.onap.so.rest.RESTConfig
29 import org.apache.commons.lang3.StringEscapeUtils
30 import java.util.regex.Matcher
31 import java.util.regex.Pattern
32
33 class ExternalAPIUtil {
34         
35         String Prefix="EXTAPI_"
36
37         public MsoUtils utils = new MsoUtils()
38         
39         ExceptionUtil exceptionUtil = new ExceptionUtil()
40
41         private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, ExternalAPIUtil.class)
42
43         public static final String PostServiceOrderRequestsTemplate =
44         "{\n" +
45         "\t\"externalId\": <externalId>,\n" +
46         "\t\"category\": <category>,\n" +
47         "\t\"description\": <description>,\n" +
48         "\t\"requestedStartDate\": <requestedStartDate>,\n" +
49         "\t\"requestedCompletionDate\": <requestedCompletionDate>,\n" +
50         "\t\"priority\": <priority>,\n" +
51         "\t\"@type\": null,\n" +
52         "\t\"@baseType\": null,\n" +
53         "\t\"@schemaLocation\": null,\n" +
54         "\t\"relatedParty\": [{\n" +
55         "\t\t\"id\": <subscriberId>, \n" +
56         "\t\t\"href\": null, \n" +
57         "\t\t\"role\": <customerRole>, \n" +
58         "\t\t\"name\": <subscriberName>, \n" +
59         "\t\t\"@referredType\": <referredType> \n" +
60         "}], \n" +
61         "\t\"orderItem\": [{\n" +
62         "\t\t\"id\": <orderItemId>,\n" +
63         "\t\t\"action\": <action>,\n" +
64         "\t\t\"service\": {\n" +
65             "\t\t\t\"serviceState\": <serviceState>,\n" +
66                         "\t\t\t\"id\": <serviceId>,\n" +
67             "\t\t\t\"name\": <serviceName>,\n" +
68             "\t\t\t\"serviceSpecification\": { \n" +
69                 "\t\t\t\t\"id\": <serviceUuId> \n" +
70             "\t\t\t},\n" +
71             "\t\t\t\"serviceCharacteristic\": [ \n" +
72             "<_requestInputs_> \n" +
73             "\t\t\t]  \n" +
74         "\t\t}\n" +   
75     "\t}]\n" +
76         "}"
77         
78         public static final String RequestInputsTemplate =
79         "{ \n" +
80     "\t\"name\": <inputName>, \n" +
81     "\t\"value\": { \n" +
82         "\t\t\"serviceCharacteristicValue\": <inputValue> \n" +
83     "\t} \n" + 
84     "}"
85
86         public ExternalAPIUtil() {
87         }
88
89 //      public String getUri(DelegateExecution execution, resourceName) {
90 //
91 //              def uri = execution.getVariable("ExternalAPIURi")
92 //              if(uri) {
93 //                      msoLogger.debug("ExternalAPIUtil.getUri: " + uri)
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                 msoLogger.debug("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                 msoLogger.debug("ExternalAPIUtil template:" + template, true);
109                 while (m.find()) {
110                         String key = template.substring(m.start() + 1, m.end() - 1);
111                         msoLogger.debug("ExternalAPIUtil key:" + key + " contains key? " + valueMap.containsKey(key), true);
112                         m.appendReplacement(result, valueMap.getOrDefault(key, "\"TBD\""));
113                 }
114                 m.appendTail(result);
115                 msoLogger.debug("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                 msoLogger.debug(" ======== STARTED Execute ExternalAPI Get Process ======== ")
132                 APIResponse apiResponse = null
133                 try{
134                         String uuid = utils.getRequestID()
135                         msoLogger.debug( "Generated uuid is: " + uuid)
136                         msoLogger.debug( "URL to be used is: " + url)
137
138                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_externalapi_auth"),execution.getVariable("URN_mso_msoKey"))
139
140                         RESTConfig config = new RESTConfig(url);
141                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/json");
142
143                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
144                                 client.addAuthorizationHeader(basicAuthCred)
145                         }
146                         apiResponse = client.get()
147
148                         msoLogger.debug( "======== COMPLETED Execute ExternalAPI Get Process ======== ")
149                 }catch(Exception e){
150                         msoLogger.debug("Exception occured while executing ExternalAPI Get Call. Exception is: \n" + e)
151                         exceptionUtil.buildAndThrowWorkflowException(execution, 9999, e.getMessage())
152                 }
153                 return apiResponse
154         }
155
156         /**
157          * This reusable method can be used for making ExternalAPI Post Calls. The url
158          * and payload should be passed as a parameters along with the execution.
159          * The method will return an APIResponse.
160          *
161          * @param execution
162          * @param url
163          * @param payload
164          *
165          * @return APIResponse
166          *
167          */
168         public APIResponse executeExternalAPIPostCall(DelegateExecution execution, String url, String payload){
169                 msoLogger.debug( " ======== Started Execute ExternalAPI Post Process ======== ")
170                 APIResponse apiResponse = null
171                 try{
172                         String uuid = utils.getRequestID()
173                         msoLogger.debug( "Generated uuid is: " + uuid)
174                         msoLogger.debug( "URL to be used is: " + url)
175
176                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_externalapi_auth"),execution.getVariable("URN_mso_msoKey"))
177                         RESTConfig config = new RESTConfig(url);
178                         RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/json").addHeader("Accept","application/json");
179
180                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
181                                 client.addAuthorizationHeader(basicAuthCred)
182                         }
183                         apiResponse = client.httpPost(payload)
184
185                         msoLogger.debug( "======== Completed Execute ExternalAPI Post Process ======== ")
186                 }catch(Exception e){
187                         msoLogger.error("Exception occured while executing ExternalAPI Post Call. Exception is: \n" + e)
188                         exceptionUtil.buildAndThrowWorkflowException(execution, 9999, e.getMessage())
189                 }
190                 return apiResponse
191         }
192
193         /**
194          * This reusable method can be used for making ExternalAPI Post Calls. The url
195          * and payload should be passed as a parameters along with the execution.
196          * The method will return an APIResponse.
197          *
198          * @param execution
199          * @param url
200          * @param payload
201          * @param authenticationHeader - addAuthenticationHeader value
202          * @param headerName - name of header you want to add, i.e. addHeader(headerName, headerValue)
203          * @param headerValue - the header's value, i.e. addHeader(headerName, headerValue)
204          *
205          * @return APIResponse
206          *
207          */
208         public APIResponse executeExternalAPIPostCall(DelegateExecution execution, String url, String payload, String authenticationHeaderValue, String headerName, String headerValue){
209                 msoLogger.debug( " ======== Started Execute ExternalAPI Post Process ======== ")
210                 APIResponse apiResponse = null
211                 try{
212                         msoLogger.debug( "URL to be used is: " + url)
213
214                         String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_externalapi_auth"),execution.getVariable("URN_mso_msoKey"))
215
216                         RESTConfig config = new RESTConfig(url);
217                         RESTClient client = new RESTClient(config).addAuthorizationHeader(authenticationHeaderValue).addHeader(headerName, headerValue)
218                         if (basicAuthCred != null && !"".equals(basicAuthCred)) {
219                                 client.addAuthorizationHeader(basicAuthCred)
220                         }
221                         apiResponse = client.httpPost(payload)
222
223                         msoLogger.debug( "======== Completed Execute ExternalAPI Post Process ======== ")
224                 }catch(Exception e){
225                         msoLogger.error("Exception occured while executing ExternalAPI Post Call. Exception is: \n" + e)
226                         exceptionUtil.buildAndThrowWorkflowException(execution, 9999, e.getMessage())
227                 }
228                 return apiResponse
229         }
230
231 }