Book Excerpt: Real World Jakarta REST Example

The following in an excerpt from Practical Cloud-Native Java Development with MicroProfile from Packt Publishing. It is available for pre-order from Amazon.com and directly from Packt. It is scheduled for release in September. This excerpt comes from chapter 4: Building Cloud-Native Applications and describes how to build a more real-world RESTful application using Jakarta REST (aka JAX-RS):


A More Real-world Example

Now that we have built a simple JAX-RS application, let’s build a more complex application – a thesaurus service where clients can search and update synonymous words. First, we’ll start with an exception mapper:

@Provider
public class NoSuchWordExceptionMapper implements ExceptionMapper<NoSuchWordException> {

    @Override
    public Response toResponse(NoSuchWordException ex) {
        return Response.status(404)
                       .entity(ex.getMessage())
                       .build();
    }
}

Most applications will have business exceptions – exceptions specific to the application domain. For a thesaurus service, that might include a NoSuchWordException, which could be used to indicate that a searched word does not exist. It is clear in the application that somebody specified a word that does not exist, but it is not clear to an HTTP client. The provider class, NoSuchWordExceptionMapper, makes that possible. It enables the resource class methods to throw a NoSuchWordException, and the JAX-RS container will map the exception to an HTTP response (in this case, a 404 Not Found).

