I'm able to create docker container for ACE-TAO service , and able to access it from parent windows machine using port-forwarding concept.
From browser i try to hit the localhost:forward-port and getting "ERR_EMPTY_RESPONSE" and TAO service is running in docker container.
If I want to verify in local, whether its connected properly or not.
How can I write Java code to verify?
The following java code connects to localhost:17500 and prints out a message saying whether or not it could create a tcp connection.
import java.io.*;
import java.net.*;
class TCPClient
{
public static void main(String argv[]) throws Exception
{
try {
Socket clientSocket = new Socket("localhost", 17500);
System.out.println("Could connect");
}
catch (ConnectException e) {
System.out.println("Cannot connect");
}
}
}
I'm using a bunch of custom made hardware (RFID readers) and talking to them using NRJavaSerial 3.11.0. My target OS is El Capitan and the target machines are either mac minis or imacs running El Capitan 10.11.1 through 10.11.4, which are meant to run unattended. Here's the code I use to connect to the device(s).
public RFIDReader(String portName,int baudRate, int resetTimerInMillis) throws NoSuchPortException, PortInUseException, UnsupportedCommOperationException, IOException
{
portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if ( portIdentifier.isCurrentlyOwned() )
{
System.out.println("Error: Port is currently in use");
}
else
{
commPort = portIdentifier.open(this.getClass().getName(),2000);
if ( commPort instanceof SerialPort )
{
serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(baudRate,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
serialPort.setOutputBufferSize(50);
serialPort.setInputBufferSize(25);
if(resetTimerInMillis!=0)
{
serialPort.enableReceiveTimeout(resetTimerInMillis);
}
in = serialPort.getInputStream();
out = serialPort.getOutputStream();
}
}
System.out.println("Connection complete: " + portName);
}
On exit, this code is run
public void close() throws IOException
{
//this.stopReadingUltraLight();
in.close();
System.out.println("Inputstream closed.");
out.close();
System.out.println("Outputstream closed.");
serialPort.removeEventListener();
System.out.println("Event listeners removed.");
serialPort.close();
System.out.println("serial Port closed.");
commPort.close();
System.out.println("Comm port closed.");
}
The first run of the application works just fine, as intended. Usage of the serial device is through the in and out stream being used in many loops. However, occasionally, when I exit the application, it seems to break the port. Subsequent starts of the application show this exception:
gnu.io.PortInUseException: Unknown Application
at gnu.io.CommPortIdentifier.open(CommPortIdentifier.java:475)
at main.java.RFIDReader.<init>(RFIDReader.java:48)
at main.java.RFIDBridge.<init>(RFIDBridge.java:151)
at main.java.WebHandler.lambda$0(WebHandler.java:379)
at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:182)
...
Once this error turns up, no application (coolterm etc.) can use the device until it's physically disconnected and reconnected. Coolterm throws an "error 83". lsof | grep usbmodem shows no process currently owning the device. I've also made the var/lock directory and run chmod 777 on it. I'm kinda at the end of my rope here and can't figure out where the ownership of the device is locked up. Any ideas?
RFIDReader.java:48 refers to the line commPort = portIdentifier.open(this.getClass().getName(),2000); in my device connecting section.
CONTEXT:
I am creating a cross-platform multicast client-server system for mobile. I have created the server side in Java. I also created the android client side and it works perfectly.
WHAT I WANT TO KNOW:
I want to know if I could create a client side in iOS using the listener program in this example http://ntrg.cs.tcd.ie/undergrad/4ba2/multicast/antony/example.html that would be compatible with my server-side that I created in Java.
If the above example will not work is there a way I can still use my Java server-side and create a native iOS client system that is compatible with the Java server-side?
SAMPLE CODE OF JAVA SERVER SIDE FOR REFERENCE:
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
//more imports...
class Server2 {
public static MulticastSocket ms1;
public static void main(String[] args) throws IOException {
try {
InetAddress sessAddr1 = InetAddress.getByName("224.2.76.24");
ms1 = new MulticastSocket(5500);
ms1.joinGroup(sessAddr1);
while(true) {
byte[] message = new byte[1024];
message = getIpAddress().getBytes();
DatagramPacket dp = new DatagramPacket(message, message.length, sessAddr1, 5500);
ms1.send(dp);
System.out.println(String.format("Sent message: %s", message));
Thread.sleep(1000);
}
} catch (Exception e) {
System.out.println(String.format("Error: %s", e));
}
}
public static String getIpAddress() {
InetAddress ip;
try {
ip = InetAddress.getLocalHost();
return(String.format("%s",ip.getHostAddress()));
} catch (Exception e) {
return("false");
}
}
}
I tested the listener code in the link and it worked perfectly.
Should not be a problem. iOS is POSIX compliant and Objective-C is defined on top of ANSI C, so you could paste the code you linked to with minor modifications straight into your project, build a simple wrapper to Objective-C and your app should compile, run and work as desired.
I am trying to write a program that will send GPS coordinates using telnet.
I keep getting the following exception:
Exception in thread "Timer-0" java.lang.NullPointerException
at org.apache.commons.net.telnet.Telnet._sendByte(Telnet.java:1060)
at org.apache.commons.net.telnet.TelnetOutputStream.write(TelnetOutputStream.java:87)
at org.apache.commons.net.io.ToNetASCIIOutputStream.write(ToNetASCIIOutputStream.java:77)
at org.apache.commons.net.io.ToNetASCIIOutputStream.write(ToNetASCIIOutputStream.java:111)
at java.io.PrintStream.write(PrintStream.java:430)
at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:202)
at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:272)
at sun.nio.cs.StreamEncoder.flushBuffer(StreamEncoder.java:85)
at java.io.OutputStreamWriter.flushBuffer(OutputStreamWriter.java:168)
at java.io.PrintStream.write(PrintStream.java:477)
at java.io.PrintStream.print(PrintStream.java:619)
at java.io.PrintStream.println(PrintStream.java:756)
at com.example.myandroid.gpsSender$1.run(gpsSender.java:34)
at java.util.TimerThread.mainLoop(Timer.java:512)
at java.util.TimerThread.run(Timer.java:462)
I don't know why I am getting this. Can you please tell me? thanks
Here is my code:
package com.example.myandroid;
import org.apache.commons.net.telnet.TelnetClient;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.SocketException;
import java.util.Timer;
import java.util.TimerTask;
public class gpsSender {
private TelnetClient telnet = new TelnetClient();
public static void main(String[] args) throws Exception {
gpsSender client = new gpsSender();
client.start();
}
public String start() throws Exception {
// Connect to the specified server
telnet.connect("localhost", 5554);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
float longitude = 1;
float latitude = 1;
int count = 0;
PrintStream out = new PrintStream(telnet.getOutputStream());
public void run() {
out.println("geo fix " + String.valueOf(longitude) + " "
+ String.valueOf(latitude));
out.flush();
System.out.println("geo fix " + String.valueOf(longitude) + " "
+ String.valueOf(latitude));
longitude++;
latitude++;
count++;
if (count > 1000) {
cancel();
}
}
}, 0, 1000);
try {
telnet.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ("Done");
}
public void write(String value) {
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}
The line
telnet.disconnect();
is going to execute, so you won't have an output stream to write to, hence the NPE. You should remove that line.
Instead of using localhost, try 10.0.2.2 - that's the IP address the emulator is usually on but I'm not sure if you can establish telnet comms with the emulator.
Edit: Here's a link to telnet the emulator but it's from a command window - perhaps you could write a small batch script for your tests to send gps coordinates but if you have to syncronise this somehow with your running test, you would have to do it from the Android app. It looks like the emulator is indeed on localhost and your 'pc' is on 10.0.2.2
Of course Use the 10.0.2.2 iP and also make sure you're giving the right permissions in your manifest .. but still, if you need to input the long. and lat. to use them in another app .. you don't really need telnet and for the emulator there's a little window called "Emulator Control" where you input manually the long. and lat. but using telnet communication with the emulator, that probably doesn't happen. and on a real phone you can use the "NetwProvider.getLocation()" but of course you can't test that on an emulator as well..
Thanks for publishing this question. This approach lets me easily manipulate the hardware and the sensors of the emulator from within my Robotium tests. Here is a code snippet to set the battery charge of the emulator to 100%:
TelnetClient telnet = new TelnetClient();
telnet.connect("10.0.2.2",5554);
PrintStream out = new PrintStream(telnet.getOutputStream());
out.println("power capacity 100");
out.flush();
telnet.disconnect();
What are the possible ways to send and receive sms from Java application?
How?
(Disclaimer: I work at Twilio)
Twilio offers a Java SDK for sending SMS via the Twilio REST API.
if all you want is simple notifications, many carriers support SMS via email; see SMS through E-Mail
There is an API called SMSLib, it's really awesome.
http://smslib.org/
Now you have a lot of Saas providers that can give you this service using their APIs
Ex: mailchimp, esendex, Twilio, ...
The best SMS API I've seen in Java is JSMPP. It is powerful, easy to use, and I used it myself for an enterprise-level application (sending over 20K SMS messages daily).
This API created to reduce the verbosity of the existing SMPP API.
It's very simple and easy to use because it hides the complexity of
the low level protocol communication such as automatically enquire
link request-response.
https://code.google.com/p/jsmpp/
I've tried some other APIs such as Ozeki, but most of them either is commercial or has limitation in its throughput (i.e can't send more than 3 SMS messages in a second, for example).
You Can Do this With A GSM Modem and Java Communications Api [Tried And Tested]
First You Need TO Set Java Comm Api
This Article Describes In Detail How to Set Up Communication Api
Next You Need A GSM Modem (preferably sim900 Module )
Java JDK latest version preferable
AT Command Guide
Code
package sample;
import java.io.*;
import java.util.*;
import gnu.io.*;
import java.io.*;
import org.apache.log4j.chainsaw.Main;
import sun.audio.*;
public class GSMConnect implements SerialPortEventListener,
CommPortOwnershipListener {
private static String comPort = "COM6"; // This COM Port must be connect with GSM Modem or your mobile phone
private String messageString = "";
private CommPortIdentifier portId = null;
private Enumeration portList;
private InputStream inputStream = null;
private OutputStream outputStream = null;
private SerialPort serialPort;
String readBufferTrial = "";
/** Creates a new instance of GSMConnect */
public GSMConnect(String comm) {
this.comPort = comm;
}
public boolean init() {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(comPort)) {
System.out.println("Got PortName");
return true;
}
}
}
return false;
}
public void checkStatus() {
send("AT+CREG?\r\n");
}
public void send(String cmd) {
try {
outputStream.write(cmd.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String phoneNumber, String message) {
char quotes ='"';
send("AT+CMGS="+quotes + phoneNumber +quotes+ "\r\n");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// send("AT+CMGS=\""+ phoneNumber +"\"\r\n");
send(message + '\032');
System.out.println("Message Sent");
}
public void hangup() {
send("ATH\r\n");
}
public void connect() throws NullPointerException {
if (portId != null) {
try {
portId.addPortOwnershipListener(this);
serialPort = (SerialPort) portId.open("MobileGateWay", 2000);
serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
} catch (PortInUseException | UnsupportedCommOperationException e) {
e.printStackTrace();
}
try {
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
/** These are the events we want to know about*/
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
serialPort.notifyOnRingIndicator(true);
} catch (TooManyListenersException e) {
e.printStackTrace();
}
//Register to home network of sim card
send("ATZ\r\n");
} else {
throw new NullPointerException("COM Port not found!!");
}
}
public void serialEvent(SerialPortEvent serialPortEvent) {
switch (serialPortEvent.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[2048];
try {
while (inputStream.available() > 0)
{
int numBytes = inputStream.read(readBuffer);
System.out.print(numBytes);
if((readBuffer.toString()).contains("RING")){
System.out.println("Enter Inside if RING Loop");
}
}
System.out.print(new String(readBuffer));
} catch (IOException e) {
}
break;
}
}
public void outCommand(){
System.out.print(readBufferTrial);
}
public void ownershipChange(int type) {
switch (type) {
case CommPortOwnershipListener.PORT_UNOWNED:
System.out.println(portId.getName() + ": PORT_UNOWNED");
break;
case CommPortOwnershipListener.PORT_OWNED:
System.out.println(portId.getName() + ": PORT_OWNED");
break;
case CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED:
System.out.println(portId.getName() + ": PORT_INUSED");
break;
}
}
public void closePort(){
serialPort.close();
}
public static void main(String args[]) {
GSMConnect gsm = new GSMConnect(comPort);
if (gsm.init()) {
try {
System.out.println("Initialization Success");
gsm.connect();
Thread.sleep(5000);
gsm.checkStatus();
Thread.sleep(5000);
gsm.sendMessage("+91XXXXXXXX", "Trial Success");
Thread.sleep(1000);
gsm.hangup();
Thread.sleep(1000);
gsm.closePort();
gsm.outCommand();
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Can't init this card");
}
}
}
You can use Nexmo to send SMS as well as receive SMS.
Sending SMS with the Nexmo Java Library is fairly straightforward. After creating a new account, renting a virtual number, and getting your API key & secret you can use the library to send SMS like so:
public class SendSMS {
public static void main(String[] args) throws Exception {
AuthMethod auth = new TokenAuthMethod(API_KEY, API_SECRET);
NexmoClient client = new NexmoClient(auth);
TextMessage message = new TextMessage(FROM_NUMBER, TO_NUMBER, "Hello from Nexmo!");
//There may be more than one response if the SMS sent is more than 160 characters.
SmsSubmissionResult[] responses = client.getSmsClient().submitMessage(message);
for (SmsSubmissionResult response : responses) {
System.out.println(response);
}
}
}
To receive SMS you'll need to set up a server that consumes a webhook. That's fairly simple as well. I recommend checking out our tutorial on receiving SMS with Java.
Disclosure: I work for Nexmo
There are two ways :
First : Use a SMS API Gateway which you need to pay for it , maybe you find some trial even free ones but it's scarce .
Second : To use AT command with a modem GSM connected to your laptop .
that's all
TextMarks gives you access to its shared shortcode to send and receive text messages from your app via their API. Messages come from/to 41411 (instead of e.g. a random phone# and unlike e-mail gateways you have the full 160 chars to work with).
You can also tell people to text in your keyword(s) to 41411 to invoke various functionality in your app. There is a JAVA API client along with several other popular languages and very comprehensive documentation and technical support.
The 14 day free trial can be easily extended for developers who are still testing it out and building their apps.
Check it out here: TextMarks API Info
OMK.smpp. API. it's base on SMPP
and simulator is also available for free
LOGICA SMPP API.
And another option is Kannel a free WAP and SMS gateway.
I suggest a cloud based solution like Twilio. Cloud based solutions are cost-effective, than an in-house solution as the there is no ongoing maintenance, required. SMS through email is not an elegant solution, as you have to get the carrier information from the user and you can never be sure that you can text all mobile numbers.
I am using twilio java api in my web application, to send sms from serverside. within few minutes, you can integrate with your app.
https://www.twilio.com/docs/java/install
Here's an example sending an SMS message from the docs:
import com.twilio.sdk.TwilioRestClient;
import com.twilio.sdk.TwilioRestException;
import com.twilio.sdk.resource.factory.MessageFactory;
import com.twilio.sdk.resource.instance.Message;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
import java.util.List;
public class Example {
// Find your Account Sid and Token at twilio.com/user/account
public static final String ACCOUNT_SID = "{{ account_sid }}";
public static final String AUTH_TOKEN = "{{ auth_token }}";
public static void main(String[] args) throws TwilioRestException {
TwilioRestClient client = new TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN);
// Build a filter for the MessageList
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Body", "Test Twilio message"));
params.add(new BasicNameValuePair("To", "+14159352345"));
params.add(new BasicNameValuePair("From", "+14158141829"));
MessageFactory messageFactory = client.getAccount().getMessageFactory();
Message message = messageFactory.create(params);
System.out.println(message.getSid());
}
}
You can you LOGICA SMPP Java API for sending and Recieving SMS in Java application.
LOGICA SMPP is well proven api in telecom application. Logica API also provide you with signalling capicity on TCP/IP connection.
You can directly integrate with various telecom operator accross the world.
It depends on how you're going to work and who your provider is.
If you work with a sms-gateway company you'll probably work through SMPP protocol (3.4 is still the most common), then have a look on OpenSMPP and jSMPP. These are powerful libs to work with SMPP.
If you're going to work with your own hardware (f.e. a gsm-modem) the easiest way to send messages is through AT commands, they differ depends on the model, so, you should find out what AT commands is supported by your modem. Next, if your modem has an IP and open to connection, you can send commands through java socket
Socket smppSocket = new Socket("YOUR_MODEM_IP", YOUR_MODEM_PORT);
DataOutputStream os = new DataOutputStream(smppSocket.getOutputStream());
DataInputStream is = new DataInputStream(smppSocket.getInputStream());
os.write(some_byte_array[]);
is.readLine();
Otherwise you'll work through a COM port, but the method is the same (sending AT commands), you can find more information how to work with serial ports here.
You can use Twilio for this. But if you are looking for some tricky workaround you can follow the workaround I have mentioned below.
This is not possible for receiving sms. But this is a tricky method you can use to send sms to number of clients. You can use twitter API. We can follow twitter account from our mobile phone with a sms. We just have to send sms to twitter. Imagine we create a twitter account with the user name of #username. Then we can send sms to 40404 as shown below.
follow #username
Then we start to get tweets which are tweeted in that account.
So after we create a twitter account then we can use Twitter API to post tweets from that account. Then all the clients who have follow that account as I mentioned before start to receiving tweets.
You can learn how to post tweets with twitter API from following link.
Twitter API
Before you start developing you have to get permission to use twitter api. You can get access to twitter api from following link.
Twitter Developer Console
This is not the best solution for your problem.But hope this help.
We also love Java in Wavecell, but this question can be answered without language-specific details since we have a REST API which will cover most of your needs:
curl -X "POST" https://api.wavecell.com/sms/v1/amazing_hq/single \
-u amazing:1234512345 \
-H "Content-Type: application/json" \
-d $'{ "source": "AmazingDev", "destination": "+6512345678", "text": "Hello, World!" }'
Look at this questions if you have problems with sending HTTP requests in Java:
HTTP POST using JSON in Java
How can I send json object in http post in java
For specific cases you can also consider using the SMPP API and already mentioned JSMPP library will help with that.
There is Ogham library. The code to send SMS is easy to write (it automatically handles character encoding and message splitting). The real SMS is sent either using SMPP protocol (standard SMS protocol) or through a provider.
You can even test your code locally with a SMPP server to check the result of your SMS before paying for real SMS sending.
package fr.sii.ogham.sample.standard.sms;
import java.util.Properties;
import fr.sii.ogham.core.builder.MessagingBuilder;
import fr.sii.ogham.core.exception.MessagingException;
import fr.sii.ogham.core.service.MessagingService;
import fr.sii.ogham.sms.message.Sms;
public class BasicSample {
public static void main(String[] args) throws MessagingException {
// [PREPARATION] Just do it once at startup of your application
// configure properties (could be stored in a properties file or defined
// in System properties)
Properties properties = new Properties();
properties.setProperty("ogham.sms.smpp.host", "<your server host>"); // <1>
properties.setProperty("ogham.sms.smpp.port", "<your server port>"); // <2>
properties.setProperty("ogham.sms.smpp.system-id", "<your server system ID>"); // <3>
properties.setProperty("ogham.sms.smpp.password", "<your server password>"); // <4>
properties.setProperty("ogham.sms.from.default-value", "<phone number to display for the sender>"); // <5>
// Instantiate the messaging service using default behavior and
// provided properties
MessagingService service = MessagingBuilder.standard() // <6>
.environment()
.properties(properties) // <7>
.and()
.build(); // <8>
// [/PREPARATION]
// [SEND A SMS]
// send the sms using fluent API
service.send(new Sms() // <9>
.message().string("sms content")
.to("+33752962193"));
// [/SEND A SMS]
}
}
There are many other features and samples / spring samples.
You can use AT & T commands for sending sms using GSM modem.