summaryrefslogtreecommitdiffstats
path: root/src/test/java/org/openecomp/sparky/viewandinspect/SearchServletTest.java
blob: 9e147358f5266290a35135f183c9ba7fbcce1569 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
/* 
* ============LICENSE_START=======================================================
* SPARKY (inventory UI service)
* ================================================================================
* Copyright © 2017 AT&T Intellectual Property.
* Copyright © 2017 Amdocs
* All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
* 
* ECOMP and OpenECOMP are trademarks
* and service marks of AT&T Intellectual Property.
*/

package org.openecomp.sparky.viewandinspect;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.anyString;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.openecomp.sparky.config.oxm.OxmEntityDescriptor;
import org.openecomp.sparky.config.oxm.OxmModelLoader;
import org.openecomp.sparky.dal.elasticsearch.SearchAdapter;
import org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestDocumentEntity;
import org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestDocumentEntityFields;
import org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestElasticHitEntity;
import org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestElasticHitsEntity;
import org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestElasticSearchResponse;
import org.openecomp.sparky.dal.elasticsearch.entity.BucketEntity;
import org.openecomp.sparky.dal.elasticsearch.entity.ElasticHitsEntity;
import org.openecomp.sparky.dal.elasticsearch.entity.ElasticSearchAggegrationResponse;
import org.openecomp.sparky.dal.elasticsearch.entity.ElasticSearchAggregation;
import org.openecomp.sparky.dal.elasticsearch.entity.ElasticSearchCountResponse;
import org.openecomp.sparky.dal.elasticsearch.entity.PayloadEntity;
import org.openecomp.sparky.dal.rest.OperationResult;
import org.openecomp.sparky.dal.sas.config.SearchServiceConfig;
import org.openecomp.sparky.dal.sas.entity.EntityCountResponse;
import org.openecomp.sparky.dal.sas.entity.GroupByAggregationResponseEntity;
import org.openecomp.sparky.dal.sas.entity.SearchAbstractionEntityBuilder;
import org.openecomp.sparky.search.VnfSearchService;
import org.openecomp.sparky.search.config.SuggestionConfig;
import org.openecomp.sparky.suggestivesearch.SuggestionEntity;
import org.openecomp.sparky.util.ExceptionHelper;
import org.openecomp.sparky.util.HttpServletHelper;
import org.openecomp.sparky.util.NodeUtils;
import org.openecomp.sparky.viewandinspect.entity.QuerySearchEntity;
import org.openecomp.sparky.viewandinspect.entity.SearchResponse;
import org.openecomp.sparky.viewandinspect.services.SearchServiceWrapper;
import org.openecomp.sparky.viewandinspect.servlet.SearchServlet;
import org.slf4j.MDC;

import org.openecomp.cl.mdc.MdcContext;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.net.MediaType;


/**
 * The Class SearchServletTest.
 */

public class SearchServletTest {

  private static final String VNF_ROUTE = "vnf";
  private static final String VIEW_INSPECT_ROUTE = "viewInspect";
  
  private HttpServletRequest commonRequest = null;
  private HttpServletResponse commonResponse = null;
  private PrintWriter printWriter = null;
  private StringWriter responseStringWriter = null;
  private SearchServiceWrapper searchWrapper = null;
  private SearchAdapter searchAdapter = null;
  private VnfSearchService vnfSearchService = null;
  private ObjectMapper mapper = null;
  private SecureRandom rand = null;
  private OxmModelLoader loader;
  private Map<String, OxmEntityDescriptor> descriptors = null;
  private SuggestionConfig suggestionConfig = null;
  private SearchServiceConfig esConfig = null;
  
