I want use multiple gateway to send messages with SMSLIB.
I have 4 HSPA modems and for each one a different operator, how to detect the name of operator and from there using a specific SMS to be sent.
Here my code:
// SendMessage.java - Sample application.
//
// This application shows you the basic procedure for sending messages.
// You will find how to send synchronous and asynchronous messages.
//
// For asynchronous dispatch, the example application sets a callback
// notification, to see what's happened with messages.
package sms;
import org.smslib.AGateway;
import org.smslib.IOutboundMessageNotification;
import org.smslib.Library;
import org.smslib.OutboundMessage;
import org.smslib.Service;
import org.smslib.modem.SerialModemGateway;
public class SendMessage
{
public void doIt() throws Exception
{
OutboundNotification outboundNotification = new OutboundNotification();
System.out.println("Example: Send message from a serial gsm modem.");
System.out.println(Library.getLibraryDescription());
System.out.println("Version: " + Library.getLibraryVersion());
SerialModemGateway gateway = new SerialModemGateway("modem.com3", "COM3", 115200, "Huawei", "");
gateway.setInbound(true);
gateway.setOutbound(true);
gateway.setSimPin("0000");
// Explicit SMSC address set is required for some modems.
// Below is for VODAFONE GREECE - be sure to set your own!
gateway.setSmscNumber("+947500001");
Service.getInstance().setOutboundMessageNotification(outboundNotification);
Service.getInstance().addGateway(gateway);
Service.getInstance().startService();
System.out.println();
System.out.println("Modem Information:");
System.out.println(" Manufacturer: " + gateway.getManufacturer());
System.out.println(" Model: " + gateway.getModel());
System.out.println(" Serial No: " + gateway.getSerialNo());
System.out.println(" SIM IMSI: " + gateway.getImsi());
System.out.println(" Signal Level: " + gateway.getSignalLevel() + " dBm");
System.out.println(" Battery Level: " + gateway.getBatteryLevel() + "%");
System.out.println();
// Send a message synchronously.
OutboundMessage msg = new OutboundMessage("0094757599108", "Hello from SMSLib!");
Service.getInstance().sendMessage(msg);
System.out.println(msg);
// Or, send out a WAP SI message.
//OutboundWapSIMessage wapMsg = new OutboundWapSIMessage("306974000000", new URL("http://www.smslib.org/"), "Visit SMSLib now!");
//Service.getInstance().sendMessage(wapMsg);
//System.out.println(wapMsg);
// You can also queue some asynchronous messages to see how the callbacks
// are called...
//msg = new OutboundMessage("309999999999", "Wrong number!");
//srv.queueMessage(msg, gateway.getGatewayId());
//msg = new OutboundMessage("308888888888", "Wrong number!");
//srv.queueMessage(msg, gateway.getGatewayId());
System.out.println("Now Sleeping - Hit <enter> to terminate.");
System.in.read();
Service.getInstance().stopService();
}
public class OutboundNotification implements IOutboundMessageNotification
{
public void process(AGateway gateway, OutboundMessage msg)
{
System.out.println("Outbound handler called from Gateway: " + gateway.getGatewayId());
System.out.println(msg);
}
}
public static void main(String args[])
{
SendMessage app = new SendMessage();
try
{
app.doIt();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
This one detect only one gateway from COM3, but i have a USB SWITCHER in COM3 and 4 modems on it.
What is the method to use to get them detected (I want a method to do it), thank you so much.
Related
My problem is that when i want to respond to an arriveng message i dont get the delivery token back from broker but the message is arrived at the broker. i can see it in the logs. So my question is how to respond with a publish to an incoming message?
This is the way i do and it does not work...
public void setMqttCallback() {
mqttClient.setCallback(new MqttCallback() {
#Override
public void connectionLost(final Throwable throwable) {
System.out.println("Lost connection to Broker because of: " + throwable.getMessage());
}
#Override
public void messageArrived(final String topic, final MqttMessage mqttMessage) throws Exception {
System.out.println("Received on " + topic + ": " + new String(mqttMessage.getPayload()));
topics = new Topics();
//Answer to arriving messages (Logic)
if (topic.equals(topics.getVehicleNavLandmarkInfo(Mqtt.VIN_ID))) {
landmarks = new Landmarks();
MqttMessage message = new MqttMessage(landmarks.getLandmarks().getBytes());
message.setQos(2);
System.out.println("Sending on " + topic + ": " + landmarks.getLandmarks());
mqttClient.publish(topics.getBackendNavLandsmarks(Mqtt.VIN_ID), message);
}
if (topic.equals(topics.getVehicleNavDestination(Mqtt.VIN_ID))) {
routing = new Routing(49.0000, 8.0000, "A");
MqttMessage message = new MqttMessage(routing.getShortestPath().getBytes());
message.setQos(2);
System.out.println("Sending on " + topic + ": " + routing.getShortestPath());
mqttClient.publish(topics.getBackendNavRoute(Mqtt.VIN_ID), message);
}
}
#Override
public void deliveryComplete(final IMqttDeliveryToken iMqttDeliveryToken) {
System.out.println("Delivered Message: " + iMqttDeliveryToken.toString());
}
});
}
The messageArrived method is blocking, so you cannot then try and publish a message using the same mqttClient connection. You need to use another thread that has its own connection to the broker.
If it is a one-off situation then you can start a new thread and do everything in it but if your application will be constantly publishing messages to arriving messages then it would be better to start a thread, connect to broker then wait for information to be passed from the messageArrived method.
import com.solacesystems.jcsmp.BytesXMLMessage;
import com.solacesystems.jcsmp.JCSMPException;
import com.solacesystems.jcsmp.JCSMPFactory;
import com.solacesystems.jcsmp.JCSMPProperties;
import com.solacesystems.jcsmp.JCSMPRequestTimeoutException;
import com.solacesystems.jcsmp.JCSMPSession;
import com.solacesystems.jcsmp.JCSMPStreamingPublishEventHandler;
import com.solacesystems.jcsmp.Requestor;
import com.solacesystems.jcsmp.TextMessage;
import com.solacesystems.jcsmp.Topic;
import com.solacesystems.jcsmp.XMLMessageConsumer;
import com.solacesystems.jcsmp.XMLMessageListener;
import com.solacesystems.jcsmp.XMLMessageProducer;
public class REquestor {
public static void main(String... args) throws JCSMPException {
// Check command line arguments
String host="tcp://52.76.233.76:55555";
String username="ccs_jcsmp_user_ccs3";
String pwd="password";
String vpn="default";
System.out.println("BasicRequestor initializing...");
// Create a JCSMP Session
final JCSMPProperties properties = new JCSMPProperties();
properties.setProperty(JCSMPProperties.HOST, host); // host:port
properties.setProperty(JCSMPProperties.USERNAME, username); // client-username
properties.setProperty(JCSMPProperties.PASSWORD, pwd); // client-password
properties.setProperty(JCSMPProperties.VPN_NAME, vpn); // message-vpn
final JCSMPSession session = JCSMPFactory.onlyInstance().createSession(properties);
session.connect();
//This will have the session create the producer and consumer required
//by the Requestor used below.
/** Anonymous inner-class for handling publishing events */
#SuppressWarnings("unused")
XMLMessageProducer producer = session.getMessageProducer(new JCSMPStreamingPublishEventHandler() {
public void responseReceived(String messageID) {
System.out.println("Producer received response for msg: " + messageID);
}
public void handleError(String messageID, JCSMPException e, long timestamp) {
System.out.printf("Producer received error for msg: %s#%s - %s%n",
messageID,timestamp,e);
}
});
XMLMessageConsumer consumer = session.getMessageConsumer((XMLMessageListener)null);
// final XMLMessageConsumer consumer = session.getMessageConsumer(new XMLMessageListener() {
//
// public void onReceive(BytesXMLMessage reply) {
//
// System.out.printf("TextMessage reply received: '%s'%n",((TextMessage)reply).getText());
//
// }
//
// public void onException(JCSMPException e) {
// System.out.printf("Consumer received exception: %s%n", e);
// }
// });
// consumer.
consumer.start();
final Topic topic = JCSMPFactory.onlyInstance().createTopic("topicAnkit");
//Time to wait for a reply before timing out
final int timeoutMs = 100000;
TextMessage request = JCSMPFactory.onlyInstance().createMessage(TextMessage.class);
final String text = "Sample Request from Java!";
request.setText(text);
try {
Requestor requestor = session.createRequestor();
System.out.printf("Connected. About to send request message '%s' to topic '%s'...%n",text,topic.getName());
BytesXMLMessage reply = requestor.request(request, timeoutMs, topic);
// Process the reply
if (reply instanceof TextMessage) {
System.out.printf("TextMessage response received: '%s'%n",
((TextMessage)reply).getText());
}
System.out.printf("Response Message Dump:%n%s%n",reply.dump());
} catch (JCSMPRequestTimeoutException e) {
System.out.println("Failed to receive a reply in " + timeoutMs + " msecs");
}
System.out.println("Exiting...");
session.closeSession();
}
}
So my requirement is I am going to send message to "TopicAnkit" and listen for response in some topic/queue "topicResponse". How to achieve this?
I see in my C++ replier I receive the request and send the reply to this program but this Java Requester is not listening to any topics.
I see a temp topic is created in sendTo field to requester and sending is success but requester not getting the response.
Please advice
1. How to get the response in Java requester from this temp topic
2. How to specify a listening topic so that C++ can send the response to this topic.
Thanks
Ankit
You don't seem to be explicitly setting which reply topic you want to use.
It can either be set on the message, or on the session, see https://docs.solace.com/API-Developer-Online-Ref-Documentation/java/com/solacesystems/jcsmp/Requestor.html
Add
final Topic responseTopic = JCSMPFactory.onlyInstance().createTopic("responseTopic");
request.setReplyTo(responseTopic);
before sending the message
Check message CorrelationId and ReplyTo.
As per solace API documentation don't forget about "#":
Requestor uses CorrelationId values starting with '#' which are reserved for internal use such as two party request/reply. If other applications are required to receive the reply, specify an application CorrelationId.
I have downloaded the source from github from this link: https://github.com/twitter/cloudhopper-smpp
Assuming I want to test receiving message between clients so I create a server and 2 clients. To run server, I used the command "make server". Then in other machine, a client connected to my server and send 1 message to other client which has phone number "123456" using following code
submit0.setSourceAddress(new Address((byte)0x03, (byte)0x00, "654321"));
submit0.setDestAddress(new Address((byte)0x01, (byte)0x01, "123456"));
submit0.setShortMessage(textBytes);
SubmitSmResp submitResp = session0.submit(submit0, 10000);
How can the client which has phone number "123456" get message content from phone number "654321"?
Thanks!
When you are creating sessionHandler like this,
DefaultSmppSessionHandler sessionHandler = new ClientSmppSessionHandler();
This ClientSmppSessionHandler should be extended to DefaultSmppSessionHandler.
There are 2 listeners.
Please see below example.
public class ClientSmppSessionHandler extends DefaultSmppSessionHandler {
private static final Logger logger = LoggerFactory.getLogger(ClientSmppSessionHandler.class);
public ClientSmppSessionHandler() {
super(logger);
}
#Override
public void firePduRequestExpired(PduRequest pduRequest) {
logger.warn("PDU request expired: {}", pduRequest);
}
#Override
public PduResponse firePduRequestReceived(PduRequest pduRequest) {
PduResponse response = pduRequest.createResponse();
logger.info("SMS Received: {}", pduRequest);
if (pduRequest.getCommandId() == SmppConstants.CMD_ID_DELIVER_SM) {
DeliverSm mo = (DeliverSm) pduRequest;
int length = mo.getShortMessageLength();
Address source_address = mo.getSourceAddress();
Address dest_address = mo.getDestAddress();
byte[] shortMessage = mo.getShortMessage();
String SMS= new String(shortMessage);
logger.info(source_address + ", " + dest_address + ", " + SMS);
}
return response;
}
}
Hi I created sample jmdns serviceListner, When i run it , It should continue to list services as it finds, But with this my program, It list few services when run and after that it does not list any service. And i have dns-sd in my google chrome browser, So when i browse services in chrome, at that time my program list other services, Otherwise my program doesn't list services. I don't get why ServiceListner itself doesn't detect any subsequent events.
public static void main(String[] args) throws Exception {
String type = "_my-app._tcp.local.";
Enumeration<NetworkInterface> ifc = NetworkInterface.getNetworkInterfaces();
while (ifc.hasMoreElements()) {
NetworkInterface anInterface = ifc.nextElement();
if (anInterface.isUp()) {
Enumeration<InetAddress> addr = anInterface.getInetAddresses();
while (addr.hasMoreElements()) {
InetAddress address = addr.nextElement();
final JmDNS jmdns = JmDNS.create(address, type);
ServiceListenerClass aClass = new ServiceListenerClass();
jmdns.addServiceListener(type, aClass);
}
}
}
}
public static class ServiceListenerClass implements ServiceListener {
public void serviceAdded(ServiceEvent event) {
event.getDNS().requestServiceInfo(event.getType(), event.getName(), true);
}
public void serviceRemoved(ServiceEvent event) {
System.out.println((count--) + " " + event.getInfo().getName());
}
public void serviceResolved(ServiceEvent event) {
System.out.println((count++) + " :Res: " + event.getInfo().getName() + " " + event.getInfo().getPort() + " " + event.getInfo().getApplication()
+ " " + event.getInfo().getDomain() + " " + event.getInfo().getKey());
}
}
I had a similar problem two.
The problem might come from your firewall settings.
In my case the javaw.exe had access to all incoming calls but could not send anything to anyone as the firewall blocked it.
Try turning of the firewall to test you programm and to be shure thats not the firewall causing the problem.
Same issue here. Starting java with the following argument solved it for me:
-Djava.net.preferIPv4Stack=true
My application is listening to Tibco RV, now I am required to switch to WebSphere MQ. I found the code like this
Tibrv.open(Tibrv.IMPL_NATIVE);
rvdTransport = new TibrvRvdTransport(...);
TibrvQueue queue = new TibrvQueue();
cmqTransport = new TibrvCmQueueTransport(...);
queueListener = new TibrvCmListener(...);
disp = new TibrvDispatcher(...)
In the MQ side, do we have similar concepts?
Thanks
Short answer - Yes.
When you download and install the WMQ client (SupportPac MQC71) you get, in addition to the Java classes, diagnostic utilities and lots of sample code. Among the sample programs you will find MQSample.java which looks like this:
import com.ibm.mq.MQException;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import com.ibm.mq.constants.MQConstants;
public class MQSample {
public static void main(String args[]) {
try {
// Create a connection to the QueueManager
System.out.println("Connecting to queue manager: " + qManager);
MQQueueManager qMgr = new MQQueueManager(qManager);
// Set up the options on the queue we wish to open
int openOptions = MQConstants.MQOO_INPUT_AS_Q_DEF | MQConstants.MQOO_OUTPUT;
// Now specify the queue that we wish to open and the open options
System.out.println("Accessing queue: " + qName);
MQQueue queue = qMgr.accessQueue(qName, openOptions);
// Define a simple WebSphere MQ Message ...
MQMessage msg = new MQMessage();
// ... and write some text in UTF8 format
msg.writeUTF("Hello, World!");
// Specify the default put message options
MQPutMessageOptions pmo = new MQPutMessageOptions();
// Put the message to the queue
System.out.println("Sending a message...");
queue.put(msg, pmo);
// Now get the message back again. First define a WebSphere MQ
// message
// to receive the data
MQMessage rcvMessage = new MQMessage();
// Specify default get message options
MQGetMessageOptions gmo = new MQGetMessageOptions();
// Get the message off the queue.
System.out.println("...and getting the message back again");
queue.get(rcvMessage, gmo);
// And display the message text...
String msgText = rcvMessage.readUTF();
System.out.println("The message is: " + msgText);
// Close the queue
System.out.println("Closing the queue");
queue.close();
// Disconnect from the QueueManager
System.out.println("Disconnecting from the Queue Manager");
qMgr.disconnect();
System.out.println("Done!");
}
catch (MQException ex) {
System.out.println("A WebSphere MQ Error occured : Completion Code " + ex.completionCode
+ " Reason Code " + ex.reasonCode);
ex.printStackTrace();
for (Throwable t = ex.getCause(); t != null; t = t.getCause()) {
System.out.println("... Caused by ");
t.printStackTrace();
}
}
catch (java.io.IOException ex) {
System.out.println("An IOException occured whilst writing to the message buffer: " + ex);
}
return;
}
}
There are of course also samples for JMS, C, C#, etc. The sample shown uses synchronous (blocking) GET calls but there are async listener methods if you want to implement with a callback mechanism.
I would also recommend looking over the application development sections of the Infocenter. These are the v7.0 docs and these are the v7.1 docs.