Search

Dark theme | Light theme
Showing posts with label Micronaut:Mastery. Show all posts
Showing posts with label Micronaut:Mastery. Show all posts

March 27, 2019

Micronaut Mastery: Parse String Value With Kb/Mb/Gb To Number

Micronaut can convert String values defined as a number followed by (case-insensitive) KB/MB/GB to a number value in certain cases. The conversion service in Micronaut supports the @ReadableBytes annotation that we can apply to a method parameter. Micronaut will then parse the String value and convert it to a number. The value 1Kb is converted to 1024. We can use this for example in a configuration class or path variable in a controller.

In the following example we have a configuration class annotated with @ConfigurationProperties with the property maxFileSize. We use the @ReadableBytes annotation to support setting the value with a String value:

package mrhaki;

import io.micronaut.context.annotation.ConfigurationProperties;
import io.micronaut.core.convert.format.ReadableBytes;

@ConfigurationProperties(SampleConfig.SAMPLE_CONFIG_PREFIX)
public class SampleConfig {
    
    public static final String SAMPLE_CONFIG_PREFIX = "sample.config";
    
    private long maxFileSize;

    /**
     * Use @ReadableBytes for parameter {@code maxFileSize}
     * to convert a String value formatted as number followed
     * by "KB", "MB" or "GB" (case-insensitive).
     * 
     * @param maxFileSize Maximum file size
     */
    public void setMaxFileSize(@ReadableBytes long maxFileSize) {
        this.maxFileSize = maxFileSize;
    }

    public long getMaxFileSize() {
        return maxFileSize;
    }
    
}

Let's write a Spock specification to test the conversion of String values to numbers:

package mrhaki

import io.micronaut.context.ApplicationContext
import spock.lang.Specification;

class SampleConfigSpec extends Specification {

    void "set maxFileSize configuration property with KB/MB/GB format"() {
        given:
        final ApplicationContext context =
                ApplicationContext.run("sample.config.maxFileSize": maxFileSize)

        when:
        final SampleConfig sampleConfig = context.getBean(SampleConfig)

        then:
        sampleConfig.maxFileSize == result

        where:
        maxFileSize || result
        "20KB"      || 20_480
        "20kb"      || 20 * 1024
        "1MB"       || 1_048_576
        "1Mb"       || 1 * 1024 * 1024
        "3GB"       || 3L * 1024 * 1024 * 1024
        113         || 113
    }
}

In another example we use the conversion on a path variable parameter in a controller method:

package mrhaki;

import io.micronaut.core.convert.format.ReadableBytes;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;

@Controller
public class SampleController {
    
    @Get("/{size}")
    public long size(@ReadableBytes final long size) {
        return size;
    }
    
}

And with the following test we can see if the conversion is done correctly:

package mrhaki

import io.micronaut.context.ApplicationContext
import io.micronaut.http.client.HttpClient
import io.micronaut.runtime.server.EmbeddedServer
import spock.lang.AutoCleanup
import spock.lang.Shared
import spock.lang.Specification

class SampleControllerSpec extends Specification {

    @Shared
    @AutoCleanup
    private static EmbeddedServer server = ApplicationContext.run(EmbeddedServer)

    @Shared
    @AutoCleanup
    private static HttpClient httpClient = HttpClient.create(server.URL)

    void "return size converted from String value with unit KB/MB/GB"() {
        expect:
        httpClient.toBlocking().retrieve("/$size") == result

        where:
        size   || result
        "20KB" || "20480"
        "20kb" || (20 * 1024).toString()
        "1MB"  || 1_048_576.toString()
        "3GB"  || (3L * 1024 * 1024 * 1024).toString()
        113    || "113"

    }
}

Written with Micronaut 1.0.4.

March 22, 2019

Micronaut Mastery: Binding Request Parameters To POJO

Micronaut supports the RFC-6570 URI template specification to define URI variables in a path definition. The path definition can be a value of the @Controller annotation or any of the routing annotations for example @Get or @Post. We can define a path variable as {?binding*} to support binding of request parameters to all properties of an object type that is defined as method argument with the name binding. We can even use the Bean Validation API (JSR380) to validate the values of the request parameters if we add an implementation of this API to our class path.

In the following example controller we have the method items with method argument sorting of type Sorting. We want to map request parameters ascending and field to the properties of the Sorting object. We only have the use the path variable {?sorting*} to make this happen. We also add the dependency io.micronaut.configuration:micronaut-hibernate-validator to our class path. If we use Gradle we can add compile("io.micronaut.configuration:micronaut-hibernate-validator") to our build file.

package mrhaki;

import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.validation.Validated;

import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import java.util.List;

@Controller("/sample")
@Validated // Enable validation of Sorting properties.
public class SampleController {
    
    private final SampleComponent sampleRepository;

    public SampleController(final SampleComponent sampleRepository) {
        this.sampleRepository = sampleRepository;
    }

    // Using the syntax {?sorting*} we can assign request parameters
    // to a POJO, where the request parameter name matches a property
    // name in the POJO. The name 'must match the argument  
    // name of our method, which is 'sorting' in our example.
    // The properties of the POJO can use the Validation API to 
    // define constraints and those will be validated if we use
    // @Valid for the method argument and @Validated at the class level.
    @Get("/{?sorting*}")
    public List<Item> items(@Valid final Sorting sorting) {
        return sampleRepository.allItems(sorting.getField(), sorting.getDirection());
    }
 
    private static class Sorting {
        
        private boolean ascending = true;
        
        @Pattern(regexp = "name|city", message = "Field must have value 'name' or 'city'.")
        private String field = "name";
        
        private String getDirection() {
            return ascending ? "ASC" : "DESC";
        }

        public boolean isAscending() {
            return ascending;
        }

        public void setAscending(final boolean ascending) {
            this.ascending = ascending;
        }

        public String getField() {
            return field;
        }

        public void setField(final String field) {
            this.field = field;
        }
    }
}

Let's write a test to check that the binding of the request parameters happens correctly. We use the Micronaut test support for Spock so we can use the @Micronaut and @MockBean annotations. We add a dependency on io.micronaut:micronaut-test-spock to our build, which is testCompile("io.micronaut.test:micronaut-test-spock:1.0.2") if we use a Gradle build.

package mrhaki

import io.micronaut.http.HttpStatus
import io.micronaut.http.client.RxHttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.http.client.exceptions.HttpClientResponseException
import io.micronaut.http.uri.UriTemplate
import io.micronaut.test.annotation.MicronautTest
import io.micronaut.test.annotation.MockBean
import spock.lang.Specification

import javax.inject.Inject

@MicronautTest
class SampleControllerSpec extends Specification {

    // Client to test the /sample endpoint.
    @Inject
    @Client("/sample")
    RxHttpClient httpClient

    // Will inject mock created by sampleRepository method.
    @Inject
    SampleComponent sampleRepository

    // Mock for SampleRepository to check method is
    // invoked with correct arguments.
    @MockBean(SampleRepository)
    SampleComponent sampleRepository() {
        return Mock(SampleComponent)
    }

    void "sorting request parameters are bound to Sorting object"() {
        given:
        // UriTemplate to expand field and ascending request parameters with values.
        // E.g. ?field=name&expanding=false.
        final requestURI = new UriTemplate("/{?field,ascending}").expand(field: paramField, ascending: paramAscending)

        when:
        httpClient.toBlocking().exchange(requestURI)

        then:
        1 * sampleRepository.allItems(sortField, sortDirection) >> []

        where:
        paramField | paramAscending | sortField | sortDirection
        null       | null           | "name"    | "ASC"
        null       | false          | "name"    | "DESC"
        null       | true           | "name"    | "ASC"
        "city"     | false          | "city"    | "DESC"
        "city"     | true           | "city"    | "ASC"
        "name"     | false          | "name"    | "DESC"
        "name"     | true           | "name"    | "ASC"
    }

    void "invalid sorting field should give error response"() {
        given:
        final requestURI = new UriTemplate("/{?field,ascending}").expand(field: "invalid")

        when:
        httpClient.toBlocking().exchange(requestURI)

        then:
        final HttpClientResponseException clientResponseException = thrown()
        clientResponseException.response.status == HttpStatus.BAD_REQUEST
        clientResponseException.message == "sorting.field: Field must have value 'name' or 'city'."
    }
}

Written with Micronaut 1.0.4.

October 3, 2018

Micronaut Mastery: Configuration Property Name Is Lowercased And Hyphen Separated

In Micronaut we can inject configuration properties in different ways into our beans. We can use for example the @Value annotation using a string value with a placeholder for the configuration property name. If we don't want to use a placeholder we can also use the @Property annotation and set the name attribute to the configuration property name. We have to pay attention to the format of the configuration property name we use. If we refer to a configuration property name using @Value or @Property we must use lowercased and hyphen separated names (also known as kebab casing). Even if the name of the configuration property is camel cased in the configuration file. For example if we have a configuration property sample.theAnswer in our application.properties file, we must use the name sample.the-answer to get the value.

