Adding back-end support for UI filters
[aai/sparky-be.git] / src / main / java / org / onap / aai / sparky / dal / rest / RestfulDataAccessor.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017 Amdocs
7  * ================================================================================
8  * Licensed 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  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  *
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  */
23 package org.onap.aai.sparky.dal.rest;
24
25 import java.security.SecureRandom;
26
27 import org.onap.aai.sparky.dal.cache.EntityCache;
28 import org.onap.aai.sparky.logging.AaiUiMsgs;
29 import org.onap.aai.sparky.util.NodeUtils;
30 import org.onap.aai.cl.api.Logger;
31 import org.onap.aai.cl.eelf.LoggerFactory;
32
33 import com.sun.jersey.api.client.Client;
34 import com.sun.jersey.api.client.ClientResponse;
35 import com.sun.jersey.api.client.WebResource;
36 import com.sun.jersey.api.client.WebResource.Builder;
37
38 /**
39  * The Class RestfulDataAccessor.
40  */
41 public class RestfulDataAccessor implements RestDataProvider {
42
43   protected SecureRandom txnIdGenerator;
44
45   protected RestClientBuilder clientBuilder;
46
47   protected EntityCache entityCache;
48   private boolean cacheEnabled;
49   private static final Logger LOG =
50       LoggerFactory.getInstance().getLogger(RestfulDataAccessor.class);
51
52   private boolean resourceNotFoundErrorsSurpressed;
53
54   public static final String APPLICATION_JSON = "application/json";
55   public static final String APPLICATION_MERGE_PATCH_JSON = "application/merge-patch+json";
56   public static final String APPLICATION_X_WWW_FORM_URL_ENCODED =
57       "application/x-www-form-urlencoded";
58
59
60   /**
61    * Instantiates a new restful data accessor.
62    *
63    * @param clientBuilder the client builder
64    */
65   public RestfulDataAccessor(RestClientBuilder clientBuilder) {
66     this.clientBuilder = clientBuilder;
67     txnIdGenerator = new SecureRandom();
68     resourceNotFoundErrorsSurpressed = false;
69     cacheEnabled = false;
70     entityCache = null;
71   }
72
73   protected boolean isCacheEnabled() {
74     return cacheEnabled;
75   }
76
77   public void setCacheEnabled(boolean cacheEnabled) {
78     this.cacheEnabled = cacheEnabled;
79   }
80
81   protected EntityCache getEntityCache() {
82     return entityCache;
83   }
84
85   public void setEntityCache(EntityCache entityCache) {
86     this.entityCache = entityCache;
87   }
88
89   /**
90    * Cache result.
91    *
92    * @param result the result
93    */
94   private void cacheResult(OperationResult result) {
95     if (cacheEnabled && entityCache != null) {
96       final String id =
97           NodeUtils.generateUniqueShaDigest(result.getRequestLink(), result.getRequestPayload());
98       entityCache.put(id, result);
99     }
100   }
101
102   /**
103    * Populate operation result.
104    *
105    * @param response the response
106    * @param opResult the op result
107    */
108   protected void populateOperationResult(ClientResponse response, OperationResult opResult) {
109
110     if (response == null) {
111       opResult.setResult(500, "Client response was null");
112       return;
113     }
114
115     int statusCode = response.getStatus();
116     String payload = response.getEntity(String.class);
117
118     opResult.setResult(statusCode, payload);
119
120   }
121
122   /**
123    * Gets the cached data.
124    *
125    * @param link the link
126    * @param payload the payload
127    * @return the cached data
128    */
129   private OperationResult getCachedData(String link, String payload) {
130     if (cacheEnabled && entityCache != null) {
131       final String id = NodeUtils.generateUniqueShaDigest(link, payload);
132       return entityCache.get(id, link);
133     }
134     return null;
135   }
136
137   /*
138    * (non-Javadoc)
139    * 
140    * @see
141    * org.onap.aai.sparky.dal.rest.RestDataProvider#doRestfulOperation(org.onap.aai.sparky.dal.rest.
142    * HttpMethod, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
143    */
144   @Override
145   public OperationResult doRestfulOperation(HttpMethod method, String url, String payload,
146       String payloadType, String acceptContentType) {
147
148     ClientResponse clientResponse = null;
149
150     long startTimeInMs = System.currentTimeMillis();
151     Client client = null;
152     Builder builder = null;
153
154     OperationResult operationResult = null;
155
156     /*
157      * Attempt to get cached data for the requested URL. We don't currently cache the other
158      * operations.
159      */
160
161     operationResult = getCachedData(url, payload);
162
163     if (operationResult != null) {
164
165       /*
166        * cache-hit, return what we found
167        */
168
169       // System.out.println("operationResult = " + operationResult.getResultCode());
170       // System.out.println("opresult = " + operationResult.getResult());
171       return operationResult;
172     }
173
174     /*
175      * else cache miss / cache disabled (default operation)
176      */
177
178     operationResult = new OperationResult();
179     operationResult.setRequestLink(url);
180
181     try {
182
183       client = clientBuilder.getClient();
184
185       switch (method) {
186         case GET: {
187           builder = setClientDefaults(client, url, null, acceptContentType);
188           clientResponse = builder.get(ClientResponse.class);
189           break;
190         }
191
192         case PUT: {
193           builder = setClientDefaults(client, url, payloadType, acceptContentType);
194           clientResponse = builder.put(ClientResponse.class, payload);
195           break;
196         }
197
198         case POST: {
199           builder = setClientDefaults(client, url, payloadType, acceptContentType);
200           clientResponse = builder.post(ClientResponse.class, payload);
201           break;
202         }
203
204         case DELETE: {
205           builder = setClientDefaults(client, url, null, acceptContentType);
206           clientResponse = builder.delete(ClientResponse.class);
207           break;
208         }
209
210         case PATCH: {
211           builder = setClientDefaults(client, url, payloadType, acceptContentType);
212           builder = builder.header("X-HTTP-Method-Override", "PATCH");
213           clientResponse = builder.post(ClientResponse.class, payload);
214           break;
215         }
216
217         case HEAD: {
218           builder = setClientDefaults(client, url, null, acceptContentType);
219           clientResponse = builder.head();
220           break;
221         }
222
223
224         default: {
225           operationResult.setResult(500, "Unhandled HTTP Method operation = " + method);
226           return operationResult;
227         }
228
229       }
230
231     } catch (Exception ex) {
232       LOG.error(AaiUiMsgs.RESTFULL_OP_ERROR_VERBOSE, url, ex.getLocalizedMessage());
233       operationResult.setResult(500,
234           String.format("Error retrieving link = '%s' from restful endpoint due to error = '%s'",
235               url, ex.getLocalizedMessage()));
236       return operationResult;
237     }
238
239     populateOperationResult(clientResponse, operationResult);
240
241     if (operationResult.getResultCode() != 404
242         || (operationResult.getResultCode() == 404 && !isResourceNotFoundErrorsSurpressed())) {
243       LOG.info(AaiUiMsgs.RESTFULL_OP_COMPLETE, method.toString(),
244           String.valueOf(System.currentTimeMillis() - startTimeInMs), url,
245           String.valueOf(operationResult.getResultCode()));
246     }
247
248     cacheResult(operationResult);
249
250     return operationResult;
251
252   }
253
254   public boolean isResourceNotFoundErrorsSurpressed() {
255     return resourceNotFoundErrorsSurpressed;
256   }
257
258   public void setResourceNotFoundErrorsSurpressed(boolean resourceNotFoundErrorsSurpressed) {
259     this.resourceNotFoundErrorsSurpressed = resourceNotFoundErrorsSurpressed;
260   }
261
262   /*
263    * (non-Javadoc)
264    * 
265    * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doGet(java.lang.String, java.lang.String)
266    */
267   @Override
268   public OperationResult doGet(String url, String acceptContentType) {
269     return doRestfulOperation(HttpMethod.GET, url, null, null, acceptContentType);
270   }
271
272   /*
273    * (non-Javadoc)
274    * 
275    * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doDelete(java.lang.String, java.lang.String)
276    */
277   @Override
278   public OperationResult doDelete(String url, String acceptContentType) {
279     return doRestfulOperation(HttpMethod.DELETE, url, null, null, acceptContentType);
280   }
281
282   /*
283    * (non-Javadoc)
284    * 
285    * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doPost(java.lang.String, java.lang.String,
286    * java.lang.String)
287    */
288   @Override
289   public OperationResult doPost(String url, String jsonPayload, String acceptContentType) {
290     return doRestfulOperation(HttpMethod.POST, url, jsonPayload, APPLICATION_JSON,
291         acceptContentType);
292   }
293
294   /*
295    * (non-Javadoc)
296    * 
297    * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doPut(java.lang.String, java.lang.String,
298    * java.lang.String)
299    */
300   @Override
301   public OperationResult doPut(String url, String jsonPayload, String acceptContentType) {
302     return doRestfulOperation(HttpMethod.PUT, url, jsonPayload, APPLICATION_JSON,
303         acceptContentType);
304   }
305
306   /*
307    * (non-Javadoc)
308    * 
309    * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doPatch(java.lang.String, java.lang.String,
310    * java.lang.String)
311    */
312   @Override
313   public OperationResult doPatch(String url, String jsonPayload, String acceptContentType) {
314     return doRestfulOperation(HttpMethod.PATCH, url, jsonPayload, APPLICATION_MERGE_PATCH_JSON,
315         acceptContentType);
316   }
317
318   /*
319    * (non-Javadoc)
320    * 
321    * @see org.onap.aai.sparky.dal.rest.RestDataProvider#doHead(java.lang.String, java.lang.String)
322    */
323   @Override
324   public OperationResult doHead(String url, String acceptContentType) {
325     return doRestfulOperation(HttpMethod.HEAD, url, null, null, acceptContentType);
326   }
327
328   /**
329    * Sets the client defaults.
330    *
331    * @param client the client
332    * @param url the url
333    * @param payloadContentType the payload content type
334    * @param acceptContentType the accept content type
335    * @return the builder
336    */
337   protected Builder setClientDefaults(Client client, String url, String payloadContentType,
338       String acceptContentType) {
339     WebResource resource = client.resource(url);
340     Builder builder = null;
341     builder = resource.accept(acceptContentType);
342
343     if (payloadContentType != null) {
344       builder = builder.header("Content-Type", payloadContentType);
345     }
346
347     return builder;
348   }
349
350   /*
351    * (non-Javadoc)
352    * 
353    * @see org.onap.aai.sparky.dal.rest.RestDataProvider#shutdown()
354    */
355   @Override
356   public void shutdown() {
357
358     if (entityCache != null) {
359       entityCache.shutdown();
360     }
361
362   }
363
364   /*
365    * (non-Javadoc)
366    * 
367    * @see org.onap.aai.sparky.dal.rest.RestDataProvider#clearCache()
368    */
369   @Override
370   public void clearCache() {
371     if (cacheEnabled) {
372       entityCache.clear();
373     }
374
375   }
376
377 }