<commit_before>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
package io.joynr.messaging.mqtt;

import static io.joynr.messaging.mqtt.MqttMessagingSkeletonTestUtil.createTestMessage;
import static io.joynr.messaging.mqtt.MqttMessagingSkeletonTestUtil.createTestRequestMessage;
import static io.joynr.messaging.mqtt.MqttMessagingSkeletonTestUtil.failIfCalledAction;
import static io.joynr.messaging.mqtt.MqttMessagingSkeletonTestUtil.feedMqttSkeletonWithMessages;
import static io.joynr.messaging.mqtt.MqttMessagingSkeletonTestUtil.feedMqttSkeletonWithRequests;
import static io.joynr.messaging.mqtt.MqttMessagingSkeletonTestUtil.getExpectToBeCalledAction;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyMap;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.Arrays;
import java.util.HashSet;
import java.util.concurrent.Semaphore;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import io.joynr.exceptions.JoynrRuntimeException;
import io.joynr.messaging.JoynrMessageProcessor;
import io.joynr.messaging.NoOpRawMessagingPreprocessor;
import io.joynr.messaging.RawMessagingPreprocessor;
import io.joynr.messaging.mqtt.statusmetrics.MqttStatusReceiver;
import io.joynr.messaging.routing.MessageRouter;
import io.joynr.messaging.routing.ReplyToAddressRegistrar;
import joynr.ImmutableMessage;
import joynr.Message;

@RunWith(MockitoJUnitRunner.class)
public class MqttMessagingSkeletonTest {
    private final int maxIncomingMqttRequests = 20;
    private final String ownTopic = "testOwnTopic";

    private MqttMessagingSkeleton subject;

    private String ownGbid = "testOwnGbid";

    @Mock
    private MessageRouter messageRouter;

    @Mock
    private ReplyToAddressRegistrar replyToAddressRegistrar;

    @Mock
    private MqttClientFactory mqttClientFactory;

    @Mock
    private JoynrMqttClient mqttClientReceiver;
    @Mock
    private JoynrMqttClient mqttClientSender;

    @Mock
    private MqttTopicPrefixProvider mqttTopicPrefixProvider;

    @Mock
    private MqttStatusReceiver mqttStatusReceiver;

    @Before
    public void setup() {
        subject = new MqttMessagingSkeleton(ownTopic,
                                            maxIncomingMqttRequests,
                                            messageRouter,
                                            replyToAddressRegistrar,
                                            mqttClientFactory,
                                            mqttTopicPrefixProvider,
                                            new NoOpRawMessagingPreprocessor(),
                                            new HashSet<JoynrMessageProcessor>(),
                                            mqttStatusReceiver,
                                            ownGbid);
        when(mqttClientFactory.createReceiver(ownGbid)).thenReturn(mqttClientReceiver);
        when(mqttClientFactory.createSender(ownGbid)).thenReturn(mqttClientSender);
        subject.init();
    }

    @Test
    public void testSkeletonCreatesAndStartsSenderAndReceiverForItsOwnGbid() {
        verify(mqttClientFactory).createReceiver(ownGbid);
        verify(mqttClientFactory).createSender(ownGbid);

        verify(mqttClientReceiver).start();
        verify(mqttClientSender).start();
    }

    @Test
    public void testSkeletonSubscribesToOwnTopic() {
        verify(mqttClientReceiver).subscribe(ownTopic + "/#");
        verify(mqttClientSender, times(0)).subscribe(anyString());
    }

    @Test
    public void testSkeletonRegistersItselfAsMessageProcessedListener() {
        verify(messageRouter).registerMessageProcessedListener(eq(subject));
    }

    @Test
    public void testSkeletonRegistersItselfAsMessageListener() {
        verify(mqttClientReceiver).setMessageListener(subject);
        verify(mqttClientSender, times(0)).setMessageListener(any(IMqttMessagingSkeleton.class));
    }

    @Test
    public void testSubscribeToMulticastWithTopicPrefix() {
        final String expectedPrefix = "testMulticastPrefix";
        final String multicastId = "multicastId";
        when(mqttTopicPrefixProvider.getMulticastTopicPrefix()).thenReturn(expectedPrefix);

        subject.registerMulticastSubscription(multicastId);
        verify(mqttClientReceiver).subscribe(expectedPrefix + multicastId);

        subject.unregisterMulticastSubscription(multicastId);
        verify(mqttClientReceiver).unsubscribe(expectedPrefix + multicastId);
    }