In the following Spock specification we see how to use it in code. The specification defines two beans that use the @Value and @Property annotations and we see that we need to use kebab casing for the configuration property names, even though we use camel casing to set the configuration property values:

package mrhaki

import groovy.transform.CompileStatic
import io.micronaut.context.ApplicationContext
import io.micronaut.context.annotation.Property
import io.micronaut.context.annotation.Value
import io.micronaut.context.exceptions.DependencyInjectionException
import spock.lang.Shared
import spock.lang.Specification

import javax.inject.Singleton

class ConfigurationPropertyNameSpec extends Specification {

    // Create application context with two configuration 
    // properties: reader.maxFileSize and reader.showProgress.
    @Shared
    private ApplicationContext context = 
            ApplicationContext.run('reader.maxFileSize': 1024, 
                                   'reader.showProgress': true)

    void "use kebab casing (hyphen-based) to get configuration property value"() {
        expect:
        with(context.getBean(FileReader)) {
            maxFileSize == 1024   
            showProgress == Boolean.TRUE
        }
    }

    void "using camel case to get configuration property should throw exception"() {
        when:
        context.getBean(InvalidFileReader).maxFileSize

        then:
        final dependencyException = thrown(DependencyInjectionException)
        dependencyException.message == """\
            |Failed to inject value for parameter [maxFileSize] of method [setMaxFileSize] of class: mrhaki.InvalidFileReader
            |
            |Message: Error resolving property value [\${reader.maxFileSize}]. Property doesn't exist
            |Path Taken: InvalidFileReader.setMaxFileSize([Integer maxFileSize])""".stripMargin()
    }
}

@CompileStatic
@Singleton
class FileReader {
    
    private Integer maxFileSize
    private Boolean showProgress
    
    // Configuration property names 
    // are normalized and 
    // stored lowercase hyphen separated (= kebab case).
    FileReader(
            @Property(name ='reader.max-file-size') Integer maxFileSize,
            @Value('${reader.show-progress:false}') Boolean showProgress) {
        
        this.maxFileSize = maxFileSize
        this.showProgress = showProgress
    }
    
    Integer getMaxFileSize() {
        return maxFileSize
    }
    
    Boolean showProgress() {
        return showProgress
    }
}

@CompileStatic
@Singleton
class InvalidFileReader {
    // Invalid reference to property name,
    // because the names are normalized and
    // stored lowercase hyphen separated.
    @Value('${reader.maxFileSize}')
    Integer maxFileSize
}

Written with Micronaut 1.0.0.RC1.

October 2, 2018

Micronaut Mastery: Consuming Server-Sent Events (SSE)

Normally we would consume server-sent events (SSE) in a web browser, but we can also consume them in our code on the server. Micronaut has a low-level HTTP client with a SseClient interface that we can use to get server-sent events. The interface has an eventStream method with different arguments that return a Publisher type of the Reactive Streams API. We can use the RxSseClient interface to get back RxJava2 Flowable return type instead of Publisher type. We can also use Micronaut's declarative HTTP client, which we define using the @Client annotation, that supports server-sent events with the correct annotation attributes.

In our example we first create a controller in Micronaut to send out server-sent events. We must create method that returns a Publisher type with Event objects. These Event objects can contains some attributes like id and name, but also the actual object we want to send:

// File: src/main/java/mrhaki/ConferencesController.java
package mrhaki;

import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.sse.Event;
import io.reactivex.Flowable;

import java.util.concurrent.TimeUnit;

@Controller("/conferences")
public class ConferencesController {

    private final ConferenceRepository repository;

    public ConferencesController(final ConferenceRepository repository) {
        this.repository = repository;
    }

    /**
     * Send each second a random Conference.
     * 
     * @return Server-sent events each second where the event is a randomly
     * selected Conference object from the repository.
     */
    @Get("/random")
    Flowable<Event<Conference>> events() {
        final Flowable<Long> tick = Flowable.interval(1, TimeUnit.SECONDS);
        final Flowable<Conference> randomConferences = repository.random().repeat();

        return tick.zipWith(randomConferences, this::createEvent);
    }

    /**
     * Create a server-sent event with id, name and the Conference data.
     * 
     * @param counter Counter used as id for event.
     * @param conference Conference data as payload for the event.
     * @return Event with id, name and Conference object.
     */
    private Event<Conference> createEvent(Long counter, final Conference conference) {
        return Event.of(conference)
                    .id(String.valueOf(counter))
                    .name("randomEvent");
    }

}

Notice how easy it is in Micronaut to use server-sent events. Let's add a declarative HTTP client that can consume the server-sent events. We must set the processes attribute of the @Get annotation with the value text/event-stream. This way Micronaut can create an implementation of this interface with the correct code to consume server-sent events:

// File: src/main/java/mrhaki/ConferencesClient.java
package mrhaki;

import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.http.sse.Event;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;

@Client("/conferences")
interface ConferencesSseClient {

    /**
     * Return Publisher with SSE containing Conference data.
     * We must set the processes attribute with the value
     * text/event-stream so Micronaut can generate an implementation
     * to support server-sent events.
     * We could also return Publisher implementation class
     * like Flowable or Flux, Micronaut will do the conversion.
     * 
     * @return Publisher with Event objects with Conference data.
     */
    @Get(value = "/random", processes = MediaType.TEXT_EVENT_STREAM)
    Publisher<Event<Conference>> randomEvents();

    /**
     * Here we use a Publisher implementation Flux. Also we don't
     * add the Event in the return type: Micronaut will leave out
     * the event metadata and we get the data that is part of
     * the event as object.
     *
     * @return Flux with Conference data.
     */
    @Get(value = "/random", processes = MediaType.TEXT_EVENT_STREAM)
    Flux<Conference> randomConferences();

}

Next we create a Spock specification to test our controller with server-sent events. In the specification we use the low-level HTTP client and the declarative client:

// File: src/test/groovy/mrhaki/ConferencesControllerSpec.groovy
package mrhaki

import io.micronaut.context.ApplicationContext
import io.micronaut.http.client.sse.RxSseClient
import io.micronaut.http.client.sse.SseClient
import io.micronaut.http.sse.Event
import io.micronaut.runtime.server.EmbeddedServer
import io.reactivex.Flowable
import spock.lang.AutoCleanup
import spock.lang.Shared
import spock.lang.Specification

class ConferencesControllerSpec extends Specification {

    @Shared
    @AutoCleanup
    private EmbeddedServer server = ApplicationContext.run(EmbeddedServer)

    /**
     * Low level client to interact with server
     * that returns server side events, that supports
     * RxJava2.
     */
    @Shared
    @AutoCleanup
    private RxSseClient sseLowLevelClient =
            server.applicationContext
                  .createBean(RxSseClient, server.getURL())

    /**
     * Declarative client for interacting
     * with server that send server side events.
     */
    @Shared
    private ConferencesSseClient sseClient =
            server.applicationContext
                  .getBean(ConferencesSseClient)

    void "test event stream with low level SSE client"() {
        when:
        // Use eventStream method of RxSseClient to get SSE
        // and convert data in event to Conference objects by 
        // setting second argument to Conference.class.
        final List<Event<Conference>> result =
                sseLowLevelClient.eventStream("/conferences/random", Conference.class)
                                 .take(2)
                                 .toList()
                                 .blockingGet()
        
        then:
        result.name.every { name -> name == "randomEvent" }
        result.id == ["0", "1"]
        result.data.every { conference -> conference instanceof Conference }
    }

    void "test event stream with declarative SSE client"() {
        when:
        // Use declarative client (using @Client)
        // with SSE support.
        List<Event<Conference>> result =
                Flowable.fromPublisher(sseClient.randomEvents())
                        .take(2)
                        .toList()
                        .blockingGet();

        then:
        result.name.every { name -> name == "randomEvent" }
        result.id == ["0", "1"]
        result.data.every { conference -> conference instanceof Conference }
    }

    void "test conference stream with declarative SSE client"() {
        when:
        // Use declarative client (using @Client)
        // with built-in extraction of data in event.
        List<Conference> result =
                sseClient.randomConferences()
                         .take(2)
                         .collectList()
                         .block();

        then:
        result.id.every(Closure.IDENTITY) // Check every id property is set.
        result.every { conference -> conference instanceof Conference }
    }
}

Written with Micronaut 1.0.0.RC1.

September 30, 2018

Micronaut Mastery: Running Code On Startup

When our Micronaut application starts we can listen for the ServiceStartedEvent event and write code that needs to run when the event is fired. We can write a bean that implements the ApplicationEventListener interface with the type ServiceStartedEvent. Or we can use the @EventListener annotation on our method with code we want to run on startup. If the execution of the code can take a while we can also add the @Async annotation to the method, so Micronaut can execute the code on a separate thread.

