6d682f403e17328a7b15d6abeef490b154e687b7
[aai/sparky-be.git] / src / test / java / org / onap / aai / sparky / viewandinspect / SearchServletTest.java
1 /* 
2 * ============LICENSE_START=======================================================
3 * SPARKY (inventory UI service)
4 * ================================================================================
5 * Copyright © 2017 AT&T Intellectual Property.
6 * Copyright © 2017 Amdocs
7 * All rights reserved.
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
12
13 *      http://www.apache.org/licenses/LICENSE-2.0
14
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
20 * ============LICENSE_END=========================================================
21
22 * ECOMP and OpenECOMP are trademarks
23 * and service marks of AT&T Intellectual Property.
24 */
25
26 package org.onap.aai.sparky.viewandinspect;
27
28 import static org.junit.Assert.assertEquals;
29 import static org.junit.Assert.assertNotNull;
30 import static org.junit.Assert.assertNull;
31 import static org.junit.Assert.assertTrue;
32 import static org.junit.Assert.fail;
33 import static org.mockito.Matchers.anyString;
34
35 import java.io.IOException;
36 import java.io.PrintWriter;
37 import java.io.StringWriter;
38 import java.security.SecureRandom;
39 import java.util.ArrayList;
40 import java.util.Arrays;
41 import java.util.HashMap;
42 import java.util.List;
43 import java.util.Map;
44
45 import javax.servlet.ServletException;
46 import javax.servlet.http.HttpServletRequest;
47 import javax.servlet.http.HttpServletResponse;
48
49 import org.junit.Before;
50 import org.junit.Test;
51 import org.mockito.ArgumentCaptor;
52 import org.mockito.Mockito;
53 import org.onap.aai.sparky.config.oxm.OxmEntityDescriptor;
54 import org.onap.aai.sparky.config.oxm.OxmModelLoader;
55 import org.onap.aai.sparky.dal.elasticsearch.SearchAdapter;
56 import org.onap.aai.sparky.dal.elasticsearch.entity.AutoSuggestDocumentEntity;
57 import org.onap.aai.sparky.dal.elasticsearch.entity.AutoSuggestDocumentEntityFields;
58 import org.onap.aai.sparky.dal.elasticsearch.entity.AutoSuggestElasticHitEntity;
59 import org.onap.aai.sparky.dal.elasticsearch.entity.AutoSuggestElasticHitsEntity;
60 import org.onap.aai.sparky.dal.elasticsearch.entity.AutoSuggestElasticSearchResponse;
61 import org.onap.aai.sparky.dal.elasticsearch.entity.BucketEntity;
62 import org.onap.aai.sparky.dal.elasticsearch.entity.ElasticHitsEntity;
63 import org.onap.aai.sparky.dal.elasticsearch.entity.ElasticSearchAggegrationResponse;
64 import org.onap.aai.sparky.dal.elasticsearch.entity.ElasticSearchAggregation;
65 import org.onap.aai.sparky.dal.elasticsearch.entity.ElasticSearchCountResponse;
66 import org.onap.aai.sparky.dal.elasticsearch.entity.PayloadEntity;
67 import org.onap.aai.sparky.dal.rest.OperationResult;
68 import org.onap.aai.sparky.dal.sas.config.SearchServiceConfig;
69 import org.onap.aai.sparky.dal.sas.entity.EntityCountResponse;
70 import org.onap.aai.sparky.dal.sas.entity.GroupByAggregationResponseEntity;
71 import org.onap.aai.sparky.dal.sas.entity.SearchAbstractionEntityBuilder;
72 import org.onap.aai.sparky.search.VnfSearchService;
73 import org.onap.aai.sparky.search.config.SuggestionConfig;
74 import org.onap.aai.sparky.suggestivesearch.SuggestionEntity;
75 import org.onap.aai.sparky.util.ExceptionHelper;
76 import org.onap.aai.sparky.util.HttpServletHelper;
77 import org.onap.aai.sparky.util.NodeUtils;
78 import org.onap.aai.sparky.viewandinspect.entity.QuerySearchEntity;
79 import org.onap.aai.sparky.viewandinspect.entity.SearchResponse;
80 import org.onap.aai.sparky.viewandinspect.services.SearchServiceWrapper;
81 import org.onap.aai.sparky.viewandinspect.servlet.SearchServlet;
82 import org.slf4j.MDC;
83
84 import org.onap.aai.cl.mdc.MdcContext;
85 import com.fasterxml.jackson.core.JsonProcessingException;
86 import com.fasterxml.jackson.databind.ObjectMapper;
87 import com.fasterxml.jackson.databind.SerializationFeature;
88 import com.fasterxml.jackson.databind.node.ObjectNode;
89 import com.google.common.net.MediaType;
90
91
92 /**
93  * The Class SearchServletTest.
94  */
95
96 public class SearchServletTest {
97
98   private static final String VNF_ROUTE = "vnf";
99   private static final String VIEW_INSPECT_ROUTE = "viewInspect";
100
101   private HttpServletRequest commonRequest = null;
102   private HttpServletResponse commonResponse = null;
103   private PrintWriter printWriter = null;
104   private StringWriter responseStringWriter = null;
105   private SearchServiceWrapper searchWrapper = null;
106   private SearchAdapter searchAdapter = null;
107   private VnfSearchService vnfSearchService = null;
108   private ObjectMapper mapper = null;
109   private SecureRandom rand = null;
110   private OxmModelLoader loader;
111   private Map<String, OxmEntityDescriptor> descriptors = null;
112   private SuggestionConfig suggestionConfig = null;
113   private SearchServiceConfig esConfig = null;
114
115   /**
116    * Inits the.
117    *
118    * @throws Exception the exception
119    */
120   @Before
121   public void init() throws Exception {
122
123     commonRequest = HttpServletHelper.getMockHttpServletRequest();
124     responseStringWriter = new StringWriter();
125     printWriter = new PrintWriter(responseStringWriter);
126     commonResponse = HttpServletHelper.getMockHttpServletResponse(printWriter);
127     mapper = new ObjectMapper();
128
129     // permit serialization of objects with no members
130     mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
131
132     rand = new SecureRandom();
133
134     loader = Mockito.mock(OxmModelLoader.class);
135     descriptors = new HashMap<String, OxmEntityDescriptor>();
136
137     esConfig = new SearchServiceConfig();
138     suggestionConfig = SuggestionConfig.getConfig();
139
140     // Use SearchServiceWrapper and VnfSearchService for suggestionConfig
141     Map<String, String> svcs = new HashMap<String, String>();
142     svcs.put("autosuggestIndexname", "SearchServiceWrapper");
143     svcs.put("indexName", "VnfSearchService");
144     suggestionConfig.setSearchIndexToSearchService(svcs);
145
146     esConfig.setIndexName("esi-localhost");
147     esConfig.setType("default");
148
149     searchAdapter = Mockito.mock(SearchAdapter.class);
150     vnfSearchService = Mockito.mock(VnfSearchService.class);
151
152     initializeEntityDescriptors();
153
154     searchWrapper = new SearchServiceWrapper();
155     searchWrapper.setSasConfig(esConfig);
156     searchWrapper.setSearch(searchAdapter);
157     searchWrapper.setVnfSearch(vnfSearchService);
158     searchWrapper.setSuggestionConfig(suggestionConfig);
159     searchWrapper.setOxmModelLoader(loader);
160   }
161
162   @Test
163   public void validateAccessors() {
164     assertNotNull("Vnf Search Service should not be null", searchWrapper.getVnfSearch());
165   }
166
167   @Test
168   public void validateInitializer() {
169
170     try {
171       assertNotNull("Oxm Model loader should not be null", searchWrapper.getOxmModelLoader());
172       assertNotNull("SearchAbstractionConfig should not be null", searchWrapper.getSasConfig());
173       assertNotNull("SearchAdapter should not be null", searchWrapper.getSearch());
174       assertNotNull("Suggestion Config should not be null", searchWrapper.getSuggestionConfig());
175       assertNotNull("VnfSearchService should not be null", searchWrapper.getVnfSearch());
176
177       searchWrapper.setOxmModelLoader(null);
178       searchWrapper.setSasConfig(null);
179       searchWrapper.setSearch(null);
180       searchWrapper.setSuggestionConfig(null);
181       searchWrapper.setVnfSearch(null);
182
183       assertNull("Oxm Model loader should be null", searchWrapper.getOxmModelLoader());
184       assertNull("SearchAbstractionConfig should be null", searchWrapper.getSasConfig());
185       assertNull("SearchAdapter should be null", searchWrapper.getSearch());
186       assertNull("Suggestion Config should be null", searchWrapper.getSuggestionConfig());
187       assertNull("VnfSearchService should be null", searchWrapper.getVnfSearch());
188
189     } catch (Exception exc) {
190       fail("Servlet Initialization Failed with error = " + exc.getMessage());
191     }
192
193   }
194
195   /**
196    * Test doGet() and doPost() for a non-existent end-point. A test objective would be to either
197    * return a 404 Not Found.
198    */
199   @Test
200   public void validateMdcContextLoggingVariablesWhenExplicitlySet() {
201
202     final String transactionId = "1234";
203     final String serviceName = "AAI_UI";
204     final String partnerName = "SparkyApp";
205
206     HttpServletHelper.assignRequestHeader(commonRequest, "X-TransactionId", transactionId);
207     HttpServletHelper.assignRequestHeader(commonRequest, "X-FromAppId", partnerName);
208
209     HttpServletHelper.assignRequestUri(commonRequest, "search/this/path/does/not/exist/");
210
211     try {
212
213       /*
214        * Testing the doGet() operation will hit the doPost() operation in the servlet as well
215        */
216
217       OperationResult result = doEvaluationTestMDC(true, commonRequest, commonResponse);
218
219       assertEquals(transactionId, MDC.get(MdcContext.MDC_REQUEST_ID));
220       assertEquals(serviceName, MDC.get(MdcContext.MDC_SERVICE_NAME));
221       assertEquals(partnerName, MDC.get(MdcContext.MDC_PARTNER_NAME));
222
223     } catch (Exception exc) {
224       exc.printStackTrace();
225       fail("Unexpected exception = " + exc.getLocalizedMessage());
226     }
227
228   }
229
230   /**
231    * Test doGet() and doPost() for a non-existent end-point. A test objective would be to either
232    * return a 404 Not Found.
233    */
234   @Test
235   public void validateMdcContextLoggingVariablesWhenNotExplicitlySet() {
236
237     /*
238      * final String transactionId = "1234"; final String serviceName = "AAI-UI"; final String
239      * partnerName = "SparkyApp";
240      * 
241      * HttpServletHelper.assignRequestHeader(commonRequest, "X-TransactionId", transactionId);
242      * HttpServletHelper.assignRequestHeader(commonRequest, "X-FromAppId", serviceName);
243      */
244
245     HttpServletHelper.assignRequestUri(commonRequest, "search/this/path/does/not/exist/");
246
247     try {
248
249       /*
250        * Testing the doGet() operation will hit the doPost() operation in the servlet as well
251        */
252
253       OperationResult result = doEvaluationTestMDC(true, commonRequest, commonResponse);
254
255       assertNotNull(MDC.get(MdcContext.MDC_REQUEST_ID));
256       assertNotNull(MDC.get(MdcContext.MDC_SERVICE_NAME));
257       assertNotNull(MDC.get(MdcContext.MDC_PARTNER_NAME));
258
259     } catch (Exception exc) {
260       exc.printStackTrace();
261       fail("Unexpected exception = " + exc.getLocalizedMessage());
262     }
263
264   }
265
266
267
268   /**
269    * Test doGet() and doPost() for a non-existent end-point.
270    */
271   @Test
272   public void validateViewAndInspectSearchError_invalidRequestUri() {
273
274     HttpServletHelper.assignRequestUri(commonRequest, "search/this/path/does/not/exist/");
275
276     try {
277
278       /*
279        * Testing the doGet() operation will hit the doPost() operation in the servlet as well
280        */
281
282       OperationResult result = doEvaluation(true, commonRequest, commonResponse);
283       assertEquals(404, result.getResultCode());
284       assertTrue(result.getResult().contains("Ignored request-uri"));
285
286     } catch (Exception exc) {
287       exc.printStackTrace();
288       fail("Unexpected exception = " + exc.getLocalizedMessage());
289     }
290
291   }
292
293
294   /**
295    * Test doGet() and doPost() for Unified Query Search success path
296    */
297   @Test
298   public void validateQuerySearch_successPath() {
299
300     try {
301
302       QuerySearchEntity searchEntity = new QuerySearchEntity();
303       searchEntity.setMaxResults("10");
304       searchEntity.setQueryStr("the quick brown fox");
305
306       HttpServletHelper.assignRequestUri(commonRequest, "search/querysearch");
307       HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(),
308           NodeUtils.convertObjectToJson(searchEntity, false));
309
310
311       // set search-abstraction-response that we expect to get back from real system, but stubbed
312       // through a mock
313       // to fulfill collaborator behavior
314
315       OperationResult mockedEntitySearchResponse = new OperationResult();
316       mockedEntitySearchResponse.setResultCode(200);
317       mockedEntitySearchResponse.setResult(NodeUtils.convertObjectToJson(
318           SearchAbstractionEntityBuilder.getSuccessfulEntitySearchResponse(), false));
319
320       // TODO: make parameters expect certain values to lock in invocation attempt against a
321       // specific input sequence
322       Mockito.when(searchAdapter.doPost(anyString(), anyString(), anyString()))
323           .thenReturn(mockedEntitySearchResponse);
324
325       List<SuggestionEntity> autoSuggestions = new ArrayList<SuggestionEntity>();
326
327       autoSuggestions.add(new SuggestionEntity("vnf", "1234", "VNFs"));
328       autoSuggestions.add(new SuggestionEntity("vnf", "1111", "Created VNFs"));
329       autoSuggestions.add(new SuggestionEntity("vnf", "1122", "ACTIVE VNFs"));
330       autoSuggestions.add(new SuggestionEntity("vnf", "2233", "ACTIVE and Error VNFs"));
331       autoSuggestions.add(new SuggestionEntity("vnf", "3344", "ACTIVE and NOT ORCHESTRATED VNFs"));
332       autoSuggestions.add(new SuggestionEntity("vnf", "4455", "ACTIVE and Running VNFs"));
333       autoSuggestions.add(new SuggestionEntity("vnf", "5566", "Activated VNFs"));
334       autoSuggestions.add(new SuggestionEntity("vnf", "6677", "CAPPED VNFs"));
335       autoSuggestions.add(new SuggestionEntity("vnf", "7788", "CAPPED and Created VNFs"));
336
337       Mockito.when(vnfSearchService.getSuggestionsResults(Mockito.anyObject(), Mockito.anyInt()))
338           .thenReturn(autoSuggestions);
339
340       /*
341        * Testing the doGet() operation will hit the doPost() operation in the servlet as well
342        */
343
344       OperationResult result = doEvaluation(true, commonRequest, commonResponse);
345
346
347       assertEquals(200, result.getResultCode());
348
349       SearchResponse searchResponse = mapper.readValue(result.getResult(), SearchResponse.class);
350
351       assertEquals(10, searchResponse.getTotalFound());
352
353       int numVnf = 0;
354       int numViewInspect = 0;
355
356       for (SuggestionEntity suggestion : searchResponse.getSuggestions()) {
357
358         if (VNF_ROUTE.equals(suggestion.getRoute())) {
359           numVnf++;
360         } else if (VIEW_INSPECT_ROUTE.equals(suggestion.getRoute())) {
361           numViewInspect++;
362         }
363       }
364
365       assertEquals(5, numVnf);
366       assertEquals(5, numViewInspect);
367
368       // assertTrue(result.getResult().contains("Ignored request-uri"));
369
370     } catch (Exception exc) {
371       fail("Unexpected exception = " + exc.getLocalizedMessage());
372     }
373
374   }
375
376   /**
377    * Test doGet() and doPost() for Unified Query Search success path
378    */
379   @Test
380   public void validateSummaryByEntityTypeCount_successPath() {
381
382     try {
383
384       HttpServletHelper.assignRequestUri(commonRequest, "search/summarybyentitytype/count");
385
386       Map<String, String> payloadFields = new HashMap<String, String>();
387       payloadFields.put("hashId",
388           "662d1b57c31df70d7ef57ec53c0ace81578ec77b6bc5de055a57c7547ec122dd");
389       payloadFields.put("groupby", "orchestration-status");
390
391
392       HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(),
393           NodeUtils.convertObjectToJson(payloadFields, false));
394
395
396       /*
397        * In this test we don't want to mock the vnf search service, only it's collaborator
398        * interactions with a REST endpoint.
399        */
400       vnfSearchService = new VnfSearchService();
401       vnfSearchService.setSearch(searchAdapter);
402       searchWrapper.setVnfSearch(vnfSearchService);
403
404       /*
405        * The first network response to mock is the one to elastic search to get the suggestion
406        * entity by hash id
407        * 
408        * http://localhost:9200/entityautosuggestindex-localhost/_search
409        * {"query":{"term":{"_id":"2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"}
410        * }}
411        */
412
413       AutoSuggestElasticSearchResponse elasticResponse = new AutoSuggestElasticSearchResponse();
414
415       elasticResponse.setTook(1);
416
417       elasticResponse.setTimedOut(false);
418       elasticResponse.addShard("total", "5");
419       elasticResponse.addShard("successful", "5");
420       elasticResponse.addShard("failed", "0");
421
422       AutoSuggestElasticHitEntity elasticHit = new AutoSuggestElasticHitEntity();
423       elasticHit.setIndex("entityautosuggestindex-localhost");
424       elasticHit.setType("default");
425       elasticHit.setId("2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d");
426       elasticHit.setScore("1");
427
428       AutoSuggestDocumentEntityFields suggestDocFields = new AutoSuggestDocumentEntityFields();
429       suggestDocFields.addInput("VNFs");
430       suggestDocFields.addInput("generic-vnfs");
431       suggestDocFields.setOutput("VNFs");
432       suggestDocFields.setPayload(new PayloadEntity());
433       suggestDocFields.setWeight(100);
434
435       AutoSuggestDocumentEntity autoSuggestDoc = new AutoSuggestDocumentEntity();
436       autoSuggestDoc.setFields(suggestDocFields);
437
438       elasticHit.setSource(autoSuggestDoc);
439
440       AutoSuggestElasticHitsEntity hits = new AutoSuggestElasticHitsEntity();
441       hits.addHit(elasticHit);
442
443       elasticResponse.setHits(hits);
444
445
446       OperationResult mockedSearchResponse = new OperationResult();
447       mockedSearchResponse.setResultCode(200);
448
449       mockedSearchResponse.setResult(NodeUtils.convertObjectToJson(elasticResponse, false));
450
451
452       /*
453        * The second response is the count API dip to elastic search
454        */
455
456       ElasticSearchCountResponse countResponse = new ElasticSearchCountResponse();
457       countResponse.setCount(3170);
458       countResponse.addShard("total", "5");
459       countResponse.addShard("successful", "5");
460       countResponse.addShard("failed", "0");
461
462       OperationResult searchResponseForCount = new OperationResult();
463       searchResponseForCount.setResultCode(200);
464
465       searchResponseForCount.setResult(NodeUtils.convertObjectToJson(countResponse, false));
466
467       // TODO: make parameters expect certain values to lock in invocation attempt against a
468       // specific input sequence
469       Mockito.when(searchAdapter.doPost(anyString(), anyString(), anyString()))
470           .thenReturn(mockedSearchResponse).thenReturn(searchResponseForCount);
471
472
473       /*
474        * Testing the doGet() operation will hit the doPost() operation in the servlet as well
475        */
476
477       OperationResult result = doEvaluation(true, commonRequest, commonResponse);
478
479
480       assertEquals(200, result.getResultCode());
481
482       //
483       // {"shards":{"total":"5","failed":"0","successful":"5"},"count":3170}
484
485       EntityCountResponse entityCountResponse =
486           mapper.readValue(result.getResult(), EntityCountResponse.class);
487
488       assertEquals(3170, entityCountResponse.getCount());
489
490     } catch (Exception exc) {
491       fail("Unexpected exception = " + exc.getLocalizedMessage());
492     }
493
494   }
495
496
497   /**
498    * Test doGet() and doPost() for Unified Query Search success path
499    */
500   @Test
501   public void validateSummaryByEntityType_successPath() {
502
503     try {
504
505       HttpServletHelper.assignRequestUri(commonRequest, "search/summarybyentitytype");
506
507       Map<String, String> payloadFields = new HashMap<String, String>();
508       payloadFields.put("hashId",
509           "662d1b57c31df70d7ef57ec53c0ace81578ec77b6bc5de055a57c7547ec122dd");
510       payloadFields.put("groupby", "orchestration-status");
511
512       HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(),
513           NodeUtils.convertObjectToJson(payloadFields, false));
514
515       /*
516        * In this test we don't want to mock the vnf search service, only it's collaborator
517        * interactions with a REST endpoint.
518        */
519       vnfSearchService = new VnfSearchService();
520       vnfSearchService.setSearch(searchAdapter);
521       searchWrapper.setVnfSearch(vnfSearchService);
522
523       /*
524        * The first network response to mock is the one to elastic search to get the suggestion
525        * entity by hash id
526        * 
527        * http://localhost:9200/entityautosuggestindex-localhost/_search
528        * {"query":{"term":{"_id":"2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"}
529        * }}
530        */
531
532       AutoSuggestElasticSearchResponse elasticResponse = new AutoSuggestElasticSearchResponse();
533
534       elasticResponse.setTook(1);
535
536       elasticResponse.setTimedOut(false);
537       elasticResponse.addShard("total", "5");
538       elasticResponse.addShard("successful", "5");
539       elasticResponse.addShard("failed", "0");
540
541       AutoSuggestElasticHitEntity elasticHit = new AutoSuggestElasticHitEntity();
542       elasticHit.setIndex("entityautosuggestindex-localhost");
543       elasticHit.setType("default");
544       elasticHit.setId("2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d");
545       elasticHit.setScore("1");
546
547       AutoSuggestDocumentEntityFields suggestDocFields = new AutoSuggestDocumentEntityFields();
548       suggestDocFields.addInput("VNFs");
549       suggestDocFields.addInput("generic-vnfs");
550       suggestDocFields.setOutput("VNFs");
551       suggestDocFields.setPayload(new PayloadEntity());
552       suggestDocFields.setWeight(100);
553
554       AutoSuggestDocumentEntity autoSuggestDoc = new AutoSuggestDocumentEntity();
555       autoSuggestDoc.setFields(suggestDocFields);
556
557       elasticHit.setSource(autoSuggestDoc);
558
559       AutoSuggestElasticHitsEntity hits = new AutoSuggestElasticHitsEntity();
560       hits.addHit(elasticHit);
561
562       elasticResponse.setHits(hits);
563
564
565       OperationResult mockedSearchResponse = new OperationResult();
566       mockedSearchResponse.setResultCode(200);
567
568       mockedSearchResponse.setResult(NodeUtils.convertObjectToJson(elasticResponse, false));
569
570
571       /*
572        * The second response is the aggregation API dip to elastic search
573        */
574
575       ElasticSearchAggegrationResponse aggResponse = new ElasticSearchAggegrationResponse();
576
577       aggResponse.setTook(20);
578       aggResponse.setTimedOut(false);
579
580       aggResponse.addShard("total", "5");
581       aggResponse.addShard("successful", "5");
582       aggResponse.addShard("failed", "0");
583
584       ElasticHitsEntity hitsEntity = new ElasticHitsEntity();
585
586       hitsEntity.setTotal(3170);
587       hitsEntity.setMaxScore(0);
588
589       aggResponse.setHits(hitsEntity);
590
591       ElasticSearchAggregation defaultAggregation = new ElasticSearchAggregation();
592
593       defaultAggregation.setDocCountErrorUpperBound(0);
594       defaultAggregation.setSumOtherDocCount(0);
595       defaultAggregation.addBucket(new BucketEntity("created", 1876));
596       defaultAggregation.addBucket(new BucketEntity("Created", 649));
597       defaultAggregation.addBucket(new BucketEntity("Activated", 158));
598       defaultAggregation.addBucket(new BucketEntity("active", 59));
599       defaultAggregation.addBucket(new BucketEntity("NOT ORCHESTRATED", 42));
600       defaultAggregation.addBucket(new BucketEntity("Pending-Create", 10));
601       defaultAggregation.addBucket(new BucketEntity("Running", 9));
602       defaultAggregation.addBucket(new BucketEntity("Configured", 7));
603       defaultAggregation.addBucket(new BucketEntity("pending-create", 7));
604       defaultAggregation.addBucket(new BucketEntity("Error", 3));
605       defaultAggregation.addBucket(new BucketEntity("planned", 3));
606       defaultAggregation.addBucket(new BucketEntity("PLANNED", 2));
607       defaultAggregation.addBucket(new BucketEntity("ERROR", 1));
608       defaultAggregation.addBucket(new BucketEntity("RUNNING", 1));
609       defaultAggregation.addBucket(new BucketEntity("example-orchestration-status-val-6176", 1));
610
611       aggResponse.addAggregation("default", defaultAggregation);
612
613       OperationResult searchResponseForAggregation = new OperationResult();
614       searchResponseForAggregation.setResultCode(200);
615
616       searchResponseForAggregation.setResult(NodeUtils.convertObjectToJson(aggResponse, false));
617
618       // TODO: make parameters expect certain values to lock in invocation attempt against a
619       // specific input sequence
620       Mockito.when(searchAdapter.doPost(anyString(), anyString(), anyString()))
621           .thenReturn(mockedSearchResponse).thenReturn(searchResponseForAggregation);
622
623
624       /*
625        * Testing the doGet() operation will hit the doPost() operation in the servlet as well
626        */
627
628       OperationResult result = doEvaluation(true, commonRequest, commonResponse);
629
630
631       assertEquals(200, result.getResultCode());
632
633       //
634       // {"shards":{"total":"5","failed":"0","successful":"5"},"count":3170}
635
636       GroupByAggregationResponseEntity groupByResponse =
637           mapper.readValue(result.getResult(), GroupByAggregationResponseEntity.class);
638
639       assertEquals(2828, groupByResponse.getAggEntity().getTotalChartHits());
640       assertEquals(15, groupByResponse.getAggEntity().getBuckets().size());
641
642     } catch (Exception exc) {
643       fail("Unexpected exception = " + exc.getLocalizedMessage());
644     }
645
646   }
647
648
649
650   /**
651    * Builds the resource entity descriptor.
652    *
653    * @param entityType the entity type
654    * @param attributeNames the attribute names
655    * @param searchableAttributes the searchable attributes
656    * @return the oxm entity descriptor
657    */
658   @SuppressWarnings("unchecked")
659   private OxmEntityDescriptor buildResourceEntityDescriptor(String entityType,
660       String attributeNames, String searchableAttributes) {
661     OxmEntityDescriptor descriptor = new OxmEntityDescriptor();
662     descriptor.setEntityName(entityType);
663
664     if (attributeNames != null) {
665       descriptor.setPrimaryKeyAttributeName(Arrays.asList(attributeNames.split(",")));
666     }
667
668     if (searchableAttributes != null) {
669       descriptor.setSearchableAttributes(Arrays.asList(searchableAttributes.split(",")));
670     }
671
672     return descriptor;
673   }
674
675   /**
676    * Initialize entity descriptors.
677    */
678   private void initializeEntityDescriptors() {
679     descriptors.put("customer",
680         buildResourceEntityDescriptor("customer", "service-instance-id", "f1,f2,f3"));
681   }
682
683   /**
684    * Builds the view and inspect search request.
685    *
686    * @param maxResults the max results
687    * @param queryStr the query str
688    * @return the string
689    * @throws JsonProcessingException the json processing exception
690    */
691   public String buildViewAndInspectSearchRequest(Integer maxResults, String queryStr)
692       throws JsonProcessingException {
693
694     /*
695      * { "maxResults" : "10", "searchStr" : "<search bar text>" }
696      */
697
698     ObjectNode rootNode = mapper.createObjectNode();
699
700     if (maxResults != null) {
701       rootNode.put("maxResults", maxResults);
702     }
703
704     if (queryStr != null) {
705       rootNode.put("queryStr", queryStr);
706     }
707
708     return NodeUtils.convertObjectToJson(rootNode, true);
709
710   }
711
712
713   /**
714    * Do evaluation.
715    *
716    * @param doGet the do get
717    * @param req the req
718    * @param res the res
719    * @return the string
720    */
721   private OperationResult doEvaluationTestMDC(boolean doGet, HttpServletRequest req,
722       HttpServletResponse res) {
723
724     /*
725      * Test method invocation
726      */
727
728     SearchServlet searchServlet = new SearchServlet();
729     try {
730       searchServlet.init();
731     } catch (ServletException e) {
732       // TODO Auto-generated catch block
733       e.printStackTrace();
734     }
735     ArgumentCaptor<Integer> responseCodeCaptor = ArgumentCaptor.forClass(Integer.class);
736
737     try {
738       if (doGet) {
739         searchServlet.doGet(req, res);
740       } else {
741         searchServlet.doPost(req, res);
742       }
743     } catch (ServletException exc) {
744       fail(ExceptionHelper.extractStackTraceElements(5, exc));
745     } catch (IOException exc) {
746       fail(ExceptionHelper.extractStackTraceElements(5, exc));
747     }
748
749     responseStringWriter.flush();
750     Mockito.verify(commonResponse, Mockito.atLeast(1)).setStatus(responseCodeCaptor.capture());
751
752     OperationResult result = new OperationResult();
753
754     result.setResultCode(responseCodeCaptor.getValue());
755     result.setResult(responseStringWriter.toString());
756
757     return result;
758
759   }
760
761   /**
762    * Do evaluation.
763    *
764    * @param doGet the do get
765    * @param req the req
766    * @param res the res
767    * @return the string
768    */
769   private OperationResult doEvaluation(boolean doGet, HttpServletRequest req,
770       HttpServletResponse res) {
771
772     /*
773      * Test method invocation
774      */
775     ArgumentCaptor<Integer> responseCodeCaptor = ArgumentCaptor.forClass(Integer.class);
776
777     try {
778       if (doGet) {
779         searchWrapper.doGet(req, res);
780       } else {
781         searchWrapper.doPost(req, res);
782       }
783     } catch (ServletException exc) {
784       fail(ExceptionHelper.extractStackTraceElements(5, exc));
785     } catch (IOException exc) {
786       fail(ExceptionHelper.extractStackTraceElements(5, exc));
787     }
788
789     responseStringWriter.flush();
790     Mockito.verify(commonResponse, Mockito.atLeast(1)).setStatus(responseCodeCaptor.capture());
791
792     OperationResult result = new OperationResult();
793
794     result.setResultCode(responseCodeCaptor.getValue());
795     result.setResult(responseStringWriter.toString());
796
797     return result;
798
799   }
800
801
802
803 }