Merge "use config value instead hard code of url"
[so.git] / adapters / mso-vfc-adapter / src / main / java / org / onap / so / adapters / vfc / util / RestfulUtil.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
6  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
7  * ================================================================================
8  * Modifications Copyright (C) 2018.
9  * ================================================================================
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  * 
14  *      http://www.apache.org/licenses/LICENSE-2.0
15  * 
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.so.adapters.vfc.util;
25
26 import java.net.HttpURLConnection;
27 import java.net.SocketTimeoutException;
28
29 import javax.ws.rs.core.UriBuilder;
30
31 import org.apache.http.HttpResponse;
32 import org.apache.http.client.HttpClient;
33 import org.apache.http.client.config.RequestConfig;
34 import org.apache.http.client.methods.HttpDelete;
35 import org.apache.http.client.methods.HttpGet;
36 import org.apache.http.client.methods.HttpPost;
37 import org.apache.http.client.methods.HttpPut;
38 import org.apache.http.client.methods.HttpRequestBase;
39 import org.apache.http.conn.ConnectTimeoutException;
40 import org.apache.http.entity.ContentType;
41 import org.apache.http.entity.StringEntity;
42 import org.apache.http.impl.client.HttpClientBuilder;
43 import org.apache.http.util.EntityUtils;
44 import org.onap.so.adapters.vfc.model.RestfulResponse;
45 import org.onap.so.logger.MessageEnum;
46 import org.onap.so.logger.MsoLogger;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.core.env.Environment;
49 import org.springframework.stereotype.Component;
50
51 /**
52  * <br>
53  * <p>
54  * </p>
55  * utility to invoke restclient
56  * 
57  * @author
58  * @version ONAP Amsterdam Release 2017-9-6
59  */
60 @Component
61 public class RestfulUtil {
62
63     /**
64      * Log service
65      */
66     private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, RestfulUtil.class);
67
68     private static final int DEFAULT_TIME_OUT = 60000;
69
70     private static final String ONAP_IP = "ONAP_IP";
71     
72     private static final String DEFAULT_MSB_IP = "127.0.0.1";
73
74     private static final Integer DEFAULT_MSB_PORT = 80;
75     
76     private static final String VFC_ADAPTER="VFC Adapter";
77
78    @Autowired
79    private Environment env;
80
81     public String getMsbHost() {
82                 // MSB_IP will be set as ONAP_IP environment parameter in install flow.
83                 String msbIp = System.getenv().get(ONAP_IP);
84                 // if ONAP IP is not set. get it from config file.
85                 if (null == msbIp || msbIp.isEmpty()) {
86                         msbIp = env.getProperty("mso.msb-ip", DEFAULT_MSB_IP);
87                 }
88         Integer msbPort = env.getProperty("mso.msb-port", Integer.class, DEFAULT_MSB_PORT);
89         
90         String msbEndpoint = UriBuilder.fromPath("").host(msbIp).port(msbPort).scheme("http").build().toString();
91         LOGGER.debug("msbEndpoint in vfc adapter: " + msbEndpoint);
92         
93         return msbEndpoint;
94     }
95
96     private RestfulUtil() {
97
98     }
99
100     public RestfulResponse send(String url, String methodType, String content) {
101         String msbUrl = getMsbHost() + url;
102         LOGGER.debug("Begin to sent message " + methodType +": " + msbUrl);
103
104         HttpRequestBase method = null;
105         HttpResponse httpResponse = null;
106
107         try {
108             int timeout = DEFAULT_TIME_OUT;
109
110             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
111                     .setConnectionRequestTimeout(timeout).build();
112
113             HttpClient client = HttpClientBuilder.create().build();
114
115             if("POST".equalsIgnoreCase(methodType)) {
116                 HttpPost httpPost = new HttpPost(msbUrl);
117                 httpPost.setConfig(requestConfig);
118                 httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
119                 method = httpPost;
120             } else if("PUT".equalsIgnoreCase(methodType)) {
121                 HttpPut httpPut = new HttpPut(msbUrl);
122                 httpPut.setConfig(requestConfig);
123                 httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
124                 method = httpPut;
125             } else if("GET".equalsIgnoreCase(methodType)) {
126                 HttpGet httpGet = new HttpGet(msbUrl);
127                 httpGet.setConfig(requestConfig);
128                 method = httpGet;
129             } else if("DELETE".equalsIgnoreCase(methodType)) {
130                 HttpDelete httpDelete = new HttpDelete(msbUrl);
131                 httpDelete.setConfig(requestConfig);
132                 method = httpDelete;
133             }
134
135             // now VFC have no auth
136             // String userCredentials =
137             // SDNCAdapterProperties.getEncryptedProperty(Constants.SDNC_AUTH_PROP,
138             // Constants.DEFAULT_SDNC_AUTH, Constants.ENCRYPTION_KEY);
139             // String authorization = "Basic " +
140             // DatatypeConverter.printBase64Binary(userCredentials.getBytes());
141             // method.setHeader("Authorization", authorization);
142
143             httpResponse = client.execute(method);
144
145             String responseContent = null;
146             if(httpResponse.getEntity() != null) {
147                 responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
148             }
149
150             int statusCode = httpResponse.getStatusLine().getStatusCode();
151             String statusMessage = httpResponse.getStatusLine().getReasonPhrase();
152
153             LOGGER.debug("VFC Response: " + statusCode + " " + statusMessage
154                     + (responseContent == null ? "" : System.lineSeparator() + responseContent));
155
156             if(httpResponse.getStatusLine().getStatusCode() >= 300) {
157                 String errMsg = "VFC returned " + statusCode + " " + statusMessage;
158                 logError(errMsg);
159                 return createResponse(statusCode, errMsg);
160             }
161
162             httpResponse = null;
163
164             if(null != method) {
165                 method.reset();
166             } else {
167                 LOGGER.debug("method is NULL:");
168             }
169
170             method = null;
171             return createResponse(statusCode, responseContent);
172
173         } catch(SocketTimeoutException | ConnectTimeoutException e) {
174             String errMsg = "Request to VFC timed out";
175             logError(errMsg, e);
176             return createResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg);
177
178         } catch(Exception e) {
179             String errMsg = "Error processing request to VFC";
180             logError(errMsg, e);
181             return createResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, errMsg);
182
183         } finally {
184             if(httpResponse != null) {
185                 try {
186                     EntityUtils.consume(httpResponse.getEntity());
187                 } catch(Exception e) {
188                     LOGGER.debug("Exception :", e);
189                 }
190             }
191
192             if(method != null) {
193                 try {
194                     method.reset();
195                 } catch(Exception e) {
196                     LOGGER.debug("Exception :", e);
197                 }
198             }
199         }
200     }
201
202     private static void logError(String errMsg, Throwable t) {
203         LOGGER.error(MessageEnum.RA_NS_EXC, VFC_ADAPTER, "", MsoLogger.ErrorCode.AvailabilityError, errMsg, t);
204     }
205
206     private static void logError(String errMsg) {
207         LOGGER.error(MessageEnum.RA_NS_EXC, VFC_ADAPTER, "", MsoLogger.ErrorCode.AvailabilityError, errMsg);
208     }
209
210     private static RestfulResponse createResponse(int statusCode, String content) {
211         RestfulResponse rsp = new RestfulResponse();
212         rsp.setStatus(statusCode);
213         rsp.setResponseContent(content);
214         return rsp;
215     }
216
217 }