More Convenience with Rest Client for MicroProfile and Method Overloading

A JAX-RS resource with optional header, or query parameters:


import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/hello")
public class GreetingResource {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String hello(@DefaultValue("james") @HeaderParam("firstName") String firstName,
                        @DefaultValue("duke") @HeaderParam("lastName") String lastName) {
        return firstName + " " + lastName;
    }
}

...is accessible via a Rest Client for MicroProfile interface with overloaded methods:


import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;

@Path("/hello")
@Produces(MediaType.TEXT_PLAIN)
@RegisterRestClient(baseUri = "http://localhost:8080")
public interface GreetingResourceClient {

    @GET
    public String hello(@HeaderParam("firstName") String firstName, @HeaderParam("lastName") String lastName);

    @GET
    public String hello(@HeaderParam("firstName") String firstName);

    @GET
    public String hello();
    
}

Now the client can be injected and the overloaded methods conveniently called:


import static org.junit.jupiter.api.Assertions.assertEquals;

import javax.inject.Inject;

import org.eclipse.microprofile.rest.client.inject.RestClient;
import org.junit.jupiter.api.Test;

import io.quarkus.test.junit.QuarkusTest;

@QuarkusTest
public class GreetingResourceTest {

    @Inject
    @RestClient
    GreetingResourceClient client;

    @Test
    void helloWithoutParameters(){
        var hello = this.client.hello();
        assertEquals(hello, "james duke");
    }

    @Test
    void helloWithFirstName(){
        var hello = this.client.hello("john");
        assertEquals(hello, "john duke");
    }

    @Test
    void helloWithFirstNameAndLastName(){
        var hello = this.client.hello("john","dukem");
        assertEquals(hello, "john dukem");
    }  
}

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments
License