Skip to content

Instantly share code, notes, and snippets.

@t2-support-gists
Created May 3, 2012 20:59
Show Gist options
  • Select an option

  • Save t2-support-gists/2589444 to your computer and use it in GitHub Desktop.

Select an option

Save t2-support-gists/2589444 to your computer and use it in GitHub Desktop.
WAP Java app1
AT&T API Samples - WAP app 1
------------------------------
This file describes how to set up, configure and run the Java Applications of the AT&T HTML5 Program sample applications.
It covers all steps required to register the application on DevConnect and, based on the generated API keys and secrets,
create and run one's own full-fledged sample applications.
1. Configuration
2. Installation
3. Parameters
4. Running the application
1. Configuration
Configuration consists of a few steps necessary to get an application registered on DevConnect with the proper services and
endpoints, depending on the type of client-side application (autonomous/non-autonomous).
To register an application, go to https://devconnect-api.att.com/ and login with your valid username and password.
Next, choose "My Apps" from the bar at the top of the page and click the "Setup a New Application" button.
Fill in the form, in particular all fields marked as "required".
Be careful while filling in the "OAuth Redirect URL" field. It should contain the URL that the oAuth provider will redirect
users to when he/she successfully authenticates and authorizes your application. For this application, it should point to
the oauth.jsp file inside this application folder. For example, if running on a local machine in a default Tomcat installation,
your OAuth Redirect URL might be http://localhost:8080/SampleApp/oauth.jsp
NOTE: You MUST select WAP Push in the list of services under field 'Services' in order to use this sample application code.
Having your application registered, you will get back an important pair of data: an API key and Secret key. They are
necessary to get your applications working with the AT&T HTML5 APIs. See 'Adjusting parameters' below to learn how to use
these keys.
Initially your newly registered application is restricted to the "Sandbox" environment only. To move it to production,
you may promote it by clicking the "Promote to production" button. Notice that you will get a different API key and secret,
so these values in your application should be adjusted accordingly.
Depending on the kind of authentication used, an application may be based on either the Autonomous Client or the Web-Server
Client OAuth flow (see https://devconnect-api.att.com/docs/oauth20/autonomous-client-application-oauth-flow or
https://devconnect-api.att.com/docs/oauth20/web-server-client-application-oauth-flow respectively).
2. Installation
** Requirements
To run the examples you need a Java environment and at least Apache Tomcat 6, or another Java web server such as Jetty.
** Setting up multiple sample applications simultaneously
In case multiple applications need to be run at the same time, make sure to put each app in a separate folder and
adjust your OAuth Redirect URL accordingly.
3. Parameters
Each sample application contains a config.jsp file. It holds configurable parameters described in an easy to read format.
Please populate the following parameters in config.jsp as specified below:
1) clientIdAut : {set the value as per your registered appliaction 'API key' field value}
2) clientSecretAut : {set the value as per your registered appliaction 'Secret key' field value}
3) FQDN : https://api.att.com
Note: If your application is promoted from Sandbox environment to Production environment and you decide to use production
application settings, you must update parameters 1-2 as per production application details.
4. Running the application
To run the application, put the entire contents of the application folder into a separate folder named SampleApp inside the webapps
folder in your Apache Tomcat home directory. If you have specified a different home directory in Tomcat for your web applications,
put it there instead.
Depending on your security settings in Apache Tomcat, you might need to enable write access to the OauthStorage.jsp file.
Once you start tomcat, typically using the command "<your-tomcat-root-folder>/bin/startup.sh", your application becomes available
in a web browser, so you may visit: http://localhost:8080/SampleApp/WAP.jsp to see it working.
<%
String clientIdAut = "";
String clientSecretAut = "";
String FQDN = "https://api.att.com";
%>
<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
<%@ page import="org.apache.commons.httpclient.*"%>
<%@ page import="org.apache.commons.httpclient.methods.*"%>
<%@ page import="org.json.JSONObject"%>
<%@ page import="org.json.JSONArray"%>
<%@ page import="java.io.*" %>
<%@ include file="OauthStorage.jsp" %>
<%@ include file="config.jsp" %>
<%
//Initialize some variables here, check if relevant variables were passed in, if not then check session, otherwise set default.
String scope = "WAP";
String accessToken = "";
String refreshToken = "";
String expires_in = "";
Long date = System.currentTimeMillis();
//This application uses the Autonomous Client OAuth consumption model
//Check if there is a valid access token that has not expired
if(date < savedAccessTokenExpiry) {
accessToken = savedAccessToken;
} else if(date < savedRefreshTokenExpiry) { //Otherwise if there is a refresh token that has not expired, use that to renew and save to file
String url = FQDN + "/oauth/token";
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
String b = "client_id=" + clientIdAut + "&client_secret=" + clientSecretAut + "&grant_type=refresh_token&refresh_token=" + savedRefreshToken;
method.addRequestHeader("Content-Type","application/x-www-form-urlencoded");
method.setRequestBody(b);
int statusCode = client.executeMethod(method);
JSONObject rpcObject = new JSONObject(method.getResponseBodyAsString());
accessToken = rpcObject.getString("access_token");
refreshToken = rpcObject.getString("refresh_token");
expires_in = rpcObject.getString("expires_in");
savedAccessTokenExpiry = date + (Long.parseLong(expires_in)*1000);
savedRefreshTokenExpiry = date + Long.parseLong("86400000");
method.releaseConnection();
PrintWriter outWrite = new PrintWriter(new BufferedWriter(new FileWriter(application.getRealPath("/OauthStorage.jsp"))), false);
String toSave = "\u003C\u0025\nString savedAccessToken = \"" + accessToken + "\";\nLong savedAccessTokenExpiry = Long.parseLong(\"" + savedAccessTokenExpiry + "\");\nString savedRefreshToken = \"" + refreshToken + "\";\nLong savedRefreshTokenExpiry = Long.parseLong(\"" + savedRefreshTokenExpiry + "\");\n\u0025\u003E";
outWrite.write(toSave);
outWrite.close();
} else if(date > savedRefreshTokenExpiry) { //Otherwise get a new access token and refresh token, and save them to file
String url = FQDN + "/oauth/token";
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
String b = "client_id=" + clientIdAut + "&client_secret=" + clientSecretAut + "&grant_type=client_credentials&scope=" + scope;
method.addRequestHeader("Content-Type","application/x-www-form-urlencoded");
method.setRequestBody(b);
int statusCode = client.executeMethod(method);
JSONObject rpcObject = new JSONObject(method.getResponseBodyAsString());
accessToken = rpcObject.getString("access_token");
refreshToken = rpcObject.getString("refresh_token");
expires_in = rpcObject.getString("expires_in");
savedAccessTokenExpiry = date + (Long.parseLong(expires_in)*1000);
savedRefreshTokenExpiry = date + Long.parseLong("86400000");
method.releaseConnection();
PrintWriter outWrite = new PrintWriter(new BufferedWriter(new FileWriter(application.getRealPath("/OauthStorage.jsp"))), false);
String toSave = "\u003C\u0025\nString savedAccessToken = \"" + accessToken + "\";\nLong savedAccessTokenExpiry = Long.parseLong(\"" + savedAccessTokenExpiry + "\");\nString savedRefreshToken = \"" + refreshToken + "\";\nLong savedRefreshTokenExpiry = Long.parseLong(\"" + savedRefreshTokenExpiry + "\");\n\u0025\u003E";
outWrite.write(toSave);
outWrite.close();
}
%>
<%
String savedAccessToken = "ad13138f408bbdaabbdafa355b0b9ee8";
Long savedAccessTokenExpiry = Long.parseLong("99");
String savedRefreshToken = "eb039c57a6efa7216e06a5114cce4a7f6576f2f3";
Long savedRefreshTokenExpiry = Long.parseLong("99");
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en"><head>
<title>AT&T Sample Application - WAPPush</title>
<meta content="text/html; charset=ISO-8859-1" http-equiv="Content-Type">
<link rel="stylesheet" type="text/css" href="style/common.css"/ >
<script type="text/javascript" src="js/helper.js">
</script>
<body>
<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
<%@ page import="com.sun.jersey.multipart.file.*" %>
<%@ page import="com.sun.jersey.multipart.BodyPart" %>
<%@ page import="com.sun.jersey.multipart.MultiPart" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.List" %>
<%@ page import="com.att.rest.*" %>
<%@ page import="java.net.*" %>
<%@ page import="javax.ws.rs.core.*" %>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="java.util.List,java.util.Iterator"%>
<%@ page import="org.json.*"%>
<%@ page import="org.w3c.dom.*" %>
<%@ page import="javax.xml.parsers.*" %>
<%@ page import="javax.xml.transform.*" %>
<%@ page import="javax.xml.transform.stream.*" %>
<%@ page import="javax.xml.transform.dom.*" %>
<%@ page import="org.apache.commons.httpclient.*"%>
<%@ page import="org.apache.commons.httpclient.methods.*"%>
<%@ page import="org.apache.commons.codec.binary.Base64" %>
<%@ include file="getToken.jsp" %>
<%
String sendWap = request.getParameter("sendWap");
String contentBodyFormat = "FORM-ENCODED";
String address = request.getParameter("address");
if(address==null || address.equalsIgnoreCase("null"))
address = (String) session.getAttribute("addressWap");
if(address==null || address.equalsIgnoreCase("null"))
address = "425-802-8620";
session.setAttribute("addressWap",address);
String fileName = "";
String subject = request.getParameter("subject");
if(subject==null || subject.equalsIgnoreCase("null"))
subject = (String) session.getAttribute("subject");
if(subject==null || subject.equalsIgnoreCase("null"))
subject = "This is a sample WAP Push message.";
session.setAttribute("subject", subject);
String url = request.getParameter("url");
if(url==null || url.equalsIgnoreCase("null"))
url = (String) session.getAttribute("url");
if(url==null || url.equalsIgnoreCase("null"))
url = "http://developer.att.com";
session.setAttribute("url", url);
String priority = "High";
String wapId = "";
String endpoint = FQDN + "/1/messages/outbox/wapPush";
%>
<div id="container">
<!-- open HEADER --><div id="header">
<div>
<div id="hcRight">
<%=new java.util.Date()%>
</div>
<div id="hcLeft">Server Time:</div>
</div>
<div>
<div id="hcRight"><script language="JavaScript" type="text/javascript">
var myDate = new Date();
document.write(myDate);
</script></div>
<div id="hcLeft">Client Time:</div>
</div>
<div>
<div id="hcRight"><script language="JavaScript" type="text/javascript">
document.write("" + navigator.userAgent);
</script></div>
<div id="hcLeft">User Agent:</div>
</div>
<br clear="all" />
</div><!-- close HEADER -->
<div id="wrapper">
<div id="content">
<h1>AT&T Sample Application - WAPPush</h1>
<h2>Feature 1: Send basic WAP message</h2>
</div>
</div>
<form method="post" name="sendWap" >
<div id="navigation">
<table border="0" width="100%">
<tbody>
<tr>
<td width="20%" valign="top" class="label">Phone:</td>
<td class="cell"><input maxlength="16" size="12" name="address" value="<%=address%>" style="width: 90%">
</td>
</tr>
<tr>
<td width="20%" valign="top" class="label">URL:</td>
<td class="cell"><input size="18" name="url" value="<%=url%>" style="width: 90%">
</td>
</tr>
<tr>
<td valign="top" class="label">Service Type:</td>
<td valign="top" class="cell">Service Indication <input type="radio" name="" value="" checked /> Service Loading <input type="radio" name="" value="" disabled /> </td>
</tr>
</tbody></table>
<div class="warning">
<strong>WARNING:</strong><br />
At this time, AT&T only supports Service Type: Service Indication due to security concerns.
</div>
</div>
<div id="extra">
<table border="0" width="100%">
<tbody>
<tr>
<td width="20%" valign="top" class="label">Alert Text:</td>
<td class="cell"><textarea rows="4" name="subject" style="width: 90%"><%=subject%></textarea></td>
</tr>
</tbody></table>
<table>
<tbody>
<tr>
<td><button type="submit" name="sendWap">Send WAP Message</button></td>
</tr>
</tbody></table>
</div>
<br clear="all" />
<div align="center"></div>
</form>
<%
//If Send WAP Push button was clicked, do this.
if(request.getParameter("sendWap")!=null) {
//Check for a few known formats the user could have entered the address, adjust accordingly
String invalidAddress = null;
if((address.indexOf("-")==3) && (address.length()==12))
address = "tel:" + address.substring(0,3) + address.substring(4,7) + address.substring(8,12);
else if((address.indexOf(":")==3) && (address.length()==14))
address = address;
else if((address.indexOf("-")==-1) && (address.length()==10))
address = "tel:" + address;
else if((address.indexOf("-")==-1) && (address.length()==11))
address = "tel:" + address.substring(1);
else if((address.indexOf("-")==-1) && (address.indexOf("+")==0) && (address.length()==12))
address = "tel:" + address.substring(2);
else
invalidAddress = "yes";
if(invalidAddress==null) {
MediaType contentBodyType = null;
String requestBody = "";
MultiPart mPart;
contentBodyType = MediaType.MULTIPART_FORM_DATA_TYPE;
JSONObject requestObject = new JSONObject();
requestObject.put("address", address);
requestBody += requestObject.toString() + "\r\n";
String attachmentBody = "";
attachmentBody += "Content-Disposition: form-data; name=\"PushContent\"\n";
attachmentBody += "Content-Type: text/vnd.wap.si\n";
attachmentBody += "Content-Length: 20\n";
attachmentBody += "X-Wap-Application-Id: x-wap-application:wml.ua\n\n";
attachmentBody += "<?xml version=\"1.0\"?>\n";
attachmentBody += "<!DOCTYPE si PUBLIC \"-//WAPFORUM//DTD SI 1.0//EN\" \"http://www.wapforum.org/DTD/si.dtd\">\n";
attachmentBody += "<si>";
attachmentBody += "<indication href=\"" + url + "\" action=\"signal-medium\" si-id=\"6532\" >\n";
attachmentBody += subject + "\n";
attachmentBody += "</indication>\n";
attachmentBody += "</si>\n";
String encodedAttachment = new String(Base64.encodeBase64(attachmentBody.getBytes()));
mPart = new MultiPart().bodyPart(new BodyPart(requestBody,MediaType.APPLICATION_JSON_TYPE)).bodyPart(new BodyPart(encodedAttachment, MediaType.TEXT_PLAIN_TYPE));
mPart.getBodyParts().get(1).getHeaders().add("Content-Transfer-Encoding", "base64");
mPart.getBodyParts().get(1).getHeaders().add("Content-Disposition","attachment; name=\"\"; filename=\"\"");
mPart.getBodyParts().get(0).getHeaders().add("Content-Transfer-Encoding", "8bit");
mPart.getBodyParts().get(0).getHeaders().add("Content-Disposition","form-data; name=\"root-fields\"");
mPart.getBodyParts().get(0).getHeaders().add("Content-ID", "<startpart>");
mPart.getBodyParts().get(1).getHeaders().add("Content-ID", "<attachment>");
// This currently uses a proprietary rest client to assemble the request body that does not follow SMIL standards. It is recommended to follow SMIL standards to ensure attachment delivery.
RestClient client;
client = new RestClient(endpoint, contentBodyType, MediaType.APPLICATION_JSON_TYPE);
client.addParameter("access_token", accessToken);
client.addRequestBody(mPart);
String responze = client.invoke(com.att.rest.HttpMethod.POST, true);
if (client.getHttpResponseCode() == 200){
JSONObject rpcObject = new JSONObject(responze);
wapId = rpcObject.getString("id");
session.setAttribute("mmsId", wapId);
session.setAttribute("wapId",wapId);
%>
<div class="successWide">
<strong>SUCCESS:</strong><br />
<strong>Message ID:</strong> <%=wapId%>
</div>
<%
} else {
%>
<div class="errorWide">
<strong>ERROR:</strong><br />
<%=responze%>
</div>
<%
}
} else { %>
<div class="errorWide">
<strong>ERROR:</strong><br />
Invalid Address Entered
</div>
<% }
}
%>
<div id="footer">
<div style="float: right; width: 20%; font-size: 9px; text-align: right">Powered by AT&amp;T Virtual Mobile</div>
<p>&#169; 2011 AT&amp;T Intellectual Property. All rights reserved. <a href="http://developer.att.com/" target="_blank">http://developer.att.com</a>
<br>
The Application hosted on this site are working examples intended to be used for reference in creating products to consume AT&amp;T Services and not meant to be used as part of your product. The data in these pages is for test purposes only and intended only for use as a reference in how the services perform.
<br>
For download of tools and documentation, please go to <a href="https://devconnect-api.att.com/" target="_blank">https://devconnect-api.att.com</a>
<br>
For more information contact <a href="mailto:developer.support@att.com">developer.support@att.com</a>
</div>
</div>
</body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment