Unable to send SMS using java - java

I was just trying to send SMS using java as I require it in my Web App.But for testing purpose I am the code that is described in this site
And the code is as follows
package logic;
import com.harshadura.gsm.smsdura.GsmModem;
/**
* #author : Harsha Siriwardena <harshadura#gmail.com>
* #copyrights : www.Durapix.org <http://www.durapix.org>
* #license : GNU GPL v3 <http://www.gnu.org/licenses/>
*
* Example on how to simply send a SMS using the smsdura API Wrapper.
*/
public class TestSMS {
private static String port = "COM3"; //Modem Port.
private static int bitRate = 115200; //this is also optional. leave as it is.
private static String modemName = "ZTE"; //this is optional.
private static String modemPin = "0000"; //Pin code if any have assigned to the modem.
private static String SMSC = "+9477000003"; //Message Center Number ex. Mobitel
public static void main(String[] args) throws Exception {
GsmModem gsmModem = new GsmModem();
GsmModem.configModem(port, bitRate, modemName, modemPin, SMSC);
gsmModem.Sender("+94712244555", "Test Message"); // (tp, msg)
}
}
When I tried to run this,I am getting this error
-----------------------------
*** SMS-DURA - GSM MODEM SMS API WRAPPER ***
www.harshadura.com
-----------------------------
Example: Send message from a serial gsm modem.
SMSLib: A Java API library for sending and receiving SMS via a GSM modem or other supported gateways.
This software is distributed under the terms of the Apache v2.0 License.
Web Site: http://smslib.org
Version: 3.5.1
log4j:WARN No appenders could be found for logger (smslib).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "main" org.smslib.GatewayException: Comm library exception: java.lang.RuntimeException: javax.comm.NoSuchPortException
at org.smslib.modem.SerialModemDriver.connectPort(SerialModemDriver.java:102)
at org.smslib.modem.AModemDriver.connect(AModemDriver.java:114)
at org.smslib.modem.ModemGateway.startGateway(ModemGateway.java:189)
at org.smslib.Service$1Starter.run(Service.java:276)
Please anybody tell me how to fix this issue

basically you the program is unable to find the PORT,use
org.smslib.helper.CommPortIdentifier
to find the correct COM port from the list of ports.

I know this is not the sort of answer you expect on SO but given the alternative I think it's better than nothing.
a) Your library is reporting that your modem is not attached.
b) You don't know how to check if your modem is attached.
While not in any way related with the company I've used nexmo with great success in the past.
If it's a necessity of your app I would strongly suggest you approach the problem by the API route that will save you enormous amount of work.
There are several companies out there that provide this service and the usage is more or less straight-forward, you simply format a URL to pass parameters back to the company. Nexmo example:
// by calling a crafted url you are requesting the company to send the sms for you
urlString = "https://rest.nexmo.com/sms/json?api_key={api_key}&api_secret={api_secret}&from=MyCompany20&to=447525856424&text=helloworld";
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream()
Nexmo is NOT the only one out there providing this service. They are the only one i've had hands on experience with.

Copy the API(comm.jar),dll(win32com),properties file(javax.comm) in
1) If Net Beans tool you are using means
C:\Program Files\Java\jdk1.7.0\jre\lib\ext
and
C:\Program Files\Java\jdk1.7.0\jre\bin
2) If Eclipse tool you are using means
C:\Program Files\Java\jre7\lib\ext
and
C:\Program Files\Java\jre7\bin
as per the instructions given in Code projects.com where you downloaded this project.
Another way If you can configure your tool then do it, logic is the API's should be under your runtime JVM(jre).
and make sure that the port which is given by you should be free that is no other apps should run on it.

Yes I also got this exception to in Harshadura's SMS wrapper.Their can be two things you did not do
You did not declare any appenders in the code so at the beginning of
your code just type in this simple code to declare appenders.
package logic;
import com.harshadura.gsm.smsdura.GsmModem;
/**
* #author : Harsha Siriwardena <harshadura#gmail.com>
* #copyrights : www.Durapix.org <http://www.durapix.org>
* #license : GNU GPL v3 <http://www.gnu.org/licenses/>
*
* Example on how to simply send a SMS using the smsdura API Wrapper.
*/
public class TestSMS {
private static String port = "COM3"; //Modem Port.
private static int bitRate = 115200; //this is also optional. leave as it is.
private static String modemName = "ZTE"; //this is optional.
private static String modemPin = "0000"; //Pin code if any have assigned to the modem.
private static String SMSC = "+9477000003"; //Message Center Number ex. Mobitel
public static void main(String[] args) throws Exception {
BasicConfigurator.configure();//Declares appenders
GsmModem gsmModem = new GsmModem();
GsmModem.configModem(port, bitRate, modemName, modemPin, SMSC);
gsmModem.Sender("+94712244555", "Test Message"); // (tp, msg)
} }
Identifying the port of your GSM modem. This you can solve by going to your My Computer Icon click manage > click device manager> click modems and Identify the port of your modem.
The port you identifed then write it on your code.String port="MyPort";

Related

How to get the automatically defined port for a Spark Java Application?

In the API documentation for Java Spark (not Apache spark), you can specify a port of 0 to have it automatically select a port. Great!
However, I cannot figure out how to get that port after the server is started. I can see it in the logs:
15:41:12.459 [Thread-2] INFO spark.webserver.JettySparkServer - >> Listening on 0.0.0.0:63134
But I need to be able to get to it programmatically, so that my integration tests are able to run reliably every time.
So how do I get that port?
I could find no way to get this information in the API, and so I filed an issue on their github.
I was able to get at it via an ugly pile of reflection:
/**
* Meant to be called from a different thread, once the spark app is running
* This is probably only going to be used during the integration testing process, not ever in prod!
*
* #return the port it's running on
*/
public static int awaitRunningPort() throws Exception {
awaitInitialization();
//I have to get the port via reflection, which is fugly, but the API doesn't exist :(
//Since we'll only use this in testing, it's not going to kill us
Object instance = getInstance();
Class theClass = instance.getClass();
Field serverField = theClass.getDeclaredField("server");
serverField.setAccessible(true);
Object oneLevelDeepServer = serverField.get(instance);
Class jettyServerClass = oneLevelDeepServer.getClass();
Field jettyServerField = jettyServerClass.getDeclaredField("server");
jettyServerField.setAccessible(true);
//Have to pull in the jetty server stuff to do this mess
Server jettyServer = (Server)jettyServerField.get(oneLevelDeepServer);
int acquiredPort = ((ServerConnector)jettyServer.getConnectors()[0]).getLocalPort();
log.debug("Acquired port: {}", acquiredPort);
return acquiredPort;
}
This works well for me in our integration tests, but I'm not using https, and it does reach about two levels deep into the API via reflection grabbing protected fields. I could not find any other way to do it. Would be quite happy to be proven wrong.
This will work on Spark 2.6.0:
public static int start (String keystoreFile, String keystorePw)
{
secure(keystoreFile, keystorePw, null, null);
port(0);
staticFiles.location("/public");
get(Path.CLOCK, ClockController.time);
get(Path.CALENDAR, CalendarController.date);
// This is the important line. It must be *after* creating the routes and *before* the call to port()
awaitInitialization();
return port();
}
Without the call to awaitInitialization() port() would return 0.

Java error sending sms message with gsm modem

Hi there I am trying to send a sms message using Java with a GSM Modem
I am learning from this URL: http://www.codeproject.com/Tips/492716/How-to-send-SMS-using-Java-with-a-HSDPA-Dongle
Here is my code:
import com.harshadura.gsm.smsdura.GsmModem;
public class TestSMS {
private static String port = "COM1"; //Modem Port.
private static int bitRate = 9600; //this is also optional. leave as it is.
private static String modemName = "ZTE"; //this is optional.
private static String modemPin = "0000"; //Pin code if any have assigned to the modem.
private static String SMSC = "+9477000003"; //Message Center Number ex. Mobitel
public static void main(String[] args) throws Exception {
GsmModem gsmModem = new GsmModem();
GsmModem.configModem(port, bitRate, modemName, modemPin, SMSC);
gsmModem.Sender("+917350320106", "Test Message"); // (tp, msg)
}
}
I have added the various libraries to the built path of my project:
comm.jar
commons-net-3.0.1.jar
smsdura-1.0.jar
RXTXcomm.jar
However, I get this error when i run the project:
Exception in thread main org.smslib.GatewayException: Comm library exception: java.lang.RuntimeException: javax.comm.NoSuchPortException
Please help
First fill arguments in this line "GsmModem.configModem(port, bitRate, modemName, modemPin, SMSC);"
1.port
can simply right click the MyComputer Icon > go to Mange > then Search for Modems > then it will pop up a interface with several tabs. Okay then you can simply notice theirs a Name called port. In front of that there is the port number. Now you know the port number. Insert that into the code.
2.Modem name
is a optional thing
3.Bit rate?
Leave it as it is. Or change to a proper one. The number will change depending modem to modem.
4.Some modems are using PIN numbers for Security. Does your one also using such a pin? If so please insert it to the code. if you have code in your modem
5.fill your network service center no...check your message setting..
This error can occur due to several reasons.
Your dongle software might be opened. So close it, double check if its running as a background service by using Task Manager. Kill it if it still runs.
Your SMSLib configurations to JVM is not affected properly. So check again the required files are there or not. You need to place them both JDK and JRE see 1
This program does not work well with 64Bit JVM, but it does not say you cannot use it in a 64 bit machine. You have installed 32Bit JDK on the machine, remove the 64Bit JDK to prevent mix ups.
The port you going to access might not really be available in the system. You can simple check the Dongle port if its there by: right clicking Computer icon then go manage > then select device manager > then expand Ports(COM LPT) column > You will see the Application interface port of your device. Thats the port you have to use thre.

