The TeleMessage Java library lets you write Java code to make REST, SOAP, XML, HTTP or URL Parameters requests to the TeleMessage API. 

 

Download Code

Download code from TeleMessage Github.

 

Using the Library

Inside the Github library you’ll find telemessage-java.jar. Add it to your project.

 

 

Dependencies

There are few libraries required to run telemessage-java.jar:

1. Apache Commons Codec

2. Apache Commons Lang

3. Java SimpleXML Framework

4. Apache Axis (axis.jar and jaxrpc.jar)

5. Apache Commons Discovery

6. Java Mail

7. wsdl4j

 

If you want to run and compile code examples, you’ll need to add additional libraries, such as Apache httpclient and Apache commons-io. You can find all dependencies inside the “lib” folder in Github.

Sending Messages

With our Java library, sending messages is very simple.

First, initiate TeleMessage object:

TeleMessage tm = new TeleMessage();

Next step, add recipient. First parameter is device value, second parameter is device type.

Supported device types are SMS, MOBILE, HOME_PHONE, BUSINESS_PHONE, FAX, EMAIL.

Note: MOBILE, HOME_PHONE, BUSINESS_PHONE – means message will be sent as a voice message.

Third parameter is description and it’s for display purpose only. Leave it null if you want it same as device value.

tm.addRecipient(new Recipient("1-xxx-xxxxxxx", "SMS", null));

 

Next, fill message data. To add text message, add following line: tm.setText("Rest sample");

if you need subject, write: tm.setSubject("My subject");

 

Now, your message is ready. The only thing is to send it using any transport you want.

In our example we use httpclient 4.3, so let’s send our message:

The first thing is to create HttpClient instance. We need to choose what protocol to use: XML, JSON or SEND_TO_URL.

For example, we can retrieve JSON gateway by calling following method: tm.getSendURL(TeleMessage.Interface.JSON).

So, creating HttpClient looks, as following: HttpPost httppost = new HttpPost(tm.getSendURL(TeleMessage.Interface.JSON));

Now, we need to prepare Stream to write into request: ByteArrayOutputStream by = new ByteArrayOutputStream(); and write our message into this Stream: tm.writeSend("username", "password", TeleMessage.Interface.JSON, by);

First and second parameters for this call it’s your TeleMessage account username and password, the third parameter is protocol you want to use (XML, JSON, SEND_TO_URL) and the last one is stream to write to.

HttpClient uses entities to fill request body, so we create such entity:

ByteArrayEntity entity = new ByteArrayEntity(by.toByteArray(), ContentType.create("application/json", "UTF-8"));
httppost.setEntity(entity);

And finally, the last step, we execute our request: HttpResponse resp = httpclient.execute(httppost);

If HTTP status is 200, means, message sent!

We almost done. If you need to check message status later, we need to add few additional lines:

InputStream in = resp.getEntity().getContent();
try {
	MessageResponse r = tm.readSendResponse(in, TeleMessage.Interface.JSON);
	System.out.println("Response is " + r.getResultCode() + ", description " + r.getResultDescription() + ", message Id " + 
	r.getMessageID() + ", message key " + r.getMessageKey());
} finally {
	if (in != null)
		IOUtils.closeQuietly(in);
}

Store messageId and messageKey for querying status later.

 

See complete example below:

package examples.json;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import telemessage.TeleMessage;
import telemessage.web.services.MessageResponse;
import telemessage.web.services.Recipient;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * @author Grinfeld Mikhail
 * @since 5/26/2014.
 */
public class HttpPostJsonExample {

