588cbc951741235683ec84fad9b4504f7e4f9d6b
[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 org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25 import org.javatuples.Pair;
26 import org.mockito.Mockito;
27 import org.onap.aai.config.SpringContextAware;
28 import org.onap.aai.exceptions.AAIException;
29 import org.onap.aai.introspection.Introspector;
30 import org.onap.aai.introspection.Loader;
31 import org.onap.aai.introspection.LoaderFactory;
32 import org.onap.aai.parsers.query.QueryParser;
33 import org.onap.aai.parsers.uri.URIToObject;
34 import org.onap.aai.rest.db.DBRequest;
35 import org.onap.aai.rest.db.HttpEntry;
36 import org.onap.aai.rest.ueb.UEBNotification;
37 import org.onap.aai.restcore.HttpMethod;
38 import org.onap.aai.restcore.RESTAPI;
39 import org.onap.aai.serialization.engines.QueryStyle;
40 import org.onap.aai.serialization.engines.TransactionalGraphEngine;
41 import org.onap.aai.setup.SchemaVersion;
42 import org.onap.aai.setup.SchemaVersions;
43
44 import javax.ws.rs.core.*;
45 import java.io.UnsupportedEncodingException;
46 import java.net.URI;
47 import java.util.*;
48
49 import static org.mockito.Matchers.anyObject;
50 import static org.mockito.Mockito.*;
51
52 public class HttpTestUtil extends RESTAPI {
53
54     protected HttpEntry traversalHttpEntry;
55
56     protected HttpEntry traversalUriHttpEntry;
57
58     private static final Logger logger = LoggerFactory.getLogger(HttpTestUtil.class);
59
60     protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
61     protected static final MediaType APPLICATION_XML = MediaType.valueOf("application/xml");
62
63     private static final String EMPTY = "";
64     private final QueryStyle queryStyle;
65
66     protected HttpHeaders httpHeaders;
67     protected UriInfo uriInfo;
68
69     protected MultivaluedMap<String, String> headersMultiMap;
70     protected MultivaluedMap<String, String> queryParameters;
71
72     protected List<String> aaiRequestContextList;
73     protected List<MediaType> outputMediaTypes;
74     protected LoaderFactory loaderFactory;
75     protected SchemaVersions schemaVersions;
76     protected UEBNotification notification;
77     protected int notificationDepth;
78     protected String acceptType;
79
80     public HttpTestUtil(QueryStyle qs) {
81         this(qs, "application/json");
82     }
83
84     public HttpTestUtil(QueryStyle qs, String acceptType) {
85         this.queryStyle = qs;
86         traversalHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class);
87         traversalUriHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class);
88         loaderFactory = SpringContextAware.getBean(LoaderFactory.class);
89         schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
90         notification = null;
91         this.acceptType = acceptType;
92     }
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, org.onap.aai.restcore.MediaType.getEnum("application/json"));
220                     httpMethod = HttpMethod.PUT;
221                     this.validateIntrospector(obj, loader, uriObject, httpMethod);
222                 }
223
224                 DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo,
225                     "JUNIT-TRANSACTION").rawRequestContent(payload).build();
226
227                 dbRequestList.add(dbRequest);
228
229             }
230
231             Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
232                 traversalHttpEntry.process(dbRequestList, "JUNIT");
233             response = responsesTuple.getValue1().get(0).getValue1();
234
235         } catch (AAIException e) {
236             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
237             success = false;
238         } catch (Exception e) {
239             AAIException ex = new AAIException("AAI_4000", e);
240             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
241             success = false;
242         } finally {
243             if (success) {
244                 if (response != null) {
245                     if ((response.getStatus() / 100) == 2) {
246                         logger.info("Successfully completed the PUT request with status {} and committing it to DB",
247                             response.getStatus());
248                     } else {
249                         logFailure(HttpMethod.PUT, response);
250                     }
251                 }
252                 dbEngine.commit();
253             } else {
254                 if (response != null) {
255                     logFailure(HttpMethod.PUT, response);
256                 }
257                 dbEngine.rollback();
258             }
259         }
260
261         return response;
262     }
263
264     public Response doPatch(String uri, String payload) throws UnsupportedEncodingException, AAIException {
265
266         this.init();
267         Response response = null;
268         boolean success = true;
269         TransactionalGraphEngine dbEngine = null;
270
271         try {
272
273             if (uri.startsWith("/aai/")) {
274                 uri = uri.substring(5);
275             }
276
277             logger.info("Starting the put request for the uri {} with payload {}", uri, payload);
278
279             String[] arr = uri.split("/");
280
281             SchemaVersion version = null;
282
283             if (arr.length > 1) {
284                 if (arr[0].matches("^v\\d+")) {
285                     version = new SchemaVersion(arr[0]);
286                     uri = uri.replaceAll("^v\\d+", "");
287                 }
288             }
289
290             if (version == null) {
291                 version = schemaVersions.getDefaultVersion();
292             }
293             Mockito.when(uriInfo.getPath()).thenReturn(uri);
294
295             if(notification != null){
296                 traversalHttpEntry.setHttpEntryProperties(version, notification, notificationDepth);
297             } else {
298                 traversalHttpEntry.setHttpEntryProperties(version);
299             }
300             Loader loader = traversalHttpEntry.getLoader();
301             dbEngine = traversalHttpEntry.getDbEngine();
302
303             URI uriObject = UriBuilder.fromPath(uri).build();
304             URIToObject uriToObject = new URIToObject(loader, uriObject);
305
306             String objType = uriToObject.getEntityName();
307             QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject);
308
309             logger.info("Unmarshalling the payload to this {}", objType);
310
311             Introspector obj;
312             HttpMethod httpMethod;
313             obj = loader.unmarshal(objType, payload, org.onap.aai.restcore.MediaType.getEnum("application/json"));
314             httpMethod = HttpMethod.MERGE_PATCH;
315             this.validateIntrospector(obj, loader, uriObject, httpMethod);
316
317             DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo,
318                 "JUNIT-TRANSACTION").rawRequestContent(payload).build();
319
320             List<DBRequest> dbRequestList = new ArrayList<>();
321             dbRequestList.add(dbRequest);
322
323             Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
324                 traversalHttpEntry.process(dbRequestList, "JUNIT");
325             response = responsesTuple.getValue1().get(0).getValue1();
326
327         } catch (AAIException e) {
328             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
329             success = false;
330         } catch (Exception e) {
331             AAIException ex = new AAIException("AAI_4000", e);
332             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
333             success = false;
334         } finally {
335             if (success) {
336                 if (response != null) {
337                     if ((response.getStatus() / 100) == 2) {
338                         logger.info("Successfully completed the PUT request with status {} and committing it to DB",
339                             response.getStatus());
340                     } else {
341                         logFailure(HttpMethod.PUT, response);
342                     }
343                 }
344                 dbEngine.commit();
345             } else {
346                 if (response != null) {
347                     logFailure(HttpMethod.PUT, response);
348                 }
349                 dbEngine.rollback();
350             }
351         }
352
353         return response;
354     }
355
356     public Response doGet(String uri, String depth){
357        return doGet(uri, depth, null);
358     }
359
360     public Response doGet(String uri, String depth, String format) {
361
362         this.init();
363         Response response = null;
364         boolean success = true;
365         TransactionalGraphEngine dbEngine = null;
366
367         try {
368
369             if (uri.startsWith("/aai/")) {
370                 uri = uri.substring(5);
371             }
372
373             logger.info("Starting the GET request for the uri {} with depth {}", uri, depth);
374
375             String[] arr = uri.split("/");
376
377             SchemaVersion version = null;
378
379             if (arr.length > 1) {
380                 if (arr[0].matches("^v\\d+")) {
381                     version = new SchemaVersion(arr[0]);
382                     uri = uri.replaceAll("^v\\d+", "");
383                 }
384             }
385
386             if (version == null) {
387                 version = schemaVersions.getDefaultVersion();
388             }
389
390             if(notification != null){
391                 traversalHttpEntry.setHttpEntryProperties(version, notification, notificationDepth);
392             } else {
393                 traversalHttpEntry.setHttpEntryProperties(version);
394             }
395             Loader loader = traversalHttpEntry.getLoader();
396             dbEngine = traversalHttpEntry.getDbEngine();
397
398             URI uriObject = UriBuilder.fromPath(uri).build();
399
400             if (depth != null) {
401                 queryParameters.add("depth", depth);
402             }
403
404             if(format != null){
405                 queryParameters.add("format", format);
406             }
407
408             QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject, queryParameters);
409
410             Mockito.when(uriInfo.getPath()).thenReturn(uri);
411
412             URIToObject uriToObject = new URIToObject(loader, uriObject);
413             String objType = "";
414             if (!uriQuery.getContainerType().equals("")) {
415                 objType = uriQuery.getContainerType();
416             } else {
417                 objType = uriQuery.getResultType();
418             }
419             logger.info("Unmarshalling the payload to this {}", objType);
420
421             Introspector obj = loader.introspectorFromName(objType);
422
423             DBRequest dbRequest = new DBRequest.Builder(HttpMethod.GET, uriObject, uriQuery, obj, httpHeaders, uriInfo,
424                     "JUNIT-TRANSACTION").build();
425
426             List<DBRequest> dbRequestList = new ArrayList<>();
427             dbRequestList.add(dbRequest);
428
429             Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
430                     traversalHttpEntry.process(dbRequestList, "JUNIT");
431             response = responsesTuple.getValue1().get(0).getValue1();
432
433         } catch (AAIException e) {
434             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
435             success = false;
436         } catch (Exception e) {
437             AAIException ex = new AAIException("AAI_4000", e);
438             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
439             success = false;
440         } finally {
441             if (success) {
442                 if (response != null) {
443                     if ((response.getStatus() / 100) == 2) {
444                         logger.info("Successfully completed the GET request with status {} and committing it to DB",
445                                 response.getStatus());
446                     } else {
447                         logFailure(HttpMethod.GET, response);
448                     }
449                 }
450                 dbEngine.commit();
451             } else {
452                 logFailure(HttpMethod.GET, response);
453                 dbEngine.rollback();
454             }
455         }
456
457         return response;
458     }
459
460     public Response doGet(String uri) throws UnsupportedEncodingException, AAIException {
461         return this.doGet(uri, "all");
462     }
463
464     public Response doDelete(Map<String, Pair<String, String>> deletes){
465
466         this.init();
467         Response response = null;
468         boolean success = true;
469         TransactionalGraphEngine dbEngine = null;
470
471         try {
472
473             List<DBRequest> dbRequestList = new ArrayList<>();
474             for (Map.Entry<String, Pair<String, String>> delete : deletes.entrySet()) {
475                 String uri = delete.getKey();
476                 String resourceVersion = delete.getValue().getValue0();
477                 String content = delete.getValue().getValue1();
478                 uri = uri.replaceAll("/aai/", "");
479                 logger.info("Starting the delete request for the uri {} with resource version {}", uri, resourceVersion);
480
481                 String[] arr = uri.split("/");
482
483                 SchemaVersion version = null;
484
485                 if (arr.length > 1) {
486                     if (arr[0].matches("^v\\d+")) {
487                         version = new SchemaVersion(arr[0]);
488                         uri = uri.replaceAll("^v\\d+", "");
489                     }
490                 }
491
492                 if (version == null) {
493                     version = schemaVersions.getDefaultVersion();
494                 }
495
496                 Mockito.when(uriInfo.getPath()).thenReturn(uri);
497                 if (notification != null) {
498                     traversalHttpEntry.setHttpEntryProperties(version, notification, notificationDepth);
499                 } else {
500                     traversalHttpEntry.setHttpEntryProperties(version);
501                 }
502                 Loader loader = traversalHttpEntry.getLoader();
503                 dbEngine = traversalHttpEntry.getDbEngine();
504
505                 URI uriObject = UriBuilder.fromPath(uri).build();
506                 URIToObject uriToObject = new URIToObject(loader, uriObject);
507
508                 String objType = uriToObject.getEntityName();
509                 queryParameters.add("resource-version", resourceVersion);
510                 QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject, queryParameters);
511
512                 logger.info("Unmarshalling the payload to this {}", objType);
513
514                 Introspector obj;
515
516                 HttpMethod httpMethod;
517
518                 if (uri.contains("/relationship-list/relationship")) {
519                     httpMethod = HttpMethod.DELETE_EDGE;
520                     obj = loader.unmarshal("relationship", content, org.onap.aai.restcore.MediaType.getEnum("application/json"));
521                 } else {
522                     obj = loader.introspectorFromName(objType);
523                     httpMethod = HttpMethod.DELETE;
524                 }
525
526                 DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo, "JUNIT-TRANSACTION").build();
527
528
529                 dbRequestList.add(dbRequest);
530             }
531             Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
532                 traversalHttpEntry.process(dbRequestList, "JUNIT");
533             response = responsesTuple.getValue1().get(0).getValue1();
534
535         } catch (AAIException e) {
536             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.DELETE, e);
537             success = false;
538         } catch (Exception e) {
539             AAIException ex = new AAIException("AAI_4000", e);
540             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.DELETE, ex);
541             success = false;
542         } finally {
543             if (success) {
544                 if (response != null) {
545                     if ((response.getStatus() / 100) == 2) {
546                         logger.info("Successfully completed the DELETE request with status {} and committing it to DB",
547                             response.getStatus());
548                     } else {
549                         logFailure(HttpMethod.DELETE, response);
550                     }
551                 }
552                 dbEngine.commit();
553             } else {
554                 logFailure(HttpMethod.DELETE, response);
555                 dbEngine.rollback();
556             }
557         }
558
559         return response;
560     }
561
562     public Response doDelete(String uri, String resourceVersion) {
563         return this.doDelete(uri, resourceVersion, null);
564     }
565     public Response doDelete(String uri, String resourceVersion, String content) {
566         Map<String, Pair<String, String>> deletes = new HashMap<>();
567         deletes.put(uri, new Pair<>(resourceVersion, content));
568         return this.doDelete(deletes);
569     }
570
571     public static void logFailure(HttpMethod httpMethod, Response response) {
572         logger.info("Unable to complete the {} request with status {} and rolling back", httpMethod.toString(),
573                 response.getStatus());
574         logger.info("Response body of failed request {}", response.getEntity());
575
576     }
577 }