Add unit test for vfc-nfvo-wfengine-mgrservice
[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    * @return
133    * @throws ClientProtocolException
134    * @throws IOException
135    */
136   public static String get(String ip, int port, String url)
137       throws ClientProtocolException, IOException {
138     return executeHttp(HttpMethod.GET, ip, port, url, null).getResult();
139   }
140
141   /**
142    * 
143    * @param ip
144    * @param port
145    * @param url
146    * @return
147    * @throws ClientProtocolException
148    * @throws IOException
149    */
150   public static RestResponse delete(String ip, int port, String url)
151       throws ClientProtocolException, IOException {
152     return executeHttp(HttpMethod.GET, ip, port, url, null);
153   }
154
155   /**
156    * 
157    * @param ip
158    * @param port
159    * @param url
160    * @param requestBody
161    * @return
162    * @throws ClientProtocolException
163    * @throws IOException
164    */
165   public static RestResponse post(String ip, int port, String url, HttpEntity requestBody)
166       throws ClientProtocolException, IOException {
167     return executeHttp(HttpMethod.POST, ip, port, url, requestBody);
168   }
169
170
171
172   /**
173    * 
174    * @param method
175    * @param ip
176    * @param port
177    * @param url
178    * @param body
179    * @return
180    * @throws ClientProtocolException
181    * @throws IOException
182    */
183   public static RestResponse executeHttpDeleteDeploy(HttpMethod method, String ip, Integer port,
184       String url) throws ClientProtocolException, IOException {
185     if (ip == null) {
186       ip = Config.getWorkflowAppConfig().getMsbClientConfig().getMsbSvrIp();
187     }
188     if(port==null) {
189       port = Config.getWorkflowAppConfig().getMsbClientConfig().getMsbSvrPort();
190     }
191     RestResponse result = new RestResponse();
192     CloseableHttpClient httpClient = HttpClients.createDefault();
193     try {
194       httpClient = HttpClients.createDefault();
195       // "http://localhost:8080/activiti-rest/service/repository/deployments/167501"
196       String deleteUrl = Constants.HTTP_HEADER + ip + Constants.COLON + port + url;
197       HttpDeleteWithBody httpDeteTest = new HttpDeleteWithBody(deleteUrl);
198       Gson gson = new Gson();
199       RequestParameters reqPa = new RequestParameters();
200       reqPa.setCasCade(true);
201       String jsonStr = gson.toJson(reqPa, RequestParameters.class);
202       StringEntity requestEntity = new StringEntity(jsonStr, "UTF-8");
203       requestEntity.setContentEncoding("UTF-8");
204       httpDeteTest.setHeader("Content-type", "application/json");
205       httpDeteTest.setHeader(Constants.AUTHORIZATION, ToolUtil.getHeader());
206       httpDeteTest.setEntity(new StringEntity(jsonStr));
207       // returnValue = httpClient.execute(httpDeteTest, responseHandler); // 调接口获取返回值时,必须用此方法
208       CloseableHttpResponse httpResonse = httpClient.execute(httpDeteTest);
209       if(httpResonse!=null && httpResonse.getStatusLine()!=null) {
210         int statusCode = httpResonse.getStatusLine().getStatusCode();
211         result.setStatusCode(statusCode);
212       }
213    //   result.setResult(EntityUtils.toString(httpResonse.getEntity()));
214     } catch (Exception e) {
215       e.printStackTrace();
216     }
217
218     finally {
219       try {
220         httpClient.close();
221       } catch (IOException e) {
222         // TODO Auto-generated catch block
223         e.printStackTrace();
224       }
225     }
226
227     return result;
228   }
229
230   /**
231    * 
232    * @param method
233    * @param ip
234    * @param port
235    * @param url
236    * @param body
237    * @return
238    * @throws ClientProtocolException
239    * @throws IOException
240    */
241   public static RestResponse executeHttpStartIntance(HttpMethod method, String ip, Integer port,
242       String url, ActivitiStartProcessRequest object) throws ClientProtocolException, IOException {
243     String returnValue = "";
244     RestResponse result = new RestResponse();
245     CloseableHttpClient httpClient = HttpClients.createDefault();
246     ResponseHandler<String> responseHandler = new BasicResponseHandler();
247     try {
248       httpClient = HttpClients.createDefault();
249       if (ip == null) {
250         ip = Config.getWorkflowAppConfig().getMsbClientConfig().getMsbSvrIp();
251       }
252       if(ip==null) {
253         port = Config.getWorkflowAppConfig().getMsbClientConfig().getMsbSvrPort();
254       }
255       HttpPost httpPost = new HttpPost(Constants.HTTP_HEADER + ip + ":" + port + url);
256       Gson gson = new Gson();
257       String jsonStr = gson.toJson(object, ActivitiStartProcessRequest.class);
258       StringEntity requestEntity = new StringEntity(jsonStr, "utf-8");
259       requestEntity.setContentEncoding("UTF-8");
260       httpPost.setHeader("Content-type", "application/json");
261       httpPost.setHeader(Constants.AUTHORIZATION, ToolUtil.getHeader());
262       httpPost.setEntity(requestEntity);
263       returnValue = httpClient.execute(httpPost, responseHandler); // 调接口获取返回值时,必须用此方法
264       CloseableHttpResponse httpResonse = httpClient.execute(httpPost);
265       if(httpResonse!=null && httpResonse.getStatusLine()!=null) {
266         int statusCode = httpResonse.getStatusLine().getStatusCode();
267         returnValue = EntityUtils.toString(httpResonse.getEntity(), "UTF-8");
268         result.setStatusCode(statusCode);
269         result.setResult(returnValue);
270       }
271     } catch (Exception e) {
272       e.printStackTrace();
273     }
274
275     finally {
276       try {
277         httpClient.close();
278       } catch (IOException e) {
279         // TODO Auto-generated catch block
280         e.printStackTrace();
281       }
282     }
283
284     return result;
285   }
286
287   /**
288    * 
289    * @param ip
290    * @param port
291    * @param url
292    * @param requestBody
293    * @return
294    * @throws ClientProtocolException
295    * @throws IOException
296    */
297   public static RestResponse post(String ip, Integer port, String url,
298       ActivitiStartProcessRequest requestBody) throws ClientProtocolException, IOException {
299     return executeHttpStartIntance(HttpMethod.POST, ip, port, url, requestBody);
300   }
301
302   /**
303    * 
304    * @param ip
305    * @param port
306    * @param url
307    * @param requestBody
308    * @return
309    * @throws ClientProtocolException
310    * @throws IOException
311    */
312   public static RestResponse post(String ip, Integer port, String url)
313       throws ClientProtocolException, IOException {
314     return executeHttpDeleteDeploy(HttpMethod.DELETE, ip, port, url);
315   }
316
317 }