Build a RESTful Webservice in less than 5 minutes

There are quite some tutorials around about building and exposing a RESTful Webservice, but some of them are outdated and make you wade through complex dependencies and tinkering with deployment descriptors and web.xml files. But using RESTeasy, the JBoss implementation that is fully compliant with the JAX-RS 2.0 JCP specification, and Eclipse you can build a simple webservice (“hello world”) with less than 10 lines of sourceode with annotations and no web.xml used in a few minutes and run it on Wildfly.

Lets build a webservice that creates random numbers.

Continue reading

Advertisements

Snippet: Get the timezone for a geo location with Groovy and Google

I have a list (table) of airport locations, but missing the timezone information (as used in Java, eg. ‘America/Los_Angeles’ which is the timezone Id in java.util.Timezone). We could use the geonames dump to retrieve the timezone from the cityname, but the cityname for some airports might not be unique or distinct, so I rather use the geographical location which I have for each airport and use a webservice to get the timzone for a specific location. We can use the geonames webservice (commercial usage allowed, but you should give credit) or the Google Timezone API (which is experimental and restricted to 2500 calls a day) .

We use Groovy to retrieve this information, using the browser you get this JSON reply for :
https://maps.googleapis.com/maps/api/timezone/json?location=39.6034810,-119.6822510&timestamp=1331161200&sensor=false

JSON

We put this into a Groovy Script to read the timeZoneId:

#!/usr/bin/env groovy
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*

def timezone = new RESTClient('https://maps.googleapis.com/maps/api/timezone/json?location=39.6034810,-119.6822510&timestamp=1331161200&sensor=false')
def resp = timezone.get( contentType : JSON)

println resp.data.timeZoneName + " - " + resp.data.timeZoneId

We need the HTTP Builder library.
Please note the httpbuilder library has some dependencise ! Put all into your .groovy/lib folder.

  • commons-beanutils-1.8.3.jar
  • commons-codec-1.6.jar
  • commons-collections-3.2.1.jar
  • commons-lang3-3.1.jar
  • commons-logging-1.1.1.jar
  • fluent-hc-4.2.2.jar
  • http-builder-0.6.jar
  • httpclient-4.2.2.jar
  • httpclient-cache-4.2.2.jar
  • httpcore-4.2.2.jar
  • httpmime-4.2.2.jar
  • json-lib-2.4-jdk15.jar
  • xml-resolver-1.2.jar

Result:

Pacific Standard Time - America/Los_Angeles

Now we can iterate through our locations and complete the data.

Alternative with geonames:

geonames JSON

#!/usr/bin/env groovy
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*

def timezone2 = new RESTClient('http://api.geonames.org/timezoneJSON?lat=47.01&lng=10.2&username=xxxxx')
def resp2 = timezone2.get( contentType : JSON)
println resp2.data.countryName + " - " + resp2.data.timezoneId

How to get started with Prefuse and Netbeans

I was looking for a java based visualization toolkit for quite a while. Either they are very static (image rendered and delivered without any interaction) or cost too much money or badly documented or plain buggy and incomplete. I found a toolkit called prefuse (link) on sourceforge which is an amazing piece of work done by Jeffrey Heer (link) of Berkeley University Stanford. Thanks for this and to the people in the forum (link) to continue the effort to answer questions.

Though it’s last release if dating 2007.10 it is feature complete and not really need to carry the beta tag, but never mind. The project migrated to flare (link) based on Flash and AS, but unfortunately that is not always the first choice, even more powerful in terms of graphics. But I wonder what would be missing. It is open source, so with community effort things can be implemented or even added.
It is released under BSD and can be used freely for commercial and non-commercial applications.

I am a true Netbean nerd, aka NB user and spent some time to get started with prefuse.

Today I wan to share with you the steps (i did) to get a running with prefuse and Netbeans running Windows.
(Please note, it might not be the perfect or smartest approach. I dont claim its the right way or complete, but I got it to work this way. )
I am sure this is very basic information for the prefuse experts, but other beginners might need to go through the same steps.

1. Donwload the file prefuse-beta-20071021.zip (link).

2. Unzip the file to folder.

3. Check for a properly set JAVA_HOME path, like

E:\Documents and Settings\SAM>echo %JAVA_HOME%
E:\Program Files\Java\jdk1.6.0_10

4. Open the file build.bat with text editor of your choice and change the follwoing line
%JAVA_HOME%\bin\java.exe -Dant.home=…
to
java.exe -Dant.home=…
(I removed the JAVA_HOME because java already is in the system PATH)

5. Open a DOS-Box (Windows, aka run.. CMD) and navigate to the folder with the build.bat file.

6. Execute ‘build.bat all’. You should get something like this:

Build

prefuse and Netbeans: Build the jarfiles

7. Start Netbeans and create a new project (New, Choose project, Java, Java Application). Lets call it PrefuseDemo.

8. Open the project properties (right click on the project name in the project explorer) and select properties. Go to the libraries sectio and add prefuse.jar and demo.jar (required for the sample code). You find these files in the folder ‘build’ created by our build.bat.

