Merge "Reorder modifiers"
[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.MsoAlarmLogger;
42 import org.openecomp.mso.properties.MsoPropertiesException;
43 import org.openecomp.mso.properties.MsoPropertiesFactory;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
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 Logger LOGGER =  LoggerFactory.getLogger(RestfulUtil.class);
62
63     private static final MsoAlarmLogger ALARMLOGGER = new MsoAlarmLogger();
64
65     private static final int DEFAULT_TIME_OUT = 60000;
66     
67     private static final String ONAP_IP = "ONAP_IP";
68     
69     private static final String DEFAULT_MSB_IP = "127.0.0.1";
70
71     private static final String DEFAULT_MSB_PORT = "80";
72
73     private static final MsoPropertiesFactory msoPropertiesFactory = new MsoPropertiesFactory();
74
75     public static String getMsbHost() {
76         String msbPort = DEFAULT_MSB_PORT;
77         // MSB_IP will be set as ONAP_IP environment parameter in install flow.
78         String msbIp = System.getenv().get(ONAP_IP);
79         try {
80             // if ONAP IP is not set. get it from config file.
81             if(null == msbIp || msbIp.isEmpty()) {
82                 msbIp = msoPropertiesFactory.getMsoJavaProperties("MSO_PROP_TOPOLOGY").getProperty("msb-ip", DEFAULT_MSB_IP);
83                 msbPort = msoPropertiesFactory.getMsoJavaProperties("MSO_PROP_TOPOLOGY").getProperty("msb-port", DEFAULT_MSB_PORT);
84             }
85         } catch(MsoPropertiesException e) {
86             LOGGER.error("Get msb properties failed",e);
87         }
88         return "http://" + msbIp + ":" + msbPort;
89     }
90
91     private RestfulUtil() {
92
93     }
94
95     public static RestfulResponse send(String url, String methodType, String content) {
96         String msbUrl = getMsbHost() + url;
97         LOGGER.info("Begin to sent message " + methodType +": " + msbUrl);
98
99         HttpRequestBase method = null;
100         HttpResponse httpResponse = null;
101
102         try {
103             int timeout = DEFAULT_TIME_OUT;
104
105             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
106                     .setConnectionRequestTimeout(timeout).build();
107
108             HttpClient client = HttpClientBuilder.create().build();
109
110             if("POST".equalsIgnoreCase(methodType)) {
111                 HttpPost httpPost = new HttpPost(msbUrl);
112                 httpPost.setConfig(requestConfig);
113                 httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
114                 method = httpPost;
115             } else if("PUT".equalsIgnoreCase(methodType)) {
116                 HttpPut httpPut = new HttpPut(msbUrl);
117                 httpPut.setConfig(requestConfig);
118                 httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON));
119                 method = httpPut;
120             } else if("GET".equalsIgnoreCase(methodType)) {
121                 HttpGet httpGet = new HttpGet(msbUrl);
122                 httpGet.setConfig(requestConfig);
123                 method = httpGet;
124             } else if("DELETE".equalsIgnoreCase(methodType)) {
125                 HttpDelete httpDelete = new HttpDelete(msbUrl);
126                 httpDelete.setConfig(requestConfig);
127                 method = httpDelete;
128             }
129
130             // now VFC have no auth
131             // String userCredentials =
132             // SDNCAdapterProperties.getEncryptedProperty(Constants.SDNC_AUTH_PROP,
133             // Constants.DEFAULT_SDNC_AUTH, Constants.ENCRYPTION_KEY);
134             // String authorization = "Basic " +
135             // DatatypeConverter.printBase64Binary(userCredentials.getBytes());
136             // method.setHeader("Authorization", authorization);
137
138             httpResponse = client.execute(method);
139
140             String responseContent = null;
141             if(httpResponse.getEntity() != null) {
142                 responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
143             }
144
145             int statusCode = httpResponse.getStatusLine().getStatusCode();
146             String statusMessage = httpResponse.getStatusLine().getReasonPhrase();
147
148             LOGGER.debug("VFC Response: " + statusCode + " " + statusMessage
149                     + (responseContent == null ? "" : System.lineSeparator() + responseContent));
150
151             if(httpResponse.getStatusLine().getStatusCode() >= 300) {
152                 String errMsg = "VFC returned " + statusCode + " " + statusMessage;
153                 logError(errMsg);
154                 return createResponse(statusCode, errMsg);
155             }
156
157             httpResponse = null;
158
159             if(null != method) {
160                 method.reset();
161             } else {
162                 LOGGER.debug("method is NULL:");
163             }
164
165             method = null;
166             return createResponse(statusCode, responseContent);
167
168         } catch(SocketTimeoutException | ConnectTimeoutException e) {
169             String errMsg = "Request to VFC timed out";
170             logError(errMsg, e);
171             return createResponse(HttpURLConnection.HTTP_CLIENT_TIMEOUT, errMsg);
172
173         } catch(Exception e) {
174             String errMsg = "Error processing request to VFC";
175             logError(errMsg, e);
176             return createResponse(HttpURLConnection.HTTP_INTERNAL_ERROR, errMsg);
177
178         } finally {
179             if(httpResponse != null) {
180                 try {
181                     EntityUtils.consume(httpResponse.getEntity());
182                 } catch(Exception e) {
183                     LOGGER.debug("Exception :", e);
184                 }
185             }
186
187             if(method != null) {
188                 try {
189                     method.reset();
190                 } catch(Exception e) {
191                     LOGGER.debug("Exception :", e);
192                 }
193             }
194         }
195     }
196
197     private static void logError(String errMsg, Throwable t) {
198         LOGGER.error(errMsg, t);
199         ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg);
200     }
201
202     private static void logError(String errMsg) {
203         LOGGER.error(errMsg);
204         ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, errMsg);
205     }
206
207     private static RestfulResponse createResponse(int statusCode, String content) {
208         RestfulResponse rsp = new RestfulResponse();
209         rsp.setStatus(statusCode);
210         rsp.setResponseContent(content);
211         return rsp;
212     }
213
214 }