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