9. Now you change the packagename (with the initial created Main.Java if selected) to prefusedemo.

10. In the build folder you also find a src folder with various sample java code. For this tutorial I took GraphView.java.

11. Create a new javaclass in the prefuse package with the name GraphView.

12. Copy the complete sourcecode from GraphView.java into it and replace the basic skeleton.

13. Fix the package name to package prefusedemo;

14. You can delete the Main.java if NB created it for you.

15. Build the project.

16. Right click onGraphView.java and select Run File. Finished ! You should see this:

t200901300014

prefuse and Netbeans: Run the demo


Remarks:
1. The other files (demos that come with the prefuse package) you can create the same way and add them into your demo application.
2. I tried to import the whole prefuse source folder into Netbeans via Import, but it didnt work.

Conclusion:
Now we got started, lets move on to understand the prefuse concept and adapt some of the samples to our own applications or create new ones from the scratch ! Stay tuned for more prefuse !

Tutorial: Starting with Glassfish and JMS (Part 2)

Today we proceed with last weeks JMS tutorial and create a standalone java application that sends a message to a topic.

It puzzles me to have a client application that I need to start “from within”. Lets find out how an application looks like that can run by itself, connect to a JNDI server and sends a message to topic. The key information I took from this discussion (link, Thanks to Foli and TravelEntity) at forums.sun.com.

Using: Netbeans 6.5 and a local Glassfish V2

1. Lets create a standard SE java project. We call it “JMSClient”

tut09010005_new_java_application

JMSClient: New Java SE project

2. Import the necessary libraries

Applicationserver JNDI Lookup
/lib/appserv-rt.jar
/lib/appserv-admin.jar
/lib/javaee.jar
/lib/j2ee.jar

Client Lib
/imq/lib/jms.jar
/imq/lib/imq.jar
/imq/lib/imqutil.jar
/lib/install/applications/jmsra/jmsra.jar

(You find them in your glassfish home directory)

Libraries

JMSClient: Libraries

3. The complete source


package jmsclient;

import java.util.Hashtable;
import java.util.Queue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.Topic;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class Main {

    public static void main(String[] args) {

        Context jndiContext = null;
        ConnectionFactory connectionFactory = null;
        Connection connection = null;
        Session session = null;
        // ---- Same sample with a queue ----
        // Queue queue = null;
        Topic topic = null;
        MessageProducer messageProducer = null;
        MapMessage message = null;

        Hashtable properties = new Hashtable(2);
        properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.appserv.naming.S1ASCtxFactory");
        properties.put(Context.PROVIDER_URL, "iiop://localhost:3700");

        try {
            jndiContext = new InitialContext(properties);
            connectionFactory = (ConnectionFactory)jndiContext.lookup("jms/ConnectionFactory");
            // ---- Same sample with a queue ----
            //queue = (Queue)jndiContext.lookup("jms/Queue");
            topic = (Topic)jndiContext.lookup("jms/Topic");

            connection = connectionFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            // ---- Same sample with a queue ----
            //messageProducer = session.createProducer(queue);
            messageProducer = session.createProducer(topic);
            message = session.createMapMessage();

            // ---- Preparing Mapped Message ----
            message.setString("lastname", "Myer");
            message.setString("firstname", "Fred");
            message.setString("id", "0200");

            messageProducer.send(message);

            connection.close();

        } catch (NamingException e) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
        }
        catch (JMSException e) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
        }
        finally {
            System.out.println("ENDED.");
            System.exit(0);
        }
    }
}

Remarks:

  • The tutorial is looking for a local server. Change (Context.PROVIDER_URL, “iiop://localhost:3700”) to the relevant server and port info.
  • We use a topic (publish/subscribe) in this sample. If you want to use a queue instead, change to the lines which are commented out and remove the topic related lines.

About unique numbers and ID’s

I am sure everyone of us had the requirement to save data in a DB, a hash or whatever. Most of the times we were creating this unique numbers, often used as keys for reference, by ourselves simply counting +1. Sooner or later we realized, oops I used the number already or I need to merge tables and now we have duplicate ID’s and so on and so on. Most DB offer some auto-increment feature or you make use of the row-id as oracle create one (internally for each record). I came across the UUID (wikipedia link), which is a universal unique ID creation method. In Java its damn simple to create one:

import java.util.UUID;
[..]
UUID uID = UUID.randomUUID(  );
[..]

I worked once for a company which used long integer as their ID field. The max value is 2,147,483,647 and recently they hit the limit facing the problem of hardcoded long integer all over the sourcecode and DB. I guess the UUID would help (using it from the start).
Remark: Putting in a lot of brain power they fixed the problem without refactoring about 1 mill lines of code.

With the help of 122 significant bits in a version 4 UUID you can create 2^122 (5,316,911,983,139,663,491,615,228,241,121,378,304) numbers ! Enough for the lifetime of this universe !