In our example application we have a reactive repository for a Mongo database and we want to save some data in the database when our Micronaut application starts. First we write a bean that implements the ApplicationEventListener:

// File: src/main/java/mrhaki/Dataloader.java
package mrhaki;

import io.micronaut.context.annotation.Requires;
import io.micronaut.context.env.Environment;
import io.micronaut.context.event.ApplicationEventListener;
import io.micronaut.discovery.event.ServiceStartedEvent;
import io.micronaut.scheduling.annotation.Async;
import io.reactivex.Flowable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Singleton;

@Singleton
@Requires(notEnv = Environment.TEST) // Don't load data in tests.
public class DataLoader implements ApplicationEventListener<ServiceStartedEvent> {

    private static final Logger log = LoggerFactory.getLogger(DataLoader.class);

    /**
     * Reactive repository for Mongo database to store
     * Conference objects with an id and name property.
     */
    private final ConferenceRepository repository;

    public DataLoader(final ConferenceRepository repository) {
        this.repository = repository;
    }

    @Async
    @Override
    public void onApplicationEvent(final ServiceStartedEvent event) {
        log.info("Loading data at startup");

        // Transform names to Conferences object and save them.
        Flowable.just("Gr8Conf", "Greach", "JavaLand", "JFall", "NextBuild")
                .map(name -> new Conference(name))
                .forEach(this::saveConference);
    }

    /**
     * Save conference in repository.
     * 
     * @param conference Conference to be saved.
     */
    private void saveConference(Conference conference) {
        repository
                .save(conference)
                .subscribe(
                        saved -> log.info("Saved conference {}.", saved),
                        throwable -> log.error("Error saving conference.", throwable));
    }
}

Alternatively we could have used the @EventListener annotation on a method with an argument of type ServiceStartedEvent:

// File: src/main/java/mrhaki/Dataloader.java
package mrhaki;

import io.micronaut.context.annotation.Requires;
import io.micronaut.context.env.Environment;
import io.micronaut.context.event.ApplicationEventListener;
import io.micronaut.discovery.event.ServiceStartedEvent;
import io.micronaut.runtime.event.annotation.EventListener;
import io.micronaut.scheduling.annotation.Async;
import io.reactivex.Flowable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Singleton;

@Singleton
@Requires(notEnv = Environment.TEST) // Don't load data in tests.
public class DataLoader {

    private static final Logger log = LoggerFactory.getLogger(DataLoader.class);

    /**
     * Reactive repository for Mongo database to store
     * Conference objects with an id and name property.
     */
    private final ConferenceRepository repository;

    public DataLoader(final ConferenceRepository repository) {
        this.repository = repository;
    }

    @EventListener
    @Async
    public void loadConferenceData(final ServiceStartedEvent event) {
        log.info("Loading data at startup");

        // Transform names to Conferences object and save them.
        Flowable.just("Gr8Conf", "Greach", "JavaLand", "JFall", "NextBuild")
                .map(name -> new Conference(name))
                .forEach(this::saveConference);
    }

    /**
     * Save conference in repository.
     * 
     * @param conference Conference to be saved.
     */
    private void saveConference(Conference conference) {
        repository
                .save(conference)
                .subscribe(
                        saved -> log.info("Saved conference {}.", saved),
                        throwable -> log.error("Error saving conference.", throwable));
    }
}

When we start our Micronaut application we can see in the log messages that our conference data is created:

22:58:17.343 [pool-1-thread-1] INFO  mrhaki.DataLoader - Loading data at startup
22:58:17.343 [main] INFO  io.micronaut.runtime.Micronaut - Startup completed in 1230ms. Server Running: http://localhost:9000
22:58:17.573 [Thread-11] INFO  mrhaki.DataLoader - Saved conference Conference{id=5bb134f505d4feefa74d19c7, name='JFall'}.
22:58:17.573 [Thread-8] INFO  mrhaki.DataLoader - Saved conference Conference{id=5bb134f505d4feefa74d19c3, name='Gr8Conf'}.
22:58:17.573 [Thread-10] INFO  mrhaki.DataLoader - Saved conference Conference{id=5bb134f505d4feefa74d19c5, name='Greach'}.
22:58:17.573 [Thread-9] INFO  mrhaki.DataLoader - Saved conference Conference{id=5bb134f505d4feefa74d19c8, name='NextBuild'}.
22:58:17.573 [Thread-6] INFO  mrhaki.DataLoader - Saved conference Conference{id=5bb134f505d4feefa74d19c6, name='JavaLand'}.

Written with Micronaut 1.0.0.RC1.

August 31, 2018

Micronaut Mastery: Change The Default Package For Generated Classes

When we use the Micronaut command line commands to generate controllers, beans and more, the classes will have a default package name. We can use a fully qualified package name for the class we want to generate, but when we only define a class name, Micronaut will use a default package name automatically. We can set the default package for an application when we first create an application with the create-app command. But we can also alter the default package name for an existing Micronaut application.

To set the default package name when we create a new application we must include the package name in our application name. For example when we want to use the default package name mrhaki.micronaut for an application that is called book-service we must use the following create-app command:

$ mn create-app mrhaki.micronaut.book-service
| Generating Java project.....
| Application created at /Users/mrhaki/Projects/mrhaki.com/blog/posts/samples/micronaut/book-service
$ tree src
src
├── main
│   ├── java
│   │   └── mrhaki
│   │       └── micronaut
│   │           └── Application.java
│   └── resources
│       ├── application.yml
│       └── logback.xml
└── test
    └── java
        └── mrhaki
            └── micronaut

9 directories, 3 files

Notice the tree structure reflects the structure for the package mrhaki.micronaut.
When we invoke the create-controller book command the generated files use the package name mrhaki.micronaut:

$ mn create-controller book
| Rendered template Controller.java to destination src/main/java/mrhaki/micronaut/BookController.java
| Rendered template ControllerTest.java to destination src/test/java/mrhaki/micronaut/BookControllerTest.java
$

We can change the default package name for an existing application as well. We must edit the file micronaut-cli.yml in the root of our project and change the property defaultPackage. In the following example we use the sed command on MacOS to replace the current default package with com.mrhaki.microanut, but we could of course also use any text editor to make the change:

$ cat micronaut-cli.yml
profile: service
defaultPackage: mrhaki.micronaut
---
testFramework: junit
sourceLanguage: java
$ sed -E -i '' 's/(defaultPackage:) .*/\1 com\.mrhaki\.micronaut/g' micronaut-cli.yml
$ cat micronaut-cli.yml
profile: service
defaultPackage: com.mrhaki.micronaut
---
testFramework: junit
sourceLanguage: java

Let's generate a new controller and see if our new default package name for the application is used:

$ mn create-controller author
| Rendered template Controller.java to destination src/main/java/com/mrhaki/micronaut/AuthorController.java
| Rendered template ControllerTest.java to destination src/test/java/com/mrhaki/micronaut/AuthorControllerTest.java
$

Written with Micronaut 1.0.0.M4.

August 30, 2018

Micronaut Mastery: Use Micronaut Beans In Spring Applications

We can add Micronaut beans to the application context of a Spring application. Micronaut has a MicronautBeanProcessor class that we need to register as Spring bean in the Spring application context. We can define which Micronaut bean types need to be added to the Spring application context via the constructor of the MicronautBeanProcessor class. This way we can use Micronaut from inside a Spring application. For example we can use the declarative HTTP client of Micronaut in our Spring applications.

First we need to add dependencies on Micronaut to our Spring application. In this example we will use the Micronaut HTTP client in our Spring application and use Gradle as build tool. We must add the following dependencies:

// File: build.gradle
...
dependencyManagement {
    imports {
        mavenBom 'io.micronaut:bom:1.0.0.M4'
    }
}
...
dependencies {
    ...
    annotationProcessor "io.micronaut:inject-java"
    compile "io.micronaut:http-client"
    compile "io.micronaut:spring"
    ...
}
...

Next we register a MicronautBeanProcessor bean in the Spring application context. We specify in the constructor that Micronaut beans annotated with @Client must be added to the Spring application context:

// File: src/main/java/mrhaki/micronaut/SampleApplication.java
package mrhaki.micronaut;

import io.micronaut.http.client.Client;
import io.micronaut.spring.beans.MicronautBeanProcessor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class SampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SampleApplication.class, args);
    }

    @Bean
    public MicronautBeanProcessor httpClientMicronautBeanProcessor() {
        // Register beans with @Client annotation.
        // We could for example also use @Singleton
        // and others, because the constructor has
        // a variable number of arguments.
        return new MicronautBeanProcessor(Client.class);
    }

}

