2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
20 package org.onap.aai.rest;
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;
38 import javax.servlet.http.HttpServletRequest;
39 import javax.ws.rs.core.*;
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;
50 public class GfpVserverDataStoredQueryTest {
52 private static final EELFLogger logger = EELFManager.getInstance().getLogger(GfpVserverDataStoredQueryTest.class);
54 protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
56 private HttpHeaders httpHeaders;
58 private MultivaluedMap<String, String> headersMultiMap;
59 private MultivaluedMap<String, String> queryParameters;
61 private List<String> aaiRequestContextList;
63 private List<MediaType> outputMediaTypes;
65 private HttpTestUtil httpTestUtil;
67 private QueryConsumer queryConsumer;
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";
75 public void setup() throws Exception {
76 httpTestUtil = new HttpTestUtil();
78 Map<String, String> templateValues = new HashMap<>();
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");
91 String cloudRegionPayload = PayloadUtil.
92 getTemplatePayload("cloud-region-with-linterface.json", templateValues);
94 Response response = httpTestUtil.doPut(CLOUD_REGION_URI, cloudRegionPayload);
95 logger.info("Response status received {}", response.getEntity());
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");
101 queryConsumer = new QueryConsumer();
103 httpHeaders = mock(HttpHeaders.class);
105 headersMultiMap = new MultivaluedHashMap<>();
106 queryParameters = Mockito.spy(new MultivaluedHashMap<>());
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", "");
114 outputMediaTypes = new ArrayList<>();
115 outputMediaTypes.add(APPLICATION_JSON);
117 aaiRequestContextList = new ArrayList<>();
118 aaiRequestContextList.add("");
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);
126 Mockito.doReturn(null).when(queryParameters).remove(anyObject());
128 when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON);
131 @Ignore("This is more of a performance test to ensure no failure when too many starting vertexes")
133 public void testStoredQueryVerifyDoesNotThrowMethodTooLargeWhenLargeNumberOfStartingVertexes() throws Exception {
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);
140 Map<String, String> templateValues = new HashMap<>();
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");
150 String payload = PayloadUtil.getTemplatePayload("custom-query.json", templateValues);
151 String query = String.format("/aai/%s/query?format=resource_and_url", VERSION.toString());
153 UriInfo uriInfo = Mockito.mock(UriInfo.class);
154 HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);
156 queryParameters.add("format", "resource_and_url");
157 Mockito.when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
158 when(uriInfo.getPath()).thenReturn(query);
160 Response response = queryConsumer.executeQuery(
164 "resource_and_url", "" +
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());
180 public void testStoredQueryWhenQueryDoesNotExistShouldReturnBadRequest() throws Exception {
182 Map<String, String> templateValues = new HashMap<>();
184 templateValues.put("start", "nodes/vservers");
185 templateValues.put("query", "fake-query");
187 String payload = PayloadUtil.getTemplatePayload("custom-query.json", templateValues);
188 String query = String.format("/aai/%s/query?format=resource_and_url", VERSION.toString());
190 UriInfo uriInfo = Mockito.mock(UriInfo.class);
191 HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);
193 queryParameters.add("format", "resource_and_url");
194 Mockito.when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
195 when(uriInfo.getPath()).thenReturn(query);
197 Response response = queryConsumer.executeQuery(
201 "resource_and_url", "" +
208 String entity = response.getEntity().toString();
210 assertEquals("Expected the response to be 400 but got this returned: " + entity,
211 400, response.getStatus());
213 assertThat("Expecting error message since query doesn't exist", entity,
214 containsString("Query payload is invalid"));
218 public void testStoredQueryWhenStartFilterReturnsZeroVertexesItShouldHandleProperly() throws Exception {
220 Map<String, String> templateValues = new HashMap<>();
222 templateValues.put("start", "nodes/vservers?vserver-name=nonexistent-filter");
223 templateValues.put("query", "gfp-vserver-data");
225 String payload = PayloadUtil.getTemplatePayload("custom-query.json", templateValues);
226 String query = String.format("/aai/%s/query?format=resource_and_url", VERSION.toString());
228 UriInfo uriInfo = Mockito.mock(UriInfo.class);
229 HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);
231 queryParameters.add("format", "resource_and_url");
232 Mockito.when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
233 when(uriInfo.getPath()).thenReturn(query);
235 Response response = queryConsumer.executeQuery(
239 "resource_and_url", "" +
246 String entity = response.getEntity().toString();
248 assertEquals("Expected the response to be 500 but got this returned: " + entity,
249 500, response.getStatus());
251 assertThat(entity, containsString("Internal Error:groovy.lang.MissingPropertyException"));
255 public void tearDown(){
259 private void removeVertexes(){
261 TitanGraph titanGraph = AAIGraph.getInstance().getGraph();
262 TitanTransaction transaction = titanGraph.newTransaction();
264 boolean success = true;
267 GraphTraversalSource g = transaction.traversal();
268 g.V().has("source-of-truth", "JUNIT").toList().stream()
269 .forEach((vertex) -> vertex.remove());
270 } catch(Exception ex){
272 logger.error("Unable to remove all of the junit vservers due to {}", ex);
275 transaction.commit();
277 transaction.rollback();
283 private void addVservers(int vserversCount){
285 TitanGraph titanGraph = AAIGraph.getInstance().getGraph();
286 TitanTransaction transaction = titanGraph.newTransaction();
288 boolean success = true;
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")
302 } catch(Exception ex){
304 logger.error("Unable to add all of the vservers due to {}", ex);
307 transaction.commit();
309 transaction.rollback();