e26f76f494017a32831a1ca4f9ed2f6451c1ab0d
[vfc/nfvo/driver/vnfm/svnfm.git] / huawei / vnfmadapter / VnfmadapterService / service / src / main / java / org / onap / vfc / nfvo / vnfm / svnfm / vnfmadapter / service / csm / connect / HttpRequests.java
1 /*
2  * Copyright 2016-2017 Huawei Technologies Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.vfc.nfvo.vnfm.svnfm.vnfmadapter.service.csm.connect;
18
19 import java.io.IOException;
20 import java.io.UnsupportedEncodingException;
21 import java.util.ArrayList;
22 import java.util.List;
23
24 import javax.net.ssl.SSLHandshakeException;
25
26 import org.apache.commons.httpclient.Header;
27 import org.apache.commons.httpclient.HttpClient;
28 import org.apache.commons.httpclient.HttpMethod;
29 import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
30 import org.apache.commons.httpclient.methods.DeleteMethod;
31 import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
32 import org.apache.commons.httpclient.methods.GetMethod;
33 import org.apache.commons.httpclient.methods.PostMethod;
34 import org.apache.commons.httpclient.methods.PutMethod;
35 import org.apache.commons.httpclient.methods.StringRequestEntity;
36 import org.apache.commons.httpclient.protocol.Protocol;
37 import org.apache.commons.lang.StringUtils;
38 import org.onap.vfc.nfvo.vnfm.svnfm.vnfmadapter.common.VnfmException;
39 import org.onap.vfc.nfvo.vnfm.svnfm.vnfmadapter.service.constant.Constant;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.springframework.http.HttpRequest;
43
44 /**
45  * HTTP Request class.</br>
46  *
47  * @author
48  * @version VFC 1.0 Sep 14, 2016
49  */
50 public final class HttpRequests {
51
52     private static final Logger LOG = LoggerFactory.getLogger(HttpRequest.class);
53
54     private static MultiThreadedHttpConnectionManager httpClientMgr;
55
56     private static final int PORT = 31943;
57
58     private HttpRequests() {
59         // constructor
60     }
61
62     static {
63         httpClientMgr = new MultiThreadedHttpConnectionManager();
64         httpClientMgr.getParams().setStaleCheckingEnabled(true);
65         httpClientMgr.getParams().setMaxTotalConnections(20);
66         httpClientMgr.getParams().setDefaultMaxConnectionsPerHost(100);
67     }
68
69     /**
70      * Request builder.</br>
71      *
72      * @author
73      * @version VFC 1.0 Sep 14, 2016
74      */
75     public static class Builder {
76
77         private final List<Header> headers = new ArrayList<>(10);
78
79         private String paramsJson;
80
81         private HttpClient client;
82
83         private HttpMethod httpMethod;
84
85         private String encoding;
86
87         private String url;
88
89         private String authenticateMode;
90
91         /**
92          * Constructor<br>
93          *
94          * @param authenticateMode
95          * @since VFC 1.0
96          */
97         public Builder(String authenticateMode) {
98             this.authenticateMode = authenticateMode;
99             client = new HttpClient(httpClientMgr);
100             client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
101             client.getHttpConnectionManager().getParams().setSoTimeout(30000);
102             encoding = Constant.ENCODEING;
103         }
104
105         /**
106          * Add header
107          * <br>
108          *
109          * @param name
110          * @param value
111          * @return
112          * @since VFC 1.0
113          */
114         public Builder addHeader(String name, String value) {
115             headers.add(new Header(name, value));
116             return this;
117         }
118
119         /**
120          * Add headers
121          * <br>
122          *
123          * @param header
124          * @param headers
125          * @return
126          * @since VFC 1.0
127          */
128         public Builder addHeaders(Header header, Header... headers) {
129             if(header != null) {
130                 this.headers.add(header);
131             }
132             if(headers != null && headers.length > 0) {
133                 for(Header h : headers) {
134                     this.headers.add(h);
135                 }
136             }
137             return this;
138         }
139
140         /**
141          * Add headers
142          * <br>
143          *
144          * @param headers
145          * @return
146          * @since VFC 1.0
147          */
148         public Builder addHeaders(List<Header> headers) {
149             if(headers != null && !headers.isEmpty()) {
150                 this.headers.addAll(headers);
151             }
152             return this;
153         }
154
155         /**
156          * Update URL
157          * <br>
158          *
159          * @param url
160          * @param path
161          * @return
162          * @throws VnfmException
163          * @since VFC 1.0
164          */
165         public Builder setUrl(String url, String path) throws VnfmException {
166             if(StringUtils.isEmpty(url)) {
167                 throw new VnfmException("com.huawei.nfvo.vcmmadapter.fusionsphere.check.httprequest.url");
168             }
169
170             this.url = url + path;
171
172             LOG.info("setUrl: url =" + url);
173
174             Protocol.registerProtocol(Constant.HTTPS,
175                     new Protocol(Constant.HTTPS, SslProtocolSocketFactory.getInstance().get(authenticateMode), PORT));
176
177             return this;
178         }
179
180         /**
181          * Update URL
182          * <br>
183          *
184          * @param url
185          * @param path
186          * @param defPort
187          * @return
188          * @throws VnfmException
189          * @since VFC 1.0
190          */
191         public Builder setUrl(String url, String path, int defPort) throws VnfmException {
192             if(StringUtils.isEmpty(url)) {
193                 throw new VnfmException("com.huawei.nfvo.vcmmadapter.fusionsphere.check.httprequest.url");
194             }
195
196             this.url = url + path;
197
198             LOG.info("setUrl: url =" + url);
199
200             Protocol.registerProtocol(Constant.HTTPS, new Protocol(Constant.HTTPS,
201                     SslProtocolSocketFactory.getInstance().get(authenticateMode), defPort));
202
203             return this;
204         }
205
206         /**
207          * HTTP POST
208          * <br>
209          *
210          * @return
211          * @since VFC 1.0
212          */
213         public Builder post() {
214             this.httpMethod = new PostMethod(url);
215             return this;
216         }
217
218         /**
219          * HTTP GET
220          * <br>
221          *
222          * @return
223          * @since VFC 1.0
224          */
225         public Builder get() {
226             this.httpMethod = new GetMethod(url);
227             return this;
228         }
229
230         /**
231          * HTTP PUT
232          * <br>
233          *
234          * @return
235          * @since VFC 1.0
236          */
237         public Builder put() {
238             this.httpMethod = new PutMethod(url);
239             return this;
240         }
241
242         /**
243          * HTTP DELETE
244          * <br>
245          *
246          * @return
247          * @since VFC 1.0
248          */
249         public Builder delete() {
250             this.httpMethod = new DeleteMethod(url);
251             return this;
252         }
253
254         /**
255          * Update Params
256          * <br>
257          *
258          * @param json
259          * @return
260          * @since VFC 1.0
261          */
262         public Builder setParams(String json) {
263             this.paramsJson = json;
264             return this;
265         }
266
267         /**
268          * Set the encoding
269          * <br>
270          *
271          * @param encode
272          * @return
273          * @since VFC 1.0
274          */
275         public Builder setEncoding(String encode) {
276             this.encoding = encode;
277             return this;
278         }
279
280         /**
281          * Make HTTP request
282          * <br>
283          *
284          * @return
285          * @since VFC 1.0
286          */
287         public String request() {
288             String result = null;
289             try {
290                 result = executeMethod().getResponseBodyAsString();
291             } catch(SSLHandshakeException e) {
292                 LOG.error(String.format("function=request, msg=http request url: %s, SSLHandshake Fail : ", url), e);
293                 try {
294                     LOG.error("function=request, msg=SSLHandshake Fail, start refresh certificate ...");
295                     SslProtocolSocketFactory socketFactory = SslProtocolSocketFactory.getInstance();
296                     socketFactory.refresh(authenticateMode);
297                     Protocol.registerProtocol(Constant.HTTPS, new Protocol(Constant.HTTPS,
298                             SslProtocolSocketFactory.getInstance().get(authenticateMode), PORT));
299                     LOG.error("function=request, msg=SSLHandshake Fail, certificate refresh successful .");
300
301                     result = executeMethod().getResponseBodyAsString();
302                 } catch(IOException ioe) {
303                     LOG.error(String.format("function=request, IOException msg=http request url: %s, error: ", url),
304                             ioe);
305                 } catch(VnfmException ose) {
306                     LOG.error(String.format("function=request, VnfmException msg=http request url: %s, error: ", url),
307                             ose);
308                 }
309             } catch(IOException | VnfmException e) {
310                 LOG.error(String.format("function=request, IOException msg=http request url: %s, error: ", url), e);
311             } finally {
312                 httpMethod.releaseConnection();
313             }
314             return result;
315         }
316
317         /**
318          * Execute the HTTP method
319          * <br>
320          *
321          * @return
322          * @throws VnfmException
323          * @throws IOException
324          * @since VFC 1.0
325          */
326         public HttpMethod execute() throws VnfmException, IOException {
327             try {
328                 executeMethod();
329             } catch(SSLHandshakeException e) {
330                 LOG.error(String.format("function=execute, msg=http request url: %s, SSLHandshake Fail : ", url), e);
331                 LOG.error("function=execute, SSLHandshake Fail, start refresh certificate ...");
332                 SslProtocolSocketFactory socketFactory = SslProtocolSocketFactory.getInstance();
333                 socketFactory.refresh(authenticateMode);
334                 Protocol.registerProtocol(Constant.HTTPS, new Protocol(Constant.HTTPS,
335                         SslProtocolSocketFactory.getInstance().get(authenticateMode), PORT));
336                 LOG.error("function=execute, SSLHandshake Fail, certificate refresh successful .");
337
338                 executeMethod();
339             }
340             return httpMethod;
341         }
342
343         private HttpMethod executeMethod() throws VnfmException, IOException {
344             if(httpMethod == null) {
345                 httpMethod = new GetMethod(url);
346             }
347
348             handleParams();
349
350             client.executeMethod(httpMethod);
351
352             return httpMethod;
353         }
354
355         private void handleParams() throws UnsupportedEncodingException {
356             if(paramsJson != null && !paramsJson.isEmpty()) {
357                 StringRequestEntity stringRequestEntity =
358                         new StringRequestEntity(paramsJson, "application/json", encoding);
359                 String contentLengthString = String.valueOf(stringRequestEntity.getContentLength());
360
361                 if(httpMethod instanceof PostMethod || httpMethod instanceof PutMethod) {
362                     ((EntityEnclosingMethod)httpMethod).setRequestEntity(stringRequestEntity);
363                     ((EntityEnclosingMethod)httpMethod).addRequestHeader("Content-Length", contentLengthString);
364                 } else {
365                     httpMethod.setQueryString(paramsJson);
366                 }
367                 addHeader("Content-Type", String.format("application/json;charset=%s", encoding));
368             }
369
370             for(Header header : headers) {
371                 httpMethod.addRequestHeader(header);
372             }
373         }
374     }
375
376 }