Showing posts with label Groovy. Show all posts
Showing posts with label Groovy. Show all posts

27 November 2010

Send SMS Text Message from Java/Groovy - via Twitter

Writing code to send an SMS text message is fairly easy on a smart phone like an Android.  But from a desktop, sending texts is still a mess, not always free, and/or requires a phone connected to your server.

I simply want to send a message to my phone when my app receives some data.  I don't need a complex library with lots of setup nor do I want to sign up for a pay service.

Now this isn't the cleanest solution to text from an app but Twitter can send messages to your phone when people you follow update their status, when someone mentions or replies to you, or when you get a direct message.

My last two write-ups, "Send a Simple Tweet with OAuth and Groovy" and "Send a Direct Message Tweet with Groovy" showed how easy it is to use Java/Groovy and the Twitter4J library to send messages to your own Twitter account or a message to anyone else.

By sending a tweet to an account that you follow or a Direct Message to your own account, Twitter can be setup to forward that message to a phone that you associate with your account.

Simply go to your Twitter account, Settings, Mobile and follow the easy instruction. Then use one of the sample apps from my previous posts and tweet-text away!

Note:
  • This only allows you to tweet-text to phones that have been setup to follow accounts. 
  • This does not allow you to send a text to a cell phone not registered with Twitter.
  • This works for what I need.
  • Do you know a better/easier, free method?  Write a comment!


What do you think? Leave a comment.

Send a Direct Message Tweet with Groovy

Alright.  Using the Twitter4J library and Groovy, I've beaten down the OAuth beast and have a simple example app to send a "update status" tweet.

Now instead of sending a message to my own account, let's do a real easy mod to send a Direct Message to a specific user   Using the same app as before, the only changes needed are:

  • import DirectMessage
  • change from twitter.updateStatus(message) to twitter.sendDirectMessage(screenName, message)
import twitter4j.DirectMessage;
import twitter4j.Twitter
import twitter4j.TwitterFactory
import twitter4j.Status
import twitter4j.http.AccessToken
import twitter4j.http.RequestToken
import java.io.BufferedReader
import com.thoughtworks.xstream.XStream

try{

   Twitter twitter = new TwitterFactory().getInstance();

   // set key and secret that you get from Twitter app registeration at:
   //     http://dev.twitter.com/pages/auth#register
   twitter.setOAuthConsumer("Your Consumer key", "Your Consumer secret");

   // load access token if it exists
   AccessToken accessToken = null
   def tokenFile = new File("accessToken.xml")

   if (tokenFile.exists()) {
      def xstream = new XStream()
      tokenFile.withInputStream { ins -> accessToken = xstream.fromXML(ins) }
      twitter.setOAuthAccessToken(accessToken)
   } 

   else {

     // get the URL to request access to Twitter acct
     RequestToken requestToken = twitter.getOAuthRequestToken();
     String authUrl = requestToken.getAuthorizationURL()
     System.out.println("Open the following URL and grant access to your account:");
     System.out.println(authUrl);

     // take the PIN and get access token
     System.out.print("Enter the PIN:");
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
     String pin = ""
     pin = br.readLine();
     accessToken = twitter.getOAuthAccessToken(requestToken, pin);

     // persist token
     def xstream = new XStream()
     xstream.classLoader = getClass().classLoader
     new File("accessToken.xml").withOutputStream { out -> xstream.toXML(accessToken, out) }
   }

   String message = "from Groovy w/ token" + accessToken.getToken()
   String screenName ="ScreenNameToSendTo"

   DirectMessage directMessage = twitter.sendDirectMessage(screenName, message)
   System.out.println("Direct message sent to " + directMessage.getRecipientScreenName());

} catch (Exception e) {
   e.printStackTrace();
}

What do you think? Leave a comment.

31 January 2009

Grid Computing with GridGain

Similar to the famous "one word - Plastics" scene in "The Graduate", a senior engineer took me aside on the weekend of the Columbia explosion and said "Grid Computing". We were working long hours for a proposal that was insane at best. At the time, I had heard of SETI@home but never really had spent any time on the subject. Tim was pretty excited about the topic. He had just read an article in some Hype-of-the-Day rag and was sure that Grid Computing was going to be the solution we needed for our proposal.

We ended up winning the job which is a really big deal. I think we're up to around $400M now over the past few years. The app is a distributed system (not a web app) but doesn't use Grid Computing and never will. It's tied into the customer's crazy network dreams and their infrastructure framework that locks our applications to theirs. Actually, it's brilliant in a business way. Our apps can't ever be used for anything other than for their original purposes.

