SparkJava (step 1) – Basics of microservice with Java

sparkjava-logoSparkJava is a small and efficient micro-service framework for the java platform.

Based on the simple JaveSE, it provides all things needed to serve quick and smart REST werbservice, in respect with the Micro-Service paragygm.

Building a quick and securized Rest WebService is no more than writing a simple java class containing the famous main(String[]) method !

to create a minimalistic JSON REST Web service you will need :

file : App.java

package com.webcontext.apps;
import static spark.Spark.*;
public class App {
 private static final String WS_SECRET_KEY="MySecretkey";
 public static void main(String[] args) {
   // retrieve some data
 get("/post", (request, response) -> {
   // ....
 });
 // retrieve some data with parameters
 get("/post/:id", (request, response) -> {
   // ....
 return "Post id: " + request.params(":id");
 });
 // Create some data
 post("/post", (request, response) -> {
   // ....
 });
 // Update some data
 put("/post/:id", (request, response) -> {
 String postId = request.params(":id");
   // ....
 });
 // delete some data
 delete("/", (request, response) -> {
   // ....
 });
}

And add in the same class the following code. all request to the applicaiton will be « filtered » by this before method to verify the presence of a WS-KEY attribute in the Http header:

 /**
  * Verify some thing in header on each request (authentication ?!)
  */
  before((request, response) -> {
   boolean authenticated = ( ( request.getHeader("WS-KEY")!=null) 
        && request.getHeader("WS-KEY").equals(WS_SECRET_KEY);
      if (!authenticated) {
        halt(401, "You are not welcome here");
      }
    }); 
  } 
 
}

Ant the small utility class to serve object as JSON

file : JsonTransformer.java

public class JsonTransformer implements ResponseTransformer {

    private Gson gson = new Gson();

    @Override
    public String render(Object model) {
        return gson.toJson(model);
    }

}

Now the url http://localhost:4567/post will serve a 401 error page if no WS-KEY is provide, or if authorization key is here, will serve a list of posts in a JSON format.

See the demonstration project at https://github.com/mcgivrer/sparkpost

just clone the repo locally,

  $> git clone git@github.com:mcgivrer/sparkpost.git

build it:

  $> mvn clean install

and run it !

  $> java -jar target/sparkpost-0.0.1-SNAPSHOT.jar

And navigate to http://localhost:9000/post

You must been showed with « a non welcome message » :

Capture du 2018-01-23 01-21-07

But if you use a REST client and add a specific header :

WS-KEY=MySecretkey

And request the previous URL (here is a screenshot from the Chrome Postman ReST client):

Capture du 2018-01-23 01-19-24

The sparkpost app will reply a small response corresonding to the HTTP request proposed by the first method:

// retrieve some data 
get("/post", (request, response) -> { 
  return "list of posts"; 
}, new JsonTransformer());

And if we test other request with our HTTP REST client, we will get similar response.

Capture du 2018-01-23 01-45-36

Ok the first steps are covered. Now, we will go further by adding some database information and a MongoDb server instance for some DevOps tests.

To Be Continued…

References

SparkJava

– SparkJava Documentation link (http://sparkjava.com/documentation.html)

Maven

we are using maven, please find bellow the used dependencies and plugins:

Dependencies

Capture du 2018-01-23 02-01-45

Maven Plugins

Capture du 2018-01-23 02-02-02

 

Publicités

Les commentaires sont fermés.

Propulsé par WordPress.com.

Retour en haut ↑

%d blogueurs aiment cette page :