    @Test
    public void testOnlySubscribeToMulticastIfNotAlreadySubscribed() {
        when(mqttTopicPrefixProvider.getMulticastTopicPrefix()).thenReturn("");
        String multicastId = "multicastId";

        subject.registerMulticastSubscription(multicastId);
        verify(mqttClientReceiver).subscribe(eq(multicastId));
        reset(mqttClientReceiver);

        subject.registerMulticastSubscription(multicastId);
        verify(mqttClientReceiver, never()).subscribe(anyString());
    }

    @Test
    public void testMultilevelWildcardTranslated() {
        when(mqttTopicPrefixProvider.getMulticastTopicPrefix()).thenReturn("");
        String multicastId = "one/two/*";

        subject.registerMulticastSubscription(multicastId);
        verify(mqttClientReceiver).subscribe(eq("one/two/#"));

        subject.unregisterMulticastSubscription(multicastId);
        verify(mqttClientReceiver).unsubscribe("one/two/#");
    }

    @SuppressWarnings("unchecked")
    @Test
    public void testMessageRouterIsCalled() throws Exception {
        RawMessagingPreprocessor preprocessor = mock(RawMessagingPreprocessor.class);
        when(preprocessor.process(any(byte[].class), anyMap())).then(returnsFirstArg());
        subject = new MqttMessagingSkeleton(ownTopic,
                                            maxIncomingMqttRequests,
                                            messageRouter,
                                            replyToAddressRegistrar,
                                            mqttClientFactory,
                                            mqttTopicPrefixProvider,
                                            preprocessor,
                                            new HashSet<JoynrMessageProcessor>(),
                                            mqttStatusReceiver,
                                            ownGbid);

        ImmutableMessage rqMessage = createTestRequestMessage();

        subject.transmit(rqMessage.getSerializedMessage(), failIfCalledAction);

        ArgumentCaptor<ImmutableMessage> captor = ArgumentCaptor.forClass(ImmutableMessage.class);
        verify(messageRouter).route(captor.capture());

        assertArrayEquals(rqMessage.getSerializedMessage(), captor.getValue().getSerializedMessage());
    }

    @Test
    public void testJoynrMessageProcessorIsCalled() throws Exception {
        JoynrMessageProcessor processorMock = mock(JoynrMessageProcessor.class);

        when(processorMock.processIncoming(any(ImmutableMessage.class))).then(returnsFirstArg());

        subject = new MqttMessagingSkeleton(ownTopic,
                                            maxIncomingMqttRequests,
                                            messageRouter,
                                            replyToAddressRegistrar,
                                            mqttClientFactory,
                                            mqttTopicPrefixProvider,
                                            new NoOpRawMessagingPreprocessor(),
                                            new HashSet<JoynrMessageProcessor>(Arrays.asList(processorMock)),
                                            mqttStatusReceiver,
                                            ownGbid);

        ImmutableMessage rqMessage = createTestRequestMessage();

        subject.transmit(rqMessage.getSerializedMessage(), failIfCalledAction);

        ArgumentCaptor<ImmutableMessage> argCaptor = ArgumentCaptor.forClass(ImmutableMessage.class);
        verify(processorMock).processIncoming(argCaptor.capture());

        Assert.assertArrayEquals(rqMessage.getSerializedMessage(), argCaptor.getValue().getSerializedMessage());
    }<commit_msg>[Java] Test MqttMessagingSkeleton calls the ReplyToAddressRegistrar<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
package io.joynr.messaging.mqtt;

import static io.joynr.messaging.mqtt.MqttMessagingSkeletonTestUtil.createTestMessage;
import static io.joynr.messaging.mqtt.MqttMessagingSkeletonTestUtil.createTestRequestMessage;
import static io.joynr.messaging.mqtt.MqttMessagingSkeletonTestUtil.failIfCalledAction;
import static io.joynr.messaging.mqtt.MqttMessagingSkeletonTestUtil.feedMqttSkeletonWithMessages;
import static io.joynr.messaging.mqtt.MqttMessagingSkeletonTestUtil.feedMqttSkeletonWithRequests;
import static io.joynr.messaging.mqtt.MqttMessagingSkeletonTestUtil.getExpectToBeCalledAction;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.Serializable;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.Semaphore;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import io.joynr.exceptions.JoynrRuntimeException;
import io.joynr.messaging.JoynrMessageProcessor;
import io.joynr.messaging.NoOpRawMessagingPreprocessor;
import io.joynr.messaging.RawMessagingPreprocessor;
import io.joynr.messaging.mqtt.statusmetrics.MqttStatusReceiver;
import io.joynr.messaging.routing.MessageRouter;
import io.joynr.messaging.routing.ReplyToAddressRegistrar;
import joynr.ImmutableMessage;
import joynr.Message;

@RunWith(MockitoJUnitRunner.class)
public class MqttMessagingSkeletonTest {
    private final int maxIncomingMqttRequests = 20;
    private final String ownTopic = "testOwnTopic";