We add the source for our Micronaut declarative HTTP client, where we access httpbin.org as a remote webservice:

// File: src/main/java/mrhaki/micronaut/HttpBinClient.java
package mrhaki.micronaut;

import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Post;
import io.micronaut.http.client.Client;

@Client("http://httpbin.org")
interface HttpBinClient {
    
    @Get("/uuid")
    ResponseUuidData uuid();
    
    @Post("/anything")
    ResponseData data(String message);
    
}

Inside a Spring controller we use the client as Spring bean:

// File: src/main/java/mrhaki/micronaut/HttpBinController.java
package mrhaki.micronaut;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import static org.springframework.http.MediaType.TEXT_PLAIN_VALUE;

@RestController
@RequestMapping("/sample")
public class HttpBinController {

    private final HttpBinClient client;

    // Inject Micronaut HTTP client via implicit
    // constructor injection.
    public HttpBinController(final HttpBinClient client) {
        this.client = client;
    }

    @GetMapping(value = "/uuid", produces = TEXT_PLAIN_VALUE)
    Mono<String> uuid() {
        return Mono.fromCallable(() -> client.uuid().getUuid().toString());
    }

    @GetMapping(value = "/data")
    Mono<ResponseData.MessageResponseData> data() {
        return Mono.fromCallable(() -> client.data("Micronaut rocks").getJson());
    }

}

Finally we have some POJO classes with the results from the remote web service calls:

// File: src/main/java/mrhaki/micronaut/ResponseUuidData.java
package mrhaki.micronaut;

import java.util.UUID;

public class ResponseUuidData {
    private UUID uuid;
    public UUID getUuid() { return uuid; }
    public void setUuid(final UUID uuid) { this.uuid = uuid; }
}
// File: src/main/java/mrhaki/micronaut/ResponseData.java
package mrhaki.micronaut;

public class ResponseData {
    private MessageResponseData json;
    public MessageResponseData getJson() { return json; }
    public void setJson(final MessageResponseData json) { this.json = json; }
    
    static class MessageResponseData {
        private String message;
        public String getMessage() { return message; }
        public void setMessage(final String message) { this.message = message; }
    }
}

It is time to start our Spring application and invoke /sample/uuid and /sample/data URLs to see the results:

$ curl -X GET http://localhost:8080/sample/uuid
7149a954-da9a-4bfb-ba04-4b9f814698fa
$ curl -X GET http://localhost:8080/sample/data
{"message":"Micronaut rocks"}

Written with Micronaut 1.0.0.M4 and Spring Boot 2.0.4.RELEASE.

August 29, 2018

Micronaut Mastery: Adding Custom Info To Info Endpoint

In a previous post we learned how to add build information to the /info endpoint in our application. We can add custom information to the /info endpoint via our application configuration or via a bean by implementing the InfoSource interface. Remember we need to add the io.micronaut:management dependency to our application for this feature.

Any configuration property that is prefixed with info will be exposed via the /info endpoint. We can define the properties in configuration files, using Java system properties or system environment variables. In the following example configuration file we add the property info.sample.message:

// File: src/main/resources/application.yml
...
info:
  sample:
    message: Micronaut is awesome

Another option is to create a new class that implements the InfoSource interface. We need to override the getSource method to return a Publisher with a PropertySource. In our example application we have a ConferenceRepository bean that can access a database with data about conferences. In the following example InfoSource implementation we want to return the number of conferences that are stored in the database:

package mrhaki.micronaut;

import io.micronaut.context.annotation.Requires;
import io.micronaut.context.env.MapPropertySource;
import io.micronaut.context.env.PropertySource;
import io.micronaut.core.async.SupplierUtil;
import io.micronaut.management.endpoint.info.InfoEndpoint;
import io.micronaut.management.endpoint.info.InfoSource;
import io.micronaut.runtime.context.scope.Refreshable;
import io.reactivex.Flowable;
import org.reactivestreams.Publisher;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

// Component is refreshable via a refresh event
@Refreshable
// Only create this component when the following 
// requirements are met:
@Requires(beans = InfoEndpoint.class)
@Requires(property = "endpoints.info.config.enabled", notEquals = "false")
public class DatabaseInfoSource implements InfoSource {

    /**
     * Repository to fetch count of conferences in the database.
     */
    private final ConferenceRepository conferenceRepository;

    /**
     * Supplier for returning result.
     */
    private final Supplier<PropertySource> supplier;

    public DatabaseInfoSource(final ConferenceRepository conferenceRepository) {
        this.conferenceRepository = conferenceRepository;
        
        // Cache result from database.
        // This component is refreshable via 
        // a refresh event to get the latest value
        // from the database.
        this.supplier = SupplierUtil.memoized(this::retrieveDatabaseInfo);
    }

    /**
     * Return information.
     * 
     * @return Information about the database.
     */
    @Override
    public Publisher<PropertySource> getSource() {
        return Flowable.just(supplier.get());
    }

    /**
     * Get information from the database via the {@link #conferenceRepository} instance.
     * 
     * @return Number of conferences in the database.
     */
    private MapPropertySource retrieveDatabaseInfo() {
        final Map<String, Long> databaseInfo = new HashMap<>();
        databaseInfo.put("db.conferences.count", conferenceRepository.count());
        return new MapPropertySource("database", databaseInfo);
    }

}

Let's run our Micronaut application and invoke the /info endpoint. We see the following response if we have 42 conference records in our database:

{
    "db": {
        "conferences": {
            "count": 42
        }
    },
    "sample": {
        "message": "Micronaut is awesome"
    }
}

Written with Micronaut 1.0.0.M4.

August 28, 2018

Micronaut Mastery: Using Specific Configuration Properties For HTTP Client

One of the (many) great features of Micronaut is the HTTP client. We use the @Client annotation to inject a low-level HTTP client. Or we define a declarative HTTP client based on an interface, for which Micronaut will generate an implementation. The @Client annotation supports the configuration parameter to reference a configuration class with configuration properties for the HTTP client. The configuration class extends HttpClientConfiguration to support for example the configuration of timeouts and connection pooling. We can add our own configuration properties as well and use them in our application.

In the following example we want to access the OpenWeatherMap API using a declarative HTTP client. First we write a class that extends HttpClientConfiguration. This gives us HTTP client configuration properties and we also add some properties to define the OpenWeatherMap URI, path and access key we need to invoke the REST API. Finally we add configuration properties for a @Retryable annotation we want to use for our HTTP client.

// File: src/main/java/mrhaki/micronaut/WeatherClientConfiguration.java
package weather;

import io.micronaut.context.annotation.ConfigurationProperties;
import io.micronaut.http.client.HttpClientConfiguration;
import io.micronaut.runtime.ApplicationConfiguration;

import java.net.URI;
import java.time.Duration;

import static weather.WeatherClientConfiguration.PREFIX;

/**
 * Custom HTTP client configuration set via application
 * properties prefixed with "weather.client".
 */
@ConfigurationProperties(PREFIX)
public class WeatherClientConfiguration extends HttpClientConfiguration {

    public static final String PREFIX = "weather.client";

    /**
     * HTTP client connection pool configuration.
     */
    private final WeatherClientConnectionPoolConfiguration connectionPoolConfiguration;

    /**
     * OpenWeatherMap URI.
     */
    private URI url;

    /**
     * Path for requests sent to OpenWeatherMap.
     */
    private String path;
    
    /** 
     * Key needed to access OpenWeatherMap API.
     */
    private String apiKey;

    public WeatherClientConfiguration(
            final ApplicationConfiguration applicationConfiguration,
            final WeatherClientConnectionPoolConfiguration connectionPoolConfiguration) {
        super(applicationConfiguration);
        this.connectionPoolConfiguration = connectionPoolConfiguration;
    }

    public URI getUrl() {
        return url;
    }

    public void setUrl(final URI url) {
        this.url = url;
    }

    public String getPath() {
        return path;
    }

    public void setPath(final String path) {
        this.path = path;
    }

    public String getApiKey() {
        return apiKey;
    }

    public void setApiKey(final String apiKey) {
        this.apiKey = apiKey;
    }

    @Override
    public ConnectionPoolConfiguration getConnectionPoolConfiguration() {
        return connectionPoolConfiguration;
    }
    
    @ConfigurationProperties(ConnectionPoolConfiguration.PREFIX)
    public static class WeatherClientConnectionPoolConfiguration extends ConnectionPoolConfiguration {
    }

    /**
     * Extra configuration propertie to set the values
     * for the @Retryable annotation on the WeatherClient.
     */
    @ConfigurationProperties(WeatherClientRetryConfiguration.PREFIX)
    public static class WeatherClientRetryConfiguration {
        
        public static final String PREFIX = "retry";
        
        private Duration delay;
        
        private int attempts;

        public Duration getDelay() {
            return delay;
        }

