SimpleAdder Tutorial - shannah/CN1RPC GitHub Wiki

This tutorial will show you how to build the most basic of client-server applications using CN1RPC. The application will consist of two projects:

  1. A Java Web Project for the server

  2. A Codename One project for the client.

You can view or download the full source of the project in this tutorial here, or here for the maven version.

Screencast

You can watch this 6.5 minute screencast of this tutorial, and follow along with the written tutorial if you like.

If you want to see the same tutorial (greatly truncated with no voice over) using a Maven project, see this screencast.

Project Layout

We will create a parent folder to store the two projects:

/path/to/adder-tutorial/
    adder-client/
        ... the codename one client project
    adder-server/
        ... the java web project

Step 1: Create the Server Project

Select "File" > "New Project" in Netbeans.

File New Project

In the "New Project" panel, select "Java Web Project".

Java Web Project

Now set the project directory to be the "adder-tutorial" directory that we created for this project, and the project name to be "adder-server", as shown below:

Server project settings

And click next. The next form asks you to set up your development server settings. You could use any Java server, but in this example, I’ll use GlassFish 4.1, and deployment context matching the server project name "/adder-server", as shown below:

Server settings

Then click next. The last form of the wizard just asks which frameworks you want to use. We won’t select any frameworks since this is such a simple app.

Frameworks panel

And click "Finish"

Once the wizard finishes generating the base project, you should see the project listed in the Projects explorer on the left. The first things we need to do is disable "Compile on Save" as this feature tends to break code generation with annotations.

Right click the "adder-server" item in the project explorer, and select "Properties" from the context menu:

Select project properties

Select "Compile" from the left side of the properties dialog, and uncheck the "Compile on Save" box:

Disable compile-on-save

Press "OK" when done.

The server project is now created.

Step 2: Create the Client Project

The client project will be a Codename One project. So once again select "New Project" from the "File" menu.

File New Project

In the "New Project" dialog, select "Codename One Project":

Select codename one project

And click "Next"

For the project name enter "adder-client" and place it in the same "adder-tutorial" directory that we placed the server project in:

Codename One project settings

And click "Next". Enter the project settings as shown below. You could pick your own package name, main class name, theme, and template, but this is my tutorial, so we’ll go with my selections here:

Codename One project settings 2

Click "Finish".

At this point your project explorer should look something like this with both your client and server projects listed:

Project explorer with client and server projects

Step 3: Add CN1RPC Library to Server Project

Note
If you are using Maven for your server project, use the maven install instructions and proceed to Step 4.

Download the CN1RPC and Java Poet jars and copy them into your server project’s "lib" directory.

Note
The links in this tutorial may be old, so you should check the Releases page for the latest download links.

Once in your adder-server/lib directory, you should add the jars to your project class path.

So right click on the "adder-server" item in the project inspector and select "Properties" again.

Select server properties

Select "Libraries" on the left menu of the dialog, and click the "Add Jar/Folder" button on the right:

Libraries panel to add jar folder

This will open a dialog to select the two jar files that we downloaded. Navigate in this file dialog and select both jar files:

Select jar files in file dialog

Once these are selected, you can click "OK" and exit the properties panel. Our project should now have all of the dependencies that we need. We can proceed to creating our web service.

Step 4: Create a Web Service

Now we are going to create our web service on the server. This is just a POJO with a public static method for doing addition.

We begin by creating a new java class for this. In Netbeans we will expand the "Source Packages" node under our "adder-server" node in the project explorer, right click on the "<default package>" package, and select "New" > "Java Class" as shown below:

New java class

In the "New Class" dialog we’ll enter the fully qualified name for the class "com.codename1.demos.adder.SimpleAdder" as shown below.

New class dialog

And click "Finish".

Then enter the following contents for the class in the editor:

package com.codename1.demos.adder;

import com.codename1.ws.annotations.WebService;

@WebService(exports="../../../adder-client")
public class SimpleAdder {
    public static int addInts(int a, int b) {
        return a+b;
    }
}

