Fix java check style issue
[msb/discovery.git] / sdclient / discovery-service / src / main / java / org / onap / msb / sdclient / wrapper / util / HttpClientUtil.java
1 /**
2  * Copyright 2016-2017 ZTE, Inc. and others.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 package org.onap.msb.sdclient.wrapper.util;
15
16 import java.io.IOException;
17 import java.math.BigInteger;
18 import java.nio.charset.Charset;
19 import java.util.ArrayList;
20 import java.util.List;
21
22 import org.apache.http.NameValuePair;
23 import org.apache.http.client.ClientProtocolException;
24 import org.apache.http.client.config.RequestConfig;
25 import org.apache.http.client.methods.CloseableHttpResponse;
26 import org.apache.http.client.methods.HttpDelete;
27 import org.apache.http.client.methods.HttpGet;
28 import org.apache.http.client.methods.HttpPost;
29 import org.apache.http.client.utils.URLEncodedUtils;
30 import org.apache.http.entity.StringEntity;
31 import org.apache.http.impl.client.CloseableHttpClient;
32 import org.apache.http.impl.client.HttpClients;
33 import org.apache.http.message.BasicNameValuePair;
34 import org.apache.http.util.EntityUtils;
35 import org.onap.msb.sdclient.core.ConsulResponse;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 public class HttpClientUtil {
40
41     private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
42
43     public static int httpPostWithJSON(String url, String params) {
44         int result = 0;
45         CloseableHttpClient httpClient = HttpClients.createDefault();
46         HttpPost httpPost = new HttpPost(url);
47         httpPost.addHeader("Content-type", "application/json; charset=utf-8");
48         httpPost.setHeader("Accept", "application/json");
49         httpPost.setEntity(new StringEntity(params, Charset.forName("UTF-8")));
50         try {
51             CloseableHttpResponse res = httpClient.execute(httpPost);
52             result = res.getStatusLine().getStatusCode();
53             if (res.getStatusLine().getStatusCode() != 200) {
54                 logger.error(String.valueOf(result));
55             }
56             res.close();
57         } catch (IOException e) {
58             String errorMsg = url + ":httpPostWithJSON connect faild";
59         } finally {
60             try {
61                 httpClient.close();
62             } catch (IOException e) {
63                 String errorMsg = url + ":close  httpClient faild";
64             }
65         }
66
67         return result;
68
69     }
70
71     public static void delete(String url, String parameter) throws Exception {
72         String result = null;
73         String baseUrl;
74         if (parameter != null) {
75             List<NameValuePair> params = new ArrayList<NameValuePair>();
76             params.add(new BasicNameValuePair("serviceName", parameter));
77             baseUrl = url + "?" + URLEncodedUtils.format(params, "UTF-8");
78         } else {
79             baseUrl = url;
80         }
81
82         CloseableHttpClient httpClient = HttpClients.createDefault();;
83         try {
84
85             HttpDelete httpDelete = new HttpDelete(baseUrl);
86             CloseableHttpResponse res = httpClient.execute(httpDelete);
87
88             if (res.getStatusLine().getStatusCode() != 200) {
89                 throw new Exception("delete fail");
90             }
91
92             res.close();
93         } catch (IOException e) {
94             String errorMsg = baseUrl + ":delete connect faild";
95         } finally {
96             try {
97                 httpClient.close();
98             } catch (IOException e) {
99                 String errorMsg = baseUrl + ":close  httpClient faild";
100             }
101         }
102
103     }
104
105     public static String httpGet(String url) {
106         String result = null;
107         CloseableHttpClient httpClient = HttpClients.createDefault();
108         HttpGet httpGet = new HttpGet(url);
109         httpGet.addHeader("Content-type", "application/json; charset=utf-8");
110         httpGet.setHeader("Accept", "application/json");
111         try {
112             CloseableHttpResponse res = httpClient.execute(httpGet);
113
114             res.getLastHeader("X-Consul-Index");
115             result = EntityUtils.toString(res.getEntity());
116             if (res.getStatusLine().getStatusCode() != 200) {
117                 logger.error(result);
118             }
119             res.close();
120         } catch (ClientProtocolException e) {
121             String errorMsg = url + ":httpGetWithJSON connect faild";
122             logger.error(errorMsg);
123         } catch (IOException e) {
124             String errorMsg = url + ":httpGetWithJSON connect faild";
125             logger.error(errorMsg);
126         } finally {
127             try {
128                 httpClient.close();
129             } catch (IOException e) {
130                 String errorMsg = url + ":close  httpClient faild";
131                 logger.error(errorMsg);
132             }
133         }
134
135         return result;
136
137     }
138
139     @SuppressWarnings("unchecked")
140     public static <T> ConsulResponse<T> httpWaitGet(String url) {
141         CloseableHttpClient httpClient = HttpClients.createDefault();
142         HttpGet httpGet = new HttpGet(url);
143         httpGet.addHeader("Content-type", "application/json; charset=utf-8");
144         httpGet.setHeader("Accept", "application/json");
145         try {
146             CloseableHttpResponse res = httpClient.execute(httpGet);
147             String result = EntityUtils.toString(res.getEntity());
148
149             if (res.getStatusLine().getStatusCode() != 200) {
150                 logger.error(result);
151             } else {
152                 String indexHeaderValue = res.getLastHeader("X-Consul-Index").getValue();
153                 BigInteger index = new BigInteger(indexHeaderValue);
154
155                 return new ConsulResponse<T>((T) result, index);
156
157             }
158
159             res.close();
160         } catch (ClientProtocolException e) {
161             String errorMsg = url + ":httpGetWithJSON connect faild " + e.getMessage();
162             logger.error(errorMsg);
163         } catch (IOException e) {
164             String errorMsg = url + ":httpGetWithJSON connect faild " + e.getMessage();
165             logger.error(errorMsg);
166         } finally {
167             try {
168                 httpClient.close();
169             } catch (IOException e) {
170                 String errorMsg = url + ":close  httpClient faild " + e.getMessage();
171                 logger.error(errorMsg);
172             }
173         }
174
175         return null;
176
177     }
178
179     public static int httpGetStatus(String url) throws Exception {
180         int iStatus = 500;
181         CloseableHttpClient httpClient = HttpClients.createDefault();
182
183         HttpGet httpGet = new HttpGet(url);
184         RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();// 设置请求和传输超时时间
185         httpGet.setConfig(requestConfig);
186         httpGet.addHeader("Content-type", "application/json; charset=utf-8");
187         httpGet.setHeader("Accept", "application/json");
188         try {
189             CloseableHttpResponse res = httpClient.execute(httpGet);
190
191             iStatus = res.getStatusLine().getStatusCode();
192             res.close();
193         } catch (ClientProtocolException e) {
194             logger.error(url + " httpGet connect faild:" + e.getMessage());
195         } catch (IOException e) {
196             logger.error(url + " httpGet connect faild:" + e.getMessage());
197         } finally {
198             try {
199                 httpClient.close();
200             } catch (IOException e) {
201                 logger.error(url + " httpGet close faild:" + e.getMessage());
202             }
203         }
204
205         return iStatus;
206
207     }
208
209 }