Add unit tests for ExternalAPIUtil
[so.git] / bpmn / MSOCommonBPMN / src / main / groovy / org / onap / so / bpmn / common / scripts / ExternalAPIUtil.groovy
index 7d4adae..250cdda 100644 (file)
@@ -2,14 +2,14 @@
  * ============LICENSE_START=======================================================
  * ONAP - SO
  * ================================================================================
- * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. 
+ * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  */
 
 package org.onap.so.bpmn.common.scripts
-import org.camunda.bpm.engine.delegate.BpmnError
+
+
 import org.camunda.bpm.engine.delegate.DelegateExecution
-import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor;
+import org.onap.logging.ref.slf4j.ONAPLogConstants
+import org.onap.so.client.HttpClient
+import org.onap.so.client.HttpClientFactory
 import org.onap.so.logger.MsoLogger
-import org.onap.so.rest.APIResponse
-import org.onap.so.rest.RESTClient
-import org.onap.so.rest.RESTConfig
-import org.apache.commons.lang3.StringEscapeUtils
+import org.onap.so.utils.TargetEntity
+
+import javax.ws.rs.core.MediaType
+import javax.ws.rs.core.Response
 import java.util.regex.Matcher
 import java.util.regex.Pattern
 
 class ExternalAPIUtil {
-       
-       String Prefix="EXTAPI_"
 
-       public MsoUtils utils = new MsoUtils()
-       
-       ExceptionUtil exceptionUtil = new ExceptionUtil()
+       String Prefix="EXTAPI_"
 
        private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, ExternalAPIUtil.class)
 
+       private final HttpClientFactory httpClientFactory;
+       private final MsoUtils utils;
+       private final ExceptionUtil exceptionUtil;
+
        public static final String PostServiceOrderRequestsTemplate =
        "{\n" +
        "\t\"externalId\": <externalId>,\n" +