Next is the resource class (full source code available at: https://github.com/PacktPublishing/Practical-Cloud-Native-Development-with-MicroProfile-4.0/blob/main/Chapter04/src/main/java/com/packt/microprofile/book/ch4/thesaurus/ThesaurusResource.java ):

@Path(“/thesaurus/{word}”)
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public class ThesaurusResource { // … 

There are a few new annotations on the resource class: @Produces and @Consumes. These annotations can be placed on resource classes or methods – like most annotations of this type in JAX-RS, annotations on the method take priority over annotations on the class. These annotations help control the matching of requests and the entity providers (MessageBodyReaders and MessageBodyWriters) to be used in deserializing the HTTP entity from the request or serializing the HTTP entity in the response.

HTTP requests and responses may contain a header that indicates the media type (also known as MIME type) of the HTTP entity – Content-Type. HTTP requests may also contain a header that specifies the media type(s) that it expects to receive in the response – Accept. In the absence of these headers, all media types are allowed (i.e., */*).

In the previous example, the resource class specifies MediaType.TEXT_PLAIN, or text/plain. Other media types include text/html, application/json, application/xml, image/jpeg, and much more. By specifying text/plain, that would prevent the resource methods from being invoked if a request contained a header like Content-Type: application/pdf or Accept: image/png – instead of invoking the resource method, the JAX-RS container would return a 415 Unsupported Media Type error.

Best practice:
Always use @Produces and @Consumes to limit media types. This will place limits on the types of requests your service will respond to. It will ensure that your application (if properly tested) can handle requests of the specified media types.

This example also introduces new method-level HTTP verb annotations: @POST, @PUT, @DELETE and @PATCH. Like @GET, these annotations specify which method should be invoked based on the HTTP request’s verb (also known as method – HTTP method is probably the more commonly used term, but we will use verb in this book to disambiguate from Java methods). The JAX-RS API set includes these five verb annotations as well as @HEAD and @OPTIONS that are less commonly used.

Special note:
If the resource class contains a method annotated with @GET but not @HEAD, the JAX-RS container would invoke the @GET method for matching HTTP HEAD requests, but it would remove the entity. Likewise, if a resource class contains any HTTP verb annotation other than @OPTIONS, the JAX-RS container would return a response indicating all of the valid verbs that could be matched for that request. Using the example above, an OPTIONS request would result in a response with a header like, Allow: DELETE, HEAD, GET, OPTIONS, PATCH, POST, PUT.

This example also introduces the idea of HTTP parameters, specifically:
@PathParam(“word”) String word;

This annotation can be placed on fields or method parameters. The value of @PathParam is word which corresponds to the template variable in the resource class’s @Path value (“/thesaurus/{word}”). This means that for an HTTP request like http://localhost:9080/myApp/rest/thesaurus/funny, the value injected in to the word field would be funny.

There are other HTTP parameter types that can be used in JAX-RS including @QueryParam, @FormParam, @CookieParam, @HeaderParam, @MatrixParam which all correspond to different parts of an HTTP request. JAX-RS also allows multiple HTTP parameter annotations to be aggregated on a single Java class and then referenced in the resource class or method as a @BeanParam.


I hope you found this excerpt helpful and enticing. Chapter 4 is packed (pun intended) full of useful knowledge for building and consuming robust RESTful services. It covers the basics, but also a lot of hidden gems in JAX-RS, JSON-B/P, CDI and MicroProfile Rest Client. And if that’s not enough, there’s eleven more chapters filled with cloud-native goodness. Ok, that’s enough advertising for one blog post… 🙂 Thanks for reading!

Practical Cloud-Native Java Development with MicroProfile

For the past six months, I’ve had the privilege to work with some amazing co-authors (Emily Jiang, John Alcorn, David Chan and Alasdair Nottingham) and a super-supportive publisher (Packt) to produce the definitive guide to Java Cloud-native development.

So, what’s in it? My co-authors and I don’t like fluff – it’s titled Practical for a reason. The book takes a deep dive into MicroProfile technologies – this include some of the technologies that MP “borrowed” from Jakarta (REST, CDI, JSON-P/B) as well as the original MicroProfile technologies like Rest Client, Config, Fault Tolerance, Metrics, etc. and some of the standalone MP technologies like GraphQL and LRA. But this book isn’t a textbook – there are practical examples with a real-world application at the core.

We also cover deployment strategies like how to run and test your application in open source servers like Open Liberty – then deploy in Docker and Kubernetes. All of the examples in the book are available in GitHub.

So, where can I get it? I’m glad you asked! It’s available for pre-sale on Amazon and Packt. It’s scheduled to release in September, 2021.

Anything else you can tell me about it? You bet! I plan to post some excerpts from the book on this site in the next few weeks. Stay tuned!

Restructuring JSON with JAX-RS ReaderInterceptors and a little bit of JSON-B Magic

Have you ever needed to consume a RESTful service but the data structure of the remote service just didn’t quite match with what you had in mind in your client application?  I ran into this situation earlier this week while exploring some commercial REST APIs. In my case, I had some JSON like this:

{
  "links":{
    "self":"https://api.myhost.com/services/v2/music?titleSearch=10%2C000"
  },
  "data":[
    {
      "type":"Song",
      "id":"56780987",
      "attributes":{
        "admin":"EMI Christian Music Publishing",
        "author":"Jonas Myrin and Matt Redman",
        "ccli_number":6016351,
        "copyright":
          "2011 Thankyou Music, Said And Done Music, and SHOUT! Publishing",
        "created_at":"2014-11-10T17:31:26Z",
        "hidden":false,
        "last_scheduled_at":"2021-05-30T08:49:00Z",
        "last_scheduled_short_dates":"May 30, 2021",
        "notes":"Vocal Range B - D'",
        "themes":", Adoration, Blessing, Christian Life, Praise",
        "title":"10,000 Reasons (Bless The Lord)"
      },
      "links":{"self":"https://api.myhost.com/services/v2/music/8802060"}
    }
  ],
  "included":[],
  "meta":{
    "total_count":1,
    "count":1,
    "can_order_by":["title","created_at","updated_at","last_scheduled_at"],
    "can_query_by":["author","ccli_number","themes","title"],
    "parent":{
        "id":"132275",
        "type":"Organization"
    }
  }
}

This JSON looks like a nicely formed HATEOAS response from a RESTful service providing song information. However, there are a few obstacles if we want to simply convert it into a Java object in our application like this:

public class Song {
    private String id;
    private String title;
    private String author;
    private LocalDate lastScheduled;
    // ... more fields, and public getters/setters ...
}

The first obstacle is that the object returned in the JSON response is not a Song object – it is a complex object that contains the song data (under the data field) and other RESTful navigational fields like links and meta.  To overcome this obstacle, we could create some sort of MetaSong object that has fields for data, links, etc., but unless we plan to use those other fields that seems like a waste. Fortunately there is a better way!

Upon receiving the response, we could intercept the JSON data and reformat it before the JAX-RS client or MicroProfile Rest Client interface converts the JSON to a Java object. We do that with a ReaderInterceptor provider, like this:

public class DataExtractionReaderInterceptor implements ReaderInterceptor {

    @Override
    public Object aroundReadFrom(ReaderInterceptorContext context)
        throws IOException, WebApplicationException {

        InputStream is = context.getInputStream();
        JsonObject json = Json.createReader(is).readObject();
        JsonValue data = json.get("data");
        is = new ByteArrayInputStream(data.toString().getBytes())
        context.setInputStream(is);
        return context.proceed();
    }
}

This code is executed on the client after the response is returned to the client but before the response is converted to a Java object. It uses JSON-P APIs to read the response stream and then extracts the data field, then replaces the response stream with a new stream that only includes that data object.

The second obstacle is that the song’s JSON fields don’t match the Java object’s fields. The JSON has a field called attributes, and the relevant fields like title, author, etc. are all child fields of that.  But in the Java object, these fields are all directly under the Song class. We can overcome this obstacle with a little JSON-B magic:

public class Song {
    private String id;
    private String title;
    private String author;
    //...

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }

    public void setAttributes(Map<String,Object> attrs) {
        setTitle((String)attrs.get("title"));
        setAuthor((String)attrs.get("author"));
        // ...
    }
}

By default, JSON-B maps the JSON fields to Java fields by calling the appropriate setter method (e.g., JSON id is a String and would map to the setId Java method). However, since we don’t want to create a separate Attributes Java class to handle the JSON child fields, we instead create a placeholder method, setAttributes that takes a Map<String, Object> parameter.  Now, JSON-B will pass in the JSON attributes object as key-value pairs that we can then map to the appropriate fields on our Song Java object.

Now all we need to do is invoke the service using either the JAX-RS Client or MicroProfile Rest Client APIs. The full source code including a runnable sample is available at https://github.com/andymc12/sample-restructure-json-data.

Thanks for checking in! As always, please let me know if you have any questions or comments.


“Physical Map of Asia (1920)” by Eric Fischer is licensed under CC BY 2.0

What’s Coming in Jakarta REST 3.1?

The ink is still drying on Jakarta EE 9 / 9.1 and the Jakarta RESTful Web Services 3.0 specs, but the REST community isn’t slowing down.  While vendors and developers are rapidly adopting EE 9, the Jakarta REST (aka JAX-RS) community is actively preparing for future releases.


DISCLAIMER: Everything in this post is planned as of the time of writing, but is subject to change without notice.


Our plans for a standalone 3.1 release have been approved. What does standalone mean? Just that it won’t be included in a larger Jakarta EE umbrella release. That might hinder adoption for some vendors who are more concerned about only implementing full profiles, like the Jakarta EE Platform or Web Profile. Still, I expect many vendors will offer the 3.1 release – either as a standalone product or feature, or as an extension of their EE 9/9.1 implementation.  Other vendors may wait for an EE 10 release, which should include all of the new features from 3.1 as well as newer features from a proposed Jakarta REST 4.0 release.


Ok, so what should we expect in Jakarta REST 3.1? Here are the proposed new features:

Java SE Bootstrap API

The idea here is to make it easier to build and deploy a RESTful service without the need of a full EE container/server/etc. Servers like Open Liberty, WebSphere Application Server, and Wildfly are great, but wouldn’t it be nice to be able to launch a RESTful service in Java SE sometimes? The use cases could include setting up a “mock” server to test your client code against, or even a production ready service that might not need all of the bells and whistles that a full server environment might provide.


See the Jakarta REST examples for how to code it.

Support for Multipart

The multipart/form-data content type has been around for a long time – and is often used to transfer multiple disparate data types from one point to another. For example, you might apply for a job on a site and send your name and address in an HTML form that also includes your resume (DOC or PDF file) and your picture (PNG, JPG, etc.). Under the hood, this is sent as a multipart request.


Until now, the Jakarta REST spec has not defined how to accept incoming multipart content or how to send it. Vendors have implemented their own approach at providing APIs for sending and receiving multipart content, but the 3.1 spec makes this portable and provides a way for all vendor implementations to provide the same level of functionality.


There are some examples for how to code it here.

JSON-B Alignment

A few years back, Adam Bien wrote an excellent blog post on how to configure JSON-B in a Jakarta REST application. The only trouble is that at that time, the approach only worked with Eclipse Jersey. Since then other implementations (including Open Liberty via Apache CXF) also enabled this functionality, but it will become a standard in 3.1, enabling more portable usage of JSON-B configuration.


What does JSON-B configuration really mean? Let’s say that you want your RESTful service to always use a specific naming strategy when converting from Java field names to JSON. This is something you would configure in a JsonbConfig object. But in order to ensure that your Jakarta REST app uses that configuration, you would need to register a ContextResolver<JsonbConfig> provider that returns your customized config object.

Provider Extensions

Most Jakarta REST applications are self-contained artifacts – usually WARs or fat/thin JARs, etc. But there are times, particularly in cloud environments, where you may want to add extensions to the application for additional qualities of service. For example, maybe you’d like to add some monitoring extensions to collect performance metrics, diagnostic tracing, or audit logging. Using the new provider extension support in Jakarta REST 3.1, these types of extensions could be applied outside of the application packaging. This will allow vendors and other third-party library developers to build extension JARs that can be added to the classpath of the application for quick and easy activation. This is all handled using the ServiceLoader mechanism.

Deprecation of @Context for better CDI Integration

Historically, JAX-RS and CDI were developed around the same time by two different groups. As such both groups built their own dependency injection mechanism. JAX-RS’s dependency injection mechanism is specific to RESTful services and injects a limited number of object types that are annotated with @Context. CDI is much more flexible and is intended to be the de facto injection mechanism for all of Jakarta EE – it uses the more common @Inject annotation. In 3.1, the Jakarta REST community made the decision to replace their component-specific injection mechanism with CDI. In a future release (presumably 4.0), the @Context annotation will be removed.
This should pave the way for vendors to reduce install footprint by using a single dependency injection mechanism. It also will allow more flexibility beyond just injection in RESTful applications. If you’re not familiar with CDI, you can learn more about it in the Open Liberty CDI guide.

The future of REST in Java certainly looks bright. What new features would you like to see?  Please feel free to leave a comment with your ideas here or open an issue at the Jakarta REST GitHub site. Until then, stay RESTful! 😉

Introduction

Hi. I’m Andy. I’ve been developing software in some form or another since I was a pre-teen. One of my first “products” was a Zork-like text adventure game on my dad’s Commodore 64, written in BASIC. I was the star of my 7th grade science fair! Since then, I’ve played with various languages like Pascal and C/C++. When I was college I took a Java Jan-Term class and fell in love – well, at least as close to love as is socially acceptable when talking about a programming language.

I knew I wanted to work with Java, and so when IBM offered me a job to work in Java on the server-side on the WebSphere Application Server, I was all-in. I’ve been at IBM almost 20 years now – and still never too far from “WAS”. I’ve worked on the logging and tracing framework, the EJB container, the classloader and OSGi runtime, and most recently I’ve worked as the Web Services Architect – playing (yes playing, this stuff is fun for me!) with RESTful services and GraphQL.

Along the way, I’ve met and worked with many wonderful people, and have learned a lot. My hope is to share some of my experiences and ideas on this site. Even after 20+ years of learning, I still don’t know it all – and I’m still learning – so if I get something wrong, or if you know of a better way to do something, please let me know.

A little more about me:

  • I’m married with three awesome kids.
  • Music is a big part of my life. I play bass (primary) and guitar (still learning), and all of my kids are currently taking lessons in various instruments. I’ve even dabbled in writing music.
  • I’m a Christian, and my faith is also a big part of my life. I play on my church’s praise team and like to volunteer to help people whenever I can.

Thanks for checking out my site.

MicroProfile Rest Client 2.0 – First Look

Originally posted on March 24, 2021 at:
https://openliberty.io/blog/2021/03/24/whats-new-in-MP-Rest-Client2.0.html

The latest release of MicroProfile’s type-safe REST client has a lot of new and exciting features. In this post, we’ll take a look at some of the new features and how you can use them in Open Liberty, including:

Getting started

The MicroProfile Rest Client 2.0 implementation is new in Open Liberty 21.0.0.3 – so make sure you are using the latest version of Liberty. Next, you will need to add the following Maven dependency to your pom.xml:

<dependency>
    <groupId>org.eclipse.microprofile.rest.client</groupId>
    <artifactId>microprofile-rest-client-api</artifactId>
    <version>2.0</version>
    <scope>provided</scope>
</dependency>

or, if you use Gradle:

dependencies {
    compileOnly group: 'org.eclipse.microprofile.rest.client', name: 'microprofile-rest-client-api', version: '2.0'
}

Also, make sure to configure your Liberty server with the mpRestClient-2.0 feature in the server.xml:

<server>
  <featureManager>
    <feature>mpRestClient-2.0</feature>
    <!-- ... -->
  </featureManager>
  <!-- ... -->
</server>

That’s it! Now that we’ve got our development and deployment environments set up, it’s time to code!

Using QueryParamStyle to specify how collections of query parameters should be formatted

Rest Client interfaces can specify query parameters using the @QueryParam("paramName") annotation, but often a server will require that multi-valued query parameters must be formatted in a certain way. For example, suppose we have a client interface like:

@RegisterRestClient
public interface MyClient {
    @GET
    String multiValues(@QueryParam("myParam") List<String> values);
}

By default, if a caller invokes the client with multiValues(Arrays.asList("a", "b", "c")) the MP Rest Client will produce an HTTP request with multiple key/value pairs – something like: ?myParam=a&myParam=b&myParam=c.

Although most servers will handle that just fine, some servers might require the HTTP request to be a single key with a comma-separated list of values, like: ?myParam=a,b,c.

Still other servers will require array-like syntax, such as: ?myParam[]=a&myParam[]=b&myParam[]=c.

In order to support those other server types, you can now use the QueryParamStyle enum when building the client instance – for example:

MyClient client = RestClientBuilder.newBuilder()
                                   .queryParamStyle(QueryParamStyle.COMMA_SEPARATED)
                                   //...
                                   .build(MyClient.class);

Alternatively, you can declare the query parameter style through MP Config by using a property like:

com.mypkg.MyClient/mp-rest/queryParamStyle=ARRAY_PAIRS

The following table lists the QueryParamStyle enum values and provides an example of the corresponding output for each value.

Enum ValueOutput Example
MULTI_PAIRS (default)?myParam=a&myParam=b&myParam=c
COMMA_SEPARATED?myParam=a,b,c
ARRAY_PAIRS?myParam[]=a&myParam[]=b&myParam[]=c

Proxy server support

You might need to use a proxy server to access some RESTful endpoints. MicroProfile Rest Client 2.0 makes it easier and more portable to specify a proxy server with the new proxyAddress(host, port) method on the RestClientBuilder class. For example, suppose you need to access an endpoint via a proxy server at myproxy.xyz.com on port 1080. You could build your rest client instance with code like:

MyClient client = RestClientBuilder.newBuilder()
                                   .proxyAddress("myproxy.xyz.com", 1080)
                                   //...
                                   .build(MyClient.class);

Alternatively, you can specify the proxy address via MP Config with a property like:

com.mypkg.MyClient/mp-rest/proxyAddress=myproxy.xyz.com:1080

Note that for portability, this approach to setting the proxy server host and port is preferred to using vendor-specific properties such as com.ibm.ws.jaxrs.client.proxy.host and com.ibm.ws.jaxrs.client.proxy.port, though these properties will still work. For proxy authentication, you can still use the com.ibm.ws.jaxrs.client.proxy.username and com.ibm.ws.jaxrs.client.proxy.password properties. For example:

MyClient client = RestClientBuilder.newBuilder()
                                   .proxyAddress("myproxy.xyz.com", 1080)
                                   .property("com.ibm.ws.jaxrs.client.proxy.username", "andymc12")
                                   .property("com.ibm.ws.jaxrs.client.proxy.password", "12345") //same as my luggage! 🙂
                                   //...
                                   .build(MyClient.class);

Automatically following redirects

If a RESTful resource has been relocated, often the HTTP response code will be in the 300 range and will indicate the new location. Rather than handling the 3XX response and manually issuing a new request, MP Rest Client 2.0 allows rest client instances to automatically follow redirects. You can configure a client to automatically follow redirects either programmatically, when you build the client instance, or via MP Config. Here is an example of configuring auto-redirect via the RestClientBuilder API:

MyClient client = RestClientBuilder.newBuilder()
                                   .followRedirects(true)
                                   //...
                                   .build(MyClient.class);

And here is how you would configure it via MP Config:

com.mypkg.MyClient/mp-rest/followRedirects=true

Support for Server Sent Events (SSEs)

Server Sent Events, part of the HTML 5 spec, enable a server to push data to a client asynchronously via events, over HTTP. The JAX-RS 2.1 spec enabled SSE support for both the client and server. Now you can consume SSE events from the type-safe MP Rest Client.

The MP Rest Client specification uses the Reactive Streams APIs to consume events. A client interface capable of consuming SSEs looks something like this:

@RegisterRestClient
public interface SseClient {
    @GET
    @Path("/path/sse")
    @Produces(MediaType.SERVER_SENT_EVENTS)
    Publisher<String> getStrings();
    @GET
    @Path("/path/sse2")
    @Produces(MediaType.SERVER_SENT_EVENTS)
    Publisher<InboundSseEvent> getEvents();
}

First, the method (or interface) must be annotated with @Produces(MediaType.SERVER_SENT_EVENTS) to indicate that it expects the server to produce SSEs. Next, the method’s return type must be org.reactivestreams.Publisher. The generic type can be javax.ws.rs.sse.InboundSseEvent (from JAX-RS), a primitive, a String, or a complex type. Complex types can only be used if;

1) the server only sends one type of event (e.g. only sends WeatherEvents – then Publisher<WeatherEvent> would be applicable)

and

2) there is a registered entity provider capable of converting the events (e.g. MessageBodyReader<WeatherEvent>).

In most cases, if the remote server sends events using JSON, you can enable the jsonb-1.0 feature in your Liberty server, which will automatically register a JSON-B-based entity provider.

Once you invoke one of these methods, you can register one or more Subscriber instances to the Publisher. Each subscriber will be notified on receipt of a new event or if the connection to the server has been closed.

Summary

MicroProfile Rest Client 2.0 has some powerful new features that are useful for building cloud native applications. You can read more about these updates on the MP Rest Client 2.0 release page.

MicroProfile Rest Client 2.0 is part of the larger MicroProfile 4.0 release. If you’d like to learn more about the other technologies in MicroProfile 4.0, check out this deep dive blog post.

As always, let us know if you have any questions with this new feature. Thanks for checking it out!

JAX-RS and Open Liberty: BYO Jackson

Originally posted on November 11, 2020 at:
https://openliberty.io/blog/2020/11/11/byo-jackson.html

Chances are that if you use JAX-RS 2.0 or 2.1 in Open Liberty, then you use JSON to format your data. If so, it’s equally likely that you use Jackson as your JSON provider. Open Liberty’s JAX-RS 2.0 implementation uses Jackson as its default JSON provider.

You might be wondering, That’s pretty cool, but how can I take advantage of Jackson in my application?

Good question! Open Liberty uses Jackson but intentionally doesn’t expose Jackson to user applications. If you want to use some of the cool features in Jackson, such as annotating fields to ignore or providing serialization processing instructions, just bring your own Jackson. In other words, package the Jackson JAX-RS provider JAR files in the WAR file of your application. You need the following JAR files:

The JacksonJsonProvider class is automatically registered if all of these JAR files are in the WEB-INF/lib directory of your WAR file. However, if you specify any classes in your Application subclass by using the getClasses() method or the getSingletons() method, as shown in the following example, then you need to register the JacksonJsonProvider class:

public class HelloWorldApplication extends Application {
    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> classes = new HashSet<>();
        // ...
        classes.add(JacksonJaxbJsonProvider.class);
        return classes;
    }
}

Automatic discovery and registration isn’t available in the JAX-RS Client APIs, so you need to explicitly register the JacksonJsonProvider class:

Client client = ClientBuilder.newClient().register(JacksonJsonProvider.class);

That’s it! Now Open Liberty’s JAX-RS implementation uses the Jackson provider from your application instead of the Jackson provider that’s built into Open Liberty. Your application can now use those cool Jackson features.

You don’t even need to do any classloading tricks, such as specifying your delegation as parentLast. The Open Liberty server doesn’t expose the Jackson API packages, so your application can load only the Jackson classes that you provide. The application also works regardless of the delegation policy, so you can use a parentLast delegation if you really want to.

If you’re interested in learning more about Jackson with Open Liberty, check out the sample.BYOJackson app at the WASdev GitHub repo. By the way, Jackson isn’t the only Java-to-JSON converter that you can choose. If you’re using JAX-RS 2.1, then you can also use JSON-B to get Java-to-JSON (and vice versa) conversion magic provided by Open Liberty. To enable JSON-B, see the JavaScript Object Notation Binding 1.0 feature documentation.

Have it your way with MicroProfile GraphQL!

Originally posted on June 10, 2020 at:
https://openliberty.io/blog/2020/06/10/microprofile-graphql-open-liberty.html

Open Liberty 20.0.0.6 introduces a new feature, MicroProfile GraphQL, which enables developers to quickly and easily write GraphQL applications with MicroProfile.

If you’re here reading about GraphQL in Open Liberty, then chances are that you already know a bit about GraphQL. In short, GraphQL is a remote data access API that addresses issues like under-fetching and over-fetching that are inherent in most RESTful applications. It allows clients to specify the exact data they want – to “have it their way”. If you would like to learn more about GraphQL, I recommend checking out the tutorial at GraphQL.org.

GraphQL applications use a schema that acts as a description of the data provided by the server and as a contract between the client and server. Most GraphQL programming models require developers to dual-maintain their schema and the application code that supports it. MicroProfile GraphQL takes a “code first” approach which allows developers to write Java code using annotations to mark GraphQL schema elements, and then the MicroProfile GraphQL implementation generates the schema at runtime.

The Open Liberty feature Microprofile GraphQL (mpGraphQL-1.0) implements the MicroProfile GraphQL 1.0 specification.

In this blog post, we’ll explore how easy it is to create GraphQL applications using this sample.

Setup

To set up your Maven environment for developing a MP GraphQL application, you’ll need a dependency like:

<dependency>
    <groupId>org.eclipse.microprofile.graphql</groupId>
    <artifactId>microprofile-graphql-api</artifactId>
    <version>1.0.2</version>
    <scope>provided</scope>
</dependency>

I recommend using the Liberty Maven plugin, but it’s not strictly necessary so long as you generate a Web Archive (WAR) file for deployment.

When configuring the Liberty server for deployment, make sure that the featureManager element in the server.xml file contains the mpGraphQL-1.0 feature. For example:

<server>
  <featureManager>
    <feature>mpGraphQL-1.0</feature>
    <feature>mpMetrics-2.3</feature>
  </featureManager>
  <!-- ... -->
</server>

The mpMetrics-2.3 feature is not required, but will track the number of GraphQL query/mutation invocations and cumulative time when enabled.

Now that we’ve got things set up, let’s look at the code.

Coding a MicroProfile GraphQL application

A MicroProfile GraphQL application should have at least one root-level query and/or mutation. To create a query or mutation, you start with a public Java class annotated with @GraphQLApi. Then you add public methods that are annotated with @Query or @Mutation for query or mutation, respectively. The query/mutation methods must always return a non-void type. These methods can return simple types like String, int, double, boolean, etc. which will be mapped to GraphQL scalars such as String, Int, Float, Boolean, etc. Alternatively, these methods could return custom Java types – the types would be mapped to GraphQL types and defined in the generated schema. For more details, see the MicroProfile GraphQL 1.0.2 API Docs.

For example, in the sample application, the currentConditions query method returns a type called Conditions – that type has properties such as temperatureF, temperatureC, precipitationType, weatherText, etc. The following schema is generated from the query and its return value:

type Conditions {
  dayTime: Boolean!
  epochTime: BigInteger!
  hasPrecipitation: Boolean!
  "ISO-8601"
  localObservationDateTime: DateTime
  location: String
  precipitationType: PrecipType
  temperatureC: Float!
  temperatureF: Float!
  weatherText: String
  wetBulbTempF: Float!
}

"Query root"
type Query {
  currentConditions(location: String): Conditions
  currentConditionsList(locations: [String]): [Conditions]
}
...

The currentConditions query has an argument, called location. In the Java code, the argument is represented by a method parameter. Like output types, arguments/parameters can be simple Java types (mapping to GraphQL scalars) or custom types, which would be mapped to input types in the generated schema.

When mapping custom types, it is possible to change the name used in the schema by using the @Name annotation. For example, if we wanted to change the schema to display tempInFahrenheit instead of temperatureF, we could just add @Name("tempInFahrenheit") to the temperatureF field in the Conditions class.

If your application uses JSON-B, then @JsonbProperty, @JsonbDateFormat, and @JsonbNumberFormat annotations can be used instead of @Name, @DateFormat or @NumberFormat. When both sets of annotations are used, the annotations from the MicroProfile GraphQL APIs take precedence over the JSON-B APIs when used for schema generation or query/mutation execution.

Another useful annotation is @Source. This annotation can be used to add a field to an entity object that might be expensive to look up or calculate, and so you might not want to spend the resources on the server side to compute that field when the client doesn’t want it anyway. Here’s an example from the sample:

    public double wetBulbTempF(@Source @Name("conditions") Conditions conditions) {
        // TODO: pretend like this is a really expensive operation
        // ...
        return conditions.getTemperatureF() - 3.0;
    }

This example is a little contrived, but it shows us that the wetBulbTempF field will only be computed if the client requests that field. This method is in a class annotated with @GraphQLApi (in this example, WeatherService) and it contains a parameter annotated with @Source that takes the entity object, Conditions. When a client issues a query or mutation that would return the Conditions entity, and that query/mutation specifies the wetBulbTempF field, the wetBulbTempF(Conditions conditions) method is invoked by the GraphQL implementation, passing in the Conditions object that was returned from the query/mutation method.

Running the MicroProfile GraphQL app

To run and test the GraphQL application, you simply need to deploy it as a WAR file. The Liberty Maven Plugin makes it easy to build, deploy, and test using Apache Maven. After you have cloned the sample from GitHub (git clone git@github.com:OpenLiberty/sample-mp-graphql.git) or downloaded the source ZIP file, just run: mvn clean package liberty:run

This builds, packages, and deploys the GraphQL application to the latest Open Liberty server runtime and starts the server and app. Then you can use the pre-packaged GraphiQL HTML interface to send queries or mutations at: http://localhost:9080/mpGraphQLSample/graphiql.html

Here are a few sample queries and mutations that you could use to get started – you may see some interesting results:

#Temperature (Fahrenheit) for Las Vegas
query LasVegas {
  currentConditions(location: "Las Vegas") {
    temperatureF
  }
}
#Is it really always sunny in Philadelphia?
query SunnyInPhilly {
  currentConditions(location: "Philadelphia") {
    weatherText
  }
}
# Weather conditions for three locations - one roundtrip
query threeLocations {
  atlanta: currentConditions(location: "Atlanta") {
        hasPrecipitation
        temperatureF
        weatherText
        precipitationType
    }
  newyork: currentConditions(location: "New York") {
        hasPrecipitation
        temperatureF
        weatherText
        precipitationType
  }
  chicago: currentConditions(location: "Chicago") {
        hasPrecipitation
        temperatureF
        weatherText
        precipitationType
    }
}
# See partial results when one portion of the query fails
query fourLocations {
  atlanta: currentConditions(location: "Atlanta") {
        hasPrecipitation
        temperatureF
        weatherText
        precipitationType
        wetBulbTempF
    }
  nowhere: currentConditions(location: "Nowhere") {
    hasPrecipitation
        temperatureF
        weatherText
        precipitationType
  }
  newyork: currentConditions(location: "New York") {
        hasPrecipitation
        temperatureF
        weatherText
        precipitationType
  }
  chicago: currentConditions(location: "Chicago") {
        hasPrecipitation
        temperatureF
        weatherText
        precipitationType
        wetBulbTempF
    }
}
# Reset the stored weather conditions
mutation {
  reset
}

Authorizing access to certain queries/mutations

It may be necessary to restrict access to certain queries/mutations to certain authenticated users. While it is not part of the MicroProfile GraphQL 1.0 specification (it is under consideration for a future version of the spec), Open Liberty makes authorization checks possible by using the @DenyAll, @PermitAll, and @RolesAllowed annotations. These annotations must be placed on the class or method of classes annotated with @GraphQLApi.

When implementing authorization with MicroProfile GraphQL, you need to enable the appSecurity-3.0 (or appSecurity-2.0) feature in the server configuration. You also need to set up the user registry and web container metadata for authentication and authorization.

In the sample, we use the basic user registry which defines two users, one for each of two roles:

  <basicRegistry id="basic" realm="sample-mp-graphql">
     <user name="user1" password="user1pwd" />
     <user name="user2" password="user2pwd" />
     <group name="Role1">
       <member name="user1"/>
     </group>
     <group name="Role2">
       <member name="user2"/>
     </group>
   </basicRegistry>

This means that user1 is part of Role1 and user2 is part of Role2. The web.xml declares these roles, and also sets up form-based authentication so that, when the Application Security feature is enabled, clients are prompted to log in using a web-based form before accessing the GraphiQL HTML page. It also allows the application to prevent users other than those in Role2 to invoke the reset mutation method:

    @RolesAllowed("Role2")
    @Mutation
    @Description("Reset the cached conditions so that new queries will return newly randomized weather data." +
                 "Returns number of entries cleared.")
    public int reset() {
        int cleared = currentConditionsMap.size();
        currentConditionsMap.clear();
        return cleared;
    }

Integration with MicroProfile Metrics

If you enable the mpMetrics-2.3 feature with mpGraphQL-1.0, Open Liberty tracks the number of times a particular query or mutation method is invoked—​and the cumulative time spent in that method. These metrics can be useful for determining what data is being accessed, how often, and where time is spent in execution.

Metrics collection and reporting for GraphQL applications is not mentioned in either the MicroProfile GraphQL 1.0 spec or the MicroProfile Metrics 2.3 spec, so the actual stats are collected and reported under the “vendor” category. To see these stats, you can browse to: http://localhost:9080/metrics/vendor

The stats are prefixed with vendor_mp_graphql_ and should look something like this:

# TYPE vendor_mp_graphql_Query_currentConditions_total counter
vendor_mp_graphql_Query_currentConditions_total 27
# TYPE vendor_mp_graphql_Query_currentConditions_elapsedTime_seconds gauge
vendor_mp_graphql_Query_currentConditions_elapsedTime_seconds 0.10273818800000001
# TYPE vendor_mp_graphql_Conditions_wetBulbTempF_total counter
vendor_mp_graphql_Conditions_wetBulbTempF_total 4
# TYPE vendor_mp_graphql_Conditions_wetBulbTempF_elapsedTime_seconds gauge
vendor_mp_graphql_Conditions_wetBulbTempF_elapsedTime_seconds 0.031866015000000004
# TYPE vendor_mp_graphql_Mutation_reset_total counter
vendor_mp_graphql_Mutation_reset_total 3
# TYPE vendor_mp_graphql_Mutation_reset_elapsedTime_seconds gauge
vendor_mp_graphql_Mutation_reset_elapsedTime_seconds 0.007540145000000001

Summary

GraphQL is a powerful and popular query language for remote data access. MicroProfile GraphQL makes it easy to develop GraphQL applications in Java. And now you use GraphQL in Open Liberty!

Improved developer experience and MicroProfile integration for MicroProfile Rest Client 1.2

Originally posted on March 28, 2019 at:
https://openliberty.io/blog/2019/03/28/developer-experience-microprofile-rest-client.html

MicroProfile Rest Client is a type-safe client API for invoking RESTful services. Version 1.2 improves the developer experience and enhances integration with other MicroProfile technologies such as CDI, Fault Tolerance, OpenTracing, etc. MicroProfile Rest Client 1.2 is part of MicroProfile 2.2, which is available in Open Liberty 19.0.0.3.

Previous releases of MicroProfile Rest Client lacked integration with CDI, Fault Tolerance, OpenTracing, etc. making it difficult to add things like timeouts, retries, circuit breakers, etc. to client interfaces. MicroProfile Rest Client 1.2 improves integration with other MicroProfile technologies but also improves the developer experience so that you can specify the base URL directly in the @RegisterRestClient annotation in the interface and specify connect and read timeouts in a portable fashion.

Sending HTTP headers or propagating them from a JAX-RS request has been a complicated problem with prior releases, but not anymore. Now you can specify HTTP headers to send or propagate using the new @ClientHeaderParam annotation, MicroProfile Config properties, or by implementing a new ClientHeadersFactory interface.

To enable the MicroProfile Rest Client feature in your server.xml:

<featureManager>
  <feature>mpRestClient-1.2</feature>
</featureManager>

Here is an example of specifying the URI in the annotation on the interface:

package io.openliberty.rest.client;
...
@RegisterRestClient(baseUri="http://localhost:9080/myBaseUri")
public interface ClientWithURI {
...

This can still be overridden by specifying a MicroProfile Config property like this:

io.openliberty.rest.client.ClientWithURI/mp-rest/uri=http://localhost:9080/myOverriddenBaseUri

If the MicroProfile Rest Client interface is invoked from within a JAX-RS resource class, then it is possible to propagate HTTP headers from the incoming request to the outgoing Rest Client request by specifying the headers to propagate using this MP Config property:

org.eclipse.microprofile.rest.client.propagateHeaders=Authorization,MyCustomHeader

It is also possible to specify or generate a header value using annotations like this:

@ClientHeaderParam(name="HeaderOrigin", value="MPRestClientInOpenLiberty")
@ClientHeaderParam(name="MyHeader", value="value1")
@Path("/somePath")
public interface MyClient {

    @GET
    @ClientHeaderParam(name="MyHeader", value="{computeValue}")
    MyResponse getSomeResponse();

    default String computeValue() {
        return "value2";
    }
...

In this example, the client would send two newly-created HTTP headers when the getSomeResponse() method is invoked:

    HeaderOrigin: MPRestClientInOpenLiberty
    MyHeader: value2

Header values can be computed by surrounding the method name in curly-braces. The only methods that can be specified to compute a header value are default interface methods in the same client interface or public static methods (which must be fully-qualified).

In the case where the same header is specified at the interface level and the method level, the value specified at the method level is used. Thus MyHeader is set to value2 rather than value1.

If the mpFaultTolerance-2.0 feature has been specified, then the functionality of the Rest Client interfaces can be augmented with handy Fault Tolerance APIs, for example:

public interface MyFaultTolerantClient {

    @GET
    @Retry(retryOn={WebApplicationException.class}, maxRetries = 3)
    String method1();

    @PUT
    @Timeout(value=3, unit=ChronoUnit.SECONDS)
    boolean method2(MyEntity entity);

    @POST
    @Fallback(fallbackMethod="queueForLater")
    boolean method3(MyEntity entity);

    default boolean queueForLater(MyEntity entity) {
        return addToRetryQueue(entity);
    }
}

In this example, method1 retries the request up to three times in the event that a WebApplicationException occurs. The @Timeout annotation on method2 automatically sets the connect and read timeouts for the request to 3 seconds, and if the request takes longer than 3 seconds, the Fault Tolerance implementation interrupts the request. Lastly, if an exception occurs when invoking method3, the Fault Tolerance implementation invokes the queueForLater method.

To try it out, take a look at Open Liberty 19.0.0.3, which provides a full implementation of MicroProfile 2.2, including MicroProfile Rest Client 1.2.

For more details, take a look at the MicroProfile Javadoc.

To learn to use MicroProfile Rest Client, see the Consuming RESTful services with template interfaces guide.

Asynchronous REST with JAX-RS and MicroProfile

Originally posted on January 24, 2019 at:
https://openliberty.io/blog/2019/01/24/async-rest-jaxrs-microprofile.html

JAX-RS and MicroProfile Rest Client make writing and consuming RESTful services both easy and powerful, especially when using their asynchronous capabilities. In this post, we’ll look at how to use asynchronous JAX-RS resource methods on the server side. There are limited use cases in which async is suitable on the server, so we’ll try to cover those cases where it is most useful. Async on the client can be very beneficial. We’ll cover the advantages, and we’ll also go over the different ways of implementing an asynchronous client including the JAX-RS 2.0 async APIs, the JAX-RS 2.1 reactive APIs, and the MicroProfile Rest Client 1.1 type-safe, async APIs.

We’ll follow a sample travel planning service at: https://github.com/OpenLiberty/sample-async-rest

The application makes RESTful calls to an airline service, hotel service, and car rental service in order to make reservations and determine the total cost of the trip.

Async on the server (JAX-RS 2.0 and 2.1)

A JAX-RS resource method can be made asynchronous by using the @Suspended annotation on a parameter of type, AsyncResponse. Usually, the resource method would return void since the actual response would be returned using the AsyncResponse.resume(Object) method. Here is an example:

@Path("/airline")
public class AirlineService {

    private static ExecutorService executor = Executors.newFixedThreadPool(10);

    @Path("/cost")
    @GET
    public void getReservation(@QueryParam("from") String from,
                               @QueryParam("to") String to,
                               @QueryParam("start") LocalDate start,
                               @QueryParam("end") LocalDate end,
                               @Suspended AsyncResponse ar) {

        executor.execute( () -> {
            Reservation r = new Reservation();
            r.setDestination(to);
            r.setInitialLocation(from);
            r.setStartDate(start);
            r.setReturnDate(end);
            r.setCost(DBHelper.getCostOfAirlineReservation(from, to, start, end));

            ar.resume(r);
        });

    }
}

So what does this actually do? First, notice that there is a fixed thread pool, limited to 10 threads (this is for simplicity – a better practice would be to make the thread pool size configurable with MicroProfile Config so that you could change this setting without recompiling). We might choose to limit the size of the thread pool to prevent overloading the back-end resource, a database in this case.

Next, notice that the getReservation resource method doesn’t actually return anything. Instead it creates a new Reservation in a Runnable (via lambda) that makes a database call and then returns the reservation to the client through the AsyncResponse object. This means that the thread invoking the getReservation method can return immediately to handle new requests. The client won’t see a response, however, until the call to the Reservation has been constructed and passed to the resume method, which might take a little while depending on how long the database request might take (DBHelper…​). This example is essentially throttling access to the database.

Let’s suppose that the database is running slowly for some reason. If we implement this method synchronously, we might run into a situation where the database starts rejecting work, leading to exceptions thrown back to the client. By implementing this asynchronously, we limit the connections to 10; additional requests would be queued until they could eventually be executed by the executor service. This is ideal so long as the database can eventually catch up with the work.

In practice, it is my opinion that there are relatively few use cases where asynchronous methods on the server are more effective than their synchronous counterparts. Throttling access to another resource (as above) is one use case. Others might include where the thread factory has created threads optimized for the response (i.e. they already contain data on a ThreadLocal). Perhaps there is a performance benefit on some application servers; Open Liberty uses a well-tuned, global thread pool, there aren’t a lot of performance benefits to using async methods on the server.

But the client is a different story…​

Async on the client using callbacks (JAX-RS 2.0)

Let’s say that your service returns a result that is composed of the results of a few other remote services. You could invoke those remote services serially, but that really only makes sense if your thread pool is limited. Instead, you could invoke the services asynchronously, using more threads, but saving time for the entire call. Here is an example:

@Path("/jaxrs20/travel")
public class MyTravelPlanningService {

    private static WebTarget airlineWebTarget = ClientBuilder.newClient()
                                                             .target(App.AIRLINE_URL);

    private static WebTarget hotelWebTarget = ClientBuilder.newClient()
                                                           .target(App.HOTEL_URL);

    private static WebTarget carRentalWebTarget = ClientBuilder.newClient()
                                                               .target(App.RENTAL_URL);

    private class ReservationInvocationCallback implements InvocationCallback<Reservation> {
        private final CountDownLatch latch;
        private final DoubleAdder costAdder;
        Throwable throwable;

        ReservationInvocationCallback(CountDownLatch latch, DoubleAdder adder) {
            this.latch = latch;
            this.costAdder = adder;
        }

        @Override
        public void completed(Reservation r) {
            costAdder.add(r.getCost());
            latch.countDown();
        }

        @Override
        public void failed(Throwable t) {
            t.printStackTrace();
            throwable = t;
            latch.countDown();
        }
    }

    @Path("/cost")
    @GET
    public double getCostOfTravel(@QueryParam("from") String from,
                                  @QueryParam("to") String to,
                                  @QueryParam("startDate") LocalDate start,
                                  @QueryParam("returnDate") LocalDate end) {

        final CountDownLatch latch = new CountDownLatch(3);
        final DoubleAdder cost = new DoubleAdder();
        ReservationInvocationCallback callback = new ReservationInvocationCallback(latch, cost);
        airlineWebTarget.queryParam("from", from)
                        .queryParam("to", to)
                        .queryParam("start", start)
                        .queryParam("end", end)
                        .request()
                        .async()
                        .get(callback);
        hotelWebTarget.queryParam("location", to)
                      .queryParam("start", start)
                      .queryParam("end", end)
                      .request()
                      .async()
                      .get(callback);
        carRentalWebTarget.queryParam("location", to)
                          .queryParam("start", start)
                          .queryParam("end", end)
                          .request()
                          .async()
                          .get(callback);

        try {
            latch.await();
        } catch (InterruptedException ex) {
            throw new WebApplicationException(ex, 500);
        }
        if (callback.throwable != null) {
            callback.throwable.printStackTrace();
            throw new WebApplicationException("Failure in downstream service",
                callback.throwable, 500);
        }
        return cost.doubleValue();
    }
}

This slightly more complex example uses an InvocationCallback which will be notified when the async response has completed (either through the completed method if the response is successful, or the failed method if not). We tell the client to invoke the services asynchronously by invoking the async() method on the Invocation.Builder object that is returned from the request() method. That returns an instance of AsyncInvoker. From there, we use an instance of the callback to asynchronously invoke three different services. We’ll only end up waiting for as long as the longest of those three services. Very efficient!

In a failure case we log the exception and then propagate it back to the client. Also, we are caching and re-using the WebTarget for each remote service. This avoids a lot of object creation in the JAX-RS implementation code, improving overall performance.

This works well, but JAX-RS 2.1 gives us another option: a reactive client API.

Async on the client using Reactive APIs (JAX-RS 2.1)

JAX-RS 2.1 adds support for reactive APIs. Out of the box, JAX-RS 2.1 supports a CompletionStage return type. This allows users to string together a chain of stages that can be completed asynchronously. JAX-RS 2.1 also allows users to extend the reactive capabilities of the client by using other reactive providers such as RxJava, Guava, etc. For simplicity and brevity, we will only cover the CompletionStage approach here. My colleague, John Koehler is writing a blog post that will provide more information on reactive extensions. Stay tuned!

Similar to the async() method in JAX-RS 2.0 (which is still available in 2.1), we get an instance of a CompletionStageRxInvoker by using the rx() method on the Invocation.Builder. The CompletionStageRxInvoker has methods similar to the AsyncInvoker, but returns CompletionStage rather than Future. Also note that these methods do not take an InvocationCallback either.

So, if we were to re-write the JAX-RS 2.0 client example using the reactive client in JAX-RS 2.1, it would look something like this:

@Path("/jaxrs21/travel")
public class MyTravelPlanningService {

    private static WebTarget airlineWebTarget = ClientBuilder.newClient()
                                                             .target(App.AIRLINE_URL);

    private static WebTarget hotelWebTarget = ClientBuilder.newClient()
                                                           .target(App.HOTEL_URL);

    private static WebTarget carRentalWebTarget = ClientBuilder.newClient()
                                                               .target(App.RENTAL_URL);


    @Path("/cost")
    @GET
    public double getCostOfTravel(@QueryParam("from") String from,
                                  @QueryParam("to") String to,
                                  @QueryParam("startDate") LocalDate start,
                                  @QueryParam("returnDate") LocalDate end) {

        final CountDownLatch latch = new CountDownLatch(3);
        final DoubleAdder cost = new DoubleAdder();
        final AtomicReference<Throwable> throwable = new AtomicReference<>();

        BiConsumer<Reservation, Throwable> consumer = (r, t) -> {
            if (t != null) {
                throwable.set(t);
            } else {
                cost.add(r.getCost());
            }
            latch.countDown();
        };

        airlineWebTarget.queryParam("from", from)
                        .queryParam("to", to)
                        .queryParam("start", start)
                        .queryParam("end", end)
                        .request()
                        .rx()
                        .get(Reservation.class)
                        .whenCompleteAsync(consumer);

        hotelWebTarget.queryParam("location", to)
                      .queryParam("start", start)
                      .queryParam("end", end)
                      .request()
                      .rx()
                      .get(Reservation.class)
                      .whenCompleteAsync(consumer);

        carRentalWebTarget.queryParam("location", to)
                          .queryParam("start", start)
                          .queryParam("end", end)
                          .request()
                          .rx()
                          .get(Reservation.class)
                          .whenCompleteAsync(consumer);
        try {
            latch.await();
        } catch (InterruptedException ex) {
            throw new WebApplicationException(ex, 500);
        }

        Throwable t = throwable.get();
        if (t != null) {
            throw new WebApplicationException("Failure in downstream service",
                                              t, 500);
        }
        return cost.doubleValue();
    }
}

Functionally, the JAX-RS 2.1 reactive client example here is not much different from the JAX-RS 2.0 async client, but I think the reactive example is cleaner and easier to understand. And less code to maintain is also nice!

Speaking of less code…​ hopefully by now you’ve heard about the MicroProfile Rest Client. It is a proxy-based, type safe client API for RESTful services. Starting in MP Rest Client 1.1, you can make asynchronous calls using Java 8’s CompletionStage. Let’s check out that approach:

Async on the client using type-safe interfaces (MicroProfile Rest Client 1.1)

MicroProfile Rest Client takes a different approach to accessing remote RESTful services – a more type-safe approach where an interface, annotated similar to a JAX-RS resource, represents a remote service. Invoking methods on the client interface would be similar to invoking methods on a service hosted locally – with clever usage of providers like ResponseExceptionMapper, ParamConverterProvider, MessageBodyReader, MessageBodyWriter, etc. which allows us to design a service interface that indeed acts like it is local.

In order for a Rest Client method to be executed asynchronously, it must return a CompletionStage. Note that in MP Rest Client 1.2, it is also possible to use MP Fault Tolerance’s @Asynchronous annotation. This functionality is outside the scope of this post, but the jist is that if your interface method returns a Future, then the MP Fault Tolerance implementation will invoke the method on a separate thread, immediately returning a Future. You can find more information about the Fault Tolerance APIs at the project site.

So in our travel planning example, you might want to create client interfaces like:

@Path("/airline")
@RegisterProvider(LocalDateParamConverter.class)
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface AirlineServiceClient {

    @Path("/cost")
    @GET
    CompletionStage<Reservation> getReservation(@QueryParam("from") String from,
                                                @QueryParam("to") String to,
                                                @QueryParam("start") LocalDate startDate,
                                                @QueryParam("end") LocalDate endDate);
}

And you would invoke the client like this:

@Path("/mpRest/travel")
public class MyTravelPlanningService {
    private final static String BASE_URI = "http://localhost:" + App.PORT + App.CONTEXT_ROOT;

    private final static AirlineServiceClient AIRLINE_CLIENT = RestClientBuilder.newBuilder()
                                                                                .baseUri(URI.create(BASE_URI))
                                                                                .build(AirlineServiceClient.class);
    private final static HotelServiceClient HOTEL_CLIENT = RestClientBuilder.newBuilder()
                                                                            .baseUri(URI.create(BASE_URI))
                                                                            .build(HotelServiceClient.class);
    private final static CarRentalServiceClient CAR_RENTAL_CLIENT = RestClientBuilder.newBuilder()
                                                                                     .baseUri(URI.create(BASE_URI))
                                                                                     .build(CarRentalServiceClient.class);

    @Path("/cost")
    @GET
    public double getCostOfTravel(@QueryParam("from") String from,
                                  @QueryParam("to") String to,
                                  @QueryParam("startDate") LocalDate start,
                                  @QueryParam("returnDate") LocalDate end) {
        final CountDownLatch latch = new CountDownLatch(3);
        final DoubleAdder cost = new DoubleAdder();
        final AtomicReference<Throwable> throwable = new AtomicReference<>();

        BiConsumer<Reservation, Throwable> consumer = (r, t) -> {
            if (t != null) {
                throwable.set(t);
            } else {
                cost.add(r.getCost());
            }
            latch.countDown();
        };

        AIRLINE_CLIENT.getReservation(from, to, start, end)
                      .whenCompleteAsync(consumer);

        HOTEL_CLIENT.getReservation(to, start, end)
                    .whenCompleteAsync(consumer);

        CAR_RENTAL_CLIENT.getReservation(to, start, end)
                         .whenCompleteAsync(consumer);

        try {
            latch.await();
        } catch (InterruptedException ex) {
            throw new WebApplicationException(ex, 500);
        }

        Throwable t = throwable.get();
        if (t != null) {
            throw new WebApplicationException("Failure in downstream service",
                                              t, 500);
        }
        return cost.doubleValue();
    }
}

This is even more clean than the JAX-RS 2.1 reactive client API!

The MP Rest Client approach also solves a problem of what to do with ThreadLocal objects that might be required for providers on the outbound request. Let’s say that we have a ThreadLocal object in our application that determines whether a given customer is a preferred loyalty club member. If so, we might add a ClientRequestFilter that would create a custom HTTP header to indicate that to the remote airline, hotel, or car rental service – something like Loyalty-ID: 1234 that might be used by the remote service to upgrade the reservation. The problem is that if the ClientRequestFilter checks the ThreadLocal object for the loyalty ID number on the asynchronous thread, it won’t be there – it was associated with the calling thread, not the async thread. This picture might help clarify the problem.

asyncREST thread local problem

Notice that the Loyalty ID is set on the calling thread, but that ID isn’t propagated to the async threads that are making the requests to the remote services. That’s where the AsyncInvocationInterceptor come into play. This is a provider type introduced in MP Rest Client 1.1 that allows users to propagate ThreadLocal objects – or really anything that is associated with the calling thread. This interface contains two methods (a third method is added in MP Rest Client 1.2 for removing contexts): prepareContext() and applyContext(). The former is invoked on the calling thread prior to “swapping” threads. The latter is invoked on the async thread.

asyncREST thread local solution

The AsyncInvocationInterceptor must be created by a AsyncInvocationInterceptorFactory like so:

public class LoyaltyAsyncInvocationInterceptorFactory
    implements AsyncInvocationInterceptorFactory {

    @Override
    public AsyncInvocationInterceptor newInterceptor() {
        return new AsyncInvocationInterceptor() {

            String loyaltyId;

            @Override
            public void prepareContext() {
                loyaltyId = App.LOYALTY_ID_THREADLOCAL.get();
            }

            @Override
            public void applyContext() {
                App.LOYALTY_ID_THREADLOCAL.set(loyaltyId);
            }};
    }
}

Let’s assume that loyalty members get a 10% discount when booking hotels online. Now let’s try invoking our travel planning site with a loyalty ID:

asyncREST curl output

With MP Rest Client we can get our loyalty discount and save about $200!

Summary

It’s getting easier to do things asynchronously with REST and Java. JAX-RS and MicroProfile give you some powerful tools in this space. Hopefully now you are more prepared to write and consumer RESTful services asynchronously.

If you’ve got any questions or run into any problems, please let us know. You can reach me on Twitter at @AndrewMcCright.

Thanks!