        public void setDelay(final Duration delay) {
            this.delay = delay;
        }

        public int getAttempts() {
            return attempts;
        }

        public void setAttempts(final int attempts) {
            this.attempts = attempts;
        }
    }
}

Next we write the declarative HTTP client as Java interface with the @Client annotation. We refer to our custom configuration and use the configuration properties to set the URI and path for accessing the OpenWeatherMap API.

// File: src/main/java/mrhaki/micronaut/WeatherClient.java
package weather;

import io.micronaut.http.annotation.Get;
import io.micronaut.http.client.Client;
import io.micronaut.retry.annotation.Retryable;
import io.reactivex.Single;

import java.util.Map;

// Declarative HTTP client with URL and path
// fetched from the application configuration.
// HTTP client configuration like pooled connections,
// timeouts are defined using WeatherClientConfiguration.
@Client(
        value = "${weather.client.url}",
        path = "${weather.client.path}",
        configuration = WeatherClientConfiguration.class)
// Retry accessing OpenWeatherMap REST API if error occurs.
@Retryable(
        attempts = "${weather.client.retry.attempts}",
        delay = "${weather.client.retry.delay}")
interface WeatherClient {

    /**
     * Get weather description for the town of Tilburg, NL. 
     * The APPID query parameter is filled in with the apiKey
     * argument value.
     *
     * @param apikey OpenWeatherMap API key to access REST API.
     * @return Response data from REST API.
     */
    @Get("weather?q=Tilburg,nl&APPID={apikey}")
    Single<Map<String, Object>> tilburg(String apikey);

}

Finally we write a controller that uses the declarative HTTP client WeatherClient to get a weather description for the town of Tilburg in The Netherlands:

// File: src/main/java/mrhaki/micronaut/WeatherController.java
package weather;

import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.reactivex.Single;

import java.util.List;
import java.util.Map;

/**
 * Controller to expose data from the 
 * OpenWeatherMap REST API.
 */
@Controller("/weather")
public class WeatherController {
    
    private final WeatherClient client;
    private final WeatherClientConfiguration configuration;

    public WeatherController(
            final WeatherClient client, 
            final WeatherClientConfiguration configuration) {
        this.client = client;
        this.configuration = configuration;
    }

    /**
     * Get weather data for town Tilburg, NL and get the
     * weather description to return.
     * 
     * @return Weather description as text.
     */
    @Get(value = "/tilburg", produces = MediaType.TEXT_PLAIN)
    public Single<String> weatherInTilburg() {
        return client.tilburg(configuration.getApiKey())
                     .map(response -> getWeatherDescription(response));
    }

    /**
     * Get weather description from response data.
     * 
     * @param data Response data from OpenWeatherMap API.
     * @return Textual description of weather.
     */
    private String getWeatherDescription(final Map<String, Object> data) {
        final List<Object> weatherList = (List<Object>) data.get("weather");
        final Map<String, Object> weather = (Map<String, Object>) weatherList.get(0);
        final String description = (String) weather.get("description");
        return description;
    }
    
}

In the application.yml configuration file we can set the values for the configuration properties:

# File: src/main/resources/application.yml
...
weather:
  client:
    url: http://api.openweathermap.org/
    path: /data/2.5/
    api-key: 39caa...
    read-timeout: 500ms
    retry:
      attempts: 2
      delay: 5s

When we run our application and access the URL http://localhost:8080/weather/tilburg using HTTPie we get the weather description:

$ http :8080/weather/tilburg
HTTP/1.1 200 OK
Content-Length: 13
Content-Type: text/plain;charset=UTF-8

moderate rain

Written with Micronaut 1.0.0.M4.

August 23, 2018

Micronaut Mastery: Using Stubs For Testing

Writing tests is always a good idea when developing an application. Micronaut makes it very easy to write tests. Using the @Client annotation we can generate a client for our REST resources that uses HTTP. Starting up a Micronaut application is so fast we can run our actual application in our tests. And using dependency injection we can replace components from the production application with stubs in our tests.

Let's show how we can use stub in our tests for an example application. In the example application we have controller ConferenceController that returns Conference objects. These objects are fetched from a simple data repository ConferenceDataRepository. When we write a test we want to replace the ConferenceDataRepository with a stub, so we can return the appropriate Conference objects for our tests.

First we take a look at the Conference class:

package mrhaki.micronaut;

public class Conference {
    
    private final String name;
    private final String location;

    public Conference(String name, String location) {
        this.name = name;
        this.location = location;
    }

    public String getName() {
        return name;
    }

    public String getLocation() {
        return location;
    }
    
}

We add an interface that describe the functionality we expect for getting Conference objects in our application:

// File: src/main/java/mrhaki/micronaut/ConferenceService.java
package mrhaki.micronaut;

import io.reactivex.Maybe;
import io.reactivex.Single;

import java.util.List;

interface ConferenceService {

    Single<List<Conference>> all();

    Maybe<Conference> findByName(final String name);
    
}

For our example the implementation of the ConferenceService is simple, but in a real world application the code would probably access a database to get the results:

// File: src/main/java/mrhaki/micronaut/ConferenceDataRepository.java
package mrhaki.micronaut;

import io.reactivex.Maybe;
import io.reactivex.Observable;
import io.reactivex.Single;

import javax.inject.Singleton;
import java.util.Arrays;
import java.util.List;

@Singleton
public class ConferenceDataRepository implements ConferenceService {

    private final static List<Conference> CONFERENCES =
            Arrays.asList(new Conference("Gr8Conf EU", "Copenhagen"),
                          new Conference("Gr8Conf US", "Minneapolis"),
                          new Conference("Greach", "Madrid"));

    public Single<List<Conference>> all() {
        return Single.just(CONFERENCES);
    }

    public Maybe<Conference> findByName(final String name) {
        return all()
                .flatMapObservable(conferences -> Observable.fromIterable(conferences))
                .filter(conference -> name.equals(conference.getName()))
                .singleElement();
    }

}

Finally our controller to return conference data via HTTP REST that uses via dependency injection the ConferenceDataRepository implementation of the ConferenceService interface:

// File: src/main/java/mrhaki/micronaut/ConferenceController.java
package mrhaki.micronaut;

import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.reactivex.Maybe;
import io.reactivex.Single;

import java.util.List;

@Controller("/conference")
public class ConferenceController {

    private final ConferenceService conferenceService;

    public ConferenceController(final ConferenceService conferenceService) {
        this.conferenceService = conferenceService;
    }

    @Get("/")
    public Single<List<Conference>> all() {
        return conferenceService.all();
    }

    @Get("/{name}")
    public Maybe<Conference> findByName(final String name) {
        return conferenceService.findByName(name);
    }
    
}

To add a stub for the ConferenceService in our test we must write a new implementation of the ConferenceService that is available on the test class path and not on the production code class path. In our test code directory (src/test/{java|groovy|kotlin}) we write our stub implementation. We use the @Primary annotation to instruct Micronaut to use this implementation of the ConferenceService interface. If we leave out the @Primary annotation we get an error, because we have two implementations of the interface on our classpath, ConferenceDataRepository and ConferenceServiceStub, and Micronaut doesn't know which one to use. By using @Primary we tell Micronaut to use the stub implementation.

// File: src/test/groovy/mrhaki/micronaut/ConferenceServiceStub.groovy
package mrhaki.micronaut

import io.micronaut.context.annotation.Primary
import io.reactivex.Maybe
import io.reactivex.Single

import javax.inject.Singleton

@Singleton
@Primary
class ConferenceServiceStub implements ConferenceService {

    Single<List<Conference>> all() {
        return Single.just([new Conference("Gr8Conf", "Copenhagen")])
    }

    Maybe<Conference> findByName(final String name) {
        if (name == 'Gr8Conf') {
            return Maybe.just(new Conference("Gr8Conf", "Copenhagen"))
        } else {
            return Maybe.empty()
        }
    }

}

In our test directory we also add a declarative HTTP client to invoke the REST resource. This client is only used for testing and makes invoking the REST resource very easy:

// File: src/test/groovy/mrhaki/micronaut/ConferenceClient.groovy
package mrhaki.micronaut

import io.micronaut.http.annotation.Get
import io.micronaut.http.client.Client
import io.reactivex.Maybe
import io.reactivex.Single

@Client("/conference")
interface ConferenceClient {

    @Get("/")
    Single<List<Conference>> all()

    @Get("/{name}")
    Maybe<Conference> findByName(final String name)

}

We write a Spock specification to test our REST resource and it will use the stub code as implementation of ConferenceService:

// File: src/test/groovy/mrhaki/micronaut/ConferenceContollerSpec.groovy
package mrhaki.micronaut

import io.micronaut.context.ApplicationContext
import io.micronaut.runtime.server.EmbeddedServer
import io.reactivex.Maybe
import io.reactivex.Single
import spock.lang.AutoCleanup
import spock.lang.Shared
import spock.lang.Specification

