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