Quarkus Cheat Sheet
Quarkus Cheat Sheet
plugins {
id 'java' mvn clean package -Pnative
id 'io.quarkus' version '0.26.1' Picocli
} ./gradlew build -Dquarkus.package.type=native
You can use Picocli to implement CLI applications:
repositories {
mavenCentral() ./mvnw quarkus:add-extension
Possible quarkus.package.type are: jar , legacy-jar , uber-jar and
} -Dextensions="picocli"
native .
dependencies {
AppCDS
implementation enforcedPlatform('io.quarkus:quarkus-bo
m:0.26.1') Automatically generate AppCDS as part of the build process set the
implementation 'io.quarkus:quarkus-resteasy' next property: quarkus.package.create-appcds=true .
}
To make use of it, just run java -jar -XX:SharedArchiveFile=app-
cds.jsa myapp.jar .
@CommandLine.Command @CommandLine.Command Dev Mode
public class HelloCommand implements Runnable { public class EntryCommand implements Runnable {
@CommandLine.Option(names = "-c", description = "JDBC c
./mvnw compile quarkus:dev
@CommandLine.Option(names = {"-n", "--name"}, descripti onnection string")
on = "Who will we greet?", defaultValue = "World") String connectionString;
./gradlew quarkusDev
String name;
@Inject
private final GreetingService greetingService; DataSource dataSource;
} Endpoints are registered automatically to provide some basic
public HelloCommand(GreetingService greetingService) { debug info in dev mode:
this.greetingService = greetingService; @ApplicationScoped
HTTP GET /quarkus/arc/beans
} class DatasourceConfiguration {
}
} lt) {
System.out.println(parseResult.matchedOption("c").g
Dev UI
etValue().toString());
}
Quarkus adds a Dev UI console to expose extension features.
}
All classes annotated with picocli.CommandLine.Command are The Dev UI is available in dev mode only and accessible at the
registered as CDI beans. /q/dev endpoint by default.
If only one class annotated with picocli.CommandLine.Command it will Adding Con guration Parameters
be used as entry point. If you want to provide your own
Extensions
@QuarkusMain :
Quarkus comes with extensions to integrate with some libraries To add con guration to your application, Quarkus relies on
such as JSON-B, Camel or MicroPro le spec. To list all available MicroPro le Con g spec.
@QuarkusMain extensions just run:
@CommandLine.Command(name = "demo", mixinStandardHelpOption
@ConfigProperty(name = "greetings.message")
s = true)
./mvnw quarkus:list-extensions String message;
public class ExampleApp implements Runnable, QuarkusApplica
tion {
@ConfigProperty(name = "greetings.message",
defaultValue = "Hello")
@Inject You can use -DsearchPattern=panache to lter out all
String messageWithDefault;
CommandLine.IFactory factory; extensions except the ones matching the expression.
@ConfigProperty(name = "greetings.message")
@Override And to register the extensions into build tool:
Optional<String> optionalMessage;
public void run() {
}
./mvnw quarkus:add-extension -Dextensions=""
@ApplicationScoped
public class ApplicationLifecycle { greetings.message = Hello World
void onStart(@Observes StartupEvent event) {}
void onStop(@Observes ShutdownEvent event) {}
}
Array , List and Set are supported. The delimiter is comma
( , ) char and \ is the escape char.
Quarkus supports graceful shutdown. By default there is no timeout Con guration Pro les
but can be set by using the quarkus.shutdown.timeout con g
Quarkus allow you to have multiple con guration in the same le
@ConfigProperty(name = "quarkus.application.name") @ConfigProperties(prefix = "greeting", namingStrategy=Namin
( application.properties ).
String applicationName; gStrategy.KEBAB_CASE)
public class GreetingConfiguration {
The syntax for this is %{profile}.config.key=value .
public String message;
public HiddenConfig hidden;
quarkus.http.port=9090 Additional locations
%dev.quarkus.http.port=8181 public static class HiddenConfig {
You can use smallrye.config.locations property to set additional
con guration les. public List<String> recipients;
}
HTTP port will be 9090, unless the 'dev' pro le is active. smallrye.config.locations=config.properties
}
@ConfigProperty(name = "message")
test { String message();
quarkus:
useJUnitPlatform() String getSuffix();
datasource:
systemProperty "quarkus.test.profile", "foo" url: jdbc:postgresql://localhost:5432/some-database
} driver: org.postgresql.Driver
If property does not follow getter/setter naming convention you
need to use org.eclipse.microprofile.config.inject.ConfigProperty
Special propertiesare set in prod mode: to set it.
Or with pro les:
quarkus.application.version and quarkus.application.name to get
Nested objects are also supporte:
them available at runtime.
Then you need to register the ConfigSource as Java service. Create
"%dev": @ApplicationScoped
a le with the following content:
quarkus: public class GreetingService {
datasource: /META-INF/services/org.eclipse.microprofile.config.spi.ConfigSource
url: jdbc:postgresql://localhost:5432/some-database public String message(String message) {
driver: org.postgresql.Driver com.acme.config.InMemoryConfig return message.toUpperCase();
}
}
In case of subkeys ~ is used to refer to the unpre xed part. Custom Converters
You can implement your own conversion types from String. Scope annotation is mandatory to make the bean discoverable.
quarkus:
Implement org.eclipse.microprofile.config.spi.Converter
http:
interface:
cors: @Inject
~: true GreetingService greetingService;
methods: GET,PUT,POST @Priority(DEFAULT_QUARKUS_CONVERTER_PRIORITY + 100)
public class CustomInstantConverter
implements Converter<Instant> {
Quarkus is designed with Substrate VM in mind. For this
Is equivalent to: @Override reason, we encourage you to use package-private scope
public Instant convert(String value) { instead of private.
quarkus.http.cors=true if ("now".equals(value.trim())) {
quarkus.http.cors.methods=GET,PUT,POST return Instant.now(); Produces
}
return Instant.parse(value); You can also create a factory of an object by using
@javax.enterprise.inject.Produces annotation.
}
Custom Loader
}
You can implement your own ConfigSource to load con guration @Produces
from different places than the default ones provided by Quarkus. @ApplicationScoped
For example, database, custom XML, REST Endpoints, … Message message() {
@Priority annotation is used to override the default
Message m = new Message();
InstantConverter .
You need to create a new class and implement ConfigSource m.setMsn("Hello");
interface: Then you need to register the Converter as Java service. Create a return m;
le with the following content: }
package com.acme.config;
/META-INF/services/org.eclipse.microprofile.config.spi.Converter @Inject
public class InMemoryConfig implements ConfigSource {
Message msg;
com.acme.config.CustomInstantConverter
private Map<String, String> prop = new HashMap<>();
@Override
public String getName() {
return "MemoryConfigSource";
}
}
To work with JSON-B you need to add a dependency:
@Qualifier @Dependent
@Retention(RUNTIME) public class TracerConfiguration {
@Target({TYPE, METHOD, FIELD, PARAMETER}) @Produces ./mvnw quarkus:add-extension
public @interface Quote { @IfBuildProfile("prod") -Dextensions="io.quarkus:quarkus-resteasy-jsonb"
@Nonbinding String value(); public Tracer realTracer(Reporter reporter, Configurati
} on configuration) {
return new RealTracer(reporter, configuration); Any POJO is marshaled/unmarshalled automatically.
@Produces }
@Quote("") @Produces
public class Sauce {
Message message(InjectionPoint msg) { @DefaultBean
private String name;
Message m = new Message(); public Tracer noopTracer() {
private long scovilleHeatUnits;
m.setMsn( return new NoopTracer();
msg.getAnnotated() }
// getter/setters
.getAnnotation(Quote.class) }
}
.value()
);
To work with JAX-B you need to add a dependency: public Response create(@Valid Sauce sauce) {} You can call the validation process manually instead of relaying to
@Valid by injecting Validator class.
./mvnw quarkus:add-extension
-Dextensions="quarkus-resteasy-jaxb" @Inject
If a validation error is triggered, a violation report is
Validator validator;
generated and serialized as JSON. If you want to
manipulate the output, you need to catch in the code the
Then annotated POJOs are converted to XML. ConstraintViolationException exception.
And use it:
@XmlRootElement
Create Your Custom Constraints
public class Message { Set<ConstraintViolation<Sauce>> violations =
First you need to create the custom annotation: validator.validate(sauce);
}
Validator fail-fast
When fail fast is enabled the validation will stop on the rst The path to log le (default: quarkus.log ) syslog.truncate
constraint violation detected. (default: false ) Message should be truncated (default: true )
file.rotation.max-file-size
method-validation.allow-overriding-parameter-constraints The maximum le size of the log le syslog.block-on-reconnect
De ne whether overriding methods that override constraints Block when attempting to reconnect (default: true )
should throw an exception. (default: false ). file.rotation.max-backup-index
The maximum number of backups to keep (default: 1 ) syslog.async
method-validation.allow-parameter-constraints-on-parallel-methods
Log asynchronously (default: false )
De ne whether parallel methods that de ne constraints should file.rotation.file-suffix
throw an exception. (default: false ). Rotating log le su x. syslog.async.queue-length
The queue length to use before ushing writing (default: 512 )
method-validation.allow-multiple-cascaded-validation-on-return-
file.rotation.rotate-on-boot
values
Indicates rotate logs at bootup (default: true ) syslog.async.overflow
De ne whether more than one constraint on a return value may
be marked for cascading validation are allowed. (default: false ). Action when queue is full (default: BLOCK )
file.async
Log asynchronously (default: false ) You can inject logger instance:
Logging
file.async.queue-length import org.jboss.logging.Logger;
You can con gure how Quarkus logs:
The queue length to use before ushing writing (default: 512 ) import io.quarkus.arc.log.LoggerName;
quarkus.log.category."com.lordofthejars".level=DEBUG @LoggerName("foo")
syslog.enable
Logger fooLog;
syslog logging is enabled (default: false )
console.color current hostname) Hostname/IP of Logstash/Graylof. Prepend tcp: for using TCP
protocol. (default: udp:localhost )
Allow color rendering (default: true )
syslog.facility
syslog.syslog-type handler.gelf.version
file.format
The syslog type of format message (default: RFC5424 ) GELF version. (default: 1.1 )
Format pattern to use for logging. Default value:
%d{yyyy-MM-dd HH:mm:ss,SSS} %h %N[%i] %-5p [%c{3.}] (%t) %s%e%n
syslog.protocol handler.gelf.extract-stack-trace
file.level Protocol used (default: TCP ) Post Stack-Trace to StackTrace eld. (default: true )
file.path Message pre xed with the size of the message (default false ) Gets the cause level to stack trace. 0 is fulls tack trace. (default:
)
handler.gelf.filter-stack-trace json.print-details You can still use the JAX-RS client without any problem
Stack-Trace ltering. (default: false ) Detailed caller information should be logged (default: false) ClientBuilder.newClient().target(…)
Adding headers
handler.gelf.timestamp-pattern Rest Client
Java Date pattern. (default: yyyy-MM-dd HH:mm:ss,SSS )
You can customize the headers passed by implementing
Quarkus implements MicroPro le Rest Client spec: MicroPro le ClientHeadersFactory annotation:
handler.gelf.level
Log level java.util.logging.Level . (default: ALL ) ./mvnw quarkus:add-extension @RegisterForReflection
-Dextensions="quarkus-rest-client" public class BaggageHeadersFactory
handler.gelf.facility implements ClientHeadersFactory {
Name of the facility. (default: jboss-logmanage ) @Override
To get content from http://worldclockapi.com/api/json/cet/now public MultivaluedMap<String, String> update(
handler.gelf.additional-field.<field>.<subfield> you need to create a service interface: MultivaluedMap<String, String> incomingHeaders,
Post additional elds. quarkus.log.handler.gelf.additional-
MultivaluedMap<String, String> outgoingHeaders) {}
field.field1.type=String
}
@Path("/api")
@RegisterRestClient
handler.gelf.include-full-mdc public interface WorldClockService {
Include all elds from the MDC. And registering it in the client using RegisterClientHeaders
@GET @Path("/json/cet/now") annotation.
@Produces(MediaType.APPLICATION_JSON)
handler.gelf.maximum-message-size
WorldClock getNow(); @RegisterClientHeaders(BaggageHeadersFactory.class)
Maximum message size (in bytes). (default: 8192 )
@RegisterRestClient
@GET public interface WorldClockService {}
handler.gelf.include-log-message-parameters @Path("/json/{where}/now")
Include message parameters from the log event. (default: true ) @Produces(MediaType.APPLICATION_JSON)
WorldClock getSauce(@BeanParam
handler.gelf.include-location WorldClockOptions worldClockOptions); Or statically set:
Include source code location. (default: true )
} @GET
@ClientHeaderParam(name="X-Log-Level", value="ERROR")
JSON output
Response getNow();
You can con gure the output to be in JSON format instead of plain
public class WorldClockOptions {
text.
@HeaderParam("Authorization")
Asynchronous
String auth;
./mvnw quarkus:add-extension
-Dextensions="quarkus-logging-json" A method on client interface can return a CompletionStage class to
@PathParam("where")
be executed asynchronously.
String where;
}
@GET @Path("/json/cet/now")
And the con guration values are pre x with quarkus.log :
@Produces(MediaType.APPLICATION_JSON)
json CompletionStage<WorldClock> getNow();
And con gure the hostname at application.properties :
JSON logging is enabled (default: true).
org.acme.quickstart.WorldClockService/mp-rest/url=
json.pretty-print Reactive
http://worldclockapi.com
JSON output is "pretty-printed" (default: false) Rest Client also integrates with reactive library named Mutiny. To
start using it you need to add the quarkus-rest-client-mutiny .
json.date-format
Injecting the client:
Specify the date format to use (default: the default format) After that, amethodon a client interface can return a
io.smallrye.mutiny.Uni instance.
@RestClient
json.record-delimiter
WorldClockService worldClockService;
Record delimiter to add (default: no delimiter) @GET @Path("/json/cet/now")
@Produces(MediaType.APPLICATION_JSON)
json.zone-id Uni<WorldClock> getNow();
If invokation happens within JAX-RS, you can propagate headers
The time zone ID from incoming to outgoing by using next property.
%s/mp-rest/keyStorePassword
public class MultipartBody { @TestHTTPResource("index.html")
Key store password. URL url;
@FormParam("file")
@PartType(MediaType.APPLICATION_OCTET_STREAM) %s/mp-rest/keyStoreType
private InputStream file; Key store type (default: JKS )
@TestHTTPEndpoint(GreetingResource.class)
@FormParam("fileName") @TestHTTPResource
Timeout
@PartType(MediaType.TEXT_PLAIN) URL url;
private String name; You can de ne the timeout of the Rest Client:
// getter/setters
org.acme.quickstart.WorldClockService/mp-rest/connectTimeou @QuarkusTest
}
t= @TestHTTPEndpoint(GreetingResource.class)
1000 public class GreetingResourceTest {
org.acme.quickstart.WorldClockService/mp-rest/readTimeout= @Test
And the Rest client interface: 2000 public void testHelloEndpoint() {
given()
import .when().get()
org.jboss.resteasy.annotations.providers.multipart.Mult Instantiate client programmatically .then()
ipartForm; .statusCode(200)
.body(is("hello"));
MovieReviewService reviewSvc = RestClientBuilder.newBuilder
@Path("/echo") }
()
@RegisterRestClient }
.baseUri(apiUri)
public interface MultipartService {
.build(WorldClockService.class);
@POST
Root path is calculated automatically, not necessary to explicitly
@Consumes(MediaType.MULTIPART_FORM_DATA)
set.
@Produces(MediaType.TEXT_PLAIN) Testing
String sendMultipartData(@MultipartForm If you want any changes made to be rolled back at the end ofthe
MultipartBody data); Quarkus archetype adds test dependencies with JUnit 5 and Rest- test you can use the io.quarkus.test.TestTransaction annotation.
Assured library to test REST endpoints.
} QuarkusTestPro le
You can de ne for each Test class a different con guration options.
SSL
This implies that the Quarkus service is restarted.
You can con gure Rest Client key stores.
org.acme.quickstart.WorldClockService/mp-rest/trustStore=
classpath:/store.jks
org.acme.quickstart.WorldClockService/mp-rest/trustStorePas
sword=
supersecret
And needs to be registered as Java SPI:
public class MyProfile implements io.quarkus.test.junit.Qua public class MyCustomTestResource
rkusTestProfile { implements QuarkusTestResourceLifecycleManager { META-
INF/services/io.quarkus.test.junit.callback.QuarkusTestBeforeClassCallback
@Override @Override
io.quarkus.it.main.SimpleAnnotationCheckerBeforeClassCallba
public Map<String, String> getConfigOverrides() { public Map<String, String> start() {
ck
return Map.of("greetings.message", "This is a Test" // return system properties that
); // should be set for the running test
} return Collections.emptyMap();
} Mocking
@Override
public String getConfigProfile() { @Override If you need to provide an alternative implementation of a service
return "my-test-profile"; public void stop() { (for testing purposes) you can do it by using CDI @Alternative
} } annotation using it in the test service placed at src/test/java :
io.quarkus.test.junit.callback.QuarkusTestAfterConstructCall
back
Mock is automatically injected and only valid for the de ned test
class.
io.quarkus.test.junit.callback.QuarkusTestBeforeEachCallback
@InjectSpy
public class SimpleAnnotationCheckerBeforeClassCallback imp
GreetingService greetingService;
lements QuarkusTestBeforeClassCallback {
@Override
Mockito.verify(greetingService, Mockito.times(1)).greet();
public void beforeClass(Class<?> testClass) {
}
}
REST Client
To Mock REST Client, you need to de ne the interface with includes Persistence
@ApplicationScope : A list of class les to include in the report. (default: ** )
Quarkus works with JPA(Hibernate) as persistence solution. But
@ApplicationScoped excludes also provides an Active Record pattern implementation under
@RegisterRestClient A list of class les to exclude from the report. Panache project.
public interface GreetingService {
} To use database access you need to add Quarkus JDBC drivers
report-location
instead of the original ones. At this time Apache Derby , H2 , MariaDB ,
@InjectMock The location of the report les. (default: jacoco-report ) MySQL , MSSQL and PostgreSQL drivers are supported.
@RestClient
GreetingService greetingService; Native Testing
./mvnw quarkus:add-extension
To test native executables annotate the test with @NativeImageTest .
-Dextensions="io.quarkus:quarkus-hibernate-orm-panache,
Mockito.when(greetingService.hello()).thenReturn("hello fro io.quarkus:quarkus-jdbc-mariadb"
m mockito");
Quarkus Integration Tests
@QuarkusTest
public String name;
@Stereotype
}
@Transactional
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TransactionalQuarkusTest { And con guration in src/main/resources/application.properties :
}
quarkus.datasource.jdbc.url=jdbc:mariadb://localhost:3306/m
@TransactionalQuarkusTest ydb
public class TestStereotypeTestCase {} quarkus.datasource.db-kind=mariadb
quarkus.datasource.username=developer
quarkus.datasource.password=developer
Test Coverage quarkus.hibernate-orm.database.generation=update
batch-fetch-size
jdbc.background-validation-interval physical-naming-strategy
The interval at which we validate idle connections in the The size of the batches. (default: -1 disabled) Class name of the Hibernate PhysicalNamingStrategy
background. (default: 2M ) implementation.
maxFetchDepth
jdbc.acquisition-timeout The maximum depth of outer join fetch tree for single-ended globally-quoted-identifiers
The timeout before cancelling the acquisition of a new associations. Should quote all identi ers. (default: false )
connection. (default: 5 )
multitenant
metrics-enabled
jdbc.leak-detection-interval De nes the method for multi-tenancy. Possible values: DATABASE ,
Metrics published with smallrye-metrics extension (default:
NONE , SCHEMA . (default: NONE )
The interval at which we check for connection leaks. false )
multitenant-schema-datasource
jdbc.idle-removal-interval second-level-caching-enabled
The interval at which we try to remove idle connections. (default: De nes the name of the data source to use in case of SCHEMA Enable/Disable 2nd level cache. (default: true )
5M )
approach.
Database operations:
query.query-plan-cache-max-size
jdbc.max-lifetime
The max lifetime of a connection. The maximum size of the query plan cache. // Insert
Developer developer = new Developer();
query.default-null-ordering developer.name = "Alex";
jdbc.transaction-isolation-level
The transaction isolation level. Possible values: UNDEFINED , NONE , Default precedence of null values in ORDER BY . Possible values: developer.persist();
none , first , last . (default: none )
READ_UNCOMMITTED , READ_COMMITTED , REPEATABLE_READ , SERIALIZABLE .
// Find All
database.generation Developer.findAll().list();
jdbc.detect-statement-leaks
Warn when a connection is returned to the pool without the Database schema is generation. Possible values: none , create ,
drop-and-create , drop , update . (default: none )
// Hibernate Filters
application having closed all open statements. (default: true ) Person.findAll().filter("Person.hasName", Parameters.with(
"name", "Alex"));
database.generation.halt-on-error
jdbc.new-connection-sql
Query executed when rst using a connection. Stop on the rst error when applying the schema. (default: false )
// Find By Query
Developer.find("name", "Alex").firstResult();
database.generation.create-schemas
jdbc.validation-query-sql
Query executed to validate a connection. Hibernate ORM should create the schemas automatically (for // Delete
databases supporting them). Developer developer = new Developer();
developer.id = 1;
jdbc.pooling-enabled
database.default-catalog developer.delete();
Disable pooling to prevent reuse of Connections. (default: true )
Default catalog.
Person.deleteById(id);
jdbc.enable-metrics // Delete By Query
database.default-schema
Enable datasource metrics collection when using quarkus- long numberOfDeleted = Developer.delete("name", "Alex");
smallrye-metrics extension.
Default Schema.
database.charset
jdbc.additional-jdbc-properties.<extraProperty>
Remember to annotate methods with @Transactional annotation to
Unspeci ed properties to be passed to the JDBC driver when Charset.
make changes persisted in the database.
creating new connections.
jdbc.timezone If queries start with the keyword from then they are treated as HQL
Hibernate con guration properties. Pre x quarkus.hibernate-orm is Time Zone JDBC driver. query, if not then next short form is supported:
skipped.
jdbc.statement-fetch-size order by which expands to from EntityName order by …
<columnName> which expands to from EntityName where count : String , [ Object… , Map<String, Object> , Parameters ] If entities are de ned in external JAR, you need to enable in these
<columnName>=? Number of entities meeting given query with parameters set. projects the Jandex plugin in project.
@Inject @Transactional
org.hibernate.SessionFactory sessionFactory; public void createDeveloper() {}
em.persist(car);
You can control the transaction scope:
Hibernate Multitenancy Also you need to add the reactive driver (ie
REST Data Panache client ).
quarkus-reactive-pg-
@ProtoFactory
public Author(String name, String surname) { Set con guration le location in application.properties :
this.name = name; Marshaller
this.surname = surname; quarkus.infinispan-embedded.xml-config=infinispan.xml
} Using org.infinispan.protostream.MessageMarshaller interface.
@ProtoField(number = 1) public class AuthorMarshaller And you can inject the main entry point for the cache:
public String getName() { implements MessageMarshaller<Author> {
return name;
} @Inject
@Override
org.infinispan.manager.EmbeddedCacheManager cacheManager;
public String getTypeName() {
@ProtoField(number = 2) return "book_sample.Author";
public String getSurname() { }
}
return surname;
Redis
@Override
public Class<? extends Author> getJavaClass() {
Quarkus integrates with Redis.
return Author.class;
Initializer to set con guration settings. }
./mvnw quarkus:add-extension
-Dextensions="redis-client"
@Override
@AutoProtoSchemaBuilder(includeClasses =
public void writeTo(ProtoStreamWriter writer,
{ Book.class, Author.class },
Author author) throws IOException {
schemaPackageName = "book_sample")
writer.writeString("name", author.getName()); Con gure Redis location:
interface BookContextInitializer
writer.writeString("surname", author.getSurname());
extends SerializationContextInitializer {
} quarkus.redis.hosts=localhost:6379
}
@Override
public Author readFrom(ProtoStreamReader reader)
User written based throws IOException { You can use synchronous or reactive clients:
String name = reader.readString("name");
There are three ways to create your schema: String surname = reader.readString("surname"); @Inject
return new Author(name, surname); RedisClient redisClient;
Proto le }
} @Inject
Creates a .proto le in the META-INF directory.
ReactiveRedisClient reactiveRedisClient;
package book_sample;
And producing the marshaller:
message Author {
required string name = 1; @Produces
required string surname = 2; MessageMarshaller authorMarshaller() {
} return new AuthorMarshaller();
}
In case of having a Collection eld you need to use the repeated key
(ie repeated Author authors = 4 ). In nispan Embedded
@OneToMany
.startAndWait() at startup time.
database-change-log-lock-table-name @IndexedEmbedded
Con gure the extension in application.properties :
The database change log lock table name. (default: public List<Book> books;
DATABASECHANGELOGLOCK )
}
default-catalog-name
The default catalog name.
index-defaults.lifecycle.required-status-wait-timeout
List of Hibernate-Elasticsearch properties pre xed with Waiting time before failing the bootstrap. @Inject
quarkus.hibernate-search.elasticsearch : DynamoDbAsyncClient dynamoDB;
index-defaults.refresh-after-write
backends Uni.createFrom().completionStage(() -> dynamoDB.scan(scanRe
Set if index should be refreshed after writes.
Map of con guration of additional backends. quest()))....
Possible annotations:
version
Version of Elasticsearch @Indexed To use it as a local DynamoDB instance:
Register entity as full text index
analysis-configurer quarkus.dynamodb.region=
Class or name of the neab used to con gure. @FullTextField eu-central-1
Full text search. Need to set an analyzer to split tokens. quarkus.dynamodb.endpoint-override=
hosts http://localhost:8000
quarkus.dynamodb.credentials.type=STATIC
List of Elasticsearch servers hosts. @KeywordField
quarkus.dynamodb.credentials.static-provider
The string is kept as one single token but can be normalized. .access-key-id=test-key
username
quarkus.dynamodb.credentials.static-provider
Username for auth. IndexedEmbedded
.secret-access-key=test-secret
Include the Book elds into the Author index.
password
How a dependency of the indexing process to a property should Credentials through the Amazon EC2 container service if the
discovery.enabled affect automatic reindexing. AWS_CONTAINER_CREDENTIALS_RELATIVE_URI set
Enables automatic discovery.
@ObjectPath Credentials through Amazon EC2 metadata service.
discovery.refresh-interval @ScaledNumberField Con guration parameters pre xed with quarkus.dynamodb :
Refresh interval of node list. For java.math.BigDecimal or java.math.BigInteger that you need
higher precision.
discovery.default-scheme Parameter Default Description
Scheme to be used for the new nodes. Amazon DynamoDB
Endpoint discovery
automatic-indexing.synchronization-strategy Quarkus integrates with https://aws.amazon.com/dynamodb/: enable-endpoint- for a service API that
Status for which you wait before considering the operation discovery
false
supports endpoint
completed ( queued , committed or searchable ). ./mvnw quarkus:add-extension discovery.
-Dextensions="quarkus-amazon-dynamodb"
automatic-indexing.enable-dirty-check
endpoint-override Con gure the Parameter Default Description Parameter Default Description
endpoint with which
the SDK should PROFILE Connections in pool
communicate. use-idle-connection-
true should be closed
reaper
asynchronously.
profile- The name of the
Time to complete an default
api-call-timeout provider.profile-name pro le to use.
execution. Endpoint of the proxy
proxy.endpoint
server.
PROCESS
List of class
interceptors
interceptors. proxy.enabled false Enables HTTP proxy.
Command to execute
process-
to retrieve
Con guration parameters pre xed with quarkus.dynamodb.aws : provider.command
credentials. proxy.username Proxy username.
Parameter Default Description
process- proxy.password Proxy password.
Region that hosts Max bytes to retrieve
provider.process- 1024
region
DynamoDB. from process.
output-limit
For NTLM, domain
proxy.ntlm-domain
name.
Credentials that The amount of time
process-
should be used between credentials
provider.credential- PT15S
DEFAULT , STATIC , expire and proxy.ntlm- For NTLM,
refresh-threshold
SYSTEM_PROPERTY , credentials refreshed. workstation workstation name.
credentials.type DEFAULT
ENV_VARIABLE ,
PROFILE , CONTAINER ,
INSTANCE_PROFILE , process- proxy.preemptive-
Authenticate pre-
PROCESS , ANONYMOUS provider.async- Should fetch basic-authentication-
false emptively.
credential-update- credentials async. enabled
enabled
Credentials speci c parameters pre xed with
quarkus.dynamodb.aws.credentials : proxy.non-proxy- List of non proxy
In case of synchronous client, the next parameters can be hosts hosts.
Parameter Default Description con gured pre xed by quarkus.dynamodb.sync-client :
uri
tls-managers-
provider.file- Key store type. URI of Neo4j. (default: localhost:7687 )
quarkus.s3.sync-client.type=apache
store.type
authentication.username
Username. (default: neo4j )
tls-managers- And con gure it:
provider.file- Key store password. authentication.password
store.password
Password. (default: neo4j )
If you are using Neo4j 4.0, you can use fully reactive. Add the next
extension: quarkus-resteasy-mutiny . Inject the instance using socket-timeout Duration
@io.quarkus.mongodb.runtime.MongoClientName annotation:
You can also use the Panache framework to write persistence part long countAll = Person.count();
Frequency to
when using MongoDB.
heartbeat-frequency Duration determine the state
Person.deleteById(id);
of servers.
./mvnw quarkus:add-extension Person.delete("status", Status.Alive);
-Dextensions="mongodb-panache"
primary ,
primaryPreferred , All list methods have equivalent stream versions.
read-preference secondary , Read preferences. MongoDB con guration comes from MongoDB Client section.
secondaryPreferred , Pagination
nearest
@MongoEntity(collection="ThePerson") You can also use pagination:
public class Person extends PanacheMongoEntity {
public String name;
Max number of PanacheQuery<Person> livingPersons =
concurrent Person.find("status", Status.Alive);
max-wait-queue-size Int @BsonProperty("birth")
operations allowed to livingPersons.page(Page.ofSize(25));
public LocalDate birthDate;
wait.
// get the first page
public Status status;
List<Person> firstPage = livingPersons.list();
Ensures are writes }
write-concern.safe boolean [true] // get the second page
are ack. List<Person> secondPage = livingPersons.nextPage().list();
Apart from the CompletionStage support, there is also support for <dependency>
Mutiny. <groupId>io.smallrye.reactive</groupId>
<artifactId>mutiny-rxjava</artifactId>
./mvnw quarkus:add-extension </dependency>
-Dextensions="quarkus-resteasy-mutiny"
From RxJava2 :
Uni<Void> uniFromCompletable = Uni.createFrom() Uni<String> uniFromMono = Uni.createFrom().converter(UniRea package org.acme.rest;
.converter(UniRxConvert ctorConverters.fromMono(), mono); import javax.ws.rs.GET;
ers.fromCompletable(), completable); Uni<String> uniFromFlux = Uni.createFrom().converter(UniRea import javax.ws.rs.Path;
Uni<String> uniFromSingle = Uni.createFrom() ctorConverters.fromFlux(), flux); @Path("rest")
.converter(UniRxConverters. Multi<String> multiFromMono = Multi.createFrom().converter public class Endpoint {
fromSingle(), single); (MultiReactorConverters.fromMono(), mono);
Uni<String> uniFromObservable = Uni.createFrom() Multi<String> multiFromFlux = Multi.createFrom().converter @Path("hello")
.converter(UniRxConverters. (MultiReactorConverters.fromFlux(), flux); @GET
fromObservable(), observable); public String hello(){
Uni<String> uniFromFlowable = Uni.createFrom() // executed in event-loop
.converter(UniRxConverters. return "Hello, World!";
To Reactor :
fromFlowable(), flowable); }
...
Mono<String> mono = uni.convert().with(UniReactorConverter @GET
Multi<Void> multiFromCompletable = Multi.createFrom() s.toMono()); public Uni<Book> culinaryGuide(){
.converter(MultiRxC Flux<String> flux = uni.convert().with(UniReactorConverter // executed in event-loop but not blocking
onverters.fromCompletable(), completable); s.toFlux()); return Book.findByIsbn("978-2081229297");
Multi<String> multiFromObservable = Multi.createFrom() }
.converter(MultiRxC Mono<String> mono2 = multi.convert().with(MultiReactorConve
onverters.fromObservable(), observable); rters.toMono()); @io.smallrye.common.annotation.Blocking
Multi<String> multiFromFlowable = Multi.createFrom() Flux<String> flux2 = multi.convert().with(MultiReactorConve @GET
.converter(MultiRxC rters.toFlux()); public String blockingHello() throws InterruptedExcepti
onverters.fromFlowable(), flowable); on {
... // executed in worker-thread
CompletionStages or Publisher return "Yaaaawwwwnnnnnn…";
}
@Outgoing("my-in-memory")
Reactor API
public Flowable<Integer> generate() {
return Flowable.interval(5, TimeUnit.SECONDS)
<dependency> .map(tick -> random.nextInt(100));
<groupId>io.smallrye.reactive</groupId> }
<artifactId>mutiny-reactor</artifactId> }
</dependency>
or in Mutiny:
From Reactor :
@ApplicationScoped @Inject @Stream(“out”) mp.messaging.outgoing.generated-price.connector=
public class ProducerData { Publisher<String> result; smallrye-kafka
@Outgoing("my-in-memory") mp.messaging.outgoing.generated-price.topic=
public Multi<Integer> generate() { @GET prices
return Multi.createFrom().ticks().every(Duration.of @Produces(SERVER_SENT_EVENTS) mp.messaging.outgoing.generated-price.bootstrap.servers=
Seconds(5)) public Publisher<String> stream() { localhost:9092
.onItem().apply(n -> random.nextInt(100)); return result; mp.messaging.outgoing.generated-price.value.serializer=
} } org.apache.kafka.common.serialization.IntegerSerializer
}
mp.messaging.incoming.prices.connector=
smallrye-kafka
Message → Business Logic
mp.messaging.incoming.prices.value.deserializer=
If you want to dispatch to all subscribers you can annotate the
org.apache.kafka.common.serialization.IntegerDeserializ
method with @Broadcast . @ApplicationScoped er
public class ReceiverMessages {
Consumes generated data from my-in-memory stream.
@Incoming("prices")
public void print(String price) {
@ApplicationScoped } A complete list of supported properties are in Kafka site. For the
public class ConsumerData { } producer and for consumer
@Incoming("my-in-memory")
public void randomNumber(int randomNumber) { JSON-B Serializer/Deserializer
System.out.println("Received " + randomNumber);
}
To indicate that the method should be executed on a worker pool You can use JSON-B to serialize/deserialize objects.
}
you can use @Blocking :
./mvnw quarkus:add-extension
@Outgoing("Y") -Dextensions="quarkus-kafka-client"
@Incoming("X")
You can also inject an stream as a eld:
@Blocking
Patterns
public BeerDeserializer() {
super(Beer.class);
REST API → Message Possible implementations are:
}
In-Memory
@Inject @Stream(“in”) }
Emitter<String> emitter;
If the stream is not con gured then it is assumed to be an in-
memory stream, if not then stream type is de ned by connector
emitter.send(message);
eld. AMQP
Kafka To integrate with AMQP you need to add next extensions:
Message → Message
To integrate with Kafka you need to add next extensions:
./mvnw quarkus:add-extension
@Incoming(“in”) -Dextensions="reactive-messaging-amqp"
@Outgoing(“out”) mvn quarkus:add-extension
public String process(String in) { -Dextensions="
} io.quarkus:quarkus-smallrye-reactive-messaging-kafka"
Then @Outgoing , @Incoming or @Stream can be used.
Then @Outgoing , @Incoming or @Stream can be used. Previous example produces content to another stream. If you want Key/cert con guration in the JKS format.
to write interactive queries, you can use Kafka streams.
MQTT con guration schema: mp.messaging.[outgoing|incoming]. reactive.key-certificate-pfx
{stream-name}.<property>=<value> . @Inject Key/cert con guration in the PFX format.
KafkaStreams streams;
The connector type is smallrye-mqtt .
reactive.thread-local
return streams
Use one connection pool per thread.
mp.messaging.outgoing.topic-price.type= .store("stream", QueryableStoreTypes.keyValueStore
smallrye-mqtt ());
reactive.reconnect-attempts
mp.messaging.outgoing.topic-price.topic=
prices The number of reconnection attempts when a pooled connection
mp.messaging.outgoing.topic-price.host= cannot be established on rst try. (default: 0 )
The Kafka Streams extension is con gured via the Quarkus
localhost
con guration le application.properties .
mp.messaging.outgoing.topic-price.port= reactive.reconnect-interval
1883 The interval between reconnection attempts when a pooled
quarkus.kafka-streams.bootstrap-servers=localhost:9092
mp.messaging.outgoing.topic-price.auto-generated-client-id= connection cannot be established on rst try. (default: PT1S )
quarkus.kafka-streams.application-id=temperature-aggregator
true
quarkus.kafka-streams.application-server=${hostname}:8080
reactive.idle-timeout
quarkus.kafka-streams.topics=weather-stations,temperature-v
mp.messaging.incoming.prices.type=
alues The maximum time without data written to or read from a
smallrye-mqtt
connection before it is removed from the pool.
mp.messaging.incoming.prices.topic=
kafka-streams.cache.max.bytes.buffering=10240
prices
mp.messaging.incoming.prices.host=
kafka-streams.commit.interval.ms=1000 Reactive PostgreSQL Client
localhost
mp.messaging.incoming.prices.port= You can use Reactive PostgreSQL to execute queries to PostreSQL
1883 IMPORTANT: All the properties within the kafka-streams database in a reactive way, instead of using JDBC way.
mp.messaging.incoming.prices.auto-generated-client-id= namespace are passed through as-is to the Kafka Streams engine.
true Changing their values requires a rebuild of the application. ./mvnw quarkus:add-extension
-Dextensions="quarkus-reactive-pg-client"
Reactive DataSource Properties
Database con guration is the same as shown in Persistence Reactive Transactions Artemis JMS
section, but URL is different as it is not a jdbc.
If you want to use JMS with Artemis, you can do it by using its
io.vertx.mutiny.sqlclient.SqlClientHelper is an util class that
extension:
quarkus.datasource.db-kind=postgresql allows you to run reactive persisten code within a transaction.
quarkus.datasource.reactive.url=postgresql:///your_database
./mvnw quarkus:add-extension
Uni<Void> r = SqlClientHelper.inTransactionUni(client, tx -
-Dextensions="quarkus-artemis-jms"
> {
Then you can inject io.vertx.mutiny.pgclient.PgPool class. Uni<RowSet<Row>> insertOne = tx.preparedQuery("INSE
RT INTO fruits (name) VALUES ($1) RETURNING (id)")
@Inject .execute(Tuple.of(fruit1.name)); And then you can inject javax.jms.ConnectionFactory :
You can use Reactive DB2 to execute queries to DB2 database in a Vert.X Cassandra Client
reactive way, instead of using JDBC. quarkus.artemis.url=tcp://localhost:61616
io.smallrye.reactive:smallrye-mutiny-vertx-cassandra-client
ost:50005/hreact
artemis.password Vert.X RabbitMQ Client
Password for authentication. io.smallrye.reactive:smallrye-mutiny-vertx-rabbitmq-client
return Uni.createFrom()
./mvnw quarkus:add-extension
.completionStage(
-Dextensions="amazon-sqs"
sqs.receiveMessage(m -> m.maxNumberOfMessages(10).q You can use io.quarkus.security.Authenticated as a shortcut of
ueueUrl(queueUrl)) @RolesAllowed("*") .
)
Injecting the client: .onItem() To alter RBAC behaviour there are two con guration properties:
@Inject quarkus.security.deny-unannotated=true
software.amazon.awssdk.services.sqs.SqsClient sqs; And you need to add the asynchronous Netty client:
SendMessageResponse response = sqs.sendMessage(m -> m.queue
<dependency> Con guration options:
Url(queueUrl).messageBody(message));
<groupId>software.amazon.awssdk</groupId>
quarkus.jaxrs.deny-uncovered
<artifactId>netty-nio-client</artifactId>
List<Message> messages = sqs.receiveMessage(m -> m.maxNumbe
</dependency> If true denies by default to all JAX-RS endpoints. (default: false )
rOfMessages(10).queueUrl(queueUrl)).messages();
quarkus.security.deny-unannotated
Con guration properties are the same as Amazon DynamoDB but If true denies by default all CDI methods and JAX-RS endpoints.
And con gure it:
changing the pre x from dynamodb to sqs . (default: false )
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>url-connection-client</artifactId>
</dependency>
or Apache HTTP:
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>apache-client</artifactId>
</dependency>
quarkus.http.auth.policy.role-policy1.roles-allowed= quarkus.security.security-providers=BC
Sets header such as Cookie is used to pass the token. (default:
Authorization ).
user,admin quarkus.security.security-providers=BCJSSE
quarkus.http.auth.permission.roles1.paths= quarkus.security.security-providers=BCFIPS
smallrye.jwt.token.cookie
/roles-secured/*,/other/*,/api/* quarkus.security.security-providers=BCFIPSJSSE
quarkus.http.auth.permission.roles1.policy= Name of the cookie containing a token.
role-policy1
smallrye.jwt.token.schemes
quarkus.http.auth.permission.permit1.paths= JWT Comma-separated list containing an alternative single or multiple
/public/* schemes. (default: Bearer ).
quarkus.http.auth.permission.permit1.policy= Quarkus implements MicroPro le JWT RBAC spec.
permit smallrye.jwt.require.named-principal
quarkus.http.auth.permission.permit1.methods= mvn quarkus:add-extension
A token must have a upn or preferred_username or sub claim set
GET -Dextensions="io.quarkus:quarkus-smallrye-jwt"
if using java.security.Principal . True makes throw an exception
if not set. (default: false ).
quarkus.http.auth.permission.deny1.paths=
/forbidden
Minimum JWT required claims: typ , alg , kid , iss , sub , exp , iat , smallrye.jwt.path.sub
quarkus.http.auth.permission.deny1.policy=
jti , upn , groups .
deny Path to the claim with subject name.
You can inject token by using JsonWebToken or a claim individually by
smallrye.jwt.claims.sub
using @Claim .
You need to provide permissions set by using the roles-allowed Default sub claim value.
property or use the built-in ones deny , permit or authenticated . @Inject
JsonWebToken jwt; smallrye.jwt.path.groups
You can use enabled property (ie Path to the claim containing the groups.
quarkus.http.auth.permission.permit1.enabled ) to enable the entire
@Inject
permission set. @Claim(standard = Claims.preferred_username) smallrye.jwt.groups-separator
String name; Separator for splitting a string which may contain multiple group
Testing
values. (default. ` `).
@Inject
Quarkus provides explicit support for testing with different users,
@Claim("groups")
and with the security subsystem disabled. smallrye.jwt.claims.groups
Set<String> groups;
Default groups claim value.
<dependency>
@Inject
<groupId>io.quarkus</groupId> smallrye.jwt.jwks.refresh-interval
JWTParser parser;
<artifactId>quarkus-test-security</artifactId>
JWK cache refresh interval in minutes. (default: 60 ).
<scope>test</scope>
</dependency>
smallrye.jwt.expiration.grace
Set of supported types: String , Set<String> , Long , Boolean,
`javax.json.JsonValue , Optional , Expiration grace in seconds. (default: 60 ).
org.eclipse.microprofile.jwt.ClaimValue .
@Test smallrye.jwt.verify.aud
@TestSecurity(authorizationEnabled = false) And con guration in src/main/resources/application.properties :
Comma separated list of the audiences that a token aud claim
void someTestMethod() { may contain.
... mp.jwt.verify.publickey.location=
} META-INF/resources/publicKey.pem smallrye.jwt.verify.algorithm
mp.jwt.verify.issuer=
@Test
Signature algorith. (defsult: RS256 )
https://quarkus.io/using-jwt-rbac
@TestSecurity(user = "testUser", roles = {"admin", "user"})
smallrye.jwt.token.kid
void someTestMethod() {
... If set then the veri cation JWK key as well every JWT token must
Con guration options:
} have a matching kid header.
mp.jwt.verify.publickey
smallrye.jwt.time-to-live
Public Key text itself to be supplied as a string.
The maximum number of seconds that a JWT may be issued for
BouncyCastle use.
mp.jwt.verify.publickey.location Relative path or URL of a public
Quarkus supports BouncyCastle, you only need to add the key.
smallrye.jwt.sign.key-location
BouncyCastle dependency and con gure the security provider:
mp.jwt.verify.issuer Location of a private key which will be used to sign the claims
iss accepted as valid. when either a no-argument sign() or innerSign() method is
called.
smallrye.jwt.token.header
smallrye.jwt.encrypt.key-location
Location of a public key which will be used to encrypt the claims tenant-enabled
Jwt.claims()
or inner JWT when a no-argument encrypt() method is called. If the tenant con guration is enabled. (default: true )
.issuer("https://server.com")
.claim("customClaim", 3)
Supported public key formats: .sign(createKey()); application-type
PKCS#8 PEM The application type. Possible values: web_app , service . (default:
JwtSignatureBuilder jwtSignatureBuilder = Jwt.claims("/test service )
JsonToken.json").jws();
JWK
jwtSignatureBuilder connection-delay
JWKS .signatureKeyId("some-key-id")
The maximum amount of time the adapter will try connecting.
.signatureAlgorithm(SignatureAlgorithm.ES256)
JWK Base64 URL .header("custom-header", "custom-value");
auth-server-url
.sign(createKey());
JWKS Base64 URL The base URL of the OpenID Connect (OIDC) server.
Jwt.claims("/testJsonToken.json")
To send a token to server-side you should use Authorization .encrypt(createKey()); introspection-path
header: curl -H "Authorization: Bearer eyJraWQiOi…" . Relative path of the RFC7662 introspection service.
JwtEncryptionBuilder jwtEncryptionBuilder = Jwt.claims("/te
To inject claim values, the bean must be @RequestScoped CDI stJsonToken.json").jwe(); jwks-path
scoped. If you need to inject claim values in scope with a lifetime jwtEncryptionBuilder
greater than @RequestScoped then you need to use Relative path of the OIDC service returning a JWK set.
.keyEncryptionKeyId("some-key-id")
javax.enterprise.inject.Instance interface.
.keyEncryptionAlgorithm(KeyEncryptionAlgorithm.ECDH_E
public-key
S_A256KW)
@Inject .header("custom-header", "custom-value"); Public key for the local JWT token veri cation
@Claim(standard = Claims.iat) .encrypt(createKey());
private Instance<Long> providerIAT; client-id
Jwt.claims("/testJsonToken.json") The client-id of the application.
.innerSign(createKey());
RBAC .encrypt(createKey()); roles.role-claim-path
Path to the claim containing an array of groups. ( realm/groups )
JWT groups claim is directly mapped to roles to be used in security
annotations.
OpenId Connect roles.role-claim-separator
quarkus.oidc.realm=quarkus credentials.secret
quarkus.oidc.auth-server-url=http://localhost:8180/auth
The client secret
quarkus.oidc.resource=backend-service
quarkus.oidc.bearer-only=true
authentication.redirect-path
quarkus.oidc.credentials.secret=secret
Relative path for calculating a redirect_uri query parameter.
authentication.restore-path-after-redirect
Con guration options with quarkus.oidc pre x:
The original request URI used before the authentication will be
enabled restored after the user has been redirected back to the
The OIDC is enabled. (default: true )
application. (default: true )
authentication.scopes
quarkus.oidc.auth-server-url=http://localhost:8180/auth/rea Authenticating via HTTP
List of scopes. lms/quarkus
quarkus.oidc.client-id=multi-tenant-client HTTP basic auth is enabled by the quarkus.http.auth.basic=true
authentication.extra-params quarkus.oidc.application-type=web-app property.
Additional properties which will be added as the query
parameters . quarkus.oidc.tenant-b.auth-server-url=https://accounts.goog HTTP form auth is enabled by the
le.com quarkus.http.auth.form.enabled=true property.
authentication.cookie-path quarkus.oidc.tenant-b.application-type=web-app
quarkus.oidc.tenant-b.client-id=xxxx Then you need to add elytron-security-properties-file or elytron-
Cookie path parameter. security-jdbc .
quarkus.oidc.tenant-b.credentials.secret=yyyy
quarkus.oidc.tenant-b.token.issuer=https://accounts.google.
proxy.host
com Security with Properties File
The host (name or IP address) of the Proxy. quarkus.oidc.tenant-b.authentication.scopes=email,profile,o
penid You can also protect endpoints and store identities (user, roles) in
proxy.port the le system.
The port number of the Proxy. (default: 80 )
proxy.username
OAuth2 mvn quarkus:add-extension
-Dextensions="elytron-security-properties-file"
The username to authenticate. Quarkus integrates with OAuth2 to be used in case of opaque
tokens (none JWT) and its validation against an introspection
proxy.password endpoint. You need to con gure the extension with users and roles les:
The password to authenticate.
And con guration in src/main/resources/application.properties :
mvn quarkus:add-extension
end-session-path -Dextensions="security-oauth2"
quarkus.security.users.file.enabled=true
Relative path of the OIDC end_session_endpoint .
quarkus.security.users.file.users=test-users.properties
quarkus.security.users.file.roles=test-roles.properties
logout.path And con guration in src/main/resources/application.properties : quarkus.security.users.file.auth-mechanism=BASIC
The relative path of the logout endpoint at the application. quarkus.security.users.file.realm-name=MyRealm
quarkus.oauth2.client-id=client_id quarkus.security.users.file.plain-text=true
logout.post-logout-path quarkus.oauth2.client-secret=secret
Relative path of the application endpoint where the user should quarkus.oauth2.introspection-url=http://oauth-server/intros
be redirected to after logging out. pect
Then users.properties and roles.properties :
tls.verification
scott=jb0ss
Sets the TLs veri cation. Possible values: REQUIRED , NONE . And you can map roles to be used in security annotations. jdoe=p4ssw0rd
(default: REQUIRED ).
@RolesAllowed("Subscriber")
With Keycloak OIDC server
https://host:port/auth/realms/{realm} where {realm} has scott=Admin,admin,Tester,user
to be replaced by the name of the Keycloak realm. jdoe=NoRolesUser
Con guration options:
You can use quarkus.http.cors property to enable
consuming form different domain. quarkus.oauth2.enabled
Determine if the OAuth2 extension is enabled. (default: true ) IMPORTANT: If plain-text is set to false (or omitted) then
Multi-tenancy passwords must be stored in the form MD5
quarkus.oauth2.client-id
( username :`realm`:`password`).
Multi-tenancy is supported by adding a sub-category to OIDC
con guration properties (ie quarkus.oidc.{tenent_id}.property ). The OAuth2 client id used to validate the token. Elytron File Properties con guration properties. Pre x
quarkus.security.users is skipped.
quarkus.oauth2.client-secret
The OAuth2 client secret used to validate the token. file.enabled
quarkus.oauth2.role-claim file.realm-name
The claim that is used in the endpoint response to load the roles The authentication realm name. (default: Quarkus )
((default: scope )
file.plain-text
If passwords are in plain or in MD5. (default: false ) You still need to add the database driver (ie jdbc-h2 ).
principal-query.bcrypt-password-mapper.salt-index
file.users You need to con gure JDBC and Elytron JDBC Realm: The index column containing the Bcrypt salt. (default: 0 )
Classpath resource of user/password. (default:
users.properties ) quarkus.datasource.url= principal-query.bcrypt-password-mapper.salt-encoding
quarkus.datasource.driver=org.h2.Driver A string referencing the salt encoding ( BASE64 or HEX ). (default:
file.roles quarkus.datasource.username=sa BASE64 )
quarkus.datasource.password=sa
Classpath resource of user/role. (default: roles.properties )
principal-query.bcrypt-password-mapper.iteration-count-index
quarkus.security.jdbc.enabled=true
Embedded Realm quarkus.security.jdbc.principal-query.sql= The index column containing the Bcrypt iteration count. (default:
0)
SELECT u.password, u.role FROM test_user u WHERE u.user
You can embed user/password/role in the same
=?
application.properties : For multiple datasources you can use the datasource name in the
quarkus.security.jdbc.principal-query
.clear-password-mapper.enabled=true properties:
quarkus.security.users.embedded.enabled=true quarkus.security.jdbc.principal-query
quarkus.security.users.embedded.plain-text=true .clear-password-mapper.password-index=1 quarkus.datasource.url=
quarkus.security.users.embedded.users.scott=jb0ss quarkus.security.jdbc.principal-query quarkus.security.jdbc.principal-query.sql=
quarkus.security.users.embedded.roles.scott=admin,tester,us .attribute-mappings.0.index=2
er quarkus.security.jdbc.principal-query quarkus.datasource.permissions.url=
quarkus.security.users.embedded.auth-mechanism=BASIC .attribute-mappings.0.to=groups quarkus.security.jdbc.principal-query.permissions.sql=
file.auth-mechanism
principal-query.sql
The authentication mechanism. (default: BASIC )
The sql query to nd the password.
file.realm-name
principal-query.datasource
The authentication realm name. (default: Quarkus )
The data source to use.
file.plain-text
principal-query.clear-password-mapper.enabled
If passwords are in plain or in MD5. (default: false )
If the clear-password-mapper is enabled. (default: false )
file.users.*
principal-query.clear-password-mapper.password-index
* is user and value is password.
The index of column containing clear password. (default: 1 )
file.roles.*
principal-query.bcrypt-password-mapper.enabled
* is user and value is role.
If the bcrypt-password-mapper is enabled. (default: false )
No password is set as it is fetched from Vault. CreateKeyParameters createKeyParameters = new CreateKeyPara authentication.app-role.role-id
renew-grace-period
Renew grace period duration (default: 1H )
quarkus.kms.endpoint-override=http://localhost:8011 <dependency>
quarkus.kms.aws.region=us-east-1 <groupId>software.amazon.awssdk</groupId>
secret-config-cache-period
quarkus.kms.aws.credentials.type=static <artifactId>url-connection-client</artifactId>
Vault con g source cache period (default: 10M ) quarkus.kms.aws.credentials.static-provider.access-key-id=t </dependency>
est-key
secret-config-kv-path quarkus.kms.aws.credentials.static-provider.secret-access-k
Vault path in kv store. List of paths is supported in CSV ey=test-secret
or Apache HTTP:
log-confidentiality-level
<dependency>
Used to hide con dential infos. low , medium , high (default: You need to set a HTTP client either URL Connection : <groupId>software.amazon.awssdk</groupId>
medium ) <artifactId>apache-client</artifactId>
<dependency> </dependency>
kv-secret-engine-version <groupId>software.amazon.awssdk</groupId>
Kv secret engine version (default: 1) <artifactId>url-connection-client</artifactId>
</dependency>
And you need to add the asynchronous Netty client:
kv-secret-engine-mount-path Kv secret engine path (default: secret )
<dependency>
tls.skip-verify or Apache HTTP: <groupId>software.amazon.awssdk</groupId>
Allows to bypass certi cate validation on TLS communications <artifactId>netty-nio-client</artifactId>
(default: false ) <dependency> </dependency>
<groupId>software.amazon.awssdk</groupId>
tls.ca-cert <artifactId>apache-client</artifactId>
Certi cate bundle used to validate TLS communications </dependency>
@Inject
tls.use-kubernetes-ca-cert
IamClient client;
mvn quarkus:add-extension
-Dextensions="amazon-kms"
Con guration properties are the same as Amazon DynamoDB but
changing the pre x from dynamodb to kms .
mvn quarkus:add-extension
kms.encrypt(req -> req.keyId(keyArn).plaintext(
-Dextensions="quarkus-amazon-iam"
SdkBytes.fromUtf8String(data))).ciphertextBlob();
You can create new annotations that bind to HTTP methods not }
de ned by the spec.
Exception Mapper
@Produces(MediaType.APPLICATION_JSON)
}
@org.jboss.resteasy.annotations.cache.NoCache
public User me() {} Declarative
@Query
public String getFilm(@Name("filmId") int id)) {}
@Query
public List<Hero> getHeroesWithSurname(
@DefaultValue("Skywalker") String surname) {
}
@Mutation
public Greetings load(Greetings greetings) {
}
}
If name not provided, then query name is resolved from method extendig io.smallrye.mutiny.vertx.core.AbstractVerticle . ssl.key
name. The le path to the corresponding certi cate private key le in
You can see the full schema at /graphql/schema.graphql . Also
GZip Support PEM format.
GraphiQL UI is enabled at dev and test mode at /graphql-ui/ .
You can con gure Quarkus to use GZip in the ssl.key-store
Extension can be con gured with the follwoing paramters pre xed application.properties le using the next properties with An optional key store which holds the certi cate information
with quarkus.smallrye-graphql . quarkus.resteasy su x: instead of specifying separate les.
root-path gzip.enabled
ssl.key-store-type
The rootPath under which queries will be served. (default: EnableGZip. (default: false )
An optional parameter to specify the type of the key store le.
/graphql )
gzip.max-input
ssl.key-store-password
root-path-ui Con gure the upper limit on de ated request body. (default: 10M )
A parameter to specify the password of the key store le.
The path where GraphQL UI is available. (default: /graphql-ui ) (default: password )
GRPC
always-include-ui ssl.trust-store
The path where GraphQL UI is available. (default: /graphql-ui ) Quarkus integrates with gRPC: Trust store which holds the certi cate information of the
certi cates to trust
root-path-ui ./mvnw quarkus:add-extension
Always include the UI. By default this will only be included in dev -Dextensions="quarkus-grpc" ssl.trust-store-type
and test. (default: false ) Parameter to specify type of the trust store le.
enable-ui Then you need to con gure build tool with gRPC plugins. In the ssl.trust-store-password
If GraphQL UI should be enabled. (default: false ) case of Maven, the kr.motd.maven:os-maven-plugin extension and A parameter to specify the password of the trust store le.
org.xolstice.maven.plugins:protobuf-maven-plugin
metrics.enabled ssl.cipher-suites
Protos les are stored at src/main/proto .
Enable metrics. (default: false ) A list of the cipher suites to use.
When java les are created two service implementations are
Vert.X Verticle provided: one with default gRPC API and other with Mutiny support. ssl.protocols
@Inject transport-security.key
host
Vertx vertx;
The path to the private key le.
The gRPC server host. (default: 0.0.0.0 )
public void init(@Observes StartupEvent ev) {
To consume the service:
CountDownLatch latch = new CountDownLatch(1); handshake-timeout
vertx.deployVerticle(BareVerticle::new, The gRPC handshake timeout.
new DeploymentOptions() @GrpcService("hello")
.setConfig( GreeterGrpc.GreeterBlockingStub client;
max-inbound-message-size
new JsonObject()
The max inbound message size in bytes. @GrpcService("hello")
.put("id", "bare")
) io.grpc.Channel channel;
plain-text
)
.thenAccept(x -> latch.countDown()); Use plain text. (default: true )
Some con guration example to set the host and the SSL
latch.countDown(); alpn parameters:
} TWhether ALPN should be used. (default: true )
}
quarkus.grpc.clients.hello.host=localhost
enable-reflection-service quarkus.grpc.clients.hello.plain-text=false
Enables the gRPC Re ection Service. (default: false ) quarkus.grpc.clients.hello.ssl.certificate=src/main/resourc
Verticles can be: es/tls/client.pem
ssl.certificate quarkus.grpc.clients.hello.ssl.key=src/main/resources/tls/c
bare lient.key
The le path to a server certi cate or certi cate chain in PEM
extending io.vertx.core.AbstractVerticle .
format. quarkus.grpc.clients.hello.ssl.trust-store=src/main/resourc
es/tls/ca.pem
mutiny
Fault Tolerance If 3 (4 x 0.75) failures occur among the rolling window of 4
org.acme.quickstart.WorldClock/getNow/Retry/enabled=false
consecutive invocations then the circuit is opened for 1000 ms and
# Disable everything except fallback
Quarkus uses MicroPro le Fault Tolerance spec: then be back to half open. If the invocation succeeds then the
MP_Fault_Tolerance_NonFallback_Enabled=false
circuit is back to closed again.
./mvnw quarkus:add-extension You can use bulkahead pattern to limit the number of concurrent
-Dextensions="io.quarkus:quarkus-smallrye-fault-toleranc access to the same resource. If the operation is synchronous it MicroPro le Fault Tolerance integrates with MicroPro le
e" uses a semaphore approach, if it is asynchronous a thread-pool Metrics spec. You can disable it by setting
one. When a request cannot be processed BulkheadException is MP_Fault_Tolerance_Metrics_Enabled to false.
thrown. It can be used together with any other fault tolerance
annotation.
MicroPro le Fault Tolerance spec uses CDI interceptor and it can Observability
be used in several elements such as CDI bean, JAX-RS resource or
MicroPro le Rest Client. @Bulkhead(5) Health Checks
@Retry(maxRetries = 4,
To do automatic retries on a method: delay = 1000, Quarkus relies on MicroPro le Health spec to provide health
retryOn = BulkheadException.class) checks.
@Path("/api") WorldClock getNow(){}
@RegisterRestClient ./mvnw quarkus:add-extension
public interface WorldClockService { -Dextensions="io.quarkus:quarkus-smallrye-health"
@GET @Path("/json/cet/now")
Fault tolerance annotations:
@Produces(MediaType.APPLICATION_JSON)
@Retry(maxRetries = 2)
Annotation Properties By just adding this extension, an endpoint is registered to /q/health
WorldClock getNow();
} providing a default health check.
@Timeout unit
{
maxRetries , delay , delayUnit , "status": "UP",
You can set fallback code in case of an error by using @Fallback
maxDuration , durationUnit , "checks": [
annotation: @Retry
jitter , jitterDelayUnit , retryOn , ]
abortOn }
@Retry(maxRetries = 1)
@Fallback(fallbackMethod = "fallbackMethod")
WorldClock getNow(){}
@Fallback fallbackMethod To create a custom health check you need to implement the
public WorldClock fallbackMethod() { HealthCheck interface and annotate either with @Readiness (ready to
kafka quarkus.smallrye-health.group-path=/customgroup
Since health checks are CDI beans, you can do: A probe to check kafka connection status. In this case you need
to enable manually by setting quarkus.kafka.health.enabled to
@ApplicationScoped true . Metrics
public class DatabaseHealthCheck {
mongoDB Quarkus can utilize the MicroPro le Metrics spec to provide metrics
@Liveness
A probe to check MongoDB connection status. support.
HealthCheck check1() {
return io.smallrye.health.HealthStatus
neo4j ./mvnw quarkus:add-extension
.up("successful-live"); -Dextensions="io.quarkus:quarkus-smallrye-metrics"
} A probe to check Neo4J connection status.
@Readiness artemis
HealthCheck check2() { A probe to check Artemis JMS connection status. The metrics can be read with JSON or the OpenMetrics format. An
return HealthStatus endpoint is registered automatically at /q/metrics providing default
metrics.
.state("successful-read", this::isReady) kafka-streams
}
Liveness (for stream state) and Readiness (topics created) MicroPro le Metrics annotations:
probes.
private boolean isReady() {}
@Timed
}
vault Tracks the duration.
A probe to check Vault conection status.
@SimplyTimed
You can ping liveness or readiness health checks individually by gRPC Tracks the duration without mean and distribution calculations.
querying /q/health/live or /q/health/ready .
A readiness probe for the gRPC services.
Quarkus comes with some HealthCheck implementations for @Metered
checking service status. Cassandra Tracks the frequency of invocations.
A readiness probe to check Cassandra connection status.
SocketHealthCheck: checks if host is reachable using a @Counted
socket. Redis Counts number of invocations.
UrlHealthCheck: checks if host is reachable using a Http URL A readiness probe to check Redis connection status.
connection. @Gauge
You can disable the automatic generation by setting Samples the value of the annotated object.
InetAddressHealthCheck: checks if host is reachable using <component>.health.enabled to false.
InetAddress.isReachable method. @ConcurrentGauge
quarkus.kafka-streams.health.enabled=false Gauge to count parallel invocations.
@Liveness quarkus.mongodb.health.enabled=false
HealthCheck check1() { quarkus.neo4j.health.enabled=false @Metric
return new UrlHealthCheck("https://www.google.com")
Used to inject a metric. Valid types Meter , Timer , Counter ,
.name("Google-Check");
Histogram . Gauge only on producer methods/ elds.
}
In the case of Vault you can pass parameters to modify the call of
the status endpoint in Vault.
binder.vertx.match-patterns
You can con gure Metrics: You can con gure Micrometer. Pre x is quarkus.micrometer : Comma-separated case-sensitive list of regular expressions
de ning Paths that should be matched and used as tags
enabled
quarkus.smallrye-metrics.path=/mymetrics
Micrometer metrics support. (default: true ) binder.vertx.ignore-patterns
The path to the metrics handler. (default: /q/metrics ) binder-enabled-default Datadog MeterRegistry con guration in Map<String, String>
Vert.x metrics support. JMX registry con guration properties in Map<String, String>
format.
micrometer.compatibility
Apply Micrometer compatibility mode. (default: false ) binder.mp-metrics.enabled
export.prometheus
Micropro le Metrics support.
Prometheus registry con guration properties in Map<String,
quarkus.hibernate-orm.metrics.enabled set to true exposes
String> format.
Hibernate metrics under vendor scope. binder.jvm
Tracing
export.datadog.enabled
Support for export to Datadog Support for Datadog. Quarkus can utilize the MicroPro le OpenTracing spec.
export.prometheus.enabled
Support for export to Prometheus. Requests sent to any endpoint are traced automatically.
This extension includes OpenTracing support and Jaeger tracer. Kafka Tracer Native Executable
Jaeger tracer con guration: Adds a span for each message sent to or received from a Kafka
You can build a native image by using GraalVM. The common use
topic.
case is creating a Docker image so you can execute the next
quarkus.jaeger.service-name=myservice commands:
quarkus.jaeger.sampler-type=const <dependency>
quarkus.jaeger.sampler-param=1 <groupId>io.opentracing.contrib</groupId>
./mvnw package -Pnative -Dquarkus.native.container-build=tr
quarkus.jaeger.endpoint=http://localhost:14268/api/traces <artifactId>opentracing-kafka-client<</artifactId>
ue
quarkus.jaeger.metrics.enabled=true </dependency>
OpenTelemetry
publish-debug-build-process-port
Inclusion of resources resources.includes
If the debug port should be published when building with docker A comma separated list of globs to match resource paths that
By default, no resources are included in native executable. and debug-build-process. (default: true ) should be added to the native image.
quarkus.native.resources.includes allows to set glob expressions to
include resources based on src/main/resources path. cleanup-server resources.excludes
If the native image server should be restarted. A comma separated list of globs to match resource paths that
Given src/main/resources/foo/selected.png :
should exclude to the native image.
enable-isolates
quarkus.native.resources.includes=foo/**
If isolates should be enabled. (default: true ) debug.enabled
enable-http-url-handler If the bytecode of all proxies should be dumped for inspection. Pre x is quarkus.container-image :
enable-https-url-handler If this build should be done using a container runtime. The group/repository of the image. (default: the ${user.name} )
If this build is done using a remote docker daemon. The name of the image. (default: the application name)
enable-all-security-services
If all security services should be added to the native image. tag
builder-image
The docker image to use to do the image build. The tag of the image. (default: the application version)
user-language
De nes the user language used for building the native additional-tags
container-runtime
executable.
The container runtime that is used to do an image based build. Additional tags of the container image.
user-country ( docker , podman )
registry
De nes the user country used for building the native executable.
container-runtime-options The registry to use for pushing. (default: docker.io )
insecure user
Container Images Creation integrates with Kubernetes
extension, so no need of extra Kubernetes properties.
Flag to allow insecure registries. (default: false ) The user to use in generated image.
Generated resource is integrated with MicroPro le Health
build always-cache-base-image
annotations.
Boolean to set if image should be built. (default: false ) Controls the optimization which skips downloading base image
layers that exist in a target registry (default: false ). Also, you can customize the generated resource by setting the new
push values in application.properties :
Boolean to set if image should be pushed. (default: false ) appcds-builder-image
./mvnw quarkus:add-extensions
platforms quarkus.kubernetes.labels.foo=bar
-Dextensions="quarkus-container-image-jib"
List of target platforms. (ie linux/amd64 ).
quarkus.kubernetes.readiness-probe.period-seconds=45
Quarkus copies any le under src/main/jib into the built container Docker
quarkus.kubernetes.mounts.github-token.path=/deployment/git
image. hub
./mvnw quarkus:add-extensions quarkus.kubernetes.mounts.github-token.read-only=true
Pre x is quarkus.container-image-jib : -Dextensions="quarkus-container-image-docker"
quarkus.kubernetes.secret-volumes.github-token.volume-name=
base-jvm-image
github-token
The base image to use for the jib build. (default: fabric8/java-
Pre x is quarkus.container-image-s2i : quarkus.kubernetes.secret-volumes.github-token.secret-name=
alpine-openjdk8-jre ) greeting-security
dockerfile-jvm-path quarkus.kubernetes.secret-volumes.github-token.default-mode
base-native-image =420
Path to the JVM Docker le. (default:
The base image to use for the native build. (default: ${project.root}/src/main/docker/Dockerfile.jvm )
registry.access.redhat.com/ubi8/ubi-minimal ) quarkus.kubernetes.config-map-volumes.github-token.config-m
ap-name=my-secret
dockerfile-native-path
jvm-arguments
Path to the native Docker le. (default: quarkus.kubernetes.expose=true
The arguments to pass to java. (default: - ${project.root}/src/main/docker/Dockerfile.native ) quarkus.kubernetes.ingress.expose=true
Dquarkus.http.host=0.0.0.0,-
quarkus.kubernetes.ingress.host=example.com
Djava.util.logging.manager=org.jboss.logmanager.LogManager ) S2I
quarkus.kubernetes.env.vars.my-env-var=foobar
native-arguments
./mvnw quarkus:add-extensions quarkus.kubernetes.env.configmaps=my-config-map,another-con
The arguments to pass to the native application. (default: - -Dextensions="quarkus-container-image-s2i" fig-map
Dquarkus.http.host=0.0.0.0 ) quarkus.kubernetes.env.secrets=my-secret,my-other-secret
environment-variables quarkus.kubernetes.resources.requests.memory=64Mi
Pre x is quarkus.container-image-docker :
Map of environment variables. quarkus.kubernetes.resources.requests.cpu=250m
base-jvm-image
quarkus.kubernetes.resources.limits.memory=512Mi
jvm-entrypoint
quarkus.kubernetes.resources.limits.cpu=1000m
The base image to use for the s2i build. (default: fabric8/java-
A custom entry point of the container image in JVM mode. alpine-openjdk8-jre )
Custom labels to add to the generated image. Kubernetes The generated manifest use the Kubernetes recommended labels
and annotations.
base-registry-username Quarkus can use Dekorate to generate Kubernetes resources.
The username to use to authenticate with the registry used to
pull the base JVM image. ./mvnw quarkus:add-extensions
-Dextensions="quarkus-kubernetes"
base-registry-password
prometheus.io/scrape: "true"
If you set this ag to true , the build and push ags from ./mvnw quarkus:add-extensions
prometheus.io/path: /metrics
container-image are set to true too. -Dextensions="quarkus-kubernetes-config"
prometheus.io/port: "8080"
-Dextensions="quarkus-kubernetes-service-binding" The application will attempt to look up the con guration from the
List of con guration options: API server. (default: false )
kubernetes fail-on-missing-config
https://quarkus io/guides/kubernetes#con guration options
The application will not start if any of the con gured con g watch-reconnect-interval
@Inject
sources cannot be located. (default: true ) Watch reconnect interval. (default: PT1S ) KubernetesClient client;
secrets.enabled
CustomResourceDefinitionList crds = client
request-timeout
.customResourceDefinitions()
Whether or not con guration can be read from secrets. (default: Maximum amount of time to wait for a request. (default: PT10S ) .list();
false )
no-proxy @QuarkusTestResource(KubernetesMockServerTestResource.clas
master-url
s)
URL of Kubernetes API server. IP addresses or hosts to exclude from proxying
@QuarkusTest
public class KubernetesClientTest {
namesapce Or programmatically:
Default namespace. @MockServer
@Dependent private KubernetesMockServer mockServer;
ca-cert-file public class KubernetesClientProducer {
username
AWS Lambda
Username.
Quarkus integrates with Amazon Lambda.
password
Password
The Cloud Event type that triggers the function is defaultChain . It
./mvnw quarkus:add-extension mvn archetype:generate \
generates a response that triggers a new Cloud Event whose type is
-Dextensions="io.quarkus:quarkus-amazon-lambda" -DarchetypeGroupId=io.quarkus \
defaultChain.output and the event source is defaultChain .
-DarchetypeArtifactId=quarkus-azure-functions-http-archet
ype \
It can be changed by using the next properties:
-DarchetypeVersion={version}
And then implement
com.amazonaws.services.lambda.runtime.RequestHandler interface. quarkus.funqy.knative-events.mapping.defaultChain.trigger=c
onfigChain.output
public class TestLambda Funqy quarkus.funqy.knative-events.mapping.defaultChain.response-
implements RequestHandler<MyInput, MyOutput> { type=annotated
@Override Quarkus Funqy is part of Quarkus’s serverless strategy and aims to quarkus.funqy.knative-events.mapping.defaultChain.response-
public MyInput handleRequest(MyOutput input, provide a portable Java API to write functions deployable to various source=configChain
Context context) { FaaS environments like AWS Lambda, Azure Functions, Knative, and
} Knative events.
}
The properties are of form: quarkus.funqy.knative-events.mapping.
public class GreetingFunction { {function name}. .
theme
And web sockets classes can be used:
Swagger UI theme to be used.
@ServerEndpoint("/chat/{username}")
footer
@ApplicationScoped
public class ChatSocket { A footer for the html page. Nothing by default.
@OnOpen deep-linking
public void onOpen(Session session, Enables deep linking for tags and operations.
@PathParam("username") String username) {}
display-operation-id
@OnClose
Controls the display of operationId in operations list.
public void onClose(..) {}
default-models-expand-depth
@OnError
public void onError(..., Throwable throwable) {} The default expansion depth for models.
@OnMessage default-model-expand-depth
public void onMessage(...) {} The default expansion depth for the model on the model-example
section.
}
default-model-rendering
Controls how the model is shown when the API is rst rendered.
OpenAPI
display-request-duration
Quarkus can expose its API description as OpenAPI spec and test it Controls the display of the request duration (in milliseconds) for
using Swagger UI. "Try it out" requests.
Then you only need to access to /openapi to get OpenAPI v3 spec filter
of services. Enables ltering.
Provides a mechanism to be noti ed when Swagger UI has description="POJO that represents a developer.")
nished rendering a newly provided de nition. public class Developer { basic-security-scheme-value
@Schema(required = true, example = "Alex") Add a scheme value to the Basic HTTP Security Scheme.
syntax-highlight private String name; (default: basic )
}
Set to false to deactivate syntax highlighting of payloads and
cURL command. jwt-security-scheme-value
@POST
Add a scheme value to the JWT Security Scheme. (default:
@Path("/developer")
oauth2-redirect-url bearer )
@Operation(summary = "Create deeloper",
OAuth redirect URL. description = "Only be done by admin.")
jwt-bearer-format
public Response createDeveloper(
request-interceptor @RequestBody(description = "Developer object", Add a bearer format to the JWT Security Scheme. (default: JWT )
Function to intercept remote de nition, "Try it out", and OAuth 2.0 required = true,
requests. content = @Content(schema = oidc-open-id-connect-url
@Schema(implementation = Developer.class))) Add a openIdConnectUrl value to the OIDC Security Scheme
request-curl-options Developer developer)
persist-authorization store-schema-directory
It persists authorization data and it would not be lost on browser The generated OpenAPI schema documents will be stored here And then you can use them to send an email:
close/refresh. on build.
mailer.send(
layout security-scheme Mail.withText("to@acme.org", "Subject", "Body")
The name of a component available via the plugin system to use Add a certain SecurityScheme with con g. ( basic , jwt , oidc , );
as the top-level layout for Swagger UI. oauth2Implicit )
Max open
mailer.max-pool-size 10
If you are using quarkus-resteasy-mutiny , you can return connections .
io.smallrye.mutiny.Uni type. Scheduled Tasks
Mail class contains methods to add cc , bcc , headers , bounce Hostname for You can schedule periodic tasks with Quarkus.
address , reply to , attachments , inline attachments and html body . mailer.own-host-name HELO/EHLO and
Message-ID
@ApplicationScoped
mailer.send(Mail.withHtml("to@acme.org", "Subject", body) public class CounterBean {
.addInlineAttachment("quarkus.png",
Connection pool
new File("quarkus.png"), mailer.keep-alive true @Scheduled(every="10s", delayed="1s")
enabled.
"image/png", "<my-image@quarkus.io>")); void increment() {}
List of Mailer parameters. quarkus. as a pre x is skipped in the next mailer.key-store Path of the key store. morning.check.cron.expr=0 15 10 * * ?
table.
mailer.key-store-
Parameter Default Description Key store password. By default Quarkus expresion is used, but you can change that by
password
setting quarkus.scheduler.cron-type property.
mailer.from Default address.
if you enable SSL for the mailer and you want to build a
quarkus.scheduler.cron-type=unix
native executable, you will need to enable the SSL support
Emails not sent, just quarkus.ssl.native=true .
false in prod , true in
mailer.mock printed and stored in
dev and test .
a MockMailbox . Testing org.quartz.Scheduler can be injected as any other bean and
scehdule jobs programmatically.
If is set to true , which is the default value in
quarkus.mailer.mock
mailer.bounce- devand test mode, you can inject MockMailbox to get the sent @Inject
Default address. messages.
address org.quartz.Scheduler quartz;
quartz.scheduleJob(job, trigger);
mailer.host mandatory SMTP host.
Quarkus integrates with Apache Tika to detect and extract When running in native mode, make sure to con gure SSL @ReadLock
metadata/text from different le types: access correctly quarkus.ssl.native=true (Native and SSL). public int getNumberOfBookings() {
return numberOfBookings;
./mvnw quarkus:add-extension Web Resources }
-Dextensions="quarkus-tika"
You can serve web resources with Quarkus. You need to place web @WriteLock
resources at src/main/resources/META-INF/resources and then they public void makeBooking(String details) {
are accessible (ie http://localhost:8080/index.html) numberOfBookings += 1;
@Inject }
io.quarkus.tika.TikaParser parser; By default static resources as served under the root context. You }
can change this by using quarkus.http.root-path property.
@POST
@Path("/text")
@Consumes({ "text/plain", "application/pdf",
Transactional Memory Any member is saved/restored automatically ( @State is not
"application/vnd.oasis.opendocument.text" }) mandatory). You can use @NotState to avoid behaviour.
Quarkus integrates with the Software Transactional Memory (STM)
@Produces(MediaType.TEXT_PLAIN)
implementation provided by the Narayana project. Transaction boundaries
public String extractText(InputStream stream) {
return parser.parse(stream).getText();
Declarative
} ./mvnw quarkus:add-extension
-Dextensions="narayana-stm"
@NestedTopLevel : De nes that the container will create a new
top-level transaction for each method invocation.
You can con gure Apache Tika in application.properties le by
Transactional objects must be interfaces and annotated with @Nested :De nes that the container will create a new top-level
using next properties pre xed with quarkus :
org.jboss.stm.annotations.Transactional . or nested transaction for each method invocation.
Parameter Default Description
Programmatically
@Transactional
Path to the Tika @NestedTopLevel
tika.tika-config- AtomicAction aa = new AtomicAction();
tika-config.xml con guration public interface FlightService {
path
resource. int getNumberOfBookings();
aa.begin();
void makeBooking(String details);
{
}
CSV of the try {
abbreviated or full flightService.makeBooking("BA123 ...");
quarkus.tika.parsers parser class to be taxiService.makeBooking("East Coast Taxis ...");
The pessimistic strategy is the default one, you can change to
loaded by the
extension. optimistic by using @Optimistic . aa.commit();
} catch (Exception e) {
Then you need to create the object inside org.jboss.stm.Container .
aa.abort();
The document may }
tika.append-embedded- have other embedded Container<FlightService> container = new Container<>(); }
true
content documents. Set if FlightServiceImpl instance = new FlightServiceImpl();
autmatically append. FlightService flightServiceProxy = container.create(instanc
e);
Quartz
JGit Quarkus integrates with Quartz to schedule periodic clustered
The implementation of the service sets the locking and what needs
tasks.
Quarkus integrates with JGit to integrate with Git repositories: to be saved/restored:
./mvnw quarkus:add-extension
./mvnw quarkus:add-extension
-Dextensions="quartz"
-Dextensions="quarkus-jgit"
force-start
To render the template:
The scheduler will be started even if no scheduled business
To con gure in clustered mode vida DataSource:
methods are found.
public class Item {
quarkus.datasource.url=jdbc:postgresql://localhost/quarkus_ start-mode public String name;
test public BigDecimal price;
Scheduler can be started in different modes: normal , forced or
quarkus.datasource.driver=org.postgresql.Driver }
halted . (default: normal )
# ...
@Inject
quarkus.quartz.clustered=true Qute io.quarkus.qute.Template item;
quarkus.quartz.store-type=db
Qute is a templating engine designed speci cally to meet the @GET
Quarkus needs. Templates should be placed by default at @Path("{id}")
src/main/resources/templates aand subdirectories. @Produces(MediaType.TEXT_HTML)
You need to de ne the datasource used by clustered mode
public TemplateInstance get(@PathParam("id") Integer id) {
and also import the database tables following the Quartz
./mvnw quarkus:add-extension return item.data("item", service.findItem(id));
schema.
-Dextensions="quarkus-resteasy-qute" }
Class name for the job. First line is not mandatory but helps on doing property checks at @TemplateExtension
compilation time. public class MyExtensions {
job-listeners.<name>.property-name static BigDecimal discountedPrice(Item item) {
Including templates passing parameters: return item.price.multiply(new BigDecimal("0.9"));
The properties passed to the class.
}
}
plugins.<name>.class
Qute for syntax supports any instance of Iterable , Map.EntrySet , There are 3 methods to inject the message:
Stream or Integer .
MessageBundles.get(AppMessages.class).hello_name("Lucie"); Content Filters
{#for i in total}
{i}:
Content lters can be used to modify the template contents before
{/for}
parsing.
or
void configureEngine(@Observes EngineBuilder builder) {
@Inject AppMessages app; builder.addParserHook(new ParserHook() {
The next map methods are supported:
@Override
app.hello_name("Lucie"); public void beforeParsing(ParserHelper parserHelper)
{#for key in map.keySet} {
{#for value in map.values} parserHelper.addContentFilter(contents -> content
{map.size} s.replace("${", "$\\{"));
or
{#if map.isEmpty} }
{map['foo'] });
<p>{msg:hello_name('Lucie')}</p>
}
{#switch person.name}
{#case 'John'}
or @Inject
MailTemplate hello;
Hey John! msg_de.properties
{#case 'Mary'}
CompletionStage<Void> c = hello.to("to@acme.org")
Hey Mary! hello_name=Hallo {name}!
.subject("Hello from Qute template")
{/switch}
.data("name", "John")
.send();
You can render programmaticaly the templates too:
{#when items.size}
{#is 1} (1) // file located at src/main/resources/templates/reports/v1/ INFO: Template located at src/main/resources/templates/hello.
There is exactly one item! report_01.{} [html|txt] .
{#is > 10} (2) @ResourcePath("reports/v1/report_01")
There are more than 10 items! Template report;
Sentry
{#else} (3)
There are 2 -10 items! String output = report
Quarkus integrates with Sentry for logging errors into an error
{/when} .data("samples", service.get())
monitoring system.
.render();
./mvnw quarkus:add-extension
Following operators can be used either in when and switch : not, ne, -Dextensions="quarkus-logging-sentry"
!= , gt, > , ge, >= , lt, < , le, <= , in , ni, !in . Value Resolvers
And the con guration to send all errors occuring in the package @ApplicationScoped
quarkus.banner.enabled
org.example to Sentrty with DSN https://abcd@sentry.io/1234 : Enables banner. (default : true )
public class CachedBean {
Quarkus integrates with Jsch for SSH communication. A classpath resource to read the solver con guration XML. Not
initial-capacity mandatory.
Minimum total size for the internal data structures.
./mvnw quarkus:add-extension
solver.environment-mode
-Dextensions="quarkus-jsch"
maximum-size Enable runtime assertions to detect common bugs in your
Maximum number of entries the cache may contain. implementation during development. Possible values:
FAST_ASSERT , FULL_ASSERT , NON_INTRUSIVE_FULL_ASSERT ,
JSch jsch = new JSch(); expire-after-write NON_REPRODUCIBLE , REPRODUCIBLE . (default: REPRODUCIBLE )
Session session = jsch.getSession(null, host, port); Speci es that each entry should be automatically removed from
session.setConfig("StrictHostKeyChecking", "no"); the cache once a xed duration has elapsed after the entry’s solver.move-thread-count
session.connect(); creation, or last write. Enable multithreaded solving for a single problem. Possible
values: MOVE_THREAD_COUNT_NONE , MOVE_THREAD_COUNT_AUTO , a number
expire-after-access or formula based on the available processors. (default:
MOVE_THREAD_COUNT_NONE )
Cache Speci es that each entry should be automatically removed from
the cache once a xed duration has elapsed after the entry’s
Quarkus can cache method calls by using as key the tuple (method creation, or last write. solver.termination.spent-limit
threadContext.withContextCapture(..) TrustStore to be used containing the SSL certi cate used by Amazon SES
.thenApplyAsync(r -> {}, managedExecutor); Consul agent.
mvn quarkus:add-extension
trust-store-password -Dextensions="amazon-ses"
If you are going to use security in a reactive environment you will Password of TrustStore to be used containing the SSL certi cate
likely need Smallrye Content Propagation to propagate the identity used by Consul agent.
throughout the reactive callback.
key-password @Inject
Con guration from HasiCorp Consul Password to recover key from KeyStore for SSL client
software.amazon.awssdk.services.ses.SesClient sesClient;
agent.connection-timeout
"Key": "config/consul-test",
"Value": "greeting.message=Hello from Consul" Connection timeout. (default: 10S ) or Apache HTTP:
agent.read-timeout <dependency>
Possible con guration parameters, pre xed with quarkus.consul- Reading timeout. (default: 60S ) <groupId>software.amazon.awssdk</groupId>
config : <artifactId>apache-client</artifactId>
Amazon Alexa </dependency>
enabled
The application will attempt to look up the con guration from You can use Amazon Alexa by adding the extension:
Consul. (default: false )
quarkus.ses.sync-client.type=apache
./mvnw quarkus:add-extension
prefix -Dextensions="quarkus-amazon-alexa"
Common pre x that all keys share when looking up the keys from
Or async:
Consul. The pre x is not included in the keys of the user
con guration
WebJar Locator
raw-value-keys
<dependency> Spring DI Spring Boot Con guration
<groupId>software.amazon.awssdk</groupId>
<artifactId>netty-nio-client</artifactId> Quarkus provides a compatibility layer for Spring dependency Quarkus provides a compatibility layer for Spring Boot
</dependency> injection. ConfigurationProperties .
Jbang Some examples of what you can do. Notice that annotations are
@ConfigurationProperties("example")
the Spring original ones.
public final class ClassProperties {
Creating an initial script:
@Configuration
private String value;
public class AppConfiguration {
jbang scripting/quarkusapp.java private AnotherClass anotherClass;
@Bean(name = "capitalizeFunction")
// getters/setters
public StringFunction capitalizer() {
Adding Quarkus dependencies in script: }
return String::toUpperCase;
}
//DEPS io.quarkus:quarkus-resteasy:{quarkus-version} }
example.value=class-value
example.anotherClass.value=true
Put some Quarkus CLI code: Or as a component:
@Component("noopFunction")
@Path("/hello")
public class NoOpSingleStringFunction Spring Cloud Con g Client
@ApplicationScoped
implements StringFunction {
public class quarkusapp {
} Quarkus integrates Spring Cloud Con g Client and MicroPro le
@GET
Con g spec.
public String sayHello() {
return "hello";
./mvnw quarkus:add-extension
} Also as a service and injection properties from
-Dextensions="quarkus-spring-cloud-config-client"
public static void main(String[] args) { application.properties .
Quarkus.run(args);
} @Service
} public class MessageProducer { You need to con gure the extension:
@Value("${greeting.message}") quarkus.spring-cloud-config.uri=http://localhost:8089
To run the script: String message; quarkus.spring-cloud-config.username=user
quarkus.spring-cloud-config.password=pass
} quarkus.spring-cloud-config.enabled=true
jbang quarkusapp.java
@Autowired @Qualifier("noopFunction") Base URI where the Spring Cloud Con g Server is available.
StringFunction noopStringFunction; (default: localhost:8888 )
label
INFO: Of course you still need to add the JDBC driver, and con gure
The label to be used to pull remote con guration properties. it in application.properties . What is currently unsupported:
@GetMapping("/{name}")
Repository fragments is also supported:
public Greeting hello(@PathVariable(name = "name")
import java.util.Optional;
String name) {
public interface PersonRepository import org.springframework.data.repository.CrudRepository;
return new Greeting(greetingBean.greet(name));
extends JpaRepository<Person, Long>, PersonFragment { import org.springframework.data.rest.core.annotation.Reposi
}
toryRestResource;
}
void makeNameUpperCase(Person person); import org.springframework.data.rest.core.annotation.RestRe
} source;
hasRole
@org.springframework.cache.annotation.Cacheable("someCache"
@PreAuthorize("hasRole('admin')") )
public Greeting greet(String name) {}
@PreAuthorize("hasRole(@roles.USER)") where roles is a bean
de ned with @Component annotation and USER is a public eld
of the class.
Quarkus provides compatibility with the following Spring Cache
hasAnyRole annotations:
@PreAuthorize("permitAll()") @CacheEvict
https://quarkus.io/guides/ @alexsotob
Java Champion and Director of DevExp at Red Hat
https://www.youtube.com/user/lordofthejars