Replaced all tabs with spaces in java and pom.xml
[so.git] / bpmn / MSOCommonBPMN / src / main / java / org / onap / so / bpmn / common / recipe / BpmnRestClient.java
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.recipe;
24
25 import java.io.IOException;
26 import java.security.GeneralSecurityException;
27 import javax.xml.bind.DatatypeConverter;
28 import org.apache.http.HttpResponse;
29 import org.apache.http.client.ClientProtocolException;
30 import org.apache.http.client.HttpClient;
31 import org.apache.http.client.config.RequestConfig;
32 import org.apache.http.client.methods.HttpPost;
33 import org.apache.http.entity.StringEntity;
34 import org.apache.http.impl.client.HttpClientBuilder;
35 import org.onap.so.bpmn.core.UrnPropertiesReader;
36 import org.onap.so.logger.ErrorCode;
37 import org.onap.so.logger.MessageEnum;
38 import org.onap.so.utils.CryptoUtils;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41 import org.springframework.beans.factory.annotation.Autowired;
42 import org.springframework.stereotype.Component;
43
44 /**
45  * Support to call resource recipes from the BPMN workflow. Such as call resource recipe in service workflow. <br>
46  * <p>
47  * </p>
48  * 
49  * @author
50  * @version ONAP Beijing Release 2018-02-27
51  */
52 @Component
53 public class BpmnRestClient {
54
55     private static Logger logger = LoggerFactory.getLogger(BpmnRestClient.class);
56
57     public static final String DEFAULT_BPEL_AUTH = "admin:admin";
58
59     public static final String ENCRYPTION_KEY_PROP = "org.onap.so.adapters.network.encryptionKey";
60
61     public static final String CONTENT_TYPE_JSON = "application/json";
62
63     public static final String CAMUNDA_AUTH = "mso.camundaAuth";
64
65     private static final String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA";
66     @Autowired
67     private UrnPropertiesReader urnPropertiesReader;
68
69     private static boolean noProperties = true;
70
71     // because for NS it will take a long time the time out of the resouce will be 2 hours.
72     private static final String DEFAULT_TIME_OUT = "7200";
73
74     public synchronized final boolean getNoPropertiesState() {
75         return noProperties;
76     }
77
78     /**
79      * post the recipe Uri <br>
80      * 
81      * @param recipeUri The request recipe uri
82      * @param requestId the request id
83      * @param recipeTimeout The recipe time out
84      * @param requestAction The request action
85      * @param serviceInstanceId The service instance id
86      * @param serviceType The service Type
87      * @param requestDetails The request Details, these information is from runtime
88      * @param recipeParamXsd The recipe params, its from recipe design
89      * @return The response of the recipe.
90      * @throws ClientProtocolException
91      * @throws IOException
92      * @since ONAP Beijing Release
93      */
94     public HttpResponse post(String recipeUri, String requestId, int recipeTimeout, String requestAction,
95             String serviceInstanceId, String serviceType, String requestDetails, String recipeParamXsd)
96             throws ClientProtocolException, IOException {
97
98         HttpClient client = HttpClientBuilder.create().build();
99
100         HttpPost post = new HttpPost(recipeUri);
101         RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(recipeTimeout)
102                 .setConnectTimeout(recipeTimeout).setConnectionRequestTimeout(recipeTimeout).build();
103         post.setConfig(requestConfig);
104         logger.debug("call the bpmn,  url: {}", recipeUri);
105         String jsonReq = wrapResourceRequest(requestId, recipeTimeout, requestAction, serviceInstanceId, serviceType,
106                 requestDetails, recipeParamXsd);
107
108         StringEntity input = new StringEntity(jsonReq);
109         input.setContentType(CONTENT_TYPE_JSON);
110         String encryptedCredentials;
111         encryptedCredentials = urnPropertiesReader.getVariable(CAMUNDA_AUTH);
112         if (encryptedCredentials != null) {
113             String userCredentials =
114                     getEncryptedPropValue(encryptedCredentials, DEFAULT_BPEL_AUTH, ENCRYPTION_KEY_PROP);
115             if (userCredentials != null) {
116                 post.addHeader("Authorization",
117                         "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes()));
118             }
119         }
120
121         post.setEntity(input);
122         return client.execute(post);
123     }
124
125     /**
126      * prepare the resource recipe bpmn request. <br>
127      * 
128      * @param requestId
129      * @param recipeTimeout
130      * @param requestAction
131      * @param serviceInstanceId
132      * @param serviceType
133      * @param requestDetails
134      * @param recipeParams
135      * @return
136      * @since ONAP Beijing Release
137      */
138     private String wrapResourceRequest(String requestId, int recipeTimeout, String requestAction,
139             String serviceInstanceId, String serviceType, String requestDetails, String recipeParams) {
140         String jsonReq = null;
141         if (requestId == null) {
142             requestId = "";
143         }
144         if (requestAction == null) {
145             requestAction = "";
146         }
147         if (serviceInstanceId == null) {
148             serviceInstanceId = "";
149         }
150
151         if (requestDetails == null) {
152             requestDetails = "";
153         }
154
155         try {
156             ResourceRecipeRequest recipeRequest = new ResourceRecipeRequest();
157             BpmnParam resourceInput = new BpmnParam();
158             BpmnParam host = new BpmnParam();
159             BpmnParam requestIdInput = new BpmnParam();
160             BpmnParam requestActionInput = new BpmnParam();
161             BpmnParam serviceInstanceIdInput = new BpmnParam();
162             BpmnParam serviceTypeInput = new BpmnParam();
163             BpmnParam recipeParamsInput = new BpmnParam();
164             BpmnIntegerParam recipeTimeoutInput = new BpmnIntegerParam();
165             recipeTimeoutInput.setValue(recipeTimeout);
166             // host.setValue(parseURL());
167             requestIdInput.setValue(requestId);
168             requestActionInput.setValue(requestAction);
169             serviceInstanceIdInput.setValue(serviceInstanceId);
170             serviceTypeInput.setValue(serviceType);
171             recipeParamsInput.setValue(recipeParams);
172             resourceInput.setValue(requestDetails);
173             recipeRequest.setHost(host);
174             recipeRequest.setRequestId(requestIdInput);
175             recipeRequest.setRequestAction(requestActionInput);
176             recipeRequest.setServiceInstanceId(serviceInstanceIdInput);
177             recipeRequest.setServiceType(serviceTypeInput);
178             recipeRequest.setRecipeParams(recipeParamsInput);
179             recipeRequest.setResourceInput(resourceInput);
180             recipeRequest.setRecipeTimeout(recipeTimeoutInput);
181             jsonReq = recipeRequest.toString();
182             logger.trace("request body is {}", jsonReq);
183         } catch (Exception e) {
184             logger.error("{} {} {} {} {}", MessageEnum.APIH_WARP_REQUEST.toString(), "Camunda", "wrapVIDRequest",
185                     ErrorCode.BusinessProcesssError.getValue(), "Error in APIH Warp request", e);
186         }
187         return jsonReq;
188     }
189
190     /**
191      * <br>
192      * 
193      * @param prop
194      * @param defaultValue
195      * @param encryptionKey
196      * @return
197      * @since ONAP Beijing Release
198      */
199     protected String getEncryptedPropValue(String prop, String defaultValue, String encryptionKey) {
200         try {
201             return CryptoUtils.decrypt(prop, urnPropertiesReader.getVariable(encryptionKey));
202         } catch (GeneralSecurityException e) {
203             logger.debug("Security exception", e);
204         }
205         return defaultValue;
206     }
207
208 }