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