Imp Modules refactored for the readthedocs
[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)
85           .setConnectTimeout(timeout).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       } else {
141         LOGGER.debug("method is NULL:");
142       }
143
144       method = null;
145
146       LOGGER.info(MessageEnum.RA_RESPONSE_FROM_SDNC, responseContent, "SDNC", "");
147       return createResponse(statusCode, responseContent);
148
149     } catch (SocketTimeoutException e) {
150       String errMsg = "Request to SDNC timed out";
151       logError(errMsg, e);
152       return createResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg);
153
154     } catch (ConnectTimeoutException e) {
155       String errMsg = "Request to SDNC timed out";
156       logError(errMsg, e);
157       return createResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg);
158
159     } catch (Exception e) {
160       String errMsg = "Error processing request to SDNC";
161       logError(errMsg, e);
162       return createResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, errMsg);
163
164     } finally {
165       if (httpResponse != null) {
166         try {
167           EntityUtils.consume(httpResponse.getEntity());
168         } catch (Exception e) {
169           LOGGER.debug("Exception :", e);
170         }
171       }
172
173       if (method != null) {
174         try {
175           method.reset();
176         } catch (Exception e) {
177           LOGGER.debug("Exception :", e);
178         }
179       }
180     }
181   }
182
183   private static void logError(String errMsg, Throwable t) {
184     LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError, errMsg,
185         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 }