Skip to content

Oneapi java tutorial

pr1001 edited this page Dec 10, 2011 · 2 revisions

OneAPI Java Example

The following is a short tutorial on using Java to program with the example OneAPI Java libraries distributed by the GSM Association.

This is a short example based on the following scenario

  • Our user wants to find a movie to see at a cinema/ theatre
  • They can start the service by sending the keyword ‘Movie’ to our service number
  • They are then sent a URL to a browse and book service
  • The service is location enabled and will return results based on the user’s location
  • The user can ask to be sent a short video clip of any film they are interested in
  • The user makes an initial request for a standard seat
  • They then select to upgrade to a premium seat
  • The booking is then confirmed and payment made

In this example we are not going to show any of the service code – just the interactions that need to be made with the OneAPI server.

This example assumes the reader is an experienced Java programmer with a complete understanding of Java application design and build processes. We are going to provide only snippets of code related to use of OneAPI. All of the examples have been checked through the java compiler but more work would be needed to create a complete service

Notes

In this example an example service provider has provided a customized version of the OneAPI Java libraries. This includes a set of ‘Service Endpoints’ – distinct URLs that point to their OneAPI server. These Service Endpoints are provided in the Java class com.serviceprovider.SPEndpoints which is available on the application’s Java build/run classpath.

Part 1 : Initialising the SMS Message Receive subscription

This first Java class simply sets up a one time subscription to the OneAPI server so that incoming SMS messages will trigger a servlet call.

import com.serviceprovider.SPEndpoints;

import org.gsm.oneapi.endpoints.ServiceEndpoints;
import org.gsm.oneapi.endpoints.ServiceEndpointsInterface;
import org.gsm.oneapi.foundation.JSONRequest;
import org.gsm.oneapi.responsebean.sms.SMSMessageReceiptSubscriptionResponse;
import org.gsm.oneapi.sms.SMSRetrieve;

import org.apache.log4j.BasicConfigurator;
import javax.servlet.http.HttpServletResponse;

public class CreateSMSReceiveSubscription {

	public static void main(String[] args) {		
		BasicConfigurator.configure(); // Initialise log4j logging 
		
		ServiceEndpointsInterface serviceEndpoints = new SPEndpoints();

		String authenticationUsername="appvendor1";
		String authenticationPassword="pass1234";
		
		/*
		 * The SMSRetrieve class contains the function we need to set up an SMS receipt subscription
		 */
		SMSRetrieve receiveFunctions=new SMSRetrieve(serviceEndpoints, authenticationUsername, authenticationPassword);

		String notifyURL="http://www.appvendor1.com/services/SMSReceivedServlet";

		SMSMessageReceiptSubscriptionResponse receiptSubscription=
						receiveFunctions.subscribeToReceiptNotifications(
								"3456", 			// Destination address
								notifyURL, 			// The URL to invoke
								"Movies", 			// Keyword to match
								"JSON", 			// Response type required
								"12345", 			// Client correlator
								"SendMoviesURL"); 		// CallbackData

		if (receiptSubscription!=null) {
			if (receiptSubscription.getHTTPResponseCode()==HttpServletResponse.SC_CREATED) {
				System.out.println("Your subscription has been created");
				System.out.println("The resourceURL is "+receiptSubscription.getResourceReference().getResourceURL());
			}
		}	
	}
}

Part 2 : The Java servlet receiving an incoming SMS message and sending a response

In this second class the servlet is invoked when an SMS is received. It will then send the URL to the movie tickets service to the mobile user requesting it.

import com.serviceprovider.SPEndpoints;

import org.gsm.oneapi.sms.SMSRetrieve;
import org.gsm.oneapi.sms.SMSSend;
import org.gsm.oneapi.endpoints.ServiceEndpoints;
import org.gsm.oneapi.endpoints.ServiceEndpointsInterface;
import org.gsm.oneapi.responsebean.sms.InboundSMSMessageNotification;
import org.gsm.oneapi.responsebean.sms.InboundSMSMessage;
import org.gsm.oneapi.responsebean.sms.SMSSendResponse;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;

public class SMSReceivedServlet extends HttpServlet {

	private static ServiceEndpointsInterface serviceEndpoints = new SPEndpoints();
	
	private String authenticationUsername="appvendor1";
	private String authenticationPassword="pass1234";
	
	private SMSSend sender=new SMSSend(serviceEndpoints, authenticationUsername, authenticationPassword);

	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
	
		// Decode the JSON data in the request body
		InboundSMSMessageNotification inboundSMSMessageNotification=
				SMSRetrieve.convertInboundSMSMessageNotification(request);
		
		// Check for an inbound SMS
		if (inboundSMSMessageNotification!=null) {
			InboundSMSMessage smsMessage=inboundSMSMessageNotification.getInboundSMSMessage();
			
			// Check the message starts with the keyword "movies"
			if (smsMessage!=null && 
					smsMessage.getMessage()!=null && 
					smsMessage.getMessage().trim().toLowerCase().startsWith("movies")) {
				
				// Prepare the SMS reply
				String destinationAddress=smsMessage.getSenderAddress();
				String[] addressList={"tel:"+destinationAddress};
				
				String senderAddress="3456";
				String clientCorrelator=null;
				String notifyURL=null; // Not needed
				String senderName="LocalMovies";
				String callbackData=null;			
				
				// Send the SMS response
				SMSSendResponse smsResponse=sender.sendSMS(senderAddress, addressList, 
							"Local movies on show at http://appvendor1.com/LocalMovies.jsp", 
							clientCorrelator, notifyURL, senderName, callbackData);
				
				if (smsResponse!=null) {
					if (smsResponse.getHTTPResponseCode()==HttpServletResponse.SC_CREATED) {
						System.out.println("Send request: "+smsResponse.getResourceReference().getResourceURL());
					}
				}
			}
		}
		response.setStatus(HttpServletResponse.SC_ACCEPTED);
	}
}

Part 3 : Locating the mobile user

In this third part the location of the mobile user is determined. The example assumes that the MSISDN of the mobile user has been stored within the session – though this could instead come from other mechanisms provided by the mobile network or otherwise determined.

import com.serviceprovider.SPEndpoints;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import org.gsm.oneapi.location.Locate;
import org.gsm.oneapi.responsebean.location.LocationResponse;
import org.gsm.oneapi.responsebean.location.TerminalLocation;
import org.gsm.oneapi.endpoints.ServiceEndpointsInterface;

public class LocateNearestServlet extends HttpServlet {

	private static ServiceEndpointsInterface serviceEndpoints = new SPEndpoints();
	
	private String authenticationUsername="appvendor1";
	private String authenticationPassword="pass1234";

	private Locate locator=new Locate(serviceEndpoints, authenticationUsername, authenticationPassword);

	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		
		String terminalAddress=(String) request.getSession().getAttribute("MSISDN");
		
		// Locate terminal to 100 metres accuracy
		LocationResponse locationResponse=locator.locateTerminal("tel:"+terminalAddress, 100);

		// Check there is a server response 
		if (locationResponse!=null && locationResponse.getHTTPResponseCode()==HttpServletResponse.SC_OK) {
						
			if (locationResponse.getTerminalLocationList()!=null) {
				TerminalLocation[] locationData=locationResponse.getTerminalLocationList().getTerminalLocation();
				
				if (locationData!=null && locationData.length==1) {
					
					// Successful location if the retrieval status matches "Retrieved"
					if ("Retrieved".equalsIgnoreCase(locationData[0].getLocationRetrievalStatus())) {
						generateResponse(request, response, 
								locationData[0].getCurrentLocation().getLatitude(),
								locationData[0].getCurrentLocation().getLongitude(),
								locationData[0].getCurrentLocation().getAccuracy());
					} else {
						indicateError(request, response);
					}
				}
			}
		}
	}
	
	private void generateResponse(HttpServletRequest request,HttpServletResponse response,
								  double latitude, double longitude, double accuracy) {
		/* application code goes here */ 
	}

	private void indicateError(HttpServletRequest request,HttpServletResponse response) {
		/* application code goes here */ 
	}
	
}

Part 4 : Sending an MMS including media content

In this fourth part the mobile user has selected a movie and asked to receive a preview clip. This servlet will send both a wallpaper image and a movie clip in the same MMS.

Note this example assumes that a notification will be generated when the MMS is sent. This could be processed in the application logic.

import com.serviceprovider.SPEndpoints;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import java.io.IOException;

import org.gsm.oneapi.mms.MMSSend;
import org.gsm.oneapi.responsebean.mms.MMSSendResponse;

import org.gsm.oneapi.endpoints.ServiceEndpoints;
import org.gsm.oneapi.endpoints.ServiceEndpointsInterface;

public class SendMovieClipServlet extends HttpServlet {

	private static ServiceEndpointsInterface serviceEndpoints = new SPEndpoints();
	
	private String authenticationUsername="appvendor1";
	private String authenticationPassword="pass1234";

	private MMSSend mmsSender=new MMSSend(serviceEndpoints, authenticationUsername, authenticationPassword);

	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		
		String terminalAddress=(String) request.getSession().getAttribute("MSISDN");
		
		String[] addressList={"tel:"+terminalAddress};

		String senderAddress="3456";
		String clientCorrelator=null;
		String notifyURL="http://http://appvendor1.com/ConfirmMMSSentServlet"; 
		String senderName="LocalMovies";
		String callbackData=terminalAddress;			
		
		String message="The Mountain is the critically acclaimed film tracking the trials and tribulations ...";

		MMSSend.Attachment picture=new MMSSend.Attachment("TheMountainWallpaper.jpg", "image/jpeg", "Resources/Wallpapers/TheMountainWallpaper.jpg");
		MMSSend.Attachment movie=new MMSSend.Attachment("TheMountainPreview.mp4", "video/mp4", "Resources/MovieClipes/TheMountainPreview.mp4");
		
		MMSSend.Attachment[] attachments={picture, movie};

		MMSSendResponse  mmsResponse=mmsSender.sendMMS(senderAddress, addressList, message, attachments, senderName, clientCorrelator, 
  notifyURL, callbackData);

		// Check there is a server response 
		if (mmsResponse!=null && mmsResponse.getHTTPResponseCode()==HttpServletResponse.SC_CREATED) {					
			if (mmsResponse.getResourceReference()!=null) {
				System.out.println("Send request: "+mmsResponse.getResourceReference().getResourceURL());
			}
		}
	}
		
}

Part 5 : Making an initial reservation for a standard seat

In this part the application is making a request to reserve a charge of $9.75 on the end user’s mobile account.

import com.serviceprovider.SPEndpoints;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.gsm.oneapi.endpoints.ServiceEndpointsInterface;
import org.gsm.oneapi.payment.Reservation;
import org.gsm.oneapi.responsebean.payment.PaymentResponse;

public class ReserveStandardSeat extends HttpServlet {	
	private static ServiceEndpointsInterface serviceEndpoints = new SPEndpoints();
	
	private String authenticationUsername="appvendor1";
	private String authenticationPassword="pass1234";
	
	Reservation reservation=new Reservation(serviceEndpoints, authenticationUsername, authenticationPassword);

	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		
		String terminalAddress=(String) request.getSession().getAttribute("MSISDN");
		
		String referenceCode="REF-12345";
		String description="Standard Seat"; 
		String currency="USD";
		double amount=9.75;
		String code=null; // Not used
		String clientCorrelator=terminalAddress+"-9:00";
		String onBehalfOf="ABC Cinemas";
		String purchaseCategoryCode="Ticket";
		String channel="Wap";
		double taxAmount=1.85;
		String serviceId="SID-12345";
		String productId="PID-10782123143";
		
		PaymentResponse reserveInitialResponse=reservation.reserveInitialAmount(
				"tel:"+terminalAddress, referenceCode, description, currency,  amount, code, clientCorrelator, 
				onBehalfOf, purchaseCategoryCode, channel, taxAmount, serviceId, productId);
		
		if (reserveInitialResponse!=null && reserveInitialResponse.getHTTPResponseCode()==HttpServletResponse.SC_CREATED) {
			if ("Reserved".equalsIgnoreCase(reserveInitialResponse.getAmountReservationTransaction().getTransactionOperationStatus())) {
request.getSession().putValue("ServerReferenceCode", 
	reserveInitialResponse.getAmountReservationTransaction().getServerReferenceCode());
request.getSession().setAttribute("clientCorrelator", clientCorrelator);
				/* Application continues processing the initial reservation */
			}
		}		
	}
		
}