Multiple SNMP Agents using SNMP4j and Java

I'm trying to create a snmp agent simulator application, that will create multiple virtual agents with unique ip address and port. I'm trying to use snmp4jagent. But i've some exceptions can you help me ?
I extend BaseAgent class to my own class then create Multiple Instance of that class. But I cannot start More than one agent at a time ie. if One agent's status is running i cannot start another agent without stopping the running agent (Code is too heavy So i don't specify any code here) code for starting an agent is
public void start() throws IOException
{
init();
addShutdownHook();
getServer().addContext(new OctetString("public"));
finishInit();
run();
sendColdStartNotification();
}
then i register Managed objects .
Code reference :
http://shivasoft.in/blog/java/snmp/creating-snmp-agent-server-in-java-using-snmp4j/
Thanks in advance
Pramod
It actually does work (as tested). Maybe you did not assign different IP addresses to your different instances. Add this to your class:
/**
* The ip address of this agent.
*/
private String ipAddress;
/**
* Initializes the transport mappings (ports) to be used by the agent.
*
* #throws IOException
*/
protected void initTransportMappings() throws IOException {
transportMappings = new TransportMapping[1];
transportMappings[0] = new DefaultUdpTransportMapping(new UdpAddress(ipAddress + "/161"));
}
You probably have to add the used ip addresses to your NIC. Example for Linux:
ip addr add 10.0.0.2/24 dev eth0
Please also provide exception messages and stacktraces if you still can't start asecond agent.

Communication between two Machines using java

I have Gui Application written which running on windows,and i want to connect to remote unix machine and perform actions there such like API's ,go over the log file in the machines and send back to the application the last log file or others API that i want to perform on the remote machine.
In the remote machine i don;t have application server i just have Java which installed there.
I want to use Java in order to perform remote API over the remote machine;
what is the advice ,can i use web services ,can any one please advise.
Thanks in advance.
If Java can perform the actions you're talking about, I would use Sockets to communicate with the UNIX-Machine (over TCP/IP).
Your Windows-PC would be the client sending commands to the Unix-PC.
Web services would be a bit heavy handed option, esp if you opt for the SOAP ones. If you don't have a problem with the client and server always being Java, RMI seems to be the simplest solution to this problem since it's communication between two different JVM's using the normal method calling mechanism (with some additional interfaces and rules to be followed to please the RMI specification).
The Spring Framework ships with a number of remoting options that are all very easy to setup. You can use their classes for simpler configuration of something standard like RMI or JMS, or use a lightweight web services protocol such as Spring's HTTP invoker or Hessian.
For analyzing log files of remote machines you can always use Apache Commons sftp programmatically to FTP a copy of the remote log file to your PC.
If you configure the log files to be rotatable or to rotate each time they reach a specific size, you can avoid reloading the same information over and over.
You can use Ganymed SSH-2 for Java to ssh to the remote host from Client Java App and run the commands. No need to run any additional components on remote server. You can do password based authentication or key based authentication to login to remote host. We had successfully used it to administer (start/stop/grep log files, etc.) applications running on remote UNIX hosts. You can capture output of the remote command using the StreamGobbler class provided in the package. You can pass multiple commands separated by semi-colon in one remote call.
Basic Example included in the package:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public class Basic
{
public static void main(String[] args)
{
String hostname = "127.0.0.1";
String username = "joe";
String password = "joespass";
try
{
/* Create a connection instance */
Connection conn = new Connection(hostname);
/* Now connect */
conn.connect();
/* Authenticate.
* If you get an IOException saying something like
* "Authentication method password not supported by the server at this stage."
* then please check the FAQ.
*/
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
/* Create a session */
Session sess = conn.openSession();
sess.execCommand("uname -a && date && uptime && who");
System.out.println("Here is some information about the remote host:");
/*
* This basic example does not handle stderr, which is sometimes dangerous
* (please read the FAQ).
*/
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true)
{
String line = br.readLine();
if (line == null)
break;
System.out.println(line);
}
/* Show exit status, if available (otherwise "null") */
System.out.println("ExitCode: " + sess.getExitStatus());
/* Close this session */
sess.close();
/* Close the connection */
conn.close();
}
catch (IOException e)
{
e.printStackTrace(System.err);
System.exit(2);
}
}
}