Some explanations:

  1. The @WebService annotation is a magic annotation that allows this class to be used as a web service. More on that in a moment.

  2. The exports="../../../adder-client" will result in client files being automatically generated to serve as a proxy for this server and installed in our client project. The "../../../adder-client" string is a relative path from the server’s source root directory to the client project so that Javac knows where to install the client files.

  3. We defined the single static method addInts which will be automatically published over HTTP so that it can be used as a web service. The @WebService annotation results in all public static methods being published in this way. If you want to make a method in this class that is not published as a web service, simply make them non-public or non-static.

If you save this file you should notice that it has already added a file named "SimpleAdderProxy.java" to your client project:

SimpleAdderProxy added

Step 5: Call the Web Service from the Client

Now that the client project has the SimpleAdderProxy class, it can call the web service directly. Let’s open the AdderClient.java file in the client project. At first it will just include the standard Hello World content.

Add the following method:

    public int showAdditionResult() throws IOException {
        SimpleAdderProxy proxy = new SimpleAdderProxy("http://localhost:8080/adder-server");
        return proxy.addInts(2, 3);

    }

This instantiates our proxy. The argument is the URL to where the server app will be deployed on our development instance of Glass Fish. This code should be fairly self explanatory.

Note
The proxy uses invokeAndBlock under the covers, making it safe to call on the EDT.

And update the start method to show the result of this addition.

    public void start() {
        if(current != null){
            current.show();
            return;
        }
        Form hi = new Form("Hi World");
        hi.addComponent(new Label("Hi World"));
        try {
            hi.addComponent(new Label("The result is "+showAdditionResult()));
        } catch (IOException ex) {
            Log.e(ex);
        }
        hi.show();
    }

Here, we just add a label that shows the result of the addition.

The full AdderClient class after these modifications looks like:

package com.codename1.demos.adder;


import com.codename1.io.Log;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.Label;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import java.io.IOException;


public class AdderClient {

    private Form current;

    public void init(Object context) {
        try {
            Resources theme = Resources.openLayered("/theme");
            UIManager.getInstance().setThemeProps(theme.getTheme(theme.getThemeResourceNames()[0]));
        } catch(IOException e){
            e.printStackTrace();
        }
        // Pro users - uncomment this code to get crash reports sent to you automatically
        /*Display.getInstance().addEdtErrorHandler(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                evt.consume();
                Log.p("Exception in AppName version " + Display.getInstance().getProperty("AppVersion", "Unknown"));
                Log.p("OS " + Display.getInstance().getPlatformName());
                Log.p("Error " + evt.getSource());
                Log.p("Current Form " + Display.getInstance().getCurrent().getName());
                Log.e((Throwable)evt.getSource());
                Log.sendLog();
            }
        });*/
    }

    public void start() {
        if(current != null){
            current.show();
            return;
        }
        Form hi = new Form("Hi World");
        hi.addComponent(new Label("Hi World"));
        try {
            hi.addComponent(new Label("The result is "+showAdditionResult()));
        } catch (IOException ex) {
            Log.e(ex);
        }
        hi.show();
    }

    public void stop() {
        current = Display.getInstance().getCurrent();
    }

    public void destroy() {
    }

    public int showAdditionResult() throws IOException {
        SimpleAdderProxy proxy = new SimpleAdderProxy("http://localhost:8080/adder-server");
        return proxy.addInts(2, 3);

    }
}

Step 6: Deploy the Server App

In Netbeans we can deploy the app on GlassFish by simply clicking the "Run" button (or right click on the "adder-server" project and select "Run".

Step 7: Run the Client App

Once the server is running, we can test our client app in the Codename One simulator. We can do this also by just running the "adder-client" project in Netbeans. The result should look something like:

Codename One Simulator

Troubleshooting

If your client project didn’t work as expected (Murphy’s law), run through this checklist:

  1. Make sure your server project has "Compile on Save" disabled.

  2. Try to Clean Build, then run the Server project. If it is successful, the server project should automatically open your system web browser to a placeholder index page.

  3. Try to clean build the client project.

Ready for Something Harder

This was about the simplest client-server app that we can build. But you’ll probably need to do some more complex things, such as passing POJOs (plain-old-java objects) as parameters and return values rather than simple primitive types.

See the Movie Database Tutorial to learn how to pass POJOs as parameters to your web service.

⚠️ **GitHub.com Fallback** ⚠️