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=========================================================
22 package org.onap.so.adapters.vfc.util;
24 import java.net.HttpURLConnection;
25 import java.net.SocketTimeoutException;
27 import javax.ws.rs.core.UriBuilder;
29 import org.apache.http.HttpResponse;
30 import org.apache.http.client.HttpClient;
31 import org.apache.http.client.config.RequestConfig;
32 import org.apache.http.client.methods.HttpDelete;
33 import org.apache.http.client.methods.HttpGet;
34 import org.apache.http.client.methods.HttpPost;
35 import org.apache.http.client.methods.HttpPut;
36 import org.apache.http.client.methods.HttpRequestBase;
37 import org.apache.http.conn.ConnectTimeoutException;
38 import org.apache.http.entity.ContentType;
39 import org.apache.http.entity.StringEntity;
40 import org.apache.http.impl.client.HttpClientBuilder;
41 import org.apache.http.util.EntityUtils;
42 import org.onap.so.adapters.vfc.model.RestfulResponse;
43 import org.onap.so.logger.MessageEnum;
44 import org.onap.so.logger.MsoAlarmLogger;
45 import org.onap.so.logger.MsoLogger;
46 import org.springframework.beans.factory.annotation.Autowired;
47 import org.springframework.core.env.Environment;
48 import org.springframework.stereotype.Component;
54 * utility to invoke restclient
57 * @version ONAP Amsterdam Release 2017-9-6
60 public class RestfulUtil {
65 private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, RestfulUtil.class);
67 private static final MsoAlarmLogger ALARMLOGGER = new MsoAlarmLogger();
69 private static final int DEFAULT_TIME_OUT = 60000;
71 private static final String ONAP_IP = "ONAP_IP";
73 private static final String DEFAULT_MSB_IP = "127.0.0.1";
75 private static final Integer DEFAULT_MSB_PORT = 80;
78 private Environment env;
80 public String getMsbHost() {
81 // MSB_IP will be set as ONAP_IP environment parameter in install flow.
82 String msbIp = System.getenv().get(ONAP_IP);
83 // if ONAP IP is not set. get it from config file.
84 if(null == msbIp || msbIp.isEmpty()) {
85 msbIp = env.getProperty("mso.msb-ip", DEFAULT_MSB_IP);
87 Integer msbPort = env.getProperty("mso.msb-port", Integer.class, DEFAULT_MSB_PORT);
89 return UriBuilder.fromPath("").host(msbIp).port(msbPort).scheme("http").build().toString();
92 private RestfulUtil() {
96 public RestfulResponse send(String url, String methodType, String content) {
97 String msbUrl = getMsbHost() + url;
98 LOGGER.info(MessageEnum.RA_NS_EXC, "Begin to sent message " + methodType +": " + msbUrl, "org.onap.so.adapters.vfc.util.RestfulUtil","VFC Adapter");
100 HttpRequestBase method = null;
101 HttpResponse httpResponse = null;
104 int timeout = DEFAULT_TIME_OUT;
106 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
107 .setConnectionRequestTimeout(timeout).build();
109 HttpClient client = HttpClientBuilder.create().build();
111 if("POST".equalsIgnoreCase(methodType)) {
112 HttpPost httpPost = new HttpPost(msbUrl);
113 httpPost.setConfig(requestConfig);
114 httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
116 } else if("PUT".equalsIgnoreCase(methodType)) {
117 HttpPut httpPut = new HttpPut(msbUrl);
118 httpPut.setConfig(requestConfig);
119 httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
121 } else if("GET".equalsIgnoreCase(methodType)) {
122 HttpGet httpGet = new HttpGet(msbUrl);
123 httpGet.setConfig(requestConfig);
125 } else if("DELETE".equalsIgnoreCase(methodType)) {
126 HttpDelete httpDelete = new HttpDelete(msbUrl);
127 httpDelete.setConfig(requestConfig);
131 // now VFC have no auth
132 // String userCredentials =
133 // SDNCAdapterProperties.getEncryptedProperty(Constants.SDNC_AUTH_PROP,
134 // Constants.DEFAULT_SDNC_AUTH, Constants.ENCRYPTION_KEY);
135 // String authorization = "Basic " +
136 // DatatypeConverter.printBase64Binary(userCredentials.getBytes());
137 // method.setHeader("Authorization", authorization);
139 httpResponse = client.execute(method);
141 String responseContent = null;
142 if(httpResponse.getEntity() != null) {
143 responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
146 int statusCode = httpResponse.getStatusLine().getStatusCode();
147 String statusMessage = httpResponse.getStatusLine().getReasonPhrase();
149 LOGGER.debug("VFC Response: " + statusCode + " " + statusMessage
150 + (responseContent == null ? "" : System.lineSeparator() + responseContent));
152 if(httpResponse.getStatusLine().getStatusCode() >= 300) {
153 String errMsg = "VFC returned " + statusCode + " " + statusMessage;
155 return createResponse(statusCode, errMsg);
163 LOGGER.debug("method is NULL:");
167 return createResponse(statusCode, responseContent);
169 } catch(SocketTimeoutException | ConnectTimeoutException e) {
170 String errMsg = "Request to VFC timed out";
172 return createResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg);
174 } catch(Exception e) {
175 String errMsg = "Error processing request to VFC";
177 return createResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, errMsg);
180 if(httpResponse != null) {
182 EntityUtils.consume(httpResponse.getEntity());
183 } catch(Exception e) {
184 LOGGER.debug("Exception :", e);
191 } catch(Exception e) {
192 LOGGER.debug("Exception :", e);
198 private static void logError(String errMsg, Throwable t) {
199 LOGGER.error(MessageEnum.RA_NS_EXC, "VFC Adapter", "", MsoLogger.ErrorCode.AvailabilityError, errMsg, t);
200 ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg);
203 private static void logError(String errMsg) {
204 LOGGER.error(MessageEnum.RA_NS_EXC, "VFC Adapter", "", MsoLogger.ErrorCode.AvailabilityError, errMsg);
205 ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg);
208 private static RestfulResponse createResponse(int statusCode, String content) {
209 RestfulResponse rsp = new RestfulResponse();
210 rsp.setStatus(statusCode);
211 rsp.setResponseContent(content);