class ConferenceContollerSpec extends Specification {
    
    @Shared
    @AutoCleanup
    private EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer)

    @Shared
    private ConferenceClient client = embeddedServer.applicationContext.getBean(ConferenceClient)

    void 'get all conferences'() {
        when:
        final Single<List<Conference>> result = client.all()
        
        then:
        final conference = result.blockingGet().first() 
        with(conference) {
            name == 'Gr8Conf'
            location == 'Copenhagen'
        }
    }
    
    void 'find conference by name'() {
        when:
        final Maybe<Conference> result = client.findByName('Gr8Conf')
        
        then:
        final conference = result.blockingGet()
        with(conference) {
            name == 'Gr8Conf'
            location == 'Copenhagen'
        }
    }
    
    void 'return empty when conference cannot be found by name'() {
        when:
        final Maybe<Conference> result = client.findByName('JavaOne')

        then:
        result.isEmpty().blockingGet()
    }
}

Written with Micronaut 1.0.0.M4.

August 22, 2018

Micronaut Mastery: Documenting Our API Using Spring REST Docs

Spring REST Docs is a project to document a RESTful API using tests. The tests are used to invoke real REST calls on the application and to generate Asciidoctor markup snippets. We can use the generated snippets in an Asciidoctor document with documentation about our API. We can use Spring REST Docs to document a REST API we create using Micronaut.

First we must change our build file and include the Asciidoctor plugin and add dependencies to Spring REST Docs. The following example Gradle build file adds the Gradle Asciidoctor plugin, Spring REST Docs dependencies and configures the test and asciidoctor tasks. Spring REST Docs supports three different web clients to invoke the REST API of our application: Spring MockMVC, Spring Webflux WebTestClient and REST Assured. We use REST Assured 3, because it has little dependencies on other frameworks (like Spring).

// File: build.gradle
...

plugins {
    id "org.asciidoctor.convert" version "1.5.8.1"
}

...

ext {
    snippetsDir = file('build/generated-snippets')
    springRestDocsVersion = '2.0.2.RELEASE'
}

dependencies {
    asciidoctor "org.springframework.restdocs:spring-restdocs-asciidoctor:$springRestDocsVersion"
    testCompile "org.springframework.restdocs:spring-restdocs-restassured:$springRestDocsVersion"
}

test {
    outputs.dir snippetsDir
}

asciidoctor {
    inputs.dir snippetsDir
    dependsOn test
}

Let's add a controller to our application that has two methods to return one or more Conference objects. We want to document both REST API resource methods. First we look at the Conference class that is used:

// File: src/main/java/mrhaki/micronaut/Conference.java
package mrhaki.micronaut;

public class Conference {
    private final String name;
    private final String location;

    public Conference(final String name, final String location) {
        this.name = name;
        this.location = location;
    }

    public String getName() {
        return name;
    }

    public String getLocation() {
        return location;
    }
}

Next we write the following controller to implement /conference to return multiple conferences and /conference/{name} to return a specific conference. The controller is dependent on the class ConferenceService that contains the real logic to get the data, but the implementation is not important for our example to document the controller:

// File: src/main/java/mrhaki/micronaut/ConferenceController.java
package mrhaki.micronaut;

import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Controller("/conference")
public class ConferenceController {
    
    private final ConferenceService conferenceService;

    public ConferenceController(final ConferenceService conferenceService) {
        this.conferenceService = conferenceService;
    }

    @Get("/")
    public Flux<Conference> all() {
        return conferenceService.all();
    }
    
    @Get("/{name}")
    public Mono<Conference> findByName(final String name) {
        return conferenceService.findByName(name);
    }
}

Now it is time to write our test that will invoke our controller and generate Asciidoctor markup snippets. We use Spock for writing the test in our example:

// File: src/test/groovy/mrhaki/micronaut/ConferenceApiSpec.groovy
package mrhaki.micronaut

import io.micronaut.context.ApplicationContext
import io.micronaut.http.HttpStatus
import io.micronaut.runtime.server.EmbeddedServer
import io.restassured.builder.RequestSpecBuilder
import io.restassured.specification.RequestSpecification
import org.junit.Rule
import org.springframework.restdocs.JUnitRestDocumentation
import spock.lang.AutoCleanup
import spock.lang.Shared
import spock.lang.Specification

import static io.restassured.RestAssured.given
import static org.springframework.restdocs.operation.preprocess.Preprocessors.modifyUris
import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields
import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document
import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.documentationConfiguration

class ConferenceApiSpec extends Specification {

    @Shared
    @AutoCleanup
    private EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer)

    @Rule
    private JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation()

    private RequestSpecification spec

    void setup() {
        // Create a REST Assured request specification
        // with some defaults. All URI's
        // will not have localhost as server name,
        // but api.example.com and the port is removed.
        // All JSON responses are prettyfied.
        this.spec = new RequestSpecBuilder()
                .addFilter(
                    documentationConfiguration(restDocumentation)
                        .operationPreprocessors()
                        .withRequestDefaults(
                            modifyUris().host('api.example.com')
                                        .removePort())
                        .withResponseDefaults(prettyPrint()))
                .build()
    }

    void "get all conferences"() {
        given:
        final request =
                given(this.spec)
                    // The server port is set and the value is
                    // used from embeddedServer.
                    .port(embeddedServer.URL.port)
                    .accept("application/json")
                    .filter(
                        document(
                            "all", 
                            responseFields(
                                fieldWithPath("[].name").description("Name of conference."),
                                fieldWithPath("[].location").description("Location of conference.")
                        )))

        when:
        final response = request.get("/conference")

        then:
        response.statusCode() == HttpStatus.OK.code
    }

    void "get conference with given name"() {
        given:
        final request = 
                given(this.spec)
                    .port(embeddedServer.URL.port)
                    .accept("application/json")
                    .filter(
                        document(
                            "getByName", 
                            responseFields(
                                fieldWithPath("name").description("Name of conference."),
                                fieldWithPath("location").description("Location of conference.")
                )))

        when:
        final response = request.get("/conference/Gr8Conf EU")

        then:
        response.statusCode() == HttpStatus.OK.code
    }

}

Finally we create a Asciidoctor document to describe our API and use the generated Asciidoctor markup snippets from Spring REST Docs in our document. We rely in our example document on the operation macro that is part of Spring REST Docs to include some generated snippets:

// File: src/docs/asciidoc/api.adoc
= Conference API

== Get all conferences

operation::all[snippets="curl-request,httpie-request,response-body,response-fields"]

== Get conference using name

operation::getByName[snippets="curl-request,httpie-request,response-body,response-fields"]

We run the Gradle asciidoctor task to create the documentation. When we open the generated HTML we see the following result:

Written with Micronaut 1.0.0.M4 and Spring REST Docs 2.0.2.RELEASE.

August 21, 2018

Micronaut Mastery: Return Response Based On HTTP Accept Header

Suppose we want our controller methods to return a JSON response when the HTTP Accept header is set to application/json and XML when the Accept header is set to application/xml. We can access the values of HTTP headers in our controller methods by adding an argument of type HttpHeaders to our method definition and Micronaut will add all HTTP headers with their values as HttpHeaders object when we run the application. In our method we can check the value of the Accept header and return a different value based on the header value.

In the following example controller we have a sample method with an argument of type HttpHeaders. We check the value of the Accept header using the method accept and return either XML or JSON as response.

package mrhaki.micronaut;

import io.micronaut.http.HttpHeaders;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;

@Controller("/message")
public class MessageController {
    
    @Get("/")
    public HttpResponse<?> sample(final HttpHeaders headers) {
        // Simple object to be returned from this method either
        // as XML or JSON, based on the HTTP Accept header.
        final Message message = new Message("Micronaut is awesome");

        // Check if HTTP Accept header is "application/xml".
        if (headerAcceptXml(headers)) {
            // Encode messages as XML.
            final String xml = encodeAsXml(message);
            
            // Return response and set content type 
            // to "application/xml".
            return HttpResponse.ok(xml)
                               .contentType(MediaType.APPLICATION_XML_TYPE);
        }
        
        // Default response as JSON.
        return HttpResponse.ok(message);
    }

    /**
     * Check HTTP Accept header with value "application/xml"
     * is sent by the client.
     * 
     * @param headers Http headers sent by the client.
     * @return True if the Accept header contains "application/xml".
     */
    private boolean headerAcceptXml(final HttpHeaders headers) {
        return headers.accept().contains(MediaType.APPLICATION_XML_TYPE);
    }

    /**
     * Very simple way to create XML String with message content.
     * 
     * @param message Message to be encoded as XML String.
     * @return XML String with message content.
     */
    private String encodeAsXml(final Message message) {
        return String.format("<content>%s</content>", message.getContent());
    }

}

