package jtwitter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.util.encoders.Base64;
import org.xml.sax.SAXException;
import android.util.Log;
/**
* TwitterRequestSender sends http requests to the Twitter web service.
*
* @author Lukasz Grzegorz Maciak
*
*/
public class TwitterConnection {
private static String PUBLIC_TIMELINE_URL = "presentlyapp.com/api/twitter/statuses/public_timeline.xml";
private static String FRIENDS_TIMELINE_URL = "presentlyapp.com/api/twitter/statuses/friends_timeline.xml";
private static String UPDATE_URL = "presentlyapp.com/api/twitter/statuses/update.xml";
private static String USER_AGENT = "Mozilla/4.5";
private static String PROTOCOL = "https://";
private static String TAG = "TwitterConnection";
private String username;
private String password;
private String subdomain;
public TwitterConnection(String subdomain, String username, String password) {
this.subdomain = subdomain;
this.username = username;
this.password = password;
}
/**
* Get the public timeline in XML format.
*
* @return TwitterResponse containing the public timeline entries
* @throws IOException
*/
public TwitterResponse getPublicTimeline() throws Exception {
return new TwitterResponse().parse(getRequest(PUBLIC_TIMELINE_URL));
}
/**
* Get the user's friends timeline (what you see on the homepage) with basic
* authentication.
*
* @return TwitterResponse containing the friends timeline entries
* @throws IOException
*/
public TwitterResponse getFriendsTimeline() throws ParseException, SAXException, ParserConfigurationException, IOException, TwitterConnectionException {
return new TwitterResponse().parse(getRequest(FRIENDS_TIMELINE_URL));
}
/**
* Update your Twitter status.
*
* @param text
* String containing text you want to update your status with
* @return TwitterResponse containing response from Twitter server
* @throws IOException
*/
public TwitterResponse updateStatus(String text) throws ParseException, SAXException, ParserConfigurationException, IOException, TwitterConnectionException {
TwitterResponse twitterResponse = null;
if (text.length() > 140) {
throw new IllegalArgumentException("Update text is longer than 140 characters");
}
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("status", text));
twitterResponse = new TwitterResponse().parse(postRequest(UPDATE_URL, new UrlEncodedFormEntity(nvps)));
return twitterResponse;
}
/**
* Sends a GET request to Present.ly
*
* @param resource
* @return String response from the server
*/
private String getRequest(String resource) {
String result = null;
String url = PROTOCOL + subdomain + "." + resource;
Log.d(TAG, "GET: " + url);
HttpClient client = new DefaultHttpClient(new BasicHttpParams());
HttpGet getMethod = new HttpGet((url));
try {
getMethod.setHeader("User-Agent", USER_AGENT);
getMethod.addHeader("Authorization", "Basic " + getCredentials());
HttpResponse httpResponse = client.execute(getMethod);
result = retrieveInputStream(httpResponse.getEntity());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
} finally {
getMethod.abort();
}
return result;
}
/**
* Sends a POST request to Present.ly
*
* @param resource
* @param formParams UrlEncodedFormEntity which is comprised of a List of NameValuePairs
* @return String response from the server
*/
private String postRequest(String resource, UrlEncodedFormEntity formParams) throws SocketTimeoutException, SocketException {
String result = null;
String url = PROTOCOL + subdomain + "." + resource;
Log.d(TAG, "POST: " + url);
HttpClient client = new DefaultHttpClient(new BasicHttpParams());
HttpPost postMethod = new HttpPost((url));
try {
postMethod.setHeader("User-Agent", USER_AGENT);
postMethod.addHeader("Authorization", "Basic " + getCredentials());
if (formParams != null)
postMethod.setEntity(formParams);
HttpResponse httpResponse = client.execute(postMethod);
result = EntityUtils.toString(httpResponse.getEntity());
if (result != null)
Log.d(TAG, "Returned response [" + httpResponse.getStatusLine() + "] from the server: " + result);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
} finally {
postMethod.abort();
}
return result;
}
/**
* Retrieves the content input stream from a GET request
*
* @param httpEntity
* @return
*/
private String retrieveInputStream(final HttpEntity httpEntity) {
int length = (int) httpEntity.getContentLength();
StringBuffer stringBuffer = new StringBuffer(length);
try {
InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);
char buffer[] = new char[length];
int count;
while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {
stringBuffer.append(buffer, 0, count);
}
} catch (UnsupportedEncodingException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
} catch (IllegalStateException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
return stringBuffer.toString();
}
private String getCredentials() {
return new String(Base64.encode((username + ":" + password).getBytes()));
}
}