Update schema service to fail to start
[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             if(uri.startsWith("/aai/")){
125                 uri = uri.substring(5);
126             }
127
128             logger.info("Starting the put request for the uri {} with payload {}", uri, payload);
129
130             String [] arr = uri.split("/");
131
132             SchemaVersion version = null;
133
134             if(arr != null && arr.length > 1){
135                 if(arr[0].matches("^v\\d+")){
136                     version = new SchemaVersion(arr[0]);
137                     uri = uri.replaceAll("^v\\d+", "");
138                 }
139             }
140
141             SchemaVersions schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
142             if(version == null){
143                 version = schemaVersions.getDefaultVersion();
144             }
145             Mockito.when(uriInfo.getPath()).thenReturn(uri);
146
147             DBConnectionType type = DBConnectionType.REALTIME;
148
149             traversalHttpEntry.setHttpEntryProperties(version, type);
150             Loader loader         = traversalHttpEntry.getLoader();
151             dbEngine              = traversalHttpEntry.getDbEngine();
152
153             URI uriObject = UriBuilder.fromPath(uri).build();
154             URIToObject uriToObject = new URIToObject(loader, uriObject);
155
156             String objType = uriToObject.getEntityName();
157             QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject);
158
159
160             logger.info("Unmarshalling the payload to this {}", objType);
161
162             Introspector obj;
163             HttpMethod httpMethod;
164             if(uri.contains("/relationship-list/relationship")){
165                 obj = loader.unmarshal("relationship", payload, org.onap.aai.restcore.MediaType.getEnum("application/json"));
166                 httpMethod = HttpMethod.PUT_EDGE;
167             } else {
168                 obj = loader.unmarshal(objType, payload, org.onap.aai.restcore.MediaType.getEnum("application/json"));
169                 httpMethod = HttpMethod.PUT;
170                 this.validateIntrospector(obj, loader, uriObject, httpMethod);
171             }
172
173
174             DBRequest dbRequest =
175                     new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo, "JUNIT-TRANSACTION")
176                             .rawRequestContent(payload).build();
177
178             List<DBRequest> dbRequestList = new ArrayList<>();
179             dbRequestList.add(dbRequest);
180
181             Pair<Boolean, List<Pair<URI, Response>>> responsesTuple  = traversalHttpEntry.process(dbRequestList, "JUNIT");
182             response = responsesTuple.getValue1().get(0).getValue1();
183
184         } catch (AAIException e) {
185             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
186             success = false;
187         } catch(Exception e){
188             AAIException ex = new AAIException("AAI_4000", e);
189             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
190             success = false;
191         } finally {
192             if(success){
193                 if(response != null){
194                     if((response.getStatus() / 100) == 2){
195                         logger.info("Successfully completed the PUT request with status {} and committing it to DB", response.getStatus());
196                     } else {
197                         logFailure(HttpMethod.PUT, response);
198                     }
199                 }
200                 dbEngine.commit();
201             } else {
202                 if(response != null) {
203                     logFailure(HttpMethod.PUT, response);
204                 }
205                 dbEngine.rollback();
206             }
207         }
208
209         return response;
210     }
211
212     public Response doGet(String uri, String depth){
213
214         this.init();
215         Response response = null;
216         boolean success = true;
217         TransactionalGraphEngine dbEngine = null;
218
219         try {
220
221             if(uri.startsWith("/aai/")){
222                 uri = uri.substring(5);
223             }
224
225             logger.info("Starting the GET request for the uri {} with depth {}", uri, depth);
226
227             String [] arr = uri.split("/");
228
229             SchemaVersion version = null;
230
231             if(arr != null && arr.length > 1){
232                 if(arr[0].matches("^v\\d+")){
233                     version = new SchemaVersion(arr[0]);
234                     uri = uri.replaceAll("^v\\d+", "");
235                 }
236             }
237
238             SchemaVersions schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
239             if(version == null){
240                 version = schemaVersions.getDefaultVersion();
241             }
242
243             DBConnectionType type = DBConnectionType.REALTIME;
244             traversalHttpEntry.setHttpEntryProperties(version, type);
245             Loader loader         = traversalHttpEntry.getLoader();
246             dbEngine              = traversalHttpEntry.getDbEngine();
247
248             URI uriObject = UriBuilder.fromPath(uri).build();
249
250             if(depth != null){
251                 queryParameters.add("depth", depth);
252             }
253
254             QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject, queryParameters);
255
256             Mockito.when(uriInfo.getPath()).thenReturn(uri);
257
258             URIToObject uriToObject = new URIToObject(loader, uriObject);
259             String objType = "";
260             if (!uriQuery.getContainerType().equals("")) {
261                 objType = uriQuery.getContainerType();
262             } else {
263                 objType = uriQuery.getResultType();
264             }
265             logger.info("Unmarshalling the payload to this {}", objType);
266
267             Introspector obj = loader.introspectorFromName(objType);
268
269             DBRequest dbRequest =
270                 new DBRequest.Builder(HttpMethod.GET, uriObject, uriQuery, obj, httpHeaders, uriInfo, "JUNIT-TRANSACTION")
271                     .build();
272
273             List<DBRequest> dbRequestList = new ArrayList<>();
274             dbRequestList.add(dbRequest);
275
276             Pair<Boolean, List<Pair<URI, Response>>> responsesTuple  = traversalHttpEntry.process(dbRequestList, "JUNIT");
277             response = responsesTuple.getValue1().get(0).getValue1();
278
279         } catch (AAIException e) {
280             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
281             success = false;
282         } catch(Exception e){
283             AAIException ex = new AAIException("AAI_4000", e);
284             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
285             success = false;
286         } finally {
287             if(success){
288                 if(response != null){
289                     if((response.getStatus() / 100) == 2){
290                         logger.info("Successfully completed the GET request with status {} and committing it to DB", response.getStatus());
291                     } else {
292                         logFailure(HttpMethod.GET, response);
293                     }
294                 }
295                 dbEngine.commit();
296             } else {
297                 logFailure(HttpMethod.GET, response);
298                 dbEngine.rollback();
299             }
300         }
301
302         return response;
303     }
304
305     public Response doGet(String uri) throws UnsupportedEncodingException, AAIException {
306         return this.doGet(uri, "all");
307     }
308
309     public Response doDelete(String uri, String resourceVersion) throws UnsupportedEncodingException, AAIException {
310
311         this.init();
312         Response response = null;
313         boolean success = true;
314         TransactionalGraphEngine dbEngine = null;
315
316         try {
317
318             uri = uri.replaceAll("/aai/", "");
319             logger.info("Starting the delete request for the uri {} with resource version {}", uri, resourceVersion);
320
321             String [] arr = uri.split("/");
322
323             SchemaVersion version = null;
324
325             if(arr != null && arr.length > 1){
326                 if(arr[0].matches("^v\\d+")){
327                     version = new SchemaVersion(arr[0]);
328                     if(!uri.contains("relationship-list/relationship")){
329                         uri = uri.replaceAll("^v\\d+", "");
330                     }
331                 }
332             }
333
334             SchemaVersions schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
335             if(version == null){
336                 version = schemaVersions.getDefaultVersion();
337             }
338
339             Mockito.when(uriInfo.getPath()).thenReturn(uri);
340             DBConnectionType type = DBConnectionType.REALTIME;
341             traversalHttpEntry.setHttpEntryProperties(version, type);
342
343             traversalHttpEntry.setHttpEntryProperties(version, type);
344             Loader loader         = traversalHttpEntry.getLoader();
345             dbEngine              = traversalHttpEntry.getDbEngine();
346
347             URI uriObject = UriBuilder.fromPath(uri).build();
348             URIToObject uriToObject = new URIToObject(loader, uriObject);
349
350             String objType = uriToObject.getEntityName();
351             queryParameters.add("resource-version", resourceVersion);
352             QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject, queryParameters);
353
354             logger.info("Unmarshalling the payload to this {}", objType);
355
356             Introspector obj;
357             HttpMethod httpMethod;
358             if(uri.contains("/relationship-list/relationship")){
359                 obj = loader.introspectorFromName("relationship");
360                 httpMethod = HttpMethod.DELETE_EDGE;
361             } else {
362                 obj = loader.introspectorFromName(objType);
363                 httpMethod = HttpMethod.DELETE;
364             }
365
366             DBRequest dbRequest =
367                     new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo, "JUNIT-TRANSACTION")
368                             .build();
369
370             List<DBRequest> dbRequestList = new ArrayList<>();
371             dbRequestList.add(dbRequest);
372
373             Pair<Boolean, List<Pair<URI, Response>>> responsesTuple  = traversalHttpEntry.process(dbRequestList, "JUNIT");
374             response = responsesTuple.getValue1().get(0).getValue1();
375
376         } catch (AAIException e) {
377             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
378             success = false;
379         } catch(Exception e){
380             AAIException ex = new AAIException("AAI_4000", e);
381             response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
382             success = false;
383         } finally {
384             if(success){
385                 if(response != null){
386                     if((response.getStatus() / 100) == 2){
387                         logger.info("Successfully completed the DELETE request with status {} and committing it to DB", response.getStatus());
388                     } else {
389                         logFailure(HttpMethod.DELETE, response);
390                     }
391                 }
392                 dbEngine.commit();
393             } else {
394                 logFailure(HttpMethod.DELETE, response);
395                 dbEngine.rollback();
396             }
397         }
398
399         return response;
400     }
401
402     public static void logFailure(HttpMethod httpMethod, Response response){
403         logger.info("Unable to complete the {} request with status {} and rolling back", httpMethod.toString(), response.getStatus());
404         logger.info("Response body of failed request {}", response.getEntity());
405
406     }
407 }