Change: add OPEN-O seed code for VF-C
[vfc/nfvo/driver/vnfm/svnfm.git] / huawei / vnfmadapter / VnfmadapterService / service / src / main / java / org / openo / nfvo / vnfmadapter / service / csm / connect / HttpRequests.java
1 /*
2  * Copyright 2016 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.openo.nfvo.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.openo.nfvo.vnfmadapter.common.VnfmException;
39 import org.openo.nfvo.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     NFVO 0.5  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     NFVO 0.5  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          *
93          * Constructor<br>
94          *
95          * @param authenticateMode
96          * @since  NFVO 0.5
97          */
98         public Builder(String authenticateMode) {
99             this.authenticateMode = authenticateMode;
100             client = new HttpClient(httpClientMgr);
101             client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
102             client.getHttpConnectionManager().getParams().setSoTimeout(30000);
103             encoding = Constant.ENCODEING;
104         }
105
106         /**
107          * Add header
108          * <br>
109          *
110          * @param name
111          * @param value
112          * @return
113          * @since  NFVO 0.5
114          */
115         public Builder addHeader(String name, String value) {
116             headers.add(new Header(name, value));
117             return this;
118         }
119
120         /**
121          * Add headers
122          * <br>
123          *
124          * @param header
125          * @param headers
126          * @return
127          * @since  NFVO 0.5
128          */
129         public Builder addHeaders(Header header, Header... headers) {
130             if(header != null) {
131                 this.headers.add(header);
132             }
133             if(headers != null && headers.length > 0) {
134                 for(Header h : headers) {
135                     this.headers.add(h);
136                 }
137             }
138             return this;
139         }
140
141         /**
142          * Add headers
143          * <br>
144          *
145          * @param headers
146          * @return
147          * @since  NFVO 0.5
148          */
149         public Builder addHeaders(List<Header> headers) {
150             if(headers != null && !headers.isEmpty()) {
151                 this.headers.addAll(headers);
152             }
153             return this;
154         }
155
156         /**
157          * Update URL
158          * <br>
159          *
160          * @param url
161          * @param path
162          * @return
163          * @throws VnfmException
164          * @since  NFVO 0.5
165          */
166         public Builder setUrl(String url, String path) throws VnfmException {
167             if(StringUtils.isEmpty(url)) {
168                 throw new VnfmException("com.huawei.nfvo.vcmmadapter.fusionsphere.check.httprequest.url");
169             }
170
171             this.url = url + path;
172
173             LOG.info("setUrl: url =" + url);
174
175             Protocol.registerProtocol("https",
176                     new Protocol("https", SslProtocolSocketFactory.getInstance().get(authenticateMode), PORT));
177
178             return this;
179         }
180
181         /**
182          * Update URL
183          * <br>
184          *
185          * @param url
186          * @param path
187          * @param defPort
188          * @return
189          * @throws VnfmException
190          * @since  NFVO 0.5
191          */
192         public Builder setUrl(String url, String path, int defPort) throws VnfmException {
193             if(StringUtils.isEmpty(url)) {
194                 throw new VnfmException("com.huawei.nfvo.vcmmadapter.fusionsphere.check.httprequest.url");
195             }
196
197             this.url = url + path;
198
199             LOG.info("setUrl: url =" + url);
200
201             Protocol.registerProtocol("https",
202                     new Protocol("https", SslProtocolSocketFactory.getInstance().get(authenticateMode), defPort));
203
204             return this;
205         }
206
207         /**
208          * HTTP POST
209          * <br>
210          *
211          * @return
212          * @since  NFVO 0.5
213          */
214         public Builder post() {
215             this.httpMethod = new PostMethod(url);
216             return this;
217         }
218
219         /**
220          * HTTP GET
221          * <br>
222          *
223          * @return
224          * @since  NFVO 0.5
225          */
226         public Builder get() {
227             this.httpMethod = new GetMethod(url);
228             return this;
229         }
230
231         /**
232          * HTTP PUT
233          * <br>
234          *
235          * @return
236          * @since  NFVO 0.5
237          */
238         public Builder put() {
239             this.httpMethod = new PutMethod(url);
240             return this;
241         }
242
243         /**
244          * HTTP DELETE
245          * <br>
246          *
247          * @return
248          * @since  NFVO 0.5
249          */
250         public Builder delete() {
251             this.httpMethod = new DeleteMethod(url);
252             return this;
253         }
254
255         /**
256          * Update Params
257          * <br>
258          *
259          * @param json
260          * @return
261          * @since  NFVO 0.5
262          */
263         public Builder setParams(String json) {
264             this.paramsJson = json;
265             return this;
266         }
267
268         /**
269          * Set the encoding
270          * <br>
271          *
272          * @param encode
273          * @return
274          * @since  NFVO 0.5
275          */
276         public Builder setEncoding(String encode) {
277             this.encoding = encode;
278             return this;
279         }
280
281         /**
282          * Make HTTP request
283          * <br>
284          *
285          * @return
286          * @since  NFVO 0.5
287          */
288         public String request() {
289             String result = null;
290             try {
291                 result = executeMethod().getResponseBodyAsString();
292             } catch(SSLHandshakeException e) {
293                 LOG.error(String.format("function=request, msg=http request url: %s, SSLHandshake Fail : ", url), e);
294                 try {
295                     LOG.error("function=request, msg=SSLHandshake Fail, start refresh certificate ...");
296                     SslProtocolSocketFactory socketFactory = SslProtocolSocketFactory.getInstance();
297                     socketFactory.refresh(authenticateMode);
298                     Protocol.registerProtocol("https",
299                             new Protocol("https", SslProtocolSocketFactory.getInstance().get(authenticateMode), PORT));
300                     LOG.error("function=request, msg=SSLHandshake Fail, certificate refresh successful .");
301
302                     result = executeMethod().getResponseBodyAsString();
303                 } catch(IOException ioe) {
304                     LOG.error(String.format("function=request, msg=http request url: %s, error: ", url), ioe);
305                 } catch(VnfmException ose) {
306                     LOG.error(String.format("function=request, msg=http request url: %s, error: ", url), ose);
307                 }
308             } catch(IOException | VnfmException e) {
309                 LOG.error(String.format("function=request, msg=http request url: %s, error: ", url), e);
310             } finally {
311                 httpMethod.releaseConnection();
312             }
313             return result;
314         }
315
316         /**
317          * Execute the HTTP method
318          * <br>
319          *
320          * @return
321          * @throws VnfmException
322          * @throws IOException
323          * @since  NFVO 0.5
324          */
325         public HttpMethod execute() throws VnfmException, IOException {
326             try {
327                 executeMethod();
328             } catch(SSLHandshakeException e) {
329                 LOG.error(String.format("function=execute, msg=http request url: %s, SSLHandshake Fail : ", url), e);
330                 LOG.error("function=execute, SSLHandshake Fail, start refresh certificate ...");
331                 SslProtocolSocketFactory socketFactory = SslProtocolSocketFactory.getInstance();
332                 socketFactory.refresh(authenticateMode);
333                 Protocol.registerProtocol("https",
334                         new Protocol("https", SslProtocolSocketFactory.getInstance().get(authenticateMode), PORT));
335                 LOG.error("function=execute, SSLHandshake Fail, certificate refresh successful .");
336
337                 executeMethod();
338             }
339             return httpMethod;
340         }
341
342         private HttpMethod executeMethod() throws VnfmException, IOException {
343             if(httpMethod == null) {
344                 httpMethod = new GetMethod(url);
345             }
346
347             handleParams();
348
349             client.executeMethod(httpMethod);
350
351             return httpMethod;
352         }
353
354         private void handleParams() throws UnsupportedEncodingException {
355             if(paramsJson != null && !paramsJson.isEmpty()) {
356                 StringRequestEntity stringRequestEntity =
357                         new StringRequestEntity(paramsJson, "application/json", encoding);
358                 String contentLengthString = String.valueOf(stringRequestEntity.getContentLength());
359
360                 if(httpMethod instanceof PostMethod || httpMethod instanceof PutMethod) {
361                     ((EntityEnclosingMethod)httpMethod).setRequestEntity(stringRequestEntity);
362                     ((EntityEnclosingMethod)httpMethod).addRequestHeader("Content-Length", contentLengthString);
363                 } else {
364                     httpMethod.setQueryString(paramsJson);
365                 }
366                 addHeader("Content-Type", String.format("application/json;charset=%s", encoding));
367             }
368
369             for(Header header : headers) {
370                 httpMethod.addRequestHeader(header);
371             }
372         }
373     }
374
375 }