Embedding rest2mobile in java projects

The rest2mobile command line can be embedded in script, but if you want to call rest2mobile directly from java code, then the r2m-cli github repo also implements a simple java client.

The rest2mobile’s simple java client is a lightweight version of r2m. It is a simple java executable with no support for history, completion, and all extra commands found in r2m. You build by compiling the cli-simple sub-module, or you can found the executable shaded in the r2m-cli releases

Given a REST example file (below), invoking it is quite simple. For instance, just copy paste this in your shell.

[code lang=”java”]cat << EOF > myexample.txt
+Name foo
java -jar magnet-tools-cli-simple-1.1.0.jar -e myexample.txt


This generates a class RestController with a foo method (along with tests) for iOS, Android, and JavaScript that can invoke a fictitious REST API at http://foo.com/a/b/c/?q=1 under the mobile directory.

This is the generated directory structure:

[code lang=”java”]$ tree mobile
├── android
│   ├── com
│   │   └── magnet
│   │   └── controller
│   │   └── api
│   │   ├── RestController.java
│   │   └── RestControllerFactory.java
│   └── src
│   └── test
│   └── java
│   └── com
│   └── magnet
│   └── controller
│   └── api
│   └── test
│   └── RestControllerTest.java
├── ios
│   ├── Podfile
│   ├── Source
│   │   ├── Controllers
│   │   │   ├── RestController.h
│   │   │   └── RestController.m
│   │   └── Nodes
│   └── Tests
│   └── RestControllerSpec.m
└── js
├── Beans
└── Controllers
└── RestController.js

Now let’s take a look at its usage:

[code lang=”java”]$ java -jar magnet-tools-cli-simple-1.1.0.jar -h
Usage: [options] [ios|js|android]
-c, –class
Controller class name to generate
Default: RestController
-e, –examples
Examples location. Can be URL, file, or directory
-f, –force
Force deletion of target directory before regenerating the code
Default: false
-h, –help
Get this usage
Default: false
-n, –namespace
Namespace to prepend to classes (ios, and js only)
-o, –out
Output directory
Default: mobile
-p, –package
Controller class name to generate
Default: com.magnet
-j, –policy
Policy to handle empty property in json, choose from
-t, –trace
Enable tracing
Default: false
-v, –verbose
enable verbose mode
Default: false

As you see, the options are similar to the r2m gen command’s

In fact, both Xcode and Android Studio/IntelliJ plugins use the simple java client to generate native code (Android Studio directly calls the java API, while the Xcode plugin simply runs the executable in a separate process).

It’s very easy to do the same:

  • embed it your java project by invoking the com.magnet.tools.cli.simple.Main(String[] args) method, or
  • for non-java clients, execute the shaded or non-shaded jar in a separate process with the right options.

… and you’re good to go.