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