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