How to send SMS using Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I want to send SMS to a mobile phone from a web application, is it possible? How do I do it?
the easiest way to do this is to use an SMS gateway.
there are lots out there, the one i've used is Clickatel to which i simply post an XML request and the gateway does the rest for next to nothing.
i have done this using java and apache commons HTTP Client
Here you can find a Java SMS API project in source forge.
Apart from that, you need a Sms Gateway for the infrastructure. Some companies provide you APIs that it is becoming as easy as pie to make the program.
Step-1.
Download Mail.jar and Activation.jar (see Resources for links) and save to the Java library directory on your computer's local drive.
Step-2.
Start a new Java class in your Java Integrated Development Environment (IDE) and name it "MyMobileJava.java".
Step-3.
Enter the following Java libraries at the start of your Java class. These libraries include the required Java Mail and Communications API resources and other supporting Input/Output and Internet class libraries for sending SMS text messages.
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
Step-4
Place the following Java code after the library import statements in order to instantiate the Java class and assign values for the default SMS text messages.
public class SMTPSend {
public SMTPSend() {
}
public void msgsend() {
String username = "MySMSUsername";
String password = "MyPassword";
String smtphost = "MySMSHost.com";
String compression = "My SMS Compression Information";
String from = "mySMSUsername#MySMSHost.com";
String to = "PhoneNumberToText#sms.MySMSHost.com";
String body = "Hello SMS World!";
Transport myTransport = null;
Step-5
Create Java code to create a new communications session that will then be used to configure the information contained within a text message. This information will then be prepared to be sent. Enter the following Java code in your Java class at the end of the code entered in step four.
try {
Properties props = System.getProperties();
props.put("mail.smtp.auth", "true");
Session mailSession = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(compression);
msg.setText(body);
msg.setSentDate(new Date());
Step-6
Send the text message by connecting to your SMS host address, saving changes to the message, and then sending the information. To do this, enter the following Java code to finish the Java class.
myTransport = mailSession.getTransport("smtp");
myTransport.connect(smtphost, username, password);
msg.saveChanges();
myTransport.sendMessage(msg, msg.getAllRecipients());
myTransport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] argv) {
SMTPSend smtpSend = new SMTPSend();
smtpSend.msgsend();
}
} //enter code here`
You can use this free Java sample program to send SMS from your PC using GSM modem connected to your computer to your COM port. You also need to download and install the Java comm api from Sun.
This program needs the following java files to function.
SerialConnection.java (This file is used to connect to your COM port from your java program)
SerialConnectionException.java (This file is for handling serial connection exceptions in your Java program)
SerialParameters.java (This program is used to set your COM port properties for connecting to your com port from your java program)
Sender.java (This is the program that implements runnable and sends SMS using the serial connection)
SMSClient.java (This java class is the main class that can be instantiated in your own java program and called to send SMS. This program in turn will use all the above four files internally to send out your SMS).
Download Send SMS Java sample program files
/*
*
* A free Java sample program
* A list of java programs to send SMS using your COM serial connection
* and a GSM modem
*
* #author William Alexander
* free for use as long as this comment is included
* in the program as it is
*
* More Free Java programs available for download
* at http://www.java-samples.com
*
*
* Note: to use this program you need to download all the 5 java files
* mentioned on top
*
*/
public class SMSClient implements Runnable{
public final static int SYNCHRONOUS=0;
public final static int ASYNCHRONOUS=1;
private Thread myThread=null;
private int mode=-1;
private String recipient=null;
private String message=null;
public int status=-1;
public long messageNo=-1;
public SMSClient(int mode) {
this.mode=mode;
}
public int sendMessage (String recipient, String message){
this.recipient=recipient;
this.message=message;
//System.out.println("recipient: " + recipient + " message: " + message);
myThread = new Thread(this);
myThread.start();
// run();
return status;
}
public void run(){
Sender aSender = new Sender(recipient,message);
try{
//send message
aSender.send ();
// System.out.println("sending ... ");
//in SYNCHRONOUS mode wait for return : 0 for OK,
//-2 for timeout, -1 for other errors
if (mode==SYNCHRONOUS) {
while (aSender.status == -1){
myThread.sleep (1000);
}
}
if (aSender.status == 0) messageNo=aSender.messageNo ;
}catch (Exception e){
e.printStackTrace();
}
this.status=aSender.status ;
aSender=null;
}
}
The easiest way to do this is to find an operator which supports sms's through mail..
Ex. You have Telia/Comviq/Chello or whatnot. If you send an email to; yournumber#youroperator.com it will send your email via sms to your phone.
Please have a look at SMSLib (http://smslib.org), an open source library for sending and receiving sms using a GMS modem or a mobile phone. It is really a great library.
I wrote a small maven lib for accessing the free (for customers only) web interface of the Swiss moblie operators Sunrise and Orange. You find the source on http://github.com/resmo/libjsms
Just retrieve all the cell phone Email-to-SMS (SMS Gateway) addresses and send an email to that email-to-SMS address.

Categories

Resources