KakimotOnline

March 15, 2009

Creating a J2ME Web Service Client

Filed under: j2me, java, mobile, programming, web service — Tags: , , — nandokakimoto @ 6:13 pm

This last week I was concentrated in developing a J2ME application that communicates with a Web Service to gather some information about route planning. Basically, the mobile app ask for a route, given an origin and a destination waypoints. Although this kind of work looks very easy, I got some problems to accomplish it. Due to that, I will share here my experiences to save you some time and if you have a different solution for creating J2ME web service clients, please let me know.

First of all, you will need the following softwares:

  • NetBeans IDE: instead of my fanatism for Eclipse IDE, I used NetBeans due to its facilities in creating web services.
  • Sun Java Wireless Toolkit: java toolkit for creating mobile applications.
  • Apache Tomcat: my target Web Server. Remember to download the .zip version.

The first step is creating the Web Service. So, inside NetBeans IDE, I will configure my tomcat installation under Tools->Servers menu option. (I’m using the pt_BR version of netbeans, so the menus may be a little different). Next, I choose Add Server and type the tomcat’s path location in my local machine. (Neatbeans comes with a native Web Server called GlassFish. If you are not aware with web server now, use this configuration as default).

Later, I have to create my web application project. So, under File->New Project menu, I choose Java Web category and Web Application project type. Click on “next” until your configuration has finished. Now, it’s time to create you source. I will show here a similar implementation of my route server.

Here I show the Waypoint class.


package entities;

public class Waypoint {

    private double lat;

    private double lng;

    public Waypoint(double lat, double lng) {
        this.lat = lat;
        this.lng = lng;
    }

    public Waypoint() {
    }

    public double getLat() {
        return lat;
    }

    public void setLat(double lat) {
        this.lat = lat;
    }

    public double getLng() {
        return lng;
    }

    public void setLng(double lng) {
        this.lng = lng;
    }

}

Here I show the Route class.


package entities;

public class Route {

    private Waypoint[]  waypoints;

    public Route(Waypoint[] waypoints) {
        this.waypoints = waypoints;
    }

    public Route() {
    }

    public Waypoint[] getWaypoints() {
        return waypoints;
    }

    public void setWaypoints(Waypoint[] waypoints) {
        this.waypoints = waypoints;
    }

}

Notice that I’m using complex object and arrays, which are in the most cases the reason of a lot of problems in deploying Web Services.

Next, I create my Web Service. To do that, right-click on the package folder and choose New->WebService. Here I show the implementation of my Web Service, which just return a route created by the given latitudes and longitudes.


package webservice;

import entities.Route;
import entities.Waypoint;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

/**
 *
 * @author Fernando Kakimoto
 */
@WebService()
public class RouteService {

    /**
     * Operação de serviço web
     */
    @WebMethod(operationName = "getRoute")
    public Route getRoute(@WebParam(name = "oLat", partName="oLatPart") double oLat,
            @WebParam(name = "oLng", partName="oLngPart") double oLng,
            @WebParam(name = "dLat", partName="dLatPart") double dLat,
            @WebParam(name = "dLng", partName="dLngPart") double dLng) {

        Waypoint w1 = new Waypoint(oLat, oLng);
        Waypoint w2 = new Waypoint(dLat, dLng);
        Waypoint[] waypoints = new Waypoint[]{w1, w2};

        return new Route(waypoints);
    }
}

After project compilation, the project tree will be similar than the picture below:

project

The Web Service is done. It’s time to create our J2ME client. For that, there are some options. One option is using the netbeans native support for that. After created a J2ME project, inside the New->J2ME Client for Web Applications menu, you are able to select a WSDL file as source and the IDE creates the J2ME client code for you. However, I tried this approach and the generated code came with errors. So, I used the second option: Sun Java Wireless Toolkit.

The WTK offers some utilites under File->Utilities menu. One of them is the Stub Generator, which generates J2ME client code for your WSDL service. So, run your service inside NetBeans or create its respective WSDL file. Next, in the stub generator, type the file path or URL, the code destination and the CLDC version. Here is how my Stub Generator looks like.

stubgenerator

After the code generation, here is the result of my WebClient J2ME project.

projectj2me

To finish, all you have to do is instantiate RouteService_Stub class and invoke getRoute() method. To make things simple, I used just one class which corresponds to the midlet. Here is the midlet code.


package main;

import client.Route;
import client.RouteService;
import client.RouteService_Stub;
import client.Waypoint;
import java.rmi.RemoteException;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.*;

/**
 * @author Fernando Kakimoto
 */
public class MainMidlet extends MIDlet implements CommandListener {
    private Command exitCommand = new Command("Exit", Command.EXIT, 1);
    private Form form = new Form("J2ME Web Client");

    public void startApp() {
        try {
            RouteService service = new RouteService_Stub();
            Route r = service.getRoute(1.5, 2.5, 1.8, 2.8);

            Waypoint origin = r.getWaypoints()[0];
            Waypoint detination = r.getWaypoints()[1];

            form.append("origin:" + origin.getLat() + "," + origin.getLng());
            form.append("\n");
            form.append("destination:" + detination.getLat() + "," + detination.getLng());

            form.addCommand(exitCommand);
            form.setCommandListener(this);
            Display.getDisplay(this).setCurrent(form);

        } catch (RemoteException ex) {
            ex.printStackTrace();
        }
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command c, Displayable d) {
        if(c == exitCommand){
            destroyApp(false);
        }
    }
}

