summaryrefslogtreecommitdiffstats
path: root/wfenginemgrservice/src/main/java/org/onap/workflow/common/RestClient.java
blob: 5dcef70aae5e7924c9fac4bddffffb45bc7e8809 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/**
 * Copyright 2017 ZTE Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.onap.workflow.common;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.onap.workflow.externalservice.entity.activitientitiy.ActivitiStartProcessRequest;
import org.onap.workflow.tools.Constants;
import org.onap.workflow.tools.HttpDeleteWithBody;
import org.onap.workflow.tools.RequestParameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;

public class RestClient {
  private static final String HTTP = "http";
  private static final Logger logger = LoggerFactory.getLogger(RestClient.class);
  public static boolean isTest = false;

  public enum HttpMethod {
    GET, POST, PUT, DELETE
  }

  /**
   * 
   * @param method
   * @param ip
   * @param port
   * @param url
   * @param body
   * @return
   * @throws ClientProtocolException
   * @throws IOException
   */
  public static RestResponse executeHttp(HttpMethod method, String ip, Integer port, String url,
      HttpEntity body) throws ClientProtocolException, IOException {
    if (isTest) {
      return new RestResponse();
    }

    logger.info("deployfile method send");
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpResponse httpResponse = null;
    RestResponse result = new RestResponse();
    try {
      if (ip == null) {
        ip = Config.getWorkflowAppConfig().getMsbClientConfig().getMsbSvrIp();
      }
      if (port == null) {
        port = Config.getWorkflowAppConfig().getMsbClientConfig().getMsbSvrPort();
      }
      HttpHost target = new HttpHost(ip, port, HTTP);
      HttpRequest request = getRequest(method, url, body);
      logger.info("deployfile method send ip" + ip);
      request.addHeader(Constants.AUTHORIZATION, ToolUtil.getHeader());

      httpResponse = httpclient.execute(target, request);
      HttpEntity entity = httpResponse.getEntity();
      logger.info("deployfile method send");
      if (entity != null && httpResponse.getStatusLine() != null) {
        result.setStatusCode(httpResponse.getStatusLine().getStatusCode());
        logger.info("reply status code deploy" + httpResponse.getStatusLine().getStatusCode());
        result.setResult(EntityUtils.toString(entity));
      }
    } catch (IOException e) {
      logger.warn("Close httpclient failed.", e);
    } finally {
      closeHttpClient(httpclient);
    }
    return result;
  }

  public static boolean closeHttpClient(CloseableHttpClient httpclient) {
    if (httpclient != null) {
      try {
        httpclient.close();
        return true;
      } catch (IOException e) {
        logger.warn("Close httpclient failed.", e);
        return false;
      }
    }
    return true;
  }

  public static HttpRequest getRequest(HttpMethod method, String url, HttpEntity body) {
    HttpRequest request = null;
    switch (method) {
      case GET:
        request = new HttpGet(url);
        break;
      case POST:
        request = new HttpPost(url);
        ((HttpPost) request).setEntity(body);
        break;
      case PUT:
        request = new HttpPut(url);
        ((HttpPut) request).setEntity(body);
        break;
      case DELETE:
        request = new HttpDelete(url);
        break;
      default:
        break;
    }
    return request;
  }

  /**
   * 
   * @param ip
   * @param port
   * @param url
   * @param requestBody
   * @return
   * @throws ClientProtocolException
   * @throws IOException
   */
  public static RestResponse post(String ip, int port, String url, HttpEntity requestBody)
      throws ClientProtocolException, IOException {
    return executeHttp(HttpMethod.POST, ip, port, url, requestBody);
  }



  /**
   * 
   * @param method
   * @param ip
   * @param port
   * @param url
   * @param body
   * @return
   * @throws ClientProtocolException
   * @throws IOException
   */
  public static RestResponse executeHttpDeleteDeploy(HttpMethod method, String ip, Integer port,
      String url) throws ClientProtocolException, IOException {
    if (isTest) {
      return new RestResponse();
    }
    if (ip == null) {
      ip = Config.getWorkflowAppConfig().getMsbClientConfig().getMsbSvrIp();
    }
    if (port == null) {
      port = Config.getWorkflowAppConfig().getMsbClientConfig().getMsbSvrPort();
    }
    RestResponse result = new RestResponse();
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
      httpClient = HttpClients.createDefault();
      // "http://localhost:8080/activiti-rest/service/repository/deployments/167501"
    /*  String deleteUrl =
          Constants.HTTP_HEADER + ip + Constants.COLON + port + url + "?cascade=true";*/
      String deleteUrl = Constants.HTTP_HEADER + ip + Constants.COLON + port + url + "?cascade=true";
      HttpDeleteWithBody httpDeteTest = new HttpDeleteWithBody(deleteUrl);
      Gson gson = new Gson();
      RequestParameters reqPa = new RequestParameters();
      reqPa.setCasCade(true);
      String jsonStr = gson.toJson(reqPa, RequestParameters.class);
      StringEntity requestEntity = new StringEntity(jsonStr, "UTF-8");
      requestEntity.setContentEncoding("UTF-8");
      httpDeteTest.setHeader("Content-type", "application/json");
      httpDeteTest.setHeader(Constants.AUTHORIZATION, ToolUtil.getHeader());
      httpDeteTest.setEntity(new StringEntity(jsonStr));
      // returnValue = httpClient.execute(httpDeteTest, responseHandler); // 调接口获取返回值时,必须用此方法
      CloseableHttpResponse httpResonse = httpClient.execute(httpDeteTest);
      if (httpResonse != null && httpResonse.getStatusLine() != null) {
        int statusCode = httpResonse.getStatusLine().getStatusCode();
        result.setStatusCode(statusCode);
      }
      // result.setResult(EntityUtils.toString(httpResonse.getEntity()));
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      closeHttpClient(httpClient);
    }

    return result;
  }

  /**
   * 
   * @param method
   * @param ip
   * @param port
   * @param url
   * @param body
   * @return
   * @throws ClientProtocolException
   * @throws IOException
   */
  public static RestResponse executeHttpStartIntance(HttpMethod method, String ip, Integer port,
      String url, ActivitiStartProcessRequest object) throws ClientProtocolException, IOException {
    if (isTest) {
      return new RestResponse();
    }
    String returnValue = "";
    RestResponse result = new RestResponse();
    CloseableHttpClient httpClient = HttpClients.createDefault();
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    try {
      httpClient = HttpClients.createDefault();
      if (ip == null) {
        ip = Config.getWorkflowAppConfig().getMsbClientConfig().getMsbSvrIp();
      }
      if (port == null) {
        port = Config.getWorkflowAppConfig().getMsbClientConfig().getMsbSvrPort();
      }
      HttpPost httpPost = new HttpPost(Constants.HTTP_HEADER + ip + ":" + port + url);
      Gson gson = new Gson();
      String jsonStr = gson.toJson(object, ActivitiStartProcessRequest.class);
      StringEntity requestEntity = new StringEntity(jsonStr, "utf-8");
      requestEntity.setContentEncoding("UTF-8");
      httpPost.setHeader("Content-type", "application/json");
      httpPost.setHeader(Constants.AUTHORIZATION, ToolUtil.getHeader());
      httpPost.setEntity(requestEntity);
//      returnValue = httpClient.execute(httpPost, responseHandler); // 调接口获取返回值时,必须用此方法
      CloseableHttpResponse httpResonse = httpClient.execute(httpPost);
      if (httpResonse != null && httpResonse.getStatusLine() != null) {
        int statusCode = httpResonse.getStatusLine().getStatusCode();
        returnValue = EntityUtils.toString(httpResonse.getEntity(), "UTF-8");
        result.setStatusCode(statusCode);
        result.setResult(returnValue);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    finally {
      closeHttpClient(httpClient);
    }

    return result;
  }

  /**
   * 
   * @param ip
   * @param port
   * @param url
   * @param requestBody
   * @return
   * @throws ClientProtocolException
   * @throws IOException
   */
  public static RestResponse post(String ip, Integer port, String url,
      ActivitiStartProcessRequest requestBody) throws ClientProtocolException, IOException {
    return executeHttpStartIntance(HttpMethod.POST, ip, port, url, requestBody);
  }

  /**
   * 
   * @param ip
   * @param port
   * @param url
   * @param requestBody
   * @return
   * @throws ClientProtocolException
   * @throws IOException
   */
  public static RestResponse post(String ip, Integer port, String url)
      throws ClientProtocolException, IOException {
    return executeHttpDeleteDeploy(HttpMethod.DELETE, ip, port, url);
  }

}