Skip to content

Getting started

Sergey Korney edited this page Aug 11, 2017 · 14 revisions

Let’s get started with RestServer. The first thing you need to do, if you haven’t already done so, is download the RestServer library.

Installing with Gradle

Modify your build.gradle to include:

repositories {
    mavenCentral()
    maven { url "https://jitpack.io" }
}

compile 'com.github.skornei:restserver:1.0.3+'

Configuring Your Project

In you application class

public class YouApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        RestServerManager.initialize(this);
    }
}

Create entity

public class TestEntity {

    private String test;

    public TestEntity() {

    }

    public TestEntity(String test) {
        this.test = test;
    }

    public String getTest() {
        return test;
    }
}

Create converter (example JeckSon)

public class JsonConverter implements BaseConverter {

    private ObjectMapper mapper = new ObjectMapper();

    @Override
    public byte[] writeValueAsBytes(Object value) {
        try {
            return mapper.writeValueAsBytes(value);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public <T> T writeValue(byte[] src, Class<T> valueType) {
        try {
            return mapper.readValue(src, valueType);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Create classes for controllers. Don’t worry though, this part is easy.

@RestController("/ping")
public class PingController {

    @GET
    public void ping() {
        System.out.println("work!");        
    }

    @POST
    @Produces(ResponseType.APPLICATION_JSON)
    public TestEntity test(Context context, RequestInfo request, ResponseInfo response, TestEntity testEntity) {
        return new TestEntity(testEntity.getTest() + ":test");
    }

    private static String getStackTrace(Throwable throwable) {
        StringWriter stringWriter = new StringWriter();
        throwable.printStackTrace(new PrintWriter(stringWriter));
        return stringWriter.toString();
    }

    @ExceptionHandler
    @Produces(ResponseType.TEXT_PLAIN)
    public void handleThrowable(Throwable throwable, ResponseInfo response) {
        String throwableStr = getStackTrace(throwable);
        response.setBody(throwableStr.getBytes());
    }
}

Create server class

@RestServer( port = MainServer.PORT,
             converter = JsonConverter.class,
             controllers = {PingController.class} )
public class MainServer extends BaseRestServer {
    public static final int PORT = 8080;
}

Init module in you class.

private MainServer mainServer = new MainServer();

...

mainServer.start(); or mainServer.stop();

How to check?

curl -i -X POST -H "Content-Type: application/json;charset=UTF-8" -d '{"test":"12345"}' 'http://192.168.1.1:8080/ping'
Clone this wiki locally