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