Java

This walkthrough will show you how to build an app that listens for tweets from a certain Twitter account, and then routes that tweet to a phone number, through Live Link 365's SMS API.

This is not a production-ready application. Please take your time to enhance it for production so that it meets your specific business requirements.

Steps

Code

keyboard_arrow_down
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# _Step_1
@john_doe= 2343

#Insert your api url here
base_url=https://livelink.sapdigitalinterconnect.com/api
#Insert your generated app key here
app_key=appKey
#Insert your generated app secret here
app_secret=appSecret

consumer_key=ckey
consumer_secret=csecret
access_token=atoken
access_token_secret=asecret
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package org.sinch;

import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

public class App {
    private static String CONSUMER_KEY = "";
    private static String CONSUMER_SECRET = "";
    private static String TOKEN = "";
    private static String TOKEN_SECRET = "";
    private static long[] follower_ids = {};

    private static String LIVELINK_APP_KEY = "";
    private static String LIVELINK_APP_SECRET = "";
    private static String BASE_URL = "";
    static Properties config;
    static MessageHandler handler;

    public static void main(String[] args) throws TwitterException, IOException {

        // _Step_6
        StatusListener listener = new StatusListener() {
            public void onStatus(Status status) {
                String message = status.getText();
                String number = "";
                Enumeration<String> enums = (Enumeration<String>) config.propertyNames();
                while (enums.hasMoreElements()) {
                    String key = enums.nextElement();
                    if (message.contains(key)) {
                        number = config.getProperty(key);
                    }
                }

                if (!number.isEmpty()) {
                    try {
                        String messageText = URLEncoder.encode(message, "UTF-8");
                        System.out.println("Sending Message...");
                        handler.sendSMS(messageText, number, handler.getAccessToken(LIVELINK_APP_KEY, LIVELINK_APP_SECRET));
                    } catch (IOException ex) {
                        Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                System.out.println(status.getUser().getName() + " : " + status.getText() + "  Tweeted AT: " + status.getCreatedAt());
            }

            @Override
            public void onDeletionNotice(StatusDeletionNotice sdn) {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void onTrackLimitationNotice(int i) {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void onScrubGeo(long l, long l1) {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void onException(Exception excptn) {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }

            @Override
            public void onStallWarning(StallWarning sw) {
                throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
            }
        };

        loadProperties();
        CONSUMER_KEY = config.getProperty("consumer_key");
        CONSUMER_SECRET = config.getProperty("consumer_secret");
        TOKEN = config.getProperty("access_token");
        TOKEN_SECRET = config.getProperty("access_token_secret");

        BASE_URL = config.getProperty("base_url");
        LIVELINK_APP_KEY = config.getProperty("app_key");
        LIVELINK_APP_SECRET = config.getProperty("app_secret");
        handler = new MessageHandler(BASE_URL);

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setOAuthConsumerKey(CONSUMER_KEY);
        cb.setOAuthConsumerSecret(CONSUMER_SECRET);
        cb.setOAuthAccessToken(TOKEN);
        cb.setOAuthAccessTokenSecret(TOKEN_SECRET);

        TwitterStreamFactory tf = new TwitterStreamFactory(cb.build());
        TwitterStream twitterStream = tf.getInstance();
        twitterStream.addListener(listener);

        // _Step_2
        FilterQuery query = new FilterQuery();
        query.follow(follower_ids);
        twitterStream.filter(query);
    }

    // _Step_3
    public static void loadProperties() {
        config = new Properties();
        InputStream input = null;
        ClassLoader loader = Thread.currentThread().getContextClassLoader();

        try {
            input = loader.getResourceAsStream("config/config.properties");
            // load a properties file
            config.load(input);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
package org.sinch;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;

public class MessageHandler {
    private String baseURL;

    public MessageHandler(String baseUrl) {
        this.baseURL = baseUrl;
    }

    // _Step_4
    public String getAccessToken(String appKey, String appSecret) throws MalformedURLException, IOException {
        String token_url = this.baseURL + "/oauth/token";
        //Encode your App Key and App Secret in Base64
        String credentials = appKey + ":" + appSecret;
        String credentialsEncoded = Base64.getEncoder().encodeToString(credentials.getBytes());
        //      System.out.println(credentialsEncoded);
        String param = "grant_type=client_credentials";
        String authTokenJsonString = this.postForAccessToken(token_url, param, credentialsEncoded);
        JSONObject object = new JSONObject(authTokenJsonString);
        //At this point, you will have retrieved your json string, which should be parsed.
        //There are many third parties available for this.
        //From the json string, extract the "access_token" attribute and return it in this function.
        //return "access_token"; //Return the "access_token" field from the json string.
        return object.getString("access_token");
    }

    public String postForAccessToken(String path, String data, String authenticationToken) throws MalformedURLException, IOException {
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization", "Basic " + authenticationToken);
        connection.setDoOutput(true);
        DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
        writer.writeBytes(data);
        writer.flush();
        writer.close();
        InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuilder response = new StringBuilder();
        String inputLine;
        while ((inputLine = reader.readLine()) != null) response.append(inputLine);
        reader.close();
        return response.toString();
    }

    // _Step_5
    public void sendSMS(String message, String destination, String authenticationToken) {
        //Make sure to escape all double quotes inside the json, only the outer quotes for each string should be left unescaped.
        //String postBody = "{" + " \"body\": \"" + message + "\"," //This is the string that will be shown to the user.
        //                  + " \"destination\": \"" + destination + "\"," //Place here the destination number(s)
        //                  + "}";
        JSONObject postBody = new JSONObject()
                .put("message", message)
                .put("destination", destination);
        //
        String url = this.baseURL + "/v2/sms";
        try {
            this.post(url, postBody.toString(), authenticationToken);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //This is a method that does an http post, given the path/url, data (a json string).
    public String post(String path, String data, String authenticationToken) throws MalformedURLException, IOException {
        URL url = new URL(path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        if (authenticationToken != null && !authenticationToken.isEmpty()) {
            connection.setRequestProperty("Authorization", "Bearer " + authenticationToken);
        }
        System.out.println(authenticationToken);
        connection.setDoOutput(true);
        DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
        writer.writeBytes(data);
        writer.flush();
        writer.close();
        InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuilder response = new StringBuilder();
        String inputLine;
        while ((inputLine = reader.readLine()) != null) response.append(inputLine);
        reader.close();
        return response.toString();
    }
}