### Configuring Mock Server Setup with a Setup Class Source: https://quarkus.io/guides/kubernetes-client This example shows how to use the `setup` attribute of `@WithKubernetesTestServer` to provide a custom class that configures the `KubernetesServer` instance. The `Setup` class implements `Consumer` to define the server's behavior. ```java @WithKubernetesTestServer(setup = MyTest.Setup.class) @QuarkusTest public class MyTest { public static class Setup implements Consumer { @Override public void accept(KubernetesServer server) { server.expect().get().withPath("/api/v1/namespaces/test/pods") .andReturn(200, new PodList()).always(); } } // tests } ``` -------------------------------- ### Start PostgreSQL Server with Docker Source: https://quarkus.io/guides/security-getting-started-tutorial Run a PostgreSQL server in a Docker container. This is required for the security-getting-started example. ```bash docker run --rm=true --name security-getting-started -e POSTGRES_USER=quarkus \ -e POSTGRES_PASSWORD=quarkus -e POSTGRES_DB=quarkus \ -p 5432:5432 docker.io/library/postgres:18 ``` -------------------------------- ### Dockerfile with UBI Minimal and Installed Libraries Source: https://quarkus.io/guides/quarkus-runtime-base-image This Dockerfile extends the basic setup by installing necessary libraries like freetype and fontconfig using `microdnf`. It also includes copying shared objects for dynamic loading at runtime. ```dockerfile FROM registry.access.redhat.com/ubi9/ubi-minimal:9.6 RUN microdnf install -y freetype fontconfig \ && microdnf clean all WORKDIR /work/ RUN chown 1001 /work \ && chmod "g+rwX" /work \ && chown 1001:root /work # Shared objects to be dynamically loaded at runtime as needed COPY --chown=1001:root target/*.so /work/ COPY --chown=1001:root --chmod=0755 target/*-runner /work/application EXPOSE 8080 USER 1001 ENTRYPOINT ["./application", "-Dquarkus.http.host=0.0.0.0"] ``` -------------------------------- ### Example Cache Metrics (Prometheus) Source: https://quarkus.io/guides/cache View example metrics for cache size, puts, gets (hits/misses), and evictions, typically exposed for Prometheus. ```prometheus # HELP cache_size The number of entries in this cache. This may be an approximation, depending on the type of cache. # TYPE cache_size gauge cache_size{cache="foo",} 8.0 # HELP cache_puts_total The number of entries added to the cache # TYPE cache_puts_total counter cache_puts_total{cache="foo",} 12.0 # HELP cache_gets_total The number of times cache lookup methods have returned a cached value. # TYPE cache_gets_total counter cache_gets_total{cache="foo",result="hit",} 53.0 cache_gets_total{cache="foo",result="miss",} 12.0 # HELP cache_evictions_total cache evictions # TYPE cache_evictions_total counter cache_evictions_total{cache="foo",} 4.0 # HELP cache_eviction_weight_total The sum of weights of evicted entries. This total does not include manual invalidations. # TYPE cache_eviction_weight_total counter cache_eviction_weight_total{cache="foo",} 540.0 ``` -------------------------------- ### Keycloak Dev Services Output Example Source: https://quarkus.io/guides/security-openid-connect-dev-services This output indicates that Dev Services for Keycloak is starting and waiting for the Keycloak instance to become available. ```log KeyCloak Dev Services Starting: 2021-11-02 17:14:24,864 INFO [org.tes.con.wai.str.HttpWaitStrategy] (build-10) /unruffled_agnesi: Waiting for 60 seconds for URL: http://localhost:32781 (where port 32781 maps to container port 8080) 2021-11-02 17:14:44,170 INFO [io.qua.oid.dep.dev.key.KeycloakDevServicesProcessor] (build-10) Dev Services for Keycloak started. ``` -------------------------------- ### Serve Static Resources from Local Directory Source: https://quarkus.io/guides/http-reference Install a Vert.x route to serve static resources from a local directory. This example configures serving from the 'static/' directory under the '/static/' endpoint. ```java package org.acme; import io.quarkus.runtime.StartupEvent; import io.vertx.ext.web.Router; import io.vertx.ext.web.handler.StaticHandler; import jakarta.enterprise.event.Observes; public class StaticResources { void installRoute(@Observes StartupEvent startupEvent, Router router) { router.route() .path("/static/*") .handler(StaticHandler.create("static/")); } } ``` -------------------------------- ### Configure Multiple Reactive Datasources and Persistence Units Source: https://quarkus.io/guides/hibernate-reactive Example `application.properties` demonstrating the setup of two distinct persistence units, 'users' and 'inventory', each configured with a reactive PostgreSQL datasource. This allows for managing separate data contexts within a single application. ```properties quarkus.datasource."users".reactive.url=vertx-reactive:postgresql://localhost/users __**(1)** quarkus.datasource."users".db-kind=postgresql %prod.quarkus.datasource."users".username=hibernate_orm_test %prod.quarkus.datasource."users".password=hibernate_orm_test quarkus.datasource."inventory".reactive.url=vertx-reactive:postgresql://localhost/inventory __**(2)** quarkus.datasource."inventory".db-kind=postgresql %prod.quarkus.datasource."inventory".username=hibernate_orm_test %prod.quarkus.datasource."inventory".password=hibernate_orm_test quarkus.hibernate-orm."users".datasource=users __**(3)** quarkus.hibernate-orm."users".packages=io.quarkus.hibernate.reactive.multiplepersistenceunits.model.config.user quarkus.hibernate-orm."inventory".datasource=inventory __**(4)** quarkus.hibernate-orm."inventory".packages=io.quarkus.hibernate.orm.multiplepersistenceunits.model.config.inventory ``` -------------------------------- ### Clone Quarkus Quickstarts Repository Source: https://quarkus.io/guides/getting-started-dev-services Clone the Quarkus quickstarts repository to access the completed example for this guide. ```bash git clone https://github.com/quarkusio/quarkus-quickstarts.git ``` -------------------------------- ### Example Bean with Security Annotations Source: https://quarkus.io/guides/all-config Illustrates a Java bean with security annotations. When `quarkus.security.deny-unannotated-members` is true, `methodB` would be denied access by default. ```java @ApplicationScoped public class A { @RolesAllowed("admin") public void methodA() { ... } public void methodB() { ... } } ``` -------------------------------- ### Build-time Initialization Example Source: https://quarkus.io/guides/native-reference This resource demonstrates build-time initialization by capturing the system time at build. The 'firstAccess' variable will hold the same value across application restarts. ```java package org.acme; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; @Path("/timestamp") public class TimestampResource { static long firstAccess = System.currentTimeMillis(); @GET @Produces(MediaType.TEXT_PLAIN) public String timestamp() { return "First access " + firstAccess; } } ``` -------------------------------- ### Filter Quarkus Plugin List Source: https://quarkus.io/guides/cli-tooling Filters the list of installable plugins by type using -t or by name using -s with a search pattern. This example shows how to list installable plugins starting with 'k'. ```bash quarkus plugin list --installable -s "k*" ``` -------------------------------- ### Example Custom Startup Script for Jib Source: https://quarkus.io/guides/container-image An example of a custom startup script that can be referenced as the container entry point for Jib builds. It demonstrates setting JVM arguments and launching the Quarkus application. ```bash java \ -Djavax.net.ssl.trustStore=/deployments/truststore \ -Djavax.net.ssl.trustStorePassword="$TRUST_STORE_PASSWORD" \ -jar quarkus-run.jar ``` -------------------------------- ### Conditional GET Request Example Source: https://quarkus.io/guides/rest Example of a GET request with the `If-Modified-Since` header to check if the resource has been modified. ```http GET /conditional HTTP/1.1 Host: localhost:8080 If-Modified-Since: Wed, 09 Dec 2020 16:10:19 GMT ``` -------------------------------- ### Build and Install Greeting Extension Source: https://quarkus.io/guides/building-my-first-extension Command to clean, build, and install the Greeting extension into the local Maven repository. This step is crucial for making the extension available for use in other projects. ```bash $ mvn clean install ``` -------------------------------- ### Build and Install Docs Module Specifically Source: https://quarkus.io/guides/doc-contribute-docs-howto Execute this command to specifically build and install the `docs` module. This is recommended for updating generated configuration documentation or viewing rendered results after making changes. ```bash ./mvnw -f docs clean install ``` -------------------------------- ### Configure Apicurio Registry Dev Services Service Name Source: https://quarkus.io/guides/all-config Set the service name label for shared Apicurio Registry Dev Services containers. This is used to find existing shared instances before starting a new one. ```properties quarkus.apicurio-registry.devservices.service-name=apicurio-registry ``` -------------------------------- ### Property Accessor Examples Source: https://quarkus.io/guides/qute-reference Demonstrates different ways to access properties using dot notation, bracket notation, and namespaces. ```qute {name} ``` ```qute {item.name} ``` ```qute {item['name']} ``` ```qute {global:colors} ``` -------------------------------- ### Successful GET Request Response Source: https://quarkus.io/guides/rest Example of a successful 200 OK response for a GET request to the conditional endpoint, including ETag and Last-Modified headers. ```http HTTP/1.1 200 OK Content-Type: text/plain;charset=UTF-8 ETag: "v1" Last-Modified: Wed, 09 Dec 2020 16:10:19 GMT Content-Length: 13 Some resource ``` -------------------------------- ### Produce ServiceStartBuildItem for Startup Event Ordering Source: https://quarkus.io/guides/writing-extensions Produce a `ServiceStartBuildItem` to ensure that runtime code for services is executed before a `StartupEvent` is sent. This is crucial for extensions that rely on other services being started. ```java // TestProcessor#startRuntimeService @BuildStep @Record(RUNTIME_INIT) ServiceStartBuildItem startRuntimeService(TestRecorder recorder, ShutdownContextBuildItem shutdownContextBuildItem, RuntimeServiceBuildItem serviceBuildItem) throws IOException { ... return new ServiceStartBuildItem("RuntimeXmlConfigService"); __**(1)** } ``` -------------------------------- ### Localized File Example - msg_de.properties Source: https://quarkus.io/guides/qute-reference Example of a localized message bundle file in German. Keys map to message bundle interface methods, and values are templates. Lines starting with '#' are comments. ```properties # This comment is ignored hello_name=Hallo {name}! __**(1)** __**(2)** ``` -------------------------------- ### Comprehensive YAML configuration with profiles Source: https://quarkus.io/guides/config-yaml This example includes datasource, Hibernate ORM, OIDC, and application-specific frontend configurations. It also demonstrates profile-specific settings using the `"%test"` prefix. ```yaml quarkus: datasource: jdbc: url: jdbc:postgresql://localhost:5432/quarkus_test hibernate-orm: database: generation: drop-and-create oidc: enabled: true auth-server-url: http://localhost:8180/auth/realms/quarkus client-id: app app: frontend: oidc-realm: quarkus oidc-app: app oidc-server: http://localhost:8180/auth # With profiles "%test": quarkus: oidc: enabled: false security: users: file: enabled: true realm-name: quarkus plain-text: true ``` -------------------------------- ### GET /people/1 - JSON Response Source: https://quarkus.io/guides/rest-data-panache Example of a JSON response for retrieving a single person by ID. ```json { "id": 1, "name": "John Johnson", "birth": "1988-01-10" } ``` -------------------------------- ### Start Keycloak Server with Docker Source: https://quarkus.io/guides/security-keycloak-authorization Use this Docker command to start a Keycloak server instance. Ensure you have a Keycloak keystore file configured. ```bash docker run --name keycloak \ -e KC_BOOTSTRAP_ADMIN_USERNAME=admin \ -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \ -p 8543:8443 \ -v "$(pwd)"/config/keycloak-keystore.jks:/etc/keycloak-keystore.jks \ quay.io/keycloak/keycloak:26.6.2 \ start --hostname-strict=false --https-key-store-file=/etc/keycloak-keystore.jks ``` -------------------------------- ### Infinispan Server Configuration Example Source: https://quarkus.io/guides/infinispan-dev-services An example of an Infinispan server configuration file (`server-config-override.xml`) that defines a local cache with Protostream encoding. This cache will be present on the server container when Dev Services starts. ```xml ``` -------------------------------- ### Run Kafka Avro Schema Quickstart Source: https://quarkus.io/guides/kafka-schema-registry-avro Command to run the Kafka Avro Schema quickstart application with specified Kafka bootstrap servers. ```bash ./target/kafka-avro-schema-quickstart-1.0.0-SNAPSHOT-runner -Dkafka.bootstrap.servers=localhost:9092 ``` -------------------------------- ### Dynamic Client Registration with TenantConfigResolver Source: https://quarkus.io/guides/security-openid-connect-client-registration Implement TenantConfigResolver to dynamically register new clients on demand. This example shows how to create client metadata, register it using OidcClientRegistration, and transform the registration response into an OidcTenantConfig. ```java package io.quarkus.it.keycloak; import java.net.URI; import java.util.List; import java.util.Optional; import jakarta.inject.Inject; import jakarta.inject.Singleton; import org.eclipse.microprofile.config.inject.ConfigProperty; import io.quarkus.oidc.OidcRequestContext; import io.quarkus.oidc.OidcTenantConfig; import io.quarkus.oidc.OidcTenantConfig.ApplicationType; import io.quarkus.oidc.TenantConfigResolver; import io.quarkus.oidc.client.registration.ClientMetadata; import io.quarkus.oidc.client.registration.OidcClientRegistration; import io.smallrye.mutiny.Uni; import io.vertx.ext.web.RoutingContext; @Singleton public class CustomTenantConfigResolver implements TenantConfigResolver { @Inject OidcClientRegistration clientReg; @Inject @ConfigProperty(name = "quarkus.oidc.auth-server-url") String authServerUrl; @Override public Uni resolve(RoutingContext routingContext, OidcRequestContext requestContext) { if (routingContext.request().path().endsWith("/protected/oidc-client-reg-existing-config")) { // New client registration done dynamically at the request time using the configured client registration ClientMetadata metadata = createMetadata("http://localhost:8081/protected/dynamic-tenant", "Dynamic Tenant Client"); return clientReg.registerClient(metadata).onItem().transform(r -> createTenantConfig("registered-client-dynamically", r)); } return null; } // Create metadata of registered clients to OidcTenantConfig private OidcTenantConfig createTenantConfig(String tenantId, ClientMetadata metadata) { String redirectPath = URI.create(metadata.getRedirectUris().get(0)).getPath(); OidcTenantConfig oidcConfig = OidcTenantConfig .authServerUrl(authServerUrl) .tenantId(tenantId) .applicationType(ApplicationType.WEB_APP) .clientName(metadata.getClientName()) .clientId(metadata.getClientId()) .credentials(metadata.getClientSecret()) .authentication().redirectPath(redirectPath).end() .build(); return oidcConfig; } protected static ClientMetadata createMetadata(String redirectUri, String clientName) { return ClientMetadata.builder() .setRedirectUri(redirectUri) .setClientName(clientName) .build(); } } ``` -------------------------------- ### GET /people/1 - HAL+JSON Response Source: https://quarkus.io/guides/rest-data-panache Example of a HAL+JSON response for retrieving a single person by ID, including links. ```json { "id": 1, "name": "John Johnson", "birth": "1988-01-10", "_links": { "self": { "href": "http://example.com/people/1" }, "remove": { "href": "http://example.com/people/1" }, "update": { "href": "http://example.com/people/1" }, "add": { "href": "http://example.com/people" }, "list": { "href": "http://example.com/people" } } } ``` -------------------------------- ### Basic YAML configuration example Source: https://quarkus.io/guides/config-yaml This example shows basic YAML configuration for datasource and REST client properties. YAML supports comments. ```yaml # YAML supports comments quarkus: datasource: db-kind: postgresql jdbc: url: jdbc:postgresql://localhost:5432/some-database # REST Client configuration property quarkus: rest-client: org.acme.rest.client.ExtensionsService: url: https://stage.code.quarkus.io/api ``` -------------------------------- ### Example application.properties for Logging Source: https://quarkus.io/guides/writing-extensions Provides an example of how to configure logging properties in `application.properties`. Properties not defined here will use default values specified in the configuration interface. ```properties quarkus.log.file.enabled=true quarkus.log.file.level=DEBUG quarkus.log.file.path=/tmp/debug.log ``` -------------------------------- ### Display help for Quarkus create commands Source: https://quarkus.io/guides/cli-tooling Use the `--help` option to view available options for creating Quarkus projects via the CLI. ```bash quarkus create app --help ``` ```bash quarkus create cli --help ``` -------------------------------- ### Run Redis Server with Docker Source: https://quarkus.io/guides/redis Starts a Redis server on port 6379 for testing or development purposes. Ensure Docker is installed and running. ```bash docker run --ulimit memlock=-1:-1 -it --rm=true --memory-swappiness=0 --name redis_quarkus_test -p 6379:6379 docker.io/library/redis:7 ``` -------------------------------- ### Enable Section Numbering and Create Project Header Source: https://quarkus.io/guides/doc-create-tutorial Enable section numbering and define a second-level heading for the first step of the tutorial. This sets up the structure for subsequent steps. ```asciidoc :sectnums: :sectnumlevels: 3 == Create a new project ``` -------------------------------- ### Swagger UI Availability Log Message Source: https://quarkus.io/guides/openapi-swaggerui Example log message indicating the URL where Swagger UI is available after starting the Quarkus application. ```log 00:00:00,000 INFO [io.qua.swa.run.SwaggerUiServletExtension] Swagger UI available at /q/swagger-ui ``` -------------------------------- ### Configure Infinispan Distributed Cache with Indexing Source: https://quarkus.io/guides/infinispan-client-reference Example of configuring a distributed cache with indexing enabled. This setup is suitable for performing queries on cached data. ```xml book_sample.Book ``` -------------------------------- ### GET /people?page=0&size=2 - HAL+JSON Response Source: https://quarkus.io/guides/rest-data-panache Example of a HAL+JSON response for retrieving a collection of people with pagination, including embedded resources and links. ```json { "_embedded": [ { "id": 1, "name": "John Johnson", "birth": "1988-01-10", "_links": { "self": { "href": "http://example.com/people/1" }, "remove": { "href": "http://example.com/people/1" }, "update": { "href": "http://example.com/people/1" }, "add": { "href": "http://example.com/people" }, "list": { "href": "http://example.com/people" } } }, { "id": 2, "name": "Peter Peterson", "birth": "1986-11-20", "_links": { "self": { "href": "http://example.com/people/2" }, "remove": { "href": "http://example.com/people/2" }, "update": { "href": "http://example.com/people/2" }, "add": { "href": "http://example.com/people" }, "list": { "href": "http://example.com/people" } } } ], "_links": { "add": { "href": "http://example.com/people" }, "list": { "href": "http://example.com/people" }, "first": { "href": "http://example.com/people?page=0&size=2" }, "last": { "href": "http://example.com/people?page=2&size=2" }, "next": { "href": "http://example.com/people?page=1&size=2" } } } ``` -------------------------------- ### Initialize Keycloak with Multiple Realm Files Source: https://quarkus.io/guides/security-openid-connect-dev-services Provide a comma-separated list of realm configuration files to initialize Keycloak Dev Services with multiple realms. ```properties quarkus.keycloak.devservices.realm-path=quarkus-realm1.json,quarkus-realm2.json ``` -------------------------------- ### MQTT Broker Configuration File Source: https://quarkus.io/guides/compose-dev-services Example configuration file for an MQTT broker, specifying persistence, logging, and listener settings. ```properties persistence true persistence_location /mosquitto/data/ log_dest file /mosquitto/log/mosquitto.log listener 1883 allow_anonymous false password_file /mosquitto/config/password.txt ``` -------------------------------- ### Example Dev Service Log Entry Source: https://quarkus.io/guides/observability-devservices-lgtm This log entry shows the configuration details for the started Dev Service, including endpoints for Grafana and OpenTelemetry. ```java [io.qu.ob.de.ObservabilityDevServiceProcessor] (build-35) Dev Service Lgtm started, config: {grafana.endpoint=http://localhost:42797, quarkus.otel.exporter.otlp.endpoint=http://localhost:34711, otel-collector.url=localhost:34711, quarkus.micrometer.export.otlp.url=http://localhost:34711/v1/metrics, quarkus.otel.exporter.otlp.protocol=http/protobuf} ``` -------------------------------- ### Configure OIDC Tenant Source: https://quarkus.io/guides/security-oidc-expanded-configuration Example of configuring specific requirements for an OIDC tenant named 'tenant-1'. This setup disables discovery and specifies the authentication server URL. ```properties quarkus.oidc.tenant-1.auth-server-url=${tenant-1-auth-server-url} quarkus.oidc.tenant-1.discovery-enabled=false ``` -------------------------------- ### Print Class Initialization Details Source: https://quarkus.io/guides/native-reference Use this build argument to get more detailed information about class initializations during the native image build. This can help in diagnosing complex initialization order problems. ```bash -Dquarkus.native.additional-build-args="-H:+PrintClassInitialization" ``` -------------------------------- ### Flyway SQL for SCHEMA Multitenancy Source: https://quarkus.io/guides/hibernate-orm Example Flyway SQL script to create tables and sequences for multiple tenants ('base' and 'mycompany') in a SCHEMA multitenancy setup. ```sql CREATE SEQUENCE base.fruit_seq INCREMENT BY 50; -- 50 is quarkus default CREATE TABLE base.fruit ( id INT, name VARCHAR(40) ); INSERT INTO base.fruit(id, name) VALUES (1, 'Cherry'); INSERT INTO base.fruit(id, name) VALUES (2, 'Apple'); INSERT INTO base.fruit(id, name) VALUES (3, 'Banana'); ALTER SEQUENCE base.fruit_seq RESTART WITH 4; CREATE SEQUENCE mycompany.fruit_seq INCREMENT BY 50; -- 50 is quarkus default CREATE TABLE mycompany.fruit ( id INT, name VARCHAR(40) ); INSERT INTO mycompany.fruit(id, name) VALUES (1, 'Avocado'); INSERT INTO mycompany.fruit(id, name) VALUES (2, 'Apricots'); INSERT INTO mycompany.fruit(id, name) VALUES (3, 'Blackberries'); ALTER SEQUENCE mycompany.fruit_seq RESTART WITH 4; ``` -------------------------------- ### Run Quarkus Application in Dev Mode Source: https://quarkus.io/guides/building-my-first-extension Start the Quarkus application in development mode. Observe the 'Installed features' log to confirm that your 'greeting-extension' is recognized and loaded. ```bash $ mvn quarkus:dev [INFO] Scanning for projects... [INFO] [INFO] -----------------------< org.acme:greeting-app >------------------------ [INFO] Building greeting-app 1.0.0-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- maven-compiler-plugin:3.15.0:compile (default-compile) @ greeting-app --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] --- quarkus-maven-plugin:3.37.0:dev (default-cli) @ greeting-app --- Listening for transport dt_socket at address: 5005 __ ____ __ _____ ___ __ ____ ______ --/ __ \/ / / / _ | / _ \/ //_/ / / / __/ -/ /_/ / /_/ / __ |/ , _/ ,< / /_/ /\ \ --\___\_\____/_/ |_/_/|_/_/|_|\____/___/ 2022-11-20 04:25:36,885 INFO [io.quarkus] (Quarkus Main Thread) greeting-app 1.0.0-SNAPSHOT on JVM (powered by Quarkus 3.37.0) started in 4.591s. Listening on: http://localhost:8080 2022-11-20 04:25:36,911 INFO [io.quarkus] (Quarkus Main Thread) Profile dev activated. Live Coding activated. 2022-11-20 04:25:36,913 INFO [io.quarkus] (Quarkus Main Thread) Installed features: [cdi, greeting-extension, resteasy-reactive, smallrye-context-propagation, vertx] ``` -------------------------------- ### Create Quarkus Project with CLI Source: https://quarkus.io/guides/maven-tooling Use this command to scaffold a new Maven project with Quarkus. Refer to the Quarkus CLI guide for installation and usage details. ```bash quarkus create app my-groupId:my-artifactId ``` -------------------------------- ### List Installable Extensions with Filtering Source: https://quarkus.io/guides/cli-tooling Lists installable extensions for the current Quarkus project, filtered by 'jdbc' and using the concise format. ```bash quarkus ext list --concise -i -s jdbc ``` -------------------------------- ### Example Kafka Dev Services Topic Configuration Source: https://quarkus.io/guides/kafka-dev-services Create Kafka topics 'test' with 3 partitions and 'messages' with 2 partitions using Dev Services. ```properties quarkus.kafka.devservices.topic-partitions.test=3 quarkus.kafka.devservices.topic-partitions.messages=2 ``` -------------------------------- ### Custom Test Resource Lifecycle Manager Source: https://quarkus.io/guides/getting-started-testing Implement QuarkusTestResourceLifecycleManager to manage external services for tests. This example shows how to start and stop WireMock, and inject it into test fields. ```java public class MyWireMockResource implements QuarkusTestResourceLifecycleManager { WireMockServer wireMockServer; @Override public Map start() { wireMockServer = new WireMockServer(8090); wireMockServer.start(); // create some stubs return Map.of("some.service.url", "localhost:" + wireMockServer.port()); } @Override public synchronized void stop() { if (wireMockServer != null) { wireMockServer.stop(); wireMockServer = null; } } @Override public void inject(TestInjector testInjector) { testInjector.injectIntoFields(wireMockServer, new TestInjector.AnnotatedAndMatchesType(InjectWireMock.class, WireMockServer.class)); } } ``` -------------------------------- ### Example Prerequisites Section with Callouts Source: https://quarkus.io/guides/doc-contribute-docs-howto Demonstrates the basic structure of a prerequisites section in AsciiDoc, including optional callouts for explanations. ```asciidoc .Prerequisites __**(1)** :prerequisites-time: 30 minutes __**(2)** include::{includes}/prerequisites.adoc[] __**(3)** * __**(4)** ``` -------------------------------- ### Quarkus JUnit Test Example Source: https://quarkus.io/guides/getting-started A basic JUnit test class for a Quarkus application. It uses `@QuarkusTest` to start the application and RestAssured to test the '/hello' and '/hello/greeting/{name}' endpoints. ```java package org.acme; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.Test; import java.util.UUID; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.is; @QuarkusTest class GreetingResourceTest { @Test void testHelloEndpoint() { given() .when().get("/hello") .then() .statusCode(200) .body(is("Hello from Quarkus REST")); } @Test void testGreetingEndpoint() { String uuid = UUID.randomUUID().toString(); given() .pathParam("name", uuid) .when().get("/hello/greeting/{name}") .then() .statusCode(200) .body(is("hello " + uuid)); } } ``` -------------------------------- ### Integrate GreetingService into Quarkus Application Source: https://quarkus.io/guides/scripting Modify the main application class to inject the GreetingService and expose a new REST endpoint. This example includes JBang dependencies and Quarkus runtime setup. ```java //usr/bin/env jbang "$0" "$@" ; exit $? //DEPS io.quarkus.platform:quarkus-bom:3.37.0@pom //DEPS io.quarkus:quarkus-rest import io.quarkus.runtime.Quarkus; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; @Path("/hello") @ApplicationScoped public class quarkusapp { @GET public String sayHello() { return "hello"; } public static void main(String[] args) { Quarkus.run(args); } @Inject GreetingService service; @GET @Produces(MediaType.TEXT_PLAIN) @Path("/greeting/{name}") public String greeting(String name) { return service.greeting(name); } @ApplicationScoped static public class GreetingService { public String greeting(String name) { return "hello " + name; } } } ``` -------------------------------- ### Define Tutorial Abstract Source: https://quarkus.io/guides/doc-create-tutorial Provide a concise abstract for your tutorial to set reader expectations about the achievable outcomes. Use action verbs to clearly state what the reader will accomplish. ```asciidoc Create an application that uses unique annotations from the experimental acme extension to define two endpoints: a simple HTTP endpoint and an endpoint that emits server-sent events (SSE). We will also use Quarkus dev mode for iterative development and testing. ``` -------------------------------- ### LRA Dev Services with Docker Compose Source: https://quarkus.io/guides/lra-dev-services Example `compose-devservices.yml` configuration for LRA Dev Services. This setup uses a specific image and exposes port 8080 for the Narayana LRA service. ```yaml name: services: narayana-lra: image: quay.io/jbosstm/lra-coordinator:latest ports: - "8080" ``` -------------------------------- ### Example HTTP Request and Response Source: https://quarkus.io/guides/qute This example shows how to call the REST endpoint and the expected plain text response, demonstrating template rendering with provided data. ```bash $ curl -w "\n" http://localhost:8080/hello?name=Martin Hello Martin! ``` -------------------------------- ### Programmatic OIDC Tenant Startup with OidcTenantConfig Source: https://quarkus.io/guides/security-oidc-bearer-token-authentication This example shows how to programmatically create an OIDC tenant using `OidcTenantConfig` builder for more complex configurations, such as requiring JWT introspection only. ```java package io.quarkus.it.oidc; import io.quarkus.oidc.Oidc; import io.quarkus.oidc.OidcTenantConfig; import jakarta.enterprise.event.Observes; public class OidcStartup { void createDefaultTenant(@Observes Oidc oidc) { var defaultTenant = OidcTenantConfig .authServerUrl("http://localhost:8180/realms/quarkus") .token().requireJwtIntrospectionOnly().end() .build(); oidc.create(defaultTenant); } } ``` -------------------------------- ### Vert.x JSON HTTP Endpoint in Quarkus Source: https://quarkus.io/guides/vertx-reference Expose JsonObject and JsonArray as Quarkus HTTP endpoint request and response bodies. This example demonstrates GET endpoints returning a JsonObject and a JsonArray. ```java package org.acme.vertx; import io.vertx.core.json.JsonObject; import io.vertx.core.json.JsonArray; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; @Path("/hello") @Produces(MediaType.APPLICATION_JSON) public class VertxJsonResource { @GET @Path("{name}/object") public JsonObject jsonObject(String name) { return new JsonObject().put("Hello", name); } @GET @Path("{name}/array") public JsonArray jsonArray(String name) { return new JsonArray().add("Hello").add(name); } } ``` -------------------------------- ### Virtual Method Examples Source: https://quarkus.io/guides/qute-reference Shows how to invoke virtual methods within expressions, including standard and infix notations. ```qute {item.getLabels(1)} ``` ```qute {name or 'John'} ``` -------------------------------- ### Order Service Startup with depends_on Source: https://quarkus.io/guides/compose-dev-services Ensure services start in a specific order by using the `depends_on` attribute in your Compose file. This example shows the 'app' service depending on the 'db' service. ```yaml services: db: image: docker.io/library/postgres:18 ports: - '5432' environment: POSTGRES_USER: myuser POSTGRES_PASSWORD: mypassword POSTGRES_DB: mydb app: image: my-application:latest ports: - '8080' depends_on: - db ``` -------------------------------- ### Install Greeting Extension Locally Source: https://quarkus.io/guides/building-my-first-extension Install the greeting-extension into your local Maven repository. This makes it available for use in other Quarkus projects. ```bash cd ./greeting-extension mvn clean install ``` -------------------------------- ### GraphQL Query to Get Film by ID Source: https://quarkus.io/guides/smallrye-graphql Example GraphQL query to retrieve a specific film by its ID. The query uses the 'filmId' parameter, which is aliased from the 'id' parameter using the @Name annotation. ```graphql query getFilm { film(filmId: 1) { title director releaseDate episodeID } } ``` -------------------------------- ### Executing GraphQL Queries via REST Endpoint Source: https://quarkus.io/guides/smallrye-graphql-client Send GET requests to the application's REST endpoints to execute GraphQL queries. This example shows how to access the dynamic client endpoint. ```bash curl -s http://localhost:8080/dynamic # to use the dynamic client ``` -------------------------------- ### Example Skill File Content Source: https://quarkus.io/guides/agent-mcp Provides example Markdown content for a `quarkus-skill.md` file, covering key patterns, testing, and common pitfalls for AI agents. ```markdown ### Data Access - Inject `MyClient` with `@Inject` — it is an `@ApplicationScoped` CDI bean. - Use `client.query("...")` for read operations. - Always wrap write operations in `@Transactional`. ### Testing - Use `@QuarkusTest` — Dev Services starts a backing service automatically. - Inject `MyClient` in tests for direct assertions. ### Common Pitfalls - Do NOT create `MyClient` manually with `new` — always let CDI inject it. - Do NOT set the connection URL without a `%prod.` profile prefix — this disables Dev Services. ``` -------------------------------- ### Invoke REST API to Get Weather Data Source: https://quarkus.io/guides/kafka-streams Example using httpie to call the REST API endpoint for weather station data. This demonstrates how to retrieve aggregated data for a specific station ID. ```http http aggregator:8080/weather-stations/data/1 ```