2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
23 import static org.mockito.Matchers.anyObject;
24 import static org.mockito.Mockito.*;
26 import java.io.UnsupportedEncodingException;
30 import javax.ws.rs.core.*;
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;
53 public class HttpTestUtil extends RESTAPI {
55 protected HttpEntry traversalHttpEntry;
57 protected HttpEntry traversalUriHttpEntry;
59 private static final Logger logger = LoggerFactory.getLogger(HttpTestUtil.class);
61 protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
62 protected static final MediaType APPLICATION_XML = MediaType.valueOf("application/xml");
64 private static final String EMPTY = "";
65 private final QueryStyle queryStyle;
67 protected HttpHeaders httpHeaders;
68 protected UriInfo uriInfo;
70 protected MultivaluedMap<String, String> headersMultiMap;
71 protected MultivaluedMap<String, String> queryParameters;
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;
81 public HttpTestUtil(QueryStyle qs) {
82 this(qs, "application/json");
85 public HttpTestUtil(QueryStyle qs, String acceptType) {
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");
92 this.acceptType = acceptType;
95 public HttpTestUtil(QueryStyle qs, UEBNotification uebNotification, int notificationDepth) {
96 this(qs, uebNotification, notificationDepth, "application/json");
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;
112 httpHeaders = Mockito.mock(HttpHeaders.class);
113 uriInfo = Mockito.mock(UriInfo.class);
115 headersMultiMap = new MultivaluedHashMap<>();
116 queryParameters = Mockito.spy(new MultivaluedHashMap<>());
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", "");
124 outputMediaTypes = new ArrayList<>();
125 if (acceptType.equals("application/json")) {
126 outputMediaTypes.add(APPLICATION_JSON);
128 outputMediaTypes.add(APPLICATION_XML);
131 aaiRequestContextList = new ArrayList<>();
132 aaiRequestContextList.add("");
134 when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap);
135 when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
137 when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList);
139 when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
140 when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters);
142 doReturn(null).when(queryParameters).remove(anyObject());
143 when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON);
146 if (notification != null) {
147 doNothing().when(notification).triggerEvents();
149 } catch (AAIException e) {
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);
160 public Response doPut(Map<String, String> uriPayload) throws UnsupportedEncodingException, AAIException {
163 Response response = null;
164 boolean success = true;
165 TransactionalGraphEngine dbEngine = null;
169 List<DBRequest> dbRequestList = new ArrayList<>();
170 for (Map.Entry<String, String> entry : uriPayload.entrySet()) {
172 String uri = entry.getKey();
173 String payload = entry.getValue();
174 if (uri.startsWith("/aai/")) {
175 uri = uri.substring(5);
178 logger.info("Starting the put request for the uri {} with payload {}", uri, payload);
180 String[] arr = uri.split("/");
182 SchemaVersion version = null;
184 if (arr.length > 1) {
185 if (arr[0].matches("^v\\d+")) {
186 version = new SchemaVersion(arr[0]);
187 uri = uri.replaceAll("^v\\d+", "");
191 if (version == null) {
192 version = schemaVersions.getDefaultVersion();
194 Mockito.when(uriInfo.getPath()).thenReturn(uri);
196 if (notification != null) {
197 traversalHttpEntry.setHttpEntryProperties(version, notification, notificationDepth);
199 traversalHttpEntry.setHttpEntryProperties(version);
201 Loader loader = traversalHttpEntry.getLoader();
202 dbEngine = traversalHttpEntry.getDbEngine();
204 URI uriObject = UriBuilder.fromPath(uri).build();
205 URIToObject uriToObject = new URIToObject(loader, uriObject);
207 String objType = uriToObject.getEntityName();
208 QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject);
210 logger.info("Unmarshalling the payload to this {}", objType);
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;
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);
225 DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo,
226 "JUNIT-TRANSACTION").rawRequestContent(payload).build();
228 dbRequestList.add(dbRequest);
232 Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
233 traversalHttpEntry.process(dbRequestList, "JUNIT");
234 response = responsesTuple.getValue1().get(0).getValue1();
236 } catch (AAIException e) {
237 response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
239 } catch (Exception e) {
240 AAIException ex = new AAIException("AAI_4000", e);
241 response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
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());
250 logFailure(HttpMethod.PUT, response);
255 if (response != null) {
256 logFailure(HttpMethod.PUT, response);
265 public Response doPatch(String uri, String payload) throws UnsupportedEncodingException, AAIException {
268 Response response = null;
269 boolean success = true;
270 TransactionalGraphEngine dbEngine = null;
274 if (uri.startsWith("/aai/")) {
275 uri = uri.substring(5);
278 logger.info("Starting the put request for the uri {} with payload {}", uri, payload);
280 String[] arr = uri.split("/");
282 SchemaVersion version = null;
284 if (arr.length > 1) {
285 if (arr[0].matches("^v\\d+")) {
286 version = new SchemaVersion(arr[0]);
287 uri = uri.replaceAll("^v\\d+", "");
291 if (version == null) {
292 version = schemaVersions.getDefaultVersion();
294 Mockito.when(uriInfo.getPath()).thenReturn(uri);
296 if (notification != null) {
297 traversalHttpEntry.setHttpEntryProperties(version, notification, notificationDepth);
299 traversalHttpEntry.setHttpEntryProperties(version);
301 Loader loader = traversalHttpEntry.getLoader();
302 dbEngine = traversalHttpEntry.getDbEngine();
304 URI uriObject = UriBuilder.fromPath(uri).build();
305 URIToObject uriToObject = new URIToObject(loader, uriObject);
307 String objType = uriToObject.getEntityName();
308 QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject);
310 logger.info("Unmarshalling the payload to this {}", objType);
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);
318 DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo,
319 "JUNIT-TRANSACTION").rawRequestContent(payload).build();
321 List<DBRequest> dbRequestList = new ArrayList<>();
322 dbRequestList.add(dbRequest);
324 Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
325 traversalHttpEntry.process(dbRequestList, "JUNIT");
326 response = responsesTuple.getValue1().get(0).getValue1();
328 } catch (AAIException e) {
329 response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
331 } catch (Exception e) {
332 AAIException ex = new AAIException("AAI_4000", e);
333 response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
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());
342 logFailure(HttpMethod.PUT, response);
347 if (response != null) {
348 logFailure(HttpMethod.PUT, response);
357 public Response doGet(String uri, String depth) {
358 return doGet(uri, depth, null);
361 public Response doGet(String uri, String depth, String format) {
364 Response response = null;
365 boolean success = true;
366 TransactionalGraphEngine dbEngine = null;
370 if (uri.startsWith("/aai/")) {
371 uri = uri.substring(5);
374 logger.info("Starting the GET request for the uri {} with depth {}", uri, depth);
376 String[] arr = uri.split("/");
378 SchemaVersion version = null;
380 if (arr.length > 1) {
381 if (arr[0].matches("^v\\d+")) {
382 version = new SchemaVersion(arr[0]);
383 uri = uri.replaceAll("^v\\d+", "");
387 if (version == null) {
388 version = schemaVersions.getDefaultVersion();
391 if (notification != null) {
392 traversalHttpEntry.setHttpEntryProperties(version, notification, notificationDepth);
394 traversalHttpEntry.setHttpEntryProperties(version);
396 Loader loader = traversalHttpEntry.getLoader();
397 dbEngine = traversalHttpEntry.getDbEngine();
399 URI uriObject = UriBuilder.fromPath(uri).build();
402 queryParameters.add("depth", depth);
405 if (format != null) {
406 queryParameters.add("format", format);
409 QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject, queryParameters);
411 Mockito.when(uriInfo.getPath()).thenReturn(uri);
413 URIToObject uriToObject = new URIToObject(loader, uriObject);
415 if (!uriQuery.getContainerType().equals("")) {
416 objType = uriQuery.getContainerType();
418 objType = uriQuery.getResultType();
420 logger.info("Unmarshalling the payload to this {}", objType);
422 Introspector obj = loader.introspectorFromName(objType);
424 DBRequest dbRequest = new DBRequest.Builder(HttpMethod.GET, uriObject, uriQuery, obj, httpHeaders, uriInfo,
425 "JUNIT-TRANSACTION").build();
427 List<DBRequest> dbRequestList = new ArrayList<>();
428 dbRequestList.add(dbRequest);
430 Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
431 traversalHttpEntry.process(dbRequestList, "JUNIT");
432 response = responsesTuple.getValue1().get(0).getValue1();
434 } catch (AAIException e) {
435 response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
437 } catch (Exception e) {
438 AAIException ex = new AAIException("AAI_4000", e);
439 response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
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());
448 logFailure(HttpMethod.GET, response);
453 logFailure(HttpMethod.GET, response);
461 public Response doGet(String uri) throws UnsupportedEncodingException, AAIException {
462 return this.doGet(uri, "all");
465 public Response doDelete(Map<String, Pair<String, String>> deletes) {
468 Response response = null;
469 boolean success = true;
470 TransactionalGraphEngine dbEngine = null;
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,
483 String[] arr = uri.split("/");
485 SchemaVersion version = null;
487 if (arr.length > 1) {
488 if (arr[0].matches("^v\\d+")) {
489 version = new SchemaVersion(arr[0]);
490 uri = uri.replaceAll("^v\\d+", "");
494 if (version == null) {
495 version = schemaVersions.getDefaultVersion();
498 Mockito.when(uriInfo.getPath()).thenReturn(uri);
499 if (notification != null) {
500 traversalHttpEntry.setHttpEntryProperties(version, notification, notificationDepth);
502 traversalHttpEntry.setHttpEntryProperties(version);
504 Loader loader = traversalHttpEntry.getLoader();
505 dbEngine = traversalHttpEntry.getDbEngine();
507 URI uriObject = UriBuilder.fromPath(uri).build();
508 URIToObject uriToObject = new URIToObject(loader, uriObject);
510 String objType = uriToObject.getEntityName();
511 queryParameters.add("resource-version", resourceVersion);
512 QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject, queryParameters);
514 logger.info("Unmarshalling the payload to this {}", objType);
518 HttpMethod httpMethod;
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"));
525 obj = loader.introspectorFromName(objType);
526 httpMethod = HttpMethod.DELETE;
529 DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo,
530 "JUNIT-TRANSACTION").build();
532 dbRequestList.add(dbRequest);
534 Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
535 traversalHttpEntry.process(dbRequestList, "JUNIT");
536 response = responsesTuple.getValue1().get(0).getValue1();
538 } catch (AAIException e) {
539 response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.DELETE, e);
541 } catch (Exception e) {
542 AAIException ex = new AAIException("AAI_4000", e);
543 response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.DELETE, ex);
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());
552 logFailure(HttpMethod.DELETE, response);
557 logFailure(HttpMethod.DELETE, response);
565 public Response doDelete(String uri, String resourceVersion) {
566 return this.doDelete(uri, resourceVersion, null);
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);
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());