For the past few months, I've been following the blog @Gridify Cloud Computing via Google Reader. Honestly I don't know why. I must have stumbled on an interesting entry one day and added then to the reader for future ref. This weekend, I was scanning the blogs and I saw a GridGain blog that started with:
When executing tasks and jobs on the grid you may be faced with the question: "How do I make sure that tasks from other users are not executed on nodes started by me?"
We're asking ourselves the same question on my project so the entry piqued my interest. The GridGain solution can't help me in anyway but it got me to their website where I started to poke around. I watched a few short videos on GridGain installation and creating an app in 15 minutes. Ok, I'm interested, let's do this.

Installation is pretty easy, just go to the downloads page and grab the installer for your OS. I'm using linux, so I got the GUI installer gridgain-unix-2.1.0.sh and ran it like this:
sh ./gridgain-unix-2.1.0.sh
Pretty easy. I decided to install under my projects folder so next I setup environment variables for GRIDGAIN_HOME in ~/.bashrc like this:
export GRIDGAIN_HOME=~/projects/gridgain-2.1.0
I haven't used Java much lately and was happy to see that GridGain had Groovy examples. I attempted to run the examples and immediately ran into difficulties. First was my fault. I un-installed Groovy a bit ago and needed to get the latest distribution. I did:
sudo apt-get install groovy
And presto, groovy was re-installed. A quick sanity check verified that it was installed:
groovy -v
This reveals that groovy 1.5.2 was installed. Hmmm, I swore that a newer version was out but 1.5.2 should be good for the GridGain demos, right? Right.

I stepped up to the first example compileGridify.sh. It immediately complained that GROOVY_HOME wasn't set. Back to ~/.bashrc and I added this line:
export GROOVY_HOME=/usr/share/groovy
Then the script started to complain that class Gridify couldn't be found. This is GridGain's own example, the thing should run almost out-of-the-box. Durn it! A little more digging reveals the the compile example referenced gridgain.jar in the classpath when the actual jar is called gridgain-2.1.0.jar. I started to edit the file and realized that there were probably other scripts in the GridGain install that may have the same error. Rather than go on an edit-fest, I simply created a soft link in GRIDGAIN_HOME like this:
ln -s gridgain-2.1.0.jar gridgain.jar
Yeah! it compiled. Now to the run script. The runGridify.sh complained that it couldn't find the groovy.lang.GroovyObject class. Kinda weird cause that's the momma groovy class. Sounds like another classpath issue. And it was. The run script references embeddable/groovy-all-1.5.7.jar. Problem is that not only did I have version 1.5.2, that version doesn't even include a groovy-all.jar. I wonder why? I then went to groovy home and looked around. Version 1.5.6 has a Debian package but the newest 1.5.7 doesn't. Sounds like 1.5.6 is the next to try. After installation, I looked at GROOVY_HOME and yes!! It has an embeddable folder and a groovy-all-1.5.6.jar. Now a quick edit to the runGridify.sh file and back in business.

The gridify example starts up a default configuration and prints out "Hello World" on a remote node. Nothing too exciting but impressive if you look at all that really is happening in the background.

The other example compileHelloWorld.sh and runHelloWorld.sh have the exact same issues with classpath jars. This example is similar to Gridify but prints "Hello" on one node and "World" on another. To do this, start another node in a terminal before running runHelloWorld.sh :
./gridgain.sh
There's many cool things that can be done with GridGain. One interesting thing is running JUnit tests after a build in a parallel manner. The GridGain guy claims that running their test on a single box takes about 3 hours. Gridifying the Ant task reduces that to about 20 minutes.

Take a look at the videos and other stuff on the website to get started. As well, DZone has a pile of hits. Search DZone for gridgain

I reported these version probs to the GridGain user forum. They made the fix and updated the wiki the next day. Nice.

http://www.gridgainsystems.com/wiki/display/GG15UG/Groovy+Configuration+And+Setup

08 February 2008

Groovy 01 - SOAP Server

As much as I like BeanShell (bsh), once I found Groovy, I don't think that I've done any new bsh development. I'm going to follow up on my earlier bsh blog entry where I promised to show cool bsh features but first I really want to lay the ground work for an Enterprise Service Bus (ESB) -like tool that I've been playing with called XMLBlaster. Now XMLBlaster doesn't call themselves an ESB. Instead they say they're MOM (Message oriented Middleware) with a lot of features.