Part 6 – Increasing the amount reserved for the premium seat upgrade

In this part of the example the application is requesting an increase in the amount reserved on the end user’s account for $4.50

import com.serviceprovider.SPEndpoints;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.gsm.oneapi.endpoints.ServiceEndpointsInterface;
import org.gsm.oneapi.payment.Reservation;
import org.gsm.oneapi.responsebean.payment.PaymentResponse;

public class UpgradeToPremiumSeat extends HttpServlet {
	
	private static ServiceEndpointsInterface serviceEndpoints = new SPEndpoints();
	
	private String authenticationUsername="appvendor1";
	private String authenticationPassword="pass1234";
	
	Reservation reservation=new Reservation(serviceEndpoints, authenticationUsername, authenticationPassword);

	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		
		String terminalAddress=(String) request.getSession().getAttribute("MSISDN");
		
		String referenceCode="REF-12345";
		String description="Premium Seat Upgrade";
		String currency="USD";
		double amount=4.5;
		String code=null; // Not used
		int referenceSequence=2;
		String onBehalfOf="ABC Cinemas";
		String purchaseCategoryCode="Ticket";
		String channel="Wap";
		double taxAmount=0.85;
		String serviceId="SID-12345";
		String productId="PID-10782125678";
		
		PaymentResponse reserveAdditionalResponse=reservation.reserveAdditionalAmount(
				"tel:"+terminalAddress, referenceCode, description, currency,  amount, referenceSequence, code,  
				onBehalfOf, purchaseCategoryCode, channel, taxAmount, serviceId, productId);
				
		if (reserveAdditionalResponse!=null && reserveAdditionalResponse.getHTTPResponseCode()==HttpServletResponse.SC_OK) {
			if ("Reserved".equalsIgnoreCase(reserveAdditionalResponse.getAmountReservationTransaction().getTransactionOperationStatus())) {
				/* Application continues processing the upgrade */
			}
		}		
	}
		
}

Part 7 : Finally the user is charged for the whole amount

The previous reservation is now turned into an actual charge on the end user’s account

import com.serviceprovider.SPEndpoints;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.gsm.oneapi.endpoints.ServiceEndpointsInterface;
import org.gsm.oneapi.payment.Reservation;
import org.gsm.oneapi.responsebean.payment.PaymentResponse;

public class ChargeUser extends HttpServlet {	
	private static ServiceEndpointsInterface serviceEndpoints = new SPEndpoints();
	
	private String authenticationUsername="appvendor1";
	private String authenticationPassword="pass1234";
	
	Reservation reservation=new Reservation(serviceEndpoints, authenticationUsername, authenticationPassword);

	public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		
		String terminalAddress=(String) request.getSession().getAttribute("MSISDN");
		String clientCorrelator=(String) request.getSession().getAttribute("clientCorrelator");
		
		String referenceCode="REF-12345";
		String description="Premium Seat";
		String currency="USD";
		double amount=9.75+4.5;
		String code=null; // Not used
		int referenceSequence=3;
		String onBehalfOf="ABC Cinemas";
		String purchaseCategoryCode="Ticket";
		String channel="Wap";
		double taxAmount=1.85+0.85;
		String serviceId="SID-12345";
		String productId="PID-10782125678";
		String callbackURL=null;
		
		PaymentResponse chargeResponse=reservation.chargeAmount(
				"tel:"+terminalAddress, referenceCode, description, currency, 
				amount, referenceSequence, referenceCode, callbackURL, clientCorrelator, 
				onBehalfOf, purchaseCategoryCode, channel, taxAmount, serviceId, productId);
				
		if (chargeResponse!=null && chargeResponse.getHTTPResponseCode()==HttpServletResponse.SC_OK) {
			if ("Charged".equalsIgnoreCase(chargeResponse.getAmountReservationTransaction().getTransactionOperationStatus())) {
				/* Application continues processing the booking */
			}
		}		
	}
		
}
Clone this wiki locally