That’s it. Simple and working.
The result you can see running the midlet sample.

phone

See you,


Fernando

January 9, 2009

Google Maps API Library for GWT

Filed under: google, java, news — Tags: , , — nandokakimoto @ 2:26 am

maps

Hello everybody,

2009 starts with a very good news for Java web developers interested in Google Maps services. This week, the Google Geo Developers Blog published about the announcement of  the Google API Libraries for Google Web Toolkit. They’re a collection of libraries that provide Java language bindings for popular Google JavaScript APIs, facilitating its use with GWT, which translates your Java code into JavaScript for deployment to end users.

In short, this library provides a way to access the Google Maps API from a GWT project without having to write additional JavaScript code. Here is how it happens:

public class SimpleMaps implements EntryPoint {
  private MapWidget map;

  // GWT module entry point method.
  public void onModuleLoad() {
    LatLng cawkerCity = LatLng.newInstance(39.509,-98.434);
    // Open a map centered on Cawker City, KS USA

    map = new MapWidget(cawkerCity, 2);
    map.setSize("500px", "300px");

    // Add some controls for the zoom level
    map.addControl(new LargeMapControl());

    // Add a marker
    map.addOverlay(new Marker(cawkerCity));

    // Add an info window to highlight a point of interest
    map.getInfoWindow().open(map.getCenter(),
        new InfoWindowContent("World's Largest Ball of Sisal Twine"));

    // Add the map to the HTML host page
    RootPanel.get("mapsTutorial").add(map);
  }
}

For more informations, the library comes with online examples and a straitforward tutorial.

See you.


Fernando

July 6, 2008

Remote Pair Programming

Filed under: eclipse, java, networks, news, web — Tags: — nandokakimoto @ 3:08 pm

Hi,

every software engineer and project manager knows about XP and Pair Programming, but most of them doesn’t know how to do it with a distributed team. A good option in this case is to make use of a Eclipse Plugin named Cola: Real-Time Shared Editing.

Cola’s main funtction is to enable code real time editing by two programmers placed in different environemnts. It’s provided by the Eclipse Communication Framework(ECF), so it’s a requeriment to have it in your Eclipse SDK, and makes use of your favorite public IM accounts like google talk, or skype.

More information, you can find here and in this screencast.


Fernando

March 25, 2008

Java Challenge Answer (3)

Filed under: java, news — nandokakimoto @ 11:33 pm

Hi,

so, did anyone put the code to run in Eclipse??

If you did it, you could see that the code is correct… it doesn’t fail in any of its parts, but why? It is really strange, because we are a assigning a String inside a list of Integer and it would fail at runtime, don’t you think?

To answer this challenge, you must be very familiar with Generics in Java 5, because somethings in Generics don’t make sense, like the code that I posted here. So, this is what happens:

Because of the legacy code before Generics, JVM has no ideia that my ArrayList was supposed to hold only Integers. The typing information does not exist at runtime. All Generics code is strictly for the compiler, which does all the verifications on Generics code and then strips the type information out of the class bytecode, exactly like pre-generics version of collection. None of the protections of Generics exists at runtime.

This is what JVM sees after the compilation: List myList = new ArrayList();So, JVM does not have any reason to throw away runtime exceptions.

Really surprising, doesn’t it?


Fernando

March 23, 2008

Java Challenge (3)

Filed under: java — nandokakimoto @ 5:52 pm

java_starting.png 

Hi guys,

here I am with another Java Challenge. Looking at the following code, are you able to say where does it fail??


import java.util.ArrayList;
import java.util.List;

public class GenericsHandler {

public void insert(List list) {
list.add(new String(“42″));
}

public static void main(String[] args) {
GenericsHandler gh = new GenericsHandler();

List<Integer> list = new ArrayList<Integer>();
gh.insert(list);

System.out.println(list.size());
System.out.println(list.get(0));
}

}

Next post, I’ll come with the answer.


Fernando

February 27, 2008

Java Challeng (2) Answer

Filed under: java, news — nandokakimoto @ 12:45 am

Well, the comments are right.

public class Test {
          public static void main(String[] args) {
                         String s1 = new String(”Test 2″);
                         String s2 = s1;
                         System.out.println(”s2 = ” + s2);
                         s1 = s1 + ” modified”;
                         System.out.println(”s2 = ” + s2);
          }
}

The code above will print:

Test 2
Test 2

However, the real reason of that is a particularity of the String class. For any other object type, where two references refer to the same object, if either reference modify the object, both references will see the change because there is still only a single object. But any time we make any changes to a String, the Virtual Machine will update the reference variable to refer to a different object.

After the assignment,  s1 and s2 variables refer to diferrent String objects, so the reference used to modify the String refer to the new object, which not modify the older one.


Fernando

Older Posts »

Blog at WordPress.com.