Update the license for 2017-2018 license
[aai/traversal.git] / aai-traversal / src / test / java / org / onap / aai / rest / GfpVserverDataStoredQueryTest.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.rest;
21
22 import com.att.eelf.configuration.EELFLogger;
23 import com.att.eelf.configuration.EELFManager;
24 import com.jayway.jsonpath.JsonPath;
25 import com.thinkaurelius.titan.core.TitanGraph;
26 import com.thinkaurelius.titan.core.TitanTransaction;
27 import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
28 import org.junit.After;
29 import org.junit.Before;
30 import org.junit.Ignore;
31 import org.junit.Test;
32 import org.mockito.Mockito;
33 import org.onap.aai.HttpTestUtil;
34 import org.onap.aai.PayloadUtil;
35 import org.onap.aai.dbmap.AAIGraph;
36 import org.onap.aai.introspection.Version;
37
38 import javax.servlet.http.HttpServletRequest;
39 import javax.ws.rs.core.*;
40 import java.util.*;
41
42 import static org.hamcrest.CoreMatchers.containsString;
43 import static org.hamcrest.MatcherAssert.assertThat;
44 import static org.junit.Assert.assertEquals;
45 import static org.junit.Assert.assertNotNull;
46 import static org.mockito.Matchers.anyObject;
47 import static org.mockito.Mockito.mock;
48 import static org.mockito.Mockito.when;
49
50 public class GfpVserverDataStoredQueryTest {
51
52     private static final EELFLogger logger = EELFManager.getInstance().getLogger(GfpVserverDataStoredQueryTest.class);
53
54     protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
55
56     private HttpHeaders httpHeaders;
57
58     private MultivaluedMap<String, String> headersMultiMap;
59     private MultivaluedMap<String, String> queryParameters;
60
61     private List<String> aaiRequestContextList;
62
63     private List<MediaType> outputMediaTypes;
64
65     private HttpTestUtil httpTestUtil;
66
67     private QueryConsumer queryConsumer;
68
69     private static final Version VERSION = Version.v11;
70     private static final String CLOUD_REGION_URI = "/aai/" + VERSION.toString()
71                                                  + "/cloud-infrastructure/cloud-regions/"
72                                                  + "cloud-region/testOwner1/testRegion1";
73
74     @Before
75     public void setup() throws Exception {
76         httpTestUtil = new HttpTestUtil();
77
78         Map<String, String> templateValues = new HashMap<>();
79
80         templateValues.put("cloud-owner", "testOwner1");
81         templateValues.put("cloud-region-id", "testRegion1");
82         templateValues.put("tenant-id", "testTenant1");
83         templateValues.put("tenant-name", "testTenantName1");
84         templateValues.put("vserver-id", "testVserver1");
85         templateValues.put("vserver-name", "junit-vservers");
86         templateValues.put("interface-name", "testlInterfaceName1");
87         templateValues.put("ipv4-address", "192.33.233.233");
88         templateValues.put("ipv6-address", "2001:0db8:85a3:0000:0000:8a2e:0370:7334");
89         templateValues.put("vlan-interface", "vlan-interface1");
90
91         String cloudRegionPayload = PayloadUtil.
92                 getTemplatePayload("cloud-region-with-linterface.json", templateValues);
93
94         Response response = httpTestUtil.doPut(CLOUD_REGION_URI, cloudRegionPayload);
95         logger.info("Response status received {}", response.getEntity());
96
97         assertNotNull("Expected the response to be not null", response);
98         assertEquals("Expecting the cloud region to be created", 201, response.getStatus());
99         logger.info("Successfully created the cloud region with linterface");
100
101         queryConsumer = new QueryConsumer();
102
103         httpHeaders         = mock(HttpHeaders.class);
104
105         headersMultiMap     = new MultivaluedHashMap<>();
106         queryParameters     = Mockito.spy(new MultivaluedHashMap<>());
107
108         headersMultiMap.add("X-FromAppId", "JUNIT");
109         headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString());
110         headersMultiMap.add("Real-Time", "true");
111         headersMultiMap.add("Accept", "application/json");
112         headersMultiMap.add("aai-request-context", "");
113
114         outputMediaTypes = new ArrayList<>();
115         outputMediaTypes.add(APPLICATION_JSON);
116
117         aaiRequestContextList = new ArrayList<>();
118         aaiRequestContextList.add("");
119
120         when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
121         when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap);
122         when(httpHeaders.getRequestHeader("X-FromAppId")).thenReturn(Arrays.asList("JUNIT"));
123         when(httpHeaders.getRequestHeader("X-TransactionId")).thenReturn(Arrays.asList("JUNIT"));
124         when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList);
125
126         Mockito.doReturn(null).when(queryParameters).remove(anyObject());
127
128         when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON);
129     }
130
131     @Ignore("This is more of a performance test to ensure no failure when too many starting vertexes")
132     @Test
133     public void testStoredQueryVerifyDoesNotThrowMethodTooLargeWhenLargeNumberOfStartingVertexes() throws Exception {
134
135         // Add hundred thousand vserver vertexes to properly
136         // test the scenario where the application was
137         // failing with method too large
138         addVservers(1000000);
139
140         Map<String, String> templateValues = new HashMap<>();
141
142         // Purposefully putting the filter to the testVserver1 as
143         // since this is a junit test other junit tests could put
144         // vserver and not properly clean up after the test
145         // so doing this to ensure that this is testing against the particular vserver
146         // as not to fail when another unit test decide to put vserver and not clean up
147         templateValues.put("start", "nodes/vservers?vserver-name=junit-vservers");
148         templateValues.put("query", "gfp-vserver-data");
149
150         String payload = PayloadUtil.getTemplatePayload("custom-query.json", templateValues);
151         String query = String.format("/aai/%s/query?format=resource_and_url", VERSION.toString());
152
153         UriInfo uriInfo = Mockito.mock(UriInfo.class);
154         HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);
155
156         queryParameters.add("format", "resource_and_url");
157         Mockito.when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
158         when(uriInfo.getPath()).thenReturn(query);
159
160         Response response = queryConsumer.executeQuery(
161             payload,
162             VERSION.toString(),
163             query,
164             "resource_and_url", "" +
165             "no_op",
166             httpHeaders,
167             uriInfo,
168             httpServletRequest
169         );
170
171         String entity = response.getEntity().toString();
172         assertEquals("Expected the response to be 200 but got this returned: " + response.getEntity().toString(),
173                 200, response.getStatus());
174         List<String> urls = JsonPath.read(entity, "$.results[*].url");
175         assertEquals("Expected the urls to be 3", 3, urls.size());
176         removeVertexes();
177     }
178
179     @Test
180     public void testStoredQueryWhenQueryDoesNotExistShouldReturnBadRequest() throws Exception {
181
182         Map<String, String> templateValues = new HashMap<>();
183
184         templateValues.put("start", "nodes/vservers");
185         templateValues.put("query", "fake-query");
186
187         String payload = PayloadUtil.getTemplatePayload("custom-query.json", templateValues);
188         String query = String.format("/aai/%s/query?format=resource_and_url", VERSION.toString());
189
190         UriInfo uriInfo = Mockito.mock(UriInfo.class);
191         HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);
192
193         queryParameters.add("format", "resource_and_url");
194         Mockito.when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
195         when(uriInfo.getPath()).thenReturn(query);
196
197         Response response = queryConsumer.executeQuery(
198                 payload,
199                 VERSION.toString(),
200                 query,
201                 "resource_and_url", "" +
202                         "no_op",
203                 httpHeaders,
204                 uriInfo,
205                 httpServletRequest
206         );
207
208         String entity = response.getEntity().toString();
209
210         assertEquals("Expected the response to be 400 but got this returned: " + entity,
211                 400, response.getStatus());
212
213         assertThat("Expecting error message since query doesn't exist", entity,
214                 containsString("Query payload is invalid"));
215     }
216
217     @Test
218     public void testStoredQueryWhenStartFilterReturnsZeroVertexesItShouldHandleProperly() throws Exception {
219
220         Map<String, String> templateValues = new HashMap<>();
221
222         templateValues.put("start", "nodes/vservers?vserver-name=nonexistent-filter");
223         templateValues.put("query", "gfp-vserver-data");
224
225         String payload = PayloadUtil.getTemplatePayload("custom-query.json", templateValues);
226         String query = String.format("/aai/%s/query?format=resource_and_url", VERSION.toString());
227
228         UriInfo uriInfo = Mockito.mock(UriInfo.class);
229         HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);
230
231         queryParameters.add("format", "resource_and_url");
232         Mockito.when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
233         when(uriInfo.getPath()).thenReturn(query);
234
235         Response response = queryConsumer.executeQuery(
236                 payload,
237                 VERSION.toString(),
238                 query,
239                 "resource_and_url", "" +
240                         "no_op",
241                 httpHeaders,
242                 uriInfo,
243                 httpServletRequest
244         );
245
246         String entity = response.getEntity().toString();
247
248         assertEquals("Expected the response to be 500 but got this returned: " + entity,
249                 500, response.getStatus());
250
251         assertThat(entity, containsString("Internal Error:groovy.lang.MissingPropertyException"));
252     }
253
254     @After
255     public void tearDown(){
256         removeVertexes();
257     }
258
259     private void removeVertexes(){
260
261         TitanGraph titanGraph = AAIGraph.getInstance().getGraph();
262         TitanTransaction transaction = titanGraph.newTransaction();
263
264         boolean success = true;
265
266         try {
267             GraphTraversalSource g = transaction.traversal();
268             g.V().has("source-of-truth", "JUNIT").toList().stream()
269                     .forEach((vertex) -> vertex.remove());
270         } catch(Exception ex){
271             success = false;
272             logger.error("Unable to remove all of the junit vservers due to {}", ex);
273         } finally {
274             if(success){
275                 transaction.commit();
276             } else {
277                 transaction.rollback();
278             }
279         }
280
281     }
282
283     private void addVservers(int vserversCount){
284
285         TitanGraph titanGraph = AAIGraph.getInstance().getGraph();
286         TitanTransaction transaction = titanGraph.newTransaction();
287
288         boolean success = true;
289
290         try {
291
292             GraphTraversalSource g = transaction.traversal();
293             for(int index = 0; index < vserversCount; index++){
294                 String randomVserverId = UUID.randomUUID().toString();
295                 g.addV().property("aai-node-type", "vserver")
296                         .property( "vserver-id", "random-" + randomVserverId)
297                         .property( "vserver-name", "junit-vservers")
298                         .property( "source-of-truth", "JUNIT")
299                         .next();
300             }
301
302         } catch(Exception ex){
303             success = false;
304             logger.error("Unable to add all of the vservers due to {}", ex);
305         } finally {
306             if(success){
307                 transaction.commit();
308             } else {
309                 transaction.rollback();
310             }
311         }
312     }
313 }