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