Archive for September, 2008|Monthly archive page

Calling a REST WebService from Java (without libs)

I needed to geocode an address today by using free WebServices. The final solution is to use yahoo, but here is the full list of other usefull services:

Anyway, still needed to call the WS from Java, but thanks to google I found a solution quickly (http://xml.nig.ac.jp/tutorial/rest/index.html) and expanded it to my usecase:

    private static String buildWebQuery(Map<String, String> parameters) throws Exception {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            String key = URLEncoder.encode(entry.getKey(), "UTF-8");
            String value = URLEncoder.encode(entry.getValue(), "UTF-8");
            sb.append(key).append("=").append(value).append("&");
        }
        return sb.toString().substring(0, sb.length() - 1);
    }

    public static String callRestfulWebService(String address, Map<String, String> parameters) throws Exception {
        return callRestfulWebService(address, parameters, null, 0);
    }

    public static String callRestfulWebService(String address, Map<String, String> parameters, String proxy, String port) throws Exception {
        return callRestfulWebService(address, parameters, proxy, Integer.parseInt(port));
    }

    public static String callRestfulWebService(String address, Map<String, String> parameters, String proxy, int port) throws Exception {

        Proxy proxyObject = null;
        if (StringUtils.isNotBlank(proxy) && port > 0) {
            InetSocketAddress proxyAddress = new InetSocketAddress(proxy, port);
            proxyObject = new Proxy(Proxy.Type.HTTP, proxyAddress);
        }

        String response = "";
        String query = buildWebQuery(parameters);

        // More info: http://xml.nig.ac.jp/tutorial/rest/index.html
        URL url = new URL(address);

        // make post mode connection
        URLConnection urlc = null;
        if (proxyObject == null) {
            urlc = url.openConnection();
        } else {
            urlc = url.openConnection(proxyObject);
        }
        urlc.setDoOutput(true);
        urlc.setAllowUserInteraction(false);

        // send query
        PrintStream ps = new PrintStream(urlc.getOutputStream());
        ps.print(query);
        ps.close();

        // retrieve result
        BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream(), "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append("\n");
        }
        br.close();
        response = sb.toString();

        return response;
    }

With these few methods you can call any REST WebService with any parameters (as Map) and use a proxy per call. The code also takes care of right encoding of parameters. The result is a xml string, which can be processed by regexp in an easy way.

Greetz, GHad

BTW: For how to create REST webservices take a look at: http://inverse2.com/?p=43

Development Ecosystem

No time/knowledge/money to setup a full build/project/issue management system? Try Buildix:

Buildix includes:

  • Subversion for Source Control
  • Mingle for Agile Project Management
  • Cruise Control for Continuous Integration
  • Trac as a wiki and bug-tracker
  • …plus a little bit of our own ThoughtWorks magic, to glue it all together

You can rapidly deploy your new infrastructure: either run Buildix from a LiveCD, or install it on an existing Ubuntu system. Use it as the base of your own software projects. The ‘Add New Project’ wizard will get your team’s projects started quickly and easily.

Sounds good. Must look for similar environments for git/mercury/bazaar. I’m still not sure about which envionment I like to use for my home pet projects.

Greetz GHad

Create unique identifiers in Java – UUID

Sometimes you have the need for unique identifiers. Luckily, Java provides an easy way for creating globaly unique strings:


import java.util.UUID;

public class GenerateUUID {

  public static final void main(String... aArgs){
    //generate random UUIDs
    UUID idOne = UUID.randomUUID();
    UUID idTwo = UUID.randomUUID();
    log("UUID One: " + idOne);
    log("UUID Two: " + idTwo);
  }

  private static void log(Object aObject){
    System.out.println( String.valueOf(aObject) );
  }
}

outputs:

UUID One: 067e6162-3b6f-4ae2-a171-2470b63dff00
UUID Two: 54947df8-0e9e-4471-a2f9-9af509fb5889

Thanks to Java Practices for providing this usefull piece of information!

Writing DSLs with groovy

Here’s a good presentation about DSL, groovy and things to consider. Enjoy!

Get more from your Java

Just take a look at HiddenFeatures for Java… I bet you’ll be surprised. A very usefull ressource if you like to look for something cool to test out

How to blog code snippets at WordPress.com

As mentioned in my previous post edit, I found the answer very quick. Here’s the URL for details on how to blog sourcecode in various languages: StackOverflow.com

Quoted:

See here: http://faq.wordpress.com/2007/09/03/how-do-i-post-source-code/

Wrap your code in these tags:

(See linked page... removed)

Available language codes:
  • cpp
  • csharp
  • css
  • delphi
  • html
  • java
  • jscript
  • php
  • python
  • ruby
  • sql
  • vb
  • xml

Hope that helps.

Thanks to AlexDuggleby!

(Really found no info on the web yesterday, didn’t search hard enough…)

Greetz, GHad

Java to XML to Java

Some simple methods using the integrated JRE-Classes (since Java 1.4) the de/serialize Objects to/from XML (must check out how to post code tonight… see below for an update):

public static Object importXML(File in) {
  try {
    FileInputStream fis = new FileInputStream(in);
    BufferedInputStream bis = new BufferedInputStream(fis);
    XMLDecoder decoder = new XMLDecoder(bis);
    Object result = decoder.readObject();
    decoder.close();
    bis.close();
    fis.close();
    return result;
  } catch (Exception e) {
    e.printStackTrace();
  }
  return null;
}
public static boolean exportXML(Object in, File out) {
  try {
    FileOutputStream fos = new FileOutputStream(out);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    XMLEncoder encoder = new XMLEncoder(bos);
    encoder.writeObject(in);
    encoder.close();
    bos.close();
    fos.close();
    return true;
  } catch (Exception e) {
    e.printStackTrace();
  }
  return false;
}

Update: Thanks to StackOverflow.com I got the answer to how to blog here in seconds! That’s really really cute!

Collaborative development Q&A

Have any question ’bout anything on development, IT, computers?

Try: http://stackoverflow.com/ and it will be answered in seconds! This really rocks!

Disable Chrome’s input field highlighting

Just stumbled upon this usefull CSS trick for disabling Chrome’s input field hightlighting:

*:focus {outline: none;}

The arrival

Howdy folks,

Finally I got my own blog up and running, so: Hello World! You may wonder whats this all about. Well, this blog is more or less just a diary where I like to put in my thoughts about whatever and my finds from the web.

The main purpose although is to have my development experiences, code fragments, cool links I found, ideas and emotions in one place, because I usually just save that stuff here and there and won’t find or remember it some time later. So I hope to make it better this time :-)

Okay, enough blabber and flubdub, greetings to everyone from Germany from the developers side of life,

GHad