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