Skip to content

Getting started

Sergey Korney edited this page Aug 9, 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.0+'

Configuring Your Project

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 server class

@RestServer( port = 8080,
             converter = JsonConverter.class,
             controllers = {PingController.class} )
public class Server extends BaseRestServer {
}

Init module in you class.

private Server server;

...

server = new Server();

...

server.start(); or server.stop();

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(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());
    }
}

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