11

I have a few utility methods that I wrote in Java, for test data creation against a service. A couple of my colleagues who have the same use case thought it would be cool if they could re-use it, but they are writing their tests in Perl and Python respectively. So I am thinking of standing up a JSON REST service that would expose these methods.

I have limited experience writing web-apps. What would be the fastest way to stand up and deploy my service?

I am thinking of using eclipse/spring to do it and ant to deploy on a Jetty container. But I would like to hear your experiences about this. Also it seems some IDEs/Plugins have better support for some technologies than others. So I would like to hear what IDE/Plugins + J2EE Technology stack + Server(If that matters) is a good combination for my usecase and why. I would like to stick to open source software.

3
  • 1
    Tangent answer, but I've found python + gunicorn to be really speedy for making quick REST mockups when I'm integrating with a 3rd party service
    – user1898811
    May 22, 2013 at 23:44
  • 1
    Thanks for the answer,Ron, but I am really looking for a Java solution since my code is in Java.
    – hyperlink
    May 22, 2013 at 23:48
  • 1
    Take a look at Airbnb's REST stack, which is Jetty, Jersey and Jackson. nerds.airbnb.com/httpjson-services-in-modern-java
    – Steve Kuo
    May 23, 2013 at 5:09

9 Answers 9

12

I believe using Maven gets you up as fast as one can. Here's how you can do it.

It uses the RESTEasy implementation of JAX-RS (the Java API for RESTful Web Services, an official part of Java EE 6).

This is a java war maven project with the bare minimum structure. These are the files:

-pom.xml
-src
 |
  --main
    |
     --java
       |
        --rest
          |
           --HelloResource.java
           --JaxRsActivator.java

I called it simpleRest as seen below. All the archives are exactly as shown:

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                        http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>simpleRest</groupId>
    <artifactId>simpleRest</artifactId>
    <version>1.0</version>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-jaxrs</artifactId>
            <version>2.3.1.GA</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
<build>
    <finalName>${project.artifactId}</finalName>
    <plugins>
        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.1.1</version>
            <configuration>
                <!-- So maven doesn't require web.xml -->
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
    </plugins>
</build>
</project>

HelloResource.java

package rest;

import java.util.Date;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/hello")
public class HelloResource {
    @GET
    @Produces("text/plain")
    public String helloResource() {
        return "Hello! It's "+new Date();
    }
}

JaxRsActivator.java:

package rest;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("/rest")
public class JaxRsActivator extends Application {

}

This generates a simpleRest.war (through mvn clean package). You can deploy it to a freshly installed JBoss AS 7.1.1.Final (just throw the war file in the deploy folder) or a Tomcat.

After that, the URL is available as expected:

http://127.0.0.1:8080/simpleRest/rest/hello

How quick is that?

1
  • Thank you, This is a great intro :)
    – hyperlink
    Jun 3, 2013 at 21:27
5

Here's the shortest way I could think of to a fully functional REST API requiring only Java, Gradle, and a text editor. Create two files in a clean project directory as follows:

build.gradle

buildscript {
    repositories { mavenCentral() }
    dependencies {
        classpath 'org.gradle.api.plugins:gradle-tomcat-plugin:0.9.8'
    }
}
apply plugin: 'tomcat'

repositories { mavenCentral() }
dependencies {
    compile(
        'com.sun.jersey:jersey-core:1.17',
        'com.sun.jersey:jersey-server:1.17',
        'com.sun.jersey:jersey-servlet:1.17',
        'com.sun.jersey:jersey-json:1.17',
    )
    tomcat(
        'org.apache.tomcat:tomcat-catalina:7.0.40',
        'org.apache.tomcat:tomcat-coyote:7.0.40',
        'org.apache.tomcat:tomcat-jasper:7.0.40',
    )
}

src/main/java/org/example/TheApplication.java

package org.example;

import com.sun.jersey.api.core.ClassNamesResourceConfig;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import javax.xml.bind.annotation.XmlRootElement;

