DMAAP-MR - Merge MR repos
[dmaap/messagerouter/messageservice.git] / src / test / java / org / onap / dmaap / dmf / mr / service / impl / EventsServiceImplTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.dmaap.dmf.mr.service.impl;
22
23 import static org.hamcrest.CoreMatchers.containsString;
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertFalse;
26 import static org.junit.Assert.assertTrue;
27 import static org.mockito.Matchers.any;
28 import static org.mockito.Matchers.anyInt;
29 import static org.mockito.Matchers.anyLong;
30 import static org.mockito.Matchers.anyString;
31 import static org.mockito.Matchers.eq;
32 import static org.mockito.Mockito.doNothing;
33 import static org.mockito.Mockito.doReturn;
34 import static org.mockito.Mockito.doThrow;
35 import static org.mockito.Mockito.mock;
36 import static org.mockito.Mockito.never;
37 import static org.mockito.Mockito.verify;
38 import static org.mockito.Mockito.when;
39
40 import com.att.nsa.limits.Blacklist;
41 import com.att.nsa.security.ReadWriteSecuredResource.AccessDeniedException;
42 import com.att.nsa.security.db.simple.NsaSimpleApiKey;
43 import java.io.ByteArrayInputStream;
44 import java.io.IOException;
45 import java.io.InputStream;
46 import java.util.ArrayList;
47 import java.util.Collections;
48 import java.util.ConcurrentModificationException;
49 import javax.servlet.http.HttpServletRequest;
50 import joptsimple.internal.Strings;
51 import org.apache.http.HttpStatus;
52 import org.apache.kafka.clients.producer.ProducerRecord;
53 import org.json.JSONObject;
54 import org.junit.Before;
55 import org.junit.Rule;
56 import org.junit.Test;
57 import org.junit.rules.ExpectedException;
58 import org.junit.runner.RunWith;
59 import org.mockito.ArgumentCaptor;
60 import org.mockito.InOrder;
61 import org.mockito.Mock;
62 import org.mockito.Mockito;
63 import org.mockito.MockitoAnnotations;
64 import org.mockito.Spy;
65 import org.mockito.runners.MockitoJUnitRunner;
66 import org.onap.dmaap.dmf.mr.CambriaApiException;
67 import org.onap.dmaap.dmf.mr.backends.Consumer;
68 import org.onap.dmaap.dmf.mr.backends.ConsumerFactory;
69 import org.onap.dmaap.dmf.mr.backends.ConsumerFactory.UnavailableException;
70 import org.onap.dmaap.dmf.mr.backends.MetricsSet;
71 import org.onap.dmaap.dmf.mr.backends.Publisher;
72 import org.onap.dmaap.dmf.mr.beans.DMaaPCambriaLimiter;
73 import org.onap.dmaap.dmf.mr.beans.DMaaPContext;
74 import org.onap.dmaap.dmf.mr.beans.DMaaPKafkaMetaBroker;
75 import org.onap.dmaap.dmf.mr.exception.DMaaPAccessDeniedException;
76 import org.onap.dmaap.dmf.mr.exception.DMaaPErrorMessages;
77 import org.onap.dmaap.dmf.mr.metabroker.Topic;
78 import org.onap.dmaap.dmf.mr.resources.CambriaOutboundEventStream;
79 import org.onap.dmaap.dmf.mr.security.DMaaPAuthenticator;
80 import org.onap.dmaap.dmf.mr.utils.ConfigurationReader;
81 import org.springframework.mock.web.MockHttpServletRequest;
82 import org.springframework.mock.web.MockHttpServletResponse;
83
84 @RunWith(MockitoJUnitRunner.class)
85 public class EventsServiceImplTest {
86
87     private InputStream iStream = null;
88     private DMaaPContext dMaapContext = new DMaaPContext();
89     private DMaaPErrorMessages pErrorMessages = new DMaaPErrorMessages();
90     @Mock
91     private ConfigurationReader configurationReader;
92     @Mock
93     private Blacklist blacklist;
94     @Mock
95     private DMaaPAuthenticator<NsaSimpleApiKey> dmaaPAuthenticator;
96     @Mock
97     private NsaSimpleApiKey nsaSimpleApiKey;
98     @Mock
99     private DMaaPKafkaMetaBroker dmaapKafkaMetaBroker;
100     @Mock
101     private Topic createdTopic;
102     @Mock
103     private ConsumerFactory factory;
104     @Mock
105     private Consumer consumer;
106     @Mock
107     private Publisher publisher;
108     @Mock
109     private DMaaPCambriaLimiter limiter;
110     @Mock
111     private MetricsSet metrics;
112     @Spy
113     private EventsServiceImpl eventsService;
114
115
116     @Rule
117     public ExpectedException thrown = ExpectedException.none();
118
119     private MockHttpServletRequest request;
120
121
122     @Before
123     public void setUp() throws Exception {
124         MockitoAnnotations.initMocks(this);
125         String source = "source of my InputStream";
126         iStream = new ByteArrayInputStream(source.getBytes("UTF-8"));
127
128         request = new MockHttpServletRequest();
129         MockHttpServletResponse response = new MockHttpServletResponse();
130         dMaapContext.setRequest(request);
131         dMaapContext.setResponse(response);
132         when(blacklist.contains(anyString())).thenReturn(false);
133         when(configurationReader.getfIpBlackList()).thenReturn(blacklist);
134         when(configurationReader.getfSecurityManager()).thenReturn(dmaaPAuthenticator);
135         dMaapContext.setConfigReader(configurationReader);
136         eventsService.setErrorMessages(pErrorMessages);
137         doReturn("100").when(eventsService).getPropertyFromAJSCmap("timeout");
138     }
139
140     @Test
141     public void getEvents_shouldFailOnAafAuthorization() throws Exception {
142         String topicPrefix = "org.onap.aaf.enforced";
143         String topicName = topicPrefix + ".topicName";
144         when(configurationReader.getfMetaBroker()).thenReturn(dmaapKafkaMetaBroker);
145         when(dmaapKafkaMetaBroker.getTopic(topicName)).thenReturn(createdTopic);
146         when(eventsService.getPropertyFromAJSCmap("enforced.topic.name.AAF")).thenReturn(topicPrefix);
147         when(eventsService.isCadiEnabled()).thenReturn(true);
148
149         thrown.expect(DMaaPAccessDeniedException.class);
150         thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_UNAUTHORIZED)));
151
152         eventsService.getEvents(dMaapContext, topicName, "CG1", "23");
153     }
154
155     @Test
156     public void getEvents_shouldFail_whenRemoteAddressIsBlacklisted() throws Exception {
157         String remoteIp = "10.154.17.115";
158         request.setRemoteAddr(remoteIp);
159         when(blacklist.contains(remoteIp)).thenReturn(true);
160         when(configurationReader.getfIpBlackList()).thenReturn(blacklist);
161
162         thrown.expect(CambriaApiException.class);
163         thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_FORBIDDEN)));
164
165         eventsService.getEvents(dMaapContext, "testTopic", "CG1", "23");
166     }
167
168     @Test
169     public void getEvents_shouldFail_whenRequestedTopicNotExists() throws Exception {
170         when(configurationReader.getfMetaBroker()).thenReturn(dmaapKafkaMetaBroker);
171         when(dmaapKafkaMetaBroker.getTopic("testTopic")).thenReturn(null);
172
173         thrown.expect(CambriaApiException.class);
174         thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_NOT_FOUND)));
175
176         eventsService.getEvents(dMaapContext, "testTopic", "CG1", "23");
177     }
178
179     @Test
180     public void getEvents_shouldFail_whenConsumerLockCannotBeAcquired() throws Exception {
181         //given
182         String topicName = "testTopic345";
183         String consumerGroup = "CG5";
184         String clientId = "13";
185         when(configurationReader.getfMetaBroker()).thenReturn(dmaapKafkaMetaBroker);
186         when(configurationReader.getfRateLimiter()).thenReturn(limiter);
187         when(dmaapKafkaMetaBroker.getTopic(topicName)).thenReturn(createdTopic);
188         when(configurationReader.getfConsumerFactory()).thenReturn(factory);
189         doThrow(new UnavailableException("Could not acquire consumer lock")).when(factory)
190             .getConsumerFor(eq(topicName), eq(consumerGroup), eq(clientId), anyInt(), anyString());
191
192         thrown.expect(CambriaApiException.class);
193         thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_SERVICE_UNAVAILABLE)));
194
195         //when
196         eventsService.getEvents(dMaapContext, topicName, consumerGroup, clientId);
197
198         //then
199         verify(factory).getConsumerFor(eq(topicName), eq(consumerGroup), eq(clientId), anyInt(), anyString());
200
201     }
202
203     @Test
204     public void getEvents_shouldFail_whenBrokerServicesAreUnavailable() throws Exception {
205         String topicName = "testTopic";
206         String consumerGroup = "CG1";
207         String clientId = "23";
208         when(configurationReader.getfMetaBroker()).thenReturn(dmaapKafkaMetaBroker);
209         when(dmaapKafkaMetaBroker.getTopic(topicName)).thenReturn(createdTopic);
210         when(configurationReader.getfConsumerFactory()).thenReturn(factory);
211
212         givenUserAuthorizedWithAAF(request, topicName, "sub");
213
214         thrown.expect(CambriaApiException.class);
215         thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_SERVICE_UNAVAILABLE)));
216
217         //when
218         eventsService.getEvents(dMaapContext, topicName, consumerGroup, clientId);
219
220         //then
221         verify(factory).destroyConsumer(topicName, consumerGroup, clientId);
222     }
223
224     private void givenUserAuthorizedWithAAF(MockHttpServletRequest request, String topicName, String operation) {
225         String permission = "org.onap.dmaap.mr.topic|:topic." + topicName + "|" + operation;
226         request.addUserRole(permission);
227     }
228
229     @Test
230     public void getEvents_shouldHandleConcurrentModificationError() throws Exception {
231         String testTopic = "testTopic";
232         when(configurationReader.getfMetaBroker()).thenReturn(dmaapKafkaMetaBroker);
233         when(dmaapKafkaMetaBroker.getTopic(testTopic)).thenReturn(createdTopic);
234         when(configurationReader.getfRateLimiter()).thenThrow(new ConcurrentModificationException("Error occurred"));
235         givenUserAuthorizedWithAAF(request, testTopic, "sub");
236
237         thrown.expect(CambriaApiException.class);
238         thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_CONFLICT)));
239
240         eventsService.getEvents(dMaapContext, "testTopic", "CG1", "23");
241     }
242
243     @Test
244     public void getEvents_shouldNotAuthorizeClient_whenSubscribingToMetricsTopic() throws Exception {
245         //given
246         HttpServletRequest permittedRequest = mock(HttpServletRequest.class);
247         when(permittedRequest.getHeaders(anyString())).thenReturn(Collections.<String>emptyEnumeration());
248         dMaapContext.setRequest(permittedRequest);
249         String metricsTopicName = "msgrtr.apinode.metrics.dmaap";
250         String consumerGroup = "CG5";
251         String clientId = "7";
252         givenConfiguredWithMocks(metricsTopicName);
253         when(factory.getConsumerFor(eq(metricsTopicName), eq(consumerGroup), eq(clientId), anyInt(), any()))
254             .thenReturn(consumer);
255         doNothing().when(eventsService).respondOkWithStream(eq(dMaapContext), any(CambriaOutboundEventStream.class));
256
257         //when
258         eventsService.getEvents(dMaapContext, metricsTopicName, consumerGroup, clientId);
259
260         //then
261         verify(eventsService).respondOkWithStream(eq(dMaapContext), any(CambriaOutboundEventStream.class));
262         verify(dmaaPAuthenticator, never()).authenticate(dMaapContext);
263         verify(permittedRequest, never()).isUserInRole(anyString());
264     }
265
266     @Test
267     public void getEvents_shouldNotAuthorizeClient_whenTopicNoteEnforcedWithAaf_andTopicHasNoOwnerSet()
268         throws Exception {
269         //given
270         String topicName = "someSimpleTopicName";
271         String consumerGroup = "CG5";
272         String clientId = "7";
273         HttpServletRequest permittedRequest = mock(HttpServletRequest.class);
274         when(permittedRequest.getHeaders(anyString())).thenReturn(Collections.<String>emptyEnumeration());
275         dMaapContext.setRequest(permittedRequest);
276         givenConfiguredWithMocks(topicName);
277         when(factory.getConsumerFor(eq(topicName), eq(consumerGroup), eq(clientId), anyInt(), any()))
278             .thenReturn(consumer);
279         doNothing().when(eventsService).respondOkWithStream(eq(dMaapContext), any(CambriaOutboundEventStream.class));
280         when(createdTopic.getOwner()).thenReturn(Strings.EMPTY);
281
282         //when
283         eventsService.getEvents(dMaapContext, topicName, consumerGroup, clientId);
284
285         //then
286         verify(eventsService).respondOkWithStream(eq(dMaapContext), any(CambriaOutboundEventStream.class));
287         verify(dmaaPAuthenticator, never()).authenticate(dMaapContext);
288         verify(permittedRequest, never()).isUserInRole(anyString());
289     }
290
291     @Test
292     public void getEvents_shouldFailDmaapAuthorization_whenTopicOwnerIsSet_andUserHasNoReadPermissionToTopic()
293         throws Exception {
294         //given
295         String topicName = "someSimpleTopicName";
296         String consumerGroup = "CG5";
297         String clientId = "7";
298         HttpServletRequest permittedRequest = mock(HttpServletRequest.class);
299         when(permittedRequest.getHeaders(anyString())).thenReturn(Collections.<String>emptyEnumeration());
300         dMaapContext.setRequest(permittedRequest);
301         givenConfiguredWithMocks(topicName);
302         when(createdTopic.getOwner()).thenReturn("SimpleTopicOwner");
303         when(dmaaPAuthenticator.authenticate(dMaapContext)).thenReturn(nsaSimpleApiKey);
304         doThrow(new AccessDeniedException("userName")).when(createdTopic).checkUserRead(nsaSimpleApiKey);
305
306         thrown.expect(AccessDeniedException.class);
307
308         //when
309         eventsService.getEvents(dMaapContext, topicName, consumerGroup, clientId);
310
311         //then
312         verify(createdTopic).checkUserRead(nsaSimpleApiKey);
313         verify(eventsService, never()).respondOkWithStream(eq(dMaapContext), any(CambriaOutboundEventStream.class));
314         verify(permittedRequest, never()).isUserInRole(anyString());
315     }
316
317
318     @Test
319     public void getEvents_shouldSuccessfullyRegisterConsumerToEventsStream_withAafAuthorization() throws Exception {
320         //given
321         String topicName = "testTopic";
322         String consumerGroup = "CG2";
323         String clientId = "6";
324         String messageLimit = "10";
325         String timeout = "25";
326         String meta = "yes";
327         String pretty = "on";
328         String cacheEnabled = "false";
329
330         givenConfiguredWithMocks(topicName);
331         givenConfiguredWithProperties(messageLimit, timeout, meta, pretty, cacheEnabled);
332         when(factory.getConsumerFor(eq(topicName), eq(consumerGroup), eq(clientId), anyInt(), anyString()))
333             .thenReturn(consumer);
334         givenUserAuthorizedWithAAF(request, topicName, "sub");
335
336         //when
337         eventsService.getEvents(dMaapContext, topicName, consumerGroup, clientId);
338
339         //then
340         ArgumentCaptor<CambriaOutboundEventStream> osWriter = ArgumentCaptor.forClass(CambriaOutboundEventStream.class);
341         verifyInvocationOrderForSuccessCase(topicName, consumerGroup, clientId, osWriter);
342         assertEventStreamProperties(osWriter.getValue(), messageLimit, timeout);
343     }
344
345     private void assertEventStreamProperties(CambriaOutboundEventStream stream, String messageLimit, String timeout) {
346         assertEquals(Integer.valueOf(messageLimit).intValue(), stream.getfLimit());
347         assertEquals(Integer.valueOf(timeout).intValue(), stream.getfTimeoutMs());
348         assertTrue(stream.isfWithMeta());
349         assertTrue(stream.isfPretty());
350     }
351
352     private void givenConfiguredWithProperties(String messageLimit, String timeout, String meta, String pretty,
353                                                String cacheEnabled) {
354         when(eventsService.getPropertyFromAJSCmap("meta")).thenReturn(meta);
355         when(eventsService.getPropertyFromAJSCmap("pretty")).thenReturn(pretty);
356         when(eventsService.getPropertyFromAJSCmap(ConsumerFactory.kSetting_EnableCache)).thenReturn(cacheEnabled);
357         request.addParameter("timeout", timeout);
358         request.addParameter("limit", messageLimit);
359     }
360
361     private void givenConfiguredWithMocks(String topicName) throws Exception {
362         when(configurationReader.getfMetaBroker()).thenReturn(dmaapKafkaMetaBroker);
363         when(configurationReader.getfRateLimiter()).thenReturn(limiter);
364         when(configurationReader.getfMetrics()).thenReturn(metrics);
365         when(dmaapKafkaMetaBroker.getTopic(topicName)).thenReturn(createdTopic);
366         when(configurationReader.getfConsumerFactory()).thenReturn(factory);
367         when(configurationReader.getfPublisher()).thenReturn(publisher);
368     }
369
370     private void verifyInvocationOrderForSuccessCase(String topicName, String consumerGroup, String clientId,
371                                                      ArgumentCaptor<CambriaOutboundEventStream> osWriter) throws Exception {
372
373         InOrder inOrder = Mockito.inOrder(configurationReader, factory, metrics, limiter, consumer, eventsService);
374         inOrder.verify(configurationReader).getfMetrics();
375         inOrder.verify(configurationReader).getfRateLimiter();
376         inOrder.verify(limiter).onCall(eq(topicName), eq(consumerGroup), eq(clientId), anyString());
377         inOrder.verify(factory).getConsumerFor(eq(topicName), eq(consumerGroup), eq(clientId), anyInt(), anyString());
378         inOrder.verify(eventsService).respondOkWithStream(eq(dMaapContext), osWriter.capture());
379         inOrder.verify(consumer).commitOffsets();
380         inOrder.verify(metrics).consumeTick(anyInt());
381         inOrder.verify(limiter).onSend(eq(topicName), eq(consumerGroup), eq(clientId), anyLong());
382         inOrder.verify(consumer).close();
383         inOrder.verifyNoMoreInteractions();
384     }
385
386     @Test
387     public void pushEvents_shouldFail_whenRemoteAddressIsBlacklisted() throws Exception {
388         String remoteIp = "10.132.64.112";
389         request.setRemoteAddr(remoteIp);
390         when(configurationReader.getfIpBlackList()).thenReturn(blacklist);
391         when(blacklist.contains(anyString())).thenReturn(true);
392
393         thrown.expect(CambriaApiException.class);
394         thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_FORBIDDEN)));
395
396         eventsService.pushEvents(dMaapContext, "testTopic", iStream, "3", "12:00:00");
397     }
398
399
400
401
402     @Test
403     public void pushEvents_shouldFailDmaapAuthorization_whenTopicOwnerIsSet_andUserHasNoWritePermissionToTopic()
404         throws Exception {
405         //given
406         String topicName = "someSimpleTopicName";
407
408         HttpServletRequest permittedRequest = mock(HttpServletRequest.class);
409         when(permittedRequest.getHeaders(anyString())).thenReturn(Collections.<String>emptyEnumeration());
410         dMaapContext.setRequest(permittedRequest);
411         givenConfiguredWithMocks(topicName);
412         when(createdTopic.getOwner()).thenReturn("SimpleTopicOwner");
413         when(dmaaPAuthenticator.authenticate(dMaapContext)).thenReturn(nsaSimpleApiKey);
414         doThrow(new AccessDeniedException("userName")).when(createdTopic).checkUserWrite(nsaSimpleApiKey);
415
416         thrown.expect(AccessDeniedException.class);
417
418         //when
419         eventsService.pushEvents(dMaapContext, topicName, iStream, "5", "13:00:00");
420
421         //then
422         verify(createdTopic).checkUserWrite(nsaSimpleApiKey);
423         verify(eventsService, never()).respondOkWithStream(eq(dMaapContext), any(CambriaOutboundEventStream.class));
424         verify(permittedRequest, never()).isUserInRole(anyString());
425     }
426
427     @Test
428     public void pushEvents_shouldFailOnAafAuthorization_whenCadiIsEnabled_topicNameEnforced_andUserHasNoPermission()
429         throws Exception {
430         //given
431         String topicPrefix = "org.onap.aaf.enforced";
432         String topicName = topicPrefix + ".topicName";
433         String permission = "org.onap.dmaap.mr.topic|:topic." + topicName + "|pub";
434         HttpServletRequest deniedRequest = mock(HttpServletRequest.class);
435         when(deniedRequest.getHeaders(anyString())).thenReturn(Collections.<String>emptyEnumeration());
436         when(configurationReader.getfMetaBroker()).thenReturn(dmaapKafkaMetaBroker);
437         when(dmaapKafkaMetaBroker.getTopic(topicName)).thenReturn(createdTopic);
438         when(eventsService.getPropertyFromAJSCmap("enforced.topic.name.AAF")).thenReturn(topicPrefix);
439         when(eventsService.isCadiEnabled()).thenReturn(true);
440         dMaapContext.setRequest(deniedRequest);
441
442         thrown.expect(DMaaPAccessDeniedException.class);
443         thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_UNAUTHORIZED)));
444
445         //when
446         eventsService.pushEvents(dMaapContext, topicName, iStream, "5", "13:00:00");
447
448         //then
449         verify(deniedRequest).isUserInRole(permission);
450     }
451
452
453     @Test
454     public void pushEvents_shouldPublishMessagesWithoutTransaction() throws Exception {
455         //given
456         String topicName = "topicWithoutTransaction";
457         givenConfiguredWithMocks(topicName);
458         doNothing().when(eventsService).respondOk(eq(dMaapContext), any(JSONObject.class));
459
460         //when
461         eventsService.pushEvents(dMaapContext, topicName, iStream, "5", "13:00:00");
462
463         //then
464         verify(publisher).sendBatchMessageNew(eq(topicName), Mockito.<ArrayList<ProducerRecord<String, String>>>any());
465         ArgumentCaptor<JSONObject> captor = ArgumentCaptor.forClass(JSONObject.class);
466         verify(eventsService).respondOk(eq(dMaapContext), captor.capture());
467         assertEquals(1, captor.getValue().getLong("count"));
468     }
469
470     @Test
471     public void pushEvents_shouldHandlePublisherError_whenPushWithoutTransaction() throws Exception {
472         //given
473         String topicName = "topicWithoutTransaction";
474         givenConfiguredWithMocks(topicName);
475         doThrow(new IOException()).when(publisher)
476             .sendBatchMessageNew(eq(topicName), Mockito.<ArrayList<ProducerRecord<String, String>>>any());
477
478         thrown.expect(CambriaApiException.class);
479         thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_NOT_FOUND)));
480
481         //when
482         eventsService.pushEvents(dMaapContext, topicName, iStream, "5", "13:00:00");
483
484         //then
485         verify(publisher).sendBatchMessageNew(eq(topicName), Mockito.<ArrayList<ProducerRecord<String, String>>>any());
486         verify(eventsService, never()).respondOk(any(DMaaPContext.class), any(JSONObject.class));
487     }
488
489
490     @Test
491     public void pushEvents_shouldPublishMessagesWithTransaction() throws Exception {
492         //given
493         String topicPrefix = "org.onap.dmaap.mr";
494         String topicName = topicPrefix + ".topicWithTransaction";
495         givenConfiguredWithMocks(topicName);
496         when(eventsService.getPropertyFromAJSCmap("enforced.topic.name.AAF")).thenReturn(topicPrefix);
497         when(eventsService.isCadiEnabled()).thenReturn(true);
498         doNothing().when(eventsService).respondOk(eq(dMaapContext), any(JSONObject.class));
499
500         request.addUserRole("org.onap.dmaap.mr.topic|:topic." + topicName + "|pub");
501
502         //when
503         eventsService.pushEvents(dMaapContext, topicName, iStream, "5", "13:00:00");
504
505         //then
506         verify(publisher).sendBatchMessageNew(eq(topicName), Mockito.<ArrayList<ProducerRecord<String, String>>>any());
507         ArgumentCaptor<JSONObject> captor = ArgumentCaptor.forClass(JSONObject.class);
508         verify(eventsService).respondOk(eq(dMaapContext), captor.capture());
509         assertEquals(1, captor.getValue().getLong("count"));
510         assertFalse(captor.getValue().getString("transactionId").isEmpty());
511     }
512
513     @Test
514     public void pushEvents_shouldHandlePublisherError_whenPushWithTransaction() throws Exception {
515         //given
516         String topicPrefix = "org.onap.dmaap.mr";
517         String topicName = topicPrefix + ".topicWithTransaction";
518         givenConfiguredWithMocks(topicName);
519         when(eventsService.getPropertyFromAJSCmap("enforced.topic.name.AAF")).thenReturn(topicPrefix);
520         when(eventsService.isCadiEnabled()).thenReturn(true);
521         request.addUserRole("org.onap.dmaap.mr.topic|:topic." + topicName + "|pub");
522         doThrow(new IOException()).when(publisher)
523             .sendBatchMessageNew(eq(topicName), Mockito.<ArrayList<ProducerRecord<String, String>>>any());
524
525         thrown.expect(CambriaApiException.class);
526         thrown.expectMessage(containsString(String.valueOf(HttpStatus.SC_NOT_FOUND)));
527
528         //when
529         eventsService.pushEvents(dMaapContext, topicName, iStream, "5", "13:00:00");
530
531         //then
532         verify(publisher).sendBatchMessageNew(eq(topicName), Mockito.<ArrayList<ProducerRecord<String, String>>>any());
533         verify(eventsService, never()).respondOk(any(DMaaPContext.class), any(JSONObject.class));
534     }
535
536     @Test
537     public void pushEvents_shouldNotPerformAnyAuthorization_whenPublishToMetricTopic() throws Exception {
538         //given
539         HttpServletRequest permittedRequest = mock(HttpServletRequest.class);
540         when(permittedRequest.getHeaders(anyString())).thenReturn(Collections.<String>emptyEnumeration());
541         dMaapContext.setRequest(permittedRequest);
542         String metricsTopicName = "msgrtr.apinode.metrics.dmaap";
543         givenConfiguredWithMocks(metricsTopicName);
544         doNothing().when(eventsService).respondOk(eq(dMaapContext), any(JSONObject.class));
545
546         //when
547         eventsService.pushEvents(dMaapContext, metricsTopicName, iStream, "5", "13:00:00");
548
549         //then
550         ArgumentCaptor<JSONObject> captor = ArgumentCaptor.forClass(JSONObject.class);
551         verify(publisher)
552             .sendBatchMessageNew(eq(metricsTopicName), Mockito.<ArrayList<ProducerRecord<String, String>>>any());
553         verify(eventsService).respondOk(eq(dMaapContext), captor.capture());
554         verify(permittedRequest, never()).isUserInRole(anyString());
555         verify(createdTopic, never()).checkUserWrite(any(NsaSimpleApiKey.class));
556         assertEquals(1, captor.getValue().getLong("count"));
557     }
558
559     @Test
560     public void pushEvents_shouldNotPerformAnyAuthorization_whenTopicHasNoOwner() throws Exception {
561         //given
562         HttpServletRequest permittedRequest = mock(HttpServletRequest.class);
563         when(permittedRequest.getHeaders(anyString())).thenReturn(Collections.<String>emptyEnumeration());
564         dMaapContext.setRequest(permittedRequest);
565         String topicName = "notEnforcedAafTopic";
566         givenConfiguredWithMocks(topicName);
567         doNothing().when(eventsService).respondOk(eq(dMaapContext), any(JSONObject.class));
568         when(createdTopic.getOwner()).thenReturn(null);
569
570         //when
571         eventsService.pushEvents(dMaapContext, topicName, iStream, "5", "13:00:00");
572
573         //then
574         ArgumentCaptor<JSONObject> captor = ArgumentCaptor.forClass(JSONObject.class);
575         verify(publisher).sendBatchMessageNew(eq(topicName), Mockito.<ArrayList<ProducerRecord<String, String>>>any());
576         verify(eventsService).respondOk(eq(dMaapContext), captor.capture());
577         verify(permittedRequest, never()).isUserInRole(anyString());
578         verify(createdTopic, never()).checkUserWrite(any(NsaSimpleApiKey.class));
579         assertEquals(1, captor.getValue().getLong("count"));
580     }
581
582 }