7690d806090b223ab7d8f8cfeb28a313fe3809a9
[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
22 package org.openecomp.mso.adapters.vfc.util;
23
24 import java.net.HttpURLConnection;
25 import java.net.SocketTimeoutException;
26
27 import org.apache.http.HttpResponse;
28 import org.apache.http.client.HttpClient;
29 import org.apache.http.client.config.RequestConfig;
30 import org.apache.http.client.methods.HttpDelete;
31 import org.apache.http.client.methods.HttpGet;
32 import org.apache.http.client.methods.HttpPost;
33 import org.apache.http.client.methods.HttpPut;
34 import org.apache.http.client.methods.HttpRequestBase;
35 import org.apache.http.conn.ConnectTimeoutException;
36 import org.apache.http.entity.ContentType;
37 import org.apache.http.entity.StringEntity;
38 import org.apache.http.impl.client.HttpClientBuilder;
39 import org.apache.http.util.EntityUtils;
40 import org.openecomp.mso.adapters.vfc.model.RestfulResponse;
41 import org.openecomp.mso.logger.MessageEnum;
42 import org.openecomp.mso.logger.MsoAlarmLogger;
43 import org.openecomp.mso.logger.MsoLogger;
44 import org.openecomp.mso.properties.MsoPropertiesException;
45 import org.openecomp.mso.properties.MsoPropertiesFactory;
46
47 /**
48  * <br>
49  * <p>
50  * </p>
51  * utility to invoke restclient
52  * 
53  * @author
54  * @version ONAP Amsterdam Release 2017-9-6
55  */
56 public class RestfulUtil {
57
58     /**
59      * Log service
60      */
61     private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA);
62
63     private static final MsoAlarmLogger ALARMLOGGER = new MsoAlarmLogger();
64
65     private static final int DEFAULT_TIME_OUT = 60000;
66
67     private static final MsoPropertiesFactory msoPropertiesFactory = new MsoPropertiesFactory();
68
69     public static String getMsbHost() {
70         String msbIp = "10.229.32.131";
71         String msbPort = "8090";
72         try {
73             msbIp = msoPropertiesFactory.getMsoJavaProperties("MSO_PROP_TOPOLOGY").getProperty("msb-ip",
74                     "10.229.32.131");
75             msbPort = msoPropertiesFactory.getMsoJavaProperties("MSO_PROP_TOPOLOGY").getProperty("msb-port", "8099");
76
77         } catch(MsoPropertiesException e) {
78             LOGGER.error(MessageEnum.RA_NS_EXC, "VFC Adapter", "", MsoLogger.ErrorCode.AvailabilityError,
79                     "Get msb properties failed");
80             e.printStackTrace();
81         }
82         return "http://" + msbIp + ":" + msbPort;
83     }
84
85     private RestfulUtil() {
86
87     }
88
89     public static RestfulResponse send(String url, String methodType, String content) {
90         String msbUrl = getMsbHost() + url;
91         LOGGER.info(MessageEnum.RA_NS_EXC, "Begin to sent message " + methodType +": " + msbUrl, "org.openecomp.mso.adapters.vfc.util.RestfulUtil","VFC Adapter");
92
93         HttpRequestBase method = null;
94         HttpResponse httpResponse = null;
95
96         try {
97             int timeout = DEFAULT_TIME_OUT;
98
99             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
100                     .setConnectionRequestTimeout(timeout).build();
101
102             HttpClient client = HttpClientBuilder.create().build();
103
104             if("POST".equals(methodType.toUpperCase())) {
105                 HttpPost httpPost = new HttpPost(msbUrl);
106                 httpPost.setConfig(requestConfig);
107                 httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
108                 method = httpPost;
109             } else if("PUT".equals(methodType.toUpperCase())) {
110                 HttpPut httpPut = new HttpPut(msbUrl);
111                 httpPut.setConfig(requestConfig);
112                 httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
113                 method = httpPut;
114             } else if("GET".equals(methodType.toUpperCase())) {
115                 HttpGet httpGet = new HttpGet(msbUrl);
116                 httpGet.setConfig(requestConfig);
117                 method = httpGet;
118             } else if("DELETE".equals(methodType.toUpperCase())) {
119                 HttpDelete httpDelete = new HttpDelete(msbUrl);
120                 httpDelete.setConfig(requestConfig);
121                 method = httpDelete;
122             }
123
124             // now VFC have no auth
125             // String userCredentials =
126             // SDNCAdapterProperties.getEncryptedProperty(Constants.SDNC_AUTH_PROP,
127             // Constants.DEFAULT_SDNC_AUTH, Constants.ENCRYPTION_KEY);
128             // String authorization = "Basic " +
129             // DatatypeConverter.printBase64Binary(userCredentials.getBytes());
130             // method.setHeader("Authorization", authorization);
131
132             httpResponse = client.execute(method);
133
134             String responseContent = null;
135             if(httpResponse.getEntity() != null) {
136                 responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
137             }
138
139             int statusCode = httpResponse.getStatusLine().getStatusCode();
140             String statusMessage = httpResponse.getStatusLine().getReasonPhrase();
141
142             LOGGER.debug("VFC Response: " + statusCode + " " + statusMessage
143                     + (responseContent == null ? "" : System.lineSeparator() + responseContent));
144
145             if(httpResponse.getStatusLine().getStatusCode() >= 300) {
146                 String errMsg = "VFC returned " + statusCode + " " + statusMessage;
147                 logError(errMsg);
148                 return createResponse(statusCode, errMsg);
149             }
150
151             httpResponse = null;
152
153             if(null != method) {
154                 method.reset();
155             } else {
156                 LOGGER.debug("method is NULL:");
157             }
158
159             method = null;
160             return createResponse(statusCode, responseContent);
161
162         } catch(SocketTimeoutException e) {
163             String errMsg = "Request to VFC timed out";
164             logError(errMsg, e);
165             return createResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg);
166
167         } catch(ConnectTimeoutException e) {
168             String errMsg = "Request to VFC timed out";
169             logError(errMsg, e);
170             return createResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg);
171
172         } catch(Exception e) {
173             String errMsg = "Error processing request to VFC";
174             logError(errMsg, e);
175             return createResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, errMsg);
176
177         } finally {
178             if(httpResponse != null) {
179                 try {
180                     EntityUtils.consume(httpResponse.getEntity());
181                 } catch(Exception e) {
182                     LOGGER.debug("Exception :", e);
183                 }
184             }
185
186             if(method != null) {
187                 try {
188                     method.reset();
189                 } catch(Exception e) {
190                     LOGGER.debug("Exception :", e);
191                 }
192             }
193         }
194     }
195
196     private static void logError(String errMsg, Throwable t) {
197         LOGGER.error(MessageEnum.RA_NS_EXC, "VFC Adapter", "", MsoLogger.ErrorCode.AvailabilityError, errMsg, t);
198         ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg);
199     }
200
201     private static void logError(String errMsg) {
202         LOGGER.error(MessageEnum.RA_NS_EXC, "VFC Adapter", "", MsoLogger.ErrorCode.AvailabilityError, errMsg);
203         ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg);
204     }
205
206     private static RestfulResponse createResponse(int statusCode, String content) {
207         RestfulResponse rsp = new RestfulResponse();
208         rsp.setStatus(statusCode);
209         rsp.setResponseContent(content);
210         return rsp;
211     }
212
213 }