GHads mind

developers thoughts & finds

Archive for September 2008

Calling a REST WebService from Java (without libs)

with 3 comments

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

Advertisements

Written by ghads

September 24, 2008 at 2:31 pm

Posted in Java development

Tagged with , ,

Development Ecosystem

leave a comment »

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

Written by ghads

September 22, 2008 at 1:00 pm

Create unique identifiers in Java – UUID

leave a comment »

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!

Written by ghads

September 19, 2008 at 9:52 am

Posted in Java development

Tagged with , ,

Writing DSLs with groovy

leave a comment »

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

Written by ghads

September 19, 2008 at 8:13 am

Posted in Groovy Development

Tagged with , , ,

Get more from your Java

leave a comment »

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

Written by ghads

September 17, 2008 at 3:17 pm

How to blog code snippets at WordPress.com

with one comment

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

Written by ghads

September 17, 2008 at 10:28 am

Posted in Blogging

Tagged with , , ,

Java to XML to Java

leave a comment »

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!

Written by ghads

September 16, 2008 at 2:49 pm

Posted in Java development

Tagged with , , ,