/app/src/main/java/red/yelo/chat/ChatRabbitMQConnector.java

https://gitlab.com/varunkothamachu/yelo-android · Java · 243 lines · 111 code · 51 blank · 81 comment · 6 complexity · b325954c08ec8ab9e576b57f3362db58 MD5 · raw file

  1. /*
  2. *
  3. * * Copyright (C) 2015 yelo.red
  4. * *
  5. * * 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
  6. * *
  7. * * http://www.apache.org/licenses/LICENSE-2.0
  8. * *
  9. * * 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.
  10. *
  11. */package red.yelo.chat;
  12. import android.os.Handler;
  13. import com.rabbitmq.client.ConsumerCancelledException;
  14. import com.rabbitmq.client.QueueingConsumer;
  15. import com.rabbitmq.client.ShutdownSignalException;
  16. import java.io.IOException;
  17. import java.io.UnsupportedEncodingException;
  18. import java.util.Map;
  19. import red.yelo.utils.Logger;
  20. /**
  21. * Consumes messages from a RabbitMQ broker
  22. */
  23. public class ChatRabbitMQConnector extends AbstractRabbitMQConnector{
  24. private static final String TAG = "ChatRabbitMQConnector";
  25. // The Queue name for this consumer
  26. private String mQueue;
  27. private QueueingConsumer mSubscription;
  28. // last message to post back
  29. private byte[] mLastMessage;
  30. public ChatRabbitMQConnector(final String server, final int port, final String virtualHost, final String exchange, final ExchangeType exchangeType) {
  31. super(server, port, virtualHost, exchange, exchangeType);
  32. }
  33. // A reference to the listener, we can only have one at a time(for now)
  34. private OnReceiveMessageHandler mOnReceiveMessageHandler;
  35. private final Handler mHandler = new Handler();
  36. // Create runnable for posting back to main thread
  37. // private final Runnable mReturnMessage = new Runnable() {
  38. // @Override
  39. // public void run() {
  40. //
  41. // mOnReceiveMessageHandler
  42. // .onReceiveMessage(mLastMessage);
  43. // }
  44. // };
  45. private final Runnable mConsumeRunner = new Runnable() {
  46. @Override
  47. public void run() {
  48. consume();
  49. }
  50. };
  51. /**
  52. * Create Exchange and then start consuming. A binding needs to be added
  53. * before any messages will be delivered
  54. */
  55. public boolean connectToRabbitMQ(final String userName,
  56. final String password, final String queueName,
  57. final boolean durable, final boolean exclusive,
  58. final boolean autoDelete, final Map<String, Object> args) {
  59. if (super.connectToRabbitMQ(userName, password)) {
  60. try {
  61. Logger.d(TAG, "Connected");
  62. mQueue = declareQueue(queueName, durable, exclusive, autoDelete, args);
  63. mSubscription = new QueueingConsumer(mChannel);
  64. mChannel.basicConsume(mQueue, true, mSubscription);
  65. //mChannel.basicQos(1);
  66. if (mExchangeType == ExchangeType.FANOUT) {
  67. addBinding("");// fanout has default binding
  68. }
  69. } catch (final IOException e) {
  70. return false;
  71. }
  72. setIsRunning(true);
  73. mHandler.post(mConsumeRunner);
  74. return true;
  75. }
  76. return false;
  77. }
  78. /**
  79. * Add a binding between this consumers Queue and the Exchange with
  80. * routingKey
  81. *
  82. * @param routingKey
  83. * @throws java.io.IOException If the binding could not be done
  84. */
  85. public void addBinding(final String routingKey) throws IOException {
  86. addBinding(mQueue, routingKey);
  87. }
  88. /**
  89. * Add a binding between a queue and a routing key on this consumers
  90. * exchange. The queue should already have been declared
  91. *
  92. * @param queue The queue to bind to
  93. * @param routingKey The routing key
  94. * @throws java.io.IOException If the binding could not be done
  95. */
  96. public void addBinding(final String queue, final String routingKey)
  97. throws IOException {
  98. mChannel.queueBind(queue, mExchange, routingKey);
  99. }
  100. /**
  101. * Declare a queue on this exchange
  102. *
  103. * @param queue The queue to declare
  104. * @param durable
  105. * @param exclusive
  106. * @param autoDelete
  107. * @param args
  108. * @return The queue name
  109. * @throws java.io.IOException If the queue could not be declared
  110. */
  111. public String declareQueue(final String queue, final boolean durable,
  112. final boolean exclusive, final boolean autoDelete,
  113. final Map<String, Object> args) throws IOException {
  114. return mChannel.queueDeclare(queue, durable, exclusive, autoDelete, args)
  115. .getQueue();
  116. }
  117. /**
  118. * Remove binding between this consumers Queue and the Exchange with
  119. * routingKey
  120. *
  121. * @param routingKey the binding key
  122. * @throws java.io.IOException If the binding could not be removed
  123. */
  124. public void removeBinding(final String routingKey) throws IOException {
  125. mChannel.queueUnbind(mQueue, mExchange, routingKey);
  126. }
  127. /**
  128. * Set the callback for received messages
  129. *
  130. * @param handler The callback
  131. */
  132. public void setOnReceiveMessageHandler(final OnReceiveMessageHandler handler) {
  133. mOnReceiveMessageHandler = handler;
  134. };
  135. private void consume() {
  136. final Thread thread = new Thread() {
  137. @Override
  138. public void run() {
  139. while (isRunning()) {
  140. QueueingConsumer.Delivery delivery;
  141. try {
  142. delivery = mSubscription.nextDelivery();
  143. final byte[] lastMessage;
  144. // mLastMessage = delivery.getBody();
  145. lastMessage= delivery.getBody();
  146. String message=new String(lastMessage, "UTF-8");
  147. Logger.d(TAG, "message"+message);
  148. mHandler.post( new Runnable() {
  149. @Override
  150. public void run() {
  151. mOnReceiveMessageHandler
  152. .onReceiveMessage(lastMessage);
  153. }
  154. });
  155. // try {
  156. // mChannel.basicAck(delivery.getEnvelope()
  157. // .getDeliveryTag(), false);
  158. // } catch (final IOException e) {
  159. // Logger.e(TAG, e, "Unable to ack message");
  160. // }
  161. } catch (final InterruptedException ie) {
  162. ie.printStackTrace();
  163. } catch (final ShutdownSignalException e) {
  164. e.printStackTrace();
  165. shutdownHappened();
  166. } catch (final ConsumerCancelledException e) {
  167. e.printStackTrace();
  168. } catch (UnsupportedEncodingException e) {
  169. e.printStackTrace();
  170. }
  171. }
  172. }
  173. };
  174. thread.start();
  175. }
  176. /**
  177. * Called when an unexpected shutdown occured when consuming for
  178. * messages(loss of network, etc)
  179. */
  180. private void shutdownHappened() {
  181. setIsRunning(false);
  182. final OnDisconnectCallback callback = getOnDisconnectCallback();
  183. if (callback != null) {
  184. callback.onDisconnect(false);
  185. }
  186. }
  187. // An interface to be implemented by an object that is interested in
  188. // messages(listener)
  189. public interface OnReceiveMessageHandler {
  190. public void onReceiveMessage(byte[] message);
  191. };
  192. }