Java

This is walkthrough showing you how to connect Live Link 365's SMS sending API to a flight booking app. This sample creates the model of a flight's booking information and sends an SMS notification to a phone number.

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
package org.sinch;

import java.util.Date;

// _Step_1
public class CustomerDetails
{

    String customerFirstName;
    String CustomerLastName;
    String CustomerMobNo;
    String cUserName;

    //add cutomer details
    public void addCustomer(String firstname,String lastName,String CustomerMobNo,String cUserName)
    {
        this.customerFirstName=firstname;
        this.CustomerLastName=lastName;
        this.CustomerMobNo=CustomerMobNo;
        this.cUserName=cUserName;

    }
    //get customer details
    public String getCustomerFirstName()
    {
        return customerFirstName;

    }
    public String getCustomerLastName()
    {
        return customerFirstName;

    }
    public String getCustomerMobNo()
    {
        return CustomerMobNo;

    }
    public String getcUserName()
    {
        return cUserName;

    }

}
  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
package org.sinch;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import org.sinch.MessageHandler;

// _Step_2
public class FlightInformation
{

    String deptTime;
    String arrTime;
    String from;
    String to;
    String flighID;
    int noOfSeats = 10;
    int noOFSeatsbooked = 6;
    static int availablesSeats;
    static CustomerDetails customerDetails;
    static List<FlightInformation> flightInfoList;
    static FlightInformation flightInfo1 = null;
    static FlightInformation flightInfo2 = null;
    static Properties CONFIG = null;
    static FlightInformation finalFlight;
    int randNum;
    static String deptTime1 = "11.30 AM";
    static String NewDeptTime = "3.00 PM";
    static MessageHandler handler;
    static String appKey;
    static String appSecret;

    public void addFlightDetails(String flighID, String from, String to, String deptTime, String arrTime)
    {
        /*
         * if (noOfFlight < Max) { flights[noOfFlight] = new flightInfo(from,
         * to, deptTime, arrTime, totalCost); noOfFlight++; } else
         */
        this.flighID = flighID;
        this.from = from;
        this.to = to;
        this.deptTime = deptTime;
        this.arrTime = arrTime;

    }

    public String getfromCity()
    {
        return from;
    }

    public String getToCity()
    {
        return to;
    }

    public String getDeptTime()
    {
        return deptTime;
    }

    public String getArrTime()
    {
        return arrTime;
    }

    public String getflighID()
    {
        return flighID;
    }

    public FlightInformation searchFlight()
    {
        Random rand = new Random();
        randNum = rand.nextInt(2);
        if (randNum == 0)
        {
            return flightInfo1;
        }
        else
        {
            if (randNum == 1)
                return flightInfo2;
        }
        return null;
    }


    public void bookFlight(FlightInformation finalFlight) throws MalformedURLException, IOException
    {
        customerDetails.addCustomer(CONFIG.getProperty("customerFirstName"), CONFIG.getProperty("cusomerLastName"), CONFIG.getProperty("contactNo"), CONFIG.getProperty("customerUsername"));
        String messageString = "Hi  " + customerDetails.customerFirstName
                               + " your flight has been booked with seat Number: " + getAvailableSeatsAndAssign(1) + " from "
                               + finalFlight.searchFlight().getfromCity() + " to " + finalFlight.searchFlight().getToCity()
                               + " departuring at " + finalFlight.searchFlight().getDeptTime();


        // int account_number = #ACCOUNT_ID; //Replace with your account number.
        appKey = CONFIG.getProperty("appKey");
        appSecret = CONFIG.getProperty("appSecret");
        String destinationNumber = customerDetails.getCustomerMobNo(); //substitute with your destination number.
        handler.sendSMS( messageString, destinationNumber, handler.getAccessToken(appKey, appSecret));


    }


    public String getAvailableSeatsAndAssign(int NoOFpeople)
    {
        String FlightID = finalFlight.getflighID();
        boolean booked = false;
        availablesSeats = noOfSeats - noOFSeatsbooked;
        if (availablesSeats != 0 && availablesSeats >= NoOFpeople)
        {
            booked = true;
            Random rand = new Random();
            int seatNumberAssign = rand.nextInt(availablesSeats);
            return FlightID + "_" + seatNumberAssign;
        }
        else
        {
        }
        return (String) null;
    }

    public void modifyDepartTime(String NewDeptTime)
    {

        deptTime1 = NewDeptTime;
    }

    public String checkIfFlightIsDelayed()
    {
        if(finalFlight.searchFlight().getDeptTime() != NewDeptTime)
        {

            return deptTime1;
        }
        return arrTime;

    }

    // _Step_6
    public static void main(String args[]) throws MalformedURLException, IOException
    {
        CONFIG = new Properties();
        try
        {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            CONFIG.load(loader.getResourceAsStream("config.properties"));

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        handler = new MessageHandler(CONFIG.getProperty("baseUrl"));
        flightInfo1 = new FlightInformation();
        flightInfo2 = new FlightInformation();
        flightInfo1.addFlightDetails(CONFIG.getProperty("flightID1"), CONFIG.getProperty("fromCity1"), CONFIG.getProperty("toCity1"), CONFIG.getProperty("deptTime1"), CONFIG.getProperty("arrTime1"));
        flightInfo2.addFlightDetails(CONFIG.getProperty("flightID2"), CONFIG.getProperty("fromCity2"), CONFIG.getProperty("toCity2"), CONFIG.getProperty("deptTime2"), CONFIG.getProperty("arrTime2"));
        customerDetails = new CustomerDetails();// get customer details
        finalFlight = flightInfo1.searchFlight();// search for flights
        flightInfo1.bookFlight(finalFlight); //book flight  and send SMS
        flightInfo1.modifyDepartTime(NewDeptTime);//this will modify the actual flight time
        flightInfo1.checkIfFlightIsDelayed();// it will check if flight is delayed and send SMS

    }
}
 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
# _Step_3
#Flight 1 data
flightID1=UNI101
fromCity1=New York
toCity1=Chicago;
deptTime1=11.30 AM
String arrTime1=1.00 PM

#Flight 2 data
flightID2=AXU201
fromCity2=Boston
toCity2=Miami
deptTime2=11.10 AM
arrTime2=2.00 PM
cost2=250
NewDeptTime=3.00 PM

customerFirstName=Mr.Sam
customerLastName=George
contactNo=1234
customerUsername=SAMG

baseUrl=hhttps://livelink.sapdigitalinterconnect.com/api
# Insert your generated app key here
appKey=appKey
# Insert your generated app secret here
appSecret=appSecret
  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
package org.sinch;

import org.json.*;
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 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 = "{" + " \"message\": \"" + message + "\"," //This is the string that will be shown to the user.
//                          + " \"destination\": \"" + destination + "\"," //Place here the destination number(s). Phone numbers have to be in E.164 format.
//                          + "}";
        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();
    }
}