Initial commit for AAI-UI(sparky-backend)
[aai/sparky-be.git] / src / test / java / org / openecomp / 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.openecomp.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.openecomp.sparky.config.oxm.OxmEntityDescriptor;
54 import org.openecomp.sparky.config.oxm.OxmModelLoader;
55 import org.openecomp.sparky.dal.elasticsearch.SearchAdapter;
56 import org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestDocumentEntity;
57 import org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestDocumentEntityFields;
58 import org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestElasticHitEntity;
59 import org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestElasticHitsEntity;
60 import org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestElasticSearchResponse;
61 import org.openecomp.sparky.dal.elasticsearch.entity.BucketEntity;
62 import org.openecomp.sparky.dal.elasticsearch.entity.ElasticHitsEntity;
63 import org.openecomp.sparky.dal.elasticsearch.entity.ElasticSearchAggegrationResponse;
64 import org.openecomp.sparky.dal.elasticsearch.entity.ElasticSearchAggregation;
65 import org.openecomp.sparky.dal.elasticsearch.entity.ElasticSearchCountResponse;
66 import org.openecomp.sparky.dal.elasticsearch.entity.PayloadEntity;
67 import org.openecomp.sparky.dal.rest.OperationResult;
68 import org.openecomp.sparky.dal.sas.config.SearchServiceConfig;
69 import org.openecomp.sparky.dal.sas.entity.EntityCountResponse;
70 import org.openecomp.sparky.dal.sas.entity.GroupByAggregationResponseEntity;
71 import org.openecomp.sparky.dal.sas.entity.SearchAbstractionEntityBuilder;
72 import org.openecomp.sparky.search.VnfSearchService;
73 import org.openecomp.sparky.search.config.SuggestionConfig;
74 import org.openecomp.sparky.suggestivesearch.SuggestionEntity;
75 import org.openecomp.sparky.util.ExceptionHelper;
76 import org.openecomp.sparky.util.HttpServletHelper;
77 import org.openecomp.sparky.util.NodeUtils;
78 import org.openecomp.sparky.viewandinspect.entity.QuerySearchEntity;
79 import org.openecomp.sparky.viewandinspect.entity.SearchResponse;
80 import org.openecomp.sparky.viewandinspect.services.SearchServiceWrapper;
81 import org.openecomp.sparky.viewandinspect.servlet.SearchServlet;
82 import org.slf4j.MDC;
83
84 import org.openecomp.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 
197    * to either 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 
232    * to either return a 404 Not Found.
233    */
234   @Test
235   public void validateMdcContextLoggingVariablesWhenNotExplicitlySet() {
236     
237     /*final String transactionId = "1234";
238     final String serviceName = "AAI-UI";
239     final String partnerName = "SparkyApp";
240     
241     HttpServletHelper.assignRequestHeader(commonRequest, "X-TransactionId", transactionId);
242     HttpServletHelper.assignRequestHeader(commonRequest, "X-FromAppId", serviceName);*/
243     
244     HttpServletHelper.assignRequestUri(commonRequest, "search/this/path/does/not/exist/");
245     
246     try {
247
248       /*
249        * Testing the doGet() operation will hit the doPost() operation in the servlet as well
250        */
251
252       OperationResult result = doEvaluationTestMDC(true, commonRequest, commonResponse);
253       
254       assertNotNull(MDC.get(MdcContext.MDC_REQUEST_ID));
255       assertNotNull(MDC.get(MdcContext.MDC_SERVICE_NAME));
256       assertNotNull(MDC.get(MdcContext.MDC_PARTNER_NAME));
257
258     } catch (Exception exc) {
259       exc.printStackTrace();
260       fail("Unexpected exception = " + exc.getLocalizedMessage());
261     }
262
263   }
264   
265   
266   
267   /**
268    * Test doGet() and doPost() for a non-existent end-point.  
269    */
270   @Test
271   public void validateViewAndInspectSearchError_invalidRequestUri() {
272     
273     HttpServletHelper.assignRequestUri(commonRequest, "search/this/path/does/not/exist/");
274     
275     try {
276
277       /*
278        * Testing the doGet() operation will hit the doPost() operation in the servlet as well
279        */
280
281       OperationResult result = doEvaluation(true, commonRequest, commonResponse);
282       assertEquals(404, result.getResultCode());
283       assertTrue(result.getResult().contains("Ignored request-uri"));
284
285     } catch (Exception exc) {
286       exc.printStackTrace();
287       fail("Unexpected exception = " + exc.getLocalizedMessage());
288     }
289
290   }
291   
292   
293   /**
294    * Test doGet() and doPost() for Unified Query Search success path  
295    */
296   @Test
297   public void validateQuerySearch_successPath() {
298
299     try {
300
301       QuerySearchEntity searchEntity = new QuerySearchEntity();
302       searchEntity.setMaxResults("10");
303       searchEntity.setQueryStr("the quick brown fox");
304
305       HttpServletHelper.assignRequestUri(commonRequest, "search/querysearch"); 
306       HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(),
307           NodeUtils.convertObjectToJson(searchEntity, false));
308
309       
310       // set search-abstraction-response that we expect to get back from real system, but stubbed through a mock
311       // to fulfill collaborator behavior
312
313       OperationResult mockedEntitySearchResponse = new OperationResult();
314       mockedEntitySearchResponse.setResultCode(200);
315       mockedEntitySearchResponse.setResult(NodeUtils.convertObjectToJson(
316           SearchAbstractionEntityBuilder.getSuccessfulEntitySearchResponse(), false));
317
318       // TODO:  make parameters expect certain values to lock in invocation attempt against a specific input sequence
319       Mockito.when(searchAdapter.doPost(anyString(), anyString(), anyString()))
320           .thenReturn(mockedEntitySearchResponse);
321       
322       List<SuggestionEntity> autoSuggestions = new ArrayList<SuggestionEntity>();
323
324       autoSuggestions.add(new SuggestionEntity("vnf","1234", "VNFs"));
325       autoSuggestions.add(new SuggestionEntity("vnf","1111", "Created VNFs"));
326       autoSuggestions.add(new SuggestionEntity("vnf","1122", "ACTIVE VNFs"));
327       autoSuggestions.add(new SuggestionEntity("vnf","2233", "ACTIVE and Error VNFs"));
328       autoSuggestions.add(new SuggestionEntity("vnf","3344", "ACTIVE and NOT ORCHESTRATED VNFs"));
329       autoSuggestions.add(new SuggestionEntity("vnf","4455", "ACTIVE and Running VNFs"));
330       autoSuggestions.add(new SuggestionEntity("vnf","5566", "Activated VNFs"));
331       autoSuggestions.add(new SuggestionEntity("vnf","6677", "CAPPED VNFs"));
332       autoSuggestions.add(new SuggestionEntity("vnf","7788", "CAPPED and Created VNFs"));
333       
334       Mockito.when(vnfSearchService.getSuggestionsResults(Mockito.anyObject(), Mockito.anyInt()))
335           .thenReturn(autoSuggestions);
336
337       /*
338        * Testing the doGet() operation will hit the doPost() operation in the servlet as well
339        */
340
341       OperationResult result = doEvaluation(true, commonRequest, commonResponse);
342       
343       
344       assertEquals(200, result.getResultCode());
345       
346       SearchResponse searchResponse = mapper.readValue(result.getResult(), SearchResponse.class);
347       
348       assertEquals(10, searchResponse.getTotalFound());
349       
350       int numVnf = 0;
351       int numViewInspect = 0;
352       
353       for ( SuggestionEntity suggestion : searchResponse.getSuggestions()) {
354       
355         if ( VNF_ROUTE.equals(suggestion.getRoute())) {
356           numVnf++;
357         } else if ( VIEW_INSPECT_ROUTE.equals(suggestion.getRoute())) {
358           numViewInspect++;
359         }
360       }
361       
362       assertEquals(5, numVnf);
363       assertEquals(5, numViewInspect);
364       
365       //assertTrue(result.getResult().contains("Ignored request-uri"));
366
367     } catch (Exception exc) {
368       fail("Unexpected exception = " + exc.getLocalizedMessage());
369     }
370
371   }
372   
373   /**
374    * Test doGet() and doPost() for Unified Query Search success path  
375    */
376   @Test
377   public void validateSummaryByEntityTypeCount_successPath() {
378
379     try {
380
381       HttpServletHelper.assignRequestUri(commonRequest, "search/summarybyentitytype/count");
382       
383       Map<String,String> payloadFields = new HashMap<String,String>();
384       payloadFields.put("hashId", "662d1b57c31df70d7ef57ec53c0ace81578ec77b6bc5de055a57c7547ec122dd");
385       payloadFields.put("groupby", "orchestration-status");
386       
387       
388       HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), NodeUtils.convertObjectToJson(payloadFields, false));
389            
390       
391       /*
392        * In this test we don't want to mock the vnf search service, only it's collaborator
393        * interactions with a REST endpoint.
394        */
395       vnfSearchService = new VnfSearchService();
396       vnfSearchService.setSearch(searchAdapter);
397       searchWrapper.setVnfSearch(vnfSearchService);
398
399       /*
400        * The first network response to mock is the one to elastic search to get the suggestion entity by hash id
401        * 
402        *    http://localhost:9200/entityautosuggestindex-localhost/_search
403        *         {"query":{"term":{"_id":"2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"}}}
404        */
405       
406       AutoSuggestElasticSearchResponse elasticResponse = new AutoSuggestElasticSearchResponse();
407       
408       elasticResponse.setTook(1);
409       
410       elasticResponse.setTimedOut(false);
411       elasticResponse.addShard("total", "5");
412       elasticResponse.addShard("successful", "5");
413       elasticResponse.addShard("failed", "0");
414       
415       AutoSuggestElasticHitEntity elasticHit = new AutoSuggestElasticHitEntity();
416       elasticHit.setIndex("entityautosuggestindex-localhost");
417       elasticHit.setType("default");
418       elasticHit.setId("2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d");
419       elasticHit.setScore("1");
420       
421       AutoSuggestDocumentEntityFields suggestDocFields = new AutoSuggestDocumentEntityFields();
422       suggestDocFields.addInput("VNFs");
423       suggestDocFields.addInput("generic-vnfs");
424       suggestDocFields.setOutput("VNFs");
425       suggestDocFields.setPayload(new PayloadEntity());
426       suggestDocFields.setWeight(100);
427       
428       AutoSuggestDocumentEntity autoSuggestDoc = new AutoSuggestDocumentEntity();
429       autoSuggestDoc.setFields(suggestDocFields);
430       
431       elasticHit.setSource(autoSuggestDoc);
432       
433       AutoSuggestElasticHitsEntity hits = new AutoSuggestElasticHitsEntity();
434       hits.addHit(elasticHit);
435       
436       elasticResponse.setHits(hits);
437       
438       
439       OperationResult mockedSearchResponse = new OperationResult();
440       mockedSearchResponse.setResultCode(200);
441       
442       mockedSearchResponse.setResult(NodeUtils.convertObjectToJson(elasticResponse, false));
443
444       
445       /*
446        * The second response is the count API dip to elastic search
447        */
448       
449       ElasticSearchCountResponse countResponse = new ElasticSearchCountResponse();
450       countResponse.setCount(3170);
451       countResponse.addShard("total", "5");
452       countResponse.addShard("successful", "5");
453       countResponse.addShard("failed", "0");
454
455       OperationResult searchResponseForCount = new OperationResult();
456       searchResponseForCount.setResultCode(200);
457       
458       searchResponseForCount.setResult(NodeUtils.convertObjectToJson(countResponse, false));
459
460       // TODO:  make parameters expect certain values to lock in invocation attempt against a specific input sequence
461       Mockito.when(searchAdapter.doPost(anyString(), anyString(), anyString()))
462           .thenReturn(mockedSearchResponse).thenReturn(searchResponseForCount);
463       
464       
465       /*
466        * Testing the doGet() operation will hit the doPost() operation in the servlet as well
467        */
468
469       OperationResult result = doEvaluation(true, commonRequest, commonResponse);
470       
471       
472       assertEquals(200, result.getResultCode());
473       
474       //
475       //{"shards":{"total":"5","failed":"0","successful":"5"},"count":3170}
476       
477      EntityCountResponse entityCountResponse = mapper.readValue(result.getResult(), EntityCountResponse.class);
478       
479      assertEquals(3170, entityCountResponse.getCount());
480
481     } catch (Exception exc) {
482       fail("Unexpected exception = " + exc.getLocalizedMessage());
483     }
484
485   }
486   
487   
488   /**
489    * Test doGet() and doPost() for Unified Query Search success path  
490    */
491   @Test
492   public void validateSummaryByEntityType_successPath() {
493
494     try {
495
496       HttpServletHelper.assignRequestUri(commonRequest, "search/summarybyentitytype");
497       
498       Map<String,String> payloadFields = new HashMap<String,String>();
499       payloadFields.put("hashId", "662d1b57c31df70d7ef57ec53c0ace81578ec77b6bc5de055a57c7547ec122dd");
500       payloadFields.put("groupby", "orchestration-status");
501       
502       HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), NodeUtils.convertObjectToJson(payloadFields, false));
503       
504       /*
505        * In this test we don't want to mock the vnf search service, only it's collaborator
506        * interactions with a REST endpoint.
507        */
508       vnfSearchService = new VnfSearchService();
509       vnfSearchService.setSearch(searchAdapter);
510       searchWrapper.setVnfSearch(vnfSearchService);
511
512       /*
513        * The first network response to mock is the one to elastic search to get the suggestion entity by hash id
514        * 
515        *    http://localhost:9200/entityautosuggestindex-localhost/_search
516        *         {"query":{"term":{"_id":"2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"}}}
517        */
518       
519       AutoSuggestElasticSearchResponse elasticResponse = new AutoSuggestElasticSearchResponse();
520       
521       elasticResponse.setTook(1);
522       
523       elasticResponse.setTimedOut(false);
524       elasticResponse.addShard("total", "5");
525       elasticResponse.addShard("successful", "5");
526       elasticResponse.addShard("failed", "0");
527       
528       AutoSuggestElasticHitEntity elasticHit = new AutoSuggestElasticHitEntity();
529       elasticHit.setIndex("entityautosuggestindex-localhost");
530       elasticHit.setType("default");
531       elasticHit.setId("2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d");
532       elasticHit.setScore("1");
533       
534       AutoSuggestDocumentEntityFields suggestDocFields = new AutoSuggestDocumentEntityFields();
535       suggestDocFields.addInput("VNFs");
536       suggestDocFields.addInput("generic-vnfs");
537       suggestDocFields.setOutput("VNFs");
538       suggestDocFields.setPayload(new PayloadEntity());
539       suggestDocFields.setWeight(100);
540       
541       AutoSuggestDocumentEntity autoSuggestDoc = new AutoSuggestDocumentEntity();
542       autoSuggestDoc.setFields(suggestDocFields);
543       
544       elasticHit.setSource(autoSuggestDoc);
545       
546       AutoSuggestElasticHitsEntity hits = new AutoSuggestElasticHitsEntity();
547       hits.addHit(elasticHit);
548       
549       elasticResponse.setHits(hits);
550       
551       
552       OperationResult mockedSearchResponse = new OperationResult();
553       mockedSearchResponse.setResultCode(200);
554       
555       mockedSearchResponse.setResult(NodeUtils.convertObjectToJson(elasticResponse, false));
556
557       
558       /*
559        * The second response is the aggregation API dip to elastic search
560        */
561       
562       ElasticSearchAggegrationResponse aggResponse = new ElasticSearchAggegrationResponse();
563       
564       aggResponse.setTook(20);
565       aggResponse.setTimedOut(false);
566       
567       aggResponse.addShard("total","5");
568       aggResponse.addShard("successful","5");
569       aggResponse.addShard("failed","0");
570       
571       ElasticHitsEntity hitsEntity = new ElasticHitsEntity();
572       
573       hitsEntity.setTotal(3170);
574       hitsEntity.setMaxScore(0);
575
576       aggResponse.setHits(hitsEntity);
577       
578       ElasticSearchAggregation defaultAggregation = new ElasticSearchAggregation();
579       
580       defaultAggregation.setDocCountErrorUpperBound(0);
581       defaultAggregation.setSumOtherDocCount(0);
582       defaultAggregation.addBucket(new BucketEntity("created",1876));
583       defaultAggregation.addBucket(new BucketEntity("Created",649));
584       defaultAggregation.addBucket(new BucketEntity("Activated",158));
585       defaultAggregation.addBucket(new BucketEntity("active",59));
586       defaultAggregation.addBucket(new BucketEntity("NOT ORCHESTRATED",42));
587       defaultAggregation.addBucket(new BucketEntity("Pending-Create",10));
588       defaultAggregation.addBucket(new BucketEntity("Running",9));
589       defaultAggregation.addBucket(new BucketEntity("Configured",7));
590       defaultAggregation.addBucket(new BucketEntity("pending-create",7));
591       defaultAggregation.addBucket(new BucketEntity("Error",3));
592       defaultAggregation.addBucket(new BucketEntity("planned",3));
593       defaultAggregation.addBucket(new BucketEntity("PLANNED",2));
594       defaultAggregation.addBucket(new BucketEntity("ERROR",1));
595       defaultAggregation.addBucket(new BucketEntity("RUNNING",1));
596       defaultAggregation.addBucket(new BucketEntity("example-orchestration-status-val-6176",1));
597       
598       aggResponse.addAggregation("default", defaultAggregation);
599       
600       OperationResult searchResponseForAggregation = new OperationResult();
601       searchResponseForAggregation.setResultCode(200);
602       
603       searchResponseForAggregation.setResult(NodeUtils.convertObjectToJson(aggResponse, false));
604
605       // TODO:  make parameters expect certain values to lock in invocation attempt against a specific input sequence
606       Mockito.when(searchAdapter.doPost(anyString(), anyString(), anyString()))
607           .thenReturn(mockedSearchResponse).thenReturn(searchResponseForAggregation);
608       
609       
610       /*
611        * Testing the doGet() operation will hit the doPost() operation in the servlet as well
612        */
613
614       OperationResult result = doEvaluation(true, commonRequest, commonResponse);
615       
616       
617       assertEquals(200, result.getResultCode());
618       
619       //
620       //{"shards":{"total":"5","failed":"0","successful":"5"},"count":3170}
621       
622      GroupByAggregationResponseEntity groupByResponse = mapper.readValue(result.getResult(), GroupByAggregationResponseEntity.class);
623       
624      assertEquals(2828, groupByResponse.getAggEntity().getTotalChartHits());
625      assertEquals(15, groupByResponse.getAggEntity().getBuckets().size());
626
627     } catch (Exception exc) {
628       fail("Unexpected exception = " + exc.getLocalizedMessage());
629     }
630
631   }
632   
633   
634   
635   /**
636    * Builds the resource entity descriptor.
637    *
638    * @param entityType the entity type
639    * @param attributeNames the attribute names
640    * @param searchableAttributes the searchable attributes
641    * @return the oxm entity descriptor
642    */
643   @SuppressWarnings("unchecked")
644   private OxmEntityDescriptor buildResourceEntityDescriptor(String entityType,
645       String attributeNames, String searchableAttributes) {
646     OxmEntityDescriptor descriptor = new OxmEntityDescriptor();
647     descriptor.setEntityName(entityType);
648
649     if (attributeNames != null) {
650       descriptor.setPrimaryKeyAttributeName(Arrays.asList(attributeNames.split(",")));
651     }
652
653     if (searchableAttributes != null) {
654       descriptor.setSearchableAttributes(Arrays.asList(searchableAttributes.split(",")));
655     }
656
657     return descriptor;
658   }
659
660   /**
661    * Initialize entity descriptors.
662    */
663   private void initializeEntityDescriptors() {
664     descriptors.put("customer",
665         buildResourceEntityDescriptor("customer", "service-instance-id", "f1,f2,f3"));
666   }
667  
668   /**
669    * Builds the view and inspect search request.
670    *
671    * @param maxResults the max results
672    * @param queryStr the query str
673    * @return the string
674    * @throws JsonProcessingException the json processing exception
675    */
676   public String buildViewAndInspectSearchRequest(Integer maxResults, String queryStr)
677       throws JsonProcessingException {
678
679     /*
680      * { "maxResults" : "10", "searchStr" : "<search bar text>" }
681      */
682
683     ObjectNode rootNode = mapper.createObjectNode();
684
685     if (maxResults != null) {
686       rootNode.put("maxResults", maxResults);
687     }
688
689     if (queryStr != null) {
690       rootNode.put("queryStr", queryStr);
691     }
692
693     return NodeUtils.convertObjectToJson(rootNode, true);
694
695   }
696
697
698   /**
699    * Do evaluation.
700    *
701    * @param doGet the do get
702    * @param req the req
703    * @param res the res
704    * @return the string
705    */
706   private OperationResult doEvaluationTestMDC(boolean doGet, HttpServletRequest req, HttpServletResponse res) {
707
708     /*
709      * Test method invocation
710      */
711
712     SearchServlet searchServlet = new SearchServlet();
713     try {
714       searchServlet.init();
715     } catch (ServletException e) {
716       // TODO Auto-generated catch block
717       e.printStackTrace();
718     }
719     ArgumentCaptor<Integer> responseCodeCaptor = ArgumentCaptor.forClass(Integer.class);
720     
721     try {
722       if (doGet) {
723         searchServlet.doGet(req, res);
724       } else {
725         searchServlet.doPost(req, res);
726       }
727     } catch (ServletException exc) {
728       fail(ExceptionHelper.extractStackTraceElements(5, exc));
729     } catch (IOException exc) {
730       fail(ExceptionHelper.extractStackTraceElements(5, exc));
731     }
732
733     responseStringWriter.flush();
734     Mockito.verify(commonResponse, Mockito.atLeast(1)).setStatus(responseCodeCaptor.capture());
735     
736     OperationResult result = new OperationResult();
737     
738     result.setResultCode(responseCodeCaptor.getValue());
739     result.setResult(responseStringWriter.toString());
740
741     return result;
742
743   }
744   
745   /**
746    * Do evaluation.
747    *
748    * @param doGet the do get
749    * @param req the req
750    * @param res the res
751    * @return the string
752    */
753   private OperationResult doEvaluation(boolean doGet, HttpServletRequest req, HttpServletResponse res) {
754
755     /*
756      * Test method invocation
757      */
758     ArgumentCaptor<Integer> responseCodeCaptor = ArgumentCaptor.forClass(Integer.class);
759     
760     try {
761       if (doGet) {
762         searchWrapper.doGet(req, res);
763       } else {
764         searchWrapper.doPost(req, res);
765       }
766     } catch (ServletException exc) {
767       fail(ExceptionHelper.extractStackTraceElements(5, exc));
768     } catch (IOException exc) {
769       fail(ExceptionHelper.extractStackTraceElements(5, exc));
770     }
771
772     responseStringWriter.flush();
773     Mockito.verify(commonResponse, Mockito.atLeast(1)).setStatus(responseCodeCaptor.capture());
774     
775     OperationResult result = new OperationResult();
776     
777     result.setResultCode(responseCodeCaptor.getValue());
778     result.setResult(responseStringWriter.toString());
779
780     return result;
781
782   }
783
784  
785
786 }