    private MqttMessagingSkeleton subject;

    private String ownGbid = "testOwnGbid";

    @Mock
    private MessageRouter messageRouter;

    @Mock
    private ReplyToAddressRegistrar replyToAddressRegistrar;

    @Mock
    private MqttClientFactory mqttClientFactory;

    @Mock
    private JoynrMqttClient mqttClientReceiver;
    @Mock
    private JoynrMqttClient mqttClientSender;

    @Mock
    private MqttTopicPrefixProvider mqttTopicPrefixProvider;

    @Mock
    private MqttStatusReceiver mqttStatusReceiver;

    @Before
    public void setup() {
        subject = new MqttMessagingSkeleton(ownTopic,
                                            maxIncomingMqttRequests,
                                            messageRouter,
                                            replyToAddressRegistrar,
                                            mqttClientFactory,
                                            mqttTopicPrefixProvider,
                                            new NoOpRawMessagingPreprocessor(),
                                            new HashSet<JoynrMessageProcessor>(),
                                            mqttStatusReceiver,
                                            ownGbid);
        when(mqttClientFactory.createReceiver(ownGbid)).thenReturn(mqttClientReceiver);
        when(mqttClientFactory.createSender(ownGbid)).thenReturn(mqttClientSender);
        subject.init();
    }

    @Test
    public void testSkeletonCreatesAndStartsSenderAndReceiverForItsOwnGbid() {
        verify(mqttClientFactory).createReceiver(ownGbid);
        verify(mqttClientFactory).createSender(ownGbid);

        verify(mqttClientReceiver).start();
        verify(mqttClientSender).start();
    }

    @Test
    public void testSkeletonSubscribesToOwnTopic() {
        verify(mqttClientReceiver).subscribe(ownTopic + "/#");
        verify(mqttClientSender, times(0)).subscribe(anyString());
    }

    @Test
    public void testSkeletonRegistersItselfAsMessageProcessedListener() {
        verify(messageRouter).registerMessageProcessedListener(eq(subject));
    }

    @Test
    public void testSkeletonRegistersItselfAsMessageListener() {
        verify(mqttClientReceiver).setMessageListener(subject);
        verify(mqttClientSender, times(0)).setMessageListener(any(IMqttMessagingSkeleton.class));
    }

    @Test
    public void testSubscribeToMulticastWithTopicPrefix() {
        final String expectedPrefix = "testMulticastPrefix";
        final String multicastId = "multicastId";
        when(mqttTopicPrefixProvider.getMulticastTopicPrefix()).thenReturn(expectedPrefix);

        subject.registerMulticastSubscription(multicastId);
        verify(mqttClientReceiver).subscribe(expectedPrefix + multicastId);

        subject.unregisterMulticastSubscription(multicastId);
        verify(mqttClientReceiver).unsubscribe(expectedPrefix + multicastId);
    }

    @Test
    public void testOnlySubscribeToMulticastIfNotAlreadySubscribed() {
        when(mqttTopicPrefixProvider.getMulticastTopicPrefix()).thenReturn("");
        String multicastId = "multicastId";

        subject.registerMulticastSubscription(multicastId);
        verify(mqttClientReceiver).subscribe(eq(multicastId));
        reset(mqttClientReceiver);

        subject.registerMulticastSubscription(multicastId);
        verify(mqttClientReceiver, never()).subscribe(anyString());
    }

    @Test
    public void testMultilevelWildcardTranslated() {
        when(mqttTopicPrefixProvider.getMulticastTopicPrefix()).thenReturn("");
        String multicastId = "one/two/*";

        subject.registerMulticastSubscription(multicastId);
        verify(mqttClientReceiver).subscribe(eq("one/two/#"));

        subject.unregisterMulticastSubscription(multicastId);
        verify(mqttClientReceiver).unsubscribe("one/two/#");
    }

    @Test
    public void testMessageRouterIsCalled() throws Exception {
        ImmutableMessage rqMessage = createTestRequestMessage();

        subject.transmit(rqMessage.getSerializedMessage(), failIfCalledAction);

        ArgumentCaptor<ImmutableMessage> captor = ArgumentCaptor.forClass(ImmutableMessage.class);
        verify(messageRouter).route(captor.capture());

        assertArrayEquals(rqMessage.getSerializedMessage(), captor.getValue().getSerializedMessage());
    }

    @Test
    public void testReplyToAddressRegistrarIsCalled() throws Exception {
        ImmutableMessage rqMessage = createTestRequestMessage();

        subject.transmit(rqMessage.getSerializedMessage(), failIfCalledAction);

        ArgumentCaptor<ImmutableMessage> immutableMessageCaptor = ArgumentCaptor.forClass(ImmutableMessage.class);
        verify(replyToAddressRegistrar).registerGlobalRoutingEntry(immutableMessageCaptor.capture(), eq(ownGbid));

        assertArrayEquals(rqMessage.getSerializedMessage(), immutableMessageCaptor.getValue().getSerializedMessage());
        assertTrue(immutableMessageCaptor.getValue().isReceivedFromGlobal());

        verify(messageRouter).route(eq(immutableMessageCaptor.getValue()));
    }

    @Test
    public void testRawMessageProcessorIsCalled() throws Exception {
        RawMessagingPreprocessor rawMessagingPreprocessorMock = mock(RawMessagingPreprocessor.class);
        when(rawMessagingPreprocessorMock.process(any(byte[].class),
                                                  Matchers.<Map<String, Serializable>> any())).then(returnsFirstArg());

        subject = new MqttMessagingSkeleton(ownTopic,
                                            maxIncomingMqttRequests,
                                            messageRouter,
                                            replyToAddressRegistrar,
                                            mqttClientFactory,
                                            mqttTopicPrefixProvider,
                                            rawMessagingPreprocessorMock,
                                            new HashSet<JoynrMessageProcessor>(),
                                            mqttStatusReceiver,
                                            ownGbid);

        ImmutableMessage rqMessage = createTestRequestMessage();

        subject.transmit(rqMessage.getSerializedMessage(), failIfCalledAction);

        ArgumentCaptor<byte[]> argCaptor = ArgumentCaptor.forClass(byte[].class);
        verify(rawMessagingPreprocessorMock).process(argCaptor.capture(), Matchers.<Map<String, Serializable>> any());

        Assert.assertArrayEquals(rqMessage.getSerializedMessage(), argCaptor.getValue());
    }

    @Test
    public void testJoynrMessageProcessorIsCalled() throws Exception {
        JoynrMessageProcessor processorMock = mock(JoynrMessageProcessor.class);

        when(processorMock.processIncoming(any(ImmutableMessage.class))).then(returnsFirstArg());

        subject = new MqttMessagingSkeleton(ownTopic,
                                            maxIncomingMqttRequests,
                                            messageRouter,
                                            replyToAddressRegistrar,
                                            mqttClientFactory,
                                            mqttTopicPrefixProvider,
                                            new NoOpRawMessagingPreprocessor(),
                                            new HashSet<JoynrMessageProcessor>(Arrays.asList(processorMock)),
                                            mqttStatusReceiver,
                                            ownGbid);

        ImmutableMessage rqMessage = createTestRequestMessage();

        subject.transmit(rqMessage.getSerializedMessage(), failIfCalledAction);

        ArgumentCaptor<ImmutableMessage> argCaptor = ArgumentCaptor.forClass(ImmutableMessage.class);
        verify(processorMock).processIncoming(argCaptor.capture());

        Assert.assertArrayEquals(rqMessage.getSerializedMessage(), argCaptor.getValue().getSerializedMessage());
    }
{'fraction_non_alphanumeric': 0.07845074597371801, 'fraction_numerical': 0.0015808714553897836, 'mean_word_length': 2.825930825930826, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 110, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5017877', 'n_tokens_mistral': 5249, 'n_tokens_neox': 5044, 'n_words': 859}