Skip to content

Instantly share code, notes, and snippets.

@anhldbk
Created July 24, 2015 07:29
Show Gist options
  • Save anhldbk/a6a2511202ece881065c to your computer and use it in GitHub Desktop.
Save anhldbk/a6a2511202ece881065c to your computer and use it in GitHub Desktop.
RESTful with Vert.x
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vertx.java.core.Handler;
import org.vertx.java.core.Vertx;
import org.vertx.java.core.VertxFactory;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.core.http.RouteMatcher;
import java.io.IOException;
public class LinguisticsServer {
private final static Logger logger = LoggerFactory.getLogger(LinguisticsServer.class);
protected Vertx vertx = VertxFactory.newVertx();
private static LinguisticsServer instance = null;
private RouteMatcher routeMatcher;
/**
* Constructor
*/
private LinguisticsServer(){
this.initialize();
}
/**
* Singleton pattern
* @return The current & only instance
*/
public synchronized static LinguisticsServer getInstance() {
if(instance == null){
instance = new LinguisticsServer();
}
return instance;
}
private void initialize(){
routeMatcher = new RouteMatcher();
routeMatcher.get("/users/get", new Handler<HttpServerRequest>() {
public void handle(HttpServerRequest request) {
//Get user and write to response
}
});
routeMatcher.post("/users/create", new Handler<HttpServerRequest>() {
public void handle(final HttpServerRequest request) {
//Create user and write to response
int i =0;
request.expectMultiPart(true);
// handle form data
request.endHandler(new Handler<Void>() {
@Override
public void handle(Void aVoid) {
String uname = request.formAttributes().get("username");
String upass = request.formAttributes().get("password");
System.out.println(uname + " " + upass);
request.response().end();
}
});
// handle body raw data
request.bodyHandler(new Handler<Buffer>() {
@Override
public void handle(Buffer buffer) {
int i = 0;
}
});
}
});
routeMatcher.put("/users/update", new Handler<HttpServerRequest>() {
public void handle(HttpServerRequest request) {
//Update user and write to response
}
});
routeMatcher.delete("/users/delete", new Handler<HttpServerRequest>() {
public void handle(HttpServerRequest request) {
//Delete user and write to response
}
});
}
/**
* Activate the server
*/
public void run() {
vertx.createHttpServer()
.requestHandler(routeMatcher)
.listen(8080);
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
getInstance().run();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment