JavaDude's Groovy Snippets

July 28, 2010

Accessing world time engine with Groovy and httpbuilder

Filed under: Groovy Tutorial — Tags: , , — admin @ 9:41 am

World Time Engine provides all kind of time related information for any given place on this planet. You can use their free web portal and enter GPS coordinates, city names or postal codes and retrieve timezone, daylight saving and more. Otherwise they provide an API to get the data via an http GET request. This service is not free, they charge you a 14 U$ for 50.000 requests.

API details you find here, but in short:

Request   
  1. http://worldtimeengine.com/api/<apikey>/<latitude>/<longitude>

and you get something like this:

Response   
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <timezone xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:noNamespaceSchemaLocation="http://worldtimeengine.com/timezone.xsd">
  4. <version>1.1</version>
  5. <location>
  6. <region>Australia/New South Wales</region>
  7. <latitude>-33.8671</latitude>
  8. <longitude>151.207</longitude>
  9. </location>
  10. <time>
  11. <utc>2008-02-13 00:50:30</utc>
  12. <local>2008-02-13 11:50:30</local>
  13. <zone>
  14. <hasDST>true</hasDST>
  15. <current>
  16. <abbreviation>EDT</abbreviation>
  17. <description>Eastern Australia Daylight Savings Time</description>
  18. <utcoffset>+11:00</utcoffset>
  19. <isdst>true</isdst>
  20. <effectiveUntil>2008-03-29 19:00:00</effectiveUntil>
  21. </current>
  22. <next>
  23. <abbreviation>EST</abbreviation>
  24. <description>Eastern Australia Standard Time</description>
  25. <utcoffset>+10:00</utcoffset>
  26. <isdst>false</isdst>
  27. <effectiveUntil>2008-10-25 18:00:00</effectiveUntil>
  28. </next>
  29. </zone>
  30. </time>
  31. </timezone>

How can we use Groovy to request for the data and access its detail ?

  • Get yourself a API Key from world time engine
  • We use the Groovy Console (groovyConsole from the shell)
  • We need the httpbuilder library
  • Copy http-builder-0.5.0.jar and all dependencies into the ./groovy/lib folder in your home folder
  • Execute this code:
    request   
    1. import groovyx.net.http.*
    2. import static groovyx.net.http.ContentType.*
    3. def worldTime = new RESTClient("http://worldtimeengine.com/api/{yourkey}/35.7647018432617/140.386001586914")
    4. def resp = worldTime.get( contentType : XML)
    5. println resp.data.time.zone.current.abbreviation.text()
    6. println resp.data

    Groovy Console

    XML Response

  • You see it is fairly simple to access specific fields with the groovy notation resp.data.time.zone.current.abbreviation.text()

How do I use this ?

  • I use Groovy classes in my java EE application. You can cut down on boilperplate code dramatically by using Groovy !
  • The above service I use in an location aware application.

January 12, 2010

Accessing Trac with Groovy and the XML-RPC library

Filed under: Groovy Snippets, Groovy Tutorial — Tags: , , — admin @ 5:47 pm

With Groovy and the XML-RPC library (groovy.codehaus.org/XMLRPC) the access to Trac gets extremely easy. The older version 0.4 and 0.5 of the library could not handle basic authorization but thanks to Tim fixing the missing feature and some other xml format error, you can now access any Trac Wikipage with as little as 3 lines of Groovy code.

  1. def serverProxy = new XMLRPCServerProxy("https://user:password@sometracserver.com/login/xmlrpc")
  2. // or
  3. // def serverProxy = new XMLRPCServerProxy("http://sometracserver.com/login/xmlrpc")
  4. serverProxy.setBasicAuth("user","password")
  5. println serverProxy.wiki.getPage("TracBackup")

Remark:
At the time of this entry version 0.6 is not released yet. Check for availability at repository.codehaus.org/org/codehaus/groovy/groovy-xmlrpc/ for the new version or update your svn copy and build by yourself (see blog entry)

Update 2010-02-01: The new version was released as 0.5.1 (link)

Debugging XML-RPC calls

Filed under: Groovy Tutorial — Tags: , , — admin @ 7:59 am

The Groovy XML-RPC library 0.5 allows me to do perform basic authorization, but my Trac Server now throws a error code 500 at me (stating XML declaration not well-formed). Since I  dont know how to check the XML request the library posts, I choose to dissect the messages at the network level using Wireshark. Luckily I have a Python library that works fine, so I can compare the working version of the XML-RPC request. (Remark: Dont forget to start wireshark as root user/sudo)

XML Error   
  1. 2010-01-07 09:03:03,095 Trac[main] DEBUG: Dispatching <Request "POST u'/login/xmlrpc'">
  2. 2010-01-07 09:03:03,117 Trac[main] ERROR: Internal Server Error:
  3. Traceback (most recent call last):
  4. File "/usr/local/Python-2.5.2/lib/python2.5/site-packages/trac/web/main.py", line 441, in _dispatch_request
  5. dispatcher.dispatch(req)
  6. File "/usr/local/Python-2.5.2/lib/python2.5/site-packages/trac/web/main.py", line 205, in dispatch
  7. resp = chosen_handler.process_request(req)
  8. File "/usr/local/Python-2.5.2/lib/python2.5/site-packages/TracXMLRPC-1.0.6-py2.5.egg/tracrpc/web_ui.py", line 163, in process_request
  9. self.process_xml_request(req, content_type)
  10. File "/usr/local/Python-2.5.2/lib/python2.5/site-packages/TracXMLRPC-1.0.6-py2.5.egg/tracrpc/web_ui.py", line 167, in process_xml_request
  11. args, method = xmlrpclib.loads(req.read(int(req.get_header('Content-Length'))))
  12. File "/usr/local/Python-2.5.2/lib/python2.5/xmlrpclib.py", line 1130, in loads
  13. p.feed(data)
  14. File "/usr/local/Python-2.5.2/lib/python2.5/xmlrpclib.py", line 547, in feed
  15. self._parser.Parse(data, 0)
  16. ExpatError: XML declaration not well-formed: line 1, column 30
  17. 2010-01-07 09:03:03,121 Trac[chrome] DEBUG: Prepare chrome data for request

Python Library/Call

XML-RPC   
  1. import xmlrpclib
  2. server = xmlrpclib.ServerProxy("http://user:password@sometracserver.com/login/xmlrpc")
  3. print server.wiki.getPage("WikiStart")

Result in Wireshark

Wireshark

Groovy Call

XML-RPC   
  1. def serverProxy = new XMLRPCServerProxy("http://sometracserver.com/project/login/xmlrpc")
  2. serverProxy.setBasicAuth("user","password")
  3. serverProxy.wiki.getPage("WikiStart")

Result in Wireshark

Wireshark

There is the problem: encoding=”+ENCODING+”
The Trac XML reader most likely will throw up the complete call because of this. Actually the comparison was not really required because the error is very obvious.

January 3, 2010

Building Groovy XML-RPC library 0.5

Filed under: Groovy Tutorial — admin @ 8:26 pm

The current release is 0.4 (groovy-xmlrpc-0.4.jar). The actual codebase also supports basic authorization (link), but this version 0.5 was not released yet due to the failing junit test.

In this tutorial we will build the library from the codebase. Using Netbeans we have all the tool we need to achieve this easily.

Tutorial:

  1. Start Netbeans. Team | Subversion | Checkout..
    Enter http://svn.codehaus.org/groovy/trunk/groovy/modules/xmlrpc/ and a local directory

    SVN

    SVN

    1. ==[IDE]== Jan 2, 2010 8:55:32 PM Checking out...
    2. co -r HEAD http://svn.codehaus.org/groovy/trunk/groovy/modules/xmlrpc /media/NEXUSII/GroovyAndGrails/GroovyBuildNB/xmlrpc --config-dir /home/sven/.netbeans/6.8/config/svn/config --non-interactive
    3. A /media/NEXUSII/GroovyAndGrails/GroovyBuildNB/xmlrpc/repository
    4. A /media/NEXUSII/GroovyAndGrails/GroovyBuildNB/xmlrpc/repository/jivesoftware
    5. A /media/NEXUSII/GroovyAndGrails/GroovyBuildNB/xmlrpc/repository/jivesoftware/smackx
    6. A /media/NEXUSII/GroovyAndGrails/GroovyBuildNB/xmlrpc/repository/jivesoftware/smackx/3.0.1
    7. A /media/NEXUSII/GroovyAndGrails/GroovyBuildNB/xmlrpc/repository/jivesoftware/smackx/3.0.1/smackx-3.0.1.jar.md5
    8. A /media/NEXUSII/GroovyAndGrails/GroovyBuildNB/xmlrpc/repository/jivesoftware/smackx/3.0.1/smackx-3.0.1.jar
    9. A /media/NEXUSII/GroovyAndGrails/GroovyBuildNB/xmlrpc/repository/jivesoftware/smack
    10. A /media/NEXUSII/GroovyAndGrails/GroovyBuildNB/xmlrpc/repository/jivesoftware/smack/3.0.1
    11. A /media/NEXUSII/GroovyAndGrails/GroovyBuildNB/xmlrpc/repository/jivesoftware/smack/3.0.1/smack-3.0.1.jar
    12. A /media/NEXUSII/GroovyAndGrails/GroovyBuildNB/xmlrpc/repository/jivesoftware/smack/3.0.1/smack-3.0.1.jar.md5
    13. A /media/NEXUSII/GroovyAndGrails/GroovyBuildNB/xmlrpc/.classpath
    14. A /media/NEXUSII/GroovyAndGrails/GroovyBuildNB/xmlrpc/.project
    15. A /media/NEXUSII/GroovyAndGrails/GroovyBuildNB/xmlrpc/src
    16. ...
  2. Build the library (right click on the project and Build)
    Build   
    1. NetBeans: Executing 'mvn -Dnetbeans.execution=true install'
    2. NetBeans: JAVA_HOME=/usr/lib/jvm/java-6-sun-1.6.0.16
    3. Scanning for projects...
    4. Building Groovy XML-RPC
    5. task-segment: [install]...
    6. Installing /media/NEXUSII/GroovyAndGrails/GroovyBuildNB/xmlrpc/target/groovy-xmlrpc-0.5.0-SNAPSHOT.jar to /home/sven/.m2/repository/org/codehaus/groovy/groovy-xmlrpc/0.5.0-SNAPSHOT/groovy-xmlrpc-0.5.0-SNAPSHOT.jar
    7. BUILD SUCCESSFULTotal time: 9 seconds
    8. Finished at: Sat Jan 02 21:34:59 CET 2010Final Memory: 25M/137M
  3. Download missing dependencies
    Eventually some libraries are missing, Netbeans will remind you. (Just press download)

    Dependency Problems

In part 2 we will use the library to access TRAC via XML-RPC.

    December 27, 2009

    Snippet: Accessing SNIPPLR with Groovy and Apache XML-RPC

    Filed under: Groovy Snippets, Groovy Tutorial — Tags: , , , — admin @ 9:49 am

    In the previous post we used the Groovy XML-RPC library, in this snippet we will use the Apache XML-RPC library. Why ? There is no basic security implemented in the Groovy XML-RPC to access for example a

    The prerequisites are still the same, just we change the library:

    • Download the Apache library from here. You should download a file from the binaries folder (apache-xmlrpc-3.1.2-bin.zip), inside you will find a lib subfolder with a couple of jars we need to add to the classpath.
      (commons-logging-1.1.jar, xmlrpc-client-3.1.2.jar, xmlrpc-server-3.1.2.jar, ws-commons-util-1.0.2.jar, xmlrpc-common-3.1.2.jar)

    Snippet:


     

    Remark: You can add more parameters for the server with

    • config.setEncoding(“UTF-8″)
      config.setBasicUserName(“[username]“);
      config.setBasicPassword(“[password]“);

    December 26, 2009

    Snippet: Accessing SNIPPLR with Groovy and XML-RPC

    Filed under: Groovy Snippets, Groovy Tutorial — Tags: , — admin @ 3:08 pm

    It is straight forward to access Snipplr via XML-RPC with Groovy. In this tutorial we use the Groovy Console to play with Snipplr snippets.

    Requirements:

    Tutorial:

    • Start the Groovy Console (usually with groovyConsole from a shell)

      Groovy Console

    • Add the XML-RPC library (Scripts| Add jar to classpath)

      Add library

    • The Snippet


       

    • Result   
      1. Forth
      2. Rails
      3. NewtonScript
      4. Diff
      5. Revolution
      6. Textpattern
      7. [..]
      8. W-Language
      9. HTML
      10. Java
      11. Objective C
      12. eZ Publish
      13. VHDL
      14. Bash
      15. C#
      16. ColdFusion
      17. You have 7 snippets and favorites
      18. [id:25390, title:Create simple XML with MarkupBuilder, updated:[timezone:-05:00 EST, datetime:Thu Dec 24 10:13:50 CET 2009], favorite:false, private:false]
      19. [id:25410, title:Create simple XML with StreamingMarkupBuilder (pretty-printed), updated:[timezone:-05:00 EST, datetime:Fri Dec 25 04:30:52 CET 2009], favorite:false, private:false]
      20. [id:24147, title:Finding the Longest Consonant Cluster, updated:[timezone:-05:00 EST, datetime:Wed Dec 02 12:15:07 CET 2009], favorite:true, private:false]
      21. [id:2090, title:Groovy Series: Regular Expressions 1/3, updated:[timezone:-05:00 EST, datetime:Fri Feb 02 11:42:05 CET 2007], favorite:true, private:false]
      22. import groovy.xml.*
      23. def createXML() {
      24. def xml = new groovy.xml.StreamingMarkupBuilder().bind(){
      25. mkp.xmlDeclaration()
      26. content() {
      27. parameter(x:0)
      28. person(id:100){
      29. firstname(&quot;John&quot;)
      30. lastname(&quot;Long&quot;)
      31. }
      32. person(id:101){
      33. firstname(&quot;Ken&quot;)
      34. lastname(&quot;Smith&quot;)
      35. }
      36. }
      37. }
      38. XmlUtil.serialize(xml)
      39. }
      40. def static main(def args) {
      41. def x = createXML()
      42. println x
      43. }
      44. xml groovy prettyprint StreamingMarkupBuilder
      45. 2009-12-25 03:37:20

      Take a look at the API documentation at snipplr.com

    Powered by WordPress