The Message class that is converted to XML or JSON is simple:

package mrhaki.micronaut;

public class Message {

    final String content;

    public Message(final String content) {
        this.content = content;
    }

    public String getContent() {
        return content;
    }

}

When we run the application and GET /message with HTTP Accept header value application/xml we get the following response:

<content>Micronaut is awesome</content>

And with HTTP Accept header value application/json we get the following response:

{
    "content": "Micronaut is awesome"
}

We can test our controller with the following Spock specification:

package mrhaki.micronaut

import io.micronaut.context.ApplicationContext
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpResponse
import io.micronaut.http.HttpStatus
import io.micronaut.http.MediaType
import io.micronaut.http.client.RxHttpClient
import io.micronaut.runtime.server.EmbeddedServer
import spock.lang.AutoCleanup
import spock.lang.Shared
import spock.lang.Specification

class MessageControllerSpec extends Specification {

    @Shared
    @AutoCleanup
    private static EmbeddedServer embeddedServer =
            ApplicationContext.run(EmbeddedServer)

    @Shared
    @AutoCleanup
    private static RxHttpClient client =
            embeddedServer.applicationContext
                          .createBean(RxHttpClient, embeddedServer.getURL())

    void "get message as XML"() {
        given:
        final request = HttpRequest.GET("/message").accept(MediaType.APPLICATION_XML_TYPE)
        HttpResponse response = client.toBlocking().exchange(request, String)

        expect:
        response.status == HttpStatus.OK
        response.body() == 'Micronaut is awesome'
    }

    void "get message as JSON"() {
        given:
        HttpResponse response = client.toBlocking().exchange("/message", Message)

        expect:
        response.status == HttpStatus.OK
        response.body().getContent() == 'Micronaut is awesome'
    }
    
}

Written with Micronaut 1.0.0.M4.

August 20, 2018

Micronaut Mastery: Add Custom Health Indicator

When we add the io.micronaut:management dependency to our Micronaut application we get, among other things, a /health endpoint. We must enable it in our application configuration where we can also configure how much information is shown and if we want to secure the endpoint. Micronaut has some built-in health indicators, some of which are only available based on certain conditions. For example there is a disk space health indicator that will return a status of DOWN when the free disk space is less than a (configurable) threshold. If we would have one or more DataSource beans for database access in our application context a health indicator is added as well to show if the database(s) are available or not.

We can also add our own health indicator that will show up in the /health endpoint. We must write a class that implements the HealthIndicator interface and add it to the application context. We could add some conditions to make sure the bean is loaded when needed. Micronaut also has the abstract AbstractHealthIndicator class that can be used as base class for writing custom health indicators.

First we must add the io.micronaut:management dependency to our compile class path, like in the following example Gradle build file:

// File: build.gradle
...
dependencies {
    ...
    compile "io.micronaut:management"
    ...
}
...

Next we write a class that implements HealthIndicator or extends AbstractHealthIndicator. In the following example we implement HealthIndicator and the method getResult. This health indicator will try to access a remote URL and will return a status UP when the URL is reachable and DOWN when the status code is invalid or an exception occurs. We also use the @Requires annotation to make sure the indicator is only loaded when the correct value is set for a configuration property and when the HealthPoint bean is available.

package mrhaki.micronaut;

import io.micronaut.health.HealthStatus;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.client.Client;
import io.micronaut.http.client.RxHttpClient;
import io.micronaut.management.health.indicator.HealthIndicator;
import io.micronaut.management.health.indicator.HealthResult;
import org.reactivestreams.Publisher;

import javax.inject.Singleton;
import java.util.Collections;

@Singleton
// Only create bean when configuration property
// endpoints.health.url.enabled equals true,
// and HealthEndpoint bean to expose /health endpoint is available.
@Requires(property = HealthEndpoint.PREFIX + ".url.enabled", value = "true")
@Requires(beans = HealthEndpoint.class)
public class RemoteUrlHealthIndicator implements HealthIndicator {

    /**
     * Name for health indicator.
     */
    private static final String NAME = "remote-url-health";

    /**
     * URL to check.
     */
    private static final String URL = "http://www.mrhaki.com/";

    /**
     * We use {@link RxHttpClient} to check if
     * URL is reachable.
     */
    private RxHttpClient client;

    /**
     * Inject client with URL to check.
     * 
     * @param client Client to check if URl is reachable.
     */
    public RemoteUrlHealthIndicator(@Client(URL) final RxHttpClient client) {
        this.client = client;
    }

    /**
     * Implementaton of {@link HealthIndicator#getResult()} where we
     * check if the url is reachable and return result based
     * on the HTTP status code.
     * 
     * @return Contains {@link HealthResult} with status UP or DOWN.
     */
    @Override
    public Publisher<HealthResult> getResult() {
        return client.exchange(HttpRequest.HEAD("/"))
                     .map(this::checkStatusCode)
                     .onErrorReturn(this::statusException);
    }

    /**
     * Check response status code and return status UP when code is
     * between 200 and 399, otherwise return status DOWN.
     * 
     * @param response Reponse with status code.
     * @return Result with checked URL in the details and status UP or DOWN.
     */
    private HealthResult checkStatusCode(HttpResponse<?> response) {
        final int statusCode = response.getStatus().getCode();
        final boolean statusOk = statusCode >= 200 && statusCode < 400;
        final HealthStatus healthStatus = statusOk ? HealthStatus.UP : HealthStatus.DOWN;

        // We use the builder API of HealthResult to create 
        // the health result with a details section containing
        // the checked URL and the health status.
        return HealthResult.builder(NAME, healthStatus)
                           .details(Collections.singletonMap("url", URL))
                           .build();
    }

    /**
     * Set status is DOWN when exception occurs checking URL status.
     * 
     * @param exception Exception thrown when checking status.
     * @return Result with exception in details in status DOWN.
     */
    private HealthResult statusException(Throwable exception) {
        // We use the build API of HealthResult to include
        // the original exception in the details and 
        // status is DOWN.
        return HealthResult.builder(NAME, HealthStatus.DOWN)
                           .exception(exception)
                           .build();
    }

}

Finally we add configuration properties to our application.yml file:

# File: src/main/resources/application.yml
...
endpoints:
  health:
    enabled: true
    sensitive: false # non-secured endpoint
    details-visible: ANONYMOUS # show details for everyone
    url:
      enabled: true
...

Let's run our Micronaut application and invoke the /health endpoint. In the JSON response we see the output of our custom health indicator:

...
        "remote-url-health": {
            "details": {
                "url": "http://www.mrhaki.com/"
            },
            "name": "micronaut-sample",
            "status": "UP"
        },
...

When we use a URL that is not available we get the following output:

...
        "remote-url-health": {
            "details": {
                "error": "io.micronaut.http.client.exceptions.HttpClientResponseException: Not Found"
            },
            "name": "micronaut-sample",
            "status": "DOWN"
        },
...

Written with Micronaut 1.0.0.M4.

August 17, 2018

Micronaut Mastery: Add Build Info To Info Endpoint

Micronaut has some built-in management endpoints to get information, a list of beans, health checks and more. To enable the endpoints we must add the dependency io.micronaut:management to our application. Then we can add configuration properties to enable the different endpoints. The /info endpoint gathers information from several sources with properties. If we want to add build information we must create a file build-info.properties with information and Micronaut will automatically add the properties from the file to the /info endpoint.

We can choose how we want to create the build-info.properties file. The location is configurable via Micronaut application configuration properties, but the default location is on the classpath at META-INF/build-info.properties. To make life easy for us we reuse the BuildInfo Gradle task from the Spring Boot Gradle plugin to create the build-info.properties file.

In the following example build file we add a build script classpath dependency on the Spring Boot Gradle plugin. This will add the BuildInfo class to our Gradle build file. Next we create a new task buildInfo using the BuildInfo type and we set the destination directory to the resources/main/META-INF directory in the project build directory. This is the default location that Micronaut uses to read the properties for the /info endpoint.

// File: build.gradle
buildscript {
   ...
   dependencies {
       ...
       classpath "org.springframework.boot:spring-boot-gradle-plugin:2.0.4.RELEASE"
       ...
    }
}
...
dependencies {
    ...
    // Add management endpoint support.
    runtime "io.micronaut:management"
    ...
}
...
import org.springframework.boot.gradle.tasks.buildinfo.BuildInfo

task buildInfo(type: BuildInfo) {
    description = 'Generates build-info.properties file.'

    group = BasePlugin.BUILD_GROUP

    destinationDir = new File(sourceSets.main.output.resourcesDir, 'META-INF')

    properties {
        time = null // Otherwise task is never up-to-date
        artifact = shadowJar.baseName
        
        // Extra properties that will be added to build-info.properties.
        additionalProperties = [
                by: System.properties['user.name'],
                operatingSystem: "${System.properties['os.name']} (${System.properties['os.version']})",
                continuousIntegration: System.getenv('CI') ? true: false,
                machine: InetAddress.localHost.hostName,
        ]
    }
}
classes.dependsOn buildInfo
...