They're website says XmlBlaster is a publish/subscribe and point to point MOM server which exchanges messages between publishers and subscribers. The message is described with XML-encoded meta information. Messages may contain everything, GIF images, Java objects, Python scripts, XML data, a word document, plain text. Communication with the server is based on CORBA (using JacORB) or RMI or XmlRpc, clients are free to choose their preferred protocol. Other protocols like email, socket or SOAP may be plugged in.

Like usual, I'm starting to get ahead of myself as I want to talk about Groovy. If you're not familiar with this great language, you must pick up Groovy In Action (GINA) as this is the Groovy Bible.

I have a Groovy SOAP Server as one "end point" or client and a number of other legacy app nodes. I'm currently using Groovy 1.0 but 1.5.4 is the latest. This new version brings features like Java 5 annotations, generics and enums, it provides significant performance gains, new meta-programming capabilities, new and improved tooling support like the new joint Groovy/Java compiler, the new interactive shell, or the Groovy Swing console, and a few other additions in its syntax, like the new Elvis operator or the ability to omit parentheses in methods with named arguments to make DSLs even more readable. Sounds great. I'm convinced so I'm upgrading as I'm writing this entry.

Grab the Groovy download and give it a try.

All installed? Great, let's move along. SOAP is a lightweight protocol intended for exchanging structured information in a decentralized, distributed environment. Groovy has a SOAP implementation based on Xfire which allows you to create a SOAP server and/or make calls to remote SOAP servers using Groovy. Get the Groovy SOAP jar and drop it into the $GROOVY_HOME/lib folder.

[edit 19 Feb 2008]
The Groovy website seems to have a broken link to download the soap jar. Try to get the jar at the link mentioned above but if that fails, try this:
http://momupload.com/files/77499/groovysoap-all-1.0-0.3-snapshot_jdk1.5.0.jar.html
[/edit]

First we're going to make an incredible simple SOAP server and then test it with the browser. Create a file named LogServer.groovy that looks like this or grab a copy here.

---------LogServer.groovy---------

import groovy.net.soap.SoapServer

// define the API
void log(logTime, logMessage) {
// real code goes here but we're just printing to stdout for now
println(logTime + ' : ' + logMessage)
}

// start server on localhost.
// use whatever port you want
def server = new SoapServer("localhost", 6980)
server.setNode("LogServer")
server.start()

-------------------------------------------

One of the great things with Groovy is that you can call Java classes from Groovy and Java can call Groovy. Because Groovy is Java. With this in mind, your SOAP server can invoke any Java legacy app. In the example above, we're just writing to std out.

Start it up by typing: groovy LogServer.groovy

In your browser, enter: http://localhost:6980

And you should see an XFire page of the available webservices at that port:

Available Services:
  • LogServerInterface [wsdl]

  • Generated by XFire ( http://xfire.codehaus.org )
Pretty neat, huh? Click on the Web Service Definition Language (WSDL) link and you'll see all the wsdl that was generated auto-magically from our very simple SOAP server.

Next time we'll write a quick SOAP client and test this server out. Until then, buy the book and read the Groovy.

28 January 2008

ESB 01

Enterprise Service Bus (ESB). Nice name. Every time I see something with "enterprise" in the title, I get the "ooh"s. Or is it the "aah"s? I simply can't walk past a book titled "Enterprise blah blah" without stopping to thumb thru it. It's only $59.99 and it's shiny. Should I impulse buy it now or add it to the Amazon cart for later?

ESBs. I've messed with a few of them, probably used Apache's ServiceMix the most. Using servicemix, I had a Groovy SOAP server working with a JMS app in about 10 minutes. Maybe it was 15. I tend to exaggerate. Whatever time, it was short and servicemix was easy. Speaking of MQ, have you read Linda's Open Message Queue Blog? It looks pretty good but she hasn't updated since October 2007.

Some guys at work are using BEA's Aqua Logic. I've not had the chance to use it but they seem to like it, especially the message transformations. I've got a demo disc sitting on my desk and anyone can download a demo. I should test drive this soon. Last summer I used both JBoss and WebLogic JEE servers and I found that WebLogic was much more stable. I think the price is a little steep for mortals but the product was better.

There's also Mule which I've never tried. I've stumbled across an interesting article "Exploring ESB Patterns with Mule". Yet another thing to work thru and try out when I have a spare hour or ten.