  /**
   * Inits the.
   *
   * @throws Exception the exception
   */
  @Before
  public void init() throws Exception {

    commonRequest = HttpServletHelper.getMockHttpServletRequest();
    responseStringWriter = new StringWriter();
    printWriter = new PrintWriter(responseStringWriter);
    commonResponse = HttpServletHelper.getMockHttpServletResponse(printWriter);
    mapper = new ObjectMapper();

    // permit serialization of objects with no members
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    
    rand = new SecureRandom();

    loader = Mockito.mock(OxmModelLoader.class); 
    descriptors = new HashMap<String, OxmEntityDescriptor>();

    esConfig = new SearchServiceConfig();
    suggestionConfig = SuggestionConfig.getConfig();
    
    // Use SearchServiceWrapper and VnfSearchService for suggestionConfig
    Map<String, String> svcs = new HashMap<String, String>();
    svcs.put("autosuggestIndexname", "SearchServiceWrapper");
    svcs.put("indexName", "VnfSearchService");
    suggestionConfig.setSearchIndexToSearchService(svcs);
    
    esConfig.setIndexName("esi-localhost");
    esConfig.setType("default");

    searchAdapter = Mockito.mock(SearchAdapter.class);
    vnfSearchService = Mockito.mock(VnfSearchService.class);

    initializeEntityDescriptors();
    
    searchWrapper = new SearchServiceWrapper();
    searchWrapper.setSasConfig(esConfig);
    searchWrapper.setSearch(searchAdapter);
    searchWrapper.setVnfSearch(vnfSearchService);
    searchWrapper.setSuggestionConfig(suggestionConfig);
    searchWrapper.setOxmModelLoader(loader);
  }

  @Test
  public void validateAccessors() {
    assertNotNull("Vnf Search Service should not be null", searchWrapper.getVnfSearch());    
  }
  
  @Test
  public void validateInitializer() {

    try {
      assertNotNull("Oxm Model loader should not be null", searchWrapper.getOxmModelLoader());
      assertNotNull("SearchAbstractionConfig should not be null", searchWrapper.getSasConfig());
      assertNotNull("SearchAdapter should not be null", searchWrapper.getSearch());
      assertNotNull("Suggestion Config should not be null", searchWrapper.getSuggestionConfig());
      assertNotNull("VnfSearchService should not be null", searchWrapper.getVnfSearch());
      
      searchWrapper.setOxmModelLoader(null);
      searchWrapper.setSasConfig(null);
      searchWrapper.setSearch(null);
      searchWrapper.setSuggestionConfig(null);
      searchWrapper.setVnfSearch(null);

      assertNull("Oxm Model loader should be null", searchWrapper.getOxmModelLoader());
      assertNull("SearchAbstractionConfig should be null", searchWrapper.getSasConfig());
      assertNull("SearchAdapter should be null", searchWrapper.getSearch());
      assertNull("Suggestion Config should be null", searchWrapper.getSuggestionConfig());
      assertNull("VnfSearchService should be null", searchWrapper.getVnfSearch());

    } catch (Exception exc) {
      fail("Servlet Initialization Failed with error = " + exc.getMessage());
    }

  }
  
  /**
   * Test doGet() and doPost() for a non-existent end-point.  A test objective would be 
   * to either return a 404 Not Found.
   */
  @Test
  public void validateMdcContextLoggingVariablesWhenExplicitlySet() {
    
    final String transactionId = "1234";
    final String serviceName = "AAI_UI";
    final String partnerName = "SparkyApp";
    
    HttpServletHelper.assignRequestHeader(commonRequest, "X-TransactionId", transactionId);
    HttpServletHelper.assignRequestHeader(commonRequest, "X-FromAppId", partnerName);
    
    HttpServletHelper.assignRequestUri(commonRequest, "search/this/path/does/not/exist/");
    
    try {
      
      /*
       * Testing the doGet() operation will hit the doPost() operation in the servlet as well
       */

      OperationResult result = doEvaluationTestMDC(true, commonRequest, commonResponse);
      
      assertEquals(transactionId,MDC.get(MdcContext.MDC_REQUEST_ID));
      assertEquals(serviceName,MDC.get(MdcContext.MDC_SERVICE_NAME));
      assertEquals(partnerName,MDC.get(MdcContext.MDC_PARTNER_NAME));

    } catch (Exception exc) {
      exc.printStackTrace();
      fail("Unexpected exception = " + exc.getLocalizedMessage());
    }

  }
  
