|
| 1 | +package de.atb.context.monitoring.monitors.messagebroker.util; |
| 2 | + |
| 3 | +/*- |
| 4 | + * #%L |
| 5 | + * ATB Context Monitoring Core Services |
| 6 | + * %% |
| 7 | + * Copyright (C) 2015 - 2021 ATB – Institut für angewandte Systemtechnik Bremen GmbH |
| 8 | + * %% |
| 9 | + * This program and the accompanying materials are made |
| 10 | + * available under the terms of the Eclipse Public License 2.0 |
| 11 | + * which is available at https://www.eclipse.org/legal/epl-2.0/ |
| 12 | + * |
| 13 | + * SPDX-License-Identifier: EPL-2.0 |
| 14 | + * #L% |
| 15 | + */ |
| 16 | + |
| 17 | +import java.io.IOException; |
| 18 | +import java.nio.charset.StandardCharsets; |
| 19 | +import java.util.UUID; |
| 20 | +import java.util.concurrent.TimeoutException; |
| 21 | + |
| 22 | +import com.google.gson.Gson; |
| 23 | +import com.rabbitmq.client.BuiltinExchangeType; |
| 24 | +import com.rabbitmq.client.CancelCallback; |
| 25 | +import com.rabbitmq.client.Channel; |
| 26 | +import com.rabbitmq.client.Connection; |
| 27 | +import com.rabbitmq.client.ConnectionFactory; |
| 28 | +import com.rabbitmq.client.DeliverCallback; |
| 29 | +import de.atb.context.monitoring.config.models.datasources.MessageBrokerDataSource; |
| 30 | +import org.apache.commons.lang3.StringUtils; |
| 31 | +import org.slf4j.Logger; |
| 32 | +import org.slf4j.LoggerFactory; |
| 33 | + |
| 34 | +/** |
| 35 | + * Helper class wrapping methods for interacting with message broker. |
| 36 | + */ |
| 37 | +public class MessageBrokerUtil { |
| 38 | + |
| 39 | + private static final Logger LOGGER = LoggerFactory.getLogger(MessageBrokerUtil.class); |
| 40 | + private static final Gson GSON = new Gson(); |
| 41 | + |
| 42 | + /** |
| 43 | + * Connect to the message broker specified by {@code host} and {@code port} |
| 44 | + * with the credentials specified by {@code userName} and {@code password}. |
| 45 | + * Create the given {@code exchange} if it does not exist yet. |
| 46 | + * |
| 47 | + * @param host the host where the message broker is running |
| 48 | + * @param port the port where the message broker is listening |
| 49 | + * @param userName the username to use when connecting to message broker - optional |
| 50 | + * @param password the password to use when connecting to message broker - optional |
| 51 | + * @param exchange the topic exchange's name |
| 52 | + * @return a {@link Channel} object representing the established connection to the message broker |
| 53 | + * @throws IOException in case of error |
| 54 | + * @throws TimeoutException in case of error |
| 55 | + */ |
| 56 | + public static Channel connectToTopicExchange(final String host, |
| 57 | + final int port, |
| 58 | + final String userName, |
| 59 | + final String password, |
| 60 | + final String exchange) throws IOException, TimeoutException { |
| 61 | + LOGGER.info("Connecting to messagebroker {}:{} with user {}", host, port, userName != null ? userName : "<null>"); |
| 62 | + final ConnectionFactory factory = new ConnectionFactory(); |
| 63 | + |
| 64 | + factory.setHost(host); |
| 65 | + factory.setPort(port); |
| 66 | + |
| 67 | + if (StringUtils.isNotBlank(userName)) { |
| 68 | + factory.setUsername(userName); |
| 69 | + } |
| 70 | + if (StringUtils.isNotBlank(password)) { |
| 71 | + factory.setPassword(password); |
| 72 | + } |
| 73 | + |
| 74 | + factory.setAutomaticRecoveryEnabled(true); |
| 75 | + |
| 76 | + final Connection connection = factory.newConnection(); |
| 77 | + |
| 78 | + final Channel channel = connection.createChannel(); |
| 79 | + |
| 80 | + LOGGER.info("Creating topic exchange {}", exchange); |
| 81 | + channel.exchangeDeclare(exchange, BuiltinExchangeType.TOPIC, true); |
| 82 | + |
| 83 | + return channel; |
| 84 | + } |
| 85 | + |
| 86 | + /** |
| 87 | + * Connect to the message broker specified by {@code host} and {@code port}. |
| 88 | + * Create the given {@code exchange} if it does not exist yet. |
| 89 | + * |
| 90 | + * @param host the host where the message broker is running |
| 91 | + * @param port the port where the message broker is listening |
| 92 | + * @param exchange the topic exchange's name |
| 93 | + * @return a {@link Channel} object representing the established connection to the message broker |
| 94 | + * @throws IOException in case of error |
| 95 | + * @throws TimeoutException in case of error |
| 96 | + * @see MessageBrokerUtil#connectToTopicExchange(String, int, String, String, String) |
| 97 | + */ |
| 98 | + public static Channel connectToTopicExchange(final String host, |
| 99 | + final int port, |
| 100 | + final String exchange) throws IOException, TimeoutException { |
| 101 | + return connectToTopicExchange(host, port, null, null, exchange); |
| 102 | + } |
| 103 | + |
| 104 | + /** |
| 105 | + * Connect to message broker. Message broker details and credentials are specified in the given {@code dataSource}. |
| 106 | + * Create the given {@code exchange} if it does not exist yet. |
| 107 | + * |
| 108 | + * @param dataSource the {@link MessageBrokerDataSource} containing the message broker connection details |
| 109 | + * @return a {@link Channel} object representing the established connection to the message broker |
| 110 | + * @throws IOException in case of error |
| 111 | + * @throws TimeoutException in case of error |
| 112 | + * @see MessageBrokerUtil#connectToTopicExchange(String, int, String, String, String) |
| 113 | + */ |
| 114 | + public static Channel connectToTopicExchange(final MessageBrokerDataSource dataSource) |
| 115 | + throws IOException, TimeoutException { |
| 116 | + return connectToTopicExchange(dataSource.getMessageBrokerServer(), |
| 117 | + dataSource.getMessageBrokerPort(), |
| 118 | + dataSource.getUserName(), |
| 119 | + dataSource.getPassword(), |
| 120 | + dataSource.getExchange()); |
| 121 | + } |
| 122 | + |
| 123 | + /** |
| 124 | + * Register the given callback functions to consume messages on the given {@code exchange} for the given {@code topic}. |
| 125 | + * <p> |
| 126 | + * Use {@link MessageBrokerUtil#connectToTopicExchange(String, int, String, String, String)} or one of its overloads |
| 127 | + * to create {@link Channel}. |
| 128 | + * |
| 129 | + * @param channel the {@link Channel} object representing the established connection to the message broker |
| 130 | + * @param exchange the topic exchange's name |
| 131 | + * @param topic the topic's name |
| 132 | + * @param queuePrefix the prefix to attach to the queue's name |
| 133 | + * @param deliverCallback callback function to handle received messages |
| 134 | + * @param cancelCallback callback function to handle cancellation of the listener |
| 135 | + * @throws IOException in case of error |
| 136 | + */ |
| 137 | + public static void registerListenerOnTopic(final Channel channel, |
| 138 | + final String exchange, |
| 139 | + final String topic, |
| 140 | + final String queuePrefix, |
| 141 | + final DeliverCallback deliverCallback, |
| 142 | + final CancelCallback cancelCallback) throws IOException { |
| 143 | + LOGGER.info("Registering listener on topic {}/{}", exchange, topic); |
| 144 | + final String queueName = String.format("%s-%s", queuePrefix, UUID.randomUUID()); |
| 145 | + final String queue = channel.queueDeclare(queueName, true, true, true, null).getQueue(); |
| 146 | + LOGGER.info("Created queue {}", queue); |
| 147 | + channel.queueBind(queue, exchange, topic); |
| 148 | + channel.basicConsume(queue, true, deliverCallback, cancelCallback); |
| 149 | + } |
| 150 | + |
| 151 | + /** |
| 152 | + * Register the given callback functions to consume messages. |
| 153 | + * The exchange and topic to register for are specified in the given {@code dataSource}. |
| 154 | + * <p> |
| 155 | + * Use {@link MessageBrokerUtil#connectToTopicExchange(String, int, String, String, String)} or one of its overloads |
| 156 | + * to create {@link Channel}. |
| 157 | + * |
| 158 | + * @param channel the {@link Channel} object representing the established connection to the message broker |
| 159 | + * @param dataSource the {@link MessageBrokerDataSource} containing the exchange and topic details |
| 160 | + * @param deliverCallback callback function to handle received messages |
| 161 | + * @param cancelCallback callback function to handle cancellation of the listener |
| 162 | + * @throws IOException in case of error |
| 163 | + */ |
| 164 | + public static void registerListenerOnTopic(final Channel channel, |
| 165 | + final MessageBrokerDataSource dataSource, |
| 166 | + final DeliverCallback deliverCallback, |
| 167 | + final CancelCallback cancelCallback) throws IOException { |
| 168 | + registerListenerOnTopic(channel, |
| 169 | + dataSource.getExchange(), |
| 170 | + dataSource.getTopic(), |
| 171 | + dataSource.getId(), |
| 172 | + deliverCallback, |
| 173 | + cancelCallback); |
| 174 | + } |
| 175 | + |
| 176 | + /** |
| 177 | + * Converts the given {@code payload} object to a JSON string |
| 178 | + * and sends it to the given {@code topic} on the given {@code exchange}. |
| 179 | + * <p> |
| 180 | + * Use {@link MessageBrokerUtil#connectToTopicExchange(String, int, String, String, String)} or one of its overloads |
| 181 | + * to create {@link Channel}. |
| 182 | + * |
| 183 | + * @param channel the {@link Channel} object representing the established connection to the message broker |
| 184 | + * @param exchange the topic exchange's name |
| 185 | + * @param topic the topic's name |
| 186 | + * @param payload the object to send |
| 187 | + * @throws IOException in case of error |
| 188 | + */ |
| 189 | + public static void convertAndSendToTopic(final Channel channel, |
| 190 | + final String exchange, |
| 191 | + final String topic, |
| 192 | + final Object payload) throws IOException { |
| 193 | + final String jsonMessage = GSON.toJson(payload); |
| 194 | + sendToTopic(channel, exchange, topic, jsonMessage); |
| 195 | + } |
| 196 | + |
| 197 | + private static void sendToTopic(final Channel channel, |
| 198 | + final String exchange, |
| 199 | + final String topic, |
| 200 | + final String jsonMessage) throws IOException { |
| 201 | + LOGGER.info("Publishing message to topic {}/{}: {}", exchange, topic, jsonMessage); |
| 202 | + channel.basicPublish(exchange, topic, null, jsonMessage.getBytes(StandardCharsets.UTF_8)); |
| 203 | + } |
| 204 | +} |
0 commit comments