Saturday, January 10, 2009

Integrating Oracle Coherence with Twitter

Months ago I wrote a program to integrate Calendar with Twitter. This time I integrated Twitter with Coherence data grid. Programmatically this is no brainer - data are being put in a Coherence Cache and then there is a cache listener that publishes the data (message) to twitter. I am a big fan of Twitter. Simple interface, Revolutionary idea and an Awesome channel. So what I did is expanded my implementation of JMS Subscriber for Oracle Coherence and added an interface to tweet the JMS Message. Read more about ezMQ here.... Following is a sample code that is a subscriber of Coherence Topic and a Publisher to Twitter:

public class Subscriber implements MessageListener {

private String un = "<your_twitter_account_id>";
private String pw = "<your_twitter_password>";

public Subscriber() {
}

private void twitter (String message) throws MalformedURLException,
IOException {
String credentials =
new BASE64Encoder ().encode ((un + ":" + pw).getBytes());
URL url = new URL ("http://twitter.com/statuses/update.xml");
URLConnection uC = url.openConnection();
uC.setDoOutput(true);
uC.setRequestProperty("Authorization", "Basic " + credentials);
OutputStreamWriter wR = new OutputStreamWriter (uC.getOutputStream());
wR.write("&status=" + message);
wR.flush();
wR.close();

// -- Get the response back
BufferedReader bR =
new BufferedReader (new InputStreamReader (uC.getInputStream()));
String line = null;
while ((line = bR.readLine()) != null) {
System.out.println(line);
}
bR.close ();
}

public static void main(String[] args)
throws Exception {
Subscriber s = new Subscriber ();
InitialContext ctx = new InitialContext();

// -- Create
TopicConnectionFactory factory =
(TopicConnectionFactory) ctx.lookup("TopicConnectionFactory");

// -- Connecting to Proxy
TopicConnection connection = factory.createTopicConnection();

// -- This is a NamedCache
Topic topic = (Topic) ctx.lookup("Topic");

TopicSession subSession =
connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
TopicSubscriber subscriber = subSession.createSubscriber(topic);
subscriber.setMessageListener(s);

System.out.println("Click to end");
System.in.read();
}

public void onMessage(Message message) {
try {
TextMessage tMsg = (TextMessage) message;
String text = tMsg.getText();
// -- Send the message to Twitter
twitter(text);

} catch (JMSException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace ();
} catch (IOException e) {
e.printStackTrace ();
}
}
}
Enjoy!

1 comment:

Sumeet said...

where is oracle coherence code?