summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/openecomp/sparky/dal/rest/RestfulDataAccessor.java
blob: 1c2fb071a0bbeccc476764cc362b26fad333f02d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/**
 * ============LICENSE_START===================================================
 * SPARKY (AAI UI service)
 * ============================================================================
 * Copyright © 2017 AT&T Intellectual Property.
 * Copyright © 2017 Amdocs
 * All rights reserved.
 * ============================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=====================================================
 *
 * ECOMP and OpenECOMP are trademarks
 * and service marks of AT&T Intellectual Property.
 */

package org.openecomp.sparky.dal.rest;

import java.security.SecureRandom;

import org.openecomp.cl.api.Logger;
import org.openecomp.cl.eelf.LoggerFactory;
import org.openecomp.sparky.dal.cache.EntityCache;
import org.openecomp.sparky.logging.AaiUiMsgs;
import org.openecomp.sparky.util.NodeUtils;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;

/**
 * The Class RestfulDataAccessor.
 */
public class RestfulDataAccessor implements RestDataProvider {

  protected SecureRandom txnIdGenerator;

  protected RestClientBuilder clientBuilder;

  protected EntityCache entityCache;
  private boolean cacheEnabled;
  private static final Logger LOG =
      LoggerFactory.getInstance().getLogger(RestfulDataAccessor.class);

  private boolean resourceNotFoundErrorsSurpressed;

  public static final String APPLICATION_JSON = "application/json";
  public static final String APPLICATION_MERGE_PATCH_JSON = "application/merge-patch+json";
  public static final String APPLICATION_X_WWW_FORM_URL_ENCODED =
      "application/x-www-form-urlencoded";


  /**
   * Instantiates a new restful data accessor.
   *
   * @param clientBuilder the client builder
   */
  public RestfulDataAccessor(RestClientBuilder clientBuilder) {
    this.clientBuilder = clientBuilder;
    txnIdGenerator = new SecureRandom();
    resourceNotFoundErrorsSurpressed = false;
    cacheEnabled = false;
    entityCache = null;
  }

  protected boolean isCacheEnabled() {
    return cacheEnabled;
  }

  public void setCacheEnabled(boolean cacheEnabled) {
    this.cacheEnabled = cacheEnabled;
  }

  protected EntityCache getEntityCache() {
    return entityCache;
  }

  public void setEntityCache(EntityCache entityCache) {
    this.entityCache = entityCache;
  }

  /**
   * Cache result.
   *
   * @param result the result
   */
  private void cacheResult(OperationResult result) {
    if (cacheEnabled && entityCache != null) {
      final String id =
          NodeUtils.generateUniqueShaDigest(result.getRequestLink(), result.getRequestPayload());
      entityCache.put(id, result);
    }
  }

  /**
   * Populate operation result.
   *
   * @param response the response
   * @param opResult the op result
   */
  protected void populateOperationResult(ClientResponse response, OperationResult opResult) {

    if (response == null) {
      opResult.setResult(500, "Client response was null");
      return;
    }

    int statusCode = response.getStatus();
    String payload = response.getEntity(String.class);

    opResult.setResult(statusCode, payload);

  }

  /**
   * Gets the cached data.
   *
   * @param link the link
   * @param payload the payload
   * @return the cached data
   */
  private OperationResult getCachedData(String link, String payload) {
    if (cacheEnabled && entityCache != null) {
      final String id = NodeUtils.generateUniqueShaDigest(link, payload);
      return entityCache.get(id, link);
    }
    return null;
  }

