refcodes-rest: RESTful services using lambdas

refcodes-rest: RESTful services using lambdas

Update [2018-05-05@22:11]: Added the section Error handling on server-side error handling mechanisms.


README

The REFCODES.ORG codes represent a group of artifacts consolidating parts of my work in the past years. Several topics are covered which I consider useful for you, programmers, developers and software engineers.

What is this repository for?

With this artifact you easily create your serverless RESTful services and REST clients. The refcodes-rest artifact lets you do it the Bare-Metal way or the syntactic sugar (see client sugar or server sugar) way (meaning the use of statically imported methods):

RESTful server

  1. Instantiate the RESTful server
  2. Register your lambda expressions
  3. Start the RESTful server

Within three simple steps you implement your lightweight Java based RESTful server. Below, you see the three steps with the help of a little syntactic sugar:

 1 // STEP 1: We use a singleton with syntactic sugar instead of instantiating a HttpRestServer:
 2 import static org.refcodes.rest.HttpRestServerSugar.*;
 3   ... 
 4   public static void main( String[] args ) {
 5     // STEP 2: Using syntactic sugar, we register our lambda expression:
 6     onGet( "/say/${name}=*", ( aRequest, aResponse ) -> {
 7       String name = aRequest.getWildcardReplacement( "name" );
 8       aResponse.getHeaderFields().withContentType( MediaType.APPLICATION_JSON ).withAddCookie( "greeting", "Hello " + name + "!" ); 
 9       return "Hello " + name + "!" ;
10     } ).open();
11     // STEP 3: We open the HttpRestServer singleton on port 8080 using our syntactic sugar:
12     open( 8080 );
13   }
14   ...

The TinyRestfulServer demo application uses syntactic sugar for setting up a RESTful server including command line arguments parsing.

REST client

  1. Instantiate the REST client
  2. Register your lambda expression for the response
  3. Fire the client’s REST request

Again, within three simple steps you implement your lightweight Java based REST client. Below you see the three steps with the help of a little syntactic sugar:

 1 // STEP 1: We use a singleton with syntactic sugar instead of instantiating a HttpRestClient: 
 2 import static org.refcodes.rest.HttpRestClientSugar.*;
 3   ... 
 4   public static void main( String[] args ) {
 5     // STEP 2: Using syntactic sugar, we define our caller, including the response listener:
 6     doGet( "http://mydomain:8080/say", ( aResponse ) -> {
 7       ... = aResponse.getResponse( SomeType.class );
 8     } ).withRequest( ... ).open();
 9     // STEP 3: We opened the caller so it fires the request to port 8080 of domain "mydomain"
10   }
11   ...

How do I get set up?

To get up and running, include the following dependency (without the three dots “…”) in your pom.xml:

1 <dependencies>
2   ...
3   <dependency>
4     <artifactId>refcodes-rest</artifactId>
5     <groupId>org.refcodes</groupId>
6     <version>1.3.3</version>
7   </dependency>
8   ...
9 </dependencies>

If you want the framework to interoperate with SLF4J logging, you may instead add the following dependencies to your pom.xml:

 1 <dependencies>
 2   ...
 3   <dependency>
 4     <artifactId>refcodes-rest</artifactId>
 5     <groupId>org.refcodes</groupId>
 6     <version>1.3.3</version>
 7   </dependency>
 8   <dependency>
 9     <groupId>org.refcodes</groupId>
10     <artifactId>refcodes-logger-alt-slf4j</artifactId>
11     <version>1.3.3</version>
12   </dependency>
13   ...
14 </dependencies>

The artifact is hosted directly at Maven Central. Jump straight to the source codes at Bitbucket. Read the artifact’s javadoc at javadoc.io.

How do I get started with the RESTful server?

Above you saw an example on how to setup your own RESTful service using syntactic sugar. One drawback of using syntactic sugar is that we can only make use of the one HttpRestServerSingleton (as of this syntactic sugar being the statically imported methods), preventing us from running multiple HttpRestServer instances on different ports in one Java application.

Lets do it the Bare-Metal way, which is not very complicated either, and which lets us instantiate as many HttpRestServer instances as we want:

 1 ...
 2 public static void main( String[] args ) {
 3   // STEP 1: We instantiate our HttpRestServer:
 4   HttpRestServer theRestServer = new HttpRestServerImpl();
 5   // STEP 2: We register our lambda expression:
 6   theRestServer.onGet( "/say/${name}=*", ( aRequest, aResponse ) -> {
 7     String name = aRequest.getWildcardReplacement( "name" );
 8     aResponse.getHeaderFields().withContentType( MediaType.APPLICATION_JSON ).withAddCookie( "greeting", "Hello " + name + "!" );
 9     return "Hello " + name + "!" ;
10   } ).open();
11   // STEP 3: We open the HttpRestServer instance on port 8080:
12   theRestServer.open( 8080 );
13 }
14 ...

The Locator-Pattern

