DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. Rest with Scala and Vert.x

Rest with Scala and Vert.x

Slim Ouertani user avatar by
Slim Ouertani
·
Mar. 13, 13 · Interview
Like (0)
Save
Tweet
Share
9.40K Views

Join the DZone community and get the full member experience.

Join For Free
A previous post introduced some features of using Scala with Vert.x. This post covers how to publish Rest web services in an elegant and simple fashion.

As in the previous post, Examples in Java and Scala are presented, source code been hosted on GitHub as part of lang-scala https://github.com/ouertani/vert.x/tree/master/vertx-lang/vertx-lang-scala

I- Resticle

Resticle is a unit of deployment dedicated to Rest. It provides a new method (“handles”) which can be used by Vert.x to start Rest services. “handles” returns a sequence of rest handlers :

  • RestHandler : Action => Response
  • Action :
    • GET(pattern : String)
    • POST (pattern : String)
    • PUT (pattern : String)
    • DELETE(pattern : String)
    • HEAD (pattern : String)
    • ALL(pattern : String)
  • Response : HttpServerRequest => Any
    • OK, Unauthorized,....

In this tutorial we will be working with the SampleResticle class, for both scala and java.

II - Hello World

Vert.x provides a powerful routing and route matching mechanism, which simplifies the routing of HTTP requests to different handlers based on pattern matching on the request path.

In Hello World snippet, let us publish a static GET service :

  • GET : /hello → code : 200 , body : world
Scala
			
class SampleResticle extends Resticle 
{
  override def handles = 
         { GET("/hello")      :>  OK( _ => "world ") }
}
Java
public class SampleResticle extends Verticle {
 
    public void start() {
        HttpServer server = vertx.createHttpServer();
        RouteMatcher routeMatcher = new RouteMatcher();
        routeMatcher.get("/hello", new Handler<HttpServerRequest>() {
            public void handle(HttpServerRequest req) {
                req.response.statusCode =200;
                req.response.end("world");
            }
        });
        server.requestHandler(routeMatcher).listen(8080, "localhost");
    }
}

III- Chaining Handlers

Using Resticle we can chain handlers quit easily. The following snippets create static GET and DELETE services :

  • GET : /hello → code : 200 , body : world
  • DELETE : /posts → code : 401 , body : Not allowed user
Scala
class SampleResticle extends Resticle 
{
  override def handles = 
         { GET("/hello")      :>  OK( _ => "world ") } ++
         { DELETE("/posts")   :>  Unauthorized {_ => "Not allowed user" }} 
}
java
public class SampleResticle extends Verticle {
 
    public void start() {
        HttpServer server = vertx.createHttpServer();
        RouteMatcher routeMatcher = new RouteMatcher();
        routeMatcher.get("/hello", new Handler<HttpServerRequest>() {
            public void handle(HttpServerRequest req) {
                req.response.statusCode =200;
                req.response.end("world");
            }
        });
         routeMatcher.delete("/posts", new Handler<HttpServerRequest>() {
            public void handle(HttpServerRequest req) {
                req.response.statusCode =401;
                req.response.end("Not allowed user");
            }
        });
        server.requestHandler(routeMatcher).listen(8080, "localhost");
    }
}

IV - Value path

Vert.x pattern matching lets you extract values from the path and use them as parameters in the request.

  • GET : /hello → code : 200 , body : world
  • DELETE : /posts → code : 401 , body : Not allowed user
  • POST : /:blogname → code : 200 , body : post {blogname} received !

 

Scala : ( Using String interpolation)
class SampleResticle extends Resticle 
{
  override def handles = 
         { GET("/hello")      :>  OK( _ => "world ") } ++
         { DELETE("/posts")   :>  Unauthorized {_ => "Not allowed user" }} ++
         { POST("/:blogname") :>  OK {req  => val param = req.params().get("blogname") ; s"post $param received !" } }
}
Java
public class SampleResticle extends Verticle {
 
