Reduce the number of problems in aai-common by removing unused imports
[aai/aai-common.git] / aai-core / src / test / java / org / onap / aai / HttpTestUtil.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *    http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.aai;
22
23 import static org.mockito.Matchers.anyObject;
24 import static org.mockito.Mockito.*;
25
26 import java.io.UnsupportedEncodingException;
27 import java.net.URI;
28 import java.util.*;
29
30 import javax.ws.rs.core.*;
31
32 import org.javatuples.Pair;
33 import org.mockito.Mockito;
34 import org.onap.aai.config.SpringContextAware;
35 import org.onap.aai.exceptions.AAIException;
36 import org.onap.aai.introspection.Introspector;
37 import org.onap.aai.introspection.Loader;
38 import org.onap.aai.introspection.LoaderFactory;
39 import org.onap.aai.parsers.query.QueryParser;
40 import org.onap.aai.parsers.uri.URIToObject;
41 import org.onap.aai.rest.db.DBRequest;
42 import org.onap.aai.rest.db.HttpEntry;
43 import org.onap.aai.rest.ueb.UEBNotification;
44 import org.onap.aai.restcore.HttpMethod;
45 import org.onap.aai.restcore.RESTAPI;
46 import org.onap.aai.serialization.engines.QueryStyle;
47 import org.onap.aai.serialization.engines.TransactionalGraphEngine;
48 import org.onap.aai.setup.SchemaVersion;
49 import org.onap.aai.setup.SchemaVersions;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 public class HttpTestUtil extends RESTAPI {
54
55     protected HttpEntry traversalHttpEntry;
56
57     protected HttpEntry traversalUriHttpEntry;
58
59     private static final Logger logger = LoggerFactory.getLogger(HttpTestUtil.class);
60
61     protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
62     protected static final MediaType APPLICATION_XML = MediaType.valueOf("application/xml");
63
64     private static final String EMPTY = "";
65     private final QueryStyle queryStyle;
66
67     protected HttpHeaders httpHeaders;
68     protected UriInfo uriInfo;
69
70     protected MultivaluedMap<String, String> headersMultiMap;
71     protected MultivaluedMap<String, String> queryParameters;
72
73     protected List<String> aaiRequestContextList;
74     protected List<MediaType> outputMediaTypes;
75     protected LoaderFactory loaderFactory;
76     protected SchemaVersions schemaVersions;
77     protected UEBNotification notification;
78     protected int notificationDepth;
79     protected String acceptType;
80
81     public HttpTestUtil(QueryStyle qs) {
82         this(qs, "application/json");
83     }
84
85     public HttpTestUtil(QueryStyle qs, String acceptType) {
86         this.queryStyle = qs;
87         traversalHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class);
88         traversalUriHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class);
89         loaderFactory = SpringContextAware.getBean(LoaderFactory.class);
90         schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
91         notification = null;
92         this.acceptType = acceptType;
93     }
94
95     public HttpTestUtil(QueryStyle qs, UEBNotification uebNotification, int notificationDepth) {
96         this(qs, uebNotification, notificationDepth, "application/json");
97     }
98
99     public HttpTestUtil(QueryStyle qs, UEBNotification uebNotification, int notificationDepth, String acceptType) {
100         this.queryStyle = qs;
101         this.traversalHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class);
102         this.traversalUriHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class);
103         this.loaderFactory = SpringContextAware.getBean(LoaderFactory.class);
104         this.schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
105         this.notification = uebNotification;
106         this.notificationDepth = notificationDepth;
107         this.acceptType = acceptType;
108     }
109
110     public void init() {
111
112         httpHeaders = Mockito.mock(HttpHeaders.class);
113         uriInfo = Mockito.mock(UriInfo.class);
114
115         headersMultiMap = new MultivaluedHashMap<>();
116         queryParameters = Mockito.spy(new MultivaluedHashMap<>());
117
118         headersMultiMap.add("X-FromAppId", "JUNIT");
119         headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString());
120         headersMultiMap.add("Real-Time", "true");
121         headersMultiMap.add("Accept", acceptType);
122         headersMultiMap.add("aai-request-context", "");
123
124         outputMediaTypes = new ArrayList<>();
125         if (acceptType.equals("application/json")) {
126             outputMediaTypes.add(APPLICATION_JSON);
127         } else {
128             outputMediaTypes.add(APPLICATION_XML);
129         }
130
131         aaiRequestContextList = new ArrayList<>();
132         aaiRequestContextList.add("");
133
134         when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap);
135         when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
136
137         when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList);
138
139         when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
140         when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters);
141
142         doReturn(null).when(queryParameters).remove(anyObject());
143         when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON);
144
145         try {
146             if (notification != null) {
147                 doNothing().when(notification).triggerEvents();
148             }
149         } catch (AAIException e) {
150             e.printStackTrace();
151         }
152     }
153
154     public Response doPut(String uri, String payload) throws UnsupportedEncodingException, AAIException {
155         Map<String, String> puts = new HashMap<>();
156         puts.put(uri, payload);
157         return this.doPut(puts);
158     }
159
160     public Response doPut(Map<String, String> uriPayload) throws UnsupportedEncodingException, AAIException {
161
162         this.init();
163         Response response = null;
164         boolean success = true;
165         TransactionalGraphEngine dbEngine = null;
166
167         try {
168
169             List<DBRequest> dbRequestList = new ArrayList<>();
170             for (Map.Entry<String, String> entry : uriPayload.entrySet()) {
171
172                 String uri = entry.getKey();
173                 String payload = entry.getValue();
174                 if (uri.startsWith("/aai/")) {
175                     uri = uri.substring(5);
176                 }
177
178                 logger.info("Starting the put request for the uri {} with payload {}", uri, payload);
179
180                 String[] arr = uri.split("/");
181
182                 SchemaVersion version = null;
183
184                 if (arr.length > 1) {
185                     if (arr[0].matches("^v\\d+")) {
186                         version = new SchemaVersion(arr[0]);
187                         uri = uri.replaceAll("^v\\d+", "");
188                     }
189                 }
190
191                 if (version == null) {
192                     version = schemaVersions.getDefaultVersion();
193                 }
194                 Mockito.when(uriInfo.getPath()).thenReturn(uri);
195
196                 if (notification != null) {
197                     traversalHttpEntry.setHttpEntryProperties(version, notification, notificationDepth);
198                 } else {
199                     traversalHttpEntry.setHttpEntryProperties(version);
200                 }
201                 Loader loader = traversalHttpEntry.getLoader();
202                 dbEngine = traversalHttpEntry.getDbEngine();
203
204                 URI uriObject = UriBuilder.fromPath(uri).build();
205                 URIToObject uriToObject = new URIToObject(loader, uriObject);
206
207                 String objType = uriToObject.getEntityName();
208                 QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject);
209
210                 logger.info("Unmarshalling the payload to this {}", objType);
211
212                 Introspector obj;
213                 HttpMethod httpMethod;
214                 if (uri.contains("/relationship-list/relationship")) {
215                     obj = loader.unmarshal("relationship", payload,
216                             org.onap.aai.restcore.MediaType.getEnum("application/json"));
217                     httpMethod = HttpMethod.PUT_EDGE;
218                 } else {
219                     obj = loader.unmarshal(objType, payload,
220                             org.onap.aai.restcore.MediaType.getEnum("application/json"));
221                     httpMethod = HttpMethod.PUT;
222                     this.validateIntrospector(obj, loader, uriObject, httpMethod);
223                 }
224
225                 DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo,
226                         "JUNIT-TRANSACTION").rawRequestContent(payload).build();
227
228                 dbRequestList.add(dbRequest);
229
230             }
231
232             Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
233                     traversalHttpEntry.process(dbRequestList, "JUNIT");
234             response = responsesTuple.getValue1().get(0).getValue1();
235
236         } catch (AAIException e) {
237             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
238             success = false;
239         } catch (Exception e) {
240             AAIException ex = new AAIException("AAI_4000", e);
241             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
242             success = false;
243         } finally {
244             if (success) {
245                 if (response != null) {
246                     if ((response.getStatus() / 100) == 2) {
247                         logger.info("Successfully completed the PUT request with status {} and committing it to DB",
248                                 response.getStatus());
249                     } else {
250                         logFailure(HttpMethod.PUT, response);
251                     }
252                 }
253                 dbEngine.commit();
254             } else {
255                 if (response != null) {
256                     logFailure(HttpMethod.PUT, response);
257                 }
258                 dbEngine.rollback();
259             }
260         }
261
262         return response;
263     }
264
265     public Response doPatch(String uri, String payload) throws UnsupportedEncodingException, AAIException {
266
267         this.init();
268         Response response = null;
269         boolean success = true;
270         TransactionalGraphEngine dbEngine = null;
271
272         try {
273
274             if (uri.startsWith("/aai/")) {
275                 uri = uri.substring(5);
276             }
277
278             logger.info("Starting the put request for the uri {} with payload {}", uri, payload);
279
280             String[] arr = uri.split("/");
281
282             SchemaVersion version = null;
283
284             if (arr.length > 1) {
285                 if (arr[0].matches("^v\\d+")) {
286                     version = new SchemaVersion(arr[0]);
287                     uri = uri.replaceAll("^v\\d+", "");
288                 }
289             }
290
291             if (version == null) {
292                 version = schemaVersions.getDefaultVersion();
293             }
294             Mockito.when(uriInfo.getPath()).thenReturn(uri);
295
296             if (notification != null) {
297                 traversalHttpEntry.setHttpEntryProperties(version, notification, notificationDepth);
298             } else {
299                 traversalHttpEntry.setHttpEntryProperties(version);
300             }
301             Loader loader = traversalHttpEntry.getLoader();
302             dbEngine = traversalHttpEntry.getDbEngine();
303
304             URI uriObject = UriBuilder.fromPath(uri).build();
305             URIToObject uriToObject = new URIToObject(loader, uriObject);
306
307             String objType = uriToObject.getEntityName();
308             QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject);
309
310             logger.info("Unmarshalling the payload to this {}", objType);
311
312             Introspector obj;
313             HttpMethod httpMethod;
314             obj = loader.unmarshal(objType, payload, org.onap.aai.restcore.MediaType.getEnum("application/json"));
315             httpMethod = HttpMethod.MERGE_PATCH;
316             this.validateIntrospector(obj, loader, uriObject, httpMethod);
317
318             DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo,
319                     "JUNIT-TRANSACTION").rawRequestContent(payload).build();
320
321             List<DBRequest> dbRequestList = new ArrayList<>();
322             dbRequestList.add(dbRequest);
323
324             Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
325                     traversalHttpEntry.process(dbRequestList, "JUNIT");
326             response = responsesTuple.getValue1().get(0).getValue1();
327
328         } catch (AAIException e) {
329             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
330             success = false;
331         } catch (Exception e) {
332             AAIException ex = new AAIException("AAI_4000", e);
333             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
334             success = false;
335         } finally {
336             if (success) {
337                 if (response != null) {
338                     if ((response.getStatus() / 100) == 2) {
339                         logger.info("Successfully completed the PUT request with status {} and committing it to DB",
340                                 response.getStatus());
341                     } else {
342                         logFailure(HttpMethod.PUT, response);
343                     }
344                 }
345                 dbEngine.commit();
346             } else {
347                 if (response != null) {
348                     logFailure(HttpMethod.PUT, response);
349                 }
350                 dbEngine.rollback();
351             }
352         }
353
354         return response;
355     }
356
357     public Response doGet(String uri, String depth) {
358         return doGet(uri, depth, null);
359     }
360
361     public Response doGet(String uri, String depth, String format) {
362
363         this.init();
364         Response response = null;
365         boolean success = true;
366         TransactionalGraphEngine dbEngine = null;
367
368         try {
369
370             if (uri.startsWith("/aai/")) {
371                 uri = uri.substring(5);
372             }
373
374             logger.info("Starting the GET request for the uri {} with depth {}", uri, depth);
375
376             String[] arr = uri.split("/");
377
378             SchemaVersion version = null;
379
380             if (arr.length > 1) {
381                 if (arr[0].matches("^v\\d+")) {
382                     version = new SchemaVersion(arr[0]);
383                     uri = uri.replaceAll("^v\\d+", "");
384                 }
385             }
386
387             if (version == null) {
388                 version = schemaVersions.getDefaultVersion();
389             }
390
391             if (notification != null) {
392                 traversalHttpEntry.setHttpEntryProperties(version, notification, notificationDepth);
393             } else {
394                 traversalHttpEntry.setHttpEntryProperties(version);
395             }
396             Loader loader = traversalHttpEntry.getLoader();
397             dbEngine = traversalHttpEntry.getDbEngine();
398
399             URI uriObject = UriBuilder.fromPath(uri).build();
400
401             if (depth != null) {
402                 queryParameters.add("depth", depth);
403             }
404
405             if (format != null) {
406                 queryParameters.add("format", format);
407             }
408
409             QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject, queryParameters);
410
411             Mockito.when(uriInfo.getPath()).thenReturn(uri);
412
413             URIToObject uriToObject = new URIToObject(loader, uriObject);
414             String objType = "";
415             if (!uriQuery.getContainerType().equals("")) {
416                 objType = uriQuery.getContainerType();
417             } else {
418                 objType = uriQuery.getResultType();
419             }
420             logger.info("Unmarshalling the payload to this {}", objType);
421
422             Introspector obj = loader.introspectorFromName(objType);
423
424             DBRequest dbRequest = new DBRequest.Builder(HttpMethod.GET, uriObject, uriQuery, obj, httpHeaders, uriInfo,
425                     "JUNIT-TRANSACTION").build();
426
427             List<DBRequest> dbRequestList = new ArrayList<>();
428             dbRequestList.add(dbRequest);
429
430             Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
431                     traversalHttpEntry.process(dbRequestList, "JUNIT");
432             response = responsesTuple.getValue1().get(0).getValue1();
433
434         } catch (AAIException e) {
435             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
436             success = false;
437         } catch (Exception e) {
438             AAIException ex = new AAIException("AAI_4000", e);
439             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
440             success = false;
441         } finally {
442             if (success) {
443                 if (response != null) {
444                     if ((response.getStatus() / 100) == 2) {
445                         logger.info("Successfully completed the GET request with status {} and committing it to DB",
446                                 response.getStatus());
447                     } else {
448                         logFailure(HttpMethod.GET, response);
449                     }
450                 }
451                 dbEngine.commit();
452             } else {
453                 logFailure(HttpMethod.GET, response);
454                 dbEngine.rollback();
455             }
456         }
457
458         return response;
459     }
460
461     public Response doGet(String uri) throws UnsupportedEncodingException, AAIException {
462         return this.doGet(uri, "all");
463     }
464
465     public Response doDelete(Map<String, Pair<String, String>> deletes) {
466
467         this.init();
468         Response response = null;
469         boolean success = true;
470         TransactionalGraphEngine dbEngine = null;
471
472         try {
473
474             List<DBRequest> dbRequestList = new ArrayList<>();
475             for (Map.Entry<String, Pair<String, String>> delete : deletes.entrySet()) {
476                 String uri = delete.getKey();
477                 String resourceVersion = delete.getValue().getValue0();
478                 String content = delete.getValue().getValue1();
479                 uri = uri.replaceAll("/aai/", "");
480                 logger.info("Starting the delete request for the uri {} with resource version {}", uri,
481                         resourceVersion);
482
483                 String[] arr = uri.split("/");
484
485                 SchemaVersion version = null;
486
487                 if (arr.length > 1) {
488                     if (arr[0].matches("^v\\d+")) {
489                         version = new SchemaVersion(arr[0]);
490                         uri = uri.replaceAll("^v\\d+", "");
491                     }
492                 }
493
494                 if (version == null) {
495                     version = schemaVersions.getDefaultVersion();
496                 }
497
498                 Mockito.when(uriInfo.getPath()).thenReturn(uri);
499                 if (notification != null) {
500                     traversalHttpEntry.setHttpEntryProperties(version, notification, notificationDepth);
501                 } else {
502                     traversalHttpEntry.setHttpEntryProperties(version);
503                 }
504                 Loader loader = traversalHttpEntry.getLoader();
505                 dbEngine = traversalHttpEntry.getDbEngine();
506
507                 URI uriObject = UriBuilder.fromPath(uri).build();
508                 URIToObject uriToObject = new URIToObject(loader, uriObject);
509
510                 String objType = uriToObject.getEntityName();
511                 queryParameters.add("resource-version", resourceVersion);
512                 QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject, queryParameters);
513
514                 logger.info("Unmarshalling the payload to this {}", objType);
515
516                 Introspector obj;
517
518                 HttpMethod httpMethod;
519
520                 if (uri.contains("/relationship-list/relationship")) {
521                     httpMethod = HttpMethod.DELETE_EDGE;
522                     obj = loader.unmarshal("relationship", content,
523                             org.onap.aai.restcore.MediaType.getEnum("application/json"));
524                 } else {
525                     obj = loader.introspectorFromName(objType);
526                     httpMethod = HttpMethod.DELETE;
527                 }
528
529                 DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo,
530                         "JUNIT-TRANSACTION").build();
531
532                 dbRequestList.add(dbRequest);
533             }
534             Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
535                     traversalHttpEntry.process(dbRequestList, "JUNIT");
536             response = responsesTuple.getValue1().get(0).getValue1();
537
538         } catch (AAIException e) {
539             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.DELETE, e);
540             success = false;
541         } catch (Exception e) {
542             AAIException ex = new AAIException("AAI_4000", e);
543             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.DELETE, ex);
544             success = false;
545         } finally {
546             if (success) {
547                 if (response != null) {
548                     if ((response.getStatus() / 100) == 2) {
549                         logger.info("Successfully completed the DELETE request with status {} and committing it to DB",
550                                 response.getStatus());
551                     } else {
552                         logFailure(HttpMethod.DELETE, response);
553                     }
554                 }
555                 dbEngine.commit();
556             } else {
557                 logFailure(HttpMethod.DELETE, response);
558                 dbEngine.rollback();
559             }
560         }
561
562         return response;
563     }
564
565     public Response doDelete(String uri, String resourceVersion) {
566         return this.doDelete(uri, resourceVersion, null);
567     }
568
569     public Response doDelete(String uri, String resourceVersion, String content) {
570         Map<String, Pair<String, String>> deletes = new HashMap<>();
571         deletes.put(uri, new Pair<>(resourceVersion, content));
572         return this.doDelete(deletes);
573     }
574
575     public static void logFailure(HttpMethod httpMethod, Response response) {
576         logger.info("Unable to complete the {} request with status {} and rolling back", httpMethod.toString(),
577                 response.getStatus());
578         logger.info("Response body of failed request {}", response.getEntity());
579
580     }
581 }