Add VF-C Adapter
[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  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.openecomp.mso.adapters.vfc.util;
21
22 import java.io.BufferedReader;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.InputStreamReader;
26 import java.net.HttpURLConnection;
27 import java.net.SocketTimeoutException;
28
29 import javax.servlet.http.HttpServletRequest;
30
31 import org.apache.http.HttpResponse;
32 import org.apache.http.client.HttpClient;
33 import org.apache.http.client.config.RequestConfig;
34 import org.apache.http.client.methods.HttpDelete;
35 import org.apache.http.client.methods.HttpGet;
36 import org.apache.http.client.methods.HttpPost;
37 import org.apache.http.client.methods.HttpPut;
38 import org.apache.http.client.methods.HttpRequestBase;
39 import org.apache.http.conn.ConnectTimeoutException;
40 import org.apache.http.entity.ContentType;
41 import org.apache.http.entity.StringEntity;
42 import org.apache.http.impl.client.HttpClientBuilder;
43 import org.apache.http.util.EntityUtils;
44 import org.openecomp.mso.adapters.vfc.model.RestfulResponse;
45 import org.openecomp.mso.logger.MessageEnum;
46 import org.openecomp.mso.logger.MsoAlarmLogger;
47 import org.openecomp.mso.logger.MsoLogger;
48
49 /**
50  * <br>
51  * <p>
52  * </p>
53  * utility to invoke restclient
54  * 
55  * @author
56  * @version GSO 0.5 2016/9/3
57  */
58 public class RestfulUtil {
59
60     /**
61      * Log service
62      */
63     private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA);
64
65     private static final MsoAlarmLogger ALARMLOGGER = new MsoAlarmLogger();
66
67     private static final int DEFAULT_TIME_OUT = 60;
68
69     private RestfulUtil() {
70
71     }
72
73     public static RestfulResponse send(String url, String methodType, String content) {
74         LOGGER.info(MessageEnum.RA_NS_EXC, url, "VFC", "");
75         LOGGER.debug("VFC Request Body:\n" + content);
76
77         HttpRequestBase method = null;
78         HttpResponse httpResponse = null;
79
80         try {
81             int timeout = DEFAULT_TIME_OUT;
82
83             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
84                     .setConnectionRequestTimeout(timeout).build();
85
86             HttpClient client = HttpClientBuilder.create().build();
87
88             if("POST".equals(methodType)) {
89                 HttpPost httpPost = new HttpPost(url);
90                 httpPost.setConfig(requestConfig);
91                 httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
92                 method = httpPost;
93             } else if("PUT".equals(methodType)) {
94                 HttpPut httpPut = new HttpPut(url);
95                 httpPut.setConfig(requestConfig);
96                 httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
97                 method = httpPut;
98             } else if("GET".equals(methodType)) {
99                 HttpGet httpGet = new HttpGet(url);
100                 httpGet.setConfig(requestConfig);
101                 method = httpGet;
102             } else if("DELETE".equals(methodType)) {
103                 HttpDelete httpDelete = new HttpDelete(url);
104                 httpDelete.setConfig(requestConfig);
105                 method = httpDelete;
106             }
107
108             // now VFC have no auth
109             // String userCredentials =
110             // SDNCAdapterProperties.getEncryptedProperty(Constants.SDNC_AUTH_PROP,
111             // Constants.DEFAULT_SDNC_AUTH, Constants.ENCRYPTION_KEY);
112             // String authorization = "Basic " +
113             // DatatypeConverter.printBase64Binary(userCredentials.getBytes());
114             // method.setHeader("Authorization", authorization);
115
116             httpResponse = client.execute(method);
117
118             String responseContent = null;
119             if(httpResponse.getEntity() != null) {
120                 responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
121             }
122
123             int statusCode = httpResponse.getStatusLine().getStatusCode();
124             String statusMessage = httpResponse.getStatusLine().getReasonPhrase();
125
126             LOGGER.debug("VFC Response: " + statusCode + " " + statusMessage
127                     + (responseContent == null ? "" : System.lineSeparator() + responseContent));
128
129             if(httpResponse.getStatusLine().getStatusCode() >= 300) {
130                 String errMsg = "VFC returned " + statusCode + " " + statusMessage;
131                 logError(errMsg);
132                 return CreateResponse(statusCode, errMsg);
133             }
134
135             httpResponse = null;
136
137             method.reset();
138             method = null;
139
140             LOGGER.info(MessageEnum.RA_RESPONSE_FROM_SDNC, responseContent, "SDNC", "");
141             return CreateResponse(statusCode, responseContent);
142
143         } catch(SocketTimeoutException e) {
144             String errMsg = "Request to SDNC timed out";
145             logError(errMsg, e);
146             return CreateResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg);
147
148         } catch(ConnectTimeoutException e) {
149             String errMsg = "Request to SDNC timed out";
150             logError(errMsg, e);
151             return CreateResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg);
152
153         } catch(Exception e) {
154             String errMsg = "Error processing request to SDNC";
155             logError(errMsg, e);
156             return CreateResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, errMsg);
157
158         } finally {
159             if(httpResponse != null) {
160                 try {
161                     EntityUtils.consume(httpResponse.getEntity());
162                 } catch(Exception e) {
163                     // Ignore
164                 }
165             }
166
167             if(method != null) {
168                 try {
169                     method.reset();
170                 } catch(Exception e) {
171                     // Ignore
172                 }
173             }
174         }
175     }
176
177     private static void logError(String errMsg, Throwable t) {
178         LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError, errMsg, t);
179         ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg);
180     }
181
182     private static void logError(String errMsg) {
183         LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError, errMsg);
184         ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg);
185     }
186
187     private static RestfulResponse CreateResponse(int statusCode, String content) {
188         RestfulResponse rsp = new RestfulResponse();
189         rsp.setStatus(statusCode);
190         rsp.setResponseContent(content);
191         return rsp;
192     }
193
194     /**
195      * @param request
196      * @return
197      */
198     public static String getRequestBody(HttpServletRequest request) {
199         String body = null;
200         StringBuilder stringBuilder = new StringBuilder();
201         BufferedReader bufferedReader = null;
202         try {
203             InputStream inputStream = request.getInputStream();
204             if(inputStream != null) {
205                 bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
206                 char[] charBuffer = new char[128];
207                 int bytesRead = -1;
208                 while((bytesRead = bufferedReader.read(charBuffer)) > 0)
209                     stringBuilder.append(charBuffer, 0, bytesRead);
210             }
211         } catch(IOException ex) {
212             LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError,
213                     "read inputStream buffer catch exception:", ex);
214         } finally {
215             if(bufferedReader != null) {
216                 try {
217                     bufferedReader.close();
218                 } catch(IOException ex) {
219                     LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError,
220                             "close buffer catch exception:", ex);
221                 }
222             }
223         }
224
225         body = stringBuilder.toString();
226         return body;
227     }
228
229 }