    public static void main(String...args) {
        TeleMessage tm = new TeleMessage();
        tm.setSubject("Hello World");
        tm.setText("Rest sample");
        tm.addRecipient(new Recipient("+1-xxx-xxxxxx", "SMS", null));

        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(tm.getSendURL(TeleMessage.Interface.JSON));
            ByteArrayOutputStream by = new ByteArrayOutputStream();
            tm.writeSend("username", "password", TeleMessage.Interface.JSON, by);

            ByteArrayEntity entity = new ByteArrayEntity(by.toByteArray(), ContentType.create("application/json", "UTF-8"));
            httppost.setEntity(entity);

            HttpResponse resp = httpclient.execute(httppost);
            if (resp != null && resp.getStatusLine().getStatusCode() == 200) {
                InputStream in = resp.getEntity().getContent();
                try {
                    MessageResponse r = tm.readSendResponse(in, TeleMessage.Interface.JSON);
                    System.out.println("Response is " + r.getResultCode() + ", description " + r.getResultDescription() + ", message Id " + 
                    r.getMessageID() + ", message key " + r.getMessageKey());
                } finally {
                    if (in != null)
                        IOUtils.closeQuietly(in);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
package examples.xml;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import telemessage.TeleMessage;
import telemessage.web.services.MessageResponse;
import telemessage.web.services.Recipient;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Grinfeld Mikhail
 * @since 5/26/2014.
 */
public class HttpPostXMLExample {
    public static void main(String...args) {
        TeleMessage tm = new TeleMessage();
        tm.setSubject("Hello World");
        tm.setText("XML sample");
        tm.addRecipient(new Recipient("+1xxxxxxxxxx", "SMS", null));

        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(tm.getSendURL(TeleMessage.Interface.XML));
            ByteArrayOutputStream by = new ByteArrayOutputStream();
            tm.writeSend("xxxxxxxxxx", "xxxxxxxx", TeleMessage.Interface.XML, by);

            ByteArrayEntity entity = new ByteArrayEntity(by.toByteArray(), ContentType.create("text/xml", "UTF-8"));
            httppost.setEntity(entity);

            HttpResponse resp = httpclient.execute(httppost);
            if (resp != null && resp.getStatusLine().getStatusCode() == 200) {
                InputStream in = resp.getEntity().getContent();
                try {
                    MessageResponse r = tm.readSendResponse(in, TeleMessage.Interface.XML);
                    System.out.println("Response is " + r.getResultCode() + ", description " + r.getResultDescription() + ", message Id " + r.getMessageID() + ", message key " + r.getMessageKey());
                } finally {
                    if (in != null)
                        IOUtils.closeQuietly(in);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package examples.soap;

import generated.*;

import javax.xml.rpc.ServiceException;
import java.rmi.RemoteException;
import java.util.Date;

public class SimpleMessageExample {
    public static void main(String...args) {
            try {
                Sender s = new SenderServiceLocator().gettelemessage();
                AuthenticationDetails a = new AuthenticationDetails("xxxxx","xxxxxxx");
                Message m = new Message();
                Recipient r = new Recipient();
                r.setValue("+1xxxxxxxxxx");
                r.setType("SMS");
                m.setTextMessage("Hello");
                m.setRecipients(new Recipient[] {r});
                m.setSubject("1st");
                MessageResponse rs = s.sendMessage(a, m);

                System.out.println("Message id: " + rs.getMessageID() + ", key: " + rs.getMessageKey() + ", result status: " + rs.getResultCode());
            } catch (ServiceException e) {
                e.printStackTrace();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
}
package examples.url;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.HttpClients;
import telemessage.TeleMessage;
import telemessage.URLResult;
import telemessage.web.services.Recipient;

import java.io.IOException;
import java.util.Map;

/**
 * @author Grinfeld Mikhail
 * @since 5/26/2014.
 */
public class HttpGetURLExample {
    public static void main(String...args) {
        TeleMessage tm = new TeleMessage();
        tm.setSubject("Hello World");
        tm.setText("SEND TO URL sample");
        tm.addRecipient(new Recipient("+1xxxxxxxxxx", "SMS", null));

        try {

            URLResult res = (URLResult)tm.writeSend("xxxxxxxxxxxx", "xxxxxxxx", TeleMessage.Interface.SEND_TO_URL, null);

            RequestBuilder builder = RequestBuilder.get().setUri(tm.getSendURL(TeleMessage.Interface.SEND_TO_URL));
            if (res.getParams() != null) {
                for (Map.Entry entry : res.getParams().entrySet()) {
                    builder.addParameter(entry.getKey(), entry.getValue());
                }
            }

            HttpResponse resp = HttpClients.createDefault().execute(builder.build());

            if (resp != null && resp.getStatusLine().getStatusCode() == 200) {
                resp.getEntity().writeTo(System.out);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

Sending Messages with Attachments

Sending message with attachments is very similar to sending a simple message. The only thing you need to do is add your file by using the addFileMessage method:

File f = new File(HttpPostFileJsonExample.class.getResource("file.png").getPath());
FileInputStream fi = new FileInputStream(f);

tm.addFileMessage(new FileMessage(f.getName(), "image/png", fi));

Note:

  1. You can’t send message with attachments by using “URL Parameters”
  2. Some file types won’t be supported by your destination, e.g. if you are sending a tiff file to SMS, the attachment won’t be added; however the same file will be delivered to a fax recipient.
  3. When you are using SOAP to send message with file attachment, you’ll need to encode file by yourself to Base64

 

See complete examples below:

package examples.json;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import telemessage.FileMessage;
import telemessage.TeleMessage;
import telemessage.web.services.MessageResponse;
import telemessage.web.services.Recipient;

import java.io.*;

/**
 * @author Grinfeld Mikhail
 * @since 5/26/2014.
 */
public class HttpPostFileJsonExample {

    public static void main(String...args) {
        try {
            TeleMessage tm = new TeleMessage();
            tm.setSubject("Hello World");
            tm.setText("Rest sample");
            tm.addRecipient(new Recipient("someemail@somedomain.com", "EMAIL", null));

            File f = new File(HttpPostFileJsonExample.class.getResource("file.png").getPath());
            FileInputStream fi = new FileInputStream(f);

            tm.addFileMessage(new FileMessage(f.getName(), "image/png", fi));

            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(tm.getSendURL(TeleMessage.Interface.JSON));
            ByteArrayOutputStream by = new ByteArrayOutputStream();
            tm.writeSend("xxxxxxxxx", "xxxxxxx", TeleMessage.Interface.JSON, by);

            ByteArrayEntity entity = new ByteArrayEntity(by.toByteArray(), ContentType.create("application/json", "UTF-8"));
            httppost.setEntity(entity);

            HttpResponse resp = httpclient.execute(httppost);
            if (resp != null && resp.getStatusLine().getStatusCode() == 200) {
                InputStream in = resp.getEntity().getContent();
                try {
                    MessageResponse r = tm.readSendResponse(in, TeleMessage.Interface.JSON);
                    System.out.println("Response is " + r.getResultCode() + ", description " + r.getResultDescription() + ", message Id " + r.getMessageID() + ", message key " + r.getMessageKey());
                } finally {
                    if (in != null)
                        IOUtils.closeQuietly(in);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
package examples.xml;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import telemessage.FileMessage;
import telemessage.TeleMessage;
import telemessage.web.services.MessageResponse;
import telemessage.web.services.Recipient;

import java.io.*;

/**
 * @author Grinfeld Mikhail
 * @since 5/26/2014.
 */
public class HttpPostFileXMLExample {
    public static void main(String...args) {
        try {
            TeleMessage tm = new TeleMessage();
            tm.setSubject("Hello World");
            tm.setText("XML sample");
            tm.addRecipient(new Recipient("someemail@somedomain.com", "EMAIL", null));

            File f = new File(HttpPostFileXMLExample.class.getResource("file.png").getPath());
            FileInputStream fi = new FileInputStream(f);

            tm.addFileMessage(new FileMessage(f.getName(), "image/png", fi));

            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(tm.getSendURL(TeleMessage.Interface.XML));
            ByteArrayOutputStream by = new ByteArrayOutputStream();
            tm.writeSend("xxxxxxx", "xxxxxx", TeleMessage.Interface.XML, by);

            ByteArrayEntity entity = new ByteArrayEntity(by.toByteArray(), ContentType.create("text/xml", "UTF-8"));
            httppost.setEntity(entity);

            HttpResponse resp = httpclient.execute(httppost);
            if (resp != null && resp.getStatusLine().getStatusCode() == 200) {
                InputStream in = resp.getEntity().getContent();
                try {
                    MessageResponse r = tm.readSendResponse(in, TeleMessage.Interface.XML);
                    System.out.println("Response is " + r.getResultCode() + ", description " + r.getResultDescription() + ", message Id " + r.getMessageID() + ", message key " + r.getMessageKey());
                } finally {
                    if (in != null)
                        IOUtils.closeQuietly(in);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
package examples.soap;

import generated.*;
import org.apache.commons.codec.binary.Base64;

import javax.xml.rpc.ServiceException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Date;

public class FileMessageExample {
    public static void main(String...args) {
            try {
                Sender s = new SenderServiceLocator().gettelemessage();
                AuthenticationDetails a = new AuthenticationDetails("xxxxx","xxxxxxx");
                Message m = new Message();
                Recipient r = new Recipient();
                r.setValue("+1xxxxxxxxxx");
                r.setType("FAX");
                m.setTextMessage("Hello");
                m.setRecipients(new Recipient[] {r});
                m.setSubject("1st");

                File f = new File(FileMessageExample.class.getResource("file.png").getPath());
                FileInputStream fi = new FileInputStream(f);
                m.setFileMessages(new FileMessage[] {
                        new FileMessage(f.getName(), "image/png", "", 0, Base64.encodeBase64String(org.apache.commons.io.IOUtils.toByteArray(fi)))
                });
                MessageResponse rs = s.sendMessage(a, m);

                System.out.println("Message id: " + rs.getMessageID() + ", key: " + rs.getMessageKey() + ", result status: " + rs.getResultCode());
            } catch (ServiceException e) {
                e.printStackTrace();
            } catch (RemoteException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

 

Query Status

Great! Message is sent, but now the status you’ve just received says that message was “not delivered yet”. Sending messages could take few seconds, so we added queryStatus in our REST and XML APIs and you can use it with our Java API Library. See how:

Again, let’s initialize TeleMessage: TeleMessage tm = new TeleMessage();

Now, we need to prepare HttpClient. It’s same as sending message with only one difference: we need to send our request to “Query Status” gateway – HttpPost httppost = new HttpPost(tm.getStatusURL(TeleMessage.Interface.JSON));

Do you remember message id and message key received from sending message response? Let’s use them:

tm.writeQueryStatus("john_donne", "password", 353381226, "731815630040821905088475443869", TeleMessage.Interface.JSON, by);

Next we need to execute HttpClient post request and the last action is parse response:

InputStream in = resp.getEntity().getContent();

try {
    StatusMessageResponse r = tm.readQueryStatusResponse(in, TeleMessage.Interface.JSON);

If response is OK, it means authentication details are correct and the message id and message key are valid. We can run over an array of recipients to check status for every recipient separately:

     System.out.println("Response is " + r.getResultCode() + 
        ", description " + r.getResultDescription() + 
        ", message Id " + r.getMessageID() + ", message key " + r.getMessageKey());
     if (r.getRecipients() != null && r.getRecipients().length > 0) {
            for (RecipientStatus rs : r.getRecipients()) {
                 System.out.println("Status is " + rs.getStatus() + 
                     " and description is \"" + rs.getDescription() + 
                     "\" for recipient " + rs.getRecipient().getValue());
            }
     }
} finally {
     if (in != null)
           IOUtils.closeQuietly(in);
}

See complete examples below: 

package examples.json;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import telemessage.TeleMessage;
import telemessage.web.services.MessageResponse;
import telemessage.web.services.Recipient;
import telemessage.web.services.RecipientStatus;
import telemessage.web.services.StatusMessageResponse;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class HttpPostQueryStatusExample {
    public static void main(String...args) {
        TeleMessage tm = new TeleMessage();

        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(tm.getStatusURL(TeleMessage.Interface.JSON));
            ByteArrayOutputStream by = new ByteArrayOutputStream();
            tm.writeQueryStatus("john_donne", "password", 353381226, "731815630040821905088475443869", TeleMessage.Interface.JSON, by);

            ByteArrayEntity entity = new ByteArrayEntity(by.toByteArray(), ContentType.create("application/json", "UTF-8"));
            httppost.setEntity(entity);

            HttpResponse resp = httpclient.execute(httppost);
            if (resp != null && resp.getStatusLine().getStatusCode() == 200) {
                InputStream in = resp.getEntity().getContent();
                try {
                    StatusMessageResponse r = tm.readQueryStatusResponse(in, TeleMessage.Interface.JSON);
                    System.out.println("Response is " + r.getResultCode() + ", description " + r.getResultDescription() + ", message Id " + r.getMessageID() + ", message key " + r.getMessageKey());
                    if (r.getRecipients() != null && r.getRecipients().length > 0) {
                        for (RecipientStatus rs : r.getRecipients()) {
                            System.out.println("Status is " + rs.getStatus() + " and description is \"" + rs.getDescription() + "\" for recipient " + rs.getRecipient().getValue());
                        }
                    }
                } finally {
                    if (in != null)
                        IOUtils.closeQuietly(in);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package examples.xml;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import telemessage.TeleMessage;
import telemessage.web.services.RecipientStatus;
import telemessage.web.services.StatusMessageResponse;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class HttpPostQueryStatusXMLExample {
    public static void main(String...args) {
        TeleMessage tm = new TeleMessage();

        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(tm.getStatusURL(TeleMessage.Interface.XML));
            ByteArrayOutputStream by = new ByteArrayOutputStream();
            // message id and message key received by sending message
            tm.writeQueryStatus("john_donne", "password", 35738123, "731815630040821905088475443969", TeleMessage.Interface.XML, by);

            ByteArrayEntity entity = new ByteArrayEntity(by.toByteArray(), ContentType.create("application/json", "UTF-8"));
            httppost.setEntity(entity);

            HttpResponse resp = httpclient.execute(httppost);
            if (resp != null && resp.getStatusLine().getStatusCode() == 200) {
                InputStream in = resp.getEntity().getContent();
                try {
                    StatusMessageResponse r = tm.readQueryStatusResponse(in, TeleMessage.Interface.XML);
                    System.out.println("Response is " + r.getResultCode() + ", description " + r.getResultDescription() + ", message Id " + r.getMessageID());
                    if (r.getRecipients() != null && r.getRecipients().length > 0) {
                        for (RecipientStatus rs : r.getRecipients()) {
                            System.out.println("Status is " + rs.getStatus() + " and description is \"" + rs.getDescription() + "\" for recipient " + rs.getRecipient().getValue());
                        }
                    }
                } catch (Exception e) {
                    System.out.println("Invalid XML or invalid data");
                } finally {
                    if (in != null)
                        IOUtils.closeQuietly(in);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package examples.soap;

import generated.*;

import javax.xml.rpc.ServiceException;
import java.rmi.RemoteException;
import java.util.Date;

public class QueryStatusExample {
    public static void main(String...args) {
        try {
            Sender s = new SenderServiceLocator().gettelemessage();
            AuthenticationDetails a = new AuthenticationDetails("password","john_donne");
            // message id and message key received by sending message
            StatusMessageResponse sr = s.queryStatus(a, 353381235, "731815630040821905088475443889");
            System.out.println("result status: " + sr.getResultCode());
            if (sr.getResultCode() == 0 || sr.getResultCode() == 100) {
                for (RecipientStatus rt : sr.getRecipients()) {
                    System.out.println("Date: " + (new Date(rt.getStatusDate())) + ", message status: " + rt.getStatus() + ", status description: " + rt.getDescription() + " for recipient " + rt.getRecipient().getValue());
                }
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}

Explore additional code samples and developer resourcesPHP LibraryREST APISOAP APIXML APIHTTP API, and more