activemq UDP jms connection - udp

i work on a project with activemq java and i use ssl or udp connection .To receive messqge i use a QeueueReceiver and MessageListener Classes .the problem is that the ssl connection perfectly but when i choose a udp connection and i send 7 messages and i put the listener working i receive 5 messages after i receive only 2 messages . i DONT know what exactly the problem sombedoy can help please there is a code
code
ry {
switch (protocol) {
case "UDP":
connectionFactoryUDP = new ActiveMQConnectionFactory(brokerUrlUDP);
connection = connectionFactoryUDP.createQueueConnection(username, password);
break;
case "TLS":
connectionFactoryTLS = new ActiveMQSslConnectionFactory();
// create connection
connectionFactoryTLS.setBrokerURL(brokerUrlTLS);
connectionFactoryTLS.setTrustStore(trustStore);
connectionFactoryTLS.setTrustStorePassword(trustStorePassword);
connectionFactoryTLS.setKeyStore(keyStore);
connectionFactoryTLS.setKeyStorePassword(keyStorePassword);
connection = connectionFactoryTLS.createQueueConnection(username,password);
break;}
//ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(this.username, this.password, "tcp://localhost:61616");
// create connection
// start
connection.start();
// create session
// create queue (it will create if queue doesn't exist)
// create listener
System.out.println("____________________________________");
MessageListener messageListener = new MessageListener() {
#Override
public void onMessage(Message message) {
System.out.println("____________________________________");
// only text type message
if (message instanceof TextMessage) {
TextMessage txt = (TextMessage) message;
try {
System.out.println("Message received =---_________--" + txt.getText());
} catch (JMSException e) {
System.out.println("error retrieving message");
System.exit(1);
}
}
}
};
session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue(queueName);
QueueReceiver consumer = session.createReceiver(queue);
consumer.setMessageListener(messageListener);
System.in.read();
consumer.close();
session.close();
connection.close();
System.out.println("-----------closed----------");
log console
2015-10-16 18:30:42 DEBUG UdpTransport:382 - Binding to address: 0.0.0.0/0.0.0.0:0
2015-10-16 18:30:42 DEBUG Connection:1:55 - SENDING: ConnectionInfo {commandId = 1, responseRequired = true, connectionId = ID:aymenmhidhi-PC-57832-1445013042216-1:1, clientId = ID:aymenmhidhi-PC-57832-1445013042216-0:1, clientIp = null, userName = aymenmhidhi, password = *****, brokerPath = null, brokerMasterConnector = false, manageable = true, clientMaster = true, faultTolerant = false, failoverReconnect = false}
2015-10-16 18:30:42 DEBUG UdpTransport:124 - Sending oneway from: udp://localhost:61625?trace=true#49257 to target: localhost/127.0.0.1:61625 command: ConnectionInfo {commandId = 1, responseRequired = true, connectionId = ID:aymenmhidhi-PC-57832-1445013042216-1:1, clientId = ID:aymenmhidhi-PC-57832-1445013042216-0:1, clientIp = null, userName = aymenmhidhi, password = *****, brokerPath = null, brokerMasterConnector = false, manageable = true, clientMaster = true, faultTolerant = false, failoverReconnect = false}
2015-10-16 18:30:42 DEBUG DefaultReplayBuffer:47 - Adding command ID: 1 to replay buffer: org.apache.activemq.transport.reliable.DefaultReplayBuffer#7e3e2cff object: java.nio.DirectByteBuffer[pos=129 lim=4096 cap=4096]
2015-10-16 18:30:42 DEBUG CommandDatagramChannel:242 - Channel: udp://localhost:61625?trace=true#49257 sending datagram: 1 to: localhost/127.0.0.1:61625
2015-10-16 18:30:42 DEBUG CommandDatagramChannel:110 - Channel: udp://localhost:61625?trace=true#49257 received from: Endpoint[name:/127.0.0.1:49258] about to process: Response {commandId = 1, responseRequired = false, correlationId = 1}
2015-10-16 18:30:42 DEBUG Connection:1:60 - RECEIVED: Response {commandId = 1, responseRequired = false, correlationId = 1}
2015-10-16 18:30:42 DEBUG CommandDatagramChannel:110 - Channel: udp://localhost:61625?trace=true#49257 received from: Endpoint[name:/127.0.0.1:49258] about to process: ConnectionControl {commandId = 2, responseRequired = false, suspend = false, resume = false, close = false, exit = false, faultTolerant = false, connectedBrokers = , reconnectTo = , token = null, rebalanceConnection = false}
2015-10-16 18:30:42 DEBUG Connection:1:60 - RECEIVED: ConnectionControl {commandId = 2, responseRequired = false, suspend = false, resume = false, close = false, exit = false, faultTolerant = false, connectedBrokers = , reconnectTo = , token = null, rebalanceConnection = false}
2015-10-16 18:30:42 DEBUG CommandDatagramChannel:110 - Channel: udp://localhost:61625?trace=true#49257 received from: Endpoint[name:/127.0.0.1:49258] about to process: BrokerInfo {commandId = 3, responseRequired = false, brokerId = ID:aymenmhidhi-PC-57133-1445011516433-0:1, brokerURL = tcp://aymenmhidhi-PC:61616, slaveBroker = false, masterBroker = false, faultTolerantConfiguration = false, networkConnection = false, duplexConnection = false, peerBrokerInfos = null, brokerName = localhost, connectionId = 0, brokerUploadUrl = null, networkProperties = null}
2015-10-16 18:30:42 DEBUG Connection:1:60 - RECEIVED: BrokerInfo {commandId = 3, responseRequired = false, brokerId = ID:aymenmhidhi-PC-57133-1445011516433-0:1, brokerURL = tcp://aymenmhidhi-PC:61616, slaveBroker = false, masterBroker = false, faultTolerantConfiguration = false, networkConnection = false, duplexConnection = false, peerBrokerInfos = null, brokerName = localhost, connectionId = 0, brokerUploadUrl = null, networkProperties = null}
2015-10-16 18:30:42 DEBUG Connection:1:55 - SENDING: ConsumerInfo {commandId = 2, responseRequired = true, consumerId = ID:aymenmhidhi-PC-57832-1445013042216-1:1:-1:1, destination = ActiveMQ.Advisory.TempQueue,ActiveMQ.Advisory.TempTopic, prefetchSize = 1000, maximumPendingMessageLimit = 0, browser = false, dispatchAsync = true, selector = null, clientId = null, subscriptionName = null, noLocal = true, exclusive = false, retroactive = false, priority = 0, brokerPath = null, optimizedAcknowledge = false, noRangeAcks = false, additionalPredicate = null}
2015-10-16 18:30:42 DEBUG UdpTransport:124 - Sending oneway from: udp://localhost:61625?trace=true#49257 to target: /127.0.0.1:49258 command: ConsumerInfo {commandId = 2, responseRequired = true, consumerId = ID:aymenmhidhi-PC-57832-1445013042216-1:1:-1:1, destination = ActiveMQ.Advisory.TempQueue,ActiveMQ.Advisory.TempTopic, prefetchSize = 1000, maximumPendingMessageLimit = 0, browser = false, dispatchAsync = true, selector = null, clientId = null, subscriptionName = null, noLocal = true, exclusive = false, retroactive = false, priority = 0, brokerPath = null, optimizedAcknowledge = false, noRangeAcks = false, additionalPredicate = null}
2015-10-16 18:30:42 DEBUG DefaultReplayBuffer:47 - Adding command ID: 2 to replay buffer: org.apache.activemq.transport.reliable.DefaultReplayBuffer#7e3e2cff object: java.nio.DirectByteBuffer[pos=155 lim=4096 cap=4096]
2015-10-16 18:30:42 DEBUG CommandDatagramChannel:242 - Channel: udp://localhost:61625?trace=true#49257 sending datagram: 2 to: /127.0.0.1:49258
2015-10-16 18:30:42 DEBUG CommandDatagramChannel:110 - Channel: udp://localhost:61625?trace=true#49257 received from: Endpoint[name:/127.0.0.1:49258] about to process: Response {commandId = 4, responseRequired = false, correlationId = 2}
2015-10-16 18:30:42 DEBUG Connection:1:60 - RECEIVED: Response {commandId = 4, responseRequired = false, correlationId = 2}
brokerurl
brokerUrlUDP=udp://localhost:61625?trace=true
Thanks.

package eu.dedalus.x1v1.arr.arrReceiver;
import java.util.concurrent.ThreadPoolExecutor;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQSslConnectionFactory;
import org.apache.activemq.broker.TransportConnector;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
public class ActiveMQQueuListener {
private static final Logger log = Logger
.getLogger(ActiveMQQueuListener.class.getName());
private String brokerUrlTLS;
private String brokerUrlUDP;
private String username;
private String password;
private ArrListener listener;
private String queueName;
private String protocol;
private String keyStore;
private String trustStore;
private String keyStorePassword;
private String trustStorePassword;
private boolean exit = false;
private QueueConnection connection = null;
private QueueSession session = null;
private ActiveMQConnectionFactory connectionFactoryUDP;
private ActiveMQSslConnectionFactory connectionFactoryTLS;
private MessageConsumer consumer;
private ThreadPoolExecutor executor;
private TransportConnector connector;
public void startReceiving() throws Exception {
System.out.println("------Start receiving---------");
try {
switch (protocol) {
case "UDP":
connectionFactoryUDP = new ActiveMQConnectionFactory(
brokerUrlUDP);
connection = connectionFactoryUDP.createQueueConnection(
username, password);
break;
case "TLS":
connectionFactoryTLS = new ActiveMQSslConnectionFactory();
// create connection
connectionFactoryTLS.setBrokerURL(brokerUrlTLS);
connectionFactoryTLS.setTrustStore(trustStore);
connectionFactoryTLS.setTrustStorePassword(trustStorePassword);
connectionFactoryTLS.setKeyStore(keyStore);
connectionFactoryTLS.setKeyStorePassword(keyStorePassword);
connection = connectionFactoryTLS.createQueueConnection(
username, password);
break;
}
// ConnectionFactory connectionFactory = new
// ActiveMQConnectionFactory(this.username, this.password,
// "tcp://localhost:61616");
// create connection
// start
connection.start();
// create session
// create queue (it will create if queue doesn't exist)
// create listener
MessageListener messageListener = new MessageListener() {
#Override
public void onMessage(Message message) {
// only text type message
if (message instanceof TextMessage) {
TextMessage txt = (TextMessage) message;
try {
System.out
.println("Message received =---_________--"
+ txt.getText());
} catch (JMSException e) {
System.out.println("error retrieving message");
System.exit(1);
}
}
}
};
session = connection.createQueueSession(false,
Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue(queueName);
QueueReceiver consumer = session.createReceiver(queue);
consumer.setMessageListener(messageListener);
System.in.read();
consumer.close();
session.close();
connection.close();
System.out.println("-----------closed----------");
} catch (Exception e) {
System.out.println("Exception while sending message to the queue"
+ e);
throw e;
}
}
public void setListener(ArrListener listener) {
this.listener = listener;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public ArrListener getListener() {
return listener;
}
public static Logger getLog() {
return log;
}
public String getQueueName() {
return queueName;
}
public void setQueueName(String queueName) {
this.queueName = queueName;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getKeyStore() {
return keyStore;
}
public void setKeyStore(String keyStore) {
this.keyStore = keyStore;
}
public String getTrustStore() {
return trustStore;
}
public void setTrustStore(String trustStore) {
this.trustStore = trustStore;
}
public String getKeyStorePassword() {
return keyStorePassword;
}
public void setKeyStorePassword(String keyStorePassword) {
this.keyStorePassword = keyStorePassword;
}
public String getTrustStorePassword() {
return trustStorePassword;
}
public void setTrustStorePassword(String trustStorePassword) {
this.trustStorePassword = trustStorePassword;
}
public String getBrokerUrlTLS() {
return brokerUrlTLS;
}
public void setBrokerUrlTLS(String brokerUrlTLS) {
this.brokerUrlTLS = brokerUrlTLS;
}
public String getBrokerUrlUDP() {
return brokerUrlUDP;
}
public void setBrokerUrlUDP(String brokerUrlUDP) {
this.brokerUrlUDP = brokerUrlUDP;
}
public void exitMethod() {
System.exit(1);
try {
consumer.close();
session.close();
connection.close();
System.out.println("-----------closed----------");
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public boolean isExit() {
return exit;
}
public void setExit(boolean exit) {
this.exit = exit;
}
public Connection getConnection() {
return connection;
}
public ActiveMQConnectionFactory getConnectionFactoryUDP() {
return connectionFactoryUDP;
}
public void setConnectionFactoryUDP(
ActiveMQConnectionFactory connectionFactoryUDP) {
this.connectionFactoryUDP = connectionFactoryUDP;
}
public ActiveMQSslConnectionFactory getConnectionFactoryTLS() {
return connectionFactoryTLS;
}
public void setConnectionFactoryTLS(
ActiveMQSslConnectionFactory connectionFactoryTLS) {
this.connectionFactoryTLS = connectionFactoryTLS;
}
}

Related

CodenameOne WebRTC CN1LIB Serverless, Manual Signaling

I am trying to breakdown the process of the webrtc signaling using the PeerConnectionStates Demo by copying the signaling strings manually like as in here Youtube:https://www.youtube.com/watch?v=YLPRBYTeoF4&t=1594s .
Github: https://github.com/chrisuehlinger/serverless-webrtc (from 25:00)
With success I would be able to troubleshoot any signaling problems from Pubnub, Firebase or any other signaling solution I may choose.
I have buttons Start, Call, Exchange and Hang.
The 'Exchange' Button shows an Interactive Dialog which has buttons
Copy Offer , Paste Offer, Set Offer, Copy Answer, Paste Answer, Set Answer. And also 'Copy Offer 2 from text file', and 'Copy Answer 2 from text file'.
If you click on the 1st set of the Dialog buttons in that order (excluding the last 2 file selection buttons), you complete the negotiation as in the original demo.
But I want it to be between 2 devices so I put the offer string from device A into a text file and paste into the text field of device B using Copy Offer 2 from text file, then click 'set offer' to generate an answer which I copy into a text file and send to device A using Copy Answer 2 from text file.
I was not able to place a finger on what I was missing. Any help is appreciated.
public class NewClass extends Form implements AutoCloseable {
private RTCVideoElement video1, video2;
private Button startButton = new Button("Start"),
callButton = new Button("Call"),
hangupButton = new Button("Hang up"),
sendOffer = new Button("Exchange"),
sendAnswer = new Button("Send Answer"),
setOffer = new Button("Set Offer"),
setAnswer = new Button("Set Answer"),
copyOffer = new Button("copy Offer"),
pasteOffer = new Button("paste Offer"),
copyAnswer = new Button("copy Answer"),
pasteAnswer = new Button("paste Answer"),
copyOffer2 = new Button("copy Offer 2- from text file"),
setOffer2 = new Button("set Offer 2"),
copyAnswer2 = new Button("copy Answer 2- from text file"),
setAnswer2 = new Button("set Answer 2");
private TextArea toffer1 = new TextArea("", 5, 7, TextArea.ANY),
toffer2 = new TextArea("", 5, 7, TextArea.ANY),
tAnswer1 = new TextArea("", 5, 7, TextArea.ANY),
tAnswer2 = new TextArea("", 5, 7, TextArea.ANY);
{
startButton.setEnabled(true);
callButton.setEnabled(false);
hangupButton.setEnabled(false);
startButton.addActionListener(evt->start());
callButton.addActionListener(evt->call());
hangupButton.addActionListener(evt->hangup());
sendOffer.addActionListener(evt->sendOffer());
// sendAnswer.addActionListener(evt->sendAnswer());
setOffer.addActionListener(evt->setOffer());
setAnswer.addActionListener(evt->setAnswer());
copyOffer.addActionListener(evt->{ Display.getInstance().copyToClipboard(toffer1.getText()); });
pasteOffer.addActionListener(evt->{ toffer2.setText((String)Display.getInstance().getPasteDataFromClipboard()); });
copyAnswer.addActionListener(evt->{ Display.getInstance().copyToClipboard(tAnswer1.getText()); });
pasteAnswer.addActionListener(evt->{ tAnswer2.setText((String)Display.getInstance().getPasteDataFromClipboard()); });
copyOffer2.addActionListener(evt->{
if (FileChooser.isAvailable()) {
FileChooser.showOpenDialog(".xls, .csv, text/plain", e2-> {
String file = (String)e2.getSource();
if (file == null) {
// hi.add("No file was selected");
// hi.revalidate();
} else {
String extension = null;
if (file.lastIndexOf(".") > 0) {
extension = file.substring(file.lastIndexOf(".")+1);
}
if ("txt".equals(extension)) {
FileSystemStorage fs = FileSystemStorage.getInstance();
try {
InputStream fis = fs.openInputStream(file);
// hi.addComponent(new SpanLabel(Util.readToString(fis)));
toffer1.setText(Util.readToString(fis));
} catch (Exception ex) {
Log.e(ex);
}
} else {
// hi.add("Selected file "+file);
}
}
//hi.revalidate();
});
}
});
copyAnswer2.addActionListener(evt->{
if (FileChooser.isAvailable()) {
FileChooser.showOpenDialog("text/plain", e2-> {
String file = (String)e2.getSource();
if (file == null) {
// hi.add("No file was selected");
// hi.revalidate();
} else {
String extension = null;
if (file.lastIndexOf(".") > 0) {
extension = file.substring(file.lastIndexOf(".")+1);
}
if ("txt".equals(extension)) {
FileSystemStorage fs = FileSystemStorage.getInstance();
try {
InputStream fis = fs.openInputStream(file);
// hi.addComponent(new SpanLabel(Util.readToString(fis)));
tAnswer1.setText(Util.readToString(fis));
} catch (Exception ex) {
Log.e(ex);
}
} else {
// hi.add("Selected file "+file);
}
}
//hi.revalidate();
});
}
});
}
InteractionDialog dlg = new InteractionDialog(" - - -");
{dlg.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
dlg.setScrollable(true);
dlg.setDisposeWhenPointerOutOfBounds(true);
dlg.add(" the offer - copy this offer ");dlg.add(copyOffer);dlg.add(copyOffer2);
dlg.addComponent(toffer1); dlg.add("===============================");
dlg.add(" paste offer here ");dlg.add(pasteOffer);
dlg.addComponent(toffer2);
dlg.addComponent(setOffer);
dlg.add("===============================");
dlg.add(" copy this answer ");dlg.add(copyAnswer);dlg.add(copyAnswer2);
dlg.addComponent(tAnswer1);
dlg.add("===============================");
dlg.add("paste answer here");dlg.add(pasteAnswer);
dlg.addComponent(tAnswer2);
dlg.addComponent(setAnswer);
}
private void sendOffer() {
//= call
Dimension pre = dlg.getContentPane().getPreferredSize();
dlg.show(Display.getInstance().getDisplayHeight()/16,0, Display.getInstance().getDisplayWidth()/16, 0);
} /*
private void sendAnswer() {
}*/
private Date startTime;
private MediaStream localStream;
private RTCPeerConnection pc1, pc2;
private SpanLabel pc1StateDiv = new SpanLabel();
private SpanLabel pc2StateDiv = new SpanLabel();
private SpanLabel pc1IceStateDiv = new SpanLabel();
private SpanLabel pc2IceStateDiv = new SpanLabel();
private SpanLabel pc1ConnStateDiv = new SpanLabel();
private SpanLabel pc2ConnStateDiv = new SpanLabel();
private static final RTCOfferOptions offerOptions = new RTCOfferOptions()
.offerToReceiveAudio(true)
.offerToReceiveVideo(true);
private RTC rtc;
public NewClass() {
super("Peer Connection Demo", new BorderLayout());
Container center = new Container(BoxLayout.y());
Container videoCnt = new Container(new BorderLayout());
String intro = "This sample was adapted from the \"PeerConnection: States Demo\" on the WebRTC web site.";
Button viewSource = new Button("View Source");
FontImage.setMaterialIcon(viewSource, FontImage.MATERIAL_LINK);
viewSource.addActionListener(evt->CN.execute("https://github.com/shannah/CN1WebRTC/blob/master/src/com/codename1/webrtc/demos/PeerConnectionStatesDemo.java"));
add(BorderLayout.NORTH, BoxLayout.encloseY(new SpanLabel(intro), viewSource));
//,toffer1,tAnswer1,setAnswer,toffer2,setOffer,tAnswer2
videoCnt.add(BorderLayout.SOUTH, FlowLayout.encloseCenter(startButton, callButton,sendOffer, hangupButton));
videoCnt.setPreferredH(CN.getDisplayHeight()/2);
center.add(videoCnt);
center.add("PC1 state:").
add(pc1StateDiv).
add("PC1 ICE state:").
add(pc1IceStateDiv).
add("PC1 connection state:").
add(pc1ConnStateDiv).
add("PC2 state:").
add(pc2StateDiv).
add("PC2 ICE state:").
add(pc2IceStateDiv).
add("PC2 connection state:").
add(pc2ConnStateDiv).
add(new SpanLabel("View the console to see logging. The MediaStream object localStream, and the RTCPeerConnection objects localPeerConnection and remotePeerConnection are in global scope, so you can inspect them in the console as well."));
center.setScrollableY(true);
add(BorderLayout.CENTER, center);
RTC.createRTC().onSuccess(r->{
rtc = r;
video1 = rtc.createVideo();
video1.setAutoplay(true);
video1.setMuted(true);
video1.applyStyle("position:fixed;width:50%;height:100%;top:0;left:0;bottom:0;");
video2 = rtc.createVideo();
video2.setAutoplay(true);
video2.applyStyle("position:fixed;width:50%;height:100%;top:0;right:0;bottom:0;");
rtc.append(video1);
rtc.append(video2);
video1.onloadedmetadata(evt->{
System.out.println("Local video videoWidth: "+video1.getVideoWidth()+"px, videoHeight: "+video1.getVideoHeight()+"px");
});
video2.onloadedmetadata(evt->{
System.out.println("Remote video size changed to "+video2.getVideoWidth()+"x"+video2.getVideoHeight());
if (startTime != null) {
long elapsedTime = System.currentTimeMillis() - startTime.getTime();
System.out.println("Setup time: "+elapsedTime+"ms");
startTime = null;
}
});
videoCnt.add(BorderLayout.CENTER, rtc.getVideoComponent());
revalidateWithAnimationSafety();
});
}
private void gotStream(MediaStream stream) {
Log.p("Received local stream");
video1.setSrcObject(stream);
localStream = stream;
stream.retain();
callButton.setEnabled(true);
}
private void start() {
Log.p("Requesting local stream");
startButton.setEnabled(false);
rtc.getUserMedia(new MediaStreamConstraints().audio(true).video(true)).onSuccess(stream->{
gotStream(stream);
}).onFail(t->{
Log.e((Throwable)t);
Dialog.show("Error", "getUserMedia() error: "+((Throwable)t).getMessage(), "OK", null);
});
}
private void call() {
callButton.setEnabled(false);
hangupButton.setEnabled(true);
Log.p("Starting call");
startTime = new Date();
MediaStreamTracks videoTracks = localStream.getVideoTracks();
MediaStreamTracks audioTracks = localStream.getAudioTracks();
if (videoTracks.size() > 0) {
Log.p("Using video device "+videoTracks.get(0).getLabel());
}
if (audioTracks.size() > 0) {
Log.p("Using audio device "+audioTracks.get(0).getLabel());
}
RTCConfiguration servers = new RTCConfiguration();
pc1 = rtc.newRTCPeerConnection(servers);
Log.p("Created local peer connection object pc1");
pc1StateDiv.setText(pc1.getSignalingState()+"");
pc1.onsignalingstatechange(evt->stateCallback1());
pc1IceStateDiv.setText(pc1.getIceConnectionState()+"");
pc1.oniceconnectionstatechange(evt->iceStateCallback1())
.onconnectionstatechange(evt->connStateCallback1())
.onicecandidate(e->onIceCandidate(pc1, e));
/* */
pc2 = rtc.newRTCPeerConnection(servers);
Log.p("Created remote peer connection object pc2");
pc2StateDiv.setText(pc2.getSignalingState()+"");
pc2.onsignalingstatechange(evt->stateCallback2());
pc2IceStateDiv.setText(pc2.getIceConnectionState()+"");
pc2.oniceconnectionstatechange(evt->iceStateCallback2())
.onconnectionstatechange(evt->connStateCallback2())
.onicecandidate(evt->{
onIceCandidate(pc2, evt);
});
pc2.ontrack(evt->gotRemoteStream(evt));
for (MediaStreamTrack track : localStream.getTracks()) {
pc1.addTrack(track, localStream);
}
Log.p("Adding local stream to peer connection");
/* */
pc1.createOffer(offerOptions).onSuccess(offer->{
gotDescription1(offer);
})
.onFail(e-> {
onCreateSessionDescriptionError((Throwable)e);
});
}
private void onCreateSessionDescriptionError(Throwable e) {
Log.p("Failed to create session description: "+e.getMessage(), Log.ERROR);
}
private void gotDescription1(RTCSessionDescription description) {
pc1.setLocalDescription(description);
Log.p("Offer from pc1:\n"+description.getSdp());
sendOffer(description.getSdp());
}
private void sendOffer(String jsDesc) {
toffer1.setText(jsDesc);
// getOffer(jsDesc);
}
private void setOffer() {
String desc = toffer2.getText();
if(desc.endsWith("\n")){getOffer(desc);}else{getOffer(desc+"\n");}
}
private void getOffer(String jsDesc) {
RTCSessionDescription description = rtc.createSessionDescription(RTCSessionDescription.RTCSdpType.Offer, jsDesc);
pc2.setRemoteDescription(description).onSuccess(ef->{
})
.onFail(e->onCreateSessionDescriptionError((Throwable)e)); ;
pc2.createAnswer()
.onSuccess(desc->{ sendAnswer(desc.getSdp()); } )
.onFail(e->onCreateSessionDescriptionError((Throwable)e));
}
private void sendAnswer(String jsDesc) {
tAnswer1.setText(jsDesc);
// getAnswer(jsDesc);
}
private void setAnswer() {
String desc = tAnswer2.getText();
//getAnswer(desc+"\n");
//getAnswer(desc);
if(desc.endsWith("\n")){getAnswer(desc);}else{getAnswer(desc+"\n");}
}
private void getAnswer(String jsDesc) {
RTCSessionDescription description = rtc.createSessionDescription(RTCSessionDescription.RTCSdpType.Answer, jsDesc);
gotDescription2(description);
}
private void gotDescription2(RTCSessionDescription description) {
pc2.setLocalDescription(description);
Log.p("Answer from pc2\n"+description.getSdp());
pc1.setRemoteDescription(description);
}
private void hangup() {
Log.p("Ending call");
pc1.close();
pc2.close();
pc1StateDiv.setText(pc1StateDiv.getText() + pc1.getSignalingState());
pc2StateDiv.setText(pc2StateDiv.getText() + pc2.getSignalingState());
pc1.release();
pc1 = null;
pc2.release();
pc2 = null;
hangupButton.setEnabled(false);
callButton.setEnabled(true);
}
private void gotRemoteStream(RTCTrackEvent e) {
if (video2.getSrcObject() != e.getStreams().get(0)) {
video2.setSrcObject(e.getStreams().get(0));
Log.p("Got remote stream");
}
}
private void stateCallback1() {
if (pc1 != null) {
Log.p("pc1 state change callback, state: "+pc1.getSignalingState());
pc1StateDiv.setText(pc1StateDiv.getText() + pc1.getSignalingState());
}
}
private void stateCallback2() {
if (pc2 != null) {
Log.p("pc2 state change callback, state: "+pc2.getSignalingState());
pc2StateDiv.setText(pc2StateDiv.getText() + pc2.getSignalingState());
}
}
private void iceStateCallback1() {
if (pc1 != null) {
Log.p("pc1 ICE connection state change callback, state: "+pc1.getIceConnectionState());
pc1IceStateDiv.setText(pc1IceStateDiv.getText() + pc1.getIceConnectionState());
}
}
private void iceStateCallback2() {
if (pc2 != null) {
Log.p("pc2 ICE connection state change callback, state: "+pc2.getIceConnectionState());
pc2IceStateDiv.setText(pc2IceStateDiv.getText() + pc2.getIceConnectionState());
}
}
private void connStateCallback1() {
if (pc1 != null) {
Log.p("pc1 connection state change callback, state: "+pc1.getConnectionState());
pc1ConnStateDiv.setText(pc1ConnStateDiv.getText() + pc1.getConnectionState());
}
}
private void connStateCallback2() {
if (pc2 != null) {
Log.p("pc2 connection state change callback, state: "+pc2.getConnectionState());
pc2ConnStateDiv.setText(pc2ConnStateDiv.getText() + pc2.getConnectionState());
}
}
private RTCPeerConnection getOtherPc(RTCPeerConnection pc) {
return pc == pc1 ? pc2 : pc1;
}
private String getName(RTCPeerConnection pc) {
return pc == pc1 ? "pc1" : "pc2";
}
private void onIceCandidate(RTCPeerConnection pc, RTCPeerConnectionIceEvent event) {
getOtherPc(pc).addIceCandidate(event.getCandidate())
.onSuccess(res->onAddIceCandidateSuccess(pc))
.onFail(e->{
Log.e((Throwable)e);
onAddIceCandidateError(pc, (Throwable)e);
}).onComplete(e->{
Log.p(getName(pc)+" ICE candidate:\n"+(event.getCandidate() != null ? event.getCandidate().getCandidate() : "(null"));
});
}
private void onAddIceCandidateSuccess(RTCPeerConnection pc) {
Log.p(getName(pc)+" addIceCandidate success");
}
private void onAddIceCandidateError(RTCPeerConnection pc, Throwable error) {
Log.p(getName(pc)+" failed to add ICE Candidate: "+error.getMessage(), Log.ERROR);
}
#Override
public void close() throws Exception {
if (rtc != null) {
rtc.close();
rtc = null;
}
if (pc1 != null) {
pc1.release();
pc1 = null;
}
if (pc2 != null) {
pc2.release();
pc2 = null;
}
}
}
Call is initiated from Phone - as device A to Simulator
On device A - My Phone
PC1 state:
nullHaveLocalOfferStable
PC1 ICE state:
New
PC1 connection state:
PC2 state:
nullHaveRemoteOffer
PC2 ICE state:
New
PC2 connection state:
On Device B - PC Simulator
PC1 state:
nullHaveLocalOfferStable
PC1 ICE state:
NewCheckingConnected
PC1 connection state:
Connecting
PC2 state:
nullHaveRemoteOfferStable
PC2 ICE state:
NewChecking
PC2 connection state:
Connecting
There is an error message:
java.lang.RuntimeException: Failed to execute 'addIceCandidate' on 'RTCPeerConnection': Error processing ICE candidate
But the final 3 lines on the console are
[EDT] 0:20:48,103 - pc2 addIceCandidate success
[EDT] 0:20:48,103 - pc2 ICE candidate:
candidate:1503035259 1 udp 7935 154.127.57.220 50066 typ relay raddr 129.205.113.2 rport 6591 generation 0 ufrag lXG+ network-cost 999
My Steps are:
from A
Start Button
Call Button - Creates Offer
Copy Offer from toffer1 (using Exchange Button)
Paste into toffer2
Set Offer Button
on B
6. Start Button
7. Call Button
8. Paste Offer of A into TextArea toffer1 and toffer2 (using Exchange Button)
9. Set Offer Button
10. Copy Answer from tAnswer1
11. Paste Answer into tAnswer2
on A
Paste Answer on tAnswer1 and tAnswer2
Set Answer Button
on B
14. set Answer Button

onMessageReceived method is not called, when app is not open

I have implemented FCM in my app, and I need to pass some data from Firebase service to Activity. I have implemented the following code, which works fine, when the app is in foreground(open). When the app is killed or in background, onMessageReceived method is not called, and the launcher activity is loaded while click on the push notification. Also, when the app is open, push message is blank. Kindly advise what I have done wrong. FYI, from backend, they are sending data payload, not notification.
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
public FirebaseMessagingService() {
}
private static final String TAG = com.google.firebase.messaging.FirebaseMessagingService.class.getSimpleName();
public static String CHAT_PUSH_NOTIFICATION_INTENT = "chatPushNotificationIntent";
private PreferencesManager preferencesManager;
#Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.e("push token >>", s);
String reliableIdentifier = FirebaseInstanceId.getInstance().getId();
FCMPreferencesManager pref = FCMPreferencesManager.getInstance(this);
if (pref != null) {
pref.setStringValue(FCMPreferencesManager.FCM_KEY_VALUE, s);
pref.setStringValue(FCMPreferencesManager.DEVICE_ID, reliableIdentifier);
}
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
try {
preferencesManager = PreferencesManager.getInstance(this);
int userId = preferencesManager.getIntValue(PreferencesManager.LOGIN_USER_ID);
Log.e("onMessage received >>", "inside service");
Log.e("userId >>", userId + "");
if (userId > 0) {
Log.e("remote message >>", remoteMessage.getNotification().getBody() + "");
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
try {
JSONObject json = new JSONObject(remoteMessage.getData().toString());
handleDataMessage(json);
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void classApprovedNotification(int jobId, String stage) {
if (!Utils.isAppIsInBackground(getApplicationContext())) {
Intent pushNotification = new Intent(Constants.PUSH_NOTIFICATION_INTENT);
pushNotification.putExtra("jobId", jobId);
pushNotification.putExtra("stage", stage);
LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);
}
}
private void handleDataMessage(JSONObject json) {
try {
Log.e("total json >> ", json.toString());
JSONObject data = json.optJSONObject("data");
Log.e("data >> ", data.toString());
String title = data.optString("title");
String message = data.optString("message");
Log.e("title >>", title);
Log.e("message >>", message);
localNotification(data, title, message, false);
} catch (Exception e) {
Log.e(TAG, "Json Exception: " + e.getMessage());
}
}
private void localNotification(JSONObject data, String title, String message, boolean isSendBird) {
int type = 0, groupId = 0, classId = 0, jobId = 0;
String stage = "";
int notificationId = (int) System.currentTimeMillis();
int userId = preferencesManager.getIntValue(PreferencesManager.LOGIN_USER_ID);
String className = "", fileName = "";
if (data != null) {
jobId = data.optInt("job_id");
stage = data.optString("stage", "");
}
Log.e("jobId in service >>", jobId + "");
Log.e("stage in service >>", stage);
Intent intent = new Intent(FirebaseMessagingService.this, VendorHomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("jobId", jobId);
intent.putExtra("stage","stage");
int requestID = (int) System.currentTimeMillis();
final PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
requestID,
intent,
PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
);
String channelId = "";
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.fyxt_logo)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
/* NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(this);*/
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(notificationId /* ID of notification */, notificationBuilder.build());
try {
PowerManager.WakeLock screenLock = null;
if ((getSystemService(POWER_SERVICE)) != null) {
screenLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "OOTUSER:WAKE");
screenLock.acquire(10 * 60 * 1000L /*10 minutes*/);
screenLock.release();
}
} catch (Exception e) {
e.printStackTrace();
}
classApprovedNotification(jobId, stage);
}
}
In my Activity, I have the following code.
private BroadcastReceiver notificationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
jobIdFromNotification = intent.getIntExtra("jobId", 0);
stageFromNotification = intent.getStringExtra("stage");
Log.e("jobIdFromNotification >>", jobIdFromNotification + "");
Log.e("stageFromNotification >>", stageFromNotification);
prefManager.setIntValue(PreferencesManager.JOB_ID_IN_PREF, jobIdFromNotification);
prefManager.setStringValue(PreferencesManager.JOB_STAGE_IN_PREF, stageFromNotification);
classApprovedViewUpdate();
}
};
private void classApprovedViewUpdate() {
if (jobIdFromNotification > 0) {
fragmentInteractionCallback = (BaseFragment.FragmentInteractionCallback) this;
Log.e("inside push receiver update ", "sfs");
if (stageFromNotification.trim().equalsIgnoreCase(Constants.STAGE_TICKET_APPROVAL)) {
sendActionToActivity(ACTION_CREATE_MAINTENANCE_REQUEST, currentTab, true, fragmentInteractionCallback);
}
}
}
Edit:
data payload:
{
"data": {
"type": 0,
"job_id": 123,
"stage": "STAGE_TICKET_APPROVAL",
}

masstransit with rabbitmq: Why message auto moved to ***_skipped queue when it responing

UCITY.API request to UCITY.USER's "ucity_us_mobilephonecomplete" queue and receive message but Masstransit auto move it to the skip queue
but other queues are working successfully
Masstransit Trace Log:
2018-03-23 15:59:22.5727|DEBUG|MassTransit.Messages|SEND rabbitmq://192.168.1.142/us/ucity_us_mobilephonecomplete 0b350000-dafb-1866-5b48-08d59093fd36 MQNamespace.USER.IMobilephoneCompleteRequest
2018-03-23 15:59:22.6077|DEBUG|MassTransit.Messages|SKIP rabbitmq://192.168.1.142/us/bus-WIN-VH8418VRIC5-UCITY.API-bc4oyyg49ccgcqg6bdk3br7trf?durable=false&autodelete=true N/A
Message Detail
he server reported 1 messages remaining.
Exchange bus-WIN-VH8418VRIC5-UCITY.API-bc4oyyg49ccgcqg6bdk3br7trf_skipped
Routing Key
Redelivered ●
Properties
message_id: 0b350000-dafb-1866-d0af-08d59093bae2
delivery_mode: 2
headers:
Content-Type: application/vnd.masstransit+json
publishId: 1
MT-Reason: dead-letter
MT-Host-MachineName: WIN-VH8418VRIC5
MT-Host-ProcessName: UCITY.API
MT-Host-ProcessId: 14648
MT-Host-Assembly: UCITY.API
MT-Host-AssemblyVersion: 1.0.0.0
MT-Host-MassTransitVersion: 4.0.1.1390
MT-Host-FrameworkVersion: 4.0.30319.42000
MT-Host-OperatingSystemVersion: Microsoft Windows NT 6.2.9200.0
content_type: application/vnd.masstransit+json
Payload
1060 bytes
Encoding: string
{
"messageId": "0b350000-dafb-1866-d0af-08d59093bae2",
"requestId": "0b350000-dafb-1866-8267-08d59093bade",
"conversationId": "0b350000-dafb-1866-0ddf-08d59093bae2",
"sourceAddress": "rabbitmq://192.168.1.142/us/ucity_us_mobilephonecomplete",
"destinationAddress": "rabbitmq://192.168.1.142/us/bus-WIN-VH8418VRIC5-UCITY.API-bc4oyyg49ccgcqg6bdk3br7trf?durable=false&autodelete=true",
"messageType": [
"urn:message:MQNamespace:IBaseResponseModel"
],
"message": {
"code": 4212,
"correlationId": "73989f86-51fd-4ae1-a467-a556a165f125",
"message": "COMPLETEMOBILEPHONE FAILD!USERWECHAT MOBILEPHONE COMPLETED",
"timeStamp": "2018-03-23T15:57:31.3218406+08:00"
},
"headers": {},
"host": {
"machineName": "WIN-VH8418VRIC5",
"processName": "UCITY.USER",
"processId": 8952,
"assembly": "UCITY.USER",
"assemblyVersion": "1.0.0.0",
"frameworkVersion": "4.0.30319.42000",
"massTransitVersion": "4.0.1.1390",
"operatingSystemVersion": "Microsoft Windows NT 6.2.9200.0"
}
}
the skipped queue what does it do
thanks for answer
Change this method to use the proper response type, instead of the base interface.
public async Task Consume(ConsumeContext<IMobilephoneCompleteRequest> context)
{
var dispatch = new UserDispatch(context.Message.CorrelationId);
try
{
var response = await dispatch.MobilephoneComplete(context.Message);
return context.RespondAsync(response);
}
catch (UCException ucEx)
{
var response = new AuthenticationResponse(context.Message.CorrelationId)
{
Code = ucEx.Code,
Message = ucEx.Message
};
return context.RespondAsync(response);
}
catch (Exception ex)
{
var response = new AuthenticationResponse(context.Message.CorrelationId)
{
Code = (int)EnumErrorStatus.UserError,
Message = ex.Message
};
Console.WriteLine(JsonConvert.SerializeObject(ex));
return context.RespondAsync(response);
}
}
The same problem for me also. The day after I figured out the problem, the cause seems to be using the Autofac register method for the current assembly like:
builder.RegisterConsumers(Assembly.GetExecutingAssembly());
Using the following (explicit registration for each consumer) instead was solved the binding problem:
builder.RegisterType<YouConsumerHandler>();
UCIT.API code
//execute request
public async Task<ResultOpenUserLogin> MobilephoneComplete(AuthenticationIdentity authenticationIdentity, ArguUserMobilephoneComplete arguUserMobilephoneComplete)
{
var response = await UserMobilephoneCompleteRequest.Client.Request(new UserMobilephoneCompleteRequest(CorrelationId)
{
DeviceType = authenticationIdentity.DeviceType,
IdUser = authenticationIdentity.IdUser,
Mobilephone = arguUserMobilephoneComplete.Mobilephone,
Passcode = arguUserMobilephoneComplete.Passcode
});// the request timeout
if (response.Code != 200)
{
throw new UCException(response.Code, response.Message);
}
return new ResultOpenUserLogin()
{
Token = response.Token,
UserInfoCompleted = !string.IsNullOrWhiteSpace(response.Mobilephone)
};
}
//UserMobilephoneCompleteRequest class detail
[RabbitMqUri(VirtualHost = "ucity_us", Queue = "ucity_us_mobilephonecomplete")]
public class UserMobilephoneCompleteRequest : BaseRequest, IMobilephoneCompleteRequest
{
public UserMobilephoneCompleteRequest(Guid? correlationId) : base(correlationId)
{
}
public int DeviceType { get; set; }
public int IdUser { get; set; }
public string Mobilephone { get; set; }
public string Passcode { get; set; }
public static IRequestClient<IMobilephoneCompleteRequest, IAuthenticationResponse> Client
{
get
{
return _requestClient;
}
}
private static IRequestClient<IMobilephoneCompleteRequest, IAuthenticationResponse> _requestClient
{
get; set;
}
public override void CreateClient(IBusControl busControl, Uri address)
{
_requestClient = busControl.CreateRequestClient<IMobilephoneCompleteRequest, IAuthenticationResponse>(address, TimeSpan.FromSeconds(10));
}
}
UCIT.USER code
//these codes work well
[RabbitMqUri(VirtualHost = "ucity_us", Queue = "ucity_us_mobilephonecomplete")]
public class MobilephoneCompleteConsumer : BaseConsumer<MobilephoneCompleteConsumer>, IConsumer<IMobilephoneCompleteRequest>
{
public async Task Consume(ConsumeContext<IMobilephoneCompleteRequest> context)
{
var dispatch = new UserDispatch(context.Message.CorrelationId);
IBaseResponseModel response = null;
try
{
response = await dispatch.MobilephoneComplete(context.Message);
}
catch (UCException ucEx)
{
response = new AuthenticationResponse(context.Message.CorrelationId)
{
Code = ucEx.Code,
Message = ucEx.Message
};
}
catch (Exception ex)
{
response = new AuthenticationResponse(context.Message.CorrelationId)
{
Code = (int)EnumErrorStatus.UserError,
Message = ex.Message
};
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(ex));
}
await context.RespondAsync(response);
}
}

.NET Core 1.1 Receiving RabbitMQ Messages

Here's a simple .net core 1.1 console app. Call it with a -r parameter and it reads all the messages in the rabbitmq Queue, call it with any other parameters, and each parameter is enqueued as a message.
Here's the problem, I can enqueue the messages fine, but all attempts to read the messages result in no messages being read. Clearly I'm not consuming the queue correctly, and would appreciate some guidance.
Thanks!
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
namespace RabbitMqDemo
{
class Program
{
static void Main(string[] args)
{
var client = new MessagingClient();
if (args.Length == 1 && args[0].ToLower() == "-r")
{
Console.WriteLine("Reading Messages from Queue.");
var messages = client.ReceiveMessages();
Console.WriteLine($"Read {messages.Length} message(s) from queue.");
foreach(var msg in messages)
Console.WriteLine(msg);
}
else
{
foreach (var msg in args)
{
client.SendMessage(msg);
}
Console.WriteLine($"Enqueued {args.Length} Message.");
}
}
}
internal class MessagingClient
{
private readonly ConnectionFactory connectionFactory;
private string ExchangeName => "defaultExchange";
private string RoutingKey => "";
private string QueueName => "Demo";
private string HostName => "localhost";
public MessagingClient()
{
this.connectionFactory = new ConnectionFactory {HostName = this.HostName};
}
public void SendMessage(string message)
{
using (var connection = this.connectionFactory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
this.QueueDeclare(channel, this.QueueName);
var properties = this.SetMessageProperties(channel, message);
string messageJson = JsonConvert.SerializeObject(message);
var body = Encoding.UTF8.GetBytes(messageJson);
channel.BasicPublish(exchange: this.ExchangeName, routingKey: this.RoutingKey, basicProperties: properties, body: body);
}
}
}
public string[] ReceiveMessages()
{
var messages = new List<string>();
using (var connection = this.connectionFactory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
this.QueueDeclare(channel, this.QueueName);
channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
string bodystring = Encoding.UTF8.GetString(ea.Body);
messages.Add(bodystring);
// ReSharper disable once AccessToDisposedClosure
channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
};
channel.BasicConsume(queue: this.QueueName, autoAck: false, consumer: consumer);
}
}
return messages.ToArray();
}
private void QueueDeclare(IModel channel, string queueName)
{
channel.ExchangeDeclare(ExchangeName, type: ExchangeType.Direct,
durable: true,
autoDelete: false,
arguments: null);
var queueDeclared = channel.QueueDeclare(queue: queueName,
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
channel.QueueBind(queueName, ExchangeName, RoutingKey);
}
private IBasicProperties SetMessageProperties(IModel channel, object message)
{
var properties = channel.CreateBasicProperties();
properties.ContentType = "application/json";
properties.Persistent = true;
return properties;
}
}
}
First, use the management UI to ensure that your exchange and queue are set up correctly and that messages have been published to it.
Second, ReceiveMessages() and thus your reader probably returns immediately with an empty array before the event has a chance to fire. You have no code to wait while the consumer receives messages from RabbitMQ. Notice in the tutorial how Console.ReadLine() is used. In your example, you can use a synchronization object (ManualResetEvent) to prevent ReceiveMessages() from returning until a certain message count is read.

how to access the activemq statistics plugin in .net

I am trying to access the activemq statistics information http://activemq.apache.org/statisticsplugin.html in c#
This is what i have so far. I am not able to get a reply from the consumer. I can the count increase in monitor website for the queue.
public class Statistics
{
private readonly string queueName = string.Empty;
private readonly string queueToMonitor = string.Empty;
private readonly IConnectionFactory connectionFactory;
private readonly IConnection connection;
private readonly ISession session;
private readonly IMessageProducer producer;
private readonly ActiveMQQueue queue;
public Statistics(string qName, string brokerUri, string queueToMon)
{
this.queueName = qName;
this.queueToMonitor = "ActiveMQ.Statistics.Destination." + queueToMon;
this.connectionFactory = new ConnectionFactory(brokerUri);
this.connection = connectionFactory.CreateConnection();
this.connection.Start();
this.session = connection.CreateSession();
queue = new ActiveMQQueue(qName);
producer = session.CreateProducer(queue);
}
public void GetStats()
{
try
{
var statusQueue = session.CreateTemporaryQueue();
var consumer = session.CreateConsumer(statusQueue);
ActiveMQQueue query = new ActiveMQQueue(queueToMonitor);
var msg = session.CreateMessage();
msg.NMSReplyTo = statusQueue;
producer.Send(queue, msg);
var reply = (ActiveMQMapMessage)consumer.Receive();
if (reply != null)
{
var test = reply.Content.ToString();
}
}
catch (Exception e)
{
var t = e.Message + " " + e.StackTrace;
}
}
}
You are sending the message to the wrong queue. You need to send the message to the ActiveMQ.Statistics.Destination.QueueToMonitor destination. I re-wrote your GetStats() function to show that it works. The critical change is which destination the producer sends the message to.
public void GetStats()
{
try
{
IDestination statusQueue = session.CreateTemporaryQueue();
IMessageConsumer consumer = session.CreateConsumer(statusQueue);
IDestination query = session.GetQueue(queueToMonitor);
IMessage msg = session.CreateMessage();
IMessageProducer producer = session.CreateProducer(query);
msg.NMSReplyTo = statusQueue;
producer.Send(msg);
IMapMessage reply = (IMapMessage) consumer.Receive();
if(reply != null)
{
IPrimitiveMap statsMap = reply.Body;
foreach(string statKey in statsMap.Keys)
{
Console.WriteLine("{0} = {1}", statKey, statsMap[statKey]);
}
}
}
catch(Exception e)
{
var t = e.Message + " " + e.StackTrace;
}
}