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