  /**
   * Test doGet() and doPost() for a non-existent end-point.  A test objective would be 
   * to either return a 404 Not Found.
   */
  @Test
  public void validateMdcContextLoggingVariablesWhenNotExplicitlySet() {
    
    /*final String transactionId = "1234";
    final String serviceName = "AAI-UI";
    final String partnerName = "SparkyApp";
    
    HttpServletHelper.assignRequestHeader(commonRequest, "X-TransactionId", transactionId);
    HttpServletHelper.assignRequestHeader(commonRequest, "X-FromAppId", serviceName);*/
    
    HttpServletHelper.assignRequestUri(commonRequest, "search/this/path/does/not/exist/");
    
    try {

      /*
       * Testing the doGet() operation will hit the doPost() operation in the servlet as well
       */

      OperationResult result = doEvaluationTestMDC(true, commonRequest, commonResponse);
      
      assertNotNull(MDC.get(MdcContext.MDC_REQUEST_ID));
      assertNotNull(MDC.get(MdcContext.MDC_SERVICE_NAME));
      assertNotNull(MDC.get(MdcContext.MDC_PARTNER_NAME));

    } catch (Exception exc) {
      exc.printStackTrace();
      fail("Unexpected exception = " + exc.getLocalizedMessage());
    }

  }
  
  
  
