1436d83a947799fb24c4b66191be2cbdd5564907
[so.git] / bpmn / MSOCommonBPMN / 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
31 import javax.ws.rs.client.Client;
32 import javax.ws.rs.client.ClientBuilder;
33 import javax.ws.rs.client.ClientResponseFilter;
34 import javax.ws.rs.client.Entity;
35 import javax.ws.rs.client.Invocation.Builder;
36 import javax.ws.rs.client.WebTarget;
37 import javax.ws.rs.core.GenericType;
38 import javax.ws.rs.core.MediaType;
39 import javax.ws.rs.core.Response;
40 import javax.ws.rs.core.UriBuilder;
41 import javax.ws.rs.ext.ContextResolver;
42
43 import org.apache.log4j.Logger;
44 import org.openecomp.mso.client.RestProperties;
45 import org.openecomp.mso.logger.MsoLogger;
46 import org.springframework.stereotype.Service;
47
48 import com.fasterxml.jackson.databind.ObjectMapper;
49
50 @Service
51 public abstract class RestClient {
52         protected static final String ECOMP_COMPONENT_NAME = "MSO";
53         
54         private static final int MAX_PAYLOAD_SIZE = 1024 * 1024;
55         private WebTarget webTarget;
56
57         protected final Map<String, String> headerMap;
58         protected final MsoLogger msoLogger;
59         protected URL host;
60         protected Optional<URI> path;
61         protected Logger logger;
62         protected String accept;
63         protected String contentType;
64
65         protected RestClient(RestProperties props, Optional<URI> path) {
66                 logger = Logger.getLogger(getClass().getName());
67                 msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL);
68
69                 headerMap = new HashMap<>();
70                 try {
71                         host = props.getEndpoint();
72                 } catch (MalformedURLException e) {
73                         logger.error("url not valid", e);
74                         throw new RuntimeException(e);
75                 }
76                 
77                 this.path = path;
78                 initializeClient(getClient());
79         }
80
81         protected RestClient(RestProperties props, Optional<URI> path, String accept, String contentType) {
82                 this(props, path);
83                 this.accept = accept;
84                 this.contentType = contentType;
85
86         }
87
88         protected RestClient(URL host, String contentType) {
89                 headerMap = new HashMap<>();
90                 logger = Logger.getLogger(getClass().getName());
91                 msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL);
92                 this.path = Optional.empty();
93                 this.host = host;
94                 this.contentType = contentType;
95                 initializeClient(getClient());
96         }
97
98         /**
99          * Override method to return false to disable logging.
100          * 
101          * @return true - to enable logging, false otherwise
102          */
103         protected boolean enableLogging() {
104                 return true;
105         }
106         
107         /**
108          * Override method to return custom value for max payload size.
109          * 
110          * @return Default value for MAX_PAYLOAD_SIZE = 1024 * 1024
111          */
112         protected int getMaxPayloadSize()
113         {
114                 return MAX_PAYLOAD_SIZE;
115         }
116
117         protected Builder getBuilder() {
118
119                 Builder builder = webTarget.request();
120                 initializeHeaderMap(headerMap);
121
122                 for (Entry<String, String> entry : headerMap.entrySet()) {
123                         builder.header(entry.getKey(), entry.getValue());
124                 }
125                 return builder;
126         }
127
128         protected abstract void initializeHeaderMap(Map<String, String> headerMap);
129
130         protected abstract Optional<ClientResponseFilter> addResponseFilter();
131
132         public abstract RestClient addRequestId(String requestId);
133
134         protected ContextResolver<ObjectMapper> getMapper() {
135                 return new CommonObjectMapperProvider();
136         }
137
138         protected String getAccept() {
139                 return accept;
140         }
141
142         protected String getContentType() {
143                 return contentType;
144         }
145
146         protected String getMergeContentType() {
147                 return "application/merge-patch+json";
148         }
149
150         protected Client getClient() {
151                 return ClientBuilder.newBuilder().build();
152         }
153
154         protected void initializeClient(Client client) {
155                 if (this.enableLogging()) {
156                         client.register(logger).register(new LoggingFilter(this.getMaxPayloadSize()));
157                 }
158                 client.register(this.getMapper());
159                 Optional<ClientResponseFilter> responseFilter = this.addResponseFilter();
160                 responseFilter.ifPresent(clientResponseFilter -> client.register(clientResponseFilter));
161                 webTarget = path.<WebTarget>map(uri -> client.target(UriBuilder.fromUri(host + uri.toString())))
162                         .orElseGet(() -> client.target(host.toString()));
163                 this.accept = MediaType.APPLICATION_JSON;
164                 this.contentType = MediaType.APPLICATION_JSON;
165         }
166
167         public Response get() {
168                 return this.getBuilder().accept(this.getAccept()).get();
169         }
170
171         public Response post(Object obj) {
172                 return this.getBuilder().accept(this.getAccept()).post(Entity.entity(obj, this.getContentType()));
173         }
174
175         public Response patch(Object obj) {
176                 return this.getBuilder().header("X-HTTP-Method-Override", "PATCH").accept(this.getAccept())
177                                 .post(Entity.entity(obj, this.getMergeContentType()));
178         }
179
180         public Response put(Object obj) {
181                 return this.getBuilder().accept(this.getAccept()).put(Entity.entity(obj, this.getContentType()));
182         }
183
184         public Response delete() {
185                 return this.getBuilder().accept(this.getAccept()).delete();
186         }
187
188         public Response delete(Object obj) {
189                 return this.getBuilder().header("X-HTTP-Method-Override", "DELETE").accept(this.getAccept())
190                                 .put(Entity.entity(obj, this.getContentType()));
191         }
192
193         public <T> T get(Class<T> resultClass) {
194                 return this.get().readEntity(resultClass);
195         }
196
197         public <T> T get(GenericType<T> resultClass) {
198                 return this.get().readEntity(resultClass);
199         }
200
201         public <T> T post(Object obj, Class<T> resultClass) {
202                 return this.post(obj).readEntity(resultClass);
203         }
204
205         public <T> T patch(Object obj, Class<T> resultClass) {
206                 return this.patch(obj).readEntity(resultClass);
207         }
208
209         public <T> T put(Object obj, Class<T> resultClass) {
210                 return this.put(obj).readEntity(resultClass);
211         }
212
213         public <T> T delete(Class<T> resultClass) {
214                 return this.delete().readEntity(resultClass);
215         }
216         
217         public <T> T delete(Object obj, Class<T> resultClass) {
218                 return this.delete(obj).readEntity(resultClass);
219         }
220 }