Fix for SONAR critical issues
[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             method.reset();
139             method = null;
140
141             LOGGER.info(MessageEnum.RA_RESPONSE_FROM_SDNC, responseContent, "SDNC", "");
142             return CreateResponse(statusCode, responseContent);
143
144         } catch(SocketTimeoutException e) {
145             String errMsg = "Request to SDNC timed out";
146             logError(errMsg, e);
147             return CreateResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg);
148
149         } catch(ConnectTimeoutException e) {
150             String errMsg = "Request to SDNC timed out";
151             logError(errMsg, e);
152             return CreateResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg);
153
154         } catch(Exception e) {
155             String errMsg = "Error processing request to SDNC";
156             logError(errMsg, e);
157             return CreateResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, errMsg);
158
159         } finally {
160             if(httpResponse != null) {
161                 try {
162                     EntityUtils.consume(httpResponse.getEntity());
163                 } catch(Exception e) {
164                         LOGGER.debug("Exception :",e);
165                 }
166             }
167
168             if(method != null) {
169                 try {
170                     method.reset();
171                 } catch(Exception e) {
172                         LOGGER.debug("Exception :",e);
173                 }
174             }
175         }
176     }
177
178     private static void logError(String errMsg, Throwable t) {
179         LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError, errMsg, t);
180         ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg);
181     }
182
183     private static void logError(String errMsg) {
184         LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError, errMsg);
185         ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg);
186     }
187
188     private static RestfulResponse CreateResponse(int statusCode, String content) {
189         RestfulResponse rsp = new RestfulResponse();
190         rsp.setStatus(statusCode);
191         rsp.setResponseContent(content);
192         return rsp;
193     }
194
195     /**
196      * @param request
197      * @return
198      */
199     public static String getRequestBody(HttpServletRequest request) {
200         String body = null;
201         StringBuilder stringBuilder = new StringBuilder();
202         BufferedReader bufferedReader = null;
203         try {
204             InputStream inputStream = request.getInputStream();
205             if(inputStream != null) {
206                 bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
207                 char[] charBuffer = new char[128];
208                 int bytesRead = -1;
209                 while((bytesRead = bufferedReader.read(charBuffer)) > 0)
210                     stringBuilder.append(charBuffer, 0, bytesRead);
211             }
212         } catch(IOException ex) {
213             LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError,
214                     "read inputStream buffer catch exception:", ex);
215         } finally {
216             if(bufferedReader != null) {
217                 try {
218                     bufferedReader.close();
219                 } catch(IOException ex) {
220                     LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError,
221                             "close buffer catch exception:", ex);
222                 }
223             }
224         }
225
226         body = stringBuilder.toString();
227         return body;
228     }
229
230 }