@Path("/")
@ApplicationPath("/")
public class TheApplication extends ClassNamesResourceConfig {
    public TheApplication() { super(TheApplication.class); }

    static Foo foo = new Foo();

    @GET @Produces("application/json")
    public Foo getFoo() {
        return foo;
    }

    @POST @Consumes("application/json")
    public Response setFoo(Foo foo) {
        TheApplication.foo = foo;
        return Response.ok().entity("Stored it!").build();
    }

    @XmlRootElement
    static class Foo {
        private String message = "Hello World";
        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }
    }
}

Once those two files are in place, gradle tomcatRunWar will start your REST API, and navigating to http://localhost:8080/fastest-web-service/ in a browser will get you the "Hello World" JSON message. If you then POST similar JSON, like {"message": "something else"} to that same URL with something like curl or Poster specifying a Content-Type of "application/json", that new object will be stored and returned on successive GET requests. It's just a very bare-bones example but covers a lot of the basics of a JSON API.

IDEs: You could further develop this easily with any common Java IDE. The Community Edition of IntelliJ IDEA and Eclipse are both popular and free IDEs. <opinion>IDEA is far superior and the Ultimate Edition is 110% worth the cost of a personal license for a regular Java developer.</opinion>

Technology Stack: JAX-RS is a leading way of writing REST APIs in Java. Pick any implementation. This example uses Jersey, the reference implementation. Spring may be overkill if you just need a simple API to expose already-written logic. It brings along more complexity than it sounds like you need. On the other hand, if you need a more flexible and capable framework that has more built-in support for virtually everything in the world, Spring may be just the ticket.

Server: Jetty or Tomcat supporting Servlet 3.0. There's not likely a reason for anything more or less.

0
1

Well I'm going to toss the NetBeans IDE bundled with GlassFish 3.x in to the ring.

Download that bundle, install it, and JAX-RS serving up services is a right-click wizard away. One download, one install, completely comprehensive. Lots of documentation, wizards, and samples.

It's really the shortest path, and it's a complete toolkit.

0
0

What we are going for in my company is an Apache TomEE server, using JAX-RS to expose our API as REST services. It is easy to set up and easy to work with.

0

I have good experience with Jersey, which is the reference implementation of jax-ws. It has support for jax-ws annotations, and it's easy to use.

0

As a consultant, I get paid for solving problems. I found that Espresso Logic is the fastest way for me to deliver JSON/REST API. It runs on a Tomcat foundation and can easily be deployed locally, on Elastic Beanstalk, or Microsoft Azure. It connects to all the major SQL databases and gives me an instant REST API for all tables, views, stored-procedures, and relationships (which are used to build more complex document style resources). It has both an HTML Studio and a Node.JS command line for administration. The best feature is the declarative logic (like a spreadsheet) for formula, derivations, and validations. The logic can be extended using both JavaScript and Java plugin libraries. I spend my time writing JavaScript solutions and letting Espresso do the heavy lifting of REST pagination, optimistic locking, SQL query optimization, and multi-table transaction logic. Full disclosure - I have known them for 25 years and this is the best game-changing technology I have seen. Check it out: www.espressologic.com

0

To speed up using the Jersey framework along the lines of https://stackoverflow.com/a/3891380/1497139

we (BITPlan - my company) have created the following open source projects:

  1. https://github.com/BITPlan/com.bitplan.simplerest
  2. https://github.com/BITPlan/com.bitplan.simplerest-api
  3. https://github.com/BITPlan/com.bitplan.simplerest-example

See the code samples below how to setup:

  1. a server
  2. some application content to be used (User)
  3. some Resource exposing the content (UserResource)
  4. a test case showing that things work

Test for Example

package com.bitplan.simplerest.example;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

import com.bitplan.rest.RestServer;
import com.bitplan.rest.test.TestRestServer;

/**
 * test the example Server
 * @author wf
 *
 */
public class TestExampleServer extends TestRestServer {
  boolean debug=true;
  @Before
  public void initServer() throws Exception {
    startServer();
  }

  @Override
  public RestServer createServer() throws Exception {
    RestServer result = new ExampleServer();
    return result;
  }

