Merge "Sonar fix in mso-adapter-utils"
[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  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License")
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.common.scripts
24
25
26 import org.camunda.bpm.engine.delegate.DelegateExecution
27 import org.onap.logging.ref.slf4j.ONAPLogConstants
28 import org.onap.so.client.HttpClient
29 import org.onap.so.client.HttpClientFactory
30 import org.slf4j.Logger
31 import org.slf4j.LoggerFactory
32 import org.onap.so.utils.TargetEntity
33
34 import javax.ws.rs.core.MediaType
35 import javax.ws.rs.core.Response
36 import java.util.regex.Matcher
37 import java.util.regex.Pattern
38
39 class ExternalAPIUtil {
40
41         String Prefix="EXTAPI_"
42
43     private static final Logger logger = LoggerFactory.getLogger( ExternalAPIUtil.class)
44
45         private final HttpClientFactory httpClientFactory
46         private final MsoUtils utils
47         private final ExceptionUtil exceptionUtil
48
49         public static final String PostServiceOrderRequestsTemplate =
50         "{\n" +
51         "\t\"externalId\": <externalId>,\n" +
52         "\t\"category\": <category>,\n" +
53         "\t\"description\": <description>,\n" +
54         "\t\"requestedStartDate\": <requestedStartDate>,\n" +
55         "\t\"requestedCompletionDate\": <requestedCompletionDate>,\n" +
56         "\t\"priority\": <priority>,\n" +
57         "\t\"@type\": null,\n" +
58         "\t\"@baseType\": null,\n" +
59         "\t\"@schemaLocation\": null,\n" +
60         "\t\"relatedParty\": [{\n" +
61         "\t\t\"id\": <subscriberId>, \n" +
62         "\t\t\"href\": null, \n" +
63         "\t\t\"role\": <customerRole>, \n" +
64         "\t\t\"name\": <subscriberName>, \n" +
65         "\t\t\"@referredType\": <referredType> \n" +
66         "}], \n" +
67         "\t\"orderItem\": [{\n" +
68         "\t\t\"id\": <orderItemId>,\n" +
69         "\t\t\"action\": <action>,\n" +
70         "\t\t\"service\": {\n" +
71             "\t\t\t\"serviceState\": <serviceState>,\n" +
72                         "\t\t\t\"id\": <serviceId>,\n" +
73             "\t\t\t\"name\": <serviceName>,\n" +
74             "\t\t\t\"serviceSpecification\": { \n" +
75                 "\t\t\t\t\"id\": <serviceUuId> \n" +
76             "\t\t\t},\n" +
77             "\t\t\t\"serviceCharacteristic\": [ \n" +
78             "<_requestInputs_> \n" +
79             "\t\t\t]  \n" +
80         "\t\t}\n" +
81     "\t}]\n" +
82         "}"
83
84         public static final String RequestInputsTemplate =
85         "{ \n" +
86     "\t\"name\": <inputName>, \n" +
87     "\t\"value\": { \n" +
88         "\t\t\"serviceCharacteristicValue\": <inputValue> \n" +
89     "\t} \n" +
90     "}"
91
92         ExternalAPIUtil(HttpClientFactory httpClientFactory, MsoUtils utils, ExceptionUtil exceptionUtil) {
93                 this.httpClientFactory = httpClientFactory
94                 this.utils = utils
95                 this.exceptionUtil = exceptionUtil
96         }
97
98 //      public String getUri(DelegateExecution execution, resourceName) {
99 //
100 //              def uri = execution.getVariable("ExternalAPIURi")
101 //              if(uri) {
102 //                      logger.debug("ExternalAPIUtil.getUri: " + uri)
103 //                      return uri
104 //              }
105 //
106 //              exceptionUtil.buildAndThrowWorkflowException(execution, 9999, 'ExternalAPI URI not find')
107 //      }
108
109         public String setTemplate(String template, Map<String, String> valueMap) {
110                 logger.debug("ExternalAPIUtil setTemplate", true)
111                 StringBuffer result = new StringBuffer()
112
113                 String pattern = "<.*>"
114                 Pattern r = Pattern.compile(pattern)
115                 Matcher m = r.matcher(template)
116
117                 logger.debug("ExternalAPIUtil template:" + template, true)
118                 while (m.find()) {
119                         String key = template.substring(m.start() + 1, m.end() - 1)
120                         logger.debug("ExternalAPIUtil key:" + key + " contains key? " + valueMap.containsKey(key), true)
121                         m.appendReplacement(result, valueMap.getOrDefault(key, "\"TBD\""))
122                 }
123                 m.appendTail(result)
124                 logger.debug("ExternalAPIUtil return:" + result.toString(), true)
125                 return result.toString()
126         }
127
128         /**
129          * This reusable method can be used for making ExternalAPI Get Calls. The url should
130          * be passed as a parameter along with the execution.  The method will
131          * return an APIResponse.
132          *
133          * @param execution
134          * @param url
135          *
136          * @return APIResponse
137          *
138          */
139         public Response executeExternalAPIGetCall(DelegateExecution execution, String url){
140                 logger.debug(" ======== STARTED Execute ExternalAPI Get Process ======== ")
141                 Response apiResponse = null
142                 try{
143                         String uuid = utils.getRequestID()
144                         logger.debug( "Generated uuid is: " + uuid)
145                         logger.debug( "URL to be used is: " + url)
146                         logger.debug("URL to be passed in header is: " + execution.getVariable("SPPartnerUrl"))
147
148                         HttpClient client = httpClientFactory.newJsonClient(new URL(url), TargetEntity.EXTERNAL)
149                         client.addBasicAuthHeader(execution.getVariable("URN_externalapi_auth"), execution.getVariable("URN_mso_msoKey"))
150                         client.addAdditionalHeader("X-FromAppId", "MSO")
151                         client.addAdditionalHeader(ONAPLogConstants.Headers.REQUEST_ID, uuid)
152                         client.addAdditionalHeader("Accept", MediaType.APPLICATION_JSON)
153                         client.addAdditionalHeader("Target",execution.getVariable("SPPartnerUrl"))
154
155                         apiResponse = client.get()
156
157                         logger.debug( "======== COMPLETED Execute ExternalAPI Get Process ======== ")
158                 }catch(Exception e){
159                         logger.debug("Exception occured while executing ExternalAPI Get Call. Exception is: \n" + e)
160                         exceptionUtil.buildAndThrowWorkflowException(execution, 9999, e.getMessage())
161                 }
162                 return apiResponse
163         }
164
165         /**
166          * This reusable method can be used for making ExternalAPI Post Calls. The url
167          * and payload should be passed as a parameters along with the execution.
168          * The method will return an APIResponse.
169          *
170          * @param execution
171          * @param url
172          * @param payload
173          *
174          * @return Response
175          *
176          */
177         public Response executeExternalAPIPostCall(DelegateExecution execution, String url, String payload){
178                 logger.debug( " ======== Started Execute ExternalAPI Post Process ======== ")
179                 Response apiResponse = null
180                 try{
181                         String uuid = utils.getRequestID()
182                         logger.debug( "Generated uuid is: " + uuid)
183                         logger.debug( "URL to be used is: " + url)
184                         logger.debug("URL to be passed in header is: " + execution.getVariable("SPPartnerUrl"))
185
186                         HttpClient httpClient = httpClientFactory.newJsonClient(new URL(url), TargetEntity.AAI)
187                         httpClient.addBasicAuthHeader(execution.getVariable("URN_externalapi_auth"), execution.getVariable("URN_mso_msoKey"))
188                         httpClient.addAdditionalHeader("X-FromAppId", "MSO")
189                         httpClient.addAdditionalHeader("X-TransactionId", uuid)
190                         httpClient.addAdditionalHeader("Target",execution.getVariable("SPPartnerUrl"))
191
192                         apiResponse = httpClient.post(payload)
193
194                         logger.debug( "======== Completed Execute ExternalAPI Post Process ======== ")
195                 }catch(Exception e){
196                         logger.error("Exception occured while executing ExternalAPI Post Call. Exception is: \n" + e)
197                         exceptionUtil.buildAndThrowWorkflowException(execution, 9999, e.getMessage())
198                 }
199                 return apiResponse
200         }
201
202
203
204 }