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