In our application configuration we enable the /info endpoint:

# File: src/main/resources/application.yml
...
endpoints:
  info:
    enabled: true
    sensitive: false
...

We start our Micronaut application and invoke the /info endpoint and we get the following data:

{
    "build": {
        "artifact": "micronaut-sample",
        "by": "mrhaki",
        "continuous-integration": "false",
        "group": "mrhaki.micronaut",
        "machine": "mrhaki.fritz.box",
        "name": "micronaut-sample",
        "operating-system": "Mac OS X (10.13.6)",
        "version": "1.0.1"
    }
}

Written with Micronaut 1.0.0.M4.

August 16, 2018

Micronaut Mastery: Decode JSON Using Custom Constructor Without Jackson Annotations

Micronaut uses Jackson to encode objects to JSON and decode JSON to objects. Micronaut adds a Jackson ObjectMapper bean to the application context with all configuration to work properly. Jackson can by default populate an object with values from JSON as the class has a no argument constructor and the properties can be accessed. But if our class doesn't have a no argument constructor we need to use the @JsonCreator and @JsonProperty annotations to help Jackson. We can use these annotation on the constructor with arguments that is used to create an object.

But we can even make it work without the extra annotations, so our classes are easier to read and better reusable. We need to add the Jackson ParameterNamesModule as module to the ObjectMapper instance in our application. And we need to compile our sources with the -parameters argument, so the argument names are preserved in the compiled code. Luckily the -parameters option is already added to our Gradle build when we create a Micronaut application. All we have to do is to add the ParameterNamesModule in our application.

We need to add a dependency on com.fasterxml.jackson.module:jackson-module-parameter-names to our compile class path. Micronaut will automatically find the ParameterNamesModule and add it to the ObjectMapper using the findAndRegisterModules method.

So we change our build.gradle file first:

// File: build.gradle
...
dependencies {
    ...
    compile "com.fasterxml.jackson.module:jackson-module-parameter-names:2.9.0"
    ...
}
...

In our application we have the following class that has an argument constructor to create a immutable object:

package mrhaki;

import java.util.Objects;

public class Language {
    private final String name;

    private final String platform;

    public Language(final String name, final String platform) {
        this.name = name;
        this.platform = platform;
    }

    public String getName() {
        return name;
    }

    public String getPlatform() {
        return platform;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) { return true; }
        if (o == null || getClass() != o.getClass()) { return false; }
        final Language language = (Language) o;
        return Objects.equals(name, language.name) &&
                Objects.equals(platform, language.platform);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, platform);
    }
}

We write the following sample controller to use the Language class as a return type (we wrap it in a Mono object so the method is reactive):

package mrhaki;

import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import reactor.core.publisher.Mono;

@Controller("/languages")
public class LanguagesController {

    @Get("/groovy")
    public Mono<Language> getGroovy() {
        return Mono.just(new Language("Groovy", "JVM"));
    }

}

And in our test we use HttpClient to invoke the controller method. The exchange method will trigger a decode of the JSON output of the controller to a Language object:

package mrhaki

import io.micronaut.context.ApplicationContext
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpStatus
import io.micronaut.http.client.HttpClient
import io.micronaut.runtime.server.EmbeddedServer
import spock.lang.AutoCleanup
import spock.lang.Shared
import spock.lang.Specification

class LanguagesControllerSpec extends Specification {

    @AutoCleanup
    @Shared
    private static EmbeddedServer server = ApplicationContext.run(EmbeddedServer)

    @AutoCleanup
    @Shared
    private static HttpClient client = server.applicationContext.createBean(HttpClient, server.URL)

    void '/languages/groovy should find language Groovy'() {
        given:
        final request = HttpRequest.GET('/languages/groovy')

        when:
        final response = client.toBlocking().exchange(request, Language)

        then:
        response.status() == HttpStatus.OK

        and:
        response.body() == new Language('Groovy', 'JVM')
    }


}

When we wouldn't have the dependency on jackson-module-parameter-names and not use the -parameter compiler option we get the following error message:

[nioEventLoopGroup-1-6] WARN  i.n.channel.DefaultChannelPipeline - An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.
io.micronaut.http.codec.CodecException: Error decoding JSON stream for type [class mrhaki.Language]: Cannot construct instance of `hello.conf.Language` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (byte[])"{"name":"Groovy","platform":"JVM"}"; line: 1, column: 2]

But with the dependency and -parameter compiler option we have a valid test without any errors. Jackson knows how to use the argument constructor to create a new Language object.

Written with Micronaut 1.0.0.M4.

Micronaut Mastery: Using Reactor Mono And Flux

Micronaut is reactive by nature and uses RxJava2 as implementation for the Reactive Streams API by default. RxJava2 is on the compile classpath by default, but we can easily use Project Reactor as implementation of the Reactive Streams API. This allows us to use the Reactor types Mono and Flux. These types are also used by Spring's Webflux framework and makes a transition from Webflux to Micronaut very easy.

How we do use Project Reactor in our Micronaut application? We only have to add the dependency the Project Reactory core library to our project. In the following example we add it to our build.gradle file as:

// File: build.gradle
...
dependencies {
    ...
    // The version of Reactor is resolved
    // via the BOM of Micronaut, so we know
    // the version is valid for Micronaut.
    compile 'io.projectreactor:reactor-core'
    ...
}
...

Now we can use Mono and Flux as return types for methods. If we use them in our controller methods Micronaut will make sure the code is handled on the Netty event loop. This means we must handle blocking calls (like accessing a database using JDBC) with care and make sure a blocking call invoked from the controller methods is handled on a different thread.

In the following example we have a simple controller. Some of the methods use a repository implementation with code that access a databases using JDBC. The methods of the repository implementation are not reactive, therefore we must use Mono.fromCallable with Reactor's elastic scheduler to make sure the code is called on separate threads and will not block our Netty event loop.

package mrhaki;

import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

import java.util.concurrent.Callable;

@Controller("/languages")
public class LanguagesController {

    // Repository reads data from database
    // using JDBC and uses simple return types.
    private final LanguagesRepository repository;

    public LanguagesController(final LanguagesRepository repository) {
        this.repository = repository;
    }

    @Get("/{name}")
    public Mono<Language> findByName(final String name) {
        return blockingGet(() -> repository.findByName(name));
    }

    @Get("/")
    public Flux<Language> findAll() {
        return blockingGet(() -> repository.findAll()).flatMapMany(Flux::fromIterable);
    }

    // Run callable code on other thread pool than Netty event loop,
    // so blocking call will not block the event loop.
    private <T> Mono<T> blockingGet(final Callable<T> callable) {
        return Mono.fromCallable(callable)
                   .subscribeOn(Schedulers.elastic());
    }
}

The repository interface looks like this:

package mrhaki;

interface LanguagesRepository {
    List<Language> findAll();
    Language findByName(String name);
}

Let's write a Spock specification to test if our controller works correctly:

package mrhaki

import io.micronaut.context.ApplicationContext
import io.micronaut.core.type.Argument
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpStatus
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.exceptions.HttpClientResponseException
import io.micronaut.runtime.server.EmbeddedServer
import spock.lang.AutoCleanup
import spock.lang.Shared
import spock.lang.Specification

class LanguagesControllerSpec extends Specification {

    @AutoCleanup
    @Shared
    private static EmbeddedServer server = ApplicationContext.run(EmbeddedServer)

    @AutoCleanup
    @Shared
    private static HttpClient client = server.applicationContext.createBean(HttpClient, server.URL)

    void '/languages should return all languages'() {
        given:
        final request = HttpRequest.GET('/languages')

        when:
        final response = client.toBlocking().exchange(request, Argument.of(List, Language))

        then:
        response.status() == HttpStatus.OK

        and:
        response.body()*.name == ['Java', 'Groovy', 'Kotlin']

        and:
        response.body().every { language -> language.platform == 'JVM' }
    }

    void '/languages/groovy should find language Groovy'() {
        given:
        final request = HttpRequest.GET('/languages/Groovy')

        when:
        final response = client.toBlocking().exchange(request, Language)

        then:
        response.status() == HttpStatus.OK

        and:
        response.body() == new Language('Groovy', 'JVM')
    }

    void '/languages/dotnet should return 404'() {
        given:
        final request = HttpRequest.GET('/languages/dotnet')

        when:
        client.toBlocking().exchange(request)

        then:
        HttpClientResponseException notFoundException = thrown(HttpClientResponseException)
        notFoundException.status == HttpStatus.NOT_FOUND
    }

}

Written with Micronaut 1.0.0.M4.