Wednesday, May 11, 2011

JSON-RPC from Android

There is a dearth of utilities on the Internetz that describe how to make a JSON-RPC 2.0 call from an Android device to a server somewhere. Attempts to create handy classes and posts on StackOverflow never quite seemed to do the trick. So... here it is. No fanfare.

Suppose you want to send this JSON string using HTTP using Content-type: application/json
{"jsonrpc":"2.0","method":"myMethod","params":[{"first":"A","second":"B"}],"id":"0"}

What makes this different from a regular HTTP call is the presence of an attachment and the Content-type: application/json designation. Here is the POST method:

 public HttpResponse doPost() throws JSONException, ClientProtocolException, IOException {
  HttpClient client = new DefaultHttpClient();
  
  JSONObject json = createMethodCall("myMethod", createMethodParams());
  Log.d(LOGTAG, json.toString());
    
  HttpResponse response = client.execute(createRequest(json));
  return response;
 }

I use the org.json libaries to construct my JSON object because the toString() method produces syntactically-correct JSON with no effort on my part:

 public JSONObject createMethodCall(String method, JSONArray params) throws JSONException {
  JSONObject json = new JSONObject();
  
  json.put("jsonrpc", "2.0");
  json.put("id", "0");   // we don't really use this so value is always zero
  json.put("method", method);
  json.put("params", params);

  return json;
 }
 
 public JSONArray createMethodParams() throws JSONException {
  JSONArray params = new JSONArray();
  
  // Default params that appear in all method calls
  params.put(new JSONObject().put("first", "A"));
  params.put(new JSONObject().put("second", "B"));
  
  // To add custom parameters, add to the return value rather than here, or this method becomes messy
  return params;
 }

The final trick is that HttpEntity is the Java object for MIME attachments. Therefore, attaching the JSON string as a StringEntity and declaring the content type as "application/json" is required for the server to recognize it as a valid JSON-RPC call.

 public HttpPost createRequest (JSONObject json) throws UnsupportedEncodingException {
  HttpPost request = new HttpPost(this.server + this.url);

  StringEntity entity = new StringEntity(json.toString());
  request.setEntity(entity);
  request.setHeader("Accept", "application/json");
  request.setHeader("Content-type", "application/json");
  
  return request;
 }

I suppose I could have gotten fancy and created a library that packages JSON-RPC more cleanly, but I chose to organize it as a collection of convenience methods. Here is the call from the parent code:

 RemoteCall remote = new RemoteCall();
 String response = null;
 try {
  response = remote.doPost();
 } catch (Exception e) {
  e.printStackTrace();
 }

Monday, May 9, 2011

Toggling Eclipse auto-suggest

The LogCat issue I described the other day caused a secondary problem: the auto-suggest feature in Eclipse was disabled! Well, to be fair I think I received a pop-up message about it, but who reads those anyway? So I accepted the message, and sadly, auto-suggest was gone.

To get it back, go to: Preferences > Java > Editor > Content Assist > Advanced. Make sure "Java Proposals" are enabled.

Friday, May 6, 2011

LogCat output is empty

I am using SpringSource Tool Suite which is a souped-up version of Eclipse (it comes with all kinds of plugins pre-installed as well as embedded servlet engines). The Android SDK comes with Log4J packaged, and the log output is shown in a window known as "LogCat". If this view isn't currently open, go to: Window > Show View > Other... > Android > LogCat

So.... For a few days, LogCat was producing output as expected. Then, it just went silent. Even restarting STS didn't bring back my beautiful logs. It turns out, whether coincidentally or otherwise, the MyLyn plugin causes some interaction as postulated in this post.

I did verify, on Mac OS X, that removing all JARs beginning with "org.eclipse.mylyn" causes LogCat to resume normally.

Thursday, May 5, 2011

Finding a Maven Repository

When you define a dependency in pom.xml, you are telling your compiler where to go get JARs from in the Maven archive. This way, you don't need to maintain your libraries and if they are updated, you simply change the version number in your pom.xml file.

If you know what dependency you need, for example, Apache Commons/IO, browse to a Maven mirror such as:
http://mirrors.ibiblio.org/pub/mirrors/maven2/
when you navigate down to:
http://mirrors.ibiblio.org/pub/mirrors/maven2/commons-io/commons-io/
The first and second directories represent the Group ID and the Artifact ID. For example:
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.0.1</version>
        </dependency>
In the above example, the reuse of "commons-io" makes it unclear, but the canonical form is:
http://mirrors.ibiblio.org/pub/mirrors/maven2/groupId/artifactId/

Wednesday, April 27, 2011

Creating a JSON-RPC service using Maven, Eclipse, and Tomcat

Oddly, there are very few resources for creating JSON-RPC services implemented using Java. JSON-RPC is a nice way for heterogeneous servers to communicate using a lightweight protocol. Because of the hierarchical nature of JSON plus its readiness for easy conversion to native domain objects, one would expect it to be a POJO by now.

However, that is not the case, and implementation requires download of third-party libraries such as jsonrpc4j. The site suggests that you create a Maven project to link to their JARs, write a couple of classes, and you magically have a JSON-RPC service. I beg to differ.

Setup

First, you need to create a Maven project, which is a macro available in SpringSource Tool Suite. Select File > New > Project... > Maven Project. Most importantly, you get a pom.xml and a /src/main directory with this macro. The Apache Web site specifies that directories in a Maven project are specified by convention. Therefore, to conform to Maven convention, you need to add a java/ directory under /src/main.

If you are a newbie to Spring, simply following the instructions in the site are not enough. In addition, you must add:

<servlet>
<servlet-name>remoting</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>remoting</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

to your web.xml. In addition, the XML file containing the properties should be named remoting-servlet.xml. Again, this is according to Spring convention.

You will need to add the following line to your interface:

import com.googlecode.jsonrpc4j.JsonRpcParamName;

and you may need to fiddle with pom.xml a little bit (I had to force Maven to use Java 1.6). In the meantime, Eclipse will likely display syntax errors but you may need to ignore them.

Compiling

The first time you attempt to compile using Maven, you should create a Run Configuration. To get the Base Directory, Browse the Workspace and select the project name. Under Goals, enter "eclipse:eclipse". Run the project once. If it succeeds, the only thing you've done is to force Eclipse to load the JARs declared in pom.xml. The syntax checker should be accurate from this point on.

Change the Goals to "clean install". As long as you don't declare new JARs, you should not need to change your Run Configuration again. Select this configuration to build your WAR file.

Deploying

Assuming you have a Tomcat instance available to you (I installed one on Ubuntu using "sudo apt-get install tomcat6"). Copy the WAR file to /var/lib/tomcat6/webapps/.

Testing

Because this is a JSON-RPC service, the most appropriate way to test is to use the following cURL command:

curl -v http://localhost:8080/projname/myServlet -d @test.json

where test.json may look like:

{
"jsonrpc": "2.0",
"method": "createUser",
"params":[
{"firstName": "Dean"}
],
"id": "0"
}

If it works, you are supposed to get a JSON response back, representing the deserialized Java object.

However, it didn't work for me. Yet.

Saturday, February 12, 2011

Access denied for user 'root'@'client machine name' (using password: YES)

I encounter this error frequently both at work and on the occasional home project. While attempting to connect to a MySQL server using say, MySQL Workbench, I get the following:

Access denied for user 'root'@'client machine name' (using password: YES)

To resolve this, there are three specific things you need to do. Please keep in mind that I'm a developer so please refer to a sys admin for more sophisticated solutions.
  1. Make sure MySQL is listening for incoming connections and that port 3306 is open
  2. Grant (remote) user privileges to your MySQL server
I'm using Ubuntu 10.10 (64-bit). I installed MySQL using

sudo apt-get install mysql-server mysql-client

and tested the installation using

mysql -u root -p
show databases;

In MySQL Workbench (I have 5.2.31 for Mac OS X), create a "New Connection" to "Start Querying", and provide the connection credentials (IP address of the MySQL server, username "root", and root password. You will likely see the error message described by the title of this blog.

Make sure MySQL is listening for incoming connections and that port 3306 is open

Perform steps 1 through 4 as described in this blog. I found that step 5 isn't necessary if you're just playing around and want to administer your own instance using the tools in Workbench.  Also, steps 6 and 7 aren't necessary because the default Ubuntu installation allows connections on all ports by default (!!!)

A simple test from your client computer is:

telnet [server ip address] 3306

You should see something meaningful but cryptic.  If you see "connection refused", then you will need to do step 6 above because it means the port has been disallowed by default (or your sys admin).

Grant (remote) user privileges to your MySQL server

Execute the following SQL query:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'some_pass' WITH GRANT OPTION;

Sunday, December 19, 2010

Using Cisco VPN on Snow Leopard

This is a great blog on setting up your VPN (Cisco IPsec only) on your Snow Leopard machine. Crazy, but neither Mac OS nor Cisco appear to have a supported standalone client.