2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
20 package org.openecomp.mso.adapters.vfc.util;
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;
29 import javax.servlet.http.HttpServletRequest;
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;
53 * utility to invoke restclient
56 * @version GSO 0.5 2016/9/3
58 public class RestfulUtil {
63 private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA);
65 private static final MsoAlarmLogger ALARMLOGGER = new MsoAlarmLogger();
67 private static final int DEFAULT_TIME_OUT = 60;
69 private RestfulUtil() {
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);
77 HttpRequestBase method = null;
78 HttpResponse httpResponse = null;
81 int timeout = DEFAULT_TIME_OUT;
83 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
84 .setConnectionRequestTimeout(timeout).build();
86 HttpClient client = HttpClientBuilder.create().build();
88 if("POST".equals(methodType)) {
89 HttpPost httpPost = new HttpPost(url);
90 httpPost.setConfig(requestConfig);
91 httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
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));
98 } else if("GET".equals(methodType)) {
99 HttpGet httpGet = new HttpGet(url);
100 httpGet.setConfig(requestConfig);
102 } else if("DELETE".equals(methodType)) {
103 HttpDelete httpDelete = new HttpDelete(url);
104 httpDelete.setConfig(requestConfig);
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);
116 httpResponse = client.execute(method);
118 String responseContent = null;
119 if(httpResponse.getEntity() != null) {
120 responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
123 int statusCode = httpResponse.getStatusLine().getStatusCode();
124 String statusMessage = httpResponse.getStatusLine().getReasonPhrase();
126 LOGGER.debug("VFC Response: " + statusCode + " " + statusMessage
127 + (responseContent == null ? "" : System.lineSeparator() + responseContent));
129 if(httpResponse.getStatusLine().getStatusCode() >= 300) {
130 String errMsg = "VFC returned " + statusCode + " " + statusMessage;
132 return CreateResponse(statusCode, errMsg);
140 LOGGER.info(MessageEnum.RA_RESPONSE_FROM_SDNC, responseContent, "SDNC", "");
141 return CreateResponse(statusCode, responseContent);
143 } catch(SocketTimeoutException e) {
144 String errMsg = "Request to SDNC timed out";
146 return CreateResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg);
148 } catch(ConnectTimeoutException e) {
149 String errMsg = "Request to SDNC timed out";
151 return CreateResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg);
153 } catch(Exception e) {
154 String errMsg = "Error processing request to SDNC";
156 return CreateResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, errMsg);
159 if(httpResponse != null) {
161 EntityUtils.consume(httpResponse.getEntity());
162 } catch(Exception e) {
170 } catch(Exception e) {
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);
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);
187 private static RestfulResponse CreateResponse(int statusCode, String content) {
188 RestfulResponse rsp = new RestfulResponse();
189 rsp.setStatus(statusCode);
190 rsp.setResponseContent(content);
198 public static String getRequestBody(HttpServletRequest request) {
200 StringBuilder stringBuilder = new StringBuilder();
201 BufferedReader bufferedReader = null;
203 InputStream inputStream = request.getInputStream();
204 if(inputStream != null) {
205 bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
206 char[] charBuffer = new char[128];
208 while((bytesRead = bufferedReader.read(charBuffer)) > 0)
209 stringBuilder.append(charBuffer, 0, bytesRead);
211 } catch(IOException ex) {
212 LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError,
213 "read inputStream buffer catch exception:", ex);
215 if(bufferedReader != null) {
217 bufferedReader.close();
218 } catch(IOException ex) {
219 LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError,
220 "close buffer catch exception:", ex);
225 body = stringBuilder.toString();