2 * ============LICENSE_START===================================================
3 * SPARKY (AAI UI service)
4 * ============================================================================
5 * Copyright © 2017 AT&T Intellectual Property.
6 * Copyright © 2017 Amdocs
8 * ============================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=====================================================
22 * ECOMP and OpenECOMP are trademarks
23 * and service marks of AT&T Intellectual Property.
26 package org.openecomp.sparky.dal.rest;
28 import java.security.SecureRandom;
30 import org.openecomp.cl.api.Logger;
31 import org.openecomp.cl.eelf.LoggerFactory;
32 import org.openecomp.sparky.dal.cache.EntityCache;
33 import org.openecomp.sparky.logging.AaiUiMsgs;
34 import org.openecomp.sparky.util.NodeUtils;
36 import com.sun.jersey.api.client.Client;
37 import com.sun.jersey.api.client.ClientResponse;
38 import com.sun.jersey.api.client.WebResource;
39 import com.sun.jersey.api.client.WebResource.Builder;
42 * The Class RestfulDataAccessor.
44 public class RestfulDataAccessor implements RestDataProvider {
46 protected SecureRandom txnIdGenerator;
48 protected RestClientBuilder clientBuilder;
50 protected EntityCache entityCache;
51 private boolean cacheEnabled;
52 private static final Logger LOG =
53 LoggerFactory.getInstance().getLogger(RestfulDataAccessor.class);
55 private boolean resourceNotFoundErrorsSurpressed;
57 public static final String APPLICATION_JSON = "application/json";
58 public static final String APPLICATION_MERGE_PATCH_JSON = "application/merge-patch+json";
59 public static final String APPLICATION_X_WWW_FORM_URL_ENCODED =
60 "application/x-www-form-urlencoded";
64 * Instantiates a new restful data accessor.
66 * @param clientBuilder the client builder
68 public RestfulDataAccessor(RestClientBuilder clientBuilder) {
69 this.clientBuilder = clientBuilder;
70 txnIdGenerator = new SecureRandom();
71 resourceNotFoundErrorsSurpressed = false;
76 protected boolean isCacheEnabled() {
80 public void setCacheEnabled(boolean cacheEnabled) {
81 this.cacheEnabled = cacheEnabled;
84 protected EntityCache getEntityCache() {
88 public void setEntityCache(EntityCache entityCache) {
89 this.entityCache = entityCache;
95 * @param result the result
97 private void cacheResult(OperationResult result) {
98 if (cacheEnabled && entityCache != null) {
100 NodeUtils.generateUniqueShaDigest(result.getRequestLink(), result.getRequestPayload());
101 entityCache.put(id, result);
106 * Populate operation result.
108 * @param response the response
109 * @param opResult the op result
111 protected void populateOperationResult(ClientResponse response, OperationResult opResult) {
113 if (response == null) {
114 opResult.setResult(500, "Client response was null");
118 int statusCode = response.getStatus();
119 String payload = response.getEntity(String.class);
121 opResult.setResult(statusCode, payload);
126 * Gets the cached data.
128 * @param link the link
129 * @param payload the payload
130 * @return the cached data
132 private OperationResult getCachedData(String link, String payload) {
133 if (cacheEnabled && entityCache != null) {
134 final String id = NodeUtils.generateUniqueShaDigest(link, payload);
135 return entityCache.get(id, link);
141 * @see org.openecomp.sparky.dal.rest.RestDataProvider#doRestfulOperation(org.openecomp.sparky.dal.rest.HttpMethod, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
144 public OperationResult doRestfulOperation(HttpMethod method, String url, String payload,
145 String payloadType, String acceptContentType) {
147 ClientResponse clientResponse = null;
149 long startTimeInMs = System.currentTimeMillis();
150 Client client = null;
151 Builder builder = null;
153 OperationResult operationResult = null;
156 * Attempt to get cached data for the requested URL. We don't currently cache the other
160 operationResult = getCachedData(url, payload);
162 if (operationResult != null) {
165 * cache-hit, return what we found
168 // System.out.println("operationResult = " + operationResult.getResultCode());
169 // System.out.println("opresult = " + operationResult.getResult());
170 return operationResult;
174 * else cache miss / cache disabled (default operation)
177 operationResult = new OperationResult();
178 operationResult.setRequestLink(url);
182 client = clientBuilder.getClient();
186 builder = setClientDefaults(client, url, null, acceptContentType);
187 clientResponse = builder.get(ClientResponse.class);
192 builder = setClientDefaults(client, url, payloadType, acceptContentType);
193 clientResponse = builder.put(ClientResponse.class, payload);
198 builder = setClientDefaults(client, url, payloadType, acceptContentType);
199 clientResponse = builder.post(ClientResponse.class, payload);
204 builder = setClientDefaults(client, url, null, acceptContentType);
205 clientResponse = builder.delete(ClientResponse.class);
210 builder = setClientDefaults(client, url, payloadType, acceptContentType);
211 builder = builder.header("X-HTTP-Method-Override", "PATCH");
212 clientResponse = builder.post(ClientResponse.class, payload);
217 builder = setClientDefaults(client, url, null, acceptContentType);
218 clientResponse = builder.head();
224 operationResult.setResult(500, "Unhandled HTTP Method operation = " + method);
225 return operationResult;
230 } catch (Exception ex) {
231 LOG.error(AaiUiMsgs.RESTFULL_OP_ERROR_VERBOSE, url, ex.getLocalizedMessage());
232 operationResult.setResult(500,
233 String.format("Error retrieving link = '%s' from restful endpoint due to error = '%s'",
234 url, ex.getLocalizedMessage()));
235 return operationResult;
238 populateOperationResult(clientResponse, operationResult);
240 if (operationResult.getResultCode() != 404
241 || (operationResult.getResultCode() == 404 && !isResourceNotFoundErrorsSurpressed())) {
242 LOG.info(AaiUiMsgs.RESTFULL_OP_COMPLETE, method.toString(),
243 String.valueOf(System.currentTimeMillis() - startTimeInMs), url,
244 String.valueOf(operationResult.getResultCode()));
247 cacheResult(operationResult);
249 return operationResult;
253 public boolean isResourceNotFoundErrorsSurpressed() {
254 return resourceNotFoundErrorsSurpressed;
257 public void setResourceNotFoundErrorsSurpressed(boolean resourceNotFoundErrorsSurpressed) {
258 this.resourceNotFoundErrorsSurpressed = resourceNotFoundErrorsSurpressed;
262 * @see org.openecomp.sparky.dal.rest.RestDataProvider#doGet(java.lang.String, java.lang.String)
265 public OperationResult doGet(String url, String acceptContentType) {
266 return doRestfulOperation(HttpMethod.GET, url, null, null, acceptContentType);
270 * @see org.openecomp.sparky.dal.rest.RestDataProvider#doDelete(java.lang.String, java.lang.String)
273 public OperationResult doDelete(String url, String acceptContentType) {
274 return doRestfulOperation(HttpMethod.DELETE, url, null, null, acceptContentType);
278 * @see org.openecomp.sparky.dal.rest.RestDataProvider#doPost(java.lang.String, java.lang.String, java.lang.String)
281 public OperationResult doPost(String url, String jsonPayload, String acceptContentType) {
282 return doRestfulOperation(HttpMethod.POST, url, jsonPayload, APPLICATION_JSON,
287 * @see org.openecomp.sparky.dal.rest.RestDataProvider#doPut(java.lang.String, java.lang.String, java.lang.String)
290 public OperationResult doPut(String url, String jsonPayload, String acceptContentType) {
291 return doRestfulOperation(HttpMethod.PUT, url, jsonPayload, APPLICATION_JSON,
296 * @see org.openecomp.sparky.dal.rest.RestDataProvider#doPatch(java.lang.String, java.lang.String, java.lang.String)
299 public OperationResult doPatch(String url, String jsonPayload, String acceptContentType) {
300 return doRestfulOperation(HttpMethod.PATCH, url, jsonPayload, APPLICATION_MERGE_PATCH_JSON,
305 * @see org.openecomp.sparky.dal.rest.RestDataProvider#doHead(java.lang.String, java.lang.String)
308 public OperationResult doHead(String url, String acceptContentType) {
309 return doRestfulOperation(HttpMethod.HEAD, url, null, null, acceptContentType);
313 * Sets the client defaults.
315 * @param client the client
317 * @param payloadContentType the payload content type
318 * @param acceptContentType the accept content type
319 * @return the builder
321 protected Builder setClientDefaults(Client client, String url, String payloadContentType,
322 String acceptContentType) {
323 WebResource resource = client.resource(url);
324 Builder builder = null;
325 builder = resource.accept(acceptContentType);
327 if (payloadContentType != null) {
328 builder = builder.header("Content-Type", payloadContentType);
335 * @see org.openecomp.sparky.dal.rest.RestDataProvider#shutdown()
338 public void shutdown() {
340 if (entityCache != null) {
341 entityCache.shutdown();
347 * @see org.openecomp.sparky.dal.rest.RestDataProvider#clearCache()
350 public void clearCache() {