    public void start() {
        HttpServer server = vertx.createHttpServer();
        RouteMatcher routeMatcher = new RouteMatcher();
        routeMatcher.get("/hello", new Handler<HttpServerRequest>() {
            public void handle(HttpServerRequest req) {
                req.response.statusCode =200;
                req.response.end("world");
            }
        });
         routeMatcher.delete("/posts", new Handler<HttpServerRequest>() {
            public void handle(HttpServerRequest req) {
                req.response.statusCode =401;
                req.response.end("Not allowed user");
            }
        });
 
         routeMatcher.post("/:blogname", new Handler<HttpServerRequest>() {
            public void handle(HttpServerRequest req) {
                req.response.statusCode =200;
                String blogName = req.params().get("blogname");
                req.response.end("post "+blogName+ " received !");
            }
        });
 
        server.requestHandler(routeMatcher).listen(8080, "localhost");
    }
}

V- Json

Let’s assume we have a Blog class with two String fields title and content :

case class Blog (title :String , content : String)

The java equivalent has been relocated to the end of the document due to its verbosity ;).

Publishing an object using Resticle is simple and transparent due to implicit convertor : T => Buffer.

Scala ( Type Class)
object Blog {
  implicit def toBuffer(blog : Blog):Buffer = JsonObject.withString("title" -> blog.title).withString("content" -> blog.content)
}
Java ( with explicit convertor )
public class Convertor {
    public static  JsonObject toJson(Blog blog) {
       return new JsonObject().putString("title", blog.getTitle()).putString("content", blog.getContent());
    } 
}
  • GET : /hello → code : 200 , body : world
  • DELETE : /posts → code : 401 , body : Not allowed user
  • POST : /:blogname → code : 200 , body : post {blogname} received !
  • GET : /:id → code : 200 , body : {"title":"rest","content":"scala & vertx"}
Scala
class SampleResticle extends Resticle 
{
  override def handles = 
         { GET("/hello")      :>  OK( _ => "world ") } ++
         { DELETE("/posts")   :>  Unauthorized {_ => "Not allowed user" }} ++
         { POST("/:blogname") :>  OK {req  => val param = req.params().get("blogname") ; s"post $param received !" } } ++
         { GET("/:id")        :>  OK ( _ => Blog("rest","scala & vertx"))}
}
Java
public class SampleResticle extends Verticle {
 
    public void start() {
        HttpServer server = vertx.createHttpServer();
        RouteMatcher routeMatcher = new RouteMatcher();
        routeMatcher.get("/hello", new Handler<HttpServerRequest>() {
            public void handle(HttpServerRequest req) {
                req.response.statusCode =200;
                req.response.end("world");
            }
        });
         routeMatcher.delete("/posts", new Handler<HttpServerRequest>() {
            public void handle(HttpServerRequest req) {
                req.response.statusCode =401;
                req.response.end("Not allowed user");
            }
        });
 
         routeMatcher.post("/:blogname", new Handler<HttpServerRequest>() {
            public void handle(HttpServerRequest req) {
                req.response.statusCode =200;
                String blogName = req.params().get("blogname");
                req.response.end("post "+blogName+ " received !");
            }
        });
 
        routeMatcher.get("/:id", new Handler<HttpServerRequest>() {
            public void handle(HttpServerRequest req) {
                req.response.statusCode =200;
                Blog blog =  new Blog("rest","scala & vertx");
                JsonObject obj = Convertor.toJson(blog);
                req.response.end(obj.encode());
            }
        });
 
        server.requestHandler(routeMatcher).listen(8080, "localhost");
    }
}

Java Blog

public class Blog {
 
    private final  String title;
    private final String content;
 
    public Blog(String title, String content) {
        this.title = title;
        this.content = content;
    }
 
    public String getTitle() {
        return title;
    }
 
    public String getContent() {
        return content;
    }
  }

Conclusion

Despite the fact that Resticle is in first development step, Rest support is by far simpler and elegant in scala than in java. As described in first tutorial Vert.x java version is burdened with a frightening number of handlers. Will Vert.x 2.0 address this point using Promises/Deferred APIs ?

 

Scala (programming language) Vert.x

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How To Check Docker Images for Vulnerabilities
  • Differences Between Site Reliability Engineer vs. Software Engineer vs. Cloud Engineer vs. DevOps Engineer
  • Better Performance and Security by Monitoring Logs, Metrics, and More
  • A Brief Overview of the Spring Cloud Framework

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: