f03f938bebcb5ad9b45d336b0c66d0d73e5670bd
[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 import java.util.Collections;
29
30 import org.acumos.cds.transport.RestPageRequest;
31 import org.apache.http.client.HttpClient;
32 import org.springframework.boot.web.client.RestTemplateBuilder;
33 import org.springframework.http.MediaType;
34 import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
35 import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
36 import org.springframework.http.converter.ResourceHttpMessageConverter;
37 import org.springframework.web.client.RestTemplate;
38 import org.springframework.web.util.UriComponentsBuilder;
39
40 import com.fasterxml.jackson.databind.ObjectMapper;
41
42 /**
43  * Support class for building clients of other components of the Acumos universe that expose an http based
44  * service interface.
45  */
46 public abstract class AbstractClient {
47
48         protected String baseUrl;
49         protected RestTemplate restTemplate;
50
51         /**
52          * Builds a restTemplate. If user and pass are both supplied, uses basic HTTP
53          * authentication; if either one is missing, no authentication is used.
54          * 
55          * @param theTarget
56          *            URL of the web endpoint
57          * @param theClient
58          *            underlying http client
59          */
60         public AbstractClient(String theTarget, HttpClient theClient) {
61                 setTarget(theTarget);
62                 
63                 this.restTemplate = new RestTemplateBuilder()
64                                                                                                         .requestFactory(new HttpComponentsClientHttpRequestFactory(theClient))
65                                                                                                         .rootUri(this.baseUrl)
66                                                                                                         .build();
67         }
68         
69         public AbstractClient(String theTarget, HttpClient theClient, ObjectMapper theMapper) {
70                 setTarget(theTarget);
71                 
72                 MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
73     messageConverter.setObjectMapper(theMapper); //try to avoid building one every time
74
75                 ResourceHttpMessageConverter contentConverter = new ResourceHttpMessageConverter();
76                 contentConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_OCTET_STREAM));
77
78                 this.restTemplate = new RestTemplateBuilder()
79                                                                                                         .requestFactory(new HttpComponentsClientHttpRequestFactory(theClient))
80                                                                                                         .messageConverters(messageConverter, contentConverter)
81                                                                                                         .rootUri(this.baseUrl)
82                                                                                                         .build();
83         
84         }
85
86         protected void setTarget(String theTarget) {
87                 if (theTarget == null)
88                         throw new IllegalArgumentException("Null URL not permitted");
89
90                 URL url = null;
91                 try {
92                         url = new URL(theTarget);
93                         this.baseUrl = url.toExternalForm();
94                 }
95                 catch (MalformedURLException ex) {
96                         throw new IllegalArgumentException("Failed to parse target URL", ex);
97                 }
98         }       
99
100         /**
101          * Builds URI by adding specified path segments and query parameters to the base
102          * URL.
103          * 
104          * @param path
105          *            Array of path segments
106          * @param queryParams
107          *            key-value pairs; ignored if null or empty. Gives special treatment
108          *            to Date-type values.
109          * @param pageRequest
110          *            page, size and sort specification; ignored if null.
111          * @return URI
112          */
113         protected URI buildUri(final String[] path, final Map<String, Object> queryParams, RestPageRequest pageRequest) {
114                 UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.baseUrl);
115                 for (int p = 0; p < path.length; ++p)
116                         builder.pathSegment(path[p]);
117                 if (queryParams != null && queryParams.size() > 0) {
118                         for (Map.Entry<String, ? extends Object> entry : queryParams.entrySet()) {
119                                 Object value = null;
120                                 // Server expect Date as Long.
121                                 if (entry.getValue() instanceof Date)
122                                         value = ((Date) entry.getValue()).getTime();
123                                 else
124                                         value = entry.getValue().toString();
125                                 builder.queryParam(entry.getKey(), value);
126                         }
127                 }
128                 if (pageRequest != null) {
129                         if (pageRequest.getSize() != null)
130                                 builder.queryParam("page", Integer.toString(pageRequest.getPage()));
131                         if (pageRequest.getPage() != null)
132                                 builder.queryParam("size", Integer.toString(pageRequest.getSize()));
133                         if (pageRequest.getFieldToDirectionMap() != null && pageRequest.getFieldToDirectionMap().size() > 0) {
134                                 for (Map.Entry<String, String> entry : pageRequest.getFieldToDirectionMap().entrySet()) {
135                                         String value = entry.getKey() + (entry.getValue() == null ? "" : ("," + entry.getValue()));
136                                         builder.queryParam("sort", value);
137                                 }
138                         }
139                 }
140                 return builder.build().encode().toUri();
141         }
142
143 }