Did you notice the Locator-Pattern "/say/${name}=*" above when registering your lambda? Subscribing your lambda expressions for incoming REST requests on specific locators, you may use a common wildcard syntax to define the lambda’s Locator-Pattern:

  • A single asterisk (*) matches zero or more characters within a locator name.
  • A double asterisk (**) matches zero or more characters across directory levels.
  • A question mark (?) matches exactly one character within a locator name.

The single asterisk (*), the double asterisk (**) and the question mark (?) we refer to as wildcard: You get an array with all the substitutes of the wildcards using the method RestRequestEvent#getWildcardReplacements().

You may name a wildcard by prefixing it with “${someWildcardName}=”. For example a named wildcard may look as follows: “${arg1}=*” or “${arg2}=**” or “${arg3}=?” or as of the example above "/say/${name}=*". When your lambda is being invoked, you can retrieve the wildcard substitution by the name of the wildcard which has been substituted (by parts of the incoming locator). You can get the text substituting a named wildcard using the method RestRequestEvent#getWildcardReplacement(String).

As of refcodes-rest version 1.1.3 a placeholder “${arg1}” with no wildcard assignment “=” is equivalent to “${arg1}=*”. In the example above you could have used "/say/${name}" instead of "/say/${name}=*".

Error handling

In case an Exception gets thrown while your lambda is processing an HTTP-Response due to an incoming HTTP-Request, you may either handle it manually in your lambda expression or you may use a predefined behavior or you may even register a custom global Exception handler. The predefined behavior is configured as follows:

1 ...
2 HttpRestServer theRestServer = new HttpRestServerImpl().withHttpExceptionHandling( HttpExceptionHandling.REPLACE );
3 ...

The behavior is specified by the enumeration HttpExceptionHandling. You currently have the following options on how an exceptional situation is handled:

  • HttpExceptionHandling.REPLACE: Create a new HTTP-Response with the according HTTP-Status-Code and the error description fields.
  • HttpExceptionHandling.UPDATE: Keep the so far processed HTTP-Response as is except the HTTP-Status-Code and also update all error description fields. Useful when you want to preserve already set fields.
  • HttpExceptionHandling.MERGE: Keep the so far processed HTTP-Response as is except update the actual HTTP-Status-Code, add only non-existing fields if possible with the error description fields. Useful when you manually prepared the HTTP-Response yourself.
  • HttpExceptionHandling.KEEP: Do not modify the so far processed HTTP-Response except update the actual HTTP-Status-Code. Useful when you manually prepared the HTTP-Response yourself.
  • HttpExceptionHandling.EMPTY: Create a new HTTP-Response with the according HTTP-Status-Code and and an empty body.

In case the Media-Type used is Application/JSON, then the error description fields generated by the predefined exception handler looks as follows:

1 {
2   "status": {
3     "exception": "org.refcodes.net.NotFoundException",
4     "code": "404",
5     "alias": "NOT FOUND",
6     "message": "There is none endpoint for handling resource locator </repl/sessionsx> with HTTP-Method <GET>.",
7     "timestamp": "1525436619219"
8   }
9 }

This custom global exception handler is represented by an instance of the functional interface HttpExceptionHandler being registered to your HttpRestServer. You may register it using the lambda notation:

1 ...
2 HttpRestServer theRestServer = new HttpRestServerImpl().withOnHttpException( ( request, response, exception, statusCode ) -> {
3   // ...
4   response.setResponse( new HttpBodyMapImpl().withPut( "message", exception.getMessage() ) );
5   // ...
6 } );
7 ...

The RESTful server’s bits and pieces

How do I get started with the REST client?

Above you saw an example on how to setup your own REST client using syntactic sugar. One drawback of using syntactic sugar is that we can only make use of the one HttpRestClientSingleton (as of this syntactic sugar being the statically imported methods), preventing us from running multiple HttpRestClient instances in one Java application (which is actually no real drawback, as the HttpRestClientSingleton can fire at any HTTP or HTTPS targets you wish to connect to).

Lets do it the Bare-Metal way, which is not very complicated either, and which lets us instantiate as many HttpRestClient instances as we want:

 1 ...
 2 public static void main( String[] args ) {
 3   // STEP 1: We instantiate our HttpRestClient:
 4   HttpRestClient theRestClient = new HttpRestClientImpl();
 5   // STEP 2: We register our lambda expression:
 6   theRestClient.doRequest( HttpMethod.POST, "http://mydomain:8080/say", ( aResponse ) -> {
 7     String theResponse = aResponse.getResponse( String.class );
 8   } ).withRequest( ... ).open();
 9   // STEP 3: We opened the caller so it fires the request to port 8080 of domain "mydomain"
10 }
11 ...

The REST client’s bits and pieces

Examples

Please refer to the example code at bitbucket.org/refcodes/refcodes-rest.

Contribution guidelines

  • Finding bugs
  • Helping fixing bugs
  • Making code and documentation better

Who do I talk to?

  • Siegfried Steiner (steiner@refcodes.org)

Terms and conditions

The REFCODES.ORG group of artifacts is published under some open source licenses; covered by the refcodes-licensing (org.refcodes group) artifact - evident in each artifact in question as of the pom.xml dependency included in such artifact.

comments powered by Disqus