2269df0456113290a635ab91827f0cbbb8ee24b3
[federation.git] / gateway / src / main / java / org / acumos / federation / gateway / common / AbstractClient.java
1 /*-
2  * ===============LICENSE_START=======================================================
3  * Acumos
4  * ===================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property & Tech Mahindra. All rights reserved.
6  * ===================================================================================
7  * This Acumos software file is distributed by AT&T and Tech Mahindra
8  * under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *  
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *  
14  * This file is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ===============LICENSE_END=========================================================
19  */
20
21 package org.acumos.federation.gateway.common;
22
23 import java.net.MalformedURLException;
24 import java.net.URI;
25 import java.net.URL;
26 import java.util.Date;
27 import java.util.Map;
28
29 import org.acumos.cds.transport.RestPageRequest;
30 import org.apache.http.client.HttpClient;
31 import org.springframework.boot.web.client.RestTemplateBuilder;
32 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
33 import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
34 import org.springframework.web.client.RestTemplate;
35 import org.springframework.web.util.UriComponentsBuilder;
36
37 import com.fasterxml.jackson.databind.ObjectMapper;
38
39 /**
40  * Support class for building clients of other components of the Acumos universe that expose an http based
41  * service interface.
42  */
43 public abstract class AbstractClient {
44
45         protected String baseUrl;
46         protected RestTemplate restTemplate;
47
48         /**
49          * Builds a restTemplate. If user and pass are both supplied, uses basic HTTP
50          * authentication; if either one is missing, no authentication is used.
51          * 
52          * @param theTarget
53          *            URL of the web endpoint
54          * @param theClient
55          *            underlying http client
56          */
57         public AbstractClient(String theTarget, HttpClient theClient) {
58                 setTarget(theTarget);
59                 this.restTemplate = new RestTemplateBuilder()
60                                                                                                         .requestFactory(new HttpComponentsClientHttpRequestFactory(theClient))
61                                                                                                         .rootUri(this.baseUrl)
62                                                                                                         .build();
63         }
64         
65         public AbstractClient(String theTarget, HttpClient theClient, ObjectMapper theMapper) {
66                 setTarget(theTarget);
67                 
68                 MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
69     messageConverter.setObjectMapper(theMapper); //try to avoid building one every time
70
71                 this.restTemplate = new RestTemplateBuilder()
72                                                                                                         .requestFactory(new HttpComponentsClientHttpRequestFactory(theClient))
73                                                                                                         .messageConverters(messageConverter)
74                                                                                                         .rootUri(this.baseUrl)
75                                                                                                         .build();
76         
77         }
78
79         protected void setTarget(String theTarget) {
80                 if (theTarget == null)
81                         throw new IllegalArgumentException("Null URL not permitted");
82
83                 URL url = null;
84                 try {
85                         url = new URL(theTarget);
86                         this.baseUrl = url.toExternalForm();
87                 }
88                 catch (MalformedURLException ex) {
89                         throw new IllegalArgumentException("Failed to parse target URL", ex);
90                 }
91         }       
92
93         /**
94          * Builds URI by adding specified path segments and query parameters to the base
95          * URL.
96          * 
97          * @param path
98          *            Array of path segments
99          * @param queryParams
100          *            key-value pairs; ignored if null or empty. Gives special treatment
101          *            to Date-type values.
102          * @param pageRequest
103          *            page, size and sort specification; ignored if null.
104          * @return URI
105          */
106         protected URI buildUri(final String[] path, final Map<String, Object> queryParams, RestPageRequest pageRequest) {
107                 UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.baseUrl);
108                 for (int p = 0; p < path.length; ++p)
109                         builder.pathSegment(path[p]);
110                 if (queryParams != null && queryParams.size() > 0) {
111                         for (Map.Entry<String, ? extends Object> entry : queryParams.entrySet()) {
112                                 Object value = null;
113                                 // Server expect Date as Long.
114                                 if (entry.getValue() instanceof Date)
115                                         value = ((Date) entry.getValue()).getTime();
116                                 else
117                                         value = entry.getValue().toString();
118                                 builder.queryParam(entry.getKey(), value);
119                         }
120                 }
121                 if (pageRequest != null) {
122                         if (pageRequest.getSize() != null)
123                                 builder.queryParam("page", Integer.toString(pageRequest.getPage()));
124                         if (pageRequest.getPage() != null)
125                                 builder.queryParam("size", Integer.toString(pageRequest.getSize()));
126                         if (pageRequest.getFieldToDirectionMap() != null && pageRequest.getFieldToDirectionMap().size() > 0) {
127                                 for (Map.Entry<String, String> entry : pageRequest.getFieldToDirectionMap().entrySet()) {
128                                         String value = entry.getKey() + (entry.getValue() == null ? "" : ("," + entry.getValue()));
129                                         builder.queryParam("sort", value);
130                                 }
131                         }
132                 }
133                 return builder.build().encode().toUri();
134         }
135
136 }