  /* (non-Javadoc)
   * @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)
   */
  @Override
  public OperationResult doRestfulOperation(HttpMethod method, String url, String payload,
      String payloadType, String acceptContentType) {

    ClientResponse clientResponse = null;

    long startTimeInMs = System.currentTimeMillis();
    Client client = null;
    Builder builder = null;

    OperationResult operationResult = null;

    /*
     * Attempt to get cached data for the requested URL. We don't currently cache the other
     * operations.
     */

    operationResult = getCachedData(url, payload);

    if (operationResult != null) {

      /*
       * cache-hit, return what we found
       */

      // System.out.println("operationResult = " + operationResult.getResultCode());
      // System.out.println("opresult = " + operationResult.getResult());
      return operationResult;
    }

    /*
     * else cache miss / cache disabled (default operation)
     */

    operationResult = new OperationResult();
    operationResult.setRequestLink(url);

    try {

      client = clientBuilder.getClient();

      switch (method) {
        case GET: {
          builder = setClientDefaults(client, url, null, acceptContentType);
          clientResponse = builder.get(ClientResponse.class);
          break;
        }

        case PUT: {
          builder = setClientDefaults(client, url, payloadType, acceptContentType);
          clientResponse = builder.put(ClientResponse.class, payload);
          break;
        }

        case POST: {
          builder = setClientDefaults(client, url, payloadType, acceptContentType);
          clientResponse = builder.post(ClientResponse.class, payload);
          break;
        }

        case DELETE: {
          builder = setClientDefaults(client, url, null, acceptContentType);
          clientResponse = builder.delete(ClientResponse.class);
          break;
        }

        case PATCH: {
          builder = setClientDefaults(client, url, payloadType, acceptContentType);
          builder = builder.header("X-HTTP-Method-Override", "PATCH");
          clientResponse = builder.post(ClientResponse.class, payload);
          break;
        }

        case HEAD: {
          builder = setClientDefaults(client, url, null, acceptContentType);
          clientResponse = builder.head();
          break;
        }


        default: {
          operationResult.setResult(500, "Unhandled HTTP Method operation = " + method);
          return operationResult;
        }

      }

    } catch (Exception ex) {
      LOG.error(AaiUiMsgs.RESTFULL_OP_ERROR_VERBOSE, url, ex.getLocalizedMessage());
      operationResult.setResult(500,
          String.format("Error retrieving link = '%s' from restful endpoint due to error = '%s'",
              url, ex.getLocalizedMessage()));
      return operationResult;
    }

    populateOperationResult(clientResponse, operationResult);

    if (operationResult.getResultCode() != 404
        || (operationResult.getResultCode() == 404 && !isResourceNotFoundErrorsSurpressed())) {
      LOG.info(AaiUiMsgs.RESTFULL_OP_COMPLETE, method.toString(),
          String.valueOf(System.currentTimeMillis() - startTimeInMs), url,
          String.valueOf(operationResult.getResultCode()));
    }

    cacheResult(operationResult);

    return operationResult;

  }

  public boolean isResourceNotFoundErrorsSurpressed() {
    return resourceNotFoundErrorsSurpressed;
  }

  public void setResourceNotFoundErrorsSurpressed(boolean resourceNotFoundErrorsSurpressed) {
    this.resourceNotFoundErrorsSurpressed = resourceNotFoundErrorsSurpressed;
  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.dal.rest.RestDataProvider#doGet(java.lang.String, java.lang.String)
   */
  @Override
  public OperationResult doGet(String url, String acceptContentType) {
    return doRestfulOperation(HttpMethod.GET, url, null, null, acceptContentType);
  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.dal.rest.RestDataProvider#doDelete(java.lang.String, java.lang.String)
   */
  @Override
  public OperationResult doDelete(String url, String acceptContentType) {
    return doRestfulOperation(HttpMethod.DELETE, url, null, null, acceptContentType);
  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.dal.rest.RestDataProvider#doPost(java.lang.String, java.lang.String, java.lang.String)
   */
  @Override
  public OperationResult doPost(String url, String jsonPayload, String acceptContentType) {
    return doRestfulOperation(HttpMethod.POST, url, jsonPayload, APPLICATION_JSON,
        acceptContentType);
  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.dal.rest.RestDataProvider#doPut(java.lang.String, java.lang.String, java.lang.String)
   */
  @Override
  public OperationResult doPut(String url, String jsonPayload, String acceptContentType) {
    return doRestfulOperation(HttpMethod.PUT, url, jsonPayload, APPLICATION_JSON,
        acceptContentType);
  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.dal.rest.RestDataProvider#doPatch(java.lang.String, java.lang.String, java.lang.String)
   */
  @Override
  public OperationResult doPatch(String url, String jsonPayload, String acceptContentType) {
    return doRestfulOperation(HttpMethod.PATCH, url, jsonPayload, APPLICATION_MERGE_PATCH_JSON,
        acceptContentType);
  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.dal.rest.RestDataProvider#doHead(java.lang.String, java.lang.String)
   */
  @Override
  public OperationResult doHead(String url, String acceptContentType) {
    return doRestfulOperation(HttpMethod.HEAD, url, null, null, acceptContentType);
  }

  /**
   * Sets the client defaults.
   *
   * @param client the client
   * @param url the url
   * @param payloadContentType the payload content type
   * @param acceptContentType the accept content type
   * @return the builder
   */
  protected Builder setClientDefaults(Client client, String url, String payloadContentType,
      String acceptContentType) {
    WebResource resource = client.resource(url);
    Builder builder = null;
    builder = resource.accept(acceptContentType);

    if (payloadContentType != null) {
      builder = builder.header("Content-Type", payloadContentType);
    }

    return builder;
  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.dal.rest.RestDataProvider#shutdown()
   */
  @Override
  public void shutdown() {

    if (entityCache != null) {
      entityCache.shutdown();
    }

  }

  /* (non-Javadoc)
   * @see org.openecomp.sparky.dal.rest.RestDataProvider#clearCache()
   */
  @Override
  public void clearCache() {
    if (cacheEnabled) {
      entityCache.clear();
    }

  }

}