2eeb2fcaf943a15dc518b3404248e326137a3679
[vfc/nfvo/wfengine.git] / wfenginemgrservice / src / main / java / org / onap / workflow / common / RestClient.java
1 /**
2  * Copyright 2017 ZTE Corporation.
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 package org.onap.workflow.common;
17
18 import java.io.IOException;
19
20 import org.apache.http.HttpEntity;
21 import org.apache.http.HttpHost;
22 import org.apache.http.HttpRequest;
23 import org.apache.http.HttpResponse;
24 import org.apache.http.client.ClientProtocolException;
25 import org.apache.http.client.ResponseHandler;
26 import org.apache.http.client.methods.CloseableHttpResponse;
27 import org.apache.http.client.methods.HttpDelete;
28 import org.apache.http.client.methods.HttpGet;
29 import org.apache.http.client.methods.HttpPost;
30 import org.apache.http.client.methods.HttpPut;
31 import org.apache.http.entity.StringEntity;
32 import org.apache.http.impl.client.BasicResponseHandler;
33 import org.apache.http.impl.client.CloseableHttpClient;
34 import org.apache.http.impl.client.HttpClients;
35 import org.apache.http.util.EntityUtils;
36 import org.onap.workflow.externalservice.entity.activitientitiy.ActivitiStartProcessRequest;
37 import org.onap.workflow.tools.Constants;
38 import org.onap.workflow.tools.HttpDeleteWithBody;
39 import org.onap.workflow.tools.RequestParameters;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 import com.google.gson.Gson;
44
45 public class RestClient {
46   private static final String HTTP = "http";
47   private static final Logger logger = LoggerFactory.getLogger(RestClient.class);
48
49   public enum HttpMethod {
50     GET, POST, PUT, DELETE
51   }
52
53   /**
54    * 
55    * @param method
56    * @param ip
57    * @param port
58    * @param url
59    * @param body
60    * @return
61    * @throws ClientProtocolException
62    * @throws IOException
63    */
64   public static RestResponse executeHttp(HttpMethod method, String ip, Integer port, String url,
65       HttpEntity body) throws ClientProtocolException, IOException {
66     logger.info("deployfile method send");
67     CloseableHttpClient httpclient = HttpClients.createDefault();
68     HttpResponse httpResponse = null;
69     RestResponse result = new RestResponse();
70     try {
71       if (ip == null) {
72         ip = Config.getWorkflowAppConfig().getMsbClientConfig().getMsbSvrIp();
73       }
74       if (port == null) {
75         port = Config.getWorkflowAppConfig().getMsbClientConfig().getMsbSvrPort();
76       }
77       HttpHost target = new HttpHost(ip, port, HTTP);
78       HttpRequest request = getRequest(method, url, body);
79       logger.info("deployfile method send ip" + ip);
80       request.addHeader(Constants.AUTHORIZATION, ToolUtil.getHeader());
81
82       httpResponse = httpclient.execute(target, request);
83       HttpEntity entity = httpResponse.getEntity();
84       logger.info("deployfile method send");
85       if (entity != null && httpResponse.getStatusLine()!=null) {
86         result.setStatusCode(httpResponse.getStatusLine().getStatusCode());
87         logger.info("reply status code deploy"+httpResponse.getStatusLine().getStatusCode());
88         result.setResult(EntityUtils.toString(entity));
89       }
90     } catch (IOException e) {
91       logger.warn("Close httpclient failed.", e);
92     } finally {
93       if (httpclient != null) {
94         try {
95           httpclient.close();
96         } catch (IOException e) {
97           logger.warn("Close httpclient failed.", e);
98         }
99       }
100     }
101     return result;
102   }
103
104   public static HttpRequest getRequest(HttpMethod method, String url, HttpEntity body) {
105     HttpRequest request = null;
106     switch (method) {
107       case GET:
108         request = new HttpGet(url);
109         break;
110       case POST:
111         request = new HttpPost(url);
112         ((HttpPost) request).setEntity(body);
113         break;
114       case PUT:
115         request = new HttpPut(url);
116         ((HttpPut) request).setEntity(body);
117         break;
118       case DELETE:
119         request = new HttpDelete(url);
120         break;
121       default:
122         break;
123     }
124     return request;
125   }
126
127   /**
128    * 
129    * @param ip
130    * @param port
131    * @param url
132    * @param requestBody
133    * @return
134    * @throws ClientProtocolException
135    * @throws IOException
136    */
137   public static RestResponse post(String ip, int port, String url, HttpEntity requestBody)
138       throws ClientProtocolException, IOException {
139     return executeHttp(HttpMethod.POST, ip, port, url, requestBody);
140   }
141
142
143
144   /**
145    * 
146    * @param method
147    * @param ip
148    * @param port
149    * @param url
150    * @param body
151    * @return
152    * @throws ClientProtocolException
153    * @throws IOException
154    */
155   public static RestResponse executeHttpDeleteDeploy(HttpMethod method, String ip, Integer port,
156       String url) throws ClientProtocolException, IOException {
157     if (ip == null) {
158       ip = Config.getWorkflowAppConfig().getMsbClientConfig().getMsbSvrIp();
159     }
160     if(port==null) {
161       port = Config.getWorkflowAppConfig().getMsbClientConfig().getMsbSvrPort();
162     }
163     RestResponse result = new RestResponse();
164     CloseableHttpClient httpClient = HttpClients.createDefault();
165     try {
166       httpClient = HttpClients.createDefault();
167       // "http://localhost:8080/activiti-rest/service/repository/deployments/167501"
168       String deleteUrl = Constants.HTTP_HEADER + ip + Constants.COLON + port + url;
169       HttpDeleteWithBody httpDeteTest = new HttpDeleteWithBody(deleteUrl);
170       Gson gson = new Gson();
171       RequestParameters reqPa = new RequestParameters();
172       reqPa.setCasCade(true);
173       String jsonStr = gson.toJson(reqPa, RequestParameters.class);
174       StringEntity requestEntity = new StringEntity(jsonStr, "UTF-8");
175       requestEntity.setContentEncoding("UTF-8");
176       httpDeteTest.setHeader("Content-type", "application/json");
177       httpDeteTest.setHeader(Constants.AUTHORIZATION, ToolUtil.getHeader());
178       httpDeteTest.setEntity(new StringEntity(jsonStr));
179       // returnValue = httpClient.execute(httpDeteTest, responseHandler); // 调接口获取返回值时,必须用此方法
180       CloseableHttpResponse httpResonse = httpClient.execute(httpDeteTest);
181       if(httpResonse!=null && httpResonse.getStatusLine()!=null) {
182         int statusCode = httpResonse.getStatusLine().getStatusCode();
183         result.setStatusCode(statusCode);
184       }
185    //   result.setResult(EntityUtils.toString(httpResonse.getEntity()));
186     } catch (Exception e) {
187       e.printStackTrace();
188     }
189
190     finally {
191       try {
192         httpClient.close();
193       } catch (IOException e) {
194         // TODO Auto-generated catch block
195         e.printStackTrace();
196       }
197     }
198
199     return result;
200   }
201
202   /**
203    * 
204    * @param method
205    * @param ip
206    * @param port
207    * @param url
208    * @param body
209    * @return
210    * @throws ClientProtocolException
211    * @throws IOException
212    */
213   public static RestResponse executeHttpStartIntance(HttpMethod method, String ip, Integer port,
214       String url, ActivitiStartProcessRequest object) throws ClientProtocolException, IOException {
215     String returnValue = "";
216     RestResponse result = new RestResponse();
217     CloseableHttpClient httpClient = HttpClients.createDefault();
218     ResponseHandler<String> responseHandler = new BasicResponseHandler();
219     try {
220       httpClient = HttpClients.createDefault();
221       if (ip == null) {
222         ip = Config.getWorkflowAppConfig().getMsbClientConfig().getMsbSvrIp();
223       }
224       if(ip==null) {
225         port = Config.getWorkflowAppConfig().getMsbClientConfig().getMsbSvrPort();
226       }
227       HttpPost httpPost = new HttpPost(Constants.HTTP_HEADER + ip + ":" + port + url);
228       Gson gson = new Gson();
229       String jsonStr = gson.toJson(object, ActivitiStartProcessRequest.class);
230       StringEntity requestEntity = new StringEntity(jsonStr, "utf-8");
231       requestEntity.setContentEncoding("UTF-8");
232       httpPost.setHeader("Content-type", "application/json");
233       httpPost.setHeader(Constants.AUTHORIZATION, ToolUtil.getHeader());
234       httpPost.setEntity(requestEntity);
235       returnValue = httpClient.execute(httpPost, responseHandler); // 调接口获取返回值时,必须用此方法
236       CloseableHttpResponse httpResonse = httpClient.execute(httpPost);
237       if(httpResonse!=null && httpResonse.getStatusLine()!=null) {
238         int statusCode = httpResonse.getStatusLine().getStatusCode();
239         returnValue = EntityUtils.toString(httpResonse.getEntity(), "UTF-8");
240         result.setStatusCode(statusCode);
241         result.setResult(returnValue);
242       }
243     } catch (Exception e) {
244       e.printStackTrace();
245     }
246
247     finally {
248       try {
249         httpClient.close();
250       } catch (IOException e) {
251         // TODO Auto-generated catch block
252         e.printStackTrace();
253       }
254     }
255
256     return result;
257   }
258
259   /**
260    * 
261    * @param ip
262    * @param port
263    * @param url
264    * @param requestBody
265    * @return
266    * @throws ClientProtocolException
267    * @throws IOException
268    */
269   public static RestResponse post(String ip, Integer port, String url,
270       ActivitiStartProcessRequest requestBody) throws ClientProtocolException, IOException {
271     return executeHttpStartIntance(HttpMethod.POST, ip, port, url, requestBody);
272   }
273
274   /**
275    * 
276    * @param ip
277    * @param port
278    * @param url
279    * @param requestBody
280    * @return
281    * @throws ClientProtocolException
282    * @throws IOException
283    */
284   public static RestResponse post(String ip, Integer port, String url)
285       throws ClientProtocolException, IOException {
286     return executeHttpDeleteDeploy(HttpMethod.DELETE, ip, port, url);
287   }
288
289 }