@@ -71,19 +74,22 @@ class ExternalAPIUtil {
             "\t\t\t\"serviceCharacteristic\": [ \n" +
             "<_requestInputs_> \n" +
             "\t\t\t]  \n" +
-        "\t\t}\n" +   
+        "\t\t}\n" +
     "\t}]\n" +
        "}"
-       
+
        public static final String RequestInputsTemplate =
        "{ \n" +
     "\t\"name\": <inputName>, \n" +
     "\t\"value\": { \n" +
         "\t\t\"serviceCharacteristicValue\": <inputValue> \n" +
-    "\t} \n" + 
+    "\t} \n" +
     "}"
 
-       public ExternalAPIUtil() {
+       ExternalAPIUtil(HttpClientFactory httpClientFactory, MsoUtils utils, ExceptionUtil exceptionUtil) {
+               this.httpClientFactory = httpClientFactory
+               this.utils = utils
+               this.exceptionUtil = exceptionUtil
        }
 
 //     public String getUri(DelegateExecution execution, resourceName) {
@@ -93,11 +99,11 @@ class ExternalAPIUtil {
 //                     msoLogger.debug("ExternalAPIUtil.getUri: " + uri)
 //                     return uri
 //             }
-//             
+//
 //             exceptionUtil.buildAndThrowWorkflowException(execution, 9999, 'ExternalAPI URI not find')
 //     }
-       
-       public String setTemplate(String template, Map<String, String> valueMap) {              
+
+       public String setTemplate(String template, Map<String, String> valueMap) {
                msoLogger.debug("ExternalAPIUtil setTemplate", true);
                StringBuffer result = new StringBuffer();
 
@@ -127,22 +133,20 @@ class ExternalAPIUtil {
         * @return APIResponse
         *
         */
-       public APIResponse executeExternalAPIGetCall(DelegateExecution execution, String url){
+       public Response executeExternalAPIGetCall(DelegateExecution execution, String url){
                msoLogger.debug(" ======== STARTED Execute ExternalAPI Get Process ======== ")
-               APIResponse apiResponse = null
+               Response apiResponse = null
                try{
                        String uuid = utils.getRequestID()
                        msoLogger.debug( "Generated uuid is: " + uuid)
                        msoLogger.debug( "URL to be used is: " + url)
 
-                       String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_externalapi_auth"),execution.getVariable("URN_mso_msoKey"))
+                       HttpClient client = httpClientFactory.create(new URL(url), MediaType.APPLICATION_JSON, TargetEntity.EXTERNAL)
+                       client.addBasicAuthHeader(execution.getVariable("URN_externalapi_auth"), execution.getVariable("URN_mso_msoKey"))
+                       client.addAdditionalHeader("X-FromAppId", "MSO")
+                       client.addAdditionalHeader(ONAPLogConstants.Headers.REQUEST_ID, uuid)
+                       client.addAdditionalHeader("Accept", MediaType.APPLICATION_JSON)
 
-                       RESTConfig config = new RESTConfig(url);
-                       RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Accept","application/json");
-
-                       if (basicAuthCred != null && !"".equals(basicAuthCred)) {
-                               client.addAuthorizationHeader(basicAuthCred)
-                       }
                        apiResponse = client.get()
 
                        msoLogger.debug( "======== COMPLETED Execute ExternalAPI Get Process ======== ")
@@ -162,25 +166,23 @@ class ExternalAPIUtil {
         * @param url
         * @param payload
         *
-        * @return APIResponse
+        * @return Response
         *
         */
-       public APIResponse executeExternalAPIPostCall(DelegateExecution execution, String url, String payload){
+       public Response executeExternalAPIPostCall(DelegateExecution execution, String url, String payload){
                msoLogger.debug( " ======== Started Execute ExternalAPI Post Process ======== ")
-               APIResponse apiResponse = null
+               Response apiResponse = null
                try{
                        String uuid = utils.getRequestID()
                        msoLogger.debug( "Generated uuid is: " + uuid)
                        msoLogger.debug( "URL to be used is: " + url)
 
-                       String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_externalapi_auth"),execution.getVariable("URN_mso_msoKey"))
-                       RESTConfig config = new RESTConfig(url);
-                       RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/json").addHeader("Accept","application/json");
+                       HttpClient httpClient = httpClientFactory.create(new URL(url), MediaType.APPLICATION_JSON, TargetEntity.AAI)
+                       httpClient.addBasicAuthHeader(execution.getVariable("URN_externalapi_auth"), execution.getVariable("URN_mso_msoKey"))
+                       httpClient.addAdditionalHeader("X-FromAppId", "MSO")
+                       httpClient.addAdditionalHeader("X-TransactionId", uuid)
 
-                       if (basicAuthCred != null && !"".equals(basicAuthCred)) {
-                               client.addAuthorizationHeader(basicAuthCred)
-                       }
-                       apiResponse = client.httpPost(payload)
+                       apiResponse = httpClient.post(payload)
 
                        msoLogger.debug( "======== Completed Execute ExternalAPI Post Process ======== ")
                }catch(Exception e){
@@ -190,42 +192,6 @@ class ExternalAPIUtil {
                return apiResponse
        }
 
-       /**
-        * This reusable method can be used for making ExternalAPI Post Calls. The url
-        * and payload should be passed as a parameters along with the execution.
-        * The method will return an APIResponse.
-        *
-        * @param execution
-        * @param url
-        * @param payload
-        * @param authenticationHeader - addAuthenticationHeader value
-        * @param headerName - name of header you want to add, i.e. addHeader(headerName, headerValue)
-        * @param headerValue - the header's value, i.e. addHeader(headerName, headerValue)
-        *
-        * @return APIResponse
-        *
-        */
-       public APIResponse executeExternalAPIPostCall(DelegateExecution execution, String url, String payload, String authenticationHeaderValue, String headerName, String headerValue){
-               msoLogger.debug( " ======== Started Execute ExternalAPI Post Process ======== ")
-               APIResponse apiResponse = null
-               try{
-                       msoLogger.debug( "URL to be used is: " + url)
-
-                       String basicAuthCred = utils.getBasicAuth(execution.getVariable("URN_externalapi_auth"),execution.getVariable("URN_mso_msoKey"))
 
-                       RESTConfig config = new RESTConfig(url);
-                       RESTClient client = new RESTClient(config).addAuthorizationHeader(authenticationHeaderValue).addHeader(headerName, headerValue)
-                       if (basicAuthCred != null && !"".equals(basicAuthCred)) {
-                               client.addAuthorizationHeader(basicAuthCred)
-                       }
-                       apiResponse = client.httpPost(payload)
-
-                       msoLogger.debug( "======== Completed Execute ExternalAPI Post Process ======== ")
-               }catch(Exception e){
-                       msoLogger.error("Exception occured while executing ExternalAPI Post Call. Exception is: \n" + e)
-                       exceptionUtil.buildAndThrowWorkflowException(execution, 9999, e.getMessage())
-               }
-               return apiResponse
-       }
 
 }
\ No newline at end of file