9f07aff1b9221c52687cbaa50b33b0d19fa3ae4c
[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.cl.api.Logger;
28 import org.onap.aai.cl.eelf.LoggerFactory;
29 import org.onap.aai.sparky.logging.AaiUiMsgs;
30
31 import com.sun.jersey.api.client.Client;
32 import com.sun.jersey.api.client.ClientResponse;
33 import com.sun.jersey.api.client.WebResource;
34 import com.sun.jersey.api.client.WebResource.Builder;
35
36 /**
37  * The Class RestfulDataAccessor.
38  * 
39  * TODO: DELETE ME
40  * 
41  */
42 public class RestfulDataAccessor implements RestDataProvider {
43
44   protected SecureRandom txnIdGenerator;
45
46   protected RestClientBuilder clientBuilder;
47
48   private static final Logger LOG =
49       LoggerFactory.getInstance().getLogger(RestfulDataAccessor.class);
50
51   private boolean resourceNotFoundErrorsSurpressed;
52
53   public static final String APPLICATION_JSON = "application/json";
54   public static final String APPLICATION_MERGE_PATCH_JSON = "application/merge-patch+json";
55   public static final String APPLICATION_X_WWW_FORM_URL_ENCODED =
56       "application/x-www-form-urlencoded";
57
58
59   /**
60    * Instantiates a new restful data accessor.
61    *
62    * @param clientBuilder the client builder
63    */
64   public RestfulDataAccessor(RestClientBuilder clientBuilder) {
65     this.clientBuilder = clientBuilder;
66     txnIdGenerator = new SecureRandom();
67     resourceNotFoundErrorsSurpressed = false;
68   }
69
70   /**
71    * Populate operation result.
72    *
73    * @param response the response
74    * @param opResult the op result
75    */
76   protected void populateOperationResult(ClientResponse response, OperationResult opResult) {
77
78     if (response == null) {
79       opResult.setResult(500, "Client response was null");
80       return;
81     }
82
83     int statusCode = response.getStatus();
84     String payload = response.getEntity(String.class);
85
86     opResult.setResult(statusCode, payload);
87
88   }
89
90   /*
91    * (non-Javadoc)
92    * 
93    * @see
94    * org.openecomp.sparky.dal.rest.RestDataProvider#doRestfulOperation(org.openecomp.sparky.dal.rest
95    * .HttpMethod, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
96    */
97   @Override
98   public OperationResult doRestfulOperation(HttpMethod method, String url, String payload,
99       String payloadType, String acceptContentType) {
100
101     ClientResponse clientResponse = null;
102
103     long startTimeInMs = System.currentTimeMillis();
104     Client client = null;
105     Builder builder = null;
106
107     /*
108      * else cache miss / cache disabled (default operation)
109      */
110
111     OperationResult operationResult = new OperationResult();
112     operationResult.setRequestLink(url);
113
114     try {
115
116       client = clientBuilder.getClient();
117
118       switch (method) {
119         case GET: {
120           builder = setClientDefaults(client, url, null, acceptContentType);
121           clientResponse = builder.get(ClientResponse.class);
122           break;
123         }
124
125         case PUT: {
126           builder = setClientDefaults(client, url, payloadType, acceptContentType);
127           clientResponse = builder.put(ClientResponse.class, payload);
128           break;
129         }
130
131         case POST: {
132           builder = setClientDefaults(client, url, payloadType, acceptContentType);
133           clientResponse = builder.post(ClientResponse.class, payload);
134           break;
135         }
136
137         case DELETE: {
138           builder = setClientDefaults(client, url, null, acceptContentType);
139           clientResponse = builder.delete(ClientResponse.class);
140           break;
141         }
142
143         case PATCH: {
144           builder = setClientDefaults(client, url, payloadType, acceptContentType);
145           builder = builder.header("X-HTTP-Method-Override", "PATCH");
146           clientResponse = builder.post(ClientResponse.class, payload);
147           break;
148         }
149
150         case HEAD: {
151           builder = setClientDefaults(client, url, null, acceptContentType);
152           clientResponse = builder.head();
153           break;
154         }
155
156
157         default: {
158           operationResult.setResult(500, "Unhandled HTTP Method operation = " + method);
159           return operationResult;
160         }
161
162       }
163
164     } catch (Exception ex) {
165       LOG.error(AaiUiMsgs.RESTFULL_OP_ERROR_VERBOSE, url, ex.getLocalizedMessage());
166       operationResult.setResult(500,
167           String.format("Error retrieving link = '%s' from restful endpoint due to error = '%s'",
168               url, ex.getLocalizedMessage()));
169       return operationResult;
170     }
171
172     populateOperationResult(clientResponse, operationResult);
173
174     if (operationResult.getResultCode() != 404
175         || (operationResult.getResultCode() == 404 && !isResourceNotFoundErrorsSurpressed())) {
176       LOG.info(AaiUiMsgs.RESTFULL_OP_COMPLETE, method.toString(),
177           String.valueOf(System.currentTimeMillis() - startTimeInMs), url,
178           String.valueOf(operationResult.getResultCode()));
179     }
180
181     return operationResult;
182
183   }
184
185   public boolean isResourceNotFoundErrorsSurpressed() {
186     return resourceNotFoundErrorsSurpressed;
187   }
188
189   public void setResourceNotFoundErrorsSurpressed(boolean resourceNotFoundErrorsSurpressed) {
190     this.resourceNotFoundErrorsSurpressed = resourceNotFoundErrorsSurpressed;
191   }
192
193   /*
194    * (non-Javadoc)
195    * 
196    * @see org.openecomp.sparky.dal.rest.RestDataProvider#doGet(java.lang.String, java.lang.String)
197    */
198   @Override
199   public OperationResult doGet(String url, String acceptContentType) {
200     return doRestfulOperation(HttpMethod.GET, url, null, null, acceptContentType);
201   }
202
203   /*
204    * (non-Javadoc)
205    * 
206    * @see org.openecomp.sparky.dal.rest.RestDataProvider#doDelete(java.lang.String,
207    * java.lang.String)
208    */
209   @Override
210   public OperationResult doDelete(String url, String acceptContentType) {
211     return doRestfulOperation(HttpMethod.DELETE, url, null, null, acceptContentType);
212   }
213
214   /*
215    * (non-Javadoc)
216    * 
217    * @see org.openecomp.sparky.dal.rest.RestDataProvider#doPost(java.lang.String, java.lang.String,
218    * java.lang.String)
219    */
220   @Override
221   public OperationResult doPost(String url, String jsonPayload, String acceptContentType) {
222     return doRestfulOperation(HttpMethod.POST, url, jsonPayload, APPLICATION_JSON,
223         acceptContentType);
224   }
225
226   /*
227    * (non-Javadoc)
228    * 
229    * @see org.openecomp.sparky.dal.rest.RestDataProvider#doPut(java.lang.String, java.lang.String,
230    * java.lang.String)
231    */
232   @Override
233   public OperationResult doPut(String url, String jsonPayload, String acceptContentType) {
234     return doRestfulOperation(HttpMethod.PUT, url, jsonPayload, APPLICATION_JSON,
235         acceptContentType);
236   }
237
238   /*
239    * (non-Javadoc)
240    * 
241    * @see org.openecomp.sparky.dal.rest.RestDataProvider#doPatch(java.lang.String, java.lang.String,
242    * java.lang.String)
243    */
244   @Override
245   public OperationResult doPatch(String url, String jsonPayload, String acceptContentType) {
246     return doRestfulOperation(HttpMethod.PATCH, url, jsonPayload, APPLICATION_MERGE_PATCH_JSON,
247         acceptContentType);
248   }
249
250   /*
251    * (non-Javadoc)
252    * 
253    * @see org.openecomp.sparky.dal.rest.RestDataProvider#doHead(java.lang.String, java.lang.String)
254    */
255   @Override
256   public OperationResult doHead(String url, String acceptContentType) {
257     return doRestfulOperation(HttpMethod.HEAD, url, null, null, acceptContentType);
258   }
259
260   /**
261    * Sets the client defaults.
262    *
263    * @param client the client
264    * @param url the url
265    * @param payloadContentType the payload content type
266    * @param acceptContentType the accept content type
267    * @return the builder
268    */
269   protected Builder setClientDefaults(Client client, String url, String payloadContentType,
270       String acceptContentType) {
271     WebResource resource = client.resource(url);
272     Builder builder = null;
273     builder = resource.accept(acceptContentType);
274
275     if (payloadContentType != null) {
276       builder = builder.header("Content-Type", payloadContentType);
277     }
278
279     return builder;
280   }
281
282   /*
283    * (non-Javadoc)
284    * 
285    * @see org.openecomp.sparky.dal.rest.RestDataProvider#shutdown()
286    */
287   @Override
288   public void shutdown() {
289
290   }
291
292   /*
293    * (non-Javadoc)
294    * 
295    * @see org.openecomp.sparky.dal.rest.RestDataProvider#clearCache()
296    */
297   @Override
298   public void clearCache() {
299
300   }
301
302 }