Java

This tutorial provides you with a step-by-step walkthrough on how to send a message using the Live Link 365 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
 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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package org.sinch;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import java.util.Base64;
import java.util.Scanner;
import java.net.Proxy;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/* Introduction.
 * In this Tutorial we will write a simple python code that can send a message to any phone number
 * You can run this application either on Terminal or in your preferred IDE.
 * The application will receive 2 input parameters that will be asked for the user upon its execution
 * First parameter will be the Message to be sent.
 * Second parameter will be the phone that will receive the message (Phone numbers have to be in E.164 format). 
 * Requirements:
 * Basic Programming experience with Java.
 * org.json library dependency
 * Generated an app_key and app_secret through the Live Link 365 Portal
 * For that, go to the portal https://livelink.sapdigitalinterconnect.com/guides/
 * Then go to Getting Started >> Step 3: Create your first APP Key
 */

// _Step_1
import org.json.*; //You will need to add org.json library dependency in order to run this project.

public class Main 
{
    /* Step 1: SETUP ENVIRONMENT VARIABLES
     *  On this step we will setup all the needed Variables to make the Live Link 365 System Work.
     *  baseUrl -> the Live Link 365 URL that will be used to make the calls to Live Link 365 API
     *  appKey -> the key generated through the Live Link 365 Portal
     *  appSecret -> the secret that you received when creating a new app_key through the Live Link 365 Portal
     *  defaultOrigin -> that is the origin that you want the phone number to receive messages from.
     */
    public static String baseUrl;
    public static String appKey;
    public static String appSecret; //Insert your generated app secret here
    public static String defaultOrigin; //Insert your default origin here

    //Extra info: If you are Behind a corporate proxy, you need to set the proxy to send HTTP Calls.
    //public static Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy", 8080));
    public static Proxy proxy = null;

    // _Step_3
    public static StringBuilder getStreamString(InputStream stream) throws IOException {
        InputStreamReader inputStreamReader = new InputStreamReader(stream);
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuilder response = new StringBuilder();
        String inputLine;
        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();
        return response;
    }

    public static Properties loadProperties(String filePath) throws IOException {
        Properties prop = new Properties();
        InputStream input = null;
        ClassLoader loader = Thread.currentThread().getContextClassLoader();

        try {
            input = loader.getResourceAsStream(filePath);
            // load a properties file
            prop.load(input);
            baseUrl = prop.getProperty("baseUrl");
            appKey = prop.getProperty("appKey");
            appSecret = prop.getProperty("appSecret");
            defaultOrigin = prop.getProperty("defaultOrigin");
        } catch (IOException ex) {
            ex.printStackTrace();
            throw ex;
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return prop;
    }

    // _Step_4: Defining Function to retrieve the oAuth2 access_token through client_credentials

    public static String getAccessToken() throws IOException {
        return  getAccessToken(appKey, appSecret);
    }

    public static String getAccessToken(String key, String secret) throws IOException
    {
        System.out.println("...... executing authorization request with key: " + key + " " + secret);
        String tokenUrl = baseUrl + "/oauth/token";
        String bearer = key + ":" + secret;
        String bearerEncoded = Base64.getEncoder().encodeToString(bearer.getBytes());

        URL url = new URL(tokenUrl);
        if(proxy != null){
            url.openConnection(proxy);
        }
        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 " + bearerEncoded);
        connection.setDoOutput(true);
        DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
        writer.writeBytes("grant_type=client_credentials");
        writer.flush();
        writer.close();

        if(connection.getResponseCode() != 200){
            JSONObject error = new JSONObject(getStreamString(connection.getErrorStream()).toString());
            System.out.printf("..... Error: " + connection.getResponseCode() + " - " + error.getString("userMessage"));
            return "";
        }

        JSONObject responseToken = new JSONObject(getStreamString(connection.getInputStream()).toString());
        String accessToken = responseToken.getString("access_token");

        System.out.println("..... authorization request successful, access token: " + accessToken);

        return accessToken;
    }

    /* _Step_5: Function to send message with two mandatory parameters, message and destination.
     * When calling this function, this will use requests library to prepare an HTTP Call
     * This HTTP Call will have an Authorization Header with a Bearer accessToken that was retrieved from the getAccessToken function.
     */
    public static void sendSMS(String message, String destination) throws IOException
    {
        String messageUrl = baseUrl + "/v2/sms";
        String bearer = getAccessToken();
        if(bearer.isEmpty()){
            return;
        }

        JSONObject messageObject = new JSONObject()
                .put("message", message)
                .put("origin", defaultOrigin)
                .put("destination", destination);

        URL url = new URL(messageUrl);
        if(proxy != null){
            url.openConnection(proxy);
        }
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty ("Authorization", "Bearer " + bearer);
        connection.setDoOutput(true);
        DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
        writer.writeBytes(messageObject.toString());
        writer.flush();
        writer.close();

        if(connection.getResponseCode() != 200){
            JSONObject error = new JSONObject(getStreamString(connection.getErrorStream()).toString());
            System.out.printf("..... Error: " + connection.getResponseCode() + " - " + error.getString("userMessage"));
            return;
        }

        System.out.println("..... Message sent successfully.");
        return;
    }

    /* _Step_6
     * Now we will write a program that receives 2 inputs
     * First it will ask for the Message that you want to send
     * Then it will ask for the phone number that you want to send the message to.
     */
    public static void main(String[] args) {
        try {
            loadProperties("config.properties");
            System.out.print("What do you want to say(text message): ");
            Scanner scanner = new Scanner(System.in);
            String message = scanner.nextLine();
            System.out.print("Who do you want to send to(phone number): "); //Phone numbers have to be in E.164 format.
            scanner = new Scanner(System.in);
            String destination = scanner.nextLine();
            System.out.println("****************************************");
            System.out.println("Sending: " + message);
            System.out.println("To: " + destination);
            sendSMS(message, destination);
        } catch (IOException ex){
            ex.printStackTrace();
            System.out.println("..... Error at sending the message");
        }

    }
}
1
2
3
4
5
6
7
8
#_Step_2: Define global access varaibles in properties file
baseUrl=https://livelink.sapdigitalinterconnect.com/api
# Insert your generated app key here
appKey=appKey
# Insert your generated app secret here
appSecret=appSecret
# Insert your default origin here
defaultOrigin=