  /**
   * Test doGet() and doPost() for a non-existent end-point.  
   */
  @Test
  public void validateViewAndInspectSearchError_invalidRequestUri() {
    
    HttpServletHelper.assignRequestUri(commonRequest, "search/this/path/does/not/exist/");
    
    try {

      /*
       * Testing the doGet() operation will hit the doPost() operation in the servlet as well
       */

      OperationResult result = doEvaluation(true, commonRequest, commonResponse);
      assertEquals(404, result.getResultCode());
      assertTrue(result.getResult().contains("Ignored request-uri"));

    } catch (Exception exc) {
      exc.printStackTrace();
      fail("Unexpected exception = " + exc.getLocalizedMessage());
    }

  }
  
  
  /**
   * Test doGet() and doPost() for Unified Query Search success path  
   */
  @Test
  public void validateQuerySearch_successPath() {

    try {

      QuerySearchEntity searchEntity = new QuerySearchEntity();
      searchEntity.setMaxResults("10");
      searchEntity.setQueryStr("the quick brown fox");

      HttpServletHelper.assignRequestUri(commonRequest, "search/querysearch"); 
      HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(),
          NodeUtils.convertObjectToJson(searchEntity, false));

      
      // set search-abstraction-response that we expect to get back from real system, but stubbed through a mock
      // to fulfill collaborator behavior

      OperationResult mockedEntitySearchResponse = new OperationResult();
      mockedEntitySearchResponse.setResultCode(200);
      mockedEntitySearchResponse.setResult(NodeUtils.convertObjectToJson(
          SearchAbstractionEntityBuilder.getSuccessfulEntitySearchResponse(), false));

      // TODO:  make parameters expect certain values to lock in invocation attempt against a specific input sequence
      Mockito.when(searchAdapter.doPost(anyString(), anyString(), anyString()))
          .thenReturn(mockedEntitySearchResponse);
      
      List<SuggestionEntity> autoSuggestions = new ArrayList<SuggestionEntity>();

      autoSuggestions.add(new SuggestionEntity("vnf","1234", "VNFs"));
      autoSuggestions.add(new SuggestionEntity("vnf","1111", "Created VNFs"));
      autoSuggestions.add(new SuggestionEntity("vnf","1122", "ACTIVE VNFs"));
      autoSuggestions.add(new SuggestionEntity("vnf","2233", "ACTIVE and Error VNFs"));
      autoSuggestions.add(new SuggestionEntity("vnf","3344", "ACTIVE and NOT ORCHESTRATED VNFs"));
      autoSuggestions.add(new SuggestionEntity("vnf","4455", "ACTIVE and Running VNFs"));
      autoSuggestions.add(new SuggestionEntity("vnf","5566", "Activated VNFs"));
      autoSuggestions.add(new SuggestionEntity("vnf","6677", "CAPPED VNFs"));
      autoSuggestions.add(new SuggestionEntity("vnf","7788", "CAPPED and Created VNFs"));
      
      Mockito.when(vnfSearchService.getSuggestionsResults(Mockito.anyObject(), Mockito.anyInt()))
          .thenReturn(autoSuggestions);

      /*
       * Testing the doGet() operation will hit the doPost() operation in the servlet as well
       */

      OperationResult result = doEvaluation(true, commonRequest, commonResponse);
      
      
      assertEquals(200, result.getResultCode());
      
      SearchResponse searchResponse = mapper.readValue(result.getResult(), SearchResponse.class);
      
      assertEquals(10, searchResponse.getTotalFound());
      
      int numVnf = 0;
      int numViewInspect = 0;
      
      for ( SuggestionEntity suggestion : searchResponse.getSuggestions()) {
      
        if ( VNF_ROUTE.equals(suggestion.getRoute())) {
          numVnf++;
        } else if ( VIEW_INSPECT_ROUTE.equals(suggestion.getRoute())) {
          numViewInspect++;
        }
      }
      
      assertEquals(5, numVnf);
      assertEquals(5, numViewInspect);
      
      //assertTrue(result.getResult().contains("Ignored request-uri"));

    } catch (Exception exc) {
      fail("Unexpected exception = " + exc.getLocalizedMessage());
    }

  }
  
  /**
   * Test doGet() and doPost() for Unified Query Search success path  
   */
  @Test
  public void validateSummaryByEntityTypeCount_successPath() {

    try {

      HttpServletHelper.assignRequestUri(commonRequest, "search/summarybyentitytype/count");
      
      Map<String,String> payloadFields = new HashMap<String,String>();
      payloadFields.put("hashId", "662d1b57c31df70d7ef57ec53c0ace81578ec77b6bc5de055a57c7547ec122dd");
      payloadFields.put("groupby", "orchestration-status");
      
      
      HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), NodeUtils.convertObjectToJson(payloadFields, false));
           
      
      /*
       * In this test we don't want to mock the vnf search service, only it's collaborator
       * interactions with a REST endpoint.
       */
      vnfSearchService = new VnfSearchService();
      vnfSearchService.setSearch(searchAdapter);
      searchWrapper.setVnfSearch(vnfSearchService);

      /*
       * The first network response to mock is the one to elastic search to get the suggestion entity by hash id
       * 
       *    http://localhost:9200/entityautosuggestindex-localhost/_search
       *         {"query":{"term":{"_id":"2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"}}}
       */
      
      AutoSuggestElasticSearchResponse elasticResponse = new AutoSuggestElasticSearchResponse();
      
      elasticResponse.setTook(1);
      
      elasticResponse.setTimedOut(false);
      elasticResponse.addShard("total", "5");
      elasticResponse.addShard("successful", "5");
      elasticResponse.addShard("failed", "0");
      
      AutoSuggestElasticHitEntity elasticHit = new AutoSuggestElasticHitEntity();
      elasticHit.setIndex("entityautosuggestindex-localhost");
      elasticHit.setType("default");
      elasticHit.setId("2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d");
      elasticHit.setScore("1");
      
      AutoSuggestDocumentEntityFields suggestDocFields = new AutoSuggestDocumentEntityFields();
      suggestDocFields.addInput("VNFs");
      suggestDocFields.addInput("generic-vnfs");
      suggestDocFields.setOutput("VNFs");
      suggestDocFields.setPayload(new PayloadEntity());
      suggestDocFields.setWeight(100);
      
      AutoSuggestDocumentEntity autoSuggestDoc = new AutoSuggestDocumentEntity();
      autoSuggestDoc.setFields(suggestDocFields);
      
      elasticHit.setSource(autoSuggestDoc);
      
      AutoSuggestElasticHitsEntity hits = new AutoSuggestElasticHitsEntity();
      hits.addHit(elasticHit);
      
      elasticResponse.setHits(hits);
      
      
      OperationResult mockedSearchResponse = new OperationResult();
      mockedSearchResponse.setResultCode(200);
      
      mockedSearchResponse.setResult(NodeUtils.convertObjectToJson(elasticResponse, false));

      
      /*
       * The second response is the count API dip to elastic search
       */
      
      ElasticSearchCountResponse countResponse = new ElasticSearchCountResponse();
      countResponse.setCount(3170);
      countResponse.addShard("total", "5");
      countResponse.addShard("successful", "5");
      countResponse.addShard("failed", "0");

      OperationResult searchResponseForCount = new OperationResult();
      searchResponseForCount.setResultCode(200);
      
      searchResponseForCount.setResult(NodeUtils.convertObjectToJson(countResponse, false));

      // TODO:  make parameters expect certain values to lock in invocation attempt against a specific input sequence
      Mockito.when(searchAdapter.doPost(anyString(), anyString(), anyString()))
          .thenReturn(mockedSearchResponse).thenReturn(searchResponseForCount);
      
      
      /*
       * Testing the doGet() operation will hit the doPost() operation in the servlet as well
       */

      OperationResult result = doEvaluation(true, commonRequest, commonResponse);
      
      
      assertEquals(200, result.getResultCode());
      
      //
      //{"shards":{"total":"5","failed":"0","successful":"5"},"count":3170}
      
     EntityCountResponse entityCountResponse = mapper.readValue(result.getResult(), EntityCountResponse.class);
      
     assertEquals(3170, entityCountResponse.getCount());

    } catch (Exception exc) {
      fail("Unexpected exception = " + exc.getLocalizedMessage());
    }

  }
  
  
  /**
   * Test doGet() and doPost() for Unified Query Search success path  
   */
  @Test
  public void validateSummaryByEntityType_successPath() {

    try {

      HttpServletHelper.assignRequestUri(commonRequest, "search/summarybyentitytype");
      
      Map<String,String> payloadFields = new HashMap<String,String>();
      payloadFields.put("hashId", "662d1b57c31df70d7ef57ec53c0ace81578ec77b6bc5de055a57c7547ec122dd");
      payloadFields.put("groupby", "orchestration-status");
      
      HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), NodeUtils.convertObjectToJson(payloadFields, false));
      
      /*
       * In this test we don't want to mock the vnf search service, only it's collaborator
       * interactions with a REST endpoint.
       */
      vnfSearchService = new VnfSearchService();
      vnfSearchService.setSearch(searchAdapter);
      searchWrapper.setVnfSearch(vnfSearchService);

      /*
       * The first network response to mock is the one to elastic search to get the suggestion entity by hash id
       * 
       *    http://localhost:9200/entityautosuggestindex-localhost/_search
       *         {"query":{"term":{"_id":"2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"}}}
       */
      
      AutoSuggestElasticSearchResponse elasticResponse = new AutoSuggestElasticSearchResponse();
      
      elasticResponse.setTook(1);
      
      elasticResponse.setTimedOut(false);
      elasticResponse.addShard("total", "5");
      elasticResponse.addShard("successful", "5");
      elasticResponse.addShard("failed", "0");
      
      AutoSuggestElasticHitEntity elasticHit = new AutoSuggestElasticHitEntity();
      elasticHit.setIndex("entityautosuggestindex-localhost");
      elasticHit.setType("default");
      elasticHit.setId("2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d");
      elasticHit.setScore("1");
      
      AutoSuggestDocumentEntityFields suggestDocFields = new AutoSuggestDocumentEntityFields();
      suggestDocFields.addInput("VNFs");
      suggestDocFields.addInput("generic-vnfs");
      suggestDocFields.setOutput("VNFs");
      suggestDocFields.setPayload(new PayloadEntity());
      suggestDocFields.setWeight(100);
      
      AutoSuggestDocumentEntity autoSuggestDoc = new AutoSuggestDocumentEntity();
      autoSuggestDoc.setFields(suggestDocFields);
      
      elasticHit.setSource(autoSuggestDoc);
      
      AutoSuggestElasticHitsEntity hits = new AutoSuggestElasticHitsEntity();
      hits.addHit(elasticHit);
      
      elasticResponse.setHits(hits);
      
      
      OperationResult mockedSearchResponse = new OperationResult();
      mockedSearchResponse.setResultCode(200);
      
      mockedSearchResponse.setResult(NodeUtils.convertObjectToJson(elasticResponse, false));

      
      /*
       * The second response is the aggregation API dip to elastic search
       */
      
      ElasticSearchAggegrationResponse aggResponse = new ElasticSearchAggegrationResponse();
      
      aggResponse.setTook(20);
      aggResponse.setTimedOut(false);
      
      aggResponse.addShard("total","5");
      aggResponse.addShard("successful","5");
      aggResponse.addShard("failed","0");
      
      ElasticHitsEntity hitsEntity = new ElasticHitsEntity();
      
      hitsEntity.setTotal(3170);
      hitsEntity.setMaxScore(0);

      aggResponse.setHits(hitsEntity);
      
      ElasticSearchAggregation defaultAggregation = new ElasticSearchAggregation();
      
      defaultAggregation.setDocCountErrorUpperBound(0);
      defaultAggregation.setSumOtherDocCount(0);
      defaultAggregation.addBucket(new BucketEntity("created",1876));
      defaultAggregation.addBucket(new BucketEntity("Created",649));
      defaultAggregation.addBucket(new BucketEntity("Activated",158));
      defaultAggregation.addBucket(new BucketEntity("active",59));
      defaultAggregation.addBucket(new BucketEntity("NOT ORCHESTRATED",42));
      defaultAggregation.addBucket(new BucketEntity("Pending-Create",10));
      defaultAggregation.addBucket(new BucketEntity("Running",9));
      defaultAggregation.addBucket(new BucketEntity("Configured",7));
      defaultAggregation.addBucket(new BucketEntity("pending-create",7));
      defaultAggregation.addBucket(new BucketEntity("Error",3));
      defaultAggregation.addBucket(new BucketEntity("planned",3));
      defaultAggregation.addBucket(new BucketEntity("PLANNED",2));
      defaultAggregation.addBucket(new BucketEntity("ERROR",1));
      defaultAggregation.addBucket(new BucketEntity("RUNNING",1));
      defaultAggregation.addBucket(new BucketEntity("example-orchestration-status-val-6176",1));
      
      aggResponse.addAggregation("default", defaultAggregation);
      
      OperationResult searchResponseForAggregation = new OperationResult();
      searchResponseForAggregation.setResultCode(200);
      
      searchResponseForAggregation.setResult(NodeUtils.convertObjectToJson(aggResponse, false));

      // TODO:  make parameters expect certain values to lock in invocation attempt against a specific input sequence
      Mockito.when(searchAdapter.doPost(anyString(), anyString(), anyString()))
          .thenReturn(mockedSearchResponse).thenReturn(searchResponseForAggregation);
      
      
      /*
       * Testing the doGet() operation will hit the doPost() operation in the servlet as well
       */

      OperationResult result = doEvaluation(true, commonRequest, commonResponse);
      
      
      assertEquals(200, result.getResultCode());
      
      //
      //{"shards":{"total":"5","failed":"0","successful":"5"},"count":3170}
      
     GroupByAggregationResponseEntity groupByResponse = mapper.readValue(result.getResult(), GroupByAggregationResponseEntity.class);
      
     assertEquals(2828, groupByResponse.getAggEntity().getTotalChartHits());
     assertEquals(15, groupByResponse.getAggEntity().getBuckets().size());

    } catch (Exception exc) {
      fail("Unexpected exception = " + exc.getLocalizedMessage());
    }

  }
  
  
  
  /**
   * Builds the resource entity descriptor.
   *
   * @param entityType the entity type
   * @param attributeNames the attribute names
   * @param searchableAttributes the searchable attributes
   * @return the oxm entity descriptor
   */
  @SuppressWarnings("unchecked")
  private OxmEntityDescriptor buildResourceEntityDescriptor(String entityType,
      String attributeNames, String searchableAttributes) {
    OxmEntityDescriptor descriptor = new OxmEntityDescriptor();
    descriptor.setEntityName(entityType);

    if (attributeNames != null) {
      descriptor.setPrimaryKeyAttributeName(Arrays.asList(attributeNames.split(",")));
    }

    if (searchableAttributes != null) {
      descriptor.setSearchableAttributes(Arrays.asList(searchableAttributes.split(",")));
    }

    return descriptor;
  }

  /**
   * Initialize entity descriptors.
   */
  private void initializeEntityDescriptors() {
    descriptors.put("customer",
        buildResourceEntityDescriptor("customer", "service-instance-id", "f1,f2,f3"));
  }
 
  /**
   * Builds the view and inspect search request.
   *
   * @param maxResults the max results
   * @param queryStr the query str
   * @return the string
   * @throws JsonProcessingException the json processing exception
   */
  public String buildViewAndInspectSearchRequest(Integer maxResults, String queryStr)
      throws JsonProcessingException {

    /*
     * { "maxResults" : "10", "searchStr" : "<search bar text>" }
     */

    ObjectNode rootNode = mapper.createObjectNode();

    if (maxResults != null) {
      rootNode.put("maxResults", maxResults);
    }

    if (queryStr != null) {
      rootNode.put("queryStr", queryStr);
    }

    return NodeUtils.convertObjectToJson(rootNode, true);

  }


  /**
   * Do evaluation.
   *
   * @param doGet the do get
   * @param req the req
   * @param res the res
   * @return the string
   */
  private OperationResult doEvaluationTestMDC(boolean doGet, HttpServletRequest req, HttpServletResponse res) {

    /*
     * Test method invocation
     */

    SearchServlet searchServlet = new SearchServlet();
    try {
      searchServlet.init();
    } catch (ServletException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    ArgumentCaptor<Integer> responseCodeCaptor = ArgumentCaptor.forClass(Integer.class);
    
    try {
      if (doGet) {
        searchServlet.doGet(req, res);
      } else {
        searchServlet.doPost(req, res);
      }
    } catch (ServletException exc) {
      fail(ExceptionHelper.extractStackTraceElements(5, exc));
    } catch (IOException exc) {
      fail(ExceptionHelper.extractStackTraceElements(5, exc));
    }

    responseStringWriter.flush();
    Mockito.verify(commonResponse, Mockito.atLeast(1)).setStatus(responseCodeCaptor.capture());
    
    OperationResult result = new OperationResult();
    
    result.setResultCode(responseCodeCaptor.getValue());
    result.setResult(responseStringWriter.toString());

    return result;

  }
  
  /**
   * Do evaluation.
   *
   * @param doGet the do get
   * @param req the req
   * @param res the res
   * @return the string
   */
  private OperationResult doEvaluation(boolean doGet, HttpServletRequest req, HttpServletResponse res) {

    /*
     * Test method invocation
     */
    ArgumentCaptor<Integer> responseCodeCaptor = ArgumentCaptor.forClass(Integer.class);
    
    try {
      if (doGet) {
        searchWrapper.doGet(req, res);
      } else {
        searchWrapper.doPost(req, res);
      }
    } catch (ServletException exc) {
      fail(ExceptionHelper.extractStackTraceElements(5, exc));
    } catch (IOException exc) {
      fail(ExceptionHelper.extractStackTraceElements(5, exc));
    }

    responseStringWriter.flush();
    Mockito.verify(commonResponse, Mockito.atLeast(1)).setStatus(responseCodeCaptor.capture());
    
    OperationResult result = new OperationResult();
    
    result.setResultCode(responseCodeCaptor.getValue());
    result.setResult(responseStringWriter.toString());

    return result;

  }

 

}