### Hello World Controller Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/quickStart/creatingServer.adoc Defines a simple controller that responds to GET requests at the `/hello` path with the text "Hello World". Ensure the file is placed in the correct package directory based on your project's language. ```java package hello.world; import io.micronaut.http.annotation.Controller; import io.micronaut.http.annotation.Get; @Controller("/hello") public class HelloController { @Get public String index() { return "Hello World"; } } ``` -------------------------------- ### Systemd Socket File Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/httpServer/serverConfiguration/listener.adoc Example systemd socket file for configuring socket activation. ```ini [Socket] ListenStream=127.0.0.1:8080 [Install] WantedBy=sockets.target ``` -------------------------------- ### Start Gradle Project Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/cli/createProject.adoc After creating a Gradle project, you can start the application using the `./gradlew run` command. ```bash $ ./gradlew run ``` -------------------------------- ### Initial Delay Scheduling Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/aop/scheduling.adoc Schedules a task to run only once after an initial delay. This example runs one minute after the server starts. ```java package import io.micronaut.scheduling.annotation.Scheduled; import jakarta.inject.Singleton; @Singleton public class ScheduledExample { @Scheduled(initialDelay = "1m") void initialDelay() { // ... } } ``` -------------------------------- ### Systemd Service File Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/httpServer/serverConfiguration/listener.adoc Example systemd service file for a Micronaut HTTP server with socket activation. ```ini [Unit] Description=Micronaut HTTP server with socket activation After=network.target app.socket Requires=app.socket [Service] Type=simple ExecStart=/usr/bin/java -jar /app.jar ``` -------------------------------- ### Request and Response Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/httpServer/requestResponse.adoc This example demonstrates how to use HttpRequest to access query parameters and HttpResponse.ok() to return a response with a custom header. ```java package example.http.server.request; import io.micronaut.http.HttpRequest; import io.micronaut.http.HttpResponse; import io.micronaut.http.MediaType; import io.micronaut.http.annotation.Controller; import io.micronaut.http.annotation.Get; @Controller("/hello") public class MessageController { @Get(produces = MediaType.TEXT_PLAIN) public HttpResponse hello(HttpRequest request) { String name = request.getParameters().get("name", "World"); return HttpResponse.ok("Hello " + name).header("X-My-Header", "My Value"); } } ``` -------------------------------- ### Install GraalVM with SDKMAN! Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/languageSupport/graal/graalServices.adoc Install and use a specific GraalVM version using SDKMAN! on Linux or Mac. ```bash sdk install java {graalVersion}-graal sdk use java {graalVersion}-graal ``` -------------------------------- ### Google Cloud Run Deployment Output Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/serverlessFunctions/gcpCloudRun.adoc This is an example of the output you will see after successfully deploying your application to Google Cloud Run. ```text Service name: (example): Deploying container to Cloud Run service [example] in project [PROJECT_ID] region [us-central1] ✓ Deploying... Done. ✓ Creating Revision... ✓ Routing traffic... ✓ Setting IAM Policy... Done. Service [example] revision [example-00004] has been deployed and is serving 100 percent of traffic at https://example-9487r97234-uc.a.run.app ``` -------------------------------- ### Start Consul with Docker Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/cloud/cloudConfiguration/distributedConfigurationConsul.adoc Use this command to quickly start a Consul instance using Docker for local development and testing. ```bash docker run -p 8500:8500 consul ``` -------------------------------- ### Bintray Service Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/httpClient/clientFilter.adoc An example `BintrayService` demonstrating the injection of `ReactorHttpClient` for interacting with the Bintray API. Configuration for organization is supported. ```java package import io.micronaut.reactor.http.client.ReactorHttpClient import jakarta.inject.Singleton @Singleton open class BintrayService( private val httpClient: ReactorHttpClient, @Value("${bintray.organization:micronaut}") private val organization: String ) { fun fetchRepositories(): HttpResponse { return httpClient.toBlocking() .exchange("https://api.bintray.com/orgs/$organization/repos", String::class.java) } fun fetchPackages(repo: String): HttpResponse { return httpClient.toBlocking() .exchange("https://api.bintray.com/repos/$organization/$repo/packages", String::class.java) } } ``` -------------------------------- ### Micronaut CLI Configuration Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/cli/commands.adoc Example of a micronaut-cli.yml file showing default package, test framework, and source language settings. ```yaml defaultPackage: example --- testFramework: spock sourceLanguage: java ``` -------------------------------- ### Install git-filter-repo Source: https://github.com/micronaut-projects/micronaut-core/wiki/New-Module-Checklist Installs the git-filter-repo tool using Homebrew. This is a prerequisite for filtering Git repositories. ```bash brew install git-filter-repo ``` -------------------------------- ### JdbcBookService Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/ioc/replaces.adoc This is an example of a JdbcBookService class. It is used to demonstrate how other classes can replace it. ```java package io.micronaut.docs.requires; import jakarta.inject.Singleton; @Singleton public class JdbcBookService { public String getBook() { return "The Lord of the Rings"; } } ``` -------------------------------- ### Install Micronaut SDK Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/RELEASE.adoc Install a specific version of the Micronaut SDK using the SDK command-line tool for verification purposes. ```bash sdk install micronaut XXX ``` -------------------------------- ### Start Gradle Project Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/cli/createProject.adoc To start a Micronaut Gradle project, execute the `./gradlew run` command in the project's root directory. ```bash ./gradlew run ``` -------------------------------- ### Supplying Configuration Values Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/config/configurationProperties.adoc Provide configuration values through property sources. This example demonstrates how to set values for the 'my.engine' configuration properties. ```java package io.micronaut.docs.config.properties; import io.micronaut.context.event.ApplicationEventListener; import io.micronaut.context.event.StartupEvent; import jakarta.inject.Singleton; @Singleton public class VehicleSpec implements ApplicationEventListener { private final EngineConfig engineConfig; public VehicleSpec(EngineConfig engineConfig) { this.engineConfig = engineConfig; } @Override public void onApplicationEvent(StartupEvent event) { System.out.println(engineConfig.getManufacturer() + " Engine Starting " + engineConfig.getCylinders() + "[" + engineConfig.getRodType().orElse("default") + "]"); } } ``` -------------------------------- ### Start Maven Project Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/cli/createProject.adoc To start a Micronaut Maven project, execute the `./mvnw mn:run` command in the project's root directory. ```bash ./mvnw mn:run ``` -------------------------------- ### Configuring Headers Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/httpClient/clientAnnotation/clientHeaders.adoc Configure header values using application.yml or environment variables. This example shows how to set the 'pet.client.id' property. ```yaml pet: client: id: foo ``` -------------------------------- ### BookFactory Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/ioc/replaces.adoc This factory class produces different types of books. It serves as a base for demonstrating factory replacement. ```java package io.micronaut.docs.replaces; import io.micronaut.context.annotation.Factory; import jakarta.inject.Singleton; @Factory public class BookFactory { @Singleton public Book book() { return new Book("The Lord of the Rings"); } @Singleton public TextBook textBook() { return new TextBook("The Hobbit"); } @Singleton public Novel novel() { return new Novel("Dune"); } } ``` -------------------------------- ### Hello World HTTP Controller Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/httpServer.adoc A basic controller that responds to GET requests at the '/hello' path with 'Hello World!' text. ```java package example.micronaut.docs.server.intro; import io.micronaut.controller.Controller; import io.micronaut.http.MediaType; @Controller("/hello") public class HelloController { @Get(produces = MediaType.TEXT_PLAIN) public String index() { return "Hello World!"; } } ``` -------------------------------- ### CurrentDateEndpoint GET Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/management/buildingEndpoints/endpointMethod.adoc Annotate a method with @Read to handle GET requests. This example shows a basic implementation. ```java package io.micronaut.docs.server.endpoint; import io.micronaut.http.MediaType; import io.micronaut.management.endpoint.annotation.Read; import jakarta.inject.Singleton; @Singleton public class CurrentDateEndpoint { @Read public long currentDate() { return System.currentTimeMillis(); } } ``` -------------------------------- ### Create Client Command Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/cli/commands.adoc Generates a Client interface. Use the --lang flag to specify the language and --force to overwrite existing files. ```bash $ mn create-client Book ``` -------------------------------- ### ResourceBundleMessageSource Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/i18n/bundle.adoc This example shows how to retrieve localized messages using `ResourceBundleMessageSource`. Ensure the appropriate locale is provided to get the correct message. ```java import io.micronaut.context.i18n.MessageSource; import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import jakarta.inject.Inject; import org.junit.jupiter.api.Test; import java.util.Locale; import static org.junit.jupiter.api.Assertions.assertEquals; @MicronautTest class I18nSpec { @Inject protected MessageSource messageSource; @Test void testI18n() { assertEquals("Hello World", messageSource.getMessage("hello", Locale.ENGLISH)); assertEquals("Hola Mundo", messageSource.getMessage("hello", new Locale("es"))); } } ``` -------------------------------- ### Masking Environment Values - Deny List Approach Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/management/providedEndpoints/environmentEndpoint.adoc Configure filtering to mask specific patterns or exact matches, allowing all other values in plain text. This example masks values starting with 'sekrt', exactly matching 'exact-match', or starting with 'private.'. ```java @Singleton public class AllPlainExceptSecretOrMatchEnvFilter implements EnvironmentEndpointFilter { // Mask anything starting with `sekrt` private static final Pattern SECRET_PREFIX_PATTERN = Pattern.compile("sekrt.*", Pattern.CASE_INSENSITIVE); // Mask anything exactly matching `exact-match` private static final String EXACT_MATCH = "exact-match"; // Mask anything that starts with `private.` private static final Predicate PREDICATE_MATCH = name -> name.startsWith("private."); @Override public void specifyFiltering(@NotNull EnvironmentFilterSpecification specification) { specification .maskNone() // All values will be in plain-text apart from the supplied patterns .exclude(SECRET_PREFIX_PATTERN) .exclude(EXACT_MATCH) .exclude(PREDICATE_MATCH); } } ``` -------------------------------- ### Create Websocket Server Command Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/cli/commands.adoc Generates a Websocket server. Use the --lang flag to specify the language and --force to overwrite existing files. ```bash $ mn create-websocket-server ``` -------------------------------- ### CurrentDateEndpoint GET with Produces Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/management/buildingEndpoints/endpointMethod.adoc The @Read annotation accepts an optional 'produces' argument to set the response media type. This example sets it to 'text/plain'. ```java package io.micronaut.docs.server.endpoint; import io.micronaut.http.MediaType; import io.micronaut.management.endpoint.annotation.Read; import jakarta.inject.Singleton; @Singleton public class CurrentDateEndpoint { @Read(produces = MediaType.TEXT_PLAIN) public String currentDate() { return "the_date_is: " + System.currentTimeMillis(); } } ``` -------------------------------- ### Method Invocation Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/appendix/architecture/introspectionArch.adoc Demonstrates how to invoke a method with specific arguments using introspection. Ensure the arguments match the method signature. ```java Method method = // ... obtain method instance Object[] args = new Object[] { (String)args[0], (Integer)args[1] }; method.invoke(bean, args); ``` -------------------------------- ### List Available Features for Application Creation Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/cli.adoc Use the `--list-features` flag with a create command to see all available features that can be included in a new project. ```bash mn> create-app --list-features Available Features (+) denotes the feature is included by default Name Description ------------------------------- --------------- Cache cache-caffeine Adds support for cache using Caffeine (https://github.com/ben-manes/caffeine) cache-ehcache Adds support for cache using EHCache (https://www.ehcache.org/) cache-hazelcast Adds support for cache using Hazelcast (https://hazelcast.org/) cache-infinispan Adds support for cache using Infinispan (https://infinispan.org/) ``` -------------------------------- ### CurrentDateEndpoint - Read Operation Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/management/buildingEndpoints/endpointMethod.adoc This snippet demonstrates how to create an endpoint that responds to GET requests using the @Read annotation. It shows a basic implementation and an example of how to consume it with curl. ```APIDOC ## GET /date ### Description Responds to GET requests to retrieve the current date. ### Method GET ### Endpoint /date ### Request Example ```bash $ curl -X GET localhost:55838/date ``` ### Response #### Success Response (200) - **date** (long) - The current date as a Unix timestamp. ### Response Example ```json 1526085903689 ``` ``` -------------------------------- ### Create Controller Command Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/cli/commands.adoc Generates a Controller class and an associated test. Use the --lang flag to specify the language and --force to overwrite existing files. ```bash $ mn create-controller Book ``` -------------------------------- ### WebSocket Chat Client Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/httpServer/websocket/websocketClient.adoc Defines a WebSocket client that implements AutoCloseable. Use @OnOpen to get the session and @OnMessage to receive server responses. The class must be abstract. ```java import io.micronaut.websocket.annotation.ClientWebSocket; import io.micronaut.websocket.WebSocketSession; import io.micronaut.websocket.annotation.OnOpen; import io.micronaut.websocket.annotation.OnMessage; import java.io.Closeable; @ClientWebSocket abstract class ChatClientWebSocket implements Closeable { @OnOpen abstract protected void onOpen(WebSocketSession session); @OnMessage abstract protected void onMessage(String message); @Override abstract public void close(); } ``` -------------------------------- ### CurrentDateEndpoint Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/management/buildingEndpoints/endpointAnnotation.adoc An example of a custom endpoint class that creates an endpoint accessible at the /date path. ```java package io.micronaut.docs.server.endpoint; import io.micronaut.management.endpoint.annotation.Endpoint; import io.micronaut.management.endpoint.annotation.Read; @Endpoint("date") class CurrentDateEndpoint { @Read public Date getDate() { return new Date(); } } ``` -------------------------------- ### Get Help for `create-app` Command Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/cli.adoc View detailed usage information and available options for a specific command using the `-h` or `--help` flag. ```bash mn> create-app -h Usage: mn create-app [-hivVx] [--list-features] [-b=BUILD-TOOL] [--jdk=] [-l=LANG] [-t=TEST] [-f=FEATURE[,FEATURE...]]... [NAME] Creates an application [NAME] The name of the application to create. -b, --build=BUILD-TOOL Which build tool to configure. Possible values: gradle, gradle_kotlin, maven. -f, --features=FEATURE[,FEATURE...] -h, --help Show this help message and exit. -i, --inplace Create a service using the current directory --jdk, --java-version= The JDK version the project should target -l, --lang=LANG Which language to use. Possible values: java, groovy, kotlin. --list-features Output the available features and their descriptions -t, --test=TEST Which test framework to use. Possible values: junit, spock, kotest. ``` -------------------------------- ### Basic Logback Configuration Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/logging/logback.adoc Set up a basic logback.xml file to define console appenders and root log level. ```xml %cyan(%d{HH:mm:ss.SSS}) %gray([%thread]) %highlight(%-5level) %magenta(%logger{36}) - %msg%n ``` -------------------------------- ### Create Bean Command Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/cli/commands.adoc Generates a Singleton bean class. Use the --lang flag to specify the language and --force to overwrite existing files. ```bash $ mn create-bean EmailService ``` -------------------------------- ### EntityIntrospectedAnnotationMapper Mapper Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/ioc/annotationMetadata.adoc An example AnnotationMapper that improves introspection capabilities for JPA entities by mapping annotations. ```java package io.micronaut.inject.beans.visitor; import io.micronaut.context.annotation.Bean; import io.micronaut.core.annotation.AnnotationMetadata; import io.micronaut.core.annotation.AnnotationValue; import io.micronaut.core.annotation.AnnotationMapper; import io.micronaut.core.annotation.AnnotationUtil; import io.micronaut.inject.annotation.NamedAnnotationMapper; import io.micronaut.inject.visitor.VisitorContext; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @Bean public class EntityIntrospectedAnnotationMapper implements NamedAnnotationMapper { @Override public String getName() { return "io.micronaut.persistence.jpa.annotation.Entity"; } @Override public Collection> map(AnnotationValue annotation, VisitorContext visitorContext) { return Collections.singleton(AnnotationValue.builder(AnnotationMetadata.INTRODUCTION).build()); } } ``` -------------------------------- ### Configure /etc/hosts for Faster Startup Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/appendix/problems.adoc On *nix systems, long application startup times can be caused by `java.net.InetAddress.getLocalHost()` calls. Edit your `/etc/hosts` file to include an entry for your hostname to resolve this. ```bash 127.0.0.1 localhost ::1 localhost ``` -------------------------------- ### Introduction Advice Annotation Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/aop/introductionAdvice.adoc Defines a custom annotation that powers introduction advice. The annotation is marked with api:aop.Introduction[] and api:context.annotation.Bean[] to ensure types annotated with it become beans. ```java package import io.micronaut.aop.Introduction; import io.micronaut.context.annotation.Bean; @Introduction @Bean public @interface Stub { } ``` -------------------------------- ### CurrentDateEndpoint POST Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/management/buildingEndpoints/endpointMethod.adoc Annotate a method with @Write to handle POST requests. This example demonstrates resetting a date. ```java package io.micronaut.docs.server.endpoint; import io.micronaut.http.MediaType; import io.micronaut.management.endpoint.annotation.Write; import jakarta.inject.Singleton; @Singleton public class CurrentDateEndpoint { @Write public String currentDate() { return "Current date reset"; } } ``` -------------------------------- ### Listen for Server Startup Events with ApplicationEventListener Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/httpServer/serverEvents.adoc Implement `ApplicationEventListener` to handle `ServerStartupEvent`. This approach is suitable for custom event handling logic. Be aware that performing significant work within this listener can increase application startup time. ```java import io.micronaut.context.event.ApplicationEventListener; ... @Singleton public class StartupListener implements ApplicationEventListener { @Override public void onApplicationEvent(ServerStartupEvent event) { // logic here ... } } ``` -------------------------------- ### MessageEndpoint DELETE Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/management/buildingEndpoints/endpointMethod.adoc Annotate a method with @Delete to handle DELETE requests. This example shows a simple delete operation. ```java package io.micronaut.docs.server.endpoint; import io.micronaut.http.MediaType; import io.micronaut.management.endpoint.annotation.Delete; import jakarta.inject.Singleton; @Singleton public class MessageEndpoint { @Delete public String message() { return "Message deleted"; } } ``` -------------------------------- ### Controller suspend function example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/languageSupport/kotlin/coroutines.adoc A controller action can be a suspend function. This example shows a basic suspend function in a controller. ```kotlin package import io.micronaut.http.annotation.Controller import io.micronaut.http.annotation.Get @Controller("/suspend") open class SuspendController { @Get("/suspend") suspend fun suspend() = "Hello suspend" } ``` -------------------------------- ### HTTP/2 Server Push Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/httpServer/http2Server.adoc Demonstrates how to use the `PushCapableHttpRequest` interface to trigger additional responses for resources like CSS files, improving client latency. Always check `isServerPushSupported()` before attempting to push. ```java import io.micronaut.http.HttpRequest import io.micronaut.http.server.types.PushCapableHttpRequest // ... controller method signature ... public void handleRequest(PushCapableHttpRequest request) { if (request.isServerPushSupported()) { request.serverPush(HttpRequest.GET("/static/style.css")) } } ``` -------------------------------- ### Driver Annotation Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/ioc/scopes/metaScopes.adoc This example shows a meta-annotation `@Driver` with a `@Singleton` scope. Classes annotated with `@Driver` will be treated as singletons. ```java package io.micronaut.docs.ioc.scopes; import io.micronaut.context.annotation.Requires; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Documented @Retention(RUNTIME) @Target({TYPE, ANNOTATION_TYPE}) @Requires(classes = Car.class) @Singleton public @interface Driver { } ``` -------------------------------- ### Build Raw Documentation Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/CONTRIBUTING.md Generate the raw documentation, excluding API and Configuration references. Links may not resolve in the browser. ```bash ./gradlew publishGuide ``` -------------------------------- ### Configuration Info Source Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/management/providedEndpoints/infoEndpoint.adoc Define custom properties for the Configuration Info Source in application.groovy. These properties will be exposed under the 'info' key in the /info endpoint response. ```groovy info.demo.string = "demo string" info.demo.number = 123 info.demo.map = [key: 'value', other_key: 123] ``` -------------------------------- ### Create Standard Server Application Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/cli/createProject.adoc Use `create-app` to generate a basic Micronaut server application. Supports options for language, test framework, build tool, and features. ```bash mn create-app my-project --features mongo-reactive,security-jwt --build maven ``` -------------------------------- ### Micronaut HTTP Controller Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/appendix/architecture/httpServerArch.adoc A basic Micronaut controller demonstrating how to handle HTTP requests and return responses. Includes necessary imports for a controller. ```java package example.micronaut.docs.server.intro; import io.micronaut.http.HttpRequest; import io.micronaut.http.annotation.Controller; import io.micronaut.http.annotation.Get; import io.micronaut.http.annotation.PathVariable; import io.micronaut.http.annotation.QueryValue; @Controller("/hello") public class HelloController { @Get public String index(@QueryValue(defaultValue = "World") String name) { return "Hello " + name; } @Get("/{name}") public String show(@PathVariable String name) { return "Hello " + name; } } ``` -------------------------------- ### DefaultScope Annotation Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/ioc/scopes/metaScopes.adoc This example demonstrates using `@DefaultScope` on a meta-annotation. It specifies `Singleton` as the default scope, which can be overridden if another scope is provided. ```java @Requires(classes = Car.class) @DefaultScope(Singleton.class) @Documented @Retention(RUNTIME) public @interface Driver { } ``` ```groovy @Requires(classes = Car.class) @DefaultScope(Singleton.class) @Documented @Retention(RUNTIME) @interface Driver { } ``` ```kotlin @Requires(classes = [Car::class]) @DefaultScope(Singleton::class) @Documented @Retention(RUNTIME) annotation class Driver ``` -------------------------------- ### Define Main Entry Point for Micronaut Application Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/appendix/architecture/httpServerArch.adoc This is the standard entry point for a Micronaut application. It initializes the Micronaut ApplicationContext, which in turn starts the HTTP server if configured. ```java public static void main(String[] args) { Micronaut.run(Application.class, args); } ``` -------------------------------- ### Server Sent Event Response Output Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/httpServer/sse.adoc Example JSON output for Server Sent Events, where each event contains a 'Headline' object. ```json data: {"title":"Micronaut 1.0 Released","description":"Come and get it"} data: {"title":"Micronaut 2.0 Released","description":"Come and get it"} ``` -------------------------------- ### Create Job Command Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/cli/commands.adoc Generates a Scheduled job class. Use the --lang flag to specify the language and --force to overwrite existing files. ```bash $ mn create-job UpdateFeeds --lang groovy ``` -------------------------------- ### Cron Scheduling Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/aop/scheduling.adoc Schedules a task using a cron expression. This example runs every Monday morning at 10:15 AM server time. ```java package import io.micronaut.scheduling.annotation.Scheduled; import jakarta.inject.Singleton; @Singleton public class ScheduledExample { @Scheduled(cron = "0 15 10 ? * MON") void cronTask() { // ... } } ``` -------------------------------- ### Generate Keystore with Multiple Aliases Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/http-netty/src/test/resources/kesytoreGenerateCommands.md Use these `keytool` commands to generate a JKS keystore file named `keystoreWithMultipleAlias.jks`. Each command adds a new key pair with a distinct alias (`alias1`, `alias2`, `alias3`), RSA algorithm, 2048-bit key size, and a 100-year validity period. Ensure you have `keytool` available in your PATH. ```shell keytool -genkeypair -v -keystore keystoreWithMultipleAlias.jks -storetype JKS -alias alias1 -keyalg RSA -keysize 2048 -validity 36500 -dname "CN=localhost1, OU=Micronaut1, O=My Company, L=City, ST=State, C=BR" -storepass password -keypass passwordAlias1 keytool -genkeypair -v -keystore keystoreWithMultipleAlias.jks -storetype JKS -alias alias2 -keyalg RSA -keysize 2048 -validity 36500 -dname "CN=localhost2, OU=Micronaut2, O=My Company, L=City, ST=State, C=BR" -storepass password -keypass passwordAlias2 keytool -genkeypair -v -keystore keystoreWithMultipleAlias.jks -storetype JKS -alias alias3 -keyalg RSA -keysize 2048 -validity 36500 -dname "CN=localhost3, OU=Micronaut3, O=My Company, L=City, ST=State, C=BR" -storepass password -keypass passwordAlias3 ``` -------------------------------- ### Reactive WebSocket Chat Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/httpServer/websocket/websocketServer.adoc An example of a reactive WebSocket handler that returns a Publisher for asynchronous message broadcasting. This avoids blocking the event loop. ```java package io.micronaut.docs.http.server.netty.websocket; import io.micronaut.websocket.annotation.OnMessage; import io.micronaut.websocket.annotation.ServerWebSocket; import io.micronaut.websocket.WebSocketBroadcaster; import io.micronaut.websocket.WebSocketSession; import jakarta.inject.Inject; import org.reactivestreams.Publisher; @ServerWebSocket("/ws/reactive-chat/{topic}/{username}") public class ReactivePojoChatServerWebSocket { @Inject protected WebSocketBroadcaster broadcaster; @OnMessage public Publisher onMessage(String message, String topic, String username, WebSocketSession session) { return broadcaster.broadcast("[" + topic + "] " + username + ": " + message); } } ``` -------------------------------- ### Testing Introduction Advice Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/aop/introductionAdvice.adoc A test class that demonstrates the behavior of StubIntroduction. It verifies that the abstract methods annotated with @Stub are correctly implemented by the introduction advice. ```java package import io.micronaut.aop.MethodInvocationContext; import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import jakarta.inject.Inject; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; @MicronautTest class IntroductionSpec { @Inject StubExample stubExample; @Test void testStubIntroduction() { assertEquals("Hello World", stubExample.sayHello()); } @Test void testStubIntroductionWithNoValue() { // This test assumes a default behavior or a different @Stub usage not shown in the example // For the provided StubExample, sayHello() is annotated with @Stub("Hello World"), so this test might need adjustment // If there was another method or class without @Stub value, it might return null. // For demonstration, let's assume a scenario where null is expected if no value is provided or convertible. // This part of the test might be conceptual based on the description's mention of returning null. // A more accurate test would require a different setup or class annotated with @Stub without a value. // For now, we'll assert the expected behavior based on the provided StubExample. // If the intention was to test a method that *should* return null, that method/class is missing. // Given the current StubExample, sayHello() returns "Hello World". // To test the null return, we'd need a different scenario. // For the sake of completeness based on the description's mention of null: // assertNull(someOtherMethodOrScenarioThatReturnsNull()); } // Example of how to potentially test the 'proceed' method if needed, though not directly applicable to @Stub // @Test // void testProceedMethod() { // // This would require a scenario where an interceptor calls proceed() // // and another interceptor handles it, or an UnsupportedOperationException is thrown. // } } ``` -------------------------------- ### Configuration Info Source JSON Response Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/management/providedEndpoints/infoEndpoint.adoc Example JSON output from the info endpoint when using the Configuration Info Source with the properties defined above. ```json { "demo": { "string": "demo string", "number": 123, "map": { "key": "value", "other_key": 123 } } } ``` -------------------------------- ### Typed Request Argument Binder Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/httpServer/customArgumentBinding.adoc Implement a TypedRequestArgumentBinder to bind arguments based on their type. This example deserializes JSON from a cookie into a ShoppingCart object. ```java package io.micronaut.docs.http.server.bind.type; import io.micronaut.core.bind.ArgumentBinder; import io.micronaut.core.bind.ArgumentBinder.BindingResult; import io.micronaut.core.bind.annotation.Bindable; import io.micronaut.core.convert.ConversionService; import io.micronaut.http.HttpRequest; import io.micronaut.http.cookie.Cookie; import io.micronaut.http.bind.binders.TypedRequestArgumentBinder; import jakarta.inject.Singleton; @Singleton public class ShoppingCartRequestArgumentBinder implements TypedRequestArgumentBinder { private final ConversionService conversionService; public ShoppingCartRequestArgumentBinder(ConversionService conversionService) { this.conversionService = conversionService; } @Override public BindingResult bind(Argument argument, HttpRequest source) { Cookie cookie = source.getCookies().get("shopping-cart"); if (cookie != null) { return bindable(conversionService.convertRequired(cookie.getValue(), argument.asType())); } return BindingResult.UNSATISFIED; } @Override public Argument argumentType() { return Argument.of(ShoppingCart.class); } } ``` -------------------------------- ### ConsumesController Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/httpServer/consumesAnnotation.adoc This example demonstrates how to use the @Consumes annotation to specify supported media types for a controller action. By default, actions consume 'application/json'. ```java package import io.micronaut.http.MediaType; import io.micronaut.http.annotation.Controller; import io.micronaut.http.annotation.Get; import io.micronaut.http.annotation.Consumes; @Controller("/consumes") public class ConsumesController { @Get @Consumes(MediaType.TEXT_PLAIN) public String index() { return "Consuming text/plain"; } @Get @Consumes("application/xml") public String xml() { return "Consuming application/xml"; } @Get // By default consumes application/json public String defaultJson() { return "Consuming application/json"; } } ``` -------------------------------- ### Create Native Image with Maven Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/languageSupport/graal/graalServices.adoc Use the `native-image` packaging format with Maven to create a native executable. ```bash $ ./mvnw package -Dpackaging=native-image ``` -------------------------------- ### Get Specific Metric Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/management/providedEndpoints/metricsEndpoint.adoc Send a GET request to /metrics/[name] to retrieve the value of a specific metric. Replace [name] with the desired metric name. ```APIDOC ## GET /metrics/{name} ### Description Retrieves the value of a specific application metric. ### Method GET ### Endpoint /metrics/{name} ### Parameters #### Path Parameters - **name** (string) - Required - The name of the metric to retrieve (e.g., `jvm.memory.used`). ### Response #### Success Response (200) - **metric_value** (number or object) - The value of the requested metric. The type can vary depending on the metric. ``` -------------------------------- ### Pet Controller Implementation Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/httpClient/clientAnnotation.adoc A server-side implementation of the PetOperations interface, demonstrating how to handle incoming HTTP requests for Pet management. ```java package io.micronaut.docs.annotation; import io.micronaut.http.annotation.Controller; import jakarta.validation.constraints.NotBlank; @Controller("/pets") public class PetController implements PetOperations { @Override public Pet save(@NotBlank String name) { Pet pet = new Pet(); pet.setName(name); return pet; } } ``` -------------------------------- ### Example HttpServerFilter Implementation Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/httpServer/filters/httpServerFilter/httpServerFilterExample.adoc An example implementation of the HttpServerFilter interface. It uses the @Filter annotation to define URI patterns and injects a TraceService to perform tracing operations in a non-blocking way. ```java package io.micronaut.docs.server.filters; import io.micronaut.http.HttpRequest; import io.micronaut.http.HttpResponse; import io.micronaut.http.annotation.Filter; import io.micronaut.http.filter.HttpServerFilter; import io.micronaut.http.filter.ServerFilterChain; import io.micronaut.inject.qualifiers.Replaces; import reactor.core.publisher.Mono; import javax.inject.Inject; @Filter("/trace/**") public class TraceFilter implements HttpServerFilter { private final TraceService traceService; public TraceFilter(@Replaces TraceService traceService) { this.traceService = traceService; } @Override public Mono> doFilter(HttpRequest request, ServerFilterChain chain) { return traceService.trace(request.getPath()) .switchMap(traceData -> chain.proceed(request)) .doOnNext(httpResponse -> httpResponse.getHeaders().add("X-Trace-Enabled", "true")); } } ``` -------------------------------- ### Fixed Delay Scheduling Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/aop/scheduling.adoc Schedules a task to run after a specified delay following the termination of the previous execution. This example runs five minutes after the previous task finishes. ```java package import io.micronaut.scheduling.annotation.Scheduled; import jakarta.inject.Singleton; @Singleton public class ScheduledExample { @Scheduled(fixedDelay = "5m") void fixedDelay() { // ... } } ``` -------------------------------- ### Publisher> Controller Example Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/httpServer/form/binding.adoc This example demonstrates handling form data as a publisher of byte arrays, suitable for streaming individual fields. It behaves similarly to Publisher. ```java snippet::io.micronaut.docs.server.form.FormController[tags="imports,class,PublisherPublisherBytes,endclass", title="Publisher> controller example"] ``` -------------------------------- ### Create Application with Custom Default Package Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/cli.adoc Specify a custom default package by prefixing the application name with the desired package structure. ```bash $ mn create-app my-demo-app ``` ```bash $ mn create-app example.my-demo-app ``` -------------------------------- ### Using retrieve for HTTP GET (Blocking) Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/httpClient/lowLevelHttpClient/clientBasics.adoc Execute an HTTP GET request and retrieve the response body as a String using the toBlocking().retrieve() method. This is for illustration; prefer non-blocking operations in production. ```java httpClient.toBlocking().retrieve("/hello") ``` -------------------------------- ### Get Specific Logger Levels Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/management/providedEndpoints/loggersEndpoint.adoc To retrieve the log levels for a particular logger, include the logger's name in the GET request to the /loggers endpoint. If the logger does not exist, it will be created with an unspecified log level. ```bash $ curl http://localhost:8080/loggers/io.micronaut.http { "configuredLevel": "NOT_SPECIFIED", "effectiveLevel": "INFO" } ``` -------------------------------- ### List Available CLI Features Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/cli/features.adoc View the supported features for a specific create command by using the `--list-features` flag. The output may differ between commands like `create-app` and `create-function-app`. ```bash $ mn create-app --list-features # Output will be supported features for the create-app command ``` ```bash $ mn create-function-app --list-features # Output will be supported features for the create-function-app command, different from above. ``` -------------------------------- ### Creating Environment with Custom Environments Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/appendix/breaks.adoc Create a custom Environment instance with a specific list of environments and then create an ApplicationContext using this custom environment. ```java Environment myEnv = Environment.create(new ApplicationContextConfiguration() { @Override public List getEnvironments() { return List.of("foobar"); } }); ApplicationContext customApplicationContext = ApplicationContext.create(myEnv); ``` -------------------------------- ### Log Output Example (Multiple Packets) Source: https://github.com/micronaut-projects/micronaut-core/blob/5.1.x/src/main/docs/guide/httpServer/byteBody/byteBodyExample.adoc This example illustrates the log output when the request body is received in multiple packets. Due to asynchronous processing, the log statements from the filter may be interleaved with controller logs. ```log 16:29:30.562 [default-nioEventLoopGroup-1-3] INFO i.m.docs.server.body.BodyLogFilter - Received body: ... 16:29:30.584 [default-nioEventLoopGroup-1-3] INFO i.m.docs.server.body.BodyLogFilter - Received body: ... 16:29:30.642 [default-nioEventLoopGroup-1-3] INFO i.m.docs.server.body.BodyLogFilter - Received body: ... 16:29:30.773 [default-nioEventLoopGroup-1-3] INFO i.m.d.server.body.BodyLogController - Creating person Person[firstName=..., lastName=...] 16:29:30.708 [default-nioEventLoopGroup-1-3] INFO i.m.docs.server.body.BodyLogFilter - Received body: ... ```