  @Test
  public void testExampleServer() throws Exception {
    String userXml=getResponseString("application/xml", "/example/user");
    if (debug)
      System.out.println(userXml);
    String expected="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><user><name>Doe</name><firstname>John</firstname><email>[email protected]</email></user>";
    assertEquals(expected,userXml);
    String userJson=getResponseString("application/json", "/example/user");
    if (debug)
      System.out.println(userJson);
    String expectedJson="{\"name\":\"Doe\",\"firstname\":\"John\",\"email\":\"[email protected]\"}";
    assertEquals(expectedJson,userJson);

  }

}

ExampleServer

package com.bitplan.simplerest.example;

import com.bitplan.rest.RestServerImpl;

/**
 * an Example Server
 * @author wf
 *
 */
public class ExampleServer extends RestServerImpl { 

  /**
   * construct Example Server
   * setting defaults
   * @throws Exception 
   */
  public ExampleServer() throws Exception {
    // listen to whole network
    settings.setHost("0.0.0.0");
    // listen on given port
    settings.setPort(8111);
    // add the default path
    settings.setContextPath("/example");
    // add a static handler
    settings.addClassPathHandler("/", "/static/");
    // setup resources from the given packages
    String packages="com.bitplan.simplerest.example.resources;";
    settings.setPackages(packages);
   }

  /**
   * start Server
   * 
   * @param args
   * @throws Exception
   */
   public static void main(String[] args) throws Exception {
     ExampleServer rs=new ExampleServer();
     rs.settings.parseArguments(args);
     rs.startWebServer();
   } // main

}

User

package com.bitplan.simplerest.example;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * example class
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class User {
  public String name;
  public String firstname;
  public String email;

}

User Resource

package com.bitplan.simplerest.example.resources;

import javax.ws.rs.GET;
import javax.ws.rs.Path;

import com.bitplan.simplerest.example.User;


@Path("/user")
public class UserResource {
  @GET
  public User getUser() {
    User user=new User();
    user.name="Doe";
    user.firstname="John";
    user.email="[email protected]";
    return user;
  }
}
0

I would like to suggest the following approach to write REST-based Web Services. The follow "script" will guide you to create a very simple, and lightweight, web project using Kikaha and Undertow. The bellow approach is quite similar to the JAXRS-based example provided by Ryan Stewart, but with higher performance and low footprint due to Undertow's architecture (Undertow is really fast).

  1. Use the Kikaha's command line tool to create a stub project:

    kikaha project create 2.0 --name=my-app

  2. Although the above command brings you a couple REST API classes out-of-box, you can create your own entity class that represents your business rule as shown bellow.

User.java

import lombok.*;

@Getter
@Setter
public class User {
    @NonNull Long id;
    @NonNull String name;
}
  1. Create a route class. It will expose methods as REST endpoints.

UserResource.java

import lombok.*;
import kikaha.urouting.api.*;
import javax.inject.*;

@Singleton
@Path("user")
@Consumes( Mimes.JSON )
@Produces( Mimes.JSON )
public class UserResource {

    User savedUser;

    @POST
    public Response saveUser( User user ){
        if ( user.getName().isEmpty() )
            return DefaultResponses.preconditionFailed()
                    .entity("Name is blank");

        savedUser = user;
        return DefaultResponses.ok();
    }

    @GET
    public User getUser(){
        return savedUser;
    }
}
  1. Run your 5Mb project through the command line:

    kikaha run-app

Disclaimer: I was involved with Kikaha's development and have implanted many Undertow projects since its first version.

0

All the answers apply to using Java locally with a local container. If you're considering cloud environments that support Java (and Java-like extensions), you might be able to do this with just one like.

The Raimme platform offers a convenient @Rest annotation. All you need to do is set the URL, and your REST service will be exposed automatically:

@Rest(url = "customer/list")
@ResponseBody
public String getCustomer()
{
    return "[]";
}

This whole feature is described in more detail here: http://raimme.com/devcenter?questionId=1cg000000000g

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.