8e5f0b4274436f373c23d1c56cc003f53b2e86ef
[so.git] / adapters / mso-vfc-adapter / src / main / java / org / openecomp / mso / 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 package org.openecomp.mso.adapters.vfc.util;
22
23 import java.io.BufferedReader;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.InputStreamReader;
27 import java.net.HttpURLConnection;
28 import java.net.SocketTimeoutException;
29
30 import javax.servlet.http.HttpServletRequest;
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.openecomp.mso.adapters.vfc.model.RestfulResponse;
46 import org.openecomp.mso.logger.MessageEnum;
47 import org.openecomp.mso.logger.MsoAlarmLogger;
48 import org.openecomp.mso.logger.MsoLogger;
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 public class RestfulUtil {
60
61     /**
62      * Log service
63      */
64     private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA);
65
66     private static final MsoAlarmLogger ALARMLOGGER = new MsoAlarmLogger();
67
68     private static final int DEFAULT_TIME_OUT = 60;
69
70     private RestfulUtil() {
71
72     }
73
74     public static RestfulResponse send(String url, String methodType, String content) {
75         LOGGER.info(MessageEnum.RA_NS_EXC, url, "VFC", "");
76         LOGGER.debug("VFC Request Body:\n" + content);
77
78         HttpRequestBase method = null;
79         HttpResponse httpResponse = null;
80
81         try {
82             int timeout = DEFAULT_TIME_OUT;
83
84             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
85                     .setConnectionRequestTimeout(timeout).build();
86
87             HttpClient client = HttpClientBuilder.create().build();
88
89             if("POST".equals(methodType)) {
90                 HttpPost httpPost = new HttpPost(url);
91                 httpPost.setConfig(requestConfig);
92                 httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
93                 method = httpPost;
94             } else if("PUT".equals(methodType)) {
95                 HttpPut httpPut = new HttpPut(url);
96                 httpPut.setConfig(requestConfig);
97                 httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
98                 method = httpPut;
99             } else if("GET".equals(methodType)) {
100                 HttpGet httpGet = new HttpGet(url);
101                 httpGet.setConfig(requestConfig);
102                 method = httpGet;
103             } else if("DELETE".equals(methodType)) {
104                 HttpDelete httpDelete = new HttpDelete(url);
105                 httpDelete.setConfig(requestConfig);
106                 method = httpDelete;
107             }
108
109             // now VFC have no auth
110             // String userCredentials =
111             // SDNCAdapterProperties.getEncryptedProperty(Constants.SDNC_AUTH_PROP,
112             // Constants.DEFAULT_SDNC_AUTH, Constants.ENCRYPTION_KEY);
113             // String authorization = "Basic " +
114             // DatatypeConverter.printBase64Binary(userCredentials.getBytes());
115             // method.setHeader("Authorization", authorization);
116
117             httpResponse = client.execute(method);
118
119             String responseContent = null;
120             if(httpResponse.getEntity() != null) {
121                 responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
122             }
123
124             int statusCode = httpResponse.getStatusLine().getStatusCode();
125             String statusMessage = httpResponse.getStatusLine().getReasonPhrase();
126
127             LOGGER.debug("VFC Response: " + statusCode + " " + statusMessage
128                     + (responseContent == null ? "" : System.lineSeparator() + responseContent));
129
130             if(httpResponse.getStatusLine().getStatusCode() >= 300) {
131                 String errMsg = "VFC returned " + statusCode + " " + statusMessage;
132                 logError(errMsg);
133                 return createResponse(statusCode, errMsg);
134             }
135
136             httpResponse = null;
137
138             if(null != method) {
139                 method.reset();
140             }
141             else {
142                 LOGGER.debug("method is NULL:");
143             }
144             
145             method = null;
146
147             LOGGER.info(MessageEnum.RA_RESPONSE_FROM_SDNC, responseContent, "SDNC", "");
148             return createResponse(statusCode, responseContent);
149
150         } catch(SocketTimeoutException e) {
151             String errMsg = "Request to SDNC timed out";
152             logError(errMsg, e);
153             return createResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg);
154
155         } catch(ConnectTimeoutException e) {
156             String errMsg = "Request to SDNC timed out";
157             logError(errMsg, e);
158             return createResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg);
159
160         } catch(Exception e) {
161             String errMsg = "Error processing request to SDNC";
162             logError(errMsg, e);
163             return createResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, errMsg);
164
165         } finally {
166             if(httpResponse != null) {
167                 try {
168                     EntityUtils.consume(httpResponse.getEntity());
169                 } catch(Exception e) {
170                         LOGGER.debug("Exception :",e);
171                 }
172             }
173
174             if(method != null) {
175                 try {
176                     method.reset();
177                 } catch(Exception e) {
178                         LOGGER.debug("Exception :",e);
179                 }
180             }
181         }
182     }
183
184     private static void logError(String errMsg, Throwable t) {
185         LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError, errMsg, t);
186         ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg);
187     }
188
189     private static void logError(String errMsg) {
190         LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError, errMsg);
191         ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg);
192     }
193
194     private static RestfulResponse createResponse(int statusCode, String content) {
195         RestfulResponse rsp = new RestfulResponse();
196         rsp.setStatus(statusCode);
197         rsp.setResponseContent(content);
198         return rsp;
199     }
200
201     /**
202      * @param request
203      * @return
204      */
205     public static String getRequestBody(HttpServletRequest request) {
206         String body = null;
207         StringBuilder stringBuilder = new StringBuilder();
208         BufferedReader bufferedReader = null;
209         try {
210             InputStream inputStream = request.getInputStream();
211             if(inputStream != null) {
212                 bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
213                 char[] charBuffer = new char[128];
214                 int bytesRead = -1;
215                 while((bytesRead = bufferedReader.read(charBuffer)) > 0)
216                     stringBuilder.append(charBuffer, 0, bytesRead);
217             }
218         } catch(IOException ex) {
219             LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError,
220                     "read inputStream buffer catch exception:", ex);
221         } finally {
222             if(bufferedReader != null) {
223                 try {
224                     bufferedReader.close();
225                 } catch(IOException ex) {
226                     LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError,
227                             "close buffer catch exception:", ex);
228                 }
229             }
230         }
231
232         body = stringBuilder.toString();
233         return body;
234     }
235
236 }