aboutsummaryrefslogtreecommitdiffstats
path: root/bpmn/MSORESTClient/src/main/java/org/openecomp/mso/rest/RESTClient.java
blob: cab3e5082ea7b80f17333110608492993b3ff2ac (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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
/*-
 * ============LICENSE_START=======================================================
 * OPENECOMP - MSO
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * 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.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.mso.rest;

import java.io.Closeable;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import javax.net.ssl.SSLSocketFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.AbstractHttpMessage;
import org.apache.http.util.EntityUtils;

/**
 * Client used to send RESTFul requests.
 * <p>
 * Many of the methods return a reference to the 'this,' thereby allowing 
 * method chaining. 
 * <br>
 * An example of usage can be found below:
 * <pre>
 * RESTClient client;
 * try {
 *     client = new RESTClient("http://www.openecomp.org");
 *     APIResponse response = client
 *         .setHeader("Accept", "application/json")
 *         .setHeader("Clientid", "clientid")
 *         .setHeader("header", "value")
 *         .httpPost("postbody");
 *     if (response.getStatusCode() == 200) {
 *         System.out.println("Success!");
 *     }
 *  } catch (RESTException re) {
 *      // Handle Exception
 *  }
 * </pre>
 *
 * @version 1.0
 * @since 1.0
 */
public class RESTClient {
    private final String proxyHost;
    private final int proxyPort;

    private final String URL;

    private final LinkedHashMap<String, List<String>> headers;
    private final LinkedHashMap<String, List<String>> parameters;
    
    private HttpEntity httpEntity;

    /**
     * Internal method used to build an APIResponse using the specified 
     * HttpResponse object.
     *
     * @param response response wrapped inside an APIResponse object
     * @return api response
     */
    private APIResponse buildResponse(HttpResponse response) 
            throws RESTException {

        return new APIResponse(response);
    }

    /**
     * Used to release any resources used by the connection.
     * @param response HttpResponse object used for releasing the connection
     * @throws RESTException if unable to release connection
     *
     */
    private void releaseConnection(HttpResponse response) throws RESTException {
        try {
            EntityUtils.consume(response.getEntity());
        } catch (IOException ioe) {
            throw new RESTException(ioe);
        }
    }

    /**
     * Sets headers to the http message.
     *
     * @param httpMsg http message to set headers for
     */
    private void addInternalHeaders(AbstractHttpMessage httpMsg) {
        if (headers.isEmpty()) {
            return;
        }

        final Set<String> keySet = headers.keySet();
        for (final String key : keySet) {
            final List<String> values = headers.get(key);
            for (final String value : values) {
                httpMsg.addHeader(key, value);
            }
        }
    }

    /**
     * Builds the query part of a URL.
     *
     * @return query
     */
    private String buildQuery() {
        if (this.parameters.size() == 0) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        String charSet = "UTF-8";
        try {
            Iterator<String> keyitr = this.parameters.keySet().iterator();
            for (int i = 0; keyitr.hasNext(); ++i) {
                if (i > 0) {
                    sb.append("&");
                }

                final String name = keyitr.next();
                final List<String> values = this.parameters.get(name);
                for(final String value : values) {
                    sb.append(URLEncoder.encode(name, charSet));
                    sb.append("=");
                    sb.append(URLEncoder.encode(value, charSet));
                }
            }
        } catch (UnsupportedEncodingException e) {
            // should not occur
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * Creates an http client that can be used for sending http requests.
     *
     * @return created http client
     *
     * @throws RESTException if unable to create http client.
     */
    private CloseableHttpClient createClient() throws RESTException {
        //TODO - we may want to trust self signed certificate at some point - add implementation here
        HttpClientBuilder clientBuilder;

		try {
			SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
					(SSLSocketFactory) SSLSocketFactory.getDefault(),
					new HostNameVerifier());
			Registry<ConnectionSocketFactory> registry = RegistryBuilder
					.<ConnectionSocketFactory> create()
					.register("http",
							PlainConnectionSocketFactory.getSocketFactory())
					.register("https", sslSocketFactory).build();
			PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(
					registry);
			clientBuilder = HttpClientBuilder.create().setConnectionManager(
					manager);
		} catch (Exception ex) {
			throw new RESTException(ex.getMessage());
		}
		clientBuilder.disableRedirectHandling();

		if ((this.proxyHost != null) && (this.proxyPort != -1)) {
			HttpHost proxy = new HttpHost(this.proxyHost, this.proxyPort);
			clientBuilder.setProxy(proxy);
		}

		return clientBuilder.build();
    }

    /**
     * Creates a RESTClient with the specified URL, proxy host, and proxy port.
     *
     * @param URL URL to send request to
     * @param proxyHost proxy host to use for sending request
     * @param proxyPort proxy port to use for sendin request
     *
     * @throws RESTException if unable to create a RESTClient
     */
    public RESTClient(String URL, String proxyHost, int proxyPort)
            throws RESTException {
        this(new RESTConfig(URL, proxyHost, proxyPort));
    }

    /**
     * Creates a RESTClient with the specified URL. No proxy host nor port will
     * be used. 
     *
     * @param URL URL to send request to
     *
     * @throws RESTException if unable to create a RESTClient
     */
    public RESTClient(String URL) throws RESTException {
        this(new RESTConfig(URL));
    }
    
    /**
     * Creates a RESTClient with the RESTConfig object.
     *
     * @param RESTConfig config to use for sending request
     *
     * @throws RESTException if unable to create a RESTClient
     */
    public RESTClient(RESTConfig cfg) throws RESTException {
        this.headers = new LinkedHashMap<String, List<String>>();
        this.parameters = new LinkedHashMap<String, List<String>>();
        this.URL = cfg.getURL();
        this.proxyHost = cfg.getProxyHost();
        this.proxyPort = cfg.getProxyPort();
    }

    /**
     * Adds parameter to be sent during http request.
     * <p>
     * Does not remove any parameters with the same name, thus allowing 
     * duplicates.
     *
     * @param name name of parameter
     * @param value value of parametr
     * @return a reference to 'this', which can be used for method chaining
     */
    public RESTClient addParameter(String name, String value) {
        if (!parameters.containsKey(name)) {
            parameters.put(name, new ArrayList<String>());
        }

        List<String> values = parameters.get(name);
        values.add(value);

        return this;
    }

    /**
     * Sets parameter to be sent during http request.
     * <p>
     * Removes any parameters with the same name, thus disallowing duplicates.
     *
     * @param name name of parameter
     * @param value value of parametr
     * @return a reference to 'this', which can be used for method chaining
     */
    public RESTClient setParameter(String name, String value) {
        if (parameters.containsKey(name)) {
            parameters.get(name).clear();
        }

        addParameter(name, value);

        return this;
    }

    /**
     * Adds http header to be sent during http request.
     * <p>
     * Does not remove any headers with the same name, thus allowing 
     * duplicates.
     *
     * @param name name of header 
     * @param value value of header 
     * @return a reference to 'this', which can be used for method chaining
     */
    public RESTClient addHeader(String name, String value) {
        if (!headers.containsKey(name)) {
            headers.put(name, new ArrayList<String>());
        }

        List<String> values = headers.get(name);
        values.add(value);

        return this;
    }

    /**
     * Sets http header to be sent during http request.
     * <p>
     * Does not remove any headers with the same name, thus allowing 
     * duplicates.
     *
     * @param name name of header 
     * @param value value of header 
     * @return a reference to 'this', which can be used for method chaining
     */
    public RESTClient setHeader(String name, String value) {
        if (headers.containsKey(name)) {
            headers.get(name).clear();
        }

        addHeader(name, value);

        return this;
    }
    
    /**
     * Convenience method for adding the authorization header using the 
     * specified OAuthToken object.
     *
     * @param token token to use for setting authorization
     * @return a reference to 'this,' which can be used for method chaining
     */
    public RESTClient addAuthorizationHeader(String token) {
        this.addHeader("Authorization", token);
        return this;
    }

    /**
     * Alias for httpGet().
     *
     * @see RESTClient#httpGet()
     */
    public APIResponse get() throws RESTException {
        return httpGet();
    }

    /**
     * Sends an http GET request using the parameters and headers previously
     * set.
     *
     * @return api response
     *
     * @throws RESTException if request was unsuccessful
     */
    public APIResponse httpGet() throws RESTException {
        HttpResponse response = null;

        try (CloseableHttpClient httpClient = createClient()) {
            String query = "";
            if (!buildQuery().equals("")) {
                query = "?" + buildQuery();
            }
            HttpGet httpGet = new HttpGet(this.getURL() + query);
            addInternalHeaders(httpGet);

            response = httpClient.execute(httpGet);

            APIResponse apiResponse = buildResponse(response);
            return apiResponse;
        } catch (IOException ioe) {
            throw new RESTException(ioe);
        } finally {
            if (response != null) {
                this.releaseConnection(response);
            }
        }
    }

    /**
     * Alias for httpPost()
     *
     * @see RESTClient#httpPost()
     */
    public APIResponse post() throws RESTException {
        return httpPost();
    }

    /**
     * Sends an http POST request.
     * <p>
     * POST body will be set to the values set using add/setParameter()
     *
     * @return api response
     *
     * @throws RESTException if POST was unsuccessful
     */
    public APIResponse httpPost() throws RESTException {
            APIResponse response = httpPost(buildQuery()); 
            return response;
    }

    /**
     * Sends an http POST request using the specified body.
     *
     * @return api response
     *
     * @throws RESTException if POST was unsuccessful
     */
    public APIResponse httpPost(String body) throws RESTException {
        HttpResponse response = null;
        try (CloseableHttpClient httpClient = createClient()) {
            HttpPost httpPost = new HttpPost(this.getURL());
            addInternalHeaders(httpPost);
            if (body != null && !body.equals("")) {
                httpEntity = new StringEntity(body);
                httpPost.setEntity(new StringEntity(body));
            }

            response = httpClient.execute(httpPost);

            return buildResponse(response);
        } catch (IOException e) {
            throw new RESTException(e);
        } finally {
            if (response != null) {
                this.releaseConnection(response);
            }
        }
    }

    /**
     * 
     * @param body Data to PUT
     * @return API response
     * @throws RESTException 
     */
    public APIResponse httpPut(String body) throws RESTException {
        HttpResponse response = null;
        try (CloseableHttpClient httpClient = createClient()) {

            String query = "";
            if (!buildQuery().equals("")) {
                query = "?" + buildQuery();
            }
            HttpPut httpPut = new HttpPut(this.getURL() + query);
            addInternalHeaders(httpPut);
            if (body != null && !body.equals("")) {
                httpEntity = new StringEntity(body);
                httpPut.setEntity(httpEntity);
            }

            response = httpClient.execute(httpPut);

            return buildResponse(response);
        } catch (IOException e) {
            throw new RESTException(e);
        } finally {
            if (response != null) {
                this.releaseConnection(response);
            }
        }
    }

    /**
     * Alias for httpPatch().
     *
     * @see RESTClient#httpPatch()
     */
    public APIResponse patch(String body) throws RESTException {
        return httpPatch(body);
    }

    /**
     * 
     * @param body Data to PATCH
     * @return API response
     * @throws RESTException 
     */
    public APIResponse httpPatch(String body) throws RESTException {
        HttpResponse response = null;
        try (CloseableHttpClient httpClient = createClient()) {
            String query = "";
            if (!buildQuery().equals("")) {
                query = "?" + buildQuery();
            }
            HttpPatch httpPatch = new HttpPatch(this.getURL() + query);
            addInternalHeaders(httpPatch);
            if (body != null && !body.equals("")) {
                httpEntity = new StringEntity(body);
                httpPatch.setEntity(httpEntity);
            }

            response = httpClient.execute(httpPatch);

            return buildResponse(response);
        } catch (IOException e) {
            throw new RESTException(e);
        } finally {
            if (response != null) {
                this.releaseConnection(response);
            }
        }
    }

    /**
     * Alias for httpDelete().
     *
     * @see RESTClient#httpDelete()
     */
    public APIResponse delete() throws RESTException {
        return httpDelete();
    }

    /**
     * Sends an http DELETE request using the parameters and headers previously
     * set.
     *
     * @return api response
     *
     * @throws RESTException if request was unsuccessful
     */
    public APIResponse httpDelete() throws RESTException {
    	return httpDelete(null);
    }

    /**
     * Sends an http DELETE request with a body, using the parameters and headers
     * previously set.
     *
     * @return api response
     *
     * @throws RESTException if request was unsuccessful
     */
    public APIResponse httpDelete(String body) throws RESTException {
        HttpResponse response = null;

        try (CloseableHttpClient httpClient = createClient()){

            String query = "";
            if (!buildQuery().equals("")) {
                query = "?" + buildQuery();
            }
            HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(this.getURL() + query);
            addInternalHeaders(httpDelete);
 
            if (body != null && !body.equals("")) {
                httpEntity = new StringEntity(body);
                httpDelete.setEntity(httpEntity);
            }

            response = httpClient.execute(httpDelete);

            APIResponse apiResponse = buildResponse(response);
            return apiResponse;
        } catch (IOException ioe) {
            throw new RESTException(ioe);
        } finally {
            if (response != null) {
                this.releaseConnection(response);
            }
        }
    }

    public String getURL() {
        return URL;
    }
    public LinkedHashMap<String,List<String>> getHeaders() {
        return headers;
    }
    public LinkedHashMap<String,List<String>> getParameters() {
        return parameters;
    }
    public HttpEntity getHttpEntity() {
        return httpEntity;
    }

	
	/**
	 * Allows inclusion of a request body with DELETE.
	 */
	private class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
	    public static final String METHOD_NAME = "DELETE";
	 
	    public String getMethod() {
	        return METHOD_NAME;
	    }
	 
	    public HttpDeleteWithBody(final String uri) {
	        super();
	        setURI(URI.create(uri));
	    }
	 
	    public HttpDeleteWithBody(final URI uri) {
	        super();
	        setURI(uri);
	    }
	 
	    public HttpDeleteWithBody() {
	        super();
	    }
	}
}