2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 package org.openecomp.sparky.dal.rest;
25 import java.security.SecureRandom;
27 import org.openecomp.cl.api.Logger;
28 import org.openecomp.cl.eelf.LoggerFactory;
29 import org.openecomp.sparky.dal.cache.EntityCache;
30 import org.openecomp.sparky.logging.AaiUiMsgs;
31 import org.openecomp.sparky.util.NodeUtils;
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;
39 * The Class RestfulDataAccessor.
41 public class RestfulDataAccessor implements RestDataProvider {
43 protected SecureRandom txnIdGenerator;
45 protected RestClientBuilder clientBuilder;
47 protected EntityCache entityCache;
48 private boolean cacheEnabled;
49 private static final Logger LOG =
50 LoggerFactory.getInstance().getLogger(RestfulDataAccessor.class);
52 private boolean resourceNotFoundErrorsSurpressed;
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";
61 * Instantiates a new restful data accessor.
63 * @param clientBuilder the client builder
65 public RestfulDataAccessor(RestClientBuilder clientBuilder) {
66 this.clientBuilder = clientBuilder;
67 txnIdGenerator = new SecureRandom();
68 resourceNotFoundErrorsSurpressed = false;
73 protected boolean isCacheEnabled() {
77 public void setCacheEnabled(boolean cacheEnabled) {
78 this.cacheEnabled = cacheEnabled;
81 protected EntityCache getEntityCache() {
85 public void setEntityCache(EntityCache entityCache) {
86 this.entityCache = entityCache;
92 * @param result the result
94 private void cacheResult(OperationResult result) {
95 if (cacheEnabled && entityCache != null) {
97 NodeUtils.generateUniqueShaDigest(result.getRequestLink(), result.getRequestPayload());
98 entityCache.put(id, result);
103 * Populate operation result.
105 * @param response the response
106 * @param opResult the op result
108 protected void populateOperationResult(ClientResponse response, OperationResult opResult) {
110 if (response == null) {
111 opResult.setResult(500, "Client response was null");
115 int statusCode = response.getStatus();
116 String payload = response.getEntity(String.class);
118 opResult.setResult(statusCode, payload);
123 * Gets the cached data.
125 * @param link the link
126 * @param payload the payload
127 * @return the cached data
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);
138 * @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)
141 public OperationResult doRestfulOperation(HttpMethod method, String url, String payload,
142 String payloadType, String acceptContentType) {
144 ClientResponse clientResponse = null;
146 long startTimeInMs = System.currentTimeMillis();
147 Client client = null;
148 Builder builder = null;
150 OperationResult operationResult = null;
153 * Attempt to get cached data for the requested URL. We don't currently cache the other
157 operationResult = getCachedData(url, payload);
159 if (operationResult != null) {
162 * cache-hit, return what we found
165 // System.out.println("operationResult = " + operationResult.getResultCode());
166 // System.out.println("opresult = " + operationResult.getResult());
167 return operationResult;
171 * else cache miss / cache disabled (default operation)
174 operationResult = new OperationResult();
175 operationResult.setRequestLink(url);
179 client = clientBuilder.getClient();
183 builder = setClientDefaults(client, url, null, acceptContentType);
184 clientResponse = builder.get(ClientResponse.class);
189 builder = setClientDefaults(client, url, payloadType, acceptContentType);
190 clientResponse = builder.put(ClientResponse.class, payload);
195 builder = setClientDefaults(client, url, payloadType, acceptContentType);
196 clientResponse = builder.post(ClientResponse.class, payload);
201 builder = setClientDefaults(client, url, null, acceptContentType);
202 clientResponse = builder.delete(ClientResponse.class);
207 builder = setClientDefaults(client, url, payloadType, acceptContentType);
208 builder = builder.header("X-HTTP-Method-Override", "PATCH");
209 clientResponse = builder.post(ClientResponse.class, payload);
214 builder = setClientDefaults(client, url, null, acceptContentType);
215 clientResponse = builder.head();
221 operationResult.setResult(500, "Unhandled HTTP Method operation = " + method);
222 return operationResult;
227 } catch (Exception ex) {
228 LOG.error(AaiUiMsgs.RESTFULL_OP_ERROR_VERBOSE, url, ex.getLocalizedMessage());
229 operationResult.setResult(500,
230 String.format("Error retrieving link = '%s' from restful endpoint due to error = '%s'",
231 url, ex.getLocalizedMessage()));
232 return operationResult;
235 populateOperationResult(clientResponse, operationResult);
237 if (operationResult.getResultCode() != 404
238 || (operationResult.getResultCode() == 404 && !isResourceNotFoundErrorsSurpressed())) {
239 LOG.info(AaiUiMsgs.RESTFULL_OP_COMPLETE, method.toString(),
240 String.valueOf(System.currentTimeMillis() - startTimeInMs), url,
241 String.valueOf(operationResult.getResultCode()));
244 cacheResult(operationResult);
246 return operationResult;
250 public boolean isResourceNotFoundErrorsSurpressed() {
251 return resourceNotFoundErrorsSurpressed;
254 public void setResourceNotFoundErrorsSurpressed(boolean resourceNotFoundErrorsSurpressed) {
255 this.resourceNotFoundErrorsSurpressed = resourceNotFoundErrorsSurpressed;
259 * @see org.openecomp.sparky.dal.rest.RestDataProvider#doGet(java.lang.String, java.lang.String)
262 public OperationResult doGet(String url, String acceptContentType) {
263 return doRestfulOperation(HttpMethod.GET, url, null, null, acceptContentType);
267 * @see org.openecomp.sparky.dal.rest.RestDataProvider#doDelete(java.lang.String, java.lang.String)
270 public OperationResult doDelete(String url, String acceptContentType) {
271 return doRestfulOperation(HttpMethod.DELETE, url, null, null, acceptContentType);
275 * @see org.openecomp.sparky.dal.rest.RestDataProvider#doPost(java.lang.String, java.lang.String, java.lang.String)
278 public OperationResult doPost(String url, String jsonPayload, String acceptContentType) {
279 return doRestfulOperation(HttpMethod.POST, url, jsonPayload, APPLICATION_JSON,
284 * @see org.openecomp.sparky.dal.rest.RestDataProvider#doPut(java.lang.String, java.lang.String, java.lang.String)
287 public OperationResult doPut(String url, String jsonPayload, String acceptContentType) {
288 return doRestfulOperation(HttpMethod.PUT, url, jsonPayload, APPLICATION_JSON,
293 * @see org.openecomp.sparky.dal.rest.RestDataProvider#doPatch(java.lang.String, java.lang.String, java.lang.String)
296 public OperationResult doPatch(String url, String jsonPayload, String acceptContentType) {
297 return doRestfulOperation(HttpMethod.PATCH, url, jsonPayload, APPLICATION_MERGE_PATCH_JSON,
302 * @see org.openecomp.sparky.dal.rest.RestDataProvider#doHead(java.lang.String, java.lang.String)
305 public OperationResult doHead(String url, String acceptContentType) {
306 return doRestfulOperation(HttpMethod.HEAD, url, null, null, acceptContentType);
310 * Sets the client defaults.
312 * @param client the client
314 * @param payloadContentType the payload content type
315 * @param acceptContentType the accept content type
316 * @return the builder
318 protected Builder setClientDefaults(Client client, String url, String payloadContentType,
319 String acceptContentType) {
320 WebResource resource = client.resource(url);
321 Builder builder = null;
322 builder = resource.accept(acceptContentType);
324 if (payloadContentType != null) {
325 builder = builder.header("Content-Type", payloadContentType);
332 * @see org.openecomp.sparky.dal.rest.RestDataProvider#shutdown()
335 public void shutdown() {
337 if (entityCache != null) {
338 entityCache.shutdown();
344 * @see org.openecomp.sparky.dal.rest.RestDataProvider#clearCache()
347 public void clearCache() {