2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.mso.adapters.vfc.util;
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;
30 import javax.servlet.http.HttpServletRequest;
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;
54 * utility to invoke restclient
57 * @version ONAP Amsterdam Release 2017-9-6
59 public class RestfulUtil {
64 private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA);
66 private static final MsoAlarmLogger ALARMLOGGER = new MsoAlarmLogger();
68 private static final int DEFAULT_TIME_OUT = 60;
70 private RestfulUtil() {
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);
78 HttpRequestBase method = null;
79 HttpResponse httpResponse = null;
82 int timeout = DEFAULT_TIME_OUT;
84 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
85 .setConnectionRequestTimeout(timeout).build();
87 HttpClient client = HttpClientBuilder.create().build();
89 if("POST".equals(methodType)) {
90 HttpPost httpPost = new HttpPost(url);
91 httpPost.setConfig(requestConfig);
92 httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
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));
99 } else if("GET".equals(methodType)) {
100 HttpGet httpGet = new HttpGet(url);
101 httpGet.setConfig(requestConfig);
103 } else if("DELETE".equals(methodType)) {
104 HttpDelete httpDelete = new HttpDelete(url);
105 httpDelete.setConfig(requestConfig);
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);
117 httpResponse = client.execute(method);
119 String responseContent = null;
120 if(httpResponse.getEntity() != null) {
121 responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
124 int statusCode = httpResponse.getStatusLine().getStatusCode();
125 String statusMessage = httpResponse.getStatusLine().getReasonPhrase();
127 LOGGER.debug("VFC Response: " + statusCode + " " + statusMessage
128 + (responseContent == null ? "" : System.lineSeparator() + responseContent));
130 if(httpResponse.getStatusLine().getStatusCode() >= 300) {
131 String errMsg = "VFC returned " + statusCode + " " + statusMessage;
133 return createResponse(statusCode, errMsg);
142 LOGGER.debug("method is NULL:");
147 LOGGER.info(MessageEnum.RA_RESPONSE_FROM_SDNC, responseContent, "SDNC", "");
148 return createResponse(statusCode, responseContent);
150 } catch(SocketTimeoutException e) {
151 String errMsg = "Request to SDNC timed out";
153 return createResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg);
155 } catch(ConnectTimeoutException e) {
156 String errMsg = "Request to SDNC timed out";
158 return createResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg);
160 } catch(Exception e) {
161 String errMsg = "Error processing request to SDNC";
163 return createResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, errMsg);
166 if(httpResponse != null) {
168 EntityUtils.consume(httpResponse.getEntity());
169 } catch(Exception e) {
170 LOGGER.debug("Exception :",e);
177 } catch(Exception e) {
178 LOGGER.debug("Exception :",e);
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);
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);
194 private static RestfulResponse createResponse(int statusCode, String content) {
195 RestfulResponse rsp = new RestfulResponse();
196 rsp.setStatus(statusCode);
197 rsp.setResponseContent(content);
205 public static String getRequestBody(HttpServletRequest request) {
207 StringBuilder stringBuilder = new StringBuilder();
208 BufferedReader bufferedReader = null;
210 InputStream inputStream = request.getInputStream();
211 if(inputStream != null) {
212 bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
213 char[] charBuffer = new char[128];
215 while((bytesRead = bufferedReader.read(charBuffer)) > 0)
216 stringBuilder.append(charBuffer, 0, bytesRead);
218 } catch(IOException ex) {
219 LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError,
220 "read inputStream buffer catch exception:", ex);
222 if(bufferedReader != null) {
224 bufferedReader.close();
225 } catch(IOException ex) {
226 LOGGER.error(MessageEnum.RA_NS_EXC, "VFC", "", MsoLogger.ErrorCode.AvailabilityError,
227 "close buffer catch exception:", ex);
232 body = stringBuilder.toString();