Merge "Change the copyright to 2018"
[so.git] / common / src / main / java / org / openecomp / mso / client / policy / RestClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License 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.openecomp.mso.client.policy;
22
23 import java.net.MalformedURLException;
24 import java.net.URI;
25 import java.net.URL;
26 import java.util.HashMap;
27 import java.util.Map;
28 import java.util.Map.Entry;
29 import java.util.Optional;
30 import java.util.UUID;
31
32 import javax.ws.rs.client.Client;
33 import javax.ws.rs.client.ClientBuilder;
34 import javax.ws.rs.client.ClientResponseFilter;
35 import javax.ws.rs.client.Entity;
36 import javax.ws.rs.client.Invocation.Builder;
37 import javax.ws.rs.client.WebTarget;
38 import javax.ws.rs.core.GenericType;
39 import javax.ws.rs.core.MediaType;
40 import javax.ws.rs.core.Response;
41 import javax.ws.rs.core.UriBuilder;
42 import javax.ws.rs.ext.ContextResolver;
43
44 import org.apache.log4j.Logger;
45 import org.openecomp.mso.client.RestProperties;
46 import org.openecomp.mso.logger.MsoLogger;
47 import org.springframework.stereotype.Service;
48
49 import com.fasterxml.jackson.databind.ObjectMapper;
50
51 @Service
52 public abstract class RestClient {
53         protected static final String ECOMP_COMPONENT_NAME = "MSO";
54         
55         private static final int MAX_PAYLOAD_SIZE = 1024 * 1024;
56         private WebTarget webTarget;
57
58         protected final Map<String, String> headerMap;
59         protected final MsoLogger msoLogger;
60         protected URL host;
61         protected Optional<URI> path;
62         protected Logger logger;
63         protected String accept;
64         protected String contentType;
65         protected UUID requestId;
66
67         protected RestClient(RestProperties props, UUID requestId, Optional<URI> path) {
68                 logger = Logger.getLogger(getClass().getName());
69                 msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL);
70                 this.requestId = requestId;
71                 headerMap = new HashMap<>();
72                 try {
73                         host = props.getEndpoint();
74                 } catch (MalformedURLException e) {
75                         logger.error("url not valid", e);
76                         throw new RuntimeException(e);
77                 }
78                 
79                 this.path = path;
80                 initializeClient(getClient());
81         }
82
83         protected RestClient(RestProperties props, UUID requestId, Optional<URI> path, String accept, String contentType) {
84                 this(props, requestId, path);
85                 this.accept = accept;
86                 this.contentType = contentType;
87                 this.requestId = requestId;
88
89         }
90
91         protected RestClient(URL host, UUID requestId, String contentType) {
92                 headerMap = new HashMap<>();
93                 logger = Logger.getLogger(getClass().getName());
94                 msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL);
95                 this.path = Optional.empty();
96                 this.host = host;
97                 this.contentType = contentType;
98                 this.requestId = requestId;
99                 initializeClient(getClient());
100         }
101
102         /**
103          * Override method to return false to disable logging.
104          * 
105          * @return true - to enable logging, false otherwise
106          */
107         protected boolean enableLogging() {
108                 return true;
109         }
110         
111         /**
112          * Override method to return custom value for max payload size.
113          * 
114          * @return Default value for MAX_PAYLOAD_SIZE = 1024 * 1024
115          */
116         protected int getMaxPayloadSize()
117         {
118                 return MAX_PAYLOAD_SIZE;
119         }
120
121         protected Builder getBuilder() {
122
123                 Builder builder = webTarget.request();
124                 initializeHeaderMap(headerMap);
125
126                 for (Entry<String, String> entry : headerMap.entrySet()) {
127                         builder.header(entry.getKey(), entry.getValue());
128                 }
129                 return builder;
130         }
131
132         protected abstract void initializeHeaderMap(Map<String, String> headerMap);
133
134         protected abstract Optional<ClientResponseFilter> addResponseFilter();
135
136         public abstract RestClient addRequestId(UUID requestId);
137
138         protected ContextResolver<ObjectMapper> getMapper() {
139                 return new CommonObjectMapperProvider();
140         }
141
142         protected String getAccept() {
143                 return accept;
144         }
145
146         protected String getContentType() {
147                 return contentType;
148         }
149
150         protected String getMergeContentType() {
151                 return "application/merge-patch+json";
152         }
153
154         protected Client getClient() {
155                 return ClientBuilder.newBuilder().build();
156         }
157
158         protected UUID getRequestId() {
159                 return this.requestId;
160         }
161         protected void initializeClient(Client client) {
162                 if (this.enableLogging()) {
163                         client.register(logger).register(new LoggingFilter(this.getMaxPayloadSize()));
164                 }
165                 client.register(this.getMapper());
166                 Optional<ClientResponseFilter> responseFilter = this.addResponseFilter();
167                 responseFilter.ifPresent(clientResponseFilter -> client.register(clientResponseFilter));
168                 webTarget = path.<WebTarget>map(uri -> client.target(UriBuilder.fromUri(host + uri.toString())))
169                         .orElseGet(() -> client.target(host.toString()));
170                 this.accept = MediaType.APPLICATION_JSON;
171                 this.contentType = MediaType.APPLICATION_JSON;
172         }
173
174         public Response get() {
175                 return this.getBuilder().accept(this.getAccept()).get();
176         }
177
178         public Response post(Object obj) {
179                 return this.getBuilder().accept(this.getAccept()).post(Entity.entity(obj, this.getContentType()));
180         }
181
182         public Response patch(Object obj) {
183                 return this.getBuilder().header("X-HTTP-Method-Override", "PATCH").accept(this.getAccept())
184                                 .post(Entity.entity(obj, this.getMergeContentType()));
185         }
186
187         public Response put(Object obj) {
188                 return this.getBuilder().accept(this.getAccept()).put(Entity.entity(obj, this.getContentType()));
189         }
190
191         public Response delete() {
192                 return this.getBuilder().accept(this.getAccept()).delete();
193         }
194
195         public Response delete(Object obj) {
196                 return this.getBuilder().header("X-HTTP-Method-Override", "DELETE").accept(this.getAccept())
197                                 .put(Entity.entity(obj, this.getContentType()));
198         }
199
200         public <T> T get(Class<T> resultClass) {
201                 return this.get().readEntity(resultClass);
202         }
203
204         public <T> T get(GenericType<T> resultClass) {
205                 return this.get().readEntity(resultClass);
206         }
207
208         public <T> T post(Object obj, Class<T> resultClass) {
209                 return this.post(obj).readEntity(resultClass);
210         }
211
212         public <T> T patch(Object obj, Class<T> resultClass) {
213                 return this.patch(obj).readEntity(resultClass);
214         }
215
216         public <T> T put(Object obj, Class<T> resultClass) {
217                 return this.put(obj).readEntity(resultClass);
218         }
219
220         public <T> T delete(Class<T> resultClass) {
221                 return this.delete().readEntity(resultClass);
222         }
223         
224         public <T> T delete(Object obj, Class<T> resultClass) {
225                 return this.delete(obj).readEntity(resultClass);
226         }
227 }