6a9e725636babce3d60cab3e533b23db1e1e2722
[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.doReturn;
25 import static org.mockito.Mockito.when;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29
30 import java.io.UnsupportedEncodingException;
31 import java.net.URI;
32 import java.util.ArrayList;
33 import java.util.List;
34 import java.util.UUID;
35
36 import javax.ws.rs.core.*;
37
38 import org.javatuples.Pair;
39 import org.mockito.Mockito;
40 import org.onap.aai.config.SpringContextAware;
41 import org.onap.aai.dbmap.DBConnectionType;
42 import org.onap.aai.exceptions.AAIException;
43 import org.onap.aai.introspection.Introspector;
44 import org.onap.aai.introspection.Loader;
45 import org.onap.aai.parsers.query.QueryParser;
46 import org.onap.aai.parsers.uri.URIToObject;
47 import org.onap.aai.rest.db.DBRequest;
48 import org.onap.aai.rest.db.HttpEntry;
49 import org.onap.aai.restcore.HttpMethod;
50 import org.onap.aai.restcore.RESTAPI;
51 import org.onap.aai.serialization.engines.QueryStyle;
52 import org.onap.aai.serialization.engines.TransactionalGraphEngine;
53 import org.onap.aai.setup.SchemaVersion;
54 import org.onap.aai.setup.SchemaVersions;
55
56 public class HttpTestUtil extends RESTAPI {
57
58     protected HttpEntry traversalHttpEntry;
59
60     protected HttpEntry traversalUriHttpEntry;
61
62     private static final EELFLogger logger = EELFManager.getInstance().getLogger(HttpTestUtil.class);
63
64     protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
65
66     private static final String EMPTY = "";
67     private final QueryStyle queryStyle;
68
69     protected HttpHeaders httpHeaders;
70     protected UriInfo uriInfo;
71
72     protected MultivaluedMap<String, String> headersMultiMap;
73     protected MultivaluedMap<String, String> queryParameters;
74
75     protected List<String> aaiRequestContextList;
76     protected List<MediaType> outputMediaTypes;
77
78     public HttpTestUtil(QueryStyle qs) {
79         this.queryStyle = qs;
80         traversalHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class);
81         traversalUriHttpEntry = SpringContextAware.getBean("traversalUriHttpEntry", HttpEntry.class);
82
83     }
84
85     public void init() {
86
87         httpHeaders = Mockito.mock(HttpHeaders.class);
88         uriInfo = Mockito.mock(UriInfo.class);
89
90         headersMultiMap = new MultivaluedHashMap<>();
91         queryParameters = Mockito.spy(new MultivaluedHashMap<>());
92
93         headersMultiMap.add("X-FromAppId", "JUNIT");
94         headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString());
95         headersMultiMap.add("Real-Time", "true");
96         headersMultiMap.add("Accept", "application/json");
97         headersMultiMap.add("aai-request-context", "");
98
99         outputMediaTypes = new ArrayList<>();
100         outputMediaTypes.add(APPLICATION_JSON);
101
102         aaiRequestContextList = new ArrayList<>();
103         aaiRequestContextList.add("");
104
105         when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap);
106         when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
107
108         when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList);
109
110         when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
111         when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters);
112
113         doReturn(null).when(queryParameters).remove(anyObject());
114         when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON);
115     }
116
117     public Response doPut(String uri, String payload) throws UnsupportedEncodingException, AAIException {
118
119         this.init();
120         Response response = null;
121         boolean success = true;
122         TransactionalGraphEngine dbEngine = null;
123
124         try {
125
126             if (uri.startsWith("/aai/")) {
127                 uri = uri.substring(5);
128             }
129
130             logger.info("Starting the put request for the uri {} with payload {}", uri, payload);
131
132             String[] arr = uri.split("/");
133
134             SchemaVersion version = null;
135
136             if (arr != null && arr.length > 1) {
137                 if (arr[0].matches("^v\\d+")) {
138                     version = new SchemaVersion(arr[0]);
139                     uri = uri.replaceAll("^v\\d+", "");
140                 }
141             }
142
143             SchemaVersions schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
144             if (version == null) {
145                 version = schemaVersions.getDefaultVersion();
146             }
147             Mockito.when(uriInfo.getPath()).thenReturn(uri);
148
149             DBConnectionType type = DBConnectionType.REALTIME;
150
151             traversalHttpEntry.setHttpEntryProperties(version, type);
152             Loader loader = traversalHttpEntry.getLoader();
153             dbEngine = traversalHttpEntry.getDbEngine();
154
155             URI uriObject = UriBuilder.fromPath(uri).build();
156             URIToObject uriToObject = new URIToObject(loader, uriObject);
157
158             String objType = uriToObject.getEntityName();
159             QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject);
160
161             logger.info("Unmarshalling the payload to this {}", objType);
162
163             Introspector obj;
164             HttpMethod httpMethod;
165             if (uri.contains("/relationship-list/relationship")) {
166                 obj = loader.unmarshal("relationship", payload,
167                         org.onap.aai.restcore.MediaType.getEnum("application/json"));
168                 httpMethod = HttpMethod.PUT_EDGE;
169             } else {
170                 obj = loader.unmarshal(objType, payload, org.onap.aai.restcore.MediaType.getEnum("application/json"));
171                 httpMethod = HttpMethod.PUT;
172                 this.validateIntrospector(obj, loader, uriObject, httpMethod);
173             }
174
175             DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo,
176                     "JUNIT-TRANSACTION").rawRequestContent(payload).build();
177
178             List<DBRequest> dbRequestList = new ArrayList<>();
179             dbRequestList.add(dbRequest);
180
181             Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
182                     traversalHttpEntry.process(dbRequestList, "JUNIT");
183             response = responsesTuple.getValue1().get(0).getValue1();
184
185         } catch (AAIException e) {
186             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
187             success = false;
188         } catch (Exception e) {
189             AAIException ex = new AAIException("AAI_4000", e);
190             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
191             success = false;
192         } finally {
193             if (success) {
194                 if (response != null) {
195                     if ((response.getStatus() / 100) == 2) {
196                         logger.info("Successfully completed the PUT request with status {} and committing it to DB",
197                                 response.getStatus());
198                     } else {
199                         logFailure(HttpMethod.PUT, response);
200                     }
201                 }
202                 dbEngine.commit();
203             } else {
204                 if (response != null) {
205                     logFailure(HttpMethod.PUT, response);
206                 }
207                 dbEngine.rollback();
208             }
209         }
210
211         return response;
212     }
213
214     public Response doGet(String uri, String depth) {
215
216         this.init();
217         Response response = null;
218         boolean success = true;
219         TransactionalGraphEngine dbEngine = null;
220
221         try {
222
223             if (uri.startsWith("/aai/")) {
224                 uri = uri.substring(5);
225             }
226
227             logger.info("Starting the GET request for the uri {} with depth {}", uri, depth);
228
229             String[] arr = uri.split("/");
230
231             SchemaVersion version = null;
232
233             if (arr != null && arr.length > 1) {
234                 if (arr[0].matches("^v\\d+")) {
235                     version = new SchemaVersion(arr[0]);
236                     uri = uri.replaceAll("^v\\d+", "");
237                 }
238             }
239
240             SchemaVersions schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
241             if (version == null) {
242                 version = schemaVersions.getDefaultVersion();
243             }
244
245             DBConnectionType type = DBConnectionType.REALTIME;
246             traversalHttpEntry.setHttpEntryProperties(version, type);
247             Loader loader = traversalHttpEntry.getLoader();
248             dbEngine = traversalHttpEntry.getDbEngine();
249
250             URI uriObject = UriBuilder.fromPath(uri).build();
251
252             if (depth != null) {
253                 queryParameters.add("depth", depth);
254             }
255
256             QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject, queryParameters);
257
258             Mockito.when(uriInfo.getPath()).thenReturn(uri);
259
260             URIToObject uriToObject = new URIToObject(loader, uriObject);
261             String objType = "";
262             if (!uriQuery.getContainerType().equals("")) {
263                 objType = uriQuery.getContainerType();
264             } else {
265                 objType = uriQuery.getResultType();
266             }
267             logger.info("Unmarshalling the payload to this {}", objType);
268
269             Introspector obj = loader.introspectorFromName(objType);
270
271             DBRequest dbRequest = new DBRequest.Builder(HttpMethod.GET, uriObject, uriQuery, obj, httpHeaders, uriInfo,
272                     "JUNIT-TRANSACTION").build();
273
274             List<DBRequest> dbRequestList = new ArrayList<>();
275             dbRequestList.add(dbRequest);
276
277             Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
278                     traversalHttpEntry.process(dbRequestList, "JUNIT");
279             response = responsesTuple.getValue1().get(0).getValue1();
280
281         } catch (AAIException e) {
282             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
283             success = false;
284         } catch (Exception e) {
285             AAIException ex = new AAIException("AAI_4000", e);
286             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
287             success = false;
288         } finally {
289             if (success) {
290                 if (response != null) {
291                     if ((response.getStatus() / 100) == 2) {
292                         logger.info("Successfully completed the GET request with status {} and committing it to DB",
293                                 response.getStatus());
294                     } else {
295                         logFailure(HttpMethod.GET, response);
296                     }
297                 }
298                 dbEngine.commit();
299             } else {
300                 logFailure(HttpMethod.GET, response);
301                 dbEngine.rollback();
302             }
303         }
304
305         return response;
306     }
307
308     public Response doGet(String uri) throws UnsupportedEncodingException, AAIException {
309         return this.doGet(uri, "all");
310     }
311
312     public Response doDelete(String uri, String resourceVersion) throws UnsupportedEncodingException, AAIException {
313
314         this.init();
315         Response response = null;
316         boolean success = true;
317         TransactionalGraphEngine dbEngine = null;
318
319         try {
320
321             uri = uri.replaceAll("/aai/", "");
322             logger.info("Starting the delete request for the uri {} with resource version {}", uri, resourceVersion);
323
324             String[] arr = uri.split("/");
325
326             SchemaVersion version = null;
327
328             if (arr != null && arr.length > 1) {
329                 if (arr[0].matches("^v\\d+")) {
330                     version = new SchemaVersion(arr[0]);
331                     if (!uri.contains("relationship-list/relationship")) {
332                         uri = uri.replaceAll("^v\\d+", "");
333                     }
334                 }
335             }
336
337             SchemaVersions schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
338             if (version == null) {
339                 version = schemaVersions.getDefaultVersion();
340             }
341
342             Mockito.when(uriInfo.getPath()).thenReturn(uri);
343             DBConnectionType type = DBConnectionType.REALTIME;
344             traversalHttpEntry.setHttpEntryProperties(version, type);
345
346             traversalHttpEntry.setHttpEntryProperties(version, type);
347             Loader loader = traversalHttpEntry.getLoader();
348             dbEngine = traversalHttpEntry.getDbEngine();
349
350             URI uriObject = UriBuilder.fromPath(uri).build();
351             URIToObject uriToObject = new URIToObject(loader, uriObject);
352
353             String objType = uriToObject.getEntityName();
354             queryParameters.add("resource-version", resourceVersion);
355             QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject, queryParameters);
356
357             logger.info("Unmarshalling the payload to this {}", objType);
358
359             Introspector obj;
360             HttpMethod httpMethod;
361             if (uri.contains("/relationship-list/relationship")) {
362                 obj = loader.introspectorFromName("relationship");
363                 httpMethod = HttpMethod.DELETE_EDGE;
364             } else {
365                 obj = loader.introspectorFromName(objType);
366                 httpMethod = HttpMethod.DELETE;
367             }
368
369             DBRequest dbRequest = new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo,
370                     "JUNIT-TRANSACTION").build();
371
372             List<DBRequest> dbRequestList = new ArrayList<>();
373             dbRequestList.add(dbRequest);
374
375             Pair<Boolean, List<Pair<URI, Response>>> responsesTuple =
376                     traversalHttpEntry.process(dbRequestList, "JUNIT");
377             response = responsesTuple.getValue1().get(0).getValue1();
378
379         } catch (AAIException e) {
380             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
381             success = false;
382         } catch (Exception e) {
383             AAIException ex = new AAIException("AAI_4000", e);
384             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
385             success = false;
386         } finally {
387             if (success) {
388                 if (response != null) {
389                     if ((response.getStatus() / 100) == 2) {
390                         logger.info("Successfully completed the DELETE request with status {} and committing it to DB",
391                                 response.getStatus());
392                     } else {
393                         logFailure(HttpMethod.DELETE, response);
394                     }
395                 }
396                 dbEngine.commit();
397             } else {
398                 logFailure(HttpMethod.DELETE, response);
399                 dbEngine.rollback();
400             }
401         }
402
403         return response;
404     }
405
406     public static void logFailure(HttpMethod httpMethod, Response response) {
407         logger.info("Unable to complete the {} request with status {} and rolling back", httpMethod.toString(),
408                 response.getStatus());
409         logger.info("Response body of failed request {}", response.getEntity());
410
411     }
412 }