summaryrefslogtreecommitdiffstats
path: root/src/test/java/org/onap/dmaap/dmf/mr/service/impl/EventsServiceImplTest.java
blob: f9178e1e27e4c85dcca601af035d587a036e8e92 (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
/*-
 * ============LICENSE_START=======================================================
 * ONAP Policy Engine
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. 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=========================================================
 */

package org.onap.dmaap.dmf.mr.service.impl;

import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import com.att.nsa.limits.Blacklist;
import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException;
import com.att.nsa.security.db.simple.NsaSimpleApiKey;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import javax.servlet.http.HttpServletRequest;
import joptsimple.internal.Strings;
import org.apache.http.HttpStatus;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import org.onap.dmaap.dmf.mr.CambriaApiException;
import org.onap.dmaap.dmf.mr.backends.Consumer;
import org.onap.dmaap.dmf.mr.backends.ConsumerFactory;
import org.onap.dmaap.dmf.mr.backends.ConsumerFactory.UnavailableException;
import org.onap.dmaap.dmf.mr.backends.MetricsSet;
import org.onap.dmaap.dmf.mr.backends.Publisher;
import org.onap.dmaap.dmf.mr.beans.DMaaPCambriaLimiter;
import org.onap.dmaap.dmf.mr.beans.DMaaPContext;
import org.onap.dmaap.dmf.mr.beans.DMaaPKafkaMetaBroker;
import org.onap.dmaap.dmf.mr.exception.DMaaPAccessDeniedException;
import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages;
import org.onap.dmaap.dmf.mr.metabroker.Topic;
import org.onap.dmaap.dmf.mr.resources.CambriaOutboundEventStream;
import org.onap.dmaap.dmf.mr.security.DMaaPAuthenticator;
import org.onap.dmaap.dmf.mr.utils.ConfigurationReader;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

@RunWith(MockitoJUnitRunner.class)
public class EventsServiceImplTest {

    private InputStream iStream = null;
    private DMaaPContext dMaapContext = new DMaaPContext();
    private DMaaPErrorMessages pErrorMessages = new DMaaPErrorMessages();
    @Mock
    private ConfigurationReader configurationReader;
    @Mock
    private Blacklist blacklist;
    @Mock
    private DMaaPAuthenticator<NsaSimpleApiKey> dmaaPAuthenticator;
    @Mock
    private NsaSimpleApiKey nsaSimpleApiKey;
    @Mock
    private DMaaPKafkaMetaBroker dmaapKafkaMetaBroker;
    @Mock
    private Topic createdTopic;
    @Mock
    private ConsumerFactory factory;
    @Mock
    private Consumer consumer;
    @Mock
    private Publisher publisher;
    @Mock
    private DMaaPCambriaLimiter limiter;
    @Mock
    private MetricsSet metrics;
    @Spy
    private EventsServiceImpl eventsService;


    @Rule
    public ExpectedException thrown = ExpectedException.none();

    private MockHttpServletRequest request;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        String source = "source of my InputStream";
        iStream = new ByteArrayInputStream(source.getBytes("UTF-8"));

        request = new MockHttpServletRequest();
        MockHttpServletResponse response = new MockHttpServletResponse();
        dMaapContext.setRequest(request);
        dMaapContext.setResponse(response);
        when(blacklist.contains(anyString())).thenReturn(false);
        when(configurationReader.getfIpBlackList()).thenReturn(blacklist);
        when(configurationReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator);
        dMaapContext.setConfigReader(configurationReader);
        eventsService.setErrorMessages(pErrorMessages);
        doReturn("100").when(eventsService).getPropertyFromAJSCmap("timeout");
    }

    @Test
    public void getEvents_shouldFailOnAafAuthorization() throws Exception {
        String topicPrefix = "org.onap.aaf.enforced";
        String topicName = topicPrefix + ".topicName";
        when(configurationReader.getfMetaBroker()).thenReturn(dmaapKafkaMetaBroker);
        when(dmaapKafkaMetaBroker.getTopic(topicName)).thenReturn(createdTopic);
        when(eventsService.getPropertyFromAJSCmap("enforced.topic.name.AAF")).thenReturn(topicPrefix);
        when(eventsService.isCadiEnabled()).thenReturn(true);

        thrown.expect(DMaaPAccessDeniedException.class);
        thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_UNAUTHORIZED)));

        eventsService.getEvents(dMaapContext, topicName, "CG1", "23");
    }

    @Test
    public void getEvents_shouldFail_whenRemoteAddressIsBlacklisted() throws Exception {
        String remoteIp = "10.154.17.115";
        request.setRemoteAddr(remoteIp);
        when(blacklist.contains(remoteIp)).thenReturn(true);
        when(configurationReader.getfIpBlackList()).thenReturn(blacklist);

        thrown.expect(CambriaApiException.class);
        thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_FORBIDDEN)));

        eventsService.getEvents(dMaapContext, "testTopic", "CG1", "23");
    }

    @Test
    public void getEvents_shouldFail_whenRequestedTopicNotExists() throws Exception {
        when(configurationReader.getfMetaBroker()).thenReturn(dmaapKafkaMetaBroker);
        when(dmaapKafkaMetaBroker.getTopic("testTopic")).thenReturn(null);

        thrown.expect(CambriaApiException.class);
        thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_NOT_FOUND)));

        eventsService.getEvents(dMaapContext, "testTopic", "CG1", "23");
    }

    @Test
    public void getEvents_shouldFail_whenConsumerLockCannotBeAcquired() throws Exception {
        //given
        String topicName = "testTopic345";
        String consumerGroup = "CG5";
        String clientId = "13";
        when(configurationReader.getfMetaBroker()).thenReturn(dmaapKafkaMetaBroker);
        when(configurationReader.getfRateLimiter()).thenReturn(limiter);
        when(dmaapKafkaMetaBroker.getTopic(topicName)).thenReturn(createdTopic);
        when(configurationReader.getfConsumerFactory()).thenReturn(factory);
        when(dmaaPAuthenticator.authenticate(dMaapContext)).thenReturn(nsaSimpleApiKey);
        doThrow(new UnavailableException("Could not acquire consumer lock")).when(factory)
            .getConsumerFor(eq(topicName), eq(consumerGroup), eq(clientId), anyInt(), anyString());

        thrown.expect(CambriaApiException.class);
        thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_SERVICE_UNAVAILABLE)));

        //when
        eventsService.getEvents(dMaapContext, topicName, consumerGroup, clientId);

        //then
        verify(factory).getConsumerFor(eq(topicName), eq(consumerGroup), eq(clientId), anyInt(), anyString());

    }

    @Test
    public void getEvents_shouldFail_whenBrokerServicesAreUnavailable() throws Exception {
        String topicName = "testTopic";
        String consumerGroup = "CG1";
        String clientId = "23";
        when(dmaaPAuthenticator.authenticate(dMaapContext)).thenReturn(null);
        when(configurationReader.getfMetaBroker()).thenReturn(dmaapKafkaMetaBroker);
        when(dmaapKafkaMetaBroker.getTopic(topicName)).thenReturn(createdTopic);
        when(configurationReader.getfConsumerFactory()).thenReturn(factory);

        givenUserAuthorizedWithAAF(request, topicName, "sub");

        thrown.expect(CambriaApiException.class);
        thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_SERVICE_UNAVAILABLE)));

        //when
        eventsService.getEvents(dMaapContext, topicName, consumerGroup, clientId);

        //then
        verify(factory).destroyConsumer(topicName, consumerGroup, clientId);
    }

    private void givenUserAuthorizedWithAAF(MockHttpServletRequest request, String topicName, String operation) {
        String permission = "org.onap.dmaap.mr.topic|:topic." + topicName + "|" + operation;
        request.addUserRole(permission);
    }

    @Test
    public void getEvents_shouldHandleConcurrentModificationError() throws Exception {
        String testTopic = "testTopic";
        when(configurationReader.getfMetaBroker()).thenReturn(dmaapKafkaMetaBroker);
        when(dmaapKafkaMetaBroker.getTopic(testTopic)).thenReturn(createdTopic);
        when(configurationReader.getfConsumerFactory()).thenReturn(factory);
        when(configurationReader.getfRateLimiter()).thenThrow(new ConcurrentModificationException("Error occurred"));
        givenUserAuthorizedWithAAF(request, testTopic, "sub");

        thrown.expect(CambriaApiException.class);
        thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_CONFLICT)));

        eventsService.getEvents(dMaapContext, "testTopic", "CG1", "23");
    }

    @Test
    public void getEvents_shouldNotAuthorizeClient_whenSubscribingToMetricsTopic() throws Exception {
        //given
        HttpServletRequest permittedRequest = mock(HttpServletRequest.class);
        when(permittedRequest.getHeaders(anyString())).thenReturn(Collections.<String>emptyEnumeration());
        dMaapContext.setRequest(permittedRequest);
        String metricsTopicName = "msgrtr.apinode.metrics.dmaap";
        String consumerGroup = "CG5";
        String clientId = "7";
        givenConfiguredWithMocks(metricsTopicName);
        when(factory.getConsumerFor(eq(metricsTopicName), eq(consumerGroup), eq(clientId), anyInt(), anyString()))
            .thenReturn(consumer);
        doNothing().when(eventsService).respondOkWithStream(eq(dMaapContext), any(CambriaOutboundEventStream.class));

        //when
        eventsService.getEvents(dMaapContext, metricsTopicName, consumerGroup, clientId);

        //then
        verify(eventsService).respondOkWithStream(eq(dMaapContext), any(CambriaOutboundEventStream.class));
        verify(dmaaPAuthenticator, never()).authenticate(dMaapContext);
        verify(permittedRequest, never()).isUserInRole(anyString());
    }

    @Test
    public void getEvents_shouldNotAuthorizeClient_whenTopicNoteEnforcedWithAaf_andTopicHasNoOwnerSet()
        throws Exception {
        //given
        String topicName = "someSimpleTopicName";
        String consumerGroup = "CG5";
        String clientId = "7";
        HttpServletRequest permittedRequest = mock(HttpServletRequest.class);
        when(permittedRequest.getHeaders(anyString())).thenReturn(Collections.<String>emptyEnumeration());
        dMaapContext.setRequest(permittedRequest);
        givenConfiguredWithMocks(topicName);
        when(factory.getConsumerFor(eq(topicName), eq(consumerGroup), eq(clientId), anyInt(), anyString()))
            .thenReturn(consumer);
        doNothing().when(eventsService).respondOkWithStream(eq(dMaapContext), any(CambriaOutboundEventStream.class));
        when(createdTopic.getOwner()).thenReturn(Strings.EMPTY);

        //when
        eventsService.getEvents(dMaapContext, topicName, consumerGroup, clientId);

        //then
        verify(eventsService).respondOkWithStream(eq(dMaapContext), any(CambriaOutboundEventStream.class));
        verify(dmaaPAuthenticator, never()).authenticate(dMaapContext);
        verify(permittedRequest, never()).isUserInRole(anyString());
    }

    @Test
    public void getEvents_shouldFailDmaapAuthorization_whenTopicOwnerIsSet_andUserHasNoReadPermissionToTopic()
        throws Exception {
        //given
        String topicName = "someSimpleTopicName";
        String consumerGroup = "CG5";
        String clientId = "7";
        HttpServletRequest permittedRequest = mock(HttpServletRequest.class);
        when(permittedRequest.getHeaders(anyString())).thenReturn(Collections.<String>emptyEnumeration());
        dMaapContext.setRequest(permittedRequest);
        givenConfiguredWithMocks(topicName);
        when(factory.getConsumerFor(eq(topicName), eq(consumerGroup), eq(clientId), anyInt(), anyString()))
            .thenReturn(consumer);
        doNothing().when(eventsService).respondOkWithStream(eq(dMaapContext), any(CambriaOutboundEventStream.class));
        when(createdTopic.getOwner()).thenReturn("SimpleTopicOwner");
        when(dmaaPAuthenticator.authenticate(dMaapContext)).thenReturn(nsaSimpleApiKey);
        doThrow(new AccessDeniedException("userName")).when(createdTopic).checkUserRead(nsaSimpleApiKey);

        thrown.expect(AccessDeniedException.class);

        //when
        eventsService.getEvents(dMaapContext, topicName, consumerGroup, clientId);

        //then
        verify(createdTopic).checkUserRead(nsaSimpleApiKey);
        verify(eventsService, never()).respondOkWithStream(eq(dMaapContext), any(CambriaOutboundEventStream.class));
        verify(permittedRequest, never()).isUserInRole(anyString());
    }


    @Test
    public void getEvents_shouldSuccessfullyRegisterConsumerToEventsStream_withAafAuthorization() throws Exception {
        //given
        String topicName = "testTopic";
        String consumerGroup = "CG2";
        String clientId = "6";
        String messageLimit = "10";
        String timeout = "25";
        String meta = "yes";
        String pretty = "on";
        String cacheEnabled = "false";

        givenConfiguredWithMocks(topicName);
        givenConfiguredWithProperties(messageLimit, timeout, meta, pretty, cacheEnabled);
        when(factory.getConsumerFor(eq(topicName), eq(consumerGroup), eq(clientId), anyInt(), anyString()))
            .thenReturn(consumer);
        givenUserAuthorizedWithAAF(request, topicName, "sub");

        //when
        eventsService.getEvents(dMaapContext, topicName, consumerGroup, clientId);

        //then
        ArgumentCaptor<CambriaOutboundEventStream> osWriter = ArgumentCaptor.forClass(CambriaOutboundEventStream.class);
        verifyInvocationOrderForSuccessCase(topicName, consumerGroup, clientId, osWriter);
        assertEventStreamProperties(osWriter.getValue(), messageLimit, timeout);
    }

    private void assertEventStreamProperties(CambriaOutboundEventStream stream, String messageLimit, String timeout) {
        assertEquals(Integer.valueOf(messageLimit).intValue(), stream.getfLimit());
        assertEquals(Integer.valueOf(timeout).intValue(), stream.getfTimeoutMs());
        assertTrue(stream.isfWithMeta());
        assertTrue(stream.isfPretty());
    }

    private void givenConfiguredWithProperties(String messageLimit, String timeout, String meta, String pretty,
        String cacheEnabled) {
        when(eventsService.getPropertyFromAJSCmap("meta")).thenReturn(meta);
        when(eventsService.getPropertyFromAJSCmap("pretty")).thenReturn(pretty);
        when(eventsService.getPropertyFromAJSCmap(ConsumerFactory.kSetting_EnableCache)).thenReturn(cacheEnabled);
        request.addParameter("timeout", timeout);
        request.addParameter("limit", messageLimit);
    }

    private void givenConfiguredWithMocks(String topicName) throws Exception {
        when(configurationReader.getfMetaBroker()).thenReturn(dmaapKafkaMetaBroker);
        when(configurationReader.getfRateLimiter()).thenReturn(limiter);
        when(configurationReader.getfMetrics()).thenReturn(metrics);
        when(dmaapKafkaMetaBroker.getTopic(topicName)).thenReturn(createdTopic);
        when(configurationReader.getfConsumerFactory()).thenReturn(factory);
        when(configurationReader.getfPublisher()).thenReturn(publisher);
    }

    private void verifyInvocationOrderForSuccessCase(String topicName, String consumerGroup, String clientId,
        ArgumentCaptor<CambriaOutboundEventStream> osWriter) throws Exception {

        InOrder inOrder = Mockito.inOrder(configurationReader, factory, metrics, limiter, consumer, eventsService);
        inOrder.verify(configurationReader).getfMetrics();
        inOrder.verify(configurationReader).getfRateLimiter();
        inOrder.verify(limiter).onCall(eq(topicName), eq(consumerGroup), eq(clientId), anyString());
        inOrder.verify(factory).getConsumerFor(eq(topicName), eq(consumerGroup), eq(clientId), anyInt(), anyString());
        inOrder.verify(eventsService).respondOkWithStream(eq(dMaapContext), osWriter.capture());
        inOrder.verify(consumer).commitOffsets();
        inOrder.verify(metrics).consumeTick(anyInt());
        inOrder.verify(limiter).onSend(eq(topicName), eq(consumerGroup), eq(clientId), anyLong());
        inOrder.verify(consumer).close();
        inOrder.verifyNoMoreInteractions();
    }

    @Test
    public void pushEvents_shouldFail_whenRemoteAddressIsBlacklisted() throws Exception {
        String remoteIp = "10.132.64.112";
        request.setRemoteAddr(remoteIp);
        when(configurationReader.getfIpBlackList()).thenReturn(blacklist);
        when(blacklist.contains(anyString())).thenReturn(true);

        thrown.expect(CambriaApiException.class);
        thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_FORBIDDEN)));

        eventsService.pushEvents(dMaapContext, "testTopic", iStream, "3", "12:00:00");
    }


  

    @Test
    public void pushEvents_shouldFailDmaapAuthorization_whenTopicOwnerIsSet_andUserHasNoWritePermissionToTopic()
        throws Exception {
        //given
        String topicName = "someSimpleTopicName";

        HttpServletRequest permittedRequest = mock(HttpServletRequest.class);
        when(permittedRequest.getHeaders(anyString())).thenReturn(Collections.<String>emptyEnumeration());
        dMaapContext.setRequest(permittedRequest);
        givenConfiguredWithMocks(topicName);
        when(createdTopic.getOwner()).thenReturn("SimpleTopicOwner");
        when(dmaaPAuthenticator.authenticate(dMaapContext)).thenReturn(nsaSimpleApiKey);
        doThrow(new AccessDeniedException("userName")).when(createdTopic).checkUserWrite(nsaSimpleApiKey);

        thrown.expect(AccessDeniedException.class);

        //when
        eventsService.pushEvents(dMaapContext, topicName, iStream, "5", "13:00:00");

        //then
        verify(createdTopic).checkUserWrite(nsaSimpleApiKey);
        verify(eventsService, never()).respondOkWithStream(eq(dMaapContext), any(CambriaOutboundEventStream.class));
        verify(permittedRequest, never()).isUserInRole(anyString());
    }

    @Test
    public void pushEvents_shouldFailOnAafAuthorization_whenCadiIsEnabled_topicNameEnforced_andUserHasNoPermission()
        throws Exception {
        //given
        String topicPrefix = "org.onap.aaf.enforced";
        String topicName = topicPrefix + ".topicName";
        String permission = "org.onap.dmaap.mr.topic|:topic." + topicName + "|pub";
        HttpServletRequest deniedRequest = mock(HttpServletRequest.class);
        when(deniedRequest.getHeaders(anyString())).thenReturn(Collections.<String>emptyEnumeration());
        when(deniedRequest.isUserInRole(permission)).thenReturn(false);
        when(configurationReader.getfMetaBroker()).thenReturn(dmaapKafkaMetaBroker);
        when(dmaapKafkaMetaBroker.getTopic(topicName)).thenReturn(createdTopic);
        when(eventsService.getPropertyFromAJSCmap("enforced.topic.name.AAF")).thenReturn(topicPrefix);
        when(eventsService.isCadiEnabled()).thenReturn(true);
        dMaapContext.setRequest(deniedRequest);

        thrown.expect(DMaaPAccessDeniedException.class);
        thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_UNAUTHORIZED)));

        //when
        eventsService.pushEvents(dMaapContext, topicName, iStream, "5", "13:00:00");

        //then
        verify(deniedRequest).isUserInRole(permission);
    }


    @Test
    public void pushEvents_shouldPublishMessagesWithoutTransaction() throws Exception {
        //given
        String topicName = "topicWithoutTransaction";
        givenConfiguredWithMocks(topicName);
        doNothing().when(eventsService).respondOk(eq(dMaapContext), any(JSONObject.class));

        //when
        eventsService.pushEvents(dMaapContext, topicName, iStream, "5", "13:00:00");

        //then
        verify(publisher).sendBatchMessageNew(eq(topicName), Mockito.<ArrayList<ProducerRecord<String, String>>>any());
        ArgumentCaptor<JSONObject> captor = ArgumentCaptor.forClass(JSONObject.class);
        verify(eventsService).respondOk(eq(dMaapContext), captor.capture());
        assertEquals(1, captor.getValue().getLong("count"));
    }

    @Test
    public void pushEvents_shouldHandlePublisherError_whenPushWithoutTransaction() throws Exception {
        //given
        String topicName = "topicWithoutTransaction";
        givenConfiguredWithMocks(topicName);
        doThrow(new IOException()).when(publisher)
            .sendBatchMessageNew(eq(topicName), Mockito.<ArrayList<ProducerRecord<String, String>>>any());

        thrown.expect(CambriaApiException.class);
        thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_NOT_FOUND)));

        //when
        eventsService.pushEvents(dMaapContext, topicName, iStream, "5", "13:00:00");

        //then
        verify(publisher).sendBatchMessageNew(eq(topicName), Mockito.<ArrayList<ProducerRecord<String, String>>>any());
        verify(eventsService, never()).respondOk(any(DMaaPContext.class), any(JSONObject.class));
    }


    @Test
    public void pushEvents_shouldPublishMessagesWithTransaction() throws Exception {
        //given
        String topicPrefix = "org.onap.dmaap.mr";
        String topicName = topicPrefix + ".topicWithTransaction";
        givenConfiguredWithMocks(topicName);
        when(eventsService.getPropertyFromAJSCmap("enforced.topic.name.AAF")).thenReturn(topicPrefix);
        when(eventsService.isCadiEnabled()).thenReturn(true);
        doNothing().when(eventsService).respondOk(eq(dMaapContext), any(JSONObject.class));

        request.addUserRole("org.onap.dmaap.mr.topic|:topic." + topicName + "|pub");

        //when
        eventsService.pushEvents(dMaapContext, topicName, iStream, "5", "13:00:00");

        //then
        verify(publisher).sendBatchMessageNew(eq(topicName), Mockito.<ArrayList<ProducerRecord<String, String>>>any());
        ArgumentCaptor<JSONObject> captor = ArgumentCaptor.forClass(JSONObject.class);
        verify(eventsService).respondOk(eq(dMaapContext), captor.capture());
        assertEquals(1, captor.getValue().getLong("count"));
        assertFalse(captor.getValue().getString("transactionId").isEmpty());
    }

    @Test
    public void pushEvents_shouldHandlePublisherError_whenPushWithTransaction() throws Exception {
        //given
        String topicPrefix = "org.onap.dmaap.mr";
        String topicName = topicPrefix + ".topicWithTransaction";
        givenConfiguredWithMocks(topicName);
        when(eventsService.getPropertyFromAJSCmap("enforced.topic.name.AAF")).thenReturn(topicPrefix);
        when(eventsService.isCadiEnabled()).thenReturn(true);
        doNothing().when(eventsService).respondOk(eq(dMaapContext), any(JSONObject.class));
        request.addUserRole("org.onap.dmaap.mr.topic|:topic." + topicName + "|pub");
        doThrow(new IOException()).when(publisher)
            .sendBatchMessageNew(eq(topicName), Mockito.<ArrayList<ProducerRecord<String, String>>>any());

        thrown.expect(CambriaApiException.class);
        thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_NOT_FOUND)));

        //when
        eventsService.pushEvents(dMaapContext, topicName, iStream, "5", "13:00:00");

        //then
        verify(publisher).sendBatchMessageNew(eq(topicName), Mockito.<ArrayList<ProducerRecord<String, String>>>any());
        verify(eventsService, never()).respondOk(any(DMaaPContext.class), any(JSONObject.class));
    }

    @Test
    public void pushEvents_shouldNotPerformAnyAuthorization_whenPublishToMetricTopic() throws Exception {
        //given
        HttpServletRequest permittedRequest = mock(HttpServletRequest.class);
        when(permittedRequest.getHeaders(anyString())).thenReturn(Collections.<String>emptyEnumeration());
        dMaapContext.setRequest(permittedRequest);
        String metricsTopicName = "msgrtr.apinode.metrics.dmaap";
        givenConfiguredWithMocks(metricsTopicName);
        doNothing().when(eventsService).respondOk(eq(dMaapContext), any(JSONObject.class));

        //when
        eventsService.pushEvents(dMaapContext, metricsTopicName, iStream, "5", "13:00:00");

        //then
        ArgumentCaptor<JSONObject> captor = ArgumentCaptor.forClass(JSONObject.class);
        verify(publisher)
            .sendBatchMessageNew(eq(metricsTopicName), Mockito.<ArrayList<ProducerRecord<String, String>>>any());
        verify(eventsService).respondOk(eq(dMaapContext), captor.capture());
        verify(permittedRequest, never()).isUserInRole(anyString());
        verify(createdTopic, never()).checkUserWrite(any(NsaSimpleApiKey.class));
        assertEquals(1, captor.getValue().getLong("count"));
    }

    @Test
    public void pushEvents_shouldNotPerformAnyAuthorization_whenTopicHasNoOwner() throws Exception {
        //given
        HttpServletRequest permittedRequest = mock(HttpServletRequest.class);
        when(permittedRequest.getHeaders(anyString())).thenReturn(Collections.<String>emptyEnumeration());
        dMaapContext.setRequest(permittedRequest);
        String topicName = "notEnforcedAafTopic";
        givenConfiguredWithMocks(topicName);
        doNothing().when(eventsService).respondOk(eq(dMaapContext), any(JSONObject.class));
        when(createdTopic.getOwner()).thenReturn(null);

        //when
        eventsService.pushEvents(dMaapContext, topicName, iStream, "5", "13:00:00");

        //then
        ArgumentCaptor<JSONObject> captor = ArgumentCaptor.forClass(JSONObject.class);
        verify(publisher).sendBatchMessageNew(eq(topicName), Mockito.<ArrayList<ProducerRecord<String, String>>>any());
        verify(eventsService).respondOk(eq(dMaapContext), captor.capture());
        verify(permittedRequest, never()).isUserInRole(anyString());
        verify(createdTopic, never()).checkUserWrite(any(NsaSimpleApiKey.class));
        assertEquals(1, captor.getValue().getLong("count"));
    }

}