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 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;
44 import javax.ws.rs.core.*;
45 import java.io.UnsupportedEncodingException;
49 import static org.mockito.Matchers.anyObject;
50 import static org.mockito.Mockito.*;
52 public class HttpTestUtil extends RESTAPI {
54 protected HttpEntry traversalHttpEntry;
56 protected HttpEntry traversalUriHttpEntry;
58 private static final Logger logger = LoggerFactory.getLogger(HttpTestUtil.class);
60 protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
61 protected static final MediaType APPLICATION_XML = MediaType.valueOf("application/xml");
63 private static final String EMPTY = "";
64 private final QueryStyle queryStyle;
66 protected HttpHeaders httpHeaders;
67 protected UriInfo uriInfo;
69 protected MultivaluedMap<String, String> headersMultiMap;
70 protected MultivaluedMap<String, String> queryParameters;
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;
80 public HttpTestUtil(QueryStyle qs) {
81 this(qs, "application/json");
84 public HttpTestUtil(QueryStyle qs, String acceptType) {
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");
91 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, org.onap.aai.restcore.MediaType.getEnum("application/json"));
220 httpMethod = HttpMethod.PUT;
221 this.validateIntrospector(obj, loader, uriObject, httpMethod);
224 DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo,
225 "JUNIT-TRANSACTION").rawRequestContent(payload).build();
227 dbRequestList.add(dbRequest);
231 Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
232 traversalHttpEntry.process(dbRequestList, "JUNIT");
233 response = responsesTuple.getValue1().get(0).getValue1();
235 } catch (AAIException e) {
236 response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
238 } catch (Exception e) {
239 AAIException ex = new AAIException("AAI_4000", e);
240 response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
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());
249 logFailure(HttpMethod.PUT, response);
254 if (response != null) {
255 logFailure(HttpMethod.PUT, response);
264 public Response doPatch(String uri, String payload) throws UnsupportedEncodingException, AAIException {
267 Response response = null;
268 boolean success = true;
269 TransactionalGraphEngine dbEngine = null;
273 if (uri.startsWith("/aai/")) {
274 uri = uri.substring(5);
277 logger.info("Starting the put request for the uri {} with payload {}", uri, payload);
279 String[] arr = uri.split("/");
281 SchemaVersion version = null;
283 if (arr.length > 1) {
284 if (arr[0].matches("^v\\d+")) {
285 version = new SchemaVersion(arr[0]);
286 uri = uri.replaceAll("^v\\d+", "");
290 if (version == null) {
291 version = schemaVersions.getDefaultVersion();
293 Mockito.when(uriInfo.getPath()).thenReturn(uri);
295 if(notification != null){
296 traversalHttpEntry.setHttpEntryProperties(version, notification, notificationDepth);
298 traversalHttpEntry.setHttpEntryProperties(version);
300 Loader loader = traversalHttpEntry.getLoader();
301 dbEngine = traversalHttpEntry.getDbEngine();
303 URI uriObject = UriBuilder.fromPath(uri).build();
304 URIToObject uriToObject = new URIToObject(loader, uriObject);
306 String objType = uriToObject.getEntityName();
307 QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject);
309 logger.info("Unmarshalling the payload to this {}", objType);
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);
317 DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo,
318 "JUNIT-TRANSACTION").rawRequestContent(payload).build();
320 List<DBRequest> dbRequestList = new ArrayList<>();
321 dbRequestList.add(dbRequest);
323 Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
324 traversalHttpEntry.process(dbRequestList, "JUNIT");
325 response = responsesTuple.getValue1().get(0).getValue1();
327 } catch (AAIException e) {
328 response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
330 } catch (Exception e) {
331 AAIException ex = new AAIException("AAI_4000", e);
332 response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
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());
341 logFailure(HttpMethod.PUT, response);
346 if (response != null) {
347 logFailure(HttpMethod.PUT, response);
356 public Response doGet(String uri, String depth){
357 return doGet(uri, depth, null);
360 public Response doGet(String uri, String depth, String format) {
363 Response response = null;
364 boolean success = true;
365 TransactionalGraphEngine dbEngine = null;
369 if (uri.startsWith("/aai/")) {
370 uri = uri.substring(5);
373 logger.info("Starting the GET request for the uri {} with depth {}", uri, depth);
375 String[] arr = uri.split("/");
377 SchemaVersion version = null;
379 if (arr.length > 1) {
380 if (arr[0].matches("^v\\d+")) {
381 version = new SchemaVersion(arr[0]);
382 uri = uri.replaceAll("^v\\d+", "");
386 if (version == null) {
387 version = schemaVersions.getDefaultVersion();
390 if(notification != null){
391 traversalHttpEntry.setHttpEntryProperties(version, notification, notificationDepth);
393 traversalHttpEntry.setHttpEntryProperties(version);
395 Loader loader = traversalHttpEntry.getLoader();
396 dbEngine = traversalHttpEntry.getDbEngine();
398 URI uriObject = UriBuilder.fromPath(uri).build();
401 queryParameters.add("depth", depth);
405 queryParameters.add("format", format);
408 QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject, queryParameters);
410 Mockito.when(uriInfo.getPath()).thenReturn(uri);
412 URIToObject uriToObject = new URIToObject(loader, uriObject);
414 if (!uriQuery.getContainerType().equals("")) {
415 objType = uriQuery.getContainerType();
417 objType = uriQuery.getResultType();
419 logger.info("Unmarshalling the payload to this {}", objType);
421 Introspector obj = loader.introspectorFromName(objType);
423 DBRequest dbRequest = new DBRequest.Builder(HttpMethod.GET, uriObject, uriQuery, obj, httpHeaders, uriInfo,
424 "JUNIT-TRANSACTION").build();
426 List<DBRequest> dbRequestList = new ArrayList<>();
427 dbRequestList.add(dbRequest);
429 Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
430 traversalHttpEntry.process(dbRequestList, "JUNIT");
431 response = responsesTuple.getValue1().get(0).getValue1();
433 } catch (AAIException e) {
434 response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
436 } catch (Exception e) {
437 AAIException ex = new AAIException("AAI_4000", e);
438 response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
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());
447 logFailure(HttpMethod.GET, response);
452 logFailure(HttpMethod.GET, response);
460 public Response doGet(String uri) throws UnsupportedEncodingException, AAIException {
461 return this.doGet(uri, "all");
464 public Response doDelete(Map<String, Pair<String, String>> deletes){
467 Response response = null;
468 boolean success = true;
469 TransactionalGraphEngine dbEngine = null;
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);
481 String[] arr = uri.split("/");
483 SchemaVersion version = null;
485 if (arr.length > 1) {
486 if (arr[0].matches("^v\\d+")) {
487 version = new SchemaVersion(arr[0]);
488 uri = uri.replaceAll("^v\\d+", "");
492 if (version == null) {
493 version = schemaVersions.getDefaultVersion();
496 Mockito.when(uriInfo.getPath()).thenReturn(uri);
497 if (notification != null) {
498 traversalHttpEntry.setHttpEntryProperties(version, notification, notificationDepth);
500 traversalHttpEntry.setHttpEntryProperties(version);
502 Loader loader = traversalHttpEntry.getLoader();
503 dbEngine = traversalHttpEntry.getDbEngine();
505 URI uriObject = UriBuilder.fromPath(uri).build();
506 URIToObject uriToObject = new URIToObject(loader, uriObject);
508 String objType = uriToObject.getEntityName();
509 queryParameters.add("resource-version", resourceVersion);
510 QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject, queryParameters);
512 logger.info("Unmarshalling the payload to this {}", objType);
516 HttpMethod httpMethod;
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"));
522 obj = loader.introspectorFromName(objType);
523 httpMethod = HttpMethod.DELETE;
526 DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo, "JUNIT-TRANSACTION").build();
529 dbRequestList.add(dbRequest);
531 Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
532 traversalHttpEntry.process(dbRequestList, "JUNIT");
533 response = responsesTuple.getValue1().get(0).getValue1();
535 } catch (AAIException e) {
536 response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.DELETE, e);
538 } catch (Exception e) {
539 AAIException ex = new AAIException("AAI_4000", e);
540 response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.DELETE, ex);
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());
549 logFailure(HttpMethod.DELETE, response);
554 logFailure(HttpMethod.DELETE, response);
562 public Response doDelete(String uri, String resourceVersion) {
563 return this.doDelete(uri, resourceVersion, null);
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);
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());