aboutsummaryrefslogtreecommitdiffstats
path: root/testsuites/integration/integration-uservice-test/src/test/java/org/onap/policy/apex/testsuites/integration/uservice/adapt/jms/JmsEventSubscriber.java
blob: 2bdacb66e6b2d4c125a02df650740e490a22ca1c (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
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
 *  Modifications Copyright (C) 2019-2020 Nordix Foundation.
 *  Modifications Copyright (C) 2021 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.apex.testsuites.integration.uservice.adapt.jms;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import lombok.Getter;
import org.apache.activemq.command.ActiveMQTopic;
import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
import org.onap.policy.apex.service.engine.event.ApexEventException;
import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
import org.onap.policy.apex.testsuites.integration.common.testclasses.PingTestClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The Class JmsEventSubscriber.
 *
 * @author Liam Fallon (liam.fallon@ericsson.com)
 */
public class JmsEventSubscriber implements Runnable {
    private static final Logger LOGGER = LoggerFactory.getLogger(JmsEventSubscriber.class);

    private final String topic;
    @Getter
    private long eventsReceivedCount = 0;

    private final Thread subscriberThread;
    private final Connection connection;

    /**
     * Instantiates a new jms event subscriber.
     *
     * @param topic the topic
     * @param connectionFactory the connection factory
     * @param username the username
     * @param password the password
     * @throws JMSException the JMS exception
     */
    public JmsEventSubscriber(final String topic, final ConnectionFactory connectionFactory, final String username,
            final String password) throws JMSException {
        this.topic = topic;
        connection = connectionFactory.createConnection(username, password);
        connection.start();

        subscriberThread = new Thread(this);
        subscriberThread.start();
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void run() {
        final Topic jmsTopic = new ActiveMQTopic(topic);
        try (final Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                final MessageConsumer jmsConsumer = jmsSession.createConsumer(jmsTopic)) {

            while (subscriberThread.isAlive() && !subscriberThread.isInterrupted()) {
                try {
                    final Message message = jmsConsumer.receive(100);
                    if (message == null) {
                        continue;
                    }

                    if (message instanceof ObjectMessage) {
                        final PingTestClass testPing = (PingTestClass) ((ObjectMessage) message).getObject();
                        testPing.verify();
                    } else if (message instanceof TextMessage) {
                        ((TextMessage) message).getText();
                    } else {
                        throw new ApexEventException("unknowm message \"" + message + "\" of type \""
                                + message.getClass().getName() + "\" received");
                    }
                    eventsReceivedCount++;
                } catch (final Exception e) {
                    if (!(e.getCause() instanceof InterruptedException)) {
                        throw new ApexEventRuntimeException("JMS message reception failed", e);
                    }
                }
            }

        } catch (final Exception e) {
            throw new ApexEventRuntimeException("JMS event consumption failed", e);
        }

        LOGGER.info("{} : event reception completed, {} events received", this.getClass().getName(),
                eventsReceivedCount);
    }

    /**
     * Shutdown.
     *
     * @throws JMSException the JMS exception
     */
    public void shutdown() throws JMSException {
        LOGGER.info("{} : stopping...", this.getClass().getName());

        subscriberThread.interrupt();

        while (subscriberThread.isAlive()) {
            ThreadUtilities.sleep(10);
        }

        connection.close();
        LOGGER.info("{} : stopped", this.getClass().getName());
    }

}