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