id
int64
0
10.2k
text_id
stringlengths
17
67
repo_owner
stringclasses
232 values
repo_name
stringclasses
295 values
issue_url
stringlengths
39
89
pull_url
stringlengths
37
87
comment_url
stringlengths
37
94
links_count
int64
1
2
link_keyword
stringclasses
12 values
issue_title
stringlengths
7
197
issue_body
stringlengths
45
21.3k
base_sha
stringlengths
40
40
head_sha
stringlengths
40
40
diff_url
stringlengths
120
170
diff
stringlengths
478
132k
changed_files
stringlengths
47
2.6k
changed_files_exts
stringclasses
22 values
changed_files_count
int64
1
22
java_changed_files_count
int64
1
22
kt_changed_files_count
int64
0
0
py_changed_files_count
int64
0
0
code_changed_files_count
int64
1
22
repo_symbols_count
int64
32.6k
242M
repo_tokens_count
int64
6.59k
49.2M
repo_lines_count
int64
992
6.2M
repo_files_without_tests_count
int64
12
28.1k
changed_symbols_count
int64
0
36.1k
changed_tokens_count
int64
0
6.5k
changed_lines_count
int64
0
561
changed_files_without_tests_count
int64
1
17
issue_symbols_count
int64
45
21.3k
issue_words_count
int64
2
1.39k
issue_tokens_count
int64
13
4.47k
issue_lines_count
int64
1
325
issue_links_count
int64
0
19
issue_code_blocks_count
int64
0
31
pull_create_at
timestamp[s]
repo_stars
int64
10
44.3k
repo_language
stringclasses
8 values
repo_languages
stringclasses
296 values
repo_license
stringclasses
2 values
2,315
quarkusio/quarkus/29557/29542
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/29542
https://github.com/quarkusio/quarkus/pull/29557
https://github.com/quarkusio/quarkus/pull/29557
1
fixes
CORS Rejected Error on same-origin requests when CORS is enabled
### Describe the bug Since Quarkus 2.14.2, requests return status `403` if CORS is enabled and the origin is not in the list of allowed CORS origins, even if the request is not cross-origin at all. ### Expected behavior CORS Settings should have no impact on same-origin requests. ### Actual behavior Enabling CORS seems to prevent all requests with an `Origin`-header that isn't explicitly whitelisted, even same-origin requests. `GET`-Requests may still work as browsers don't add the `Origin`-Header to same-origin `GET`-requests. ### How to Reproduce? Reproducer: [cors.zip](https://github.com/quarkusio/quarkus/files/10106358/cors.zip) See the test or just start the project and try to use the Dev UI - anything that isn't a plain GET request like the attempts to establish websockets for test and logstream will fail. ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.14.2.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
4228a370eeec6df2282f19536fcec180a5955d4a
3c18d3941345339cc072248f0e145e1140ad0ad8
https://github.com/quarkusio/quarkus/compare/4228a370eeec6df2282f19536fcec180a5955d4a...3c18d3941345339cc072248f0e145e1140ad0ad8
diff --git a/extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/cors/CORSHandlerTestWildcardOriginCase.java b/extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/cors/CORSHandlerTestWildcardOriginCase.java index bea0ee15783..c1852e10dd8 100644 --- a/extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/cors/CORSHandlerTestWildcardOriginCase.java +++ b/extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/cors/CORSHandlerTestWildcardOriginCase.java @@ -49,6 +49,60 @@ void corsNotMatchingOrigin() { .header("Access-Control-Allow-Credentials", "false"); } + @Test + void corsSameOriginRequest() { + String origin = "http://localhost:8081"; + given().header("Origin", origin) + .get("/test").then() + .statusCode(200) + .header("Access-Control-Allow-Origin", origin); + } + + @Test + void corsInvalidSameOriginRequest1() { + String origin = "http"; + given().header("Origin", origin) + .get("/test").then() + .statusCode(403) + .header("Access-Control-Allow-Origin", nullValue()); + } + + @Test + void corsInvalidSameOriginRequest2() { + String origin = "http://local"; + given().header("Origin", origin) + .get("/test").then() + .statusCode(403) + .header("Access-Control-Allow-Origin", nullValue()); + } + + @Test + void corsInvalidSameOriginRequest3() { + String origin = "http://localhost"; + given().header("Origin", origin) + .get("/test").then() + .statusCode(403) + .header("Access-Control-Allow-Origin", nullValue()); + } + + @Test + void corsInvalidSameOriginRequest4() { + String origin = "http://localhost:9999"; + given().header("Origin", origin) + .get("/test").then() + .statusCode(403) + .header("Access-Control-Allow-Origin", nullValue()); + } + + @Test + void corsInvalidSameOriginRequest5() { + String origin = "https://localhost:8483"; + given().header("Origin", origin) + .get("/test").then() + .statusCode(403) + .header("Access-Control-Allow-Origin", nullValue()); + } + @Test @DisplayName("Returns false 'Access-Control-Allow-Credentials' header on matching origin '*'") void corsMatchingOriginWithWildcard() { diff --git a/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/cors/CORSFilter.java b/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/cors/CORSFilter.java index 4a7fee1a14e..d9cba6755d0 100644 --- a/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/cors/CORSFilter.java +++ b/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/cors/CORSFilter.java @@ -1,5 +1,6 @@ package io.quarkus.vertx.http.runtime.cors; +import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -176,7 +177,7 @@ public void handle(RoutingContext event) { } boolean allowsOrigin = isConfiguredWithWildcard(corsConfig.origins) || corsConfig.origins.get().contains(origin) - || isOriginAllowedByRegex(allowedOriginsRegex, origin); + || isOriginAllowedByRegex(allowedOriginsRegex, origin) || isSameOrigin(request, origin); if (allowsOrigin) { response.headers().set(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, origin); @@ -210,4 +211,18 @@ public void handle(RoutingContext event) { } } } + + private static boolean isSameOrigin(HttpServerRequest request, String origin) { + String absUriString = request.absoluteURI(); + if (absUriString.startsWith(origin)) { + // Make sure that Origin URI contains scheme, host, and port. + // If no port is set in Origin URI then the request URI must not have it set either + URI baseUri = URI.create(absUriString.substring(0, origin.length())); + if (baseUri.getScheme() != null && baseUri.getHost() != null + && (baseUri.getPort() > 0 || URI.create(absUriString).getPort() == -1)) { + return true; + } + } + return false; + } }
['extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/cors/CORSHandlerTestWildcardOriginCase.java', 'extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/cors/CORSFilter.java']
{'.java': 2}
2
2
0
0
2
23,800,932
4,680,639
607,376
5,588
907
189
17
1
1,208
172
291
43
1
0
1970-01-01T00:27:49
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,313
quarkusio/quarkus/29596/29592
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/29592
https://github.com/quarkusio/quarkus/pull/29596
https://github.com/quarkusio/quarkus/pull/29596
1
closes
[infinispan-client] cache configuration not available while bootstrapping dev mode
### Describe the bug Hi, I am trying to use infinispan cache configuration that was recently added to application yaml [1]. I am trying to use it in dev mode and this results in NPE while bootstraping. Testing with the configured cache is working well. `2022-11-30 19:47:52,653 ERROR [io.qua.run.Application] (Quarkus Main Thread) Failed to start application (with profile dev): java.lang.NullPointerException: Cannot invoke "java.net.URL.toURI()" because "configFile" is null at io.quarkus.infinispan.client.runtime.InfinispanClientProducer.builderFromProperties(InfinispanClientProducer.java:239) at io.quarkus.infinispan.client.runtime.InfinispanClientProducer.initialize(InfinispanClientProducer.java:66) at io.quarkus.infinispan.client.runtime.InfinispanClientProducer.remoteCacheManager(InfinispanClientProducer.java:367)` I debugged the issue and it looks like the classloader that is used to retrieve configuration file as a resource can't do it (`Quarkus Base Runtime ClassLoader: DEV`) but if I get the Thread's classLoader(`Quarkus Runtime ClassLoader: DEV restart no:0`) I am able to do so. [1] https://quarkus.io/guides/infinispan-client#quarkus-infinispan-client_quarkus.infinispan-client.cache.-cache-.configuration-uri ### Expected behavior Dev mode will start correctly and Infinispan server will be configured with the cache specified in application.yaml. ### Actual behavior Starting dev mode throws NPE on failing to find resource defined in the application.yaml ### How to Reproduce? I've created a simple reproducer. 1. git clone https://github.com/michalovjan/infinispan-bug-reproducer.git 2. mvn clean install quarkus:dev ### Output of `uname -a` or `ver` Darwin jmichalo-mac 22.1.0 Darwin Kernel Version 22.1.0: Sun Oct 9 20:14:30 PDT 2022; root:xnu-8792.41.9~2/RELEASE_ARM64_T8103 arm64 ### Output of `java -version` openjdk 17.0.2 2022-01-18 OpenJDK Runtime Environment Temurin-17.0.2+8 (build 17.0.2+8) OpenJDK 64-Bit Server VM Temurin-17.0.2+8 (build 17.0.2+8, mixed mode) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.14.2.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.6 (84538c9988a25aec085021c365c560670ad80f63) Maven home: /Users/jmichalo/.m2/wrapper/dists/apache-maven-3.8.6-bin/67568434/apache-maven-3.8.6 Java version: 17.0.2, vendor: Eclipse Adoptium, runtime: /Users/jmichalo/.sdkman/candidates/java/17.0.2-tem Default locale: en_CZ, platform encoding: UTF-8 OS name: "mac os x", version: "13.0.1", arch: "aarch64", family: "mac" ### Additional information _No response_
c69d8d8e661dbe8fbab35060d892b1cf60601410
5deeb182e32e6bb9c9883bc38d03e6abe1d922aa
https://github.com/quarkusio/quarkus/compare/c69d8d8e661dbe8fbab35060d892b1cf60601410...5deeb182e32e6bb9c9883bc38d03e6abe1d922aa
diff --git a/extensions/infinispan-client/runtime/src/main/java/io/quarkus/infinispan/client/runtime/InfinispanClientProducer.java b/extensions/infinispan-client/runtime/src/main/java/io/quarkus/infinispan/client/runtime/InfinispanClientProducer.java index f59c6dbd49a..16e1bfa30f5 100644 --- a/extensions/infinispan-client/runtime/src/main/java/io/quarkus/infinispan/client/runtime/InfinispanClientProducer.java +++ b/extensions/infinispan-client/runtime/src/main/java/io/quarkus/infinispan/client/runtime/InfinispanClientProducer.java @@ -233,7 +233,7 @@ private ConfigurationBuilder builderFromProperties(Properties properties) { String cacheName = cache.getKey(); InfinispanClientRuntimeConfig.RemoteCacheConfig remoteCacheConfig = cache.getValue(); if (remoteCacheConfig.configurationUri.isPresent()) { - URL configFile = InfinispanClientProducer.class.getClassLoader() + URL configFile = Thread.currentThread().getContextClassLoader() .getResource(remoteCacheConfig.configurationUri.get()); try { builder.remoteCache(cacheName).configurationURI(configFile.toURI());
['extensions/infinispan-client/runtime/src/main/java/io/quarkus/infinispan/client/runtime/InfinispanClientProducer.java']
{'.java': 1}
1
1
0
0
1
23,801,653
4,680,876
607,368
5,588
162
24
2
1
2,642
285
776
51
2
0
1970-01-01T00:27:49
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,301
quarkusio/quarkus/29883/29836
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/29836
https://github.com/quarkusio/quarkus/pull/29883
https://github.com/quarkusio/quarkus/pull/29883
1
fixes
ArC - improve the way a wildcard in a producer return/field type is detected
### Describe the bug It seems that we don't search through the "nested" parameterized types. Note that wildcards are not legal in a a producer return/field type. See also https://jakarta.ee/specifications/cdi/2.0/cdi-spec-2.0.html#producer_field. This is a follow-up of https://github.com/quarkusio/quarkus/pull/4756. ### Expected behavior _No response_ ### Actual behavior _No response_ ### How to Reproduce? Replace the return type of `io.quarkus.arc.processor.TypesTest.Producer.produce()`; `List<? extends Number>` -> `List<Set<? extends Number>>` ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
340b85c1b8b005750d6009a1990f59a77f32bff5
b39b96b22f22cda141ee9e04088eeb34814c1119
https://github.com/quarkusio/quarkus/compare/340b85c1b8b005750d6009a1990f59a77f32bff5...b39b96b22f22cda141ee9e04088eeb34814c1119
diff --git a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/Types.java b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/Types.java index 0b914cad9ef..1aee1542711 100644 --- a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/Types.java +++ b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/Types.java @@ -432,6 +432,30 @@ static List<Type> getResolvedParameters(ClassInfo classInfo, Map<String, Type> r } } + static void detectWildcardAndThrow(Type type, AnnotationTarget producerFieldOrMethod) { + if (producerFieldOrMethod == null) { + // not a producer, no further analysis required + return; + } + if (type.kind().equals(Kind.WILDCARD_TYPE)) { + throw new DefinitionException("Producer " + + (producerFieldOrMethod.kind().equals(AnnotationTarget.Kind.FIELD) ? "field " : "method ") + + producerFieldOrMethod + + " declared on class " + + (producerFieldOrMethod.kind().equals(AnnotationTarget.Kind.FIELD) + ? producerFieldOrMethod.asField().declaringClass().name() + : producerFieldOrMethod.asMethod().declaringClass().name()) + + + " contains a parameterized type with a wildcard. This type is not a legal bean type" + + " according to CDI specification."); + } else if (type.kind().equals(Kind.PARAMETERIZED_TYPE)) { + for (Type t : type.asParameterizedType().arguments()) { + // recursive check of all parameterized types + detectWildcardAndThrow(t, producerFieldOrMethod); + } + } + } + static Set<Type> getTypeClosure(ClassInfo classInfo, AnnotationTarget producerFieldOrMethod, Map<String, Type> resolvedTypeParameters, BeanDeployment beanDeployment, BiConsumer<ClassInfo, Map<String, Type>> resolvedTypeVariablesConsumer) { @@ -445,19 +469,12 @@ static Set<Type> getTypeClosure(ClassInfo classInfo, AnnotationTarget producerFi } else { // Canonical ParameterizedType with unresolved type variables Type[] typeParams = new Type[typeParameters.size()]; - boolean skipThisType = false; for (int i = 0; i < typeParameters.size(); i++) { typeParams[i] = resolvedTypeParameters.get(typeParameters.get(i).identifier()); - // this should only be the case for producers; wildcard is not a legal bean type + // for producers, wildcard is not a legal bean type and results in a definition error // see https://docs.jboss.org/cdi/spec/2.0/cdi-spec.html#legal_bean_types - if (typeParams[i].kind().equals(Kind.WILDCARD_TYPE) && producerFieldOrMethod != null) { - LOGGER.info("Producer " + - (producerFieldOrMethod.kind().equals(AnnotationTarget.Kind.FIELD) ? "field " : "method ") + - producerFieldOrMethod + - " contains a parameterized typed with a wildcard. This type is not a legal bean type" + - " according to CDI specification and will be ignored during bean resolution."); - skipThisType = true; - } + // NOTE: wildcard can be nested, such as List<Set<? extends Number>> + detectWildcardAndThrow(typeParams[i], producerFieldOrMethod); } if (resolvedTypeVariablesConsumer != null) { Map<String, Type> resolved = new HashMap<>(); @@ -466,9 +483,7 @@ static Set<Type> getTypeClosure(ClassInfo classInfo, AnnotationTarget producerFi } resolvedTypeVariablesConsumer.accept(classInfo, resolved); } - if (!skipThisType) { - types.add(ParameterizedType.create(classInfo.name(), typeParams, null)); - } + types.add(ParameterizedType.create(classInfo.name(), typeParams, null)); } // Interfaces for (Type interfaceType : classInfo.interfaceTypes()) { diff --git a/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/TypesTest.java b/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/TypesTest.java index fbe3e19e240..eb35c5ff8ac 100644 --- a/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/TypesTest.java +++ b/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/TypesTest.java @@ -1,6 +1,7 @@ package io.quarkus.arc.processor; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; @@ -11,11 +12,11 @@ import java.util.Map; import java.util.Set; +import javax.enterprise.inject.spi.DefinitionException; + import org.jboss.jandex.ClassInfo; import org.jboss.jandex.DotName; -import org.jboss.jandex.FieldInfo; import org.jboss.jandex.IndexView; -import org.jboss.jandex.MethodInfo; import org.jboss.jandex.ParameterizedType; import org.jboss.jandex.Type; import org.jboss.jandex.Type.Kind; @@ -26,7 +27,7 @@ public class TypesTest { @Test public void testGetTypeClosure() throws IOException { IndexView index = Basics.index(Foo.class, Baz.class, Producer.class, Object.class, List.class, Collection.class, - Iterable.class); + Iterable.class, Set.class); DotName bazName = DotName.createSimple(Baz.class.getName()); DotName fooName = DotName.createSimple(Foo.class.getName()); DotName producerName = DotName.createSimple(Producer.class.getName()); @@ -64,18 +65,19 @@ public void testGetTypeClosure() throws IOException { } } ClassInfo producerClass = index.getClassByName(producerName); - String producersName = "produce"; - MethodInfo producerMethod = producerClass.method(producersName); - // Object is the sole type - Set<Type> producerMethodTypes = Types.getProducerMethodTypeClosure(producerMethod, - dummyDeployment); - assertEquals(1, producerMethodTypes.size()); + final String producersName = "produce"; + assertThrows(DefinitionException.class, + () -> Types.getProducerMethodTypeClosure(producerClass.method(producersName), dummyDeployment)); + assertThrows(DefinitionException.class, + () -> Types.getProducerFieldTypeClosure(producerClass.field(producersName), dummyDeployment)); + + // now assert the same with nested wildcard + final String nestedWildCardProducersName = "produceNested"; + assertThrows(DefinitionException.class, + () -> Types.getProducerMethodTypeClosure(producerClass.method(nestedWildCardProducersName), dummyDeployment)); + assertThrows(DefinitionException.class, + () -> Types.getProducerFieldTypeClosure(producerClass.field(nestedWildCardProducersName), dummyDeployment)); - // Object is the sole type - FieldInfo producerField = producerClass.field(producersName); - Set<Type> producerFieldTypes = Types.getProducerFieldTypeClosure(producerField, - dummyDeployment); - assertEquals(1, producerFieldTypes.size()); } static class Foo<T> { @@ -94,6 +96,12 @@ public List<? extends Number> produce() { return null; } + public List<Set<? extends Number>> produceNested() { + return null; + } + List<? extends Number> produce; + + List<Set<? extends Number>> produceNested; } }
['independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/Types.java', 'independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/TypesTest.java']
{'.java': 2}
2
2
0
0
2
24,068,922
4,738,803
614,086
5,630
2,546
470
41
1
898
114
228
43
2
0
1970-01-01T00:27:51
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,302
quarkusio/quarkus/29832/29783
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/29783
https://github.com/quarkusio/quarkus/pull/29832
https://github.com/quarkusio/quarkus/pull/29832
1
resolves
@PreDestroy method not awaited
## Quarkus version 2.14.2 on Linux with OpenJSD 11.0.17+8 ## Actual behaviour I get the following exception on session timeout: ``` ERROR [io.qua.arc.imp.AbstractInstanceHandle] (executor-thread-31) Error occurred while destroying instance of bean [...SessionManager_Bean]: javax.enterprise.context.ContextNotActiveException: SessionScoped context was not active when trying to obtain a bean instance for a client proxy of CLASS bean [class=...MyAPIClient, id=5b2...] ``` ## Expected behavior Session scope and @SessionScoped beans should not be destroyed as long as all methods annotated with @PreDestroy of unremovable beans have returned. ## How to Reproduce? ```java @Named("myAPIClient") @SessionScoped public class MyAPIClient implements Serializable { ... } @Named("sessionManager") @SessionScoped public class SessionManager implements Serializable { @Inject private myAPIClient myAPIClient; @PreDestroy public void autoLogout() { myAPIClient.doSomething(); // <-- Exception thrown here } ... } ``` Any hints?
4fe6585189ef929d145d46721a76a073052c76fd
6263710342517015d32ebf904757b12f0dfa4c9d
https://github.com/quarkusio/quarkus/compare/4fe6585189ef929d145d46721a76a073052c76fd...6263710342517015d32ebf904757b12f0dfa4c9d
diff --git a/extensions/undertow/runtime/src/main/java/io/quarkus/undertow/runtime/HttpSessionContext.java b/extensions/undertow/runtime/src/main/java/io/quarkus/undertow/runtime/HttpSessionContext.java index da04a1be1d3..25a5d54942d 100644 --- a/extensions/undertow/runtime/src/main/java/io/quarkus/undertow/runtime/HttpSessionContext.java +++ b/extensions/undertow/runtime/src/main/java/io/quarkus/undertow/runtime/HttpSessionContext.java @@ -16,6 +16,8 @@ import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; +import org.jboss.logging.Logger; + import io.quarkus.arc.Arc; import io.quarkus.arc.ContextInstanceHandle; import io.quarkus.arc.InjectableBean; @@ -31,6 +33,10 @@ public class HttpSessionContext implements InjectableContext, HttpSessionListene private static final String CONTEXTUAL_INSTANCES_KEY = HttpSessionContext.class.getName() + ".contextualInstances"; + private static final ThreadLocal<HttpSession> DESTRUCT_SESSION = new ThreadLocal<>(); + + private static final Logger LOG = Logger.getLogger(HttpSessionContext.class); + @Override public Class<? extends Annotation> getScope() { return SessionScoped.class; @@ -39,17 +45,16 @@ public Class<? extends Annotation> getScope() { @SuppressWarnings("unchecked") @Override public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) { - HttpServletRequest request = servletRequest(); - if (request == null) { + HttpSession session = session(true); + if (session == null) { throw new ContextNotActiveException(); } InjectableBean<T> bean = (InjectableBean<T>) contextual; - ComputingCache<Key, ContextInstanceHandle<?>> contextualInstances = getContextualInstances(request); + ComputingCache<Key, ContextInstanceHandle<?>> contextualInstances = getContextualInstances(session); if (creationalContext != null) { return (T) contextualInstances.getValue(new Key(creationalContext, bean.getIdentifier())).get(); } else { - InstanceHandle<T> handle = (InstanceHandle<T>) contextualInstances - .getValueIfPresent(new Key(null, bean.getIdentifier())); + InstanceHandle<T> handle = (InstanceHandle<T>) contextualInstances.getValueIfPresent(Key.of(bean.getIdentifier())); return handle != null ? handle.get() : null; } } @@ -61,7 +66,7 @@ public <T> T get(Contextual<T> contextual) { @Override public boolean isActive() { - return servletRequest() != null; + return session(true) != null; } @Override @@ -70,9 +75,9 @@ public ContextState getState() { @Override public Map<InjectableBean<?>, Object> getContextualInstances() { - HttpServletRequest httpServletRequest = servletRequest(); - if (httpServletRequest != null) { - return HttpSessionContext.this.getContextualInstances(httpServletRequest).getPresentValues().stream() + HttpSession session = session(false); + if (session != null) { + return HttpSessionContext.this.getContextualInstances(session).getPresentValues().stream() .collect(Collectors.toMap(ContextInstanceHandle::getBean, ContextInstanceHandle::get)); } return Collections.emptyMap(); @@ -82,13 +87,12 @@ public Map<InjectableBean<?>, Object> getContextualInstances() { @Override public void destroy(Contextual<?> contextual) { - HttpServletRequest httpServletRequest = servletRequest(); - if (httpServletRequest == null) { + HttpSession session = session(true); + if (session == null) { throw new ContextNotActiveException(); } InjectableBean<?> bean = (InjectableBean<?>) contextual; - InstanceHandle<?> instanceHandle = getContextualInstances(httpServletRequest) - .remove(new Key(null, bean.getIdentifier())); + InstanceHandle<?> instanceHandle = getContextualInstances(session).remove(Key.of(bean.getIdentifier())); if (instanceHandle != null) { instanceHandle.destroy(); } @@ -96,34 +100,38 @@ public void destroy(Contextual<?> contextual) { @Override public void destroy() { - HttpServletRequest httpServletRequest = servletRequest(); - if (httpServletRequest == null) { + HttpSession session = session(true); + if (session == null) { throw new ContextNotActiveException(); } - HttpSession session = httpServletRequest.getSession(false); - if (session != null) { - destroy(session); - } + destroy(session); } private void destroy(HttpSession session) { synchronized (this) { - ComputingCache<Key, ContextInstanceHandle<?>> contextualInstances = getContextualInstances(session); - for (ContextInstanceHandle<?> instance : contextualInstances.getPresentValues()) { - try { - instance.destroy(); - } catch (Exception e) { - throw new IllegalStateException("Unable to destroy instance" + instance.get(), e); + ComputingCache<Key, ContextInstanceHandle<?>> instances = getContextualInstances(session); + for (ContextInstanceHandle<?> instance : instances.getPresentValues()) { + // try to remove the contextual instance from the context + ContextInstanceHandle<?> val = instances.remove(Key.of(instance.getBean().getIdentifier())); + if (val != null) { + // destroy it afterwards + try { + val.destroy(); + } catch (Exception e) { + LOG.errorf(e, "Unable to destroy bean instance: %s", val.get()); + } } } - contextualInstances.clear(); + if (!instances.isEmpty()) { + LOG.warnf( + "Some @SessionScoped beans were created during destruction of the session context: %s\\n\\t- potential @PreDestroy callbacks declared on the beans were not invoked\\n\\t- in general, @SessionScoped beans should not call other @SessionScoped beans in a @PreDestroy callback", + instances.getPresentValues().stream().map(ContextInstanceHandle::getBean) + .collect(Collectors.toList())); + } + instances.clear(); } } - private ComputingCache<Key, ContextInstanceHandle<?>> getContextualInstances(HttpServletRequest httpServletRequest) { - return getContextualInstances(httpServletRequest.getSession()); - } - @SuppressWarnings({ "unchecked", "rawtypes" }) private ComputingCache<Key, ContextInstanceHandle<?>> getContextualInstances(HttpSession session) { ComputingCache<Key, ContextInstanceHandle<?>> contextualInstances = (ComputingCache<Key, ContextInstanceHandle<?>>) session @@ -135,6 +143,9 @@ private ComputingCache<Key, ContextInstanceHandle<?>> getContextualInstances(Htt if (contextualInstances == null) { contextualInstances = new ComputingCache<>(key -> { InjectableBean bean = Arc.container().bean(key.beanIdentifier); + if (key.creationalContext == null) { + throw new IllegalStateException("Cannot create bean "); + } return new ContextInstanceHandleImpl(bean, bean.create(key.creationalContext), key.creationalContext); }); session.setAttribute(CONTEXTUAL_INSTANCES_KEY, contextualInstances); @@ -144,16 +155,22 @@ private ComputingCache<Key, ContextInstanceHandle<?>> getContextualInstances(Htt return contextualInstances; } - private HttpServletRequest servletRequest() { + private HttpSession session(boolean create) { + HttpSession session = null; try { - return (HttpServletRequest) ServletRequestContext.requireCurrent().getServletRequest(); - } catch (IllegalStateException e) { - return null; + session = ((HttpServletRequest) ServletRequestContext.requireCurrent().getServletRequest()).getSession(create); + } catch (IllegalStateException ignored) { + session = DESTRUCT_SESSION.get(); } + return session; } static class Key { + static Key of(String beanIdentifier) { + return new Key(null, beanIdentifier); + } + CreationalContext<?> creationalContext; String beanIdentifier; @@ -187,7 +204,13 @@ public boolean equals(Object obj) { @Override public void sessionDestroyed(HttpSessionEvent se) { - destroy(se.getSession()); + HttpSession session = se.getSession(); + try { + DESTRUCT_SESSION.set(session); + destroy(session); + } finally { + DESTRUCT_SESSION.remove(); + } } }
['extensions/undertow/runtime/src/main/java/io/quarkus/undertow/runtime/HttpSessionContext.java']
{'.java': 1}
1
1
0
0
1
24,036,736
4,732,813
613,364
5,622
5,247
843
93
1
1,103
124
250
52
0
2
1970-01-01T00:27:50
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,303
quarkusio/quarkus/29821/29712
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/29712
https://github.com/quarkusio/quarkus/pull/29821
https://github.com/quarkusio/quarkus/pull/29821
1
fix
keycloak-admin-client-reactive maps wrong id to AuthorizationResources
### Describe the bug When executing: ```java var authorizationResource = realmResource.clients().get(clientResourceId).authorization() var defaultPermission = authorizationResource.permissions().resource().findByName("Default Permission"); var permissionId = defaultPermission.getId(); authorizationResource.permissions().resource() .findById(permissionId).remove() ``` The api called is ``` http://localhost:8082/admin/realms/testrealm/clients/{clientResourceId}/authz/resource-server/permission/resource/{clientResourceId} ``` Instead of: ``` http://localhost:8082/admin/realms/testrealm/clients/{clientResourceId}/authz/resource-server/permission/resource/{permissionId} ``` Which leads to a 404 as the id of the permission is wrong. This only happens with the `reactive` version, not with the `classic` ### Expected behavior _No response_ ### Actual behavior _No response_ ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.14.2.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
30f5ad3d516744682a28914fe36031a76d444aac
2c7a295e097a72a8b5b2d478533c6cb29c780dfb
https://github.com/quarkusio/quarkus/compare/30f5ad3d516744682a28914fe36031a76d444aac...2c7a295e097a72a8b5b2d478533c6cb29c780dfb
diff --git a/extensions/resteasy-reactive/jaxrs-client-reactive/deployment/src/main/java/io/quarkus/jaxrs/client/reactive/deployment/JaxrsClientReactiveProcessor.java b/extensions/resteasy-reactive/jaxrs-client-reactive/deployment/src/main/java/io/quarkus/jaxrs/client/reactive/deployment/JaxrsClientReactiveProcessor.java index 39cfc80d380..86edc4adff4 100644 --- a/extensions/resteasy-reactive/jaxrs-client-reactive/deployment/src/main/java/io/quarkus/jaxrs/client/reactive/deployment/JaxrsClientReactiveProcessor.java +++ b/extensions/resteasy-reactive/jaxrs-client-reactive/deployment/src/main/java/io/quarkus/jaxrs/client/reactive/deployment/JaxrsClientReactiveProcessor.java @@ -1161,8 +1161,31 @@ private void handleSubResourceMethod(List<JaxrsClientReactiveEnricherBuildItem> ownerContext.constructor.writeInstanceField(forMethodTargetDesc, ownerContext.constructor.getThis(), constructorTarget); - ResultHandle subInstance = ownerMethod.newInstance(subConstructorDescriptor, - ownerMethod.readInstanceField(forMethodTargetDesc, ownerMethod.getThis())); + Supplier<FieldDescriptor> methodParamAnnotationsField = ownerContext.getLazyJavaMethodParamAnnotationsField( + methodIndex); + Supplier<FieldDescriptor> methodGenericParametersField = ownerContext.getLazyJavaMethodGenericParametersField( + methodIndex); + + AssignableResultHandle client = createRestClientField(name, ownerContext.classCreator, ownerMethod); + AssignableResultHandle webTarget = ownerMethod.createVariable(WebTarget.class); + ownerMethod.assign(webTarget, ownerMethod.readInstanceField(forMethodTargetDesc, ownerMethod.getThis())); + // Setup Path param from current method + for (int i = 0; i < method.getParameters().length; i++) { + MethodParameter param = method.getParameters()[i]; + if (param.parameterType == ParameterType.PATH) { + ResultHandle paramValue = ownerMethod.getMethodParam(i); + // methodTarget = methodTarget.resolveTemplate(paramname, paramvalue); + addPathParam(ownerMethod, webTarget, param.name, paramValue, + param.type, + client, + ownerMethod.readStaticField(methodGenericParametersField.get()), + ownerMethod.readStaticField(methodParamAnnotationsField.get()), + i); + } + } + + // Continue creating the subresource instance with the web target updated + ResultHandle subInstance = ownerMethod.newInstance(subConstructorDescriptor, webTarget); List<SubResourceParameter> subParamFields = new ArrayList<>(); @@ -1179,23 +1202,24 @@ private void handleSubResourceMethod(List<JaxrsClientReactiveEnricherBuildItem> ownerParameter.paramIndex)); } - FieldDescriptor clientField = createRestClientField(name, ownerContext.classCreator, ownerMethod, - subContext.classCreator, subInstance); - - Supplier<FieldDescriptor> methodParamAnnotationsField = ownerContext.getLazyJavaMethodParamAnnotationsField( - methodIndex); - Supplier<FieldDescriptor> methodGenericParametersField = ownerContext.getLazyJavaMethodGenericParametersField( - methodIndex); - // method parameters are rewritten to sub client fields (directly, public fields): + FieldDescriptor clientField = subContext.classCreator.getFieldCreator("client", RestClientBase.class) + .setModifiers(Modifier.PUBLIC) + .getFieldDescriptor(); + ownerMethod.writeInstanceField(clientField, subInstance, client); + // method parameters (except path parameters) are rewritten to sub client fields (directly, public fields): for (int i = 0; i < method.getParameters().length; i++) { - FieldDescriptor paramField = subContext.classCreator.getFieldCreator("param" + i, - method.getParameters()[i].type) - .setModifiers(Modifier.PUBLIC) - .getFieldDescriptor(); - ownerMethod.writeInstanceField(paramField, subInstance, ownerMethod.getMethodParam(i)); - subParamFields.add(new SubResourceParameter(method.getParameters()[i], method.getParameters()[i].type, - jandexMethod.parameterType(i), paramField, methodParamAnnotationsField, methodGenericParametersField, - i)); + MethodParameter param = method.getParameters()[i]; + if (param.parameterType != ParameterType.PATH) { + FieldDescriptor paramField = subContext.classCreator.getFieldCreator("param" + i, param.type) + .setModifiers(Modifier.PUBLIC) + .getFieldDescriptor(); + ownerMethod.writeInstanceField(paramField, subInstance, ownerMethod.getMethodParam(i)); + subParamFields.add(new SubResourceParameter(method.getParameters()[i], param.type, + jandexMethod.parameterType(i), paramField, methodParamAnnotationsField, + methodGenericParametersField, + i)); + } + } int subMethodIndex = 0; @@ -1555,22 +1579,19 @@ private void appendPath(MethodCreator constructor, String pathPart, AssignableRe * Create the `client` field into the `c` class that represents a RestClientBase instance. * The RestClientBase instance is coming from either a root client or a sub client (clients generated from root clients). */ - private FieldDescriptor createRestClientField(String name, ClassCreator c, MethodCreator methodCreator, ClassCreator sub, - ResultHandle subInstance) { - FieldDescriptor clientField = sub.getFieldCreator("client", RestClientBase.class) - .setModifiers(Modifier.PUBLIC) - .getFieldDescriptor(); + private AssignableResultHandle createRestClientField(String name, ClassCreator c, MethodCreator methodCreator) { + AssignableResultHandle client = methodCreator.createVariable(RestClientBase.class); if (c.getSuperClass().contains(RestClientBase.class.getSimpleName())) { // We're in a root client, so we can set the client field with: sub.client = (RestClientBase) this - methodCreator.writeInstanceField(clientField, subInstance, methodCreator.getThis()); + methodCreator.assign(client, methodCreator.getThis()); } else { FieldDescriptor subClientField = FieldDescriptor.of(name, "client", RestClientBase.class); - // We're in a sub sub resource, so we need to get the client from the field: subSub.client = sub.client - methodCreator.writeInstanceField(clientField, subInstance, - methodCreator.readInstanceField(subClientField, methodCreator.getThis())); + // We're in a sub-sub resource, so we need to get the client from the field: subSub.client = sub.client + methodCreator.assign(client, methodCreator.readInstanceField(subClientField, methodCreator.getThis())); } - return clientField; + + return client; } private void handleMultipartField(String formParamName, String partType, String partFilename, diff --git a/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/subresource/SubResourceTest.java b/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/subresource/SubResourceTest.java index ee757d02229..53e6cc1d39f 100644 --- a/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/subresource/SubResourceTest.java +++ b/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/subresource/SubResourceTest.java @@ -61,6 +61,14 @@ void shouldPassParamsToSubSubResource() { assertThat(result).isEqualTo("rt/mthd/sub/subSimple"); } + @Test + void shouldPassPathParamsToSubSubResource() { + // should result in sending GET /path/rt/mthd/sub/s/ss + RootClient rootClient = RestClientBuilder.newBuilder().baseUri(baseUri).build(RootClient.class); + String result = rootClient.sub("rt", "mthd").sub("s").get("ss"); + assertThat(result).isEqualTo("rt/mthd/sub/s/ss"); + } + @Test void shouldDoMultiplePosts() { RootClient rootClient = RestClientBuilder.newBuilder().baseUri(baseUri).build(RootClient.class); @@ -129,6 +137,9 @@ interface SubClient { @Path("/sub") SubSubClient sub(); + @Path("/sub/{methodParam}") + SubSubClient sub(@PathParam("methodParam") String methodParam); + @POST @ClientHeaderParam(name = "overridable", value = "SubClient") @ClientHeaderParam(name = "fromSubMethod", value = "{fillingMethod}") @@ -146,6 +157,10 @@ interface SubSubClient { @Path("/subSimple") String simpleSub(); + @GET + @Path("/{methodParam}") + String get(@PathParam("methodParam") String methodParam); + @POST @ClientHeaderParam(name = "overridable", value = "SubSubClient") @ClientHeaderParam(name = "fromSubMethod", value = "{fillingMethod}")
['extensions/resteasy-reactive/jaxrs-client-reactive/deployment/src/main/java/io/quarkus/jaxrs/client/reactive/deployment/JaxrsClientReactiveProcessor.java', 'extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/subresource/SubResourceTest.java']
{'.java': 2}
2
2
0
0
2
24,034,765
4,732,470
613,329
5,622
5,588
933
77
1
1,271
125
283
56
2
3
1970-01-01T00:27:50
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,312
quarkusio/quarkus/29620/29585
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/29585
https://github.com/quarkusio/quarkus/pull/29620
https://github.com/quarkusio/quarkus/pull/29620
1
fixes
@ConsumeEvent annotated method is called twice per message when generic parent class has an abstract method for it
### Describe the bug Having a class extending a class with generics which has an abstract method for the consumer method, this will result in the method annotated with `@ConsumeEvent` on the extending class to be called twice per eventbus message. ### Expected behavior Its expected that a method annotated with `@ConsumeEvent` is invoked only once per message. 1. Remove `public abstract void consume(@NonNull T event);` from `GreetingService` 2. Start the application 3. You will notice that the consumer is invoked only once per message ### Actual behavior Having a class extending a class with generics which has an abstract method for the consumer method, this will result in the method annotated with `@Consume` on the extending class to be called twice per eventbus message. 1. Start the application 2. You will notice duplicated outputs from consumer like `consuming HelloEvent on HelloService: ee73ab41-6b9a-465a-967c-d264046e0cc0` ### How to Reproduce? Reproducer: 1. Clone https://github.com/benjaminrau/genericdoublesconsumer 2. Start the application 3. See the duplicated output for same UUID (there should be only one) Ive also prepared a test which shows that the consumer is registered twice in Vertx HandlerMap: `https://github.com/benjaminrau/genericdoublesconsumer/blob/master/src/test/java/org/acme/EventBusTest.java` ### Output of `uname -a` or `ver` Linux br-builders-nb 5.14.0-1052-oem #59-Ubuntu SMP Fri Sep 9 09:37:59 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux ### Output of `java -version` openjdk version "17" 2021-09-14 OpenJDK Runtime Environment (build 17+35-2724) OpenJDK 64-Bit Server VM (build 17+35-2724, mixed mode, sharing) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.14.2.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information The log output clearly shows that the consumer is called twice for the same message since the payload is a randomized UUID string. ``` 2022-11-30 17:39:41,659 INFO [org.acm.HelloService] (vert.x-eventloop-thread-1) consuming HelloEvent on HelloService: cdd635b3-f7ee-4a07-adea-56fbebfc5366 2022-11-30 17:39:41,659 INFO [org.acm.HelloService] (vert.x-eventloop-thread-0) consuming HelloEvent on HelloService: cdd635b3-f7ee-4a07-adea-56fbebfc5366 2022-11-30 17:39:43,659 INFO [org.acm.HelloService] (vert.x-eventloop-thread-1) consuming HelloEvent on HelloService: eedb7070-d1e8-4686-8e53-c6733926ad52 2022-11-30 17:39:43,659 INFO [org.acm.HelloService] (vert.x-eventloop-thread-0) consuming HelloEvent on HelloService: eedb7070-d1e8-4686-8e53-c6733926ad52 ```
c28c01474cb75c0cec70f289d470c507c521b895
b1664aa85a3272490807fbb6c18859f02f4a157e
https://github.com/quarkusio/quarkus/compare/c28c01474cb75c0cec70f289d470c507c521b895...b1664aa85a3272490807fbb6c18859f02f4a157e
diff --git a/extensions/vertx/deployment/src/main/java/io/quarkus/vertx/deployment/VertxProcessor.java b/extensions/vertx/deployment/src/main/java/io/quarkus/vertx/deployment/VertxProcessor.java index 7eeb82fb9f9..2bd342cb402 100644 --- a/extensions/vertx/deployment/src/main/java/io/quarkus/vertx/deployment/VertxProcessor.java +++ b/extensions/vertx/deployment/src/main/java/io/quarkus/vertx/deployment/VertxProcessor.java @@ -122,6 +122,9 @@ void collectEventConsumers( AnnotationStore annotationStore = beanRegistrationPhase.getContext().get(BuildExtension.Key.ANNOTATION_STORE); for (BeanInfo bean : beanRegistrationPhase.getContext().beans().classBeans()) { for (MethodInfo method : bean.getTarget().get().asClass().methods()) { + if (method.isSynthetic()) { + continue; + } AnnotationInstance consumeEvent = annotationStore.getAnnotation(method, CONSUME_EVENT); if (consumeEvent != null) { // Validate method params and return type
['extensions/vertx/deployment/src/main/java/io/quarkus/vertx/deployment/VertxProcessor.java']
{'.java': 1}
1
1
0
0
1
23,806,293
4,681,828
607,473
5,588
94
14
3
1
2,720
327
775
61
2
1
1970-01-01T00:27:49
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,311
quarkusio/quarkus/29623/10673
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/10673
https://github.com/quarkusio/quarkus/pull/29623
https://github.com/quarkusio/quarkus/pull/29623
1
closes
OutboundSseEvent is not correctly serialized
**Describe the bug** When creating a `OutboundSseEvent` object and returning it back in a REST Endpoint it is not correctly serialized. **Expected behavior** `Server-Side Event` is sent back and it is able to be deserialized correctly. **Actual behavior** Either an exception that the object cannot be serialized or in case of using ``` @Produces(MediaType.SERVER_SENT_EVENTS) @SseElementType(MediaType.SERVER_SENT_EVENTS) ``` Then all properties like `name`, `data`, `comment` ... are serialized as a data and not in the correct fields. **To Reproduce** Steps to reproduce the behavior: Repo is here: https://github.com/lordofthejars/quarkus-quartz-streams 1. Run https://github.com/lordofthejars/quarkus-quartz-streams/blob/master/src/test/java/org/acme/ExampleResourceTest.java **Environment (please complete the following information):** - Quarkus 1.6.0.Final
b82d50ff5a48321e844c5dea822859f943a9a606
dc5f031c0f8b5f24f7f5bdba418e6f04b8dcbf25
https://github.com/quarkusio/quarkus/compare/b82d50ff5a48321e844c5dea822859f943a9a606...dc5f031c0f8b5f24f7f5bdba418e6f04b8dcbf25
diff --git a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/stream/StreamResource.java b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/stream/StreamResource.java index def237ac8da..307d5b77d5d 100644 --- a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/stream/StreamResource.java +++ b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/stream/StreamResource.java @@ -8,7 +8,10 @@ import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; +import javax.ws.rs.sse.OutboundSseEvent; +import javax.ws.rs.sse.Sse; import org.jboss.resteasy.reactive.common.util.MultiCollectors; import org.reactivestreams.Publisher; @@ -152,4 +155,13 @@ public Multi<String> sse() { public Multi<String> sseThrows() { throw new IllegalStateException("STOP"); } + + @Path("sse/raw") + @GET + @Produces(MediaType.SERVER_SENT_EVENTS) + public Multi<OutboundSseEvent> sseRaw(@Context Sse sse) { + return Multi.createFrom().items(sse.newEventBuilder().id("one").data("uno").name("eins").build(), + sse.newEventBuilder().id("two").data("dos").name("zwei").build(), + sse.newEventBuilder().id("three").data("tres").name("drei").build()); + } } diff --git a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/stream/StreamTestCase.java b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/stream/StreamTestCase.java index 36df4075e76..d43b1ddb124 100644 --- a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/stream/StreamTestCase.java +++ b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/stream/StreamTestCase.java @@ -237,4 +237,32 @@ public void testSseThrows() throws InterruptedException { Assertions.assertEquals(1, errors.size()); } } + + @Test + public void testSseForMultiWithOutboundSseEvent() throws InterruptedException { + Client client = ClientBuilder.newBuilder().build(); + WebTarget target = client.target(this.uri.toString() + "stream/sse/raw"); + try (SseEventSource sse = SseEventSource.target(target).build()) { + CountDownLatch latch = new CountDownLatch(1); + List<Throwable> errors = new CopyOnWriteArrayList<>(); + List<String> results = new CopyOnWriteArrayList<>(); + List<String> ids = new CopyOnWriteArrayList<>(); + List<String> names = new CopyOnWriteArrayList<>(); + sse.register(event -> { + results.add(event.readData()); + ids.add(event.getId()); + names.add(event.getName()); + }, error -> { + errors.add(error); + }, () -> { + latch.countDown(); + }); + sse.open(); + Assertions.assertTrue(latch.await(20, TimeUnit.SECONDS)); + Assertions.assertEquals(Arrays.asList("uno", "dos", "tres"), results); + Assertions.assertEquals(Arrays.asList("one", "two", "three"), ids); + Assertions.assertEquals(Arrays.asList("eins", "zwei", "drei"), names); + Assertions.assertEquals(0, errors.size()); + } + } } diff --git a/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/handlers/PublisherResponseHandler.java b/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/handlers/PublisherResponseHandler.java index 3ac1f35a6de..45389d6c2ca 100644 --- a/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/handlers/PublisherResponseHandler.java +++ b/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/handlers/PublisherResponseHandler.java @@ -11,6 +11,7 @@ import java.util.function.Consumer; import javax.ws.rs.core.MediaType; +import javax.ws.rs.sse.OutboundSseEvent; import org.jboss.logging.Logger; import org.jboss.resteasy.reactive.common.util.RestMediaType; @@ -49,7 +50,12 @@ private static class SseMultiSubscriber extends AbstractMultiSubscriber { @Override public void onNext(Object item) { - OutboundSseEventImpl event = new OutboundSseEventImpl.BuilderImpl().data(item).build(); + OutboundSseEvent event; + if (item instanceof OutboundSseEvent) { + event = (OutboundSseEvent) item; + } else { + event = new OutboundSseEventImpl.BuilderImpl().data(item).build(); + } SseUtil.send(requestContext, event, customizers).whenComplete(new BiConsumer<Object, Throwable>() { @Override public void accept(Object v, Throwable t) {
['extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/stream/StreamTestCase.java', 'independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/handlers/PublisherResponseHandler.java', 'extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/stream/StreamResource.java']
{'.java': 3}
3
3
0
0
3
23,969,245
4,719,907
611,754
5,610
403
92
8
1
908
98
213
30
2
1
1970-01-01T00:27:49
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,310
quarkusio/quarkus/29641/29575
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/29575
https://github.com/quarkusio/quarkus/pull/29641
https://github.com/quarkusio/quarkus/pull/29641
1
fixes
Unexpected beans added to the index and affecting restarting the application
### Describe the bug I did not manage to come up with a reproducer using a regular Quarkus application. But the issue happens if you try out this branch https://github.com/pedroigor/keycloak/tree/tmp-reactive. That branch is about switching from Resteasy Classic to Reactive in Keycloak. The issue does not happen if using Resteasy Classic and I'm not sure what is the relation, if any. Basically, when reloading the application in dev mode or when running tests using the `QuarkusMainTestExtension`, reloading the application fails with this error: ``` org.junit.jupiter.api.extension.ParameterResolutionException: Failed to resolve parameter [io.quarkus.test.junit.main.LaunchResult arg0] in method [void org.keycloak.it.cli.StartCommandTest.testHttpEnabled(io.quarkus.test.junit.main.LaunchResult)]: java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors [error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: Found 8 deployment problems: [1] Ambiguous dependencies for type javax.transaction.TransactionManager and qualifiers [@Default] - java member: io.quarkus.agroal.runtime.DataSources():transactionManager - declared on CLASS bean [types=[io.quarkus.agroal.runtime.DataSources, java.lang.Object], qualifiers=[@Default, @Any], target=io.quarkus.agroal.runtime.DataSources] - available beans: - CLASS bean [types=[java.io.Serializable, javax.transaction.TransactionManager, com.arjuna.ats.jta.cdi.NarayanaTransactionManager, com.arjuna.ats.jta.cdi.DelegatingTransactionManager, java.lang.Object], qualifiers=[@Default, @Any], target=com.arjuna.ats.jta.cdi.NarayanaTransactionManager] - CLASS bean [types=[javax.transaction.TransactionManager, java.io.Serializable, io.quarkus.narayana.jta.runtime.CDIDelegatingTransactionManager, java.lang.Object], qualifiers=[@Default, @Any], target=io.quarkus.narayana.jta.runtime.CDIDelegatingTransactionManager] ``` The first start of the application works fine and only `CDIDelegatingTransactionManager` is available to resolve `TransactionManager` bean types. However, reloading the application causes the `com.arjuna.ats.jta.cdi.NarayanaTransactionManager` to also be recognized as a potential resolver hence failing with that error. If we remove the `com.arjuna.ats.jta.cdi.NarayanaTransactionManager` at build time from our extension, the issue does not happen: ``` buildTimeConditionBuildItemBuildProducer.produce(new BuildTimeConditionBuildItem(index.getIndex().getClassByName(DotName.createSimple("com.arjuna.ats.jta.cdi.NarayanaTransactionManager")), false));` ``` ### Expected behavior Being able to reload the application without introducing beans that otherwise should be excluded. ### Actual behavior Failing to reload the application as per the description. ### How to Reproduce? * Checkout this branch https://github.com/pedroigor/keycloak/tree/tmp-reactive-bean-issue * mvn -Pdistribution -DskipTests clean install * cd quarkus/server * mvn quarkus:dev -Dquarkus.args=start-dev * After starting Keycloak in dev mode, force a restart (type `s`) ### Output of `uname -a` or `ver` Linux fedora 6.0.9-200.fc36.x86_64 #1 SMP PREEMPT_DYNAMIC Wed Nov 16 17:50:45 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux ### Output of `java -version` openjdk version "18.0.2.1" 2022-08-18 OpenJDK Runtime Environment (build 18.0.2.1+1-1) OpenJDK 64-Bit Server VM (build 18.0.2.1+1-1, mixed mode, sharing) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.14.1.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
fddf2570f0227c4253d3d240a4ddac5b56263cfe
c2ab3421a74bf755aa2bb595645bcf8bbfd009d6
https://github.com/quarkusio/quarkus/compare/fddf2570f0227c4253d3d240a4ddac5b56263cfe...c2ab3421a74bf755aa2bb595645bcf8bbfd009d6
diff --git a/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/ArcProcessor.java b/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/ArcProcessor.java index 00fe8ebcf53..f2fb782c542 100644 --- a/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/ArcProcessor.java +++ b/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/ArcProcessor.java @@ -277,7 +277,8 @@ public void transform(TransformationContext transformationContext) { } }); - builder.setBeanArchiveIndex(index); + builder.setComputingBeanArchiveIndex(index); + builder.setImmutableBeanArchiveIndex(beanArchiveIndex.getImmutableIndex()); builder.setApplicationIndex(combinedIndex.getIndex()); List<BeanDefiningAnnotation> beanDefiningAnnotations = additionalBeanDefiningAnnotations.stream() .map((s) -> new BeanDefiningAnnotation(s.getName(), s.getDefaultScope())).collect(Collectors.toList()); diff --git a/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/BeanArchiveIndexBuildItem.java b/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/BeanArchiveIndexBuildItem.java index fbb2813c638..0c0550f7d7e 100644 --- a/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/BeanArchiveIndexBuildItem.java +++ b/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/BeanArchiveIndexBuildItem.java @@ -14,26 +14,42 @@ * Compared to {@link io.quarkus.deployment.builditem.CombinedIndexBuildItem} this index can contain additional classes * that were indexed while bean discovery was in progress. * - * It also holds information about all programmatically registered beans and all generated bean classes. - * * @see GeneratedBeanBuildItem - * @see AdditionalBeanBuildItem * @see io.quarkus.deployment.builditem.CombinedIndexBuildItem */ public final class BeanArchiveIndexBuildItem extends SimpleBuildItem { private final IndexView index; + private final IndexView immutableIndex; private final Set<DotName> generatedClassNames; - public BeanArchiveIndexBuildItem(IndexView index, Set<DotName> generatedClassNames) { + public BeanArchiveIndexBuildItem(IndexView index, IndexView immutableIndex, Set<DotName> generatedClassNames) { this.index = index; + this.immutableIndex = immutableIndex; this.generatedClassNames = generatedClassNames; } + /** + * This index is built on top of the immutable index. + * + * @return the computing index that can also index classes on demand + */ public IndexView getIndex() { return index; } + /** + * + * @return an immutable index that represents the bean archive + */ + public IndexView getImmutableIndex() { + return immutableIndex; + } + + /** + * + * @return the set of classes generated via {@link GeneratedBeanBuildItem} + */ public Set<DotName> getGeneratedClassNames() { return generatedClassNames; } diff --git a/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/BeanArchiveProcessor.java b/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/BeanArchiveProcessor.java index 29283e4df95..cb75954e4b3 100644 --- a/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/BeanArchiveProcessor.java +++ b/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/BeanArchiveProcessor.java @@ -84,12 +84,12 @@ public BeanArchiveIndexBuildItem build(ArcConfig config, ApplicationArchivesBuil additionalClasses.put(knownMissingClass, Optional.empty()); } - // Finally, index ArC/CDI API built-in classes - return new BeanArchiveIndexBuildItem( - BeanArchives.buildBeanArchiveIndex(Thread.currentThread().getContextClassLoader(), additionalClasses, - applicationIndex, - additionalBeanIndexer.complete()), - generatedClassNames); + IndexView immutableBeanArchiveIndex = BeanArchives.buildImmutableBeanArchiveIndex(applicationIndex, + additionalBeanIndexer.complete()); + IndexView computingBeanArchiveIndex = BeanArchives.buildComputingBeanArchiveIndex( + Thread.currentThread().getContextClassLoader(), + additionalClasses, immutableBeanArchiveIndex); + return new BeanArchiveIndexBuildItem(computingBeanArchiveIndex, immutableBeanArchiveIndex, generatedClassNames); } private IndexView buildApplicationIndex(ArcConfig config, ApplicationArchivesBuildItem applicationArchivesBuildItem, diff --git a/extensions/spring-di/deployment/src/test/java/io/quarkus/spring/di/deployment/SpringDIProcessorTest.java b/extensions/spring-di/deployment/src/test/java/io/quarkus/spring/di/deployment/SpringDIProcessorTest.java index 5791891b3fc..41e6975855d 100644 --- a/extensions/spring-di/deployment/src/test/java/io/quarkus/spring/di/deployment/SpringDIProcessorTest.java +++ b/extensions/spring-di/deployment/src/test/java/io/quarkus/spring/di/deployment/SpringDIProcessorTest.java @@ -205,7 +205,8 @@ public void getAnnotationsToAddBeanMethodWithScope() { private IndexView getIndex(final Class<?>... classes) { try { Index index = Index.of(classes); - return BeanArchives.buildBeanArchiveIndex(getClass().getClassLoader(), new ConcurrentHashMap<>(), index); + return BeanArchives.buildComputingBeanArchiveIndex(getClass().getClassLoader(), new ConcurrentHashMap<>(), + BeanArchives.buildImmutableBeanArchiveIndex(index)); } catch (IOException e) { throw new IllegalStateException("Failed to index classes", e); } diff --git a/extensions/spring-scheduled/deployment/src/test/java/io/quarkus/spring/scheduled/deployment/SpringScheduledProcessorTest.java b/extensions/spring-scheduled/deployment/src/test/java/io/quarkus/spring/scheduled/deployment/SpringScheduledProcessorTest.java index 3abb0f2f333..45db58171f5 100644 --- a/extensions/spring-scheduled/deployment/src/test/java/io/quarkus/spring/scheduled/deployment/SpringScheduledProcessorTest.java +++ b/extensions/spring-scheduled/deployment/src/test/java/io/quarkus/spring/scheduled/deployment/SpringScheduledProcessorTest.java @@ -115,7 +115,8 @@ public void testBuildDelayParamFromInvalidFormat() { private IndexView getIndex(final Class<?>... classes) { try { Index index = Index.of(classes); - return BeanArchives.buildBeanArchiveIndex(getClass().getClassLoader(), new ConcurrentHashMap<>(), index); + return BeanArchives.buildComputingBeanArchiveIndex(getClass().getClassLoader(), new ConcurrentHashMap<>(), + BeanArchives.buildImmutableBeanArchiveIndex(index)); } catch (IOException e) { throw new IllegalStateException("Failed to index classes", e); } diff --git a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/AnnotationLiteralProcessor.java b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/AnnotationLiteralProcessor.java index 88e8e83a893..78c2a429fec 100644 --- a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/AnnotationLiteralProcessor.java +++ b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/AnnotationLiteralProcessor.java @@ -46,7 +46,7 @@ public class AnnotationLiteralProcessor { generateAnnotationLiteralClassName(key.annotationName()), applicationClassPredicate.test(key.annotationName()), key.annotationClass)); - this.beanArchiveIndex = beanArchiveIndex; + this.beanArchiveIndex = Objects.requireNonNull(beanArchiveIndex); } boolean hasLiteralsToGenerate() { diff --git a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanArchives.java b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanArchives.java index bd14d9e679f..4a6dd5c8854 100644 --- a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanArchives.java +++ b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanArchives.java @@ -52,14 +52,23 @@ public final class BeanArchives { /** * * @param applicationIndexes - * @return the final bean archive index + * @return the immutable bean archive index */ - public static IndexView buildBeanArchiveIndex(ClassLoader deploymentClassLoader, - Map<DotName, Optional<ClassInfo>> additionalClasses, IndexView... applicationIndexes) { + public static IndexView buildImmutableBeanArchiveIndex(IndexView... applicationIndexes) { List<IndexView> indexes = new ArrayList<>(); Collections.addAll(indexes, applicationIndexes); indexes.add(buildAdditionalIndex()); - return new IndexWrapper(CompositeIndex.create(indexes), deploymentClassLoader, additionalClasses); + return CompositeIndex.create(indexes); + } + + /** + * + * @param wrappedIndexes + * @return the computing bean archive index + */ + public static IndexView buildComputingBeanArchiveIndex(ClassLoader deploymentClassLoader, + Map<DotName, Optional<ClassInfo>> additionalClasses, IndexView immutableIndex) { + return new IndexWrapper(immutableIndex, deploymentClassLoader, additionalClasses); } private static IndexView buildAdditionalIndex() { diff --git a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanDeployment.java b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanDeployment.java index dfcca8ff7eb..4997affe0f4 100644 --- a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanDeployment.java +++ b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanDeployment.java @@ -14,6 +14,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; @@ -55,8 +56,8 @@ public class BeanDeployment { private final BuildContextImpl buildContext; - private final IndexView beanArchiveIndex; - + private final IndexView beanArchiveComputingIndex; + private final IndexView beanArchiveImmutableIndex; private final IndexView applicationIndex; private final Map<DotName, ClassInfo> qualifiers; @@ -124,7 +125,8 @@ public class BeanDeployment { } this.beanDefiningAnnotations = beanDefiningAnnotations; this.resourceAnnotations = new HashSet<>(builder.resourceAnnotations); - this.beanArchiveIndex = builder.beanArchiveIndex; + this.beanArchiveComputingIndex = builder.beanArchiveComputingIndex; + this.beanArchiveImmutableIndex = Objects.requireNonNull(builder.beanArchiveImmutableIndex); this.applicationIndex = builder.applicationIndex; this.annotationStore = new AnnotationStore(initAndSort(builder.annotationTransformers, buildContext), buildContext); if (buildContext != null) { @@ -141,11 +143,11 @@ public class BeanDeployment { this.excludeTypes = builder.excludeTypes != null ? new ArrayList<>(builder.excludeTypes) : Collections.emptyList(); qualifierNonbindingMembers = new HashMap<>(); - qualifiers = findQualifiers(this.beanArchiveIndex); + qualifiers = findQualifiers(); for (QualifierRegistrar registrar : builder.qualifierRegistrars) { for (Map.Entry<DotName, Set<String>> entry : registrar.getAdditionalQualifiers().entrySet()) { DotName dotName = entry.getKey(); - ClassInfo classInfo = getClassByName(this.beanArchiveIndex, dotName); + ClassInfo classInfo = getClassByName(getBeanArchiveIndex(), dotName); if (classInfo != null) { Set<String> nonbindingMembers = entry.getValue(); if (nonbindingMembers == null) { @@ -156,15 +158,15 @@ public class BeanDeployment { } } } - repeatingQualifierAnnotations = findContainerAnnotations(qualifiers, this.beanArchiveIndex); + repeatingQualifierAnnotations = findContainerAnnotations(qualifiers); buildContextPut(Key.QUALIFIERS.asString(), Collections.unmodifiableMap(qualifiers)); interceptorNonbindingMembers = new HashMap<>(); - interceptorBindings = findInterceptorBindings(this.beanArchiveIndex); + interceptorBindings = findInterceptorBindings(); for (InterceptorBindingRegistrar registrar : builder.interceptorBindingRegistrars) { for (InterceptorBindingRegistrar.InterceptorBinding binding : registrar.getAdditionalBindings()) { DotName dotName = binding.getName(); - ClassInfo annotationClass = getClassByName(this.beanArchiveIndex, dotName); + ClassInfo annotationClass = getClassByName(getBeanArchiveIndex(), dotName); if (annotationClass != null) { Set<String> nonbinding = new HashSet<>(); for (MethodInfo method : annotationClass.methods()) { @@ -177,7 +179,7 @@ public class BeanDeployment { interceptorBindings.put(dotName, annotationClass); } } - repeatingInterceptorBindingAnnotations = findContainerAnnotations(interceptorBindings, this.beanArchiveIndex); + repeatingInterceptorBindingAnnotations = findContainerAnnotations(interceptorBindings); buildContextPut(Key.INTERCEPTOR_BINDINGS.asString(), Collections.unmodifiableMap(interceptorBindings)); Set<DotName> additionalStereotypes = new HashSet<>(); @@ -185,12 +187,11 @@ public class BeanDeployment { additionalStereotypes.addAll(stereotypeRegistrar.getAdditionalStereotypes()); } - this.stereotypes = findStereotypes(this.beanArchiveIndex, interceptorBindings, customContexts, additionalStereotypes, + this.stereotypes = findStereotypes(interceptorBindings, customContexts, additionalStereotypes, annotationStore); buildContextPut(Key.STEREOTYPES.asString(), Collections.unmodifiableMap(stereotypes)); this.transitiveInterceptorBindings = findTransitiveInterceptorBindings(interceptorBindings.keySet(), - this.beanArchiveIndex, new HashMap<>(), interceptorBindings, annotationStore); this.injectionPoints = new CopyOnWriteArrayList<>(); @@ -199,7 +200,7 @@ public class BeanDeployment { this.beans = new CopyOnWriteArrayList<>(); this.observers = new CopyOnWriteArrayList<>(); - this.assignabilityCheck = new AssignabilityCheck(beanArchiveIndex, applicationIndex); + this.assignabilityCheck = new AssignabilityCheck(getBeanArchiveIndex(), applicationIndex); this.beanResolver = new BeanResolverImpl(this); this.delegateInjectionPointResolver = new DelegateInjectionPointResolverImpl(this); this.interceptorResolver = new InterceptorResolver(this); @@ -517,12 +518,17 @@ public Collection<StereotypeInfo> getStereotypes() { } /** - * This index was used to discover components (beans, interceptors, qualifiers, etc.) and during type-safe resolution. + * Returns the index that was used during discovery and type-safe resolution. + * <p> + * In general, the returned index is usually "computing" which means that it attempts to compute the information for the + * classes that were not part of the initial bean archive index. I.e. the returned index corresponds to + * {@link BeanProcessor.Builder#setComputingBeanArchiveIndex(IndexView)}. However, if the computing index was not set then + * the index set by {@link BeanProcessor.Builder#setImmutableBeanArchiveIndex(IndexView)} is used instead. * * @return the bean archive index */ public IndexView getBeanArchiveIndex() { - return beanArchiveIndex; + return beanArchiveComputingIndex != null ? beanArchiveComputingIndex : beanArchiveImmutableIndex; } /** @@ -670,9 +676,9 @@ private void buildContextPut(String key, Object value) { } } - private Map<DotName, ClassInfo> findQualifiers(IndexView index) { + private Map<DotName, ClassInfo> findQualifiers() { Map<DotName, ClassInfo> qualifiers = new HashMap<>(); - for (AnnotationInstance qualifier : index.getAnnotations(DotNames.QUALIFIER)) { + for (AnnotationInstance qualifier : beanArchiveImmutableIndex.getAnnotations(DotNames.QUALIFIER)) { ClassInfo qualifierClass = qualifier.target().asClass(); if (isExcluded(qualifierClass)) { continue; @@ -682,23 +688,23 @@ private Map<DotName, ClassInfo> findQualifiers(IndexView index) { return qualifiers; } - private Map<DotName, ClassInfo> findContainerAnnotations(Map<DotName, ClassInfo> annotations, IndexView index) { + private Map<DotName, ClassInfo> findContainerAnnotations(Map<DotName, ClassInfo> annotations) { Map<DotName, ClassInfo> containerAnnotations = new HashMap<>(); for (ClassInfo annotation : annotations.values()) { AnnotationInstance repeatableMetaAnnotation = annotation.declaredAnnotation(DotNames.REPEATABLE); if (repeatableMetaAnnotation != null) { DotName containerAnnotationName = repeatableMetaAnnotation.value().asClass().name(); - ClassInfo containerClass = getClassByName(index, containerAnnotationName); + ClassInfo containerClass = getClassByName(getBeanArchiveIndex(), containerAnnotationName); containerAnnotations.put(containerAnnotationName, containerClass); } } return containerAnnotations; } - private Map<DotName, ClassInfo> findInterceptorBindings(IndexView index) { + private Map<DotName, ClassInfo> findInterceptorBindings() { Map<DotName, ClassInfo> bindings = new HashMap<>(); // Note: doesn't use AnnotationStore, this will operate on classes without applying annotation transformers - for (AnnotationInstance binding : index.getAnnotations(DotNames.INTERCEPTOR_BINDING)) { + for (AnnotationInstance binding : beanArchiveImmutableIndex.getAnnotations(DotNames.INTERCEPTOR_BINDING)) { ClassInfo bindingClass = binding.target().asClass(); if (isExcluded(bindingClass)) { continue; @@ -709,7 +715,6 @@ private Map<DotName, ClassInfo> findInterceptorBindings(IndexView index) { } private static Map<DotName, Set<AnnotationInstance>> findTransitiveInterceptorBindings(Collection<DotName> initialBindings, - IndexView index, Map<DotName, Set<AnnotationInstance>> result, Map<DotName, ClassInfo> interceptorBindings, AnnotationStore annotationStore) { // for all known interceptor bindings @@ -748,20 +753,20 @@ private static Set<AnnotationInstance> recursiveBuild(DotName name, return result; } - private Map<DotName, StereotypeInfo> findStereotypes(IndexView index, Map<DotName, ClassInfo> interceptorBindings, + private Map<DotName, StereotypeInfo> findStereotypes(Map<DotName, ClassInfo> interceptorBindings, Map<ScopeInfo, Function<MethodCreator, ResultHandle>> customContexts, Set<DotName> additionalStereotypes, AnnotationStore annotationStore) { Map<DotName, StereotypeInfo> stereotypes = new HashMap<>(); Set<DotName> stereotypeNames = new HashSet<>(); - for (AnnotationInstance annotation : index.getAnnotations(DotNames.STEREOTYPE)) { + for (AnnotationInstance annotation : beanArchiveImmutableIndex.getAnnotations(DotNames.STEREOTYPE)) { stereotypeNames.add(annotation.target().asClass().name()); } stereotypeNames.addAll(additionalStereotypes); for (DotName stereotypeName : stereotypeNames) { - ClassInfo stereotypeClass = getClassByName(index, stereotypeName); + ClassInfo stereotypeClass = getClassByName(getBeanArchiveIndex(), stereotypeName); if (stereotypeClass != null && !isExcluded(stereotypeClass)) { boolean isAlternative = false; @@ -852,7 +857,8 @@ private List<BeanInfo> findBeans(Collection<DotName> beanDefiningAnnotations, Li .map(StereotypeInfo::getName) .collect(Collectors.toSet()); - for (ClassInfo beanClass : beanArchiveIndex.getKnownClasses()) { + // If needed use the specialized immutable index to discover beans + for (ClassInfo beanClass : beanArchiveImmutableIndex.getKnownClasses()) { if (Modifier.isInterface(beanClass.flags()) || Modifier.isAbstract(beanClass.flags()) || beanClass.isAnnotation() || beanClass.isEnum()) { @@ -987,7 +993,7 @@ private List<BeanInfo> findBeans(Collection<DotName> beanDefiningAnnotations, Li } DotName superType = aClass.superName(); aClass = superType != null && !superType.equals(DotNames.OBJECT) - ? getClassByName(beanArchiveIndex, superType) + ? getClassByName(getBeanArchiveIndex(), superType) : null; } for (FieldInfo field : beanClass.fields()) { @@ -1233,7 +1239,7 @@ static void processErrors(List<Throwable> errors) { private List<InterceptorInfo> findInterceptors(List<InjectionPointInfo> injectionPoints) { Map<DotName, ClassInfo> interceptorClasses = new HashMap<>(); - for (AnnotationInstance annotation : beanArchiveIndex.getAnnotations(DotNames.INTERCEPTOR)) { + for (AnnotationInstance annotation : beanArchiveImmutableIndex.getAnnotations(DotNames.INTERCEPTOR)) { if (Kind.CLASS.equals(annotation.target().kind())) { interceptorClasses.put(annotation.target().asClass().name(), annotation.target().asClass()); } @@ -1260,7 +1266,7 @@ private List<InterceptorInfo> findInterceptors(List<InjectionPointInfo> injectio private List<DecoratorInfo> findDecorators(List<InjectionPointInfo> injectionPoints) { Map<DotName, ClassInfo> decoratorClasses = new HashMap<>(); - for (AnnotationInstance annotation : beanArchiveIndex.getAnnotations(DotNames.DECORATOR)) { + for (AnnotationInstance annotation : beanArchiveImmutableIndex.getAnnotations(DotNames.DECORATOR)) { if (Kind.CLASS.equals(annotation.target().kind())) { decoratorClasses.put(annotation.target().asClass().name(), annotation.target().asClass()); } diff --git a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanProcessor.java b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanProcessor.java index b869031c546..4427cfe4bea 100644 --- a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanProcessor.java +++ b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanProcessor.java @@ -91,7 +91,10 @@ private BeanProcessor(Builder builder) { this.applicationClassPredicate = builder.applicationClassPredicate; this.name = builder.name; this.output = builder.output; - this.annotationLiterals = new AnnotationLiteralProcessor(builder.beanArchiveIndex, applicationClassPredicate); + this.annotationLiterals = new AnnotationLiteralProcessor( + builder.beanArchiveComputingIndex != null ? builder.beanArchiveComputingIndex + : builder.beanArchiveImmutableIndex, + applicationClassPredicate); this.generateSources = builder.generateSources; this.allowMocking = builder.allowMocking; this.transformUnproxyableClasses = builder.transformUnproxyableClasses; @@ -99,7 +102,9 @@ private BeanProcessor(Builder builder) { // Initialize all build processors buildContext = new BuildContextImpl(); - buildContext.putInternal(Key.INDEX.asString(), builder.beanArchiveIndex); + buildContext.putInternal(Key.INDEX.asString(), + builder.beanArchiveComputingIndex != null ? builder.beanArchiveComputingIndex + : builder.beanArchiveImmutableIndex); this.beanRegistrars = initAndSort(builder.beanRegistrars, buildContext); this.observerRegistrars = initAndSort(builder.observerRegistrars, buildContext); @@ -440,7 +445,8 @@ public Predicate<DotName> getInjectionPointAnnotationsPredicate() { public static class Builder { String name; - IndexView beanArchiveIndex; + IndexView beanArchiveComputingIndex; + IndexView beanArchiveImmutableIndex; IndexView applicationIndex; Collection<BeanDefiningAnnotation> additionalBeanDefiningAnnotations; ResourceOutput output; @@ -510,14 +516,33 @@ public Builder setName(String name) { } /** - * Set the bean archive index. This index is mandatory and is used to discover components (beans, interceptors, - * qualifiers, etc.) and during type-safe resolution. + * Set the computing bean archive index. This index is optional and can be used for example during type-safe resolution. + * If it's not set then the immutable index is used instead. + * <p> + * The computing index must be built on top of the immutable index and compute only the classes that are not part of the + * immutable index. + * <p> + * This index is never used to discover components (beans, observers, etc.). + * + * @param index + * @return self + * @see Builder#setImmutableBeanArchiveIndex(IndexView) + */ + public Builder setComputingBeanArchiveIndex(IndexView index) { + this.beanArchiveComputingIndex = index; + return this; + } + + /** + * Set the immutable bean archive index. This index is mandatory and is used to discover components (beans, observers, + * etc.). * - * @param beanArchiveIndex + * @param index * @return self + * @see Builder#setComputingBeanArchiveIndex(IndexView) */ - public Builder setBeanArchiveIndex(IndexView beanArchiveIndex) { - this.beanArchiveIndex = beanArchiveIndex; + public Builder setImmutableBeanArchiveIndex(IndexView index) { + this.beanArchiveImmutableIndex = index; return this; } @@ -526,11 +551,11 @@ public Builder setBeanArchiveIndex(IndexView beanArchiveIndex) { * <p> * Some types may not be part of the bean archive index but are still needed during type-safe resolution. * - * @param applicationIndex + * @param index * @return self */ - public Builder setApplicationIndex(IndexView applicationIndex) { - this.applicationIndex = applicationIndex; + public Builder setApplicationIndex(IndexView index) { + this.applicationIndex = index; return this; } diff --git a/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/BeanInfoInjectionsTest.java b/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/BeanInfoInjectionsTest.java index 981ae74c5bd..ff22bbd5688 100644 --- a/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/BeanInfoInjectionsTest.java +++ b/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/BeanInfoInjectionsTest.java @@ -42,7 +42,7 @@ public void testInjections() throws IOException { Type listStringType = ParameterizedType.create(name(List.class), new Type[] { Type.create(name(String.class), Kind.CLASS) }, null); - BeanDeployment deployment = BeanProcessor.builder().setBeanArchiveIndex(index).build().getBeanDeployment(); + BeanDeployment deployment = BeanProcessor.builder().setImmutableBeanArchiveIndex(index).build().getBeanDeployment(); deployment.registerCustomContexts(Collections.emptyList()); deployment.registerBeans(Collections.emptyList()); BeanInfo barBean = deployment.getBeans().stream().filter(b -> b.getTarget().get().equals(barClass)).findFirst().get(); diff --git a/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/BeanInfoQualifiersTest.java b/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/BeanInfoQualifiersTest.java index 6e5203478b4..3c95a2c557f 100644 --- a/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/BeanInfoQualifiersTest.java +++ b/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/BeanInfoQualifiersTest.java @@ -37,7 +37,7 @@ public void testQualifiers() throws IOException { ClassInfo fooClass = index.getClassByName(fooName); BeanInfo bean = Beans.createClassBean(fooClass, - BeanProcessor.builder().setBeanArchiveIndex(index).build().getBeanDeployment(), + BeanProcessor.builder().setImmutableBeanArchiveIndex(index).build().getBeanDeployment(), null); AnnotationInstance requiredFooQualifier = index.getAnnotations(fooQualifierName).stream() diff --git a/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/BeanInfoTypesTest.java b/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/BeanInfoTypesTest.java index 75dd27ee2e3..bc53674cd78 100644 --- a/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/BeanInfoTypesTest.java +++ b/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/BeanInfoTypesTest.java @@ -37,7 +37,7 @@ public void testResolver() throws IOException { Collection.class, List.class, Iterable.class, Object.class, String.class); - BeanDeployment deployment = BeanProcessor.builder().setBeanArchiveIndex(index).build().getBeanDeployment(); + BeanDeployment deployment = BeanProcessor.builder().setImmutableBeanArchiveIndex(index).build().getBeanDeployment(); DotName fooName = name(Foo.class); ClassInfo fooClass = index.getClassByName(fooName); diff --git a/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/TypesTest.java b/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/TypesTest.java index b6bcc935947..fbe3e19e240 100644 --- a/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/TypesTest.java +++ b/independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/TypesTest.java @@ -32,7 +32,8 @@ public void testGetTypeClosure() throws IOException { DotName producerName = DotName.createSimple(Producer.class.getName()); ClassInfo fooClass = index.getClassByName(fooName); Map<ClassInfo, Map<String, Type>> resolvedTypeVariables = new HashMap<>(); - BeanDeployment dummyDeployment = BeanProcessor.builder().setBeanArchiveIndex(index).build().getBeanDeployment(); + BeanDeployment dummyDeployment = BeanProcessor.builder().setImmutableBeanArchiveIndex(index).build() + .getBeanDeployment(); // Baz, Foo<String>, Object Set<Type> bazTypes = Types.getTypeClosure(index.getClassByName(bazName), null, diff --git a/independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/ArcTestContainer.java b/independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/ArcTestContainer.java index 6d428b83335..fda3d072e71 100644 --- a/independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/ArcTestContainer.java +++ b/independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/ArcTestContainer.java @@ -20,6 +20,7 @@ import org.jboss.jandex.DotName; import org.jboss.jandex.Index; +import org.jboss.jandex.IndexView; import org.jboss.jandex.Indexer; import org.junit.jupiter.api.extension.AfterEachCallback; import org.junit.jupiter.api.extension.BeforeEachCallback; @@ -322,14 +323,14 @@ private ClassLoader init(ExtensionContext context) { Arc.shutdown(); // Build index - Index beanArchiveIndex; + IndexView immutableBeanArchiveIndex; try { - beanArchiveIndex = index(beanClasses); + immutableBeanArchiveIndex = BeanArchives.buildImmutableBeanArchiveIndex(index(beanClasses)); } catch (IOException e) { throw new IllegalStateException("Failed to create index", e); } - Index applicationIndex; + IndexView applicationIndex; if (additionalClasses.isEmpty()) { applicationIndex = null; } else { @@ -370,8 +371,9 @@ private ClassLoader init(ExtensionContext context) { BeanProcessor.Builder builder = BeanProcessor.builder() .setName(testClass.getSimpleName()) - .setBeanArchiveIndex(BeanArchives.buildBeanArchiveIndex(getClass().getClassLoader(), - new ConcurrentHashMap<>(), beanArchiveIndex)) + .setImmutableBeanArchiveIndex(immutableBeanArchiveIndex) + .setComputingBeanArchiveIndex(BeanArchives.buildComputingBeanArchiveIndex(getClass().getClassLoader(), + new ConcurrentHashMap<>(), immutableBeanArchiveIndex)) .setApplicationIndex(applicationIndex); if (!resourceAnnotations.isEmpty()) { builder.addResourceAnnotations(resourceAnnotations.stream()
['independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/AnnotationLiteralProcessor.java', 'independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanDeployment.java', 'extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/ArcProcessor.java', 'extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/BeanArchiveProcessor.java', 'independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/TypesTest.java', 'independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/BeanInfoTypesTest.java', 'extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/BeanArchiveIndexBuildItem.java', 'extensions/spring-scheduled/deployment/src/test/java/io/quarkus/spring/scheduled/deployment/SpringScheduledProcessorTest.java', 'independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/BeanInfoQualifiersTest.java', 'extensions/spring-di/deployment/src/test/java/io/quarkus/spring/di/deployment/SpringDIProcessorTest.java', 'independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanProcessor.java', 'independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/ArcTestContainer.java', 'independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/BeanArchives.java', 'independent-projects/arc/processor/src/test/java/io/quarkus/arc/processor/BeanInfoInjectionsTest.java']
{'.java': 14}
14
14
0
0
14
23,990,922
4,724,032
612,253
5,613
10,864
2,057
167
7
3,826
366
949
67
2
2
1970-01-01T00:27:49
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,309
quarkusio/quarkus/29674/29469
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/29469
https://github.com/quarkusio/quarkus/pull/29674
https://github.com/quarkusio/quarkus/pull/29674
1
fix
Response Body in ClientExceptionMapper is always null
### Describe the bug We implemented a REST-Client using the quarkus-rest-client-reactive dependency. For this client we added custom exception handling using the `@ClientExceptionMapper` annotation. There we could read the body of the response. e.g.: ```java @ClientExceptionMapper static ServiceException handle(Response response) { response.bufferEntity(); Error error = response.readEntity(Error.class); return new ServiceException(error.getReason(), error.getMessage(), response.getStatus()); } ``` Now with the new version the entity object is always null. (So error.getMessag will throw a NullPointerException) (Also if we jus handle the WebApplicationException we can't read the body because its null) For the status everything works fine. This works for quarkus-plattform version 2.13.3 but not in version 2.14.1. ### Expected behavior The error object should be the parsed (json-)-response-object. ### Actual behavior The error object is null because the entity of response is null. ### How to Reproduce? 1. Create a rest-client 2. Make a request that will fail (400, 404, ...) 3. Handle the custom/WebApplicationException 4. read the response body from the exception ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` openjdk version "17.0.2" 2022-01-18 OpenJDK Runtime Environment (build 17.0.2+8-86) OpenJDK 64-Bit Server VM (build 17.0.2+8-86, mixed mode, sharing) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.2 (ea98e05a04480131370aa0c110b8c54cf726c06f) ### Additional information _No response_
35b6eae2ffe4ba963a485a93fb10bf2306b0420b
bd57642ab2d5451a5652e0cf2f318f1cd9c402c1
https://github.com/quarkusio/quarkus/compare/35b6eae2ffe4ba963a485a93fb10bf2306b0420b...bd57642ab2d5451a5652e0cf2f318f1cd9c402c1
diff --git a/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/BasicRestClientTest.java b/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/BasicRestClientTest.java index ab885f48c38..3148c53acf5 100644 --- a/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/BasicRestClientTest.java +++ b/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/BasicRestClientTest.java @@ -1,10 +1,7 @@ package io.quarkus.rest.client.reactive; -import static io.restassured.RestAssured.given; import static org.assertj.core.api.Assertions.assertThat; -import static org.awaitility.Awaitility.await; -import java.time.Duration; import java.util.Map; import java.util.Set; @@ -75,23 +72,4 @@ void shouldMapQueryParamsWithSpecialCharacters() { assertThat(map.get("p5")).isEqualTo("5"); assertThat(map.get("p6")).isEqualTo("6"); } - - /** - * Test to reproduce https://github.com/quarkusio/quarkus/issues/28818. - */ - @Test - void shouldCloseConnectionsWhenFailures() { - // It's using 30 seconds because it's the default timeout to release connections. This timeout should not be taken into - // account when there are failures, and we should be able to call 3 times to the service without waiting. - await().atMost(Duration.ofSeconds(30)) - .until(() -> { - for (int call = 0; call < 3; call++) { - given() - .when().get("/hello/callClientForImageInfo") - .then() - .statusCode(500); - } - return true; - }); - } } diff --git a/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/HelloClient2.java b/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/HelloClient2.java index 2c2c31eab34..660c55a0260 100644 --- a/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/HelloClient2.java +++ b/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/HelloClient2.java @@ -4,7 +4,6 @@ import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; -import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.eclipse.microprofile.rest.client.inject.RegisterRestClient; @@ -24,10 +23,4 @@ public interface HelloClient2 { @GET @Path("delay") Uni<String> delay(); - - @POST - @Path("/imageInfo") - @Consumes("image/gif") - @Produces(MediaType.TEXT_PLAIN) - String imageInfo(byte[] imageFile); } diff --git a/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/HelloResource.java b/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/HelloResource.java index 65b0dc25760..f298c0b3030 100644 --- a/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/HelloResource.java +++ b/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/HelloResource.java @@ -78,23 +78,4 @@ public Uni<String> delay() { return Uni.createFrom().item("Hello") .onItem().delayIt().by(Duration.ofMillis(500)); } - - @Path("callClientForImageInfo") - @GET - public String callClientForImageInfo() { - int size = 1024 * 1024 * 5; - - byte[] buffer = new byte[size]; - - //Should provoke 415 Unsupported Media Type - return client2.imageInfo(buffer); - } - - @POST - @Consumes({ "image/jpeg", "image/png" }) - @Path("/imageInfo") - @Produces(MediaType.TEXT_PLAIN) - public String imageInfo(byte[] imageFile) { - throw new IllegalStateException("This method should never be invoked"); - } } diff --git a/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/handlers/ClientSendRequestHandler.java b/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/handlers/ClientSendRequestHandler.java index 2bf3f434ecb..8d1d7d62c3c 100644 --- a/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/handlers/ClientSendRequestHandler.java +++ b/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/handlers/ClientSendRequestHandler.java @@ -20,7 +20,6 @@ import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; import javax.ws.rs.core.Variant; import org.jboss.logging.Logger; @@ -244,11 +243,6 @@ public void handle(HttpClientResponse clientResponse) { } } - if (Response.Status.Family.familyOf(status) != Response.Status.Family.SUCCESSFUL) { - httpClientRequest.connection().close(); - requestContext.resume(); - } - if (isResponseMultipart(requestContext)) { QuarkusMultipartResponseDecoder multipartDecoder = new QuarkusMultipartResponseDecoder( clientResponse); @@ -372,16 +366,17 @@ public void handle(Buffer buffer) { requestContext.resume(t); } } - }).onFailure(new Handler<>() { - @Override - public void handle(Throwable failure) { - if (failure instanceof IOException) { - requestContext.resume(new ProcessingException(failure)); - } else { - requestContext.resume(failure); - } - } - }); + }) + .onFailure(new Handler<>() { + @Override + public void handle(Throwable failure) { + if (failure instanceof IOException) { + requestContext.resume(new ProcessingException(failure)); + } else { + requestContext.resume(failure); + } + } + }); } private boolean isResponseMultipart(RestClientRequestContext requestContext) {
['extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/HelloResource.java', 'extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/HelloClient2.java', 'independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/handlers/ClientSendRequestHandler.java', 'extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/BasicRestClientTest.java']
{'.java': 4}
4
4
0
0
4
23,970,667
4,720,183
611,794
5,610
1,119
155
27
1
1,780
227
440
60
0
1
1970-01-01T00:27:50
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,308
quarkusio/quarkus/29681/29497
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/29497
https://github.com/quarkusio/quarkus/pull/29681
https://github.com/quarkusio/quarkus/pull/29681
1
fix
Missing spec.template.metadata.labels in deployment
### Describe the bug Following the OpenShift Guide (https://quarkus.io/guides/deploying-to-openshift) I tried to switch from the default DeploymentConfig to Deployment but ended up with the error: ``` Message: Deployment.apps "openshift-quickstart" is invalid: spec.template.metadata.labels: Invalid value: map[string]string(nil): `selector` does not match template `labels`. ``` Looking at the produced openshift.yml I saw that there seems to be missing metadata labels in the spec template: ```yaml --- apiVersion: apps/v1 kind: Deployment metadata: annotations: app.openshift.io/vcs-url: <<unknown>> app.quarkus.io/build-timestamp: 2022-11-25 - 17:08:22 +0000 labels: app.kubernetes.io/version: 1.0.0-SNAPSHOT app.kubernetes.io/name: openshift-quickstart app.openshift.io/runtime: quarkus name: openshift-quickstart spec: replicas: 1 selector: matchLabels: app.kubernetes.io/name: openshift-quickstart app.kubernetes.io/version: 1.0.0-SNAPSHOT template: spec: containers: - env: - name: JAVA_APP_JAR value: /deployments/quarkus-run.jar image: image-registry.openshift-image-registry.svc:5000/quarkus-test/openshift-quickstart:1.0.0-SNAPSHOT imagePullPolicy: Always name: openshift-quickstart ports: - containerPort: 8080 name: http protocol: TCP --- ``` ### Expected behavior Ending up with a working Deployment when using the config "quarkus.openshift.deployment-kind=Deployment" ### Actual behavior ```posh [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 49.388 s [INFO] Finished at: 2022-11-25T18:08:46+01:00 [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal io.quarkus.platform:quarkus-maven-plugin:2.14.1.Final:build (default) on project openshift-quickstart: Failed to build quarkus application: io.quarkus.builder.BuildException: Build failure: Build failed due to errors [ERROR] [error]: Build step io.quarkus.kubernetes.deployment.KubernetesDeployer#deploy threw an exception: io.fabric8.kubernetes.client.KubernetesClientException: Failure executing: POST at: https://api.crc.testing:6443/apis/apps/v1/namespaces/quarkus-test/deployments. Message: Deployment.apps "openshift-quickstart" is invalid: spec.template.metadata.labels: Invalid value: map[string]string(nil): `selector` does not match template `labels`. Received status: Status(apiVersion=v1, code=422, details=StatusDetails(causes=[StatusCause(field=spec.template.metadata.labels, message=Invalid value: map[string]string(nil): `selector` does not match template `labels`, reason=FieldValueInvalid, additionalProperties={})], group=apps, kind=Deployment, name=openshift-quickstart, retryAfterSeconds=null, uid=null, additionalProperties={}), kind=Status, message=Deployment.apps "openshift-quickstart" is invalid: spec.template.metadata.labels: Invalid value: map[string]string(nil): `selector` does not match template `labels`, metadata=ListMeta(_continue=null, remainingItemCount=null, resourceVersion=null, selfLink=null, additionalProperties={}), reason=Invalid, status=Failure, additionalProperties={}). [ERROR] at io.fabric8.kubernetes.client.KubernetesClientException.copyAsCause(KubernetesClientException.java:238) [ERROR] at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.waitForResult(OperationSupport.java:517) [ERROR] at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.handleResponse(OperationSupport.java:551) [ERROR] at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.handleResponse(OperationSupport.java:535) [ERROR] at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.handleCreate(OperationSupport.java:328) [ERROR] at io.fabric8.kubernetes.client.dsl.internal.BaseOperation.handleCreate(BaseOperation.java:675) [ERROR] at io.fabric8.kubernetes.client.dsl.internal.BaseOperation.handleCreate(BaseOperation.java:88) [ERROR] at io.fabric8.kubernetes.client.dsl.internal.CreateOnlyResourceOperation.create(CreateOnlyResourceOperation.java:42) [ERROR] at io.fabric8.kubernetes.client.utils.internal.CreateOrReplaceHelper.createOrReplace(CreateOrReplaceHelper.java:50) [ERROR] at io.fabric8.kubernetes.client.dsl.internal.BaseOperation.createOrReplace(BaseOperation.java:296) [ERROR] at io.fabric8.kubernetes.client.dsl.internal.BaseOperation.createOrReplace(BaseOperation.java:88) [ERROR] at io.fabric8.kubernetes.client.extension.ResourceAdapter.createOrReplace(ResourceAdapter.java:121) [ERROR] at io.quarkus.kubernetes.deployment.KubernetesDeployer.lambda$deploy$5(KubernetesDeployer.java:251) [ERROR] at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183) [ERROR] at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179) [ERROR] at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625) [ERROR] at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509) [ERROR] at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499) [ERROR] at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150) [ERROR] at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173) [ERROR] at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) [ERROR] at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:596) [ERROR] at io.quarkus.kubernetes.deployment.KubernetesDeployer.deploy(KubernetesDeployer.java:226) [ERROR] at io.quarkus.kubernetes.deployment.KubernetesDeployer.deploy(KubernetesDeployer.java:135) [ERROR] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [ERROR] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) [ERROR] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [ERROR] at java.base/java.lang.reflect.Method.invoke(Method.java:568) [ERROR] at io.quarkus.deployment.ExtensionLoader$3.execute(ExtensionLoader.java:909) [ERROR] at io.quarkus.builder.BuildContext.run(BuildContext.java:281) [ERROR] at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) [ERROR] at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) [ERROR] at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478) [ERROR] at java.base/java.lang.Thread.run(Thread.java:833) [ERROR] at org.jboss.threads.JBossThread.run(JBossThread.java:501) [ERROR] Caused by: io.fabric8.kubernetes.client.KubernetesClientException: Failure executing: POST at: https://api.crc.testing:6443/apis/apps/v1/namespaces/quarkus-test/deployments. Message: Deployment.apps "openshift-quickstart" is invalid: spec.template.metadata.labels: Invalid value: map[string]string(nil): `selector` does not match template `labels`. Received status: Status(apiVersion=v1, code=422, details=StatusDetails(causes=[StatusCause(field=spec.template.metadata.labels, message=Invalid value: map[string]string(nil): `selector` does not match template `labels`, reason=FieldValueInvalid, additionalProperties={})], group=apps, kind=Deployment, name=openshift-quickstart, retryAfterSeconds=null, uid=null, additionalProperties={}), kind=Status, message=Deployment.apps "openshift-quickstart" is invalid: spec.template.metadata.labels: Invalid value: map[string]string(nil): `selector` does not match template `labels`, metadata=ListMeta(_continue=null, remainingItemCount=null, resourceVersion=null, selfLink=null, additionalProperties={}), reason=Invalid, status=Failure, additionalProperties={}). [ERROR] at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.requestFailure(OperationSupport.java:709) [ERROR] at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.requestFailure(OperationSupport.java:689) [ERROR] at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.assertResponseCode(OperationSupport.java:640) [ERROR] at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.lambda$handleResponse$0(OperationSupport.java:576) [ERROR] at java.base/java.util.concurrent.CompletableFuture$UniApply.tryFire(CompletableFuture.java:646) [ERROR] at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:510) [ERROR] at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2147) [ERROR] at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.lambda$retryWithExponentialBackoff$2(OperationSupport.java:618) [ERROR] at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:863) [ERROR] at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:841) [ERROR] at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:510) [ERROR] at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2147) [ERROR] at io.fabric8.kubernetes.client.okhttp.OkHttpClientImpl$4.onResponse(OkHttpClientImpl.java:277) [ERROR] at okhttp3.RealCall$AsyncCall.execute(RealCall.java:174) [ERROR] at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) [ERROR] at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) [ERROR] at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) [ERROR] at java.base/java.lang.Thread.run(Thread.java:833) [ERROR] -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException ``` ### How to Reproduce? 1. mvn io.quarkus.platform:quarkus-maven-plugin:2.14.1.Final:create -DprojectGroupId=org.acme -DprojectArtifactId=openshift-quickstart -Dextensions="resteasy-reactive,openshift" 2. cd openshift-quickstart 3. mvnw install -Dquarkus.kubernetes.deploy=true -Dquarkus.openshift.deployment-kind=Deployment -Dquarkus.container-image.group=quarkus-test ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` Java version: 17.0.3 ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.6 ### Additional information _No response_
36c5fa542edbf49351e2b9ee0392fd56863452e4
e673ea5989f422866bcd37cfac05fac6453f13d0
https://github.com/quarkusio/quarkus/compare/36c5fa542edbf49351e2b9ee0392fd56863452e4...e673ea5989f422866bcd37cfac05fac6453f13d0
diff --git a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddDeploymentResourceDecorator.java b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddDeploymentResourceDecorator.java index c877ad32e26..2afcf46e728 100644 --- a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddDeploymentResourceDecorator.java +++ b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddDeploymentResourceDecorator.java @@ -24,6 +24,8 @@ public void visit(KubernetesListFluent<?> list) { .withMatchLabels(new HashMap<String, String>()) .endSelector() .withNewTemplate() + .withNewMetadata() + .endMetadata() .withNewSpec() .addNewContainer() .withName(name) diff --git a/integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/OpenshiftWithDeploymentResourceTest.java b/integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/OpenshiftWithDeploymentResourceTest.java index d4e5ae89ea8..4b86271cfdc 100644 --- a/integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/OpenshiftWithDeploymentResourceTest.java +++ b/integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/OpenshiftWithDeploymentResourceTest.java @@ -2,6 +2,7 @@ package io.quarkus.it.kubernetes; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; import java.io.IOException; import java.nio.file.Path; @@ -29,10 +30,12 @@ // public class OpenshiftWithDeploymentResourceTest { + private static final String NAME = "openshift-with-deployment-resource"; + @RegisterExtension static final QuarkusProdModeTest config = new QuarkusProdModeTest() .withApplicationRoot((jar) -> jar.addClasses(GreetingResource.class)) - .setApplicationName("openshift-with-deployment-resource") + .setApplicationName(NAME) .setApplicationVersion("0.1-SNAPSHOT") .overrideConfigKey("quarkus.openshift.deployment-kind", "Deployment") .overrideConfigKey("quarkus.openshift.replicas", "3") @@ -55,17 +58,21 @@ public void assertGeneratedResources() throws IOException { assertThat(kubernetesList).filteredOn(h -> "BuildConfig".equals(h.getKind())).hasSize(1); assertThat(kubernetesList).filteredOn(h -> "ImageStream".equals(h.getKind())).hasSize(2); assertThat(kubernetesList).filteredOn(h -> "ImageStream".equals(h.getKind()) - && h.getMetadata().getName().equals("openshift-with-deployment-resource")).hasSize(1); + && h.getMetadata().getName().equals(NAME)).hasSize(1); assertThat(kubernetesList).filteredOn(i -> i instanceof Deployment).singleElement().satisfies(i -> { assertThat(i).isInstanceOfSatisfying(Deployment.class, d -> { assertThat(d.getMetadata()).satisfies(m -> { - assertThat(m.getName()).isEqualTo("openshift-with-deployment-resource"); + assertThat(m.getName()).isEqualTo(NAME); }); assertThat(d.getSpec()).satisfies(deploymentSpec -> { assertThat(deploymentSpec.getReplicas()).isEqualTo(3); assertThat(deploymentSpec.getTemplate()).satisfies(t -> { + assertThat(t.getMetadata()).satisfies(metadata -> assertThat(metadata.getLabels()).containsAnyOf( + entry("app.kubernetes.io/name", NAME), + entry("app.kubernetes.io/version", "0.1-SNAPSHOT"))); + assertThat(t.getSpec()).satisfies(podSpec -> { assertThat(podSpec.getContainers()).singleElement().satisfies(container -> { assertThat(container.getImage())
['integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/OpenshiftWithDeploymentResourceTest.java', 'extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddDeploymentResourceDecorator.java']
{'.java': 2}
2
2
0
0
2
23,993,963
4,724,588
612,326
5,614
67
11
2
1
11,351
606
2,624
151
4
3
1970-01-01T00:27:50
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,306
quarkusio/quarkus/29683/29663
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/29663
https://github.com/quarkusio/quarkus/pull/29683
https://github.com/quarkusio/quarkus/pull/29683
1
fixes
gradle addExtension fails if you have no root properties file defined
### Describe the bug Running `gradle addExtension --extensions='container-image-jib'` with no root properties file, I.E. `gradle.properties` fails. ### Expected behavior I would expect the extension to be added successfully. ### Actual behavior ``` ❯ gradle addExtension --extensions='container-image-jib' > Task :lib:addExtension FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':lib:addExtension'. > Failed to add extensions [container-image-jib] * Try: > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. > Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 566ms 1 actionable task: 1 executed ``` Running with `--stacktrace`: ``` org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':lib:addExtension'. at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.lambda$executeIfValid$1(ExecuteActionsTaskExecuter.java:142) at org.gradle.internal.Try$Failure.ifSuccessfulOrElse(Try.java:282) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:140) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:128) at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:77) at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46) at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:51) at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57) at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56) at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52) at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:204) at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:199) at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66) at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59) at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:53) at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:73) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52) at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:69) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:327) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:314) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:307) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:293) at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:420) at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:342) at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64) at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48) Caused by: org.gradle.api.GradleException: Failed to add extensions [container-image-jib] at io.quarkus.gradle.tasks.QuarkusAddExtension.addExtension(QuarkusAddExtension.java:47) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:125) at org.gradle.api.internal.project.taskfactory.StandardTaskAction.doExecute(StandardTaskAction.java:58) at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:51) at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:29) at org.gradle.api.internal.tasks.execution.TaskExecution$3.run(TaskExecution.java:236) at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:29) at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:26) at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66) at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59) at org.gradle.internal.operations.DefaultBuildOperationRunner.run(DefaultBuildOperationRunner.java:47) at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:68) at org.gradle.api.internal.tasks.execution.TaskExecution.executeAction(TaskExecution.java:221) at org.gradle.api.internal.tasks.execution.TaskExecution.executeActions(TaskExecution.java:204) at org.gradle.api.internal.tasks.execution.TaskExecution.executeWithPreviousOutputFiles(TaskExecution.java:187) at org.gradle.api.internal.tasks.execution.TaskExecution.execute(TaskExecution.java:165) at org.gradle.internal.execution.steps.ExecuteStep.executeInternal(ExecuteStep.java:89) at org.gradle.internal.execution.steps.ExecuteStep.access$000(ExecuteStep.java:40) at org.gradle.internal.execution.steps.ExecuteStep$1.call(ExecuteStep.java:53) at org.gradle.internal.execution.steps.ExecuteStep$1.call(ExecuteStep.java:50) at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:204) at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:199) at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66) at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59) at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:53) at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:73) at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:50) at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:40) at org.gradle.internal.execution.steps.RemovePreviousOutputsStep.execute(RemovePreviousOutputsStep.java:68) at org.gradle.internal.execution.steps.RemovePreviousOutputsStep.execute(RemovePreviousOutputsStep.java:38) at org.gradle.internal.execution.steps.CancelExecutionStep.execute(CancelExecutionStep.java:41) at org.gradle.internal.execution.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:74) at org.gradle.internal.execution.steps.TimeoutStep.execute(TimeoutStep.java:55) at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:51) at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:29) at org.gradle.internal.execution.steps.CaptureStateAfterExecutionStep.executeDelegateBroadcastingChanges(CaptureStateAfterExecutionStep.java:124) at org.gradle.internal.execution.steps.CaptureStateAfterExecutionStep.execute(CaptureStateAfterExecutionStep.java:80) at org.gradle.internal.execution.steps.CaptureStateAfterExecutionStep.execute(CaptureStateAfterExecutionStep.java:58) at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:48) at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:36) at org.gradle.internal.execution.steps.BuildCacheStep.executeWithoutCache(BuildCacheStep.java:181) at org.gradle.internal.execution.steps.BuildCacheStep.lambda$execute$1(BuildCacheStep.java:71) at org.gradle.internal.Either$Right.fold(Either.java:175) at org.gradle.internal.execution.caching.CachingState.fold(CachingState.java:59) at org.gradle.internal.execution.steps.BuildCacheStep.execute(BuildCacheStep.java:69) at org.gradle.internal.execution.steps.BuildCacheStep.execute(BuildCacheStep.java:47) at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:36) at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:25) at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:36) at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:22) at org.gradle.internal.execution.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:110) at org.gradle.internal.execution.steps.SkipUpToDateStep.lambda$execute$2(SkipUpToDateStep.java:56) at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:56) at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:38) at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:73) at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:44) at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:37) at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:27) at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:89) at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:50) at org.gradle.internal.execution.steps.ValidateStep.execute(ValidateStep.java:114) at org.gradle.internal.execution.steps.ValidateStep.execute(ValidateStep.java:57) at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:76) at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:50) at org.gradle.internal.execution.steps.SkipEmptyWorkStep.executeWithNoEmptySources(SkipEmptyWorkStep.java:254) at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:91) at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:56) at org.gradle.internal.execution.steps.RemoveUntrackedExecutionStateStep.execute(RemoveUntrackedExecutionStateStep.java:32) at org.gradle.internal.execution.steps.RemoveUntrackedExecutionStateStep.execute(RemoveUntrackedExecutionStateStep.java:21) at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsStartedStep.execute(MarkSnapshottingInputsStartedStep.java:38) at org.gradle.internal.execution.steps.LoadPreviousExecutionStateStep.execute(LoadPreviousExecutionStateStep.java:43) at org.gradle.internal.execution.steps.LoadPreviousExecutionStateStep.execute(LoadPreviousExecutionStateStep.java:31) at org.gradle.internal.execution.steps.AssignWorkspaceStep.lambda$execute$0(AssignWorkspaceStep.java:40) at org.gradle.api.internal.tasks.execution.TaskExecution$4.withWorkspace(TaskExecution.java:281) at org.gradle.internal.execution.steps.AssignWorkspaceStep.execute(AssignWorkspaceStep.java:40) at org.gradle.internal.execution.steps.AssignWorkspaceStep.execute(AssignWorkspaceStep.java:30) at org.gradle.internal.execution.steps.IdentityCacheStep.execute(IdentityCacheStep.java:37) at org.gradle.internal.execution.steps.IdentityCacheStep.execute(IdentityCacheStep.java:27) at org.gradle.internal.execution.steps.IdentifyStep.execute(IdentifyStep.java:44) at org.gradle.internal.execution.steps.IdentifyStep.execute(IdentifyStep.java:33) at org.gradle.internal.execution.impl.DefaultExecutionEngine$1.execute(DefaultExecutionEngine.java:76) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:139) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:128) at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:77) at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46) at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:51) at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57) at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56) at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52) at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:204) at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:199) at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66) at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157) at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59) at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:53) at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:73) at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52) at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:69) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:327) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:314) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:307) at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:293) at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:420) at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:342) at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64) at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48) Caused by: java.lang.NullPointerException: Cannot invoke "java.util.Properties.store(java.io.OutputStream, String)" because the return value of "io.quarkus.devtools.project.buildfile.AbstractGradleBuildFile$Model.getRootPropertiesContent()" is null at io.quarkus.devtools.project.buildfile.AbstractGradleBuildFile.writeToDisk(AbstractGradleBuildFile.java:50) at io.quarkus.devtools.project.buildfile.GradleProjectBuildFile.writeToDisk(GradleProjectBuildFile.java:20) at io.quarkus.devtools.project.buildfile.BuildFile.install(BuildFile.java:72) at io.quarkus.devtools.commands.handlers.AddExtensionsCommandHandler.execute(AddExtensionsCommandHandler.java:49) at io.quarkus.devtools.commands.AddExtensions.execute(AddExtensions.java:47) at io.quarkus.gradle.tasks.QuarkusAddExtension.addExtension(QuarkusAddExtension.java:45) ... 116 more ``` ### How to Reproduce? Set up a new gradle project as follows: ``` ❯ gradle init Select type of project to generate: 1: basic 2: application 3: library 4: Gradle plugin Enter selection (default: basic) [1..4] 3 Select implementation language: 1: C++ 2: Groovy 3: Java 4: Kotlin 5: Scala 6: Swift Enter selection (default: Java) [1..6] 3 Select build script DSL: 1: Groovy 2: Kotlin Enter selection (default: Groovy) [1..2] 1 Generate build using new APIs and behavior (some features may change in the next minor release)? (default: no) [yes, no] Select test framework: 1: JUnit 4 2: TestNG 3: Spock 4: JUnit Jupiter Enter selection (default: JUnit Jupiter) [1..4] Project name (default: code): Source package (default: code): > Task :init Get more help with your project: https://docs.gradle.org/7.5.1/samples/sample_building_java_libraries.html BUILD SUCCESSFUL in 17s 2 actionable tasks: 2 executed ``` Overwrite `lib/build.gradle` with the following: ``` plugins { // Apply the java-library plugin for API and implementation separation. id 'java-library' id "io.quarkus" version "2.14.2.Final" } repositories { // Use Maven Central for resolving dependencies. mavenCentral() mavenLocal() } dependencies { implementation enforcedPlatform(implementation(enforcedPlatform("io.quarkus.platform:quarkus-bom:2.14.2.Final"))) implementation 'io.quarkus:quarkus-container-image-jib-parent:2.14.2.Final' implementation 'io.quarkus:quarkus-container-image-jib:2.14.2.Final' } ``` Run `gradle addExtension --extensions='container-image-jib'` and watch it fail. Now add `gradle.properties` to the root directory of the project, re-run the command and watch it pass. ### Output of `uname -a` or `ver` Darwin C02GF586MD6R 22.1.0 Darwin Kernel Version 22.1.0: Sun Oct 9 20:14:54 PDT 2022; root:xnu-8792.41.9~2/RELEASE_X86_64 x86_64 ### Output of `java -version` openjdk version "17.0.5" 2022-10-18 ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.14.2.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Gradle 7.5.1 ### Additional information _No response_
36c5fa542edbf49351e2b9ee0392fd56863452e4
1c16ec12e22dcfe7a311aa1ed02cbce2a73dbb37
https://github.com/quarkusio/quarkus/compare/36c5fa542edbf49351e2b9ee0392fd56863452e4...1c16ec12e22dcfe7a311aa1ed02cbce2a73dbb37
diff --git a/independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/project/buildfile/AbstractGradleBuildFile.java b/independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/project/buildfile/AbstractGradleBuildFile.java index dba8d5bd5a3..dd5ea2931ce 100644 --- a/independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/project/buildfile/AbstractGradleBuildFile.java +++ b/independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/project/buildfile/AbstractGradleBuildFile.java @@ -46,16 +46,20 @@ public AbstractGradleBuildFile(final Path projectDirPath, final ExtensionCatalog public void writeToDisk() throws IOException { if (rootProjectPath != null) { Files.write(rootProjectPath.resolve(getSettingsGradlePath()), getModel().getRootSettingsContent().getBytes()); - try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { - getModel().getRootPropertiesContent().store(out, "Gradle properties"); - Files.write(rootProjectPath.resolve(GRADLE_PROPERTIES_PATH), - out.toByteArray()); + if (hasRootProjectFile(GRADLE_PROPERTIES_PATH)) { + try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { + getModel().getRootPropertiesContent().store(out, "Gradle properties"); + Files.write(rootProjectPath.resolve(GRADLE_PROPERTIES_PATH), + out.toByteArray()); + } } } else { writeToProjectFile(getSettingsGradlePath(), getModel().getSettingsContent().getBytes()); - try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { - getModel().getPropertiesContent().store(out, "Gradle properties"); - writeToProjectFile(GRADLE_PROPERTIES_PATH, out.toByteArray()); + if (hasProjectFile(GRADLE_PROPERTIES_PATH)) { + try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { + getModel().getPropertiesContent().store(out, "Gradle properties"); + writeToProjectFile(GRADLE_PROPERTIES_PATH, out.toByteArray()); + } } } writeToProjectFile(getBuildGradlePath(), getModel().getBuildContent().getBytes());
['independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/project/buildfile/AbstractGradleBuildFile.java']
{'.java': 1}
1
1
0
0
1
23,993,963
4,724,588
612,326
5,614
1,245
195
18
1
21,259
731
4,372
289
2
4
1970-01-01T00:27:50
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,332
quarkusio/quarkus/28935/28922
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/28922
https://github.com/quarkusio/quarkus/pull/28935
https://github.com/quarkusio/quarkus/pull/28935
1
fix
NullPointerException in Reactive REST Client
### Describe the bug There is a NullPointerException in the quarkus reactive rest client (at least in version 2.13.3.Final and 2.14.0.CR1): ``` java.lang.NullPointerException at org.jboss.resteasy.reactive.common.jaxrs.AbstractResponseBuilder.setAllHeaders(AbstractResponseBuilder.java:134) at org.jboss.resteasy.reactive.client.handlers.ClientResponseCompleteRestHandler.mapToResponse(ClientResponseCompleteRestHandler.java:45) at io.quarkus.rest.client.reactive.runtime.MicroProfileRestClientResponseFilter.filter(MicroProfileRestClientResponseFilter.java:35) at org.jboss.resteasy.reactive.client.handlers.ClientResponseFilterRestHandler.handle(ClientResponseFilterRestHandler.java:21) at org.jboss.resteasy.reactive.client.handlers.ClientResponseFilterRestHandler.handle(ClientResponseFilterRestHandler.java:10) at org.jboss.resteasy.reactive.common.core.AbstractResteasyReactiveContext.invokeHandler(AbstractResteasyReactiveContext.java:229) at org.jboss.resteasy.reactive.common.core.AbstractResteasyReactiveContext.run(AbstractResteasyReactiveContext.java:145) at org.jboss.resteasy.reactive.client.impl.RestClientRequestContext$1.lambda$execute$0(RestClientRequestContext.java:279) at io.vertx.core.impl.ContextInternal.dispatch(ContextInternal.java:264) at io.vertx.core.impl.ContextInternal.dispatch(ContextInternal.java:246) at io.vertx.core.impl.EventLoopContext.lambda$runOnContext$0(EventLoopContext.java:43) at io.netty.util.concurrent.AbstractEventExecutor.runTask(AbstractEventExecutor.java:174) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:167) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:470) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:569) at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997) at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.base/java.lang.Thread.run(Thread.java:829) ``` I managed to create a reproducer, see https://github.com/simonbaeumler/quarkus-rest-client-reactive-npe-reproducer To see the NullPointerException, just execute the test ExtensionsResourceTest.customTest() in the reproducer. So far I have pinned down the Exception happening only with this two conditions present: * The rest-client has a custom exeption handler defined (see e.g. class org.acme.rest.client.ApiExceptionMapper in the reproducer) * The rest-client runs in a read-timeout. ### Expected behavior An IllegalStateException that will be raised in the caller method of the RestClient. ### Actual behavior An NullPointerException is thrown that cannot be catched by the caller method of the RestClient. ### How to Reproduce? See https://github.com/simonbaeumler/quarkus-rest-client-reactive-npe-reproducer To see the NullPointerException, just execute the test ExtensionsResourceTest.customTest() in the reproducer. ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` openjdk version "11.0.16.1" 2022-08-12 OpenJDK Runtime Environment (Red_Hat-11.0.16.1.1-1.fc35) (build 11.0.16.1+1) OpenJDK 64-Bit Server VM (Red_Hat-11.0.16.1.1-1.fc35) (build 11.0.16.1+1, mixed mode, sharing) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.13.3.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
95db64848e29e9787e58e8d4cae27d2e808a0bcd
1d074d6cfb4b4c12648ddeb9221ae8711e3b7176
https://github.com/quarkusio/quarkus/compare/95db64848e29e9787e58e8d4cae27d2e808a0bcd...1d074d6cfb4b4c12648ddeb9221ae8711e3b7176
diff --git a/independent-projects/resteasy-reactive/common/runtime/src/main/java/org/jboss/resteasy/reactive/common/jaxrs/AbstractResponseBuilder.java b/independent-projects/resteasy-reactive/common/runtime/src/main/java/org/jboss/resteasy/reactive/common/jaxrs/AbstractResponseBuilder.java index 591867ed4b8..27a43da67ef 100644 --- a/independent-projects/resteasy-reactive/common/runtime/src/main/java/org/jboss/resteasy/reactive/common/jaxrs/AbstractResponseBuilder.java +++ b/independent-projects/resteasy-reactive/common/runtime/src/main/java/org/jboss/resteasy/reactive/common/jaxrs/AbstractResponseBuilder.java @@ -131,9 +131,11 @@ public <T extends ResponseImpl> T populateResponse(T response, boolean copyHeade } public void setAllHeaders(MultivaluedMap<String, String> values) { - for (Map.Entry<String, List<String>> i : values.entrySet()) { - for (String v : i.getValue()) { - metadata.add(i.getKey(), v); + if (values != null) { + for (Map.Entry<String, List<String>> i : values.entrySet()) { + for (String v : i.getValue()) { + metadata.add(i.getKey(), v); + } } } }
['independent-projects/resteasy-reactive/common/runtime/src/main/java/org/jboss/resteasy/reactive/common/jaxrs/AbstractResponseBuilder.java']
{'.java': 1}
1
1
0
0
1
23,349,647
4,588,072
596,124
5,494
385
78
8
1
3,590
240
847
72
2
1
1970-01-01T00:27:47
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,334
quarkusio/quarkus/28608/28607
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/28607
https://github.com/quarkusio/quarkus/pull/28608
https://github.com/quarkusio/quarkus/pull/28608
1
fixes
MongoDb Srv connection does not work on windows
### Describe the bug For the windows project, when you run the application with the maven commande mvn compile quarkus:dev -Dquarkus.profile=local The application failed to open a mongo connection with the SRV protocol. "/etc/resolv.conf" ### Expected behavior The mongodb SRV protocol should work out of the box ### Actual behavior we have a great stack trace with NPE : ``` 2022-10-14 18:17:06,767 ERROR [org.jbo.res.rea.com.cor.AbstractResteasyReactiveContext] (executor-thread-0) Request failed: java.lang.NullPointerException: Cannot invoke "java.util.List.isEmpty()" because "list" is null at io.quarkus.mongodb.runtime.dns.MongoDnsClient.lambda$new$0(MongoDnsClient.java:58) at java.base/java.util.Optional.orElseGet(Optional.java:364) at io.quarkus.mongodb.runtime.dns.MongoDnsClient.<init>(MongoDnsClient.java:56) at io.quarkus.mongodb.runtime.dns.MongoDnsClientProvider.create(MongoDnsClientProvider.java:12) at com.mongodb.internal.dns.DefaultDnsResolver.<init>(DefaultDnsResolver.java:44) at com.mongodb.ConnectionString.<init>(ConnectionString.java:397) at io.quarkus.mongodb.runtime.MongoClients.createMongoConfiguration(MongoClients.java:262) at io.quarkus.mongodb.runtime.MongoClients.createMongoClient(MongoClients.java:118) at io.quarkus.mongodb.runtime.MongoClients_Subclass.createMongoClient$$superforward1(Unknown Source) at io.quarkus.mongodb.runtime.MongoClients_Subclass$$function$$4.apply(Unknown Source) at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:53) at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.proceed(InvocationInterceptor.java:62) at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.monitor(InvocationInterceptor.java:49) at io.quarkus.arc.runtime.devconsole.InvocationInterceptor_Bean.intercept(Unknown Source) at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41) at io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:40) at io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:32) at io.quarkus.mongodb.runtime.MongoClients_Subclass.createMongoClient(Unknown Source) at io.quarkus.mongodb.runtime.MongoClientRecorder.lambda$mongoClientSupplier$0(MongoClientRecorder.java:63) at io.quarkus.mongodb.runtime.MongoClientRecorder$MongoClientSupplier.get(MongoClientRecorder.java:57) at com.mongodb.client.MongoClient_38bcba43bbcf7928744e8baa654420f551f1ff9a_Synthetic_Bean.create(Unknown Source) at com.mongodb.client.MongoClient_38bcba43bbcf7928744e8baa654420f551f1ff9a_Synthetic_Bean.create(Unknown Source) at io.quarkus.arc.impl.AbstractSharedContext.createInstanceHandle(AbstractSharedContext.java:111) at io.quarkus.arc.impl.AbstractSharedContext$1.get(AbstractSharedContext.java:35) at io.quarkus.arc.impl.AbstractSharedContext$1.get(AbstractSharedContext.java:32) at io.quarkus.arc.impl.LazyValue.get(LazyValue.java:26) at io.quarkus.arc.impl.ComputingCache.computeIfAbsent(ComputingCache.java:69) at io.quarkus.arc.impl.AbstractSharedContext.get(AbstractSharedContext.java:32) at io.quarkus.arc.impl.ClientProxies.getApplicationScopedDelegate(ClientProxies.java:19) at com.mongodb.client.MongoClient_38bcba43bbcf7928744e8baa654420f551f1ff9a_Synthetic_ClientProxy.arc$delegate(Unknown Source) at com.mongodb.client.MongoClient_38bcba43bbcf7928744e8baa654420f551f1ff9a_Synthetic_ClientProxy.getDatabase(Unknown Source) ``` ### How to Reproduce? Step to reproduce the behaviour : 1. Having a windows environment or not having the right to read this file ( "/etc/resolv.conf") 2. try to connect a mongodb with srv protocole ( url connection must start with mongodb+srv) 3. try to open the connection, the NPE rise ! ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` Java version: 17.0.1 ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.12.0 ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.1 ### Additional information You should not initialize a list with null List<String> nameServers = null; should be nameServers = new ArrayList<>();
983ab03aff1087656e81c780cb2768c7ef3dd76c
06ff785629b0b4a23b5ec754eeed71a84ae03804
https://github.com/quarkusio/quarkus/compare/983ab03aff1087656e81c780cb2768c7ef3dd76c...06ff785629b0b4a23b5ec754eeed71a84ae03804
diff --git a/extensions/mongodb-client/runtime/src/main/java/io/quarkus/mongodb/runtime/dns/MongoDnsClient.java b/extensions/mongodb-client/runtime/src/main/java/io/quarkus/mongodb/runtime/dns/MongoDnsClient.java index e12c70dc854..d20705bedae 100644 --- a/extensions/mongodb-client/runtime/src/main/java/io/quarkus/mongodb/runtime/dns/MongoDnsClient.java +++ b/extensions/mongodb-client/runtime/src/main/java/io/quarkus/mongodb/runtime/dns/MongoDnsClient.java @@ -8,6 +8,7 @@ import java.nio.file.Paths; import java.time.Duration; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -82,7 +83,7 @@ public class MongoDnsClient implements DnsClient { private static List<String> nameServers() { Path conf = Paths.get("/etc/resolv.conf"); - List<String> nameServers = null; + List<String> nameServers = Collections.emptyList(); if (Files.exists(conf)) { try (Stream<String> lines = Files.lines(conf)) { nameServers = lines @@ -91,7 +92,6 @@ private static List<String> nameServers() { .collect(Collectors.toList()); } catch (IOException | ArrayIndexOutOfBoundsException e) { Logger.getLogger(MongoDnsClientProvider.class).info("Unable to read the /etc/resolv.conf file", e); - nameServers = new ArrayList<>(); } } return nameServers;
['extensions/mongodb-client/runtime/src/main/java/io/quarkus/mongodb/runtime/dns/MongoDnsClient.java']
{'.java': 1}
1
1
0
0
1
23,204,997
4,559,808
592,873
5,478
183
31
4
1
4,319
266
1,056
87
0
1
1970-01-01T00:27:45
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,354
quarkusio/quarkus/28056/28049
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/28049
https://github.com/quarkusio/quarkus/pull/28056
https://github.com/quarkusio/quarkus/pull/28056
1
fix
Redis client filters the null values with the mget command
### Describe the bug In the redis documentation, here : https://redis.io/commands/mget/ The missing values should be returned as null, it enables to detect in an efficient way, which keys are missing or have been deleted due to timeout policies. However, the implementation of the ReactiveRedisClient uses the io.quarkus.redis.runtime.datasource.Marshaller which filters this values with the method #decodeAsOrderedMap. The null values should not be filtered and the user should do it, if necessary. ### Expected behavior More compliance with the redis documentation, and non filtered null values. ### Actual behavior The null values are filtered by default. ### How to Reproduce? 1. Create a quarkus app with version 2.12.2.Final 2. Create a ReactiveRedisDatasource 3. use the mget command to fetch non existing values 4. Recover an empty map ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.12.2.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) maven ### Additional information _No response_
9bc683f75218169a5a613de87e75102532330586
ca68abb68ef95dd9ac896058d280448a3d0f6afb
https://github.com/quarkusio/quarkus/compare/9bc683f75218169a5a613de87e75102532330586...ca68abb68ef95dd9ac896058d280448a3d0f6afb
diff --git a/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/hash/HashCommands.java b/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/hash/HashCommands.java index 1f923856fa3..d71e80ae867 100644 --- a/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/hash/HashCommands.java +++ b/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/hash/HashCommands.java @@ -125,6 +125,7 @@ * @param key the key * @param fields the fields * @return list of values associated with the given fields, in the same order as they are requested. + * If a requested field does not exist, the returned map contains a {@code null} value for that field. **/ Map<F, V> hmget(K key, F... fields); diff --git a/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/hash/ReactiveHashCommands.java b/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/hash/ReactiveHashCommands.java index ccea4615e14..51647e07464 100644 --- a/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/hash/ReactiveHashCommands.java +++ b/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/hash/ReactiveHashCommands.java @@ -126,6 +126,7 @@ * @param key the key * @param fields the fields * @return list of values associated with the given fields, in the same order as they are requested. + * If a requested field does not exist, the returned map contains a {@code null} value for that field. **/ Uni<Map<F, V>> hmget(K key, F... fields); diff --git a/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/string/ReactiveStringCommands.java b/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/string/ReactiveStringCommands.java index fcbe689fb14..5bac8b361ff 100644 --- a/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/string/ReactiveStringCommands.java +++ b/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/string/ReactiveStringCommands.java @@ -183,7 +183,8 @@ * Requires Redis 1.0.0 * * @param keys the keys - * @return list of values at the specified keys. + * @return the value of key, or {@code null} when key does not exist. If one of the passed key does not exist, the + * returned map contains a {@code null} value associated with the missing key. **/ Uni<Map<K, V>> mget(K... keys); diff --git a/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/string/StringCommands.java b/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/string/StringCommands.java index ac992c038ad..b3d592620e3 100644 --- a/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/string/StringCommands.java +++ b/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/string/StringCommands.java @@ -182,7 +182,8 @@ * Requires Redis 1.0.0 * * @param keys the keys - * @return list of values at the specified keys. + * @return list of values at the specified keys. If one of the passed key does not exist, the returned map contains + * a {@code null} value associated with the missing key. **/ Map<K, V> mget(K... keys); diff --git a/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/value/ReactiveValueCommands.java b/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/value/ReactiveValueCommands.java index 896d7793a3a..e9ddc167549 100644 --- a/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/value/ReactiveValueCommands.java +++ b/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/value/ReactiveValueCommands.java @@ -63,7 +63,8 @@ * Requires Redis 1.0.0 * * @param key the key - * @return the value of key, or {@code null} when key does not exist. + * @return the value of key, or {@code null} when key does not exist. If one of the passed key does not exist, the + * returned map contains a {@code null} value associated with the missing key. **/ Uni<V> get(K key); diff --git a/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/value/ValueCommands.java b/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/value/ValueCommands.java index 2f6416d11e8..48ad3e81489 100644 --- a/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/value/ValueCommands.java +++ b/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/value/ValueCommands.java @@ -183,7 +183,8 @@ * Requires Redis 1.0.0 * * @param keys the keys - * @return list of values at the specified keys. + * @return list of values at the specified keys. If one of the passed key does not exist, the returned map contains + * a {@code null} value associated with the missing key. **/ Map<K, V> mget(K... keys); diff --git a/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/runtime/datasource/Marshaller.java b/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/runtime/datasource/Marshaller.java index c6d1186d144..d34850f1085 100644 --- a/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/runtime/datasource/Marshaller.java +++ b/extensions/redis-client/runtime/src/main/java/io/quarkus/redis/runtime/datasource/Marshaller.java @@ -149,9 +149,7 @@ final <F, V> Map<F, V> decodeAsOrderedMap(Response response, Class<V> typeOfValu Map<F, V> map = new LinkedHashMap<>(); for (F field : fields) { Response v = iterator.next(); - if (v != null) { // Skip null entries - map.put(field, decode(typeOfValue, v)); - } + map.put(field, decode(typeOfValue, v)); } return map; } diff --git a/extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/HashCommandsTest.java b/extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/HashCommandsTest.java index 643952e39ab..a5dd256e798 100644 --- a/extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/HashCommandsTest.java +++ b/extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/HashCommandsTest.java @@ -142,12 +142,12 @@ void hstrlen() { void hmget() { populateForHmget(); Map<String, Person> values = hash.hmget(key, "one", "missing", "two"); - assertThat(values).hasSize(2); - assertThat(values).containsExactly(entry("one", Person.person1), entry("two", Person.person2)); + assertThat(values).hasSize(3); + assertThat(values).containsExactly(entry("one", Person.person1), entry("missing", null), entry("two", Person.person2)); } private void populateForHmget() { - assertThat(hash.hmget(key, "one", "two").values()).isEmpty(); + assertThat(hash.hmget(key, "one", "two")).allSatisfy((s, p) -> assertThat(p).isNull()); hash.hset(key, "one", Person.person1); hash.hset(key, "two", Person.person2); } diff --git a/extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/StringCommandsTest.java b/extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/StringCommandsTest.java index bb73b2b134b..3e0e16ca628 100644 --- a/extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/StringCommandsTest.java +++ b/extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/StringCommandsTest.java @@ -99,15 +99,24 @@ void getset() { @Test void mget() { - assertThat(strings.mget(key)).isEmpty(); + assertThat(strings.mget(key)).containsExactly(entry(key, null)); strings.set("one", "1"); strings.set("two", "2"); assertThat(strings.mget("one", "two")).containsExactly(entry("one", "1"), entry("two", "2")); } + @Test + void mgetWithMissingKey() { + assertThat(strings.mget(key)).containsExactly(entry(key, null)); + strings.set("one", "1"); + strings.set("two", "2"); + assertThat(strings.mget("one", "missing", "two")).containsExactly(entry("one", "1"), + entry("missing", null), entry("two", "2")); + } + @Test void mset() { - assertThat(strings.mget("one", "two")).isEmpty(); + assertThat(strings.mget(key)).containsExactly(entry(key, null)); Map<String, String> map = new LinkedHashMap<>(); map.put("one", "1"); map.put("two", "2"); diff --git a/extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/ValueCommandsTest.java b/extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/ValueCommandsTest.java index 0bd8815e307..18d63308c18 100644 --- a/extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/ValueCommandsTest.java +++ b/extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/ValueCommandsTest.java @@ -99,15 +99,24 @@ void getset() { @Test void mget() { - assertThat(values.mget(key)).isEmpty(); + assertThat(values.mget(key)).containsExactly(entry(key, null)); values.set("one", "1"); values.set("two", "2"); assertThat(values.mget("one", "two")).containsExactly(entry("one", "1"), entry("two", "2")); } + @Test + void mgetWithMissingKey() { + assertThat(values.mget(key)).containsExactly(entry(key, null)); + values.set("one", "1"); + values.set("two", "2"); + assertThat(values.mget("one", "missing", "two")).containsExactly(entry("one", "1"), + entry("missing", null), entry("two", "2")); + } + @Test void mset() { - assertThat(values.mget("one", "two")).isEmpty(); + assertThat(values.mget("one", "two")).containsExactly(entry("one", null), entry("two", null)); Map<String, String> map = new LinkedHashMap<>(); map.put("one", "1"); map.put("two", "2");
['extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/hash/HashCommands.java', 'extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/value/ValueCommands.java', 'extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/ValueCommandsTest.java', 'extensions/redis-client/runtime/src/main/java/io/quarkus/redis/runtime/datasource/Marshaller.java', 'extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/StringCommandsTest.java', 'extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/string/ReactiveStringCommands.java', 'extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/string/StringCommands.java', 'extensions/redis-client/runtime/src/test/java/io/quarkus/redis/datasource/HashCommandsTest.java', 'extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/value/ReactiveValueCommands.java', 'extensions/redis-client/runtime/src/main/java/io/quarkus/redis/datasource/hash/ReactiveHashCommands.java']
{'.java': 10}
10
10
0
0
10
22,669,505
4,440,285
578,229
5,392
1,444
329
18
7
1,190
175
278
49
1
0
1970-01-01T00:27:43
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,335
quarkusio/quarkus/28578/28577
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/28577
https://github.com/quarkusio/quarkus/pull/28578
https://github.com/quarkusio/quarkus/pull/28578
1
fixes
Access log logged twice if non-root path is a prefix of root path
### Describe the bug Original - https://github.com/smallrye/smallrye-health/issues/412#issuecomment-1272883427. We need to distinguish cases where either of the paths is mapped to "/" (root/main router), if one is a subpath of another, or if they are totally different. TBH, I'm thinking the best would be to log everything under "/". So the question is whether it makes sense to log for instance GET /whatever if the quarkus.http.root-path=/app. Not for me to decide but I'll mention it in the PR. ### Expected behavior _No response_ ### Actual behavior _No response_ ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
2e7bba4037340bdc7468a0d763bd9632705db017
0e100af7c02d4abe51e433c54a1eece7bfa5527a
https://github.com/quarkusio/quarkus/compare/2e7bba4037340bdc7468a0d763bd9632705db017...0e100af7c02d4abe51e433c54a1eece7bfa5527a
diff --git a/extensions/vertx-http/deployment/src/main/java/io/quarkus/vertx/http/deployment/VertxHttpProcessor.java b/extensions/vertx-http/deployment/src/main/java/io/quarkus/vertx/http/deployment/VertxHttpProcessor.java index ef861524db7..0380a2925ed 100644 --- a/extensions/vertx-http/deployment/src/main/java/io/quarkus/vertx/http/deployment/VertxHttpProcessor.java +++ b/extensions/vertx-http/deployment/src/main/java/io/quarkus/vertx/http/deployment/VertxHttpProcessor.java @@ -312,9 +312,8 @@ ServiceStartBuildItem finalizeRouter( defaultRoute.map(DefaultRouteBuildItem::getRoute).orElse(null), listOfFilters, vertx.getVertx(), lrc, mainRouter, httpRouteRouter.getHttpRouter(), httpRouteRouter.getMutinyRouter(), httpRouteRouter.getFrameworkRouter(), - nonApplicationRootPathBuildItem.isDedicatedRouterRequired(), - nonApplicationRootPathBuildItem.isAttachedToMainRouter(), httpRootPathBuildItem.getRootPath(), + nonApplicationRootPathBuildItem.getNonApplicationRootPath(), launchMode.getLaunchMode(), !requireBodyHandlerBuildItems.isEmpty(), bodyHandler, gracefulShutdownFilter, shutdownConfig, executorBuildItem.getExecutorProxy()); diff --git a/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxHttpRecorder.java b/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxHttpRecorder.java index fb2249f0335..b596cee278f 100644 --- a/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxHttpRecorder.java +++ b/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxHttpRecorder.java @@ -341,8 +341,8 @@ public void finalizeRouter(BeanContainer container, Consumer<Route> defaultRoute LiveReloadConfig liveReloadConfig, Optional<RuntimeValue<Router>> mainRouterRuntimeValue, RuntimeValue<Router> httpRouterRuntimeValue, RuntimeValue<io.vertx.mutiny.ext.web.Router> mutinyRouter, RuntimeValue<Router> frameworkRouter, - boolean nonApplicationDedicatedRouter, boolean nonApplicationAttachedToMainRouter, - String rootPath, LaunchMode launchMode, boolean requireBodyHandler, + String rootPath, String nonRootPath, + LaunchMode launchMode, boolean requireBodyHandler, Handler<RoutingContext> bodyHandler, GracefulShutdownFilter gracefulShutdownFilter, ShutdownConfig shutdownConfig, Executor executor) { @@ -560,10 +560,17 @@ public void handle(HttpServerRequest event) { } AccessLogHandler handler = new AccessLogHandler(receiver, accessLog.pattern, getClass().getClassLoader(), accessLog.excludePattern); - if (nonApplicationDedicatedRouter && !nonApplicationAttachedToMainRouter) { + if (rootPath.equals("/") || nonRootPath.equals("/")) { + mainRouterRuntimeValue.orElse(httpRouterRuntimeValue).getValue().route().order(Integer.MIN_VALUE) + .handler(handler); + } else if (nonRootPath.startsWith(rootPath)) { + httpRouteRouter.route().order(Integer.MIN_VALUE).handler(handler); + } else if (rootPath.startsWith(nonRootPath)) { + frameworkRouter.getValue().route().order(Integer.MIN_VALUE).handler(handler); + } else { + httpRouteRouter.route().order(Integer.MIN_VALUE).handler(handler); frameworkRouter.getValue().route().order(Integer.MIN_VALUE).handler(handler); } - httpRouteRouter.route().order(Integer.MIN_VALUE).handler(handler); quarkusWrapperNeeded = true; }
['extensions/vertx-http/deployment/src/main/java/io/quarkus/vertx/http/deployment/VertxHttpProcessor.java', 'extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxHttpRecorder.java']
{'.java': 2}
2
2
0
0
2
23,159,611
4,550,212
591,563
5,471
1,321
240
18
2
951
144
228
43
1
0
1970-01-01T00:27:45
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,353
quarkusio/quarkus/28141/28090
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/28090
https://github.com/quarkusio/quarkus/pull/28141
https://github.com/quarkusio/quarkus/pull/28141
1
fixes
cli test fails without settings.xml
### Describe the bug If no settings.xml is present in the maven user location, cli test will fail with 3 failures and 3 errors. ```shell ./mvnw -f devtools/cli test ... [ERROR] Tests run: 79, Failures: 3, Errors: 3, Skipped: 0 ``` [Full Maven Log](https://github.com/quarkusio/quarkus/files/9607348/maven.log) ### Expected behavior cli test should be able to run without settings.xml ### Actual behavior Fails without settings.xml ### How to Reproduce? Steps to reproduce the behavior: 1. Ensure that no user settings.xml is defined 2. Run `./mvnw -f devtools/cli test` ### Output of `uname -a` or `ver` Darwin mavenrunner-mac 21.6.0 Darwin Kernel Version 21.6.0: Mon Aug 22 20:19:52 PDT 2022; root:xnu-8020.140.49~2/RELEASE_ARM64_T6000 arm64 ### Output of `java -version` openjdk version "17.0.2" 2022-01-18 ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev e19f65e535 ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.6 (84538c9988a25aec085021c365c560670ad80f63) ### Additional information _No response_
23562c3ed09f8f79ce4f1c24f91a03bcfa918235
2b0923f614c04aa16ece0c11ae4e70d5f850e00a
https://github.com/quarkusio/quarkus/compare/23562c3ed09f8f79ce4f1c24f91a03bcfa918235...2b0923f614c04aa16ece0c11ae4e70d5f850e00a
diff --git a/devtools/cli/src/main/java/io/quarkus/cli/build/MavenRunner.java b/devtools/cli/src/main/java/io/quarkus/cli/build/MavenRunner.java index d8bcb2b29ab..2c801a99990 100644 --- a/devtools/cli/src/main/java/io/quarkus/cli/build/MavenRunner.java +++ b/devtools/cli/src/main/java/io/quarkus/cli/build/MavenRunner.java @@ -1,6 +1,7 @@ package io.quarkus.cli.build; import java.io.File; +import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayDeque; import java.util.ArrayList; @@ -32,6 +33,7 @@ import picocli.CommandLine; public class MavenRunner implements BuildSystemRunner { + public static String MAVEN_SETTINGS = "maven.settings"; static final String[] windowsWrapper = { "mvnw.cmd", "mvnw.bat" }; static final String otherWrapper = "mvnw"; @@ -238,13 +240,13 @@ void setMavenProperties(ArrayDeque<String> args, boolean batchMode) { args.addFirst("-Dstyle.color=always"); } - String mavenSettings = propertiesOptions.properties.remove("maven.settings"); + String mavenSettings = propertiesOptions.properties.remove(MAVEN_SETTINGS); if (mavenSettings != null && !mavenSettings.isEmpty()) { args.add("-s"); args.add(mavenSettings); } else { - mavenSettings = System.getProperty("maven.settings"); - if (mavenSettings != null && !mavenSettings.isEmpty()) { + mavenSettings = System.getProperty(MAVEN_SETTINGS); + if (mavenSettings != null && !mavenSettings.isEmpty() && Files.exists(Path.of(mavenSettings))) { args.add("-s"); args.add(mavenSettings); } diff --git a/devtools/cli/src/test/java/io/quarkus/cli/CliDriver.java b/devtools/cli/src/test/java/io/quarkus/cli/CliDriver.java index ddf060402c3..2ee05931bef 100644 --- a/devtools/cli/src/test/java/io/quarkus/cli/CliDriver.java +++ b/devtools/cli/src/test/java/io/quarkus/cli/CliDriver.java @@ -1,5 +1,8 @@ package io.quarkus.cli; +import static io.quarkus.cli.build.MavenRunner.MAVEN_SETTINGS; +import static org.apache.maven.cli.MavenCli.LOCAL_REPO_PROPERTY; + import java.io.ByteArrayOutputStream; import java.io.File; import java.io.PrintStream; @@ -12,6 +15,9 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.function.BinaryOperator; +import java.util.function.UnaryOperator; import org.junit.jupiter.api.Assertions; @@ -20,6 +26,9 @@ public class CliDriver { static final PrintStream stdout = System.out; static final PrintStream stderr = System.err; + private static final BinaryOperator<String> ARG_FORMATTER = (key, value) -> "-D" + key + "=" + value; + private static final UnaryOperator<String> REPO_ARG_FORMATTER = value -> ARG_FORMATTER.apply(LOCAL_REPO_PROPERTY, value); + private static final UnaryOperator<String> SETTINGS_ARG_FORMATTER = value -> ARG_FORMATTER.apply(MAVEN_SETTINGS, value); public static class CliDriverBuilder { @@ -63,8 +72,10 @@ public Result execute() throws Exception { newArgs.subList(index, newArgs.size()).clear(); } - propagateProperty("maven.repo.local", mavenLocalRepo, newArgs); - propagateProperty("maven.settings", mavenSettings, newArgs); + Optional.ofNullable(mavenLocalRepo).or(CliDriver::getMavenLocalRepoProperty).map(REPO_ARG_FORMATTER) + .ifPresent(newArgs::add); + Optional.ofNullable(mavenSettings).or(CliDriver::getMavenSettingsProperty).map(SETTINGS_ARG_FORMATTER) + .ifPresent(newArgs::add); newArgs.add("--cli-test"); newArgs.add("--cli-test-dir"); @@ -81,7 +92,7 @@ public Result execute() throws Exception { PrintStream errPs = new PrintStream(err); System.setErr(errPs); - final Map<String, String> originalProps = collectOverridenProps(newArgs); + final Map<String, String> originalProps = collectOverriddenProps(newArgs); Result result = new Result(); QuarkusCli cli = new QuarkusCli(); @@ -109,7 +120,7 @@ protected void resetProperties(Map<String, String> originalProps) { } } - protected Map<String, String> collectOverridenProps(List<String> newArgs) { + protected Map<String, String> collectOverriddenProps(List<String> newArgs) { final Map<String, String> originalProps = new HashMap<>(); for (String s : newArgs) { if (s.startsWith("-D")) { @@ -121,22 +132,14 @@ protected Map<String, String> collectOverridenProps(List<String> newArgs) { originalProps.put(propName, origValue); } else if (System.getProperties().contains(propName)) { originalProps.put(propName, "true"); + } else { + originalProps.put(propName, null); } } } } return originalProps; } - - private static void propagateProperty(String propName, String testValue, List<String> args) { - if (testValue == null) { - testValue = System.getProperty(propName); - if (testValue == null) { - return; - } - } - args.add("-D" + propName + "=" + testValue); - } } public static CliDriverBuilder builder() { @@ -144,14 +147,8 @@ public static CliDriverBuilder builder() { } public static void preserveLocalRepoSettings(Collection<String> args) { - String s = convertToProperty("maven.repo.local"); - if (s != null) { - args.add(s); - } - s = convertToProperty("maven.settings"); - if (s != null) { - args.add(s); - } + getMavenLocalRepoProperty().map(REPO_ARG_FORMATTER).ifPresent(args::add); + getMavenSettingsProperty().map(SETTINGS_ARG_FORMATTER).ifPresent(args::add); } public static Result executeArbitraryCommand(Path startingDir, String... args) throws Exception { @@ -439,12 +436,12 @@ public static void validateApplicationProperties(Path projectRoot, List<String> "Properties file should contain " + conf + ". Found:\\n" + propertiesFile)); } - private static String convertToProperty(String name) { - String value = System.getProperty(name); - if (value != null) { - return "-D" + name + "=" + value; - } - return null; + private static Optional<String> getMavenLocalRepoProperty() { + return Optional.ofNullable(System.getProperty(LOCAL_REPO_PROPERTY)); + } + + private static Optional<String> getMavenSettingsProperty() { + return Optional.ofNullable(System.getProperty(MAVEN_SETTINGS)).filter(value -> Files.exists(Path.of(value))); } private static void retryDelete(File file) { diff --git a/devtools/cli/src/test/java/io/quarkus/cli/RegistryClientBuilderTestBase.java b/devtools/cli/src/test/java/io/quarkus/cli/RegistryClientBuilderTestBase.java index 00a402bcda5..d101dbe0018 100644 --- a/devtools/cli/src/test/java/io/quarkus/cli/RegistryClientBuilderTestBase.java +++ b/devtools/cli/src/test/java/io/quarkus/cli/RegistryClientBuilderTestBase.java @@ -1,7 +1,7 @@ package io.quarkus.cli; -import java.io.BufferedReader; import java.io.BufferedWriter; +import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.nio.file.Files; @@ -59,7 +59,7 @@ static void setup() throws Exception { final BootstrapMavenContext mavenContext = new BootstrapMavenContext( BootstrapMavenContext.config().setWorkspaceDiscovery(false)); - final Settings settings = getBaseMavenSettings(mavenContext.getUserSettings().toPath()); + final Settings settings = getBaseMavenSettings(mavenContext.getUserSettings()); Profile profile = new Profile(); settings.addActiveProfile("qs-test-registry"); @@ -106,11 +106,9 @@ protected static String getCurrentQuarkusVersion() { return v; } - private static Settings getBaseMavenSettings(Path mavenSettings) throws IOException { - if (Files.exists(mavenSettings)) { - try (BufferedReader reader = Files.newBufferedReader(mavenSettings)) { - return new DefaultSettingsReader().read(reader, Map.of()); - } + private static Settings getBaseMavenSettings(File mavenSettings) throws IOException { + if (mavenSettings != null && mavenSettings.exists()) { + return new DefaultSettingsReader().read(mavenSettings, Map.of()); } return new Settings(); }
['devtools/cli/src/test/java/io/quarkus/cli/CliDriver.java', 'devtools/cli/src/main/java/io/quarkus/cli/build/MavenRunner.java', 'devtools/cli/src/test/java/io/quarkus/cli/RegistryClientBuilderTestBase.java']
{'.java': 3}
3
3
0
0
3
22,849,915
4,480,973
583,924
5,419
573
114
8
1
1,114
152
348
49
1
1
1970-01-01T00:27:43
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,352
quarkusio/quarkus/28174/28088
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/28088
https://github.com/quarkusio/quarkus/pull/28174
https://github.com/quarkusio/quarkus/pull/28174
1
fixes
REST client considers the wrong environment variable for `quarkus.rest-client."config-key".url`
### Describe the bug I have set an environment `QUARKUS_REST_CLIENT__MY_CLIENT__URL` variable set which is supposed to override the `quarkus.rest-client."my-client".url` at runtime. The `quarkus.rest-client."my-client".url` has a fallback setting in `application.properties`. ### Expected behavior The REST client uses the URL from the environment variable. This works in Quarkus 2.11.1, but does not work in Quarkus 2.12.2. ### Actual behavior This happens in Quarkus 2.12.2: The REST client ignores the environment variablee and uses the fallback setting in `application.properties`. When I change the name of the environment variable to `QUARKUS_REST_CLIENT_MY_CLIENT_URL` (note the missing extra underscores for the `"`) then the value of the environment variable is used. In Quarkus 2.11.1, everything works as expected. ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` Darwin <redacted> 20.6.0 Darwin Kernel Version 20.6.0: Tue Feb 22 21:10:41 PST 2022; root:xnu-7195.141.26~1/RELEASE_X86_64 x86_64 ### Output of `java -version` openjdk version "11.0.11" 2021-04-20 OpenJDK Runtime Environment AdoptOpenJDK-11.0.11+9 (build 11.0.11+9) OpenJDK 64-Bit Server VM AdoptOpenJDK-11.0.11+9 (build 11.0.11+9, mixed mode) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.12.2 ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.6 ### Additional information _No response_
d18b47671db3303e950eba55436bf7d8dd23ce33
1c0f8e7f6340f4c614c31089f777688631106cf7
https://github.com/quarkusio/quarkus/compare/d18b47671db3303e950eba55436bf7d8dd23ce33...1c0f8e7f6340f4c614c31089f777688631106cf7
diff --git a/core/runtime/src/main/java/io/quarkus/runtime/configuration/ConfigUtils.java b/core/runtime/src/main/java/io/quarkus/runtime/configuration/ConfigUtils.java index 210d5f34d1c..4fc98dae8fe 100644 --- a/core/runtime/src/main/java/io/quarkus/runtime/configuration/ConfigUtils.java +++ b/core/runtime/src/main/java/io/quarkus/runtime/configuration/ConfigUtils.java @@ -5,6 +5,8 @@ import static io.smallrye.config.SmallRyeConfig.SMALLRYE_CONFIG_PROFILE; import static io.smallrye.config.SmallRyeConfig.SMALLRYE_CONFIG_PROFILE_PARENT; import static io.smallrye.config.SmallRyeConfigBuilder.META_INF_MICROPROFILE_CONFIG_PROPERTIES; +import static java.lang.Integer.MAX_VALUE; +import static java.lang.Integer.MIN_VALUE; import java.io.IOException; import java.net.URL; @@ -13,7 +15,6 @@ import java.util.Collections; import java.util.Comparator; import java.util.HashMap; -import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; @@ -39,13 +40,13 @@ import io.smallrye.config.EnvConfigSource; import io.smallrye.config.FallbackConfigSourceInterceptor; import io.smallrye.config.KeyMap; -import io.smallrye.config.KeyMapBackedConfigSource; import io.smallrye.config.Priorities; import io.smallrye.config.ProfileConfigSourceInterceptor; import io.smallrye.config.RelocateConfigSourceInterceptor; import io.smallrye.config.SmallRyeConfig; import io.smallrye.config.SmallRyeConfigBuilder; import io.smallrye.config.SysPropConfigSource; +import io.smallrye.config.common.MapBackedConfigSource; import io.smallrye.config.common.utils.ConfigSourceUtil; /** @@ -115,10 +116,8 @@ public static SmallRyeConfigBuilder configBuilder(final boolean runTime, final b builder.addDiscoveredValidator(); builder.withDefaultValue(UUID_KEY, UUID.randomUUID().toString()); builder.withSources(new DotEnvConfigSourceProvider()); - builder.withSources( - new DefaultsConfigSource(loadBuildTimeRunTimeValues(), "BuildTime RunTime Fixed", Integer.MAX_VALUE)); - builder.withSources( - new DefaultsConfigSource(loadRunTimeDefaultValues(), "RunTime Defaults", Integer.MIN_VALUE + 100)); + builder.withSources(new DefaultsConfigSource(loadBuildTimeRunTimeValues(), "BuildTime RunTime Fixed", MAX_VALUE)); + builder.withSources(new DefaultsConfigSource(loadRunTimeDefaultValues(), "RunTime Defaults", MIN_VALUE + 100)); } else { List<ConfigSource> sources = new ArrayList<>(); sources.addAll(classPathSources(META_INF_MICROPROFILE_CONFIG_PROPERTIES, classLoader)); @@ -384,43 +383,35 @@ public Set<String> getPropertyNames() { } } - static class DefaultsConfigSource extends KeyMapBackedConfigSource { + static class DefaultsConfigSource extends MapBackedConfigSource { private final KeyMap<String> wildcards; - private final Set<String> propertyNames; public DefaultsConfigSource(final Map<String, String> properties, final String name, final int ordinal) { - super(name, ordinal, propertiesToKeyMap(properties)); + // Defaults may contain wildcards, but we don't want to expose them in getPropertyNames, so we need to filter them + super(name, filterWildcards(properties), ordinal); this.wildcards = new KeyMap<>(); - this.propertyNames = new HashSet<>(); for (Map.Entry<String, String> entry : properties.entrySet()) { if (entry.getKey().contains("*")) { this.wildcards.findOrAdd(entry.getKey()).putRootValue(entry.getValue()); - } else { - this.propertyNames.add(entry.getKey()); } } } - @Override - public Set<String> getPropertyNames() { - return propertyNames; - } - @Override public String getValue(final String propertyName) { String value = super.getValue(propertyName); return value == null ? wildcards.findRootValue(propertyName) : value; } - private static KeyMap<String> propertiesToKeyMap(final Map<String, String> properties) { - KeyMap<String> keyMap = new KeyMap<>(); + private static Map<String, String> filterWildcards(final Map<String, String> properties) { + Map<String, String> filtered = new HashMap<>(); for (Map.Entry<String, String> entry : properties.entrySet()) { if (entry.getKey().contains("*")) { continue; } - keyMap.findOrAdd(entry.getKey()).putRootValue(entry.getValue()); + filtered.put(entry.getKey(), entry.getValue()); } - return keyMap; + return filtered; } }
['core/runtime/src/main/java/io/quarkus/runtime/configuration/ConfigUtils.java']
{'.java': 1}
1
1
0
0
1
22,687,162
4,443,467
578,571
5,396
2,015
375
33
1
1,494
198
439
43
0
0
1970-01-01T00:27:43
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,351
quarkusio/quarkus/28198/27862
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/27862
https://github.com/quarkusio/quarkus/pull/28198
https://github.com/quarkusio/quarkus/pull/28198
1
fixes
ElasticSearch Dev Service image cannot be replaced with custom-built image
### Describe the bug In the ElasticSearch DEV service you can use your own image (`quarkus.elasticsearch.devservices.image-name`), however it is not accepted because it is not **name-compatible** with the expected value: `docker.elastic.co/elasticsearch/elasticsearch`. ### Expected behavior Any image that extends an ElasticSearch image is accepted and used. ### Actual behavior ``` ERROR [io.qua.dep.dev.IsolatedDevModeMain] (main) Failed to start quarkus: java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors [error]: Build step io.quarkus.elasticsearch.restclient.common.deployment.DevServicesElasticsearchProcessor#startElasticsearchDevService threw an exception: java.lang.RuntimeException: java.lang.IllegalStateException: Failed to verify that image 'registry.gitlab.com/xxxxx/search-service/elastic-with-files:my-tag' is a compatible substitute for 'docker.elastic.co/elasticsearch/elasticsearch'. This generally means that you are trying to use an image that Testcontainers has not been designed to use. If this is deliberate, and if you are confident that the image is compatible, you should declare compatibility in code using the `asCompatibleSubstituteFor` method. For example: DockerImageName myImage = DockerImageName.parse("registry.gitlab.com/xxxxx/search-service/elastic-with-files:my-tag").asCompatibleSubstituteFor("docker.elastic.co/elasticsearch/elasticsearch"); and then use `myImage` instead. at io.quarkus.elasticsearch.restclient.common.deployment.DevServicesElasticsearchProcessor.startElasticsearchDevService(DevServicesElasticsearchProcessor.java:98) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at io.quarkus.deployment.ExtensionLoader$3.execute(ExtensionLoader.java:977) at io.quarkus.builder.BuildContext.run(BuildContext.java:281) at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478) at java.base/java.lang.Thread.run(Thread.java:833) at org.jboss.threads.JBossThread.run(JBossThread.java:501) Caused by: java.lang.IllegalStateException: Failed to verify that image 'registry.gitlab.com/xxxxx/search-service/elastic-with-files:my-tag' is a compatible substitute for 'docker.elastic.co/elasticsearch/elasticsearch'. This generally means that you are trying to use an image that Testcontainers has not been designed to use. If this is deliberate, and if you are confident that the image is compatible, you should declare compatibility in code using the `asCompatibleSubstituteFor` method. For example: DockerImageName myImage = DockerImageName.parse("registry.gitlab.com/xxxxx/search-service/elastic-with-files:my-tag").asCompatibleSubstituteFor("docker.elastic.co/elasticsearch/elasticsearch"); and then use `myImage` instead. at org.testcontainers.utility.DockerImageName.assertCompatibleWith(DockerImageName.java:270) at org.testcontainers.elasticsearch.ElasticsearchContainer.<init>(ElasticsearchContainer.java:95) at io.quarkus.elasticsearch.restclient.common.deployment.DevServicesElasticsearchProcessor.lambda$startElasticsearch$1(DevServicesElasticsearchProcessor.java:198) at java.base/java.util.Optional.orElseGet(Optional.java:364) at io.quarkus.elasticsearch.restclient.common.deployment.DevServicesElasticsearchProcessor.startElasticsearch(DevServicesElasticsearchProcessor.java:224) at io.quarkus.elasticsearch.restclient.common.deployment.DevServicesElasticsearchProcessor.startElasticsearchDevService(DevServicesElasticsearchProcessor.java:88) ... 11 more ``` ### How to Reproduce? mvn io.quarkus.platform:quarkus-maven-plugin:2.12.1.Final:create \\ -DprojectGroupId=org.acme \\ -DprojectArtifactId=elasticsearch-quickstart \\ -DclassName="org.acme.datasource.GreetingResource" \\ -Dextensions="resteasy,resteasy-jackson,elasticsearch-rest-client" cd elasticsearch-quickstart/ echo "quarkus.elasticsearch.devservices.image-name = debian:buster" >> ./src/main/resources/application.properties mvn verify ### Output of `uname -a` or `ver` Linux ****** 5.4.72-microsoft-standard-WSL2 #1 SMP Wed Oct 28 23:40:43 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux ### Output of `java -version` openjdk version "17.0.3" 2022-04-19 OpenJDK Runtime Environment (build 17.0.3+7-Ubuntu-0ubuntu0.20.04.1) OpenJDK 64-Bit Server VM (build 17.0.3+7-Ubuntu-0ubuntu0.20.04.1, mixed mode, sharing) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.12.1.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.6 (84538c9988a25aec085021c365c560670ad80f63) Maven home: /opt/maven Java version: 17.0.3, vendor: Private Build, runtime: /usr/lib/jvm/java-17-openjdk-amd64 Default locale: en, platform encoding: UTF-8 OS name: "linux", version: "5.4.72-microsoft-standard-wsl2", arch: "amd64", family: "unix" ### Additional information This bug has the identical problem as: https://github.com/quarkusio/quarkus/issues/20945
cd4f781a0141cf159102232b553b95bb4357b636
cf81292249ab52f3cd36a81fb0789135c1d81949
https://github.com/quarkusio/quarkus/compare/cd4f781a0141cf159102232b553b95bb4357b636...cf81292249ab52f3cd36a81fb0789135c1d81949
diff --git a/extensions/elasticsearch-rest-client-common/deployment/src/main/java/io/quarkus/elasticsearch/restclient/common/deployment/DevServicesElasticsearchProcessor.java b/extensions/elasticsearch-rest-client-common/deployment/src/main/java/io/quarkus/elasticsearch/restclient/common/deployment/DevServicesElasticsearchProcessor.java index 44803e7d84c..fae32662211 100644 --- a/extensions/elasticsearch-rest-client-common/deployment/src/main/java/io/quarkus/elasticsearch/restclient/common/deployment/DevServicesElasticsearchProcessor.java +++ b/extensions/elasticsearch-rest-client-common/deployment/src/main/java/io/quarkus/elasticsearch/restclient/common/deployment/DevServicesElasticsearchProcessor.java @@ -176,7 +176,7 @@ private DevServicesResultBuildItem.RunningDevService startElasticsearch( throw new BuildException("Dev services for Elasticsearch didn't support Opensearch", Collections.emptyList()); } - // Hibernate search Elasticsearch have a version configuration property, we need to check that it is coherent + // Hibernate Search Elasticsearch have a version configuration property, we need to check that it is coherent // with the image we are about to launch if (buildItemConfig.version != null) { String containerTag = config.imageName.substring(config.imageName.indexOf(':') + 1); @@ -197,7 +197,7 @@ private DevServicesResultBuildItem.RunningDevService startElasticsearch( // Starting the server final Supplier<DevServicesResultBuildItem.RunningDevService> defaultElasticsearchSupplier = () -> { ElasticsearchContainer container = new ElasticsearchContainer( - DockerImageName.parse(config.imageName)); + DockerImageName.parse(config.imageName).asCompatibleSubstituteFor("elasticsearch/elasticsearch")); ConfigureUtil.configureSharedNetwork(container, "elasticsearch"); if (config.serviceName != null) { container.withLabel(DEV_SERVICE_LABEL, config.serviceName); diff --git a/extensions/kafka-client/deployment/src/main/java/io/quarkus/kafka/client/deployment/DevServicesKafkaProcessor.java b/extensions/kafka-client/deployment/src/main/java/io/quarkus/kafka/client/deployment/DevServicesKafkaProcessor.java index 319ff7d521d..0bbe4d81122 100644 --- a/extensions/kafka-client/deployment/src/main/java/io/quarkus/kafka/client/deployment/DevServicesKafkaProcessor.java +++ b/extensions/kafka-client/deployment/src/main/java/io/quarkus/kafka/client/deployment/DevServicesKafkaProcessor.java @@ -246,7 +246,7 @@ private RunningDevService startKafka(DockerStatusBuildItem dockerStatusBuildItem KAFKA_BOOTSTRAP_SERVERS, container.getBootstrapServers()); } else { RedPandaKafkaContainer container = new RedPandaKafkaContainer( - DockerImageName.parse(config.imageName), + DockerImageName.parse(config.imageName).asCompatibleSubstituteFor("vectorized/redpanda"), config.fixedExposedPort, launchMode.getLaunchMode() == LaunchMode.DEVELOPMENT ? config.serviceName : null, useSharedNetwork, config.redpanda); diff --git a/extensions/schema-registry/devservice/deployment/src/main/java/io/quarkus/apicurio/registry/devservice/DevServicesApicurioRegistryProcessor.java b/extensions/schema-registry/devservice/deployment/src/main/java/io/quarkus/apicurio/registry/devservice/DevServicesApicurioRegistryProcessor.java index 79e659a5562..7698a26f355 100644 --- a/extensions/schema-registry/devservice/deployment/src/main/java/io/quarkus/apicurio/registry/devservice/DevServicesApicurioRegistryProcessor.java +++ b/extensions/schema-registry/devservice/deployment/src/main/java/io/quarkus/apicurio/registry/devservice/DevServicesApicurioRegistryProcessor.java @@ -173,7 +173,8 @@ private RunningDevService startApicurioRegistry(DockerStatusBuildItem dockerStat getRegistryUrlConfigs("http://" + address.getUrl()))) .orElseGet(() -> { ApicurioRegistryContainer container = new ApicurioRegistryContainer( - DockerImageName.parse(config.imageName), config.fixedExposedPort, + DockerImageName.parse(config.imageName).asCompatibleSubstituteFor("apicurio/apicurio-registry-mem"), + config.fixedExposedPort, launchMode.getLaunchMode() == LaunchMode.DEVELOPMENT ? config.serviceName : null, useSharedNetwork); timeout.ifPresent(container::withStartupTimeout); diff --git a/extensions/smallrye-reactive-messaging-amqp/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/amqp/deployment/AmqpDevServicesProcessor.java b/extensions/smallrye-reactive-messaging-amqp/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/amqp/deployment/AmqpDevServicesProcessor.java index d6c6fa0146a..99fdf9a906b 100644 --- a/extensions/smallrye-reactive-messaging-amqp/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/amqp/deployment/AmqpDevServicesProcessor.java +++ b/extensions/smallrye-reactive-messaging-amqp/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/amqp/deployment/AmqpDevServicesProcessor.java @@ -176,7 +176,7 @@ private RunningDevService startAmqpBroker(DockerStatusBuildItem dockerStatusBuil final Supplier<RunningDevService> defaultAmqpBrokerSupplier = () -> { // Starting the broker ArtemisContainer container = new ArtemisContainer( - DockerImageName.parse(config.imageName), + DockerImageName.parse(config.imageName).asCompatibleSubstituteFor("artemiscloud/activemq-artemis-broker"), config.extra, config.fixedExposedPort, launchMode.getLaunchMode() == LaunchMode.DEVELOPMENT ? config.serviceName : null); diff --git a/extensions/smallrye-reactive-messaging-rabbitmq/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/rabbitmq/deployment/RabbitMQDevServicesProcessor.java b/extensions/smallrye-reactive-messaging-rabbitmq/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/rabbitmq/deployment/RabbitMQDevServicesProcessor.java index 85763f737ae..39d102ff575 100644 --- a/extensions/smallrye-reactive-messaging-rabbitmq/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/rabbitmq/deployment/RabbitMQDevServicesProcessor.java +++ b/extensions/smallrye-reactive-messaging-rabbitmq/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/rabbitmq/deployment/RabbitMQDevServicesProcessor.java @@ -176,7 +176,7 @@ private RunningDevService startRabbitMQBroker(DockerStatusBuildItem dockerStatus } ConfiguredRabbitMQContainer container = new ConfiguredRabbitMQContainer( - DockerImageName.parse(config.imageName), + DockerImageName.parse(config.imageName).asCompatibleSubstituteFor("rabbitmq"), config.fixedExposedPort, config.fixedExposedHttpPort, launchMode.getLaunchMode() == LaunchMode.DEVELOPMENT ? config.serviceName : null);
['extensions/smallrye-reactive-messaging-amqp/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/amqp/deployment/AmqpDevServicesProcessor.java', 'extensions/schema-registry/devservice/deployment/src/main/java/io/quarkus/apicurio/registry/devservice/DevServicesApicurioRegistryProcessor.java', 'extensions/kafka-client/deployment/src/main/java/io/quarkus/kafka/client/deployment/DevServicesKafkaProcessor.java', 'extensions/smallrye-reactive-messaging-rabbitmq/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/rabbitmq/deployment/RabbitMQDevServicesProcessor.java', 'extensions/elasticsearch-rest-client-common/deployment/src/main/java/io/quarkus/elasticsearch/restclient/common/deployment/DevServicesElasticsearchProcessor.java']
{'.java': 5}
5
5
0
0
5
22,811,532
4,473,746
583,011
5,406
1,220
212
13
5
5,630
387
1,352
76
1
1
1970-01-01T00:27:44
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,350
quarkusio/quarkus/28210/28098
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/28098
https://github.com/quarkusio/quarkus/pull/28210
https://github.com/quarkusio/quarkus/pull/28210
1
fix
Potential NPE in QuarkusClassLoader
I am trying to run a Quarkus app in a local container and use [remote development mode](https://quarkus.io/guides/maven-tooling#remote-development-mode) and I'm facing the same error: ``` backend | 2022-09-20 14:56:35,633 ERROR [io.qua.dep.dev.IsolatedDevModeMain] (vert.x-worker-thread-1) Failed to start quarkus: java.lang.RuntimeException: java.lang.NullPointerException: Cannot invoke "io.quarkus.bootstrap.classloading.ClassPathResource.getUrl()" because "res" is null backend | at io.quarkus.runner.bootstrap.AugmentActionImpl.runAugment(AugmentActionImpl.java:330) backend | at io.quarkus.runner.bootstrap.AugmentActionImpl.reloadExistingApplication(AugmentActionImpl.java:265) backend | at io.quarkus.runner.bootstrap.AugmentActionImpl.reloadExistingApplication(AugmentActionImpl.java:60) backend | at io.quarkus.deployment.dev.IsolatedDevModeMain.restartApp(IsolatedDevModeMain.java:251) backend | at io.quarkus.deployment.dev.IsolatedDevModeMain.restartCallback(IsolatedDevModeMain.java:234) backend | at io.quarkus.deployment.dev.RuntimeUpdatesProcessor.doScan(RuntimeUpdatesProcessor.java:536) backend | at io.quarkus.deployment.dev.RuntimeUpdatesProcessor.doScan(RuntimeUpdatesProcessor.java:436) backend | at io.quarkus.vertx.http.runtime.devmode.VertxHttpHotReplacementSetup$4.handle(VertxHttpHotReplacementSetup.java:152) backend | at io.quarkus.vertx.http.runtime.devmode.VertxHttpHotReplacementSetup$4.handle(VertxHttpHotReplacementSetup.java:139) backend | at io.vertx.core.impl.ContextBase.lambda$null$0(ContextBase.java:137) backend | at io.vertx.core.impl.ContextInternal.dispatch(ContextInternal.java:264) backend | at io.vertx.core.impl.ContextBase.lambda$executeBlocking$1(ContextBase.java:135) backend | at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) backend | at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) backend | at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1452) backend | at org.jboss.threads.DelegatingRunnable.run(DelegatingRunnable.java:29) backend | at org.jboss.threads.ThreadLocalResettingRunnable.run(ThreadLocalResettingRunnable.java:29) backend | at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) backend | at java.base/java.lang.Thread.run(Thread.java:833) backend | Caused by: java.lang.NullPointerException: Cannot invoke "io.quarkus.bootstrap.classloading.ClassPathResource.getUrl()" because "res" is null backend | at io.quarkus.bootstrap.classloading.QuarkusClassLoader.getResources(QuarkusClassLoader.java:250) backend | at io.quarkus.bootstrap.classloading.QuarkusClassLoader.getResources(QuarkusClassLoader.java:265) backend | at io.quarkus.bootstrap.classloading.QuarkusClassLoader.getResources(QuarkusClassLoader.java:197) backend | at io.smallrye.common.classloader.ClassPathUtils.consumeAsPaths(ClassPathUtils.java:84) backend | at io.smallrye.config.AbstractLocationConfigSourceLoader.tryClassPath(AbstractLocationConfigSourceLoader.java:128) backend | at io.smallrye.config.AbstractLocationConfigSourceLoader.loadConfigSources(AbstractLocationConfigSourceLoader.java:93) backend | at io.smallrye.config.AbstractLocationConfigSourceLoader.loadConfigSources(AbstractLocationConfigSourceLoader.java:76) backend | at io.quarkus.runtime.configuration.ApplicationPropertiesConfigSourceLoader$InClassPath.getConfigSources(ApplicationPropertiesConfigSourceLoader.java:30) backend | at io.quarkus.runtime.configuration.ApplicationPropertiesConfigSourceLoader$InClassPath.getConfigSources(ApplicationPropertiesConfigSourceLoader.java:27) backend | at io.smallrye.config.SmallRyeConfigBuilder.build(SmallRyeConfigBuilder.java:439) backend | at io.quarkus.deployment.ExtensionLoader.loadStepsFrom(ExtensionLoader.java:179) backend | at io.quarkus.deployment.QuarkusAugmentor.run(QuarkusAugmentor.java:105) backend | at io.quarkus.runner.bootstrap.AugmentActionImpl.runAugment(AugmentActionImpl.java:328) backend | ... 18 more ``` I am not using any database migration tool. Could it be related? _Originally posted by @y-luis in https://github.com/quarkusio/quarkus/issues/25256#issuecomment-1252562974_
8b2acbe409c521b3c84f527a47ee3215bc1dd298
93f5b5b1f4a7ad4085d54069eab8efbba025cecc
https://github.com/quarkusio/quarkus/compare/8b2acbe409c521b3c84f527a47ee3215bc1dd298...93f5b5b1f4a7ad4085d54069eab8efbba025cecc
diff --git a/core/deployment/src/main/java/io/quarkus/deployment/dev/RuntimeUpdatesProcessor.java b/core/deployment/src/main/java/io/quarkus/deployment/dev/RuntimeUpdatesProcessor.java index 57df8f03e13..3b869b5fadf 100644 --- a/core/deployment/src/main/java/io/quarkus/deployment/dev/RuntimeUpdatesProcessor.java +++ b/core/deployment/src/main/java/io/quarkus/deployment/dev/RuntimeUpdatesProcessor.java @@ -53,6 +53,7 @@ import org.jboss.jandex.Indexer; import org.jboss.logging.Logger; +import io.quarkus.bootstrap.runner.DevModeMediator; import io.quarkus.bootstrap.runner.Timing; import io.quarkus.changeagent.ClassChangeAgent; import io.quarkus.deployment.dev.DevModeContext.ModuleInfo; @@ -602,6 +603,7 @@ public Set<String> syncState(Map<String, String> fileHashes) { ret.add(i.getKey()); } } + List<Path> removedFiles = List.of(); for (Map.Entry<String, String> remaining : ourHashes.entrySet()) { String file = remaining.getKey(); if (file.endsWith("META-INF/MANIFEST.MF") || file.contains("META-INF/maven") @@ -609,8 +611,14 @@ public Set<String> syncState(Map<String, String> fileHashes) { //we have some filters, for files that we don't want to delete continue; } - log.info("Deleting removed file " + file); - Files.deleteIfExists(applicationRoot.resolve(file)); + log.info("Scheduled for removal " + file); + if (removedFiles.isEmpty()) { + removedFiles = new ArrayList<>(); + } + removedFiles.add(applicationRoot.resolve(file)); + } + if (!removedFiles.isEmpty()) { + DevModeMediator.removedFiles.addLast(removedFiles); } return ret; } catch (IOException e) { diff --git a/independent-projects/bootstrap/runner/src/main/java/io/quarkus/bootstrap/runner/DevModeMediator.java b/independent-projects/bootstrap/runner/src/main/java/io/quarkus/bootstrap/runner/DevModeMediator.java index 0cc428bf191..87d382db3c6 100644 --- a/independent-projects/bootstrap/runner/src/main/java/io/quarkus/bootstrap/runner/DevModeMediator.java +++ b/independent-projects/bootstrap/runner/src/main/java/io/quarkus/bootstrap/runner/DevModeMediator.java @@ -9,9 +9,11 @@ import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Deque; import java.util.List; import java.util.Timer; import java.util.TimerTask; +import java.util.concurrent.LinkedBlockingDeque; import org.jboss.logging.Logger; @@ -24,6 +26,8 @@ public class DevModeMediator { protected static final Logger LOGGER = Logger.getLogger(DevModeMediator.class); + public static final Deque<List<Path>> removedFiles = new LinkedBlockingDeque<>(); + static void doDevMode(Path appRoot) throws IOException, ClassNotFoundException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { Path deploymentClassPath = appRoot.resolve(QuarkusEntryPoint.LIB_DEPLOYMENT_DEPLOYMENT_CLASS_PATH_DAT); @@ -88,6 +92,13 @@ public void run() { closeable.close(); } closeable = null; + final List<Path> pathsToDelete = removedFiles.pollFirst(); + if (pathsToDelete != null) { + for (Path p : pathsToDelete) { + LOGGER.info("Deleting " + p); + Files.deleteIfExists(p); + } + } try { closeable = doStart(appRoot, deploymentClassPath); } catch (Exception e) {
['core/deployment/src/main/java/io/quarkus/deployment/dev/RuntimeUpdatesProcessor.java', 'independent-projects/bootstrap/runner/src/main/java/io/quarkus/bootstrap/runner/DevModeMediator.java']
{'.java': 2}
2
2
0
0
2
22,841,954
4,479,409
583,725
5,417
1,119
186
23
2
4,401
208
1,055
41
2
1
1970-01-01T00:27:44
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,349
quarkusio/quarkus/28213/28116
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/28116
https://github.com/quarkusio/quarkus/pull/28213
https://github.com/quarkusio/quarkus/pull/28213
1
fixes
VertxInputStream 10 s delay with parallel requests
### Describe the bug I have setup reseteasy reactive POST endpoint. When sending a lot of parallel requests with a client that reuses the connection, a delay of 10 seconds sometimes can occur in VertxInputStream. The bug seems to be the following: Assume we have two parallel requests A and B. connection is shared between A and B. 1. A and B both sets waiting = true and ends up in connection.wait() (VertxInputStream ~row 245) 2. A.endHandler is called (VertxInputStream ~row 188) 3. A.waiting == true so connection.notify() is called 4. Now, it is arbitray who will continue, assume B continues to run. This sets B.waiting = false (VertxInputStream ~row 249) 5. B.endHandler is called (VertxInputStream ~row 188) 6. B.waiting == false so connection.notify() is not called 7. The conneciton.wait() for A will not get notified and will timeout after rem (~10) seconds The code below shows the code from the sequence above. ```java request.endHandler(new Handler<Void>() { @Override public void handle(Void event) { synchronized (connection) { eof = true; if (waiting) { connection.notify(); } } } }); ... protected ByteBuf readBlocking() throws IOException { synchronized (request.connection()) { ... try { ... waiting = true; request.connection().wait(rem); } catch (InterruptedException e) { throw new InterruptedIOException(e.getMessage()); } finally { waiting = false; } } ... } ``` It works fine when not sharing the connection. ### Expected behavior The expected behaviour is that VertxInputStream should not delay the requests like this. ### Actual behavior Sometimes requests (that reads data with VertxInputStream) gets delayed by 10 seconds. ### How to Reproduce? [src.zip](https://github.com/quarkusio/quarkus/files/9614315/src.zip) The attached code shows the problem isolated. Also, the code from the description shows the core of the problem. ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` 17.0.1 ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.12.2 ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) 7.4 ### Additional information _No response_
70df6b8d5313960d86338d886a2169a6ccf099de
eb5083b8745a850b6eb73be8a05480e10c70e1e1
https://github.com/quarkusio/quarkus/compare/70df6b8d5313960d86338d886a2169a6ccf099de...eb5083b8745a850b6eb73be8a05480e10c70e1e1
diff --git a/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxInputStream.java b/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxInputStream.java index 9e56af5b332..10717a6f0c8 100644 --- a/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxInputStream.java +++ b/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxInputStream.java @@ -190,7 +190,7 @@ public void handle(Void event) { synchronized (connection) { eof = true; if (waiting) { - connection.notify(); + connection.notifyAll(); } } } @@ -212,7 +212,7 @@ public void handle(Throwable event) { } } if (waiting) { - connection.notify(); + connection.notifyAll(); } } } diff --git a/independent-projects/resteasy-reactive/server/vertx/src/main/java/org/jboss/resteasy/reactive/server/vertx/VertxInputStream.java b/independent-projects/resteasy-reactive/server/vertx/src/main/java/org/jboss/resteasy/reactive/server/vertx/VertxInputStream.java index c30afb92de7..9c56278499d 100644 --- a/independent-projects/resteasy-reactive/server/vertx/src/main/java/org/jboss/resteasy/reactive/server/vertx/VertxInputStream.java +++ b/independent-projects/resteasy-reactive/server/vertx/src/main/java/org/jboss/resteasy/reactive/server/vertx/VertxInputStream.java @@ -190,7 +190,7 @@ public void handle(Void event) { synchronized (connection) { eof = true; if (waiting) { - connection.notify(); + connection.notifyAll(); } } } @@ -212,7 +212,7 @@ public void handle(Throwable event) { } } if (waiting) { - connection.notify(); + connection.notifyAll(); } } }
['extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxInputStream.java', 'independent-projects/resteasy-reactive/server/vertx/src/main/java/org/jboss/resteasy/reactive/server/vertx/VertxInputStream.java']
{'.java': 2}
2
2
0
0
2
22,844,104
4,479,791
583,769
5,417
474
36
8
2
2,444
325
545
81
1
1
1970-01-01T00:27:44
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,348
quarkusio/quarkus/28253/27904
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/27904
https://github.com/quarkusio/quarkus/pull/28253
https://github.com/quarkusio/quarkus/pull/28253
1
fixes
Kafka configuration reported as unknown config
### Describe the bug I have configured a property for a kafka incoming topic which quarkus report as unknown: `mp.messaging.incoming.topic-test1-in.pause-if-no-requests=false` The documentation has this propertties available to use but I get a warning on startup: `2022-09-13 17:34:03,125 WARN [org.apa.kaf.cli.con.ConsumerConfig] (main) The configuration 'pause-if-no-requests' was supplied but isn't a known config.` In DEV mode, sometimes, it also issues a warning for the property: `mp.messaging.incoming.topic-test1-in.group.id=my-consumer-group` The warning is issues on the AdminClientConfig class: `2022-09-13 17:38:29,082 WARN [org.apa.kaf.cli.adm.AdminClientConfig] (executor-thread-0) The configuration 'group.id' was supplied but isn't a known config` ### Expected behavior No warning issued if these property is present ### Actual behavior _No response_ ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.12.1.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
38f4138c08b31575def5dac3c2e4b35bea9d3c98
57f18eb8792673a93c364db14ed21d205e720193
https://github.com/quarkusio/quarkus/compare/38f4138c08b31575def5dac3c2e4b35bea9d3c98...57f18eb8792673a93c364db14ed21d205e720193
diff --git a/extensions/kafka-client/deployment/src/main/java/io/quarkus/kafka/client/deployment/DevServicesKafkaProcessor.java b/extensions/kafka-client/deployment/src/main/java/io/quarkus/kafka/client/deployment/DevServicesKafkaProcessor.java index 0bbe4d81122..03b704e56fe 100644 --- a/extensions/kafka-client/deployment/src/main/java/io/quarkus/kafka/client/deployment/DevServicesKafkaProcessor.java +++ b/extensions/kafka-client/deployment/src/main/java/io/quarkus/kafka/client/deployment/DevServicesKafkaProcessor.java @@ -152,7 +152,7 @@ public void createTopicPartitions(String bootstrapServers, KafkaDevServiceCfg co // get current partitions for topics asked to be created Set<String> currentTopics = adminClient.listTopics().names() .get(adminClientTimeout, TimeUnit.MILLISECONDS); - Map<String, TopicDescription> partitions = adminClient.describeTopics(currentTopics).all() + Map<String, TopicDescription> partitions = adminClient.describeTopics(currentTopics).allTopicNames() .get(adminClientTimeout, TimeUnit.MILLISECONDS); // find new topics to create List<NewTopic> newTopics = topicPartitions.entrySet().stream() diff --git a/extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/KafkaAdminClient.java b/extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/KafkaAdminClient.java index c9b75dc1d00..d9901b7bb12 100644 --- a/extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/KafkaAdminClient.java +++ b/extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/KafkaAdminClient.java @@ -30,8 +30,13 @@ public class KafkaAdminClient { @PostConstruct void init() { - Map<String, Object> conf = new HashMap<>(config); + Map<String, Object> conf = new HashMap<>(); conf.put(AdminClientConfig.REQUEST_TIMEOUT_MS_CONFIG, DEFAULT_ADMIN_CLIENT_TIMEOUT); + for (Map.Entry<String, Object> entry : config.entrySet()) { + if (AdminClientConfig.configNames().contains(entry.getKey())) { + conf.put(entry.getKey(), entry.getValue().toString()); + } + } client = AdminClient.create(conf); } @@ -81,4 +86,11 @@ public Collection<AclBinding> getAclInfo() throws InterruptedException, Executio var options = new DescribeAclsOptions().timeoutMs(1_000); return client.describeAcls(filter, options).values().get(); } + + public Map<String, TopicDescription> describeTopics(Collection<String> topicNames) + throws InterruptedException, ExecutionException { + return client.describeTopics(topicNames) + .allTopicNames() + .get(); + } } diff --git a/extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/ui/KafkaTopicClient.java b/extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/ui/KafkaTopicClient.java index 174ef04aa08..8a2340fd475 100644 --- a/extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/ui/KafkaTopicClient.java +++ b/extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/ui/KafkaTopicClient.java @@ -9,12 +9,9 @@ import java.util.function.Function; import java.util.stream.Collectors; -import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; -import org.apache.kafka.clients.admin.AdminClient; -import org.apache.kafka.clients.admin.AdminClientConfig; import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; @@ -27,6 +24,7 @@ import org.apache.kafka.common.serialization.BytesSerializer; import org.apache.kafka.common.utils.Bytes; +import io.quarkus.kafka.client.runtime.KafkaAdminClient; import io.quarkus.kafka.client.runtime.ui.model.Order; import io.quarkus.kafka.client.runtime.ui.model.converter.KafkaModelConverter; import io.quarkus.kafka.client.runtime.ui.model.request.KafkaMessageCreateRequest; @@ -38,8 +36,8 @@ public class KafkaTopicClient { // TODO: make configurable private static final int RETRIES = 3; - //TODO: inject me - private AdminClient adminClient; + @Inject + KafkaAdminClient adminClient; KafkaModelConverter modelConverter = new KafkaModelConverter(); @@ -47,13 +45,6 @@ public class KafkaTopicClient { @Identifier("default-kafka-broker") Map<String, Object> config; - @PostConstruct - void init() { - Map<String, Object> conf = new HashMap<>(config); - conf.put(AdminClientConfig.REQUEST_TIMEOUT_MS_CONFIG, "5000"); - adminClient = AdminClient.create(conf); - } - private Producer<Bytes, Bytes> createProducer() { Map<String, Object> config = new HashMap<>(this.config); @@ -260,8 +251,6 @@ public void createMessage(KafkaMessageCreateRequest request) { public List<Integer> partitions(String topicName) throws ExecutionException, InterruptedException { return adminClient.describeTopics(List.of(topicName)) - .allTopicNames() - .get() .values().stream() .reduce((a, b) -> { throw new IllegalStateException(
['extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/ui/KafkaTopicClient.java', 'extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/KafkaAdminClient.java', 'extensions/kafka-client/deployment/src/main/java/io/quarkus/kafka/client/deployment/DevServicesKafkaProcessor.java']
{'.java': 3}
3
3
0
0
3
22,861,166
4,483,353
584,211
5,421
1,443
272
33
3
1,257
158
321
49
0
0
1970-01-01T00:27:44
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,347
quarkusio/quarkus/28254/28246
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/28246
https://github.com/quarkusio/quarkus/pull/28254
https://github.com/quarkusio/quarkus/pull/28254
1
fixes
Using oidc error-path doesn't keep the original path params used for session handling
### Describe the bug I have an rest resource protected with OIDC, and wants to implement a customized web page when the authentication could not be performed. I am trying to accomplish this with the setting: quarkus.oidc.authentication.error-path=/error If I surf to my application with the following url: http://localhost/application?ref=xxxxx Quarkus will redirect the browser with a 302 response and the location url as something like this: http://thirdPartyAuth/uas?state=yyyyy&redirect_uri=http://localhost/application If the user perform a successful authentication and gets redirected back to the application I will land on this page: http://localhost:8080/application?ref=xxxxx i.e I have access to the original ref parameter and I can correlate this in my bigger session and a can mark this task as completed. However when something gets wrong. For example when a user is canceling the authentication on the third party auth server the user is redirected to the error page with this uri: http://localhost/application/error?state=yyyyy The redirect on error is working and the user is presented with a correct error web page. The problem is that I am missing the ref=xxxxx parameter. I have only access to the parameter state=yyyyy whis is made up in the Quarkus extension. If this is an expected behaviour is it possible for me to set the state=yyyyy parameter from the application myself or if it is possible to fetch this parameter when the authentication process is starting so that I now whet user is landing on the error page? ### Expected behavior Using the property: quarkus.oidc.authentication.error-path=/error Quarkus should keep the original path parameters so that the user land on the page: http://localhost:8080/application/error?ref=xxxxx when an error occurs during the authentication process. ### Actual behavior Using the property: quarkus.oidc.authentication.error-path=/error The user land on the page: http://localhost:8080/application/error?state=yyyyy I can't figure out how to map the state paramater to my original ref parameter? ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` Quarkus 2.12.1.Final ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
258d9d1826de6b0ecb00750d0d9d4fa4c2fc0864
50125bce72a63e18d6e423dfa217d3809e08c500
https://github.com/quarkusio/quarkus/compare/258d9d1826de6b0ecb00750d0d9d4fa4c2fc0864...50125bce72a63e18d6e423dfa217d3809e08c500
diff --git a/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/CodeAuthenticationMechanism.java b/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/CodeAuthenticationMechanism.java index 84576f9348c..68e53d0a981 100644 --- a/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/CodeAuthenticationMechanism.java +++ b/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/CodeAuthenticationMechanism.java @@ -153,17 +153,41 @@ public Uni<SecurityIdentity> apply(TenantConfigContext tenantContext) { LOG.debugf("Authentication has failed, error: %s, description: %s", error, errorDescription); if (oidcTenantConfig.authentication.errorPath.isPresent()) { - URI absoluteUri = URI.create(context.request().absoluteURI()); + Uni<TenantConfigContext> resolvedContext = resolver.resolveContext(context); + return resolvedContext.onItem() + .transformToUni(new Function<TenantConfigContext, Uni<? extends SecurityIdentity>>() { + @Override + public Uni<SecurityIdentity> apply(TenantConfigContext tenantContext) { + URI absoluteUri = URI.create(context.request().absoluteURI()); + + String userQuery = null; + + // This is an original redirect from IDP, check if the original request path and query need to be restored + CodeAuthenticationStateBean stateBean = getCodeAuthenticationBean(parsedStateCookieValue, + tenantContext); + if (stateBean != null && stateBean.getRestorePath() != null) { + String restorePath = stateBean.getRestorePath(); + int userQueryIndex = restorePath.indexOf("?"); + if (userQueryIndex >= 0 && userQueryIndex + 1 < restorePath.length()) { + userQuery = restorePath.substring(userQueryIndex + 1); + } + } - StringBuilder errorUri = new StringBuilder(buildUri(context, - isForceHttps(oidcTenantConfig), - absoluteUri.getAuthority(), - oidcTenantConfig.authentication.errorPath.get())); - errorUri.append('?').append(getRequestParametersAsQuery(absoluteUri, requestParams, oidcTenantConfig)); + StringBuilder errorUri = new StringBuilder(buildUri(context, + isForceHttps(oidcTenantConfig), + absoluteUri.getAuthority(), + oidcTenantConfig.authentication.errorPath.get())); + errorUri.append('?') + .append(getRequestParametersAsQuery(absoluteUri, requestParams, oidcTenantConfig)); + if (userQuery != null) { + errorUri.append('&').append(userQuery); + } - String finalErrorUri = errorUri.toString(); - LOG.debugf("Error URI: %s", finalErrorUri); - return Uni.createFrom().failure(new AuthenticationRedirectException(finalErrorUri)); + String finalErrorUri = errorUri.toString(); + LOG.debugf("Error URI: %s", finalErrorUri); + return Uni.createFrom().failure(new AuthenticationRedirectException(finalErrorUri)); + } + }); } else { LOG.error( "Authentication has failed but no error handler is found, completing the code flow with HTTP status 401"); diff --git a/integration-tests/oidc-code-flow/src/main/java/io/quarkus/it/keycloak/TenantHttps.java b/integration-tests/oidc-code-flow/src/main/java/io/quarkus/it/keycloak/TenantHttps.java index 4f752143d3e..f06cffa5a46 100644 --- a/integration-tests/oidc-code-flow/src/main/java/io/quarkus/it/keycloak/TenantHttps.java +++ b/integration-tests/oidc-code-flow/src/main/java/io/quarkus/it/keycloak/TenantHttps.java @@ -33,7 +33,8 @@ public String getTenantWithQuery(@QueryParam("code") String value) { @GET @Path("error") - public String getError(@QueryParam("error") String error, @QueryParam("error_description") String errorDescription) { - return "error: " + error + ", error_description: " + errorDescription; + public String getError(@QueryParam("error") String error, @QueryParam("error_description") String errorDescription, + @QueryParam("code") String value) { + return "code: " + value + ", error: " + error + ", error_description: " + errorDescription; } } diff --git a/integration-tests/oidc-code-flow/src/test/java/io/quarkus/it/keycloak/CodeFlowTest.java b/integration-tests/oidc-code-flow/src/test/java/io/quarkus/it/keycloak/CodeFlowTest.java index 0049d1d1eed..a808bf0c98a 100644 --- a/integration-tests/oidc-code-flow/src/test/java/io/quarkus/it/keycloak/CodeFlowTest.java +++ b/integration-tests/oidc-code-flow/src/test/java/io/quarkus/it/keycloak/CodeFlowTest.java @@ -148,7 +148,7 @@ public void testCodeFlowScopeErrorWithErrorPage() throws IOException { endpointErrorLocation = "http" + endpointErrorLocation.substring(5); HtmlPage page = webClient.getPage(URI.create(endpointErrorLocation).toURL()); - assertEquals("error: invalid_scope, error_description: Invalid scopes: unknown", + assertEquals("code: b, error: invalid_scope, error_description: Invalid scopes: unknown", page.getBody().asText()); webClient.getCookieManager().clearCookies(); }
['integration-tests/oidc-code-flow/src/main/java/io/quarkus/it/keycloak/TenantHttps.java', 'integration-tests/oidc-code-flow/src/test/java/io/quarkus/it/keycloak/CodeFlowTest.java', 'extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/CodeAuthenticationMechanism.java']
{'.java': 3}
3
3
0
0
3
22,881,792
4,487,025
584,767
5,424
3,115
446
42
1
2,489
352
553
68
6
0
1970-01-01T00:27:44
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,346
quarkusio/quarkus/28285/28184
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/28184
https://github.com/quarkusio/quarkus/pull/28285
https://github.com/quarkusio/quarkus/pull/28285
1
fixes
quarkus-smallrye-graphql: @ErrorDataFetch event is not emitted in batch query
### Describe the bug When executing a non-batch query, the following code can receive the error that is thrown during data-fetching process. ``` public void onError(@Observes @ErrorDataFetch ErrorInfo errorInfo) { System.out.println("[error] " + errorInfo.getT().getMessage()); } ``` But, when executing a [batch query](https://quarkus.io/guides/smallrye-graphql#batching) and an error is thrown in the batch process, the above observer can't receive the error. I guess that we should call `eventEmitter.fireOnDataFetchError(...)` like [this code of non-batching query](https://github.com/quarkusio/quarkus/blob/7744dec/extensions/smallrye-graphql/runtime/src/main/java/io/quarkus/smallrye/graphql/runtime/spi/datafetcher/QuarkusDefaultDataFetcher.java#L90). ### Expected behavior _No response_ ### Actual behavior _No response_ ### How to Reproduce? I wrote a minimum reproducible example. https://github.com/ikenox/code-with-quarkus/blob/e794dddd21d75d09e9a3e68b4602f5da48d7ca62/src/main/java/info/ikenox/ExampleResolver.java You can reproduce the issue by executing the following GraphQL query. ``` query { example{ fooValue bar{ barValue } } } ``` ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
47429fc11ded66d1571601fd81fca78cf9b2ea05
0ac49b1f6f8247e6ec0f8661f77833a009e7602a
https://github.com/quarkusio/quarkus/compare/47429fc11ded66d1571601fd81fca78cf9b2ea05...0ac49b1f6f8247e6ec0f8661f77833a009e7602a
diff --git a/extensions/smallrye-graphql/runtime/src/main/java/io/quarkus/smallrye/graphql/runtime/spi/datafetcher/QuarkusDefaultDataFetcher.java b/extensions/smallrye-graphql/runtime/src/main/java/io/quarkus/smallrye/graphql/runtime/spi/datafetcher/QuarkusDefaultDataFetcher.java index d6d6dad5005..311891879e5 100644 --- a/extensions/smallrye-graphql/runtime/src/main/java/io/quarkus/smallrye/graphql/runtime/spi/datafetcher/QuarkusDefaultDataFetcher.java +++ b/extensions/smallrye-graphql/runtime/src/main/java/io/quarkus/smallrye/graphql/runtime/spi/datafetcher/QuarkusDefaultDataFetcher.java @@ -3,6 +3,7 @@ import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CompletionStage; +import java.util.function.Consumer; import org.eclipse.microprofile.graphql.GraphQLException; @@ -110,10 +111,20 @@ private CompletionStage<List<T>> invokeBatchBlocking(DataFetchingEnvironment dfe return (List<T>) operationInvoker.invokePrivileged(arguments); }); + // this gets called on a batch error, so that error callbacks can run with the proper context too + Consumer<Throwable> onErrorConsumer = threadContext.contextualConsumer((Throwable exception) -> { + io.smallrye.graphql.api.Context context = dfe.getGraphQlContext().get("context"); + eventEmitter.fireOnDataFetchError(context, exception); + }); + // Here call blocking with context BlockingHelper.runBlocking(vc, contextualCallable, result); - return result.future().toCompletionStage(); - + return result.future().toCompletionStage() + .whenComplete((resultList, error) -> { + if (error != null) { + onErrorConsumer.accept(error); + } + }); } private boolean runBlocking(DataFetchingEnvironment dfe) {
['extensions/smallrye-graphql/runtime/src/main/java/io/quarkus/smallrye/graphql/runtime/spi/datafetcher/QuarkusDefaultDataFetcher.java']
{'.java': 1}
1
1
0
0
1
22,855,126
4,482,052
584,048
5,420
733
132
15
1
1,547
165
391
61
3
2
1970-01-01T00:27:44
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,345
quarkusio/quarkus/28296/28292
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/28292
https://github.com/quarkusio/quarkus/pull/28296
https://github.com/quarkusio/quarkus/pull/28296
1
fix
`StorkClientRequestFilter` not registered when using `ClientBuilder` to build a jax-rs client
### Describe the bug When using Stork with a manually-created jax-rs client (via `ClientBuilder.newClient()`), the `StorkClientRequestFilter` is not automatically registered. Stork worked fine with the jax-rs client in Quarkus 2.12, but in 2.13 this is broken unless the user manually registers the filter. See https://github.com/quarkusio/quarkus-super-heroes/blob/main/rest-fights/src/main/java/io/quarkus/sample/superheroes/fight/client/VillainClient.java#L38 If the user does not manually register the filter then they will end up with a failure that looks something like ``` java.lang.IllegalArgumentException: Invalid REST Client URL used: 'stork://villain-service/api/villains/random' ``` At a very minimum, this should be documented in the Quarkus 2.13 release notes. ### Expected behavior I would expect Stork to "just work" with the jax-rs client, as it did prior to Quarkus 2.12. ### Actual behavior The application fails if the user does not manually register the filter. ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information The `OpenTelemetryClientFilter` seems to be registered automatically when creating the jax-rs client this way, so there must be a way to do this as well for the `StorkClientRequestFilter`.
8da3049fe4bc109060c3d4c8f0d37107be48264b
1563b88de6d6d08e83e9df2fb27ccd384c57ade6
https://github.com/quarkusio/quarkus/compare/8da3049fe4bc109060c3d4c8f0d37107be48264b...1563b88de6d6d08e83e9df2fb27ccd384c57ade6
diff --git a/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/stork/StorkIntegrationTest.java b/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/stork/StorkIntegrationTest.java index f57a1d437d7..32c92031137 100644 --- a/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/stork/StorkIntegrationTest.java +++ b/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/stork/StorkIntegrationTest.java @@ -4,6 +4,10 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.net.URI; +import java.net.URISyntaxException; + +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.core.UriBuilder; import org.eclipse.microprofile.rest.client.RestClientBuilder; import org.eclipse.microprofile.rest.client.inject.RestClient; @@ -34,6 +38,19 @@ void shouldDetermineUrlViaStork() { assertThat(greeting).isEqualTo("hello, black and white bird"); } + @Test + void shouldDetermineUrlViaStorkWhenUsingTarget() throws URISyntaxException { + String greeting = ClientBuilder.newClient().target("stork://hello-service/hello").request().get(String.class); + assertThat(greeting).isEqualTo("Hello"); + + greeting = ClientBuilder.newClient().target(new URI("stork://hello-service/hello")).request().get(String.class); + assertThat(greeting).isEqualTo("Hello"); + + greeting = ClientBuilder.newClient().target(UriBuilder.fromUri("stork://hello-service/hello")).request() + .get(String.class); + assertThat(greeting).isEqualTo("Hello"); + } + @Test void shouldDetermineUrlViaStorkCDI() { String greeting = client.echo("big bird"); diff --git a/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/WebTargetImpl.java b/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/WebTargetImpl.java index 56fc7d2f4d0..1b4b0355ae6 100644 --- a/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/WebTargetImpl.java +++ b/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/WebTargetImpl.java @@ -320,10 +320,45 @@ private void abortIfClosed() { protected InvocationBuilderImpl createQuarkusRestInvocationBuilder(HttpClient client, UriBuilder uri, ConfigurationImpl configuration) { - return new InvocationBuilderImpl(uri.build(), restClient, client, this, configuration, + URI actualUri = uri.build(); + registerStorkFilterIfNeeded(configuration, actualUri); + return new InvocationBuilderImpl(actualUri, restClient, client, this, configuration, handlerChain.setPreClientSendHandler(preClientSendHandler), requestContext); } + /** + * If the URI starts with stork:// or storks://, then register the StorkClientRequestFilter automatically. + * + * @param configuration the configuration + * @param actualUri the uri + */ + private static void registerStorkFilterIfNeeded(ConfigurationImpl configuration, URI actualUri) { + if (actualUri.getScheme() != null && actualUri.getScheme().startsWith("stork") + && !isStorkAlreadyRegistered(configuration)) { + configuration.register(StorkClientRequestFilter.class); + } + } + + /** + * Checks if the Stork request filter is already registered. + * We cannot use configuration.isRegistered, as the user registration uses a subclass, and so fail the equality + * expectation. + * <p> + * This method prevents having the stork filter registered twice: once because the uri starts with stork:// and, + * once from the user. + * + * @param configuration the configuration + * @return {@code true} if stork is already registered. + */ + private static boolean isStorkAlreadyRegistered(ConfigurationImpl configuration) { + for (Class<?> clazz : configuration.getClasses()) { + if (clazz.getName().startsWith(StorkClientRequestFilter.class.getName())) { + return true; + } + } + return false; + } + @Override public WebTargetImpl property(String name, Object value) { abortIfClosed();
['independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/WebTargetImpl.java', 'extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/stork/StorkIntegrationTest.java']
{'.java': 2}
2
2
0
0
2
22,859,531
4,482,898
584,146
5,420
1,675
332
37
1
1,552
208
379
51
1
1
1970-01-01T00:27:44
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,344
quarkusio/quarkus/28312/27778
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/27778
https://github.com/quarkusio/quarkus/pull/28312
https://github.com/quarkusio/quarkus/pull/28312
1
fixes
Misleading 'unrecognized configuration' warnings for quarkus.debug.transformed-classes-dir and quarkus.debug.generated-sources-dir
### Describe the bug https://quarkus.io/guides/writing-extensions suggests the following debug options: > There are also three system properties that allow you to dump the generated/transformed classes to the filesystem and inspect them later, for example via a decompiler in your IDE. > > `quarkus.debug.generated-classes-dir` - to dump the generated classes, such as bean metadata > `quarkus.debug.transformed-classes-dir` - to dump the transformed classes, e.g. Panache entities > `quarkus.debug.generated-sources-dir` - to dump the ZIG files; ZIG file is a textual representation of the generated code that is referenced in the stack traces All of the options produce the expected output, but there are warnings in the log for the transformed classes and generated sources options (but not the generated classes): ``` 2022-09-07 10:45:32,489 WARN [io.qua.config] (Quarkus Main Thread) Unrecognized configuration key "quarkus.debug.generated-sources-dir" was provided; it will be ignored; verify that the dependency extension for this configuration is set or that you did not make a typo 2022-09-07 10:45:32,489 WARN [io.qua.config] (Quarkus Main Thread) Unrecognized configuration key "quarkus.debug.transformed-classes-dir" was provided; it will be ignored; verify that the dependency extension for this configuration is set or that you did not make a typo ``` I can't see any different handling in the code for the three options, so I'm not sure why one doesn't get a warning and two do. ### Expected behavior Since these are valid options, there should not be a warning in the log. ### Actual behavior ``` 2022-09-07 10:45:32,489 WARN [io.qua.config] (Quarkus Main Thread) Unrecognized configuration key "quarkus.debug.generated-sources-dir" was provided; it will be ignored; verify that the dependency extension for this configuration is set or that you did not make a typo 2022-09-07 10:45:32,489 WARN [io.qua.config] (Quarkus Main Thread) Unrecognized configuration key "quarkus.debug.transformed-classes-dir" was provided; it will be ignored; verify that the dependency extension for this configuration is set or that you did not make a typo ``` ### How to Reproduce? Any Quarkus application should reproduce; I used an application of my own and also the getting started app. ``` quarkus create app org.acme:getting-started \\ --extension=resteasy-reactive cd getting-started mvn quarkus:dev -Dquarkus.debug.transformed-classes-dir=transformed -Dquarkus.debug.generated-classes-dir=generated -Dquarkus.debug.generated-sources-dir=sources ``` ### Output of `uname -a` or `ver` Darwin hcummins-mac 21.6.0 Darwin Kernel Version 21.6.0: Wed Aug 10 14:28:23 PDT 2022; root:xnu-8020.141.5~2/RELEASE_ARM64_T6000 arm64 ### Output of `java -version` openjdk version "17.0.2" 2022-01-18 OpenJDK Runtime Environment Temurin-17.0.2+8 (build 17.0.2+8) OpenJDK 64-Bit Server VM Temurin-17.0.2+8 (build 17.0.2+8, mixed mode) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.12.0.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.6 (84538c9988a25aec085021c365c560670ad80f63) ### Additional information _No response_
91be040f20841699302ae2c89852ede12802d8e0
15424f4e8fb0142571d5793f7453131f56a38453
https://github.com/quarkusio/quarkus/compare/91be040f20841699302ae2c89852ede12802d8e0...15424f4e8fb0142571d5793f7453131f56a38453
diff --git a/core/deployment/src/main/java/io/quarkus/deployment/DebugConfig.java b/core/deployment/src/main/java/io/quarkus/deployment/DebugConfig.java index e54d05c7355..bdacdd8419c 100644 --- a/core/deployment/src/main/java/io/quarkus/deployment/DebugConfig.java +++ b/core/deployment/src/main/java/io/quarkus/deployment/DebugConfig.java @@ -25,4 +25,18 @@ public class DebugConfig { */ @ConfigItem Optional<String> generatedClassesDir; + + /** + * If set to a directory, all transformed classes (e.g. Panache entities) will be written into that directory + */ + @ConfigItem + Optional<String> transformedClassesDir; + + /** + * If set to a directory, ZIG files for generated code will be written into that directory. + * <p> + * A ZIG file is a textual representation of the generated code that is referenced in the stacktraces. + */ + @ConfigItem + Optional<String> generatedSourcesDir; }
['core/deployment/src/main/java/io/quarkus/deployment/DebugConfig.java']
{'.java': 1}
1
1
0
0
1
22,860,171
4,483,033
584,172
5,421
493
112
14
1
3,261
426
879
64
1
3
1970-01-01T00:27:44
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,290
quarkusio/quarkus/30255/30044
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/30044
https://github.com/quarkusio/quarkus/pull/30255
https://github.com/quarkusio/quarkus/pull/30255
1
fix
Resteasy Reactive Rest Client fails to re-construct large chunks of streamed json (stream+json) and fails deserialization
### Describe the bug Note: This is related to #30040 in that both result in `JsonMappingException`s, but this is a different issue. I am trying to use `RestMediaType.APPLICATION_STREAM_JSON` to stream a `Multi` that contains a few larger objects (think ~25 kB each) from my reactive java server to a reactive java client, using the rest client. However, the deserialization of the objects fails with `Unexpected end-of-input` errors, either at the end of `1943` bytes or `8192` bytes. (For the `1943` case, I think there is potentially header info on the first chunk that is cutting into the `8192` total, since when I try to collect the chunks as Strings instead of reading them as my custom objects, all but the first String are 8192 chars long) Through my own investigation I have found the workaround is to increase the Vertx `HttpClientOptions` for `DEFAULT_MAX_CHUNK_SIZE` and `DEFAULT_RECEIVE_BUFFER_SIZE`, both of which are defaulted to `8192` Maybe that is the final solution, but I would think that the rest client should be able to use the newline-delimited json to determine when it has received an entire object, and buffer/hold in memory up to that point before attempting to deserialize. ### Expected behavior Rest client can properly receive and deserialize a stream of larger json objects, without having to fiddle with the http client options myself ### Actual behavior Errors in the client: ``` com.fasterxml.jackson.databind.JsonMappingException: Unexpected end-of-input in field name at [Source: (ByteArrayInputStream); line: 1, column: 1943] ... com.fasterxml.jackson.core.io.JsonEOFException: Unexpected end-of-input in VALUE_STRING at [Source: (ByteArrayInputStream); line: 1, column: 8192] ``` ### How to Reproduce? Reproducer: `service3` (client) and `service4` (server) in https://github.com/fleckware/quarkus-test 1. in one terminal `./gradlew service4:quarkusDev` 2. in a separate terminal `./gradlew service3:quarkusDev` 3. in a separate terminal `curl localhost:8081/service4/test/large > output.json` 4. observe that when hitting the streaming endpoint on the server directly, there is no issue 5. now try to hit it using the rest client `curl localhost:8080/service3/test/large` 6. observe the json mapping error in the `service3` terminal ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` openjdk 11.0.10 ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.15.0 ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) gradle 7.4.2 ### Additional information _No response_
f9a688a2185346b9ff41ff0e9157c9ab30f142c4
e7eeaea9944db9700ce9f8c6ace17d49237f3313
https://github.com/quarkusio/quarkus/compare/f9a688a2185346b9ff41ff0e9157c9ab30f142c4...e7eeaea9944db9700ce9f8c6ace17d49237f3313
diff --git a/extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/sse/Message.java b/extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/streams/Message.java similarity index 70% rename from extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/sse/Message.java rename to extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/streams/Message.java index c09c92acb96..79109e22e20 100644 --- a/extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/sse/Message.java +++ b/extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/streams/Message.java @@ -1,4 +1,4 @@ -package io.quarkus.resteasy.reactive.jackson.deployment.test.sse; +package io.quarkus.resteasy.reactive.jackson.deployment.test.streams; public class Message { public String name; diff --git a/extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/sse/SseResource.java b/extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/streams/StreamResource.java similarity index 84% rename from extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/sse/SseResource.java rename to extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/streams/StreamResource.java index 3176a97a817..fd5c2b81a72 100644 --- a/extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/sse/SseResource.java +++ b/extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/streams/StreamResource.java @@ -1,6 +1,9 @@ -package io.quarkus.resteasy.reactive.jackson.deployment.test.sse; +package io.quarkus.resteasy.reactive.jackson.deployment.test.streams; import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; import javax.ws.rs.GET; import javax.ws.rs.Path; @@ -16,8 +19,8 @@ import io.smallrye.common.annotation.Blocking; import io.smallrye.mutiny.Multi; -@Path("sse") -public class SseResource { +@Path("streams") +public class StreamResource { @GET @Produces(MediaType.SERVER_SENT_EVENTS) @@ -120,4 +123,21 @@ public Multi<Message> multiStreamJson() { return Multi.createFrom().items(new Message("hello"), new Message("stef")); } + /** + * Reproduce <a href="https://github.com/quarkusio/quarkus/issues/30044">#30044</a>. + */ + @Path("stream-json/multi/fast") + @GET + @Produces(RestMediaType.APPLICATION_STREAM_JSON) + @RestStreamElementType(MediaType.APPLICATION_JSON) + public Multi<Message> multiStreamJsonFast() { + List<UUID> ids = new ArrayList<>(5000); + for (int i = 0; i < 5000; i++) { + ids.add(UUID.randomUUID()); + } + return Multi.createFrom().items(ids::stream) + .onItem().transform(id -> new Message(id.toString())) + .onOverflow().buffer(81920); + } + } diff --git a/extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/sse/SseTestCase.java b/extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/streams/StreamTestCase.java similarity index 78% rename from extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/sse/SseTestCase.java rename to extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/streams/StreamTestCase.java index afb909111ba..bc82769dd1d 100644 --- a/extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/sse/SseTestCase.java +++ b/extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/streams/StreamTestCase.java @@ -1,4 +1,4 @@ -package io.quarkus.resteasy.reactive.jackson.deployment.test.sse; +package io.quarkus.resteasy.reactive.jackson.deployment.test.streams; import static io.restassured.RestAssured.when; import static org.assertj.core.api.Assertions.assertThat; @@ -33,7 +33,7 @@ import io.quarkus.test.common.http.TestHTTPResource; import io.smallrye.mutiny.Multi; -public class SseTestCase { +public class StreamTestCase { @TestHTTPResource URI uri; @@ -41,16 +41,16 @@ public class SseTestCase { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class) - .addClasses(SseResource.class, Message.class)); + .addClasses(StreamResource.class, Message.class)); @Test public void testSseFromSse() throws Exception { - testSse("sse"); + testSse("streams"); } @Test public void testSseFromMulti() throws Exception { - testSse("sse/multi"); + testSse("streams/multi"); } private void testSse(String path) throws Exception { @@ -81,12 +81,12 @@ public void accept(Throwable throwable) { @Test public void testMultiFromSse() { - testMulti("sse"); + testMulti("streams"); } @Test public void testMultiFromMulti() { - testMulti("sse/multi"); + testMulti("streams/multi"); } private void testMulti(String path) { @@ -99,24 +99,24 @@ private void testMulti(String path) { @Test public void testJsonMultiFromSse() { - testJsonMulti("sse/json"); - testJsonMulti("sse/json2"); - testJsonMulti("sse/blocking/json"); + testJsonMulti("streams/json"); + testJsonMulti("streams/json2"); + testJsonMulti("streams/blocking/json"); } @Test public void testJsonMultiFromMulti() { - testJsonMulti("sse/json/multi"); + testJsonMulti("streams/json/multi"); } @Test public void testJsonMultiFromMultiWithDefaultElementType() { - testJsonMulti("sse/json/multi2"); + testJsonMulti("streams/json/multi2"); } @Test public void testNdJsonMultiFromMulti() { - when().get(uri.toString() + "sse/ndjson/multi") + when().get(uri.toString() + "streams/ndjson/multi") .then().statusCode(HttpStatus.SC_OK) // @formatter:off .body(is("{\\"name\\":\\"hello\\"}\\n" @@ -127,7 +127,7 @@ public void testNdJsonMultiFromMulti() { @Test public void testStreamJsonMultiFromMulti() { - when().get(uri.toString() + "sse/stream-json/multi") + when().get(uri.toString() + "streams/stream-json/multi") .then().statusCode(HttpStatus.SC_OK) // @formatter:off .body(is("{\\"name\\":\\"hello\\"}\\n" @@ -143,4 +143,19 @@ private void testJsonMulti(String path) { List<Message> list = multi.collect().asList().await().atMost(Duration.ofSeconds(30)); assertThat(list).extracting("name").containsExactly("hello", "stef"); } + + /** + * Reproduce <a href="https://github.com/quarkusio/quarkus/issues/30044">#30044</a>. + */ + @Test + public void testStreamJsonMultiFromMultiFast() { + String payload = when().get(uri.toString() + "streams/stream-json/multi/fast") + .then().statusCode(HttpStatus.SC_OK) + .header(HttpHeaders.CONTENT_TYPE, containsString(RestMediaType.APPLICATION_STREAM_JSON)) + .extract().response().asString(); + + // the payload include 5000 json objects + assertThat(payload.lines()).hasSize(5000) + .allSatisfy(s -> assertThat(s).matches("\\\\{\\"name\\":\\".*\\"}")); + } } diff --git a/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/MultiInvoker.java b/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/MultiInvoker.java index c6edb7584aa..aa4129bbd27 100644 --- a/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/MultiInvoker.java +++ b/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/MultiInvoker.java @@ -1,6 +1,7 @@ package org.jboss.resteasy.reactive.client.impl; import java.io.ByteArrayInputStream; +import java.io.IOException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; @@ -18,6 +19,7 @@ import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpClientResponse; import io.vertx.core.net.impl.ConnectionBase; +import io.vertx.core.parsetools.RecordParser; public class MultiInvoker extends AbstractRxInvoker<Multi<?>> { @@ -121,10 +123,13 @@ public <R> Multi<R> method(String name, Entity<?> entity, GenericType<R> respons } else { HttpClientResponse vertxResponse = restClientRequestContext.getVertxClientResponse(); if (!emitter.isCancelled()) { - // FIXME: this is probably not good enough if (response.getStatus() == 200 && MediaType.SERVER_SENT_EVENTS_TYPE.isCompatible(response.getMediaType())) { registerForSse(multiRequest, responseType, response, vertxResponse); + } else if (response.getStatus() == 200 + && RestMediaType.APPLICATION_STREAM_JSON_TYPE.isCompatible(response.getMediaType())) { + registerForJsonStream(multiRequest, restClientRequestContext, responseType, response, + vertxResponse); } else { // read stuff in chunks registerForChunks(multiRequest, restClientRequestContext, responseType, response, vertxResponse); @@ -267,4 +272,46 @@ private boolean startsWith(byte[] array, byte[] prefix) { }); } + private <R> void registerForJsonStream(MultiRequest<? super R> multiRequest, + RestClientRequestContext restClientRequestContext, + GenericType<R> responseType, + ResponseImpl response, + HttpClientResponse vertxClientResponse) { + RecordParser parser = RecordParser.newDelimited("\\n"); + parser.handler(new Handler<Buffer>() { + @Override + public void handle(Buffer chunk) { + + ByteArrayInputStream in = new ByteArrayInputStream(chunk.getBytes()); + try { + R item = restClientRequestContext.readEntity(in, responseType, response.getMediaType(), + response.getMetadata()); + multiRequest.emitter.emit(item); + } catch (IOException e) { + multiRequest.emitter.fail(e); + } + } + }); + vertxClientResponse.exceptionHandler(t -> { + if (t == ConnectionBase.CLOSED_EXCEPTION) { + // we can ignore this one since we registered a closeHandler + } else { + multiRequest.emitter.fail(t); + } + }); + vertxClientResponse.endHandler(new Handler<Void>() { + @Override + public void handle(Void c) { + multiRequest.complete(); + } + }); + + vertxClientResponse.handler(parser); + + // watch for user cancelling + multiRequest.onCancel(() -> { + vertxClientResponse.request().connection().close(); + }); + } + }
['extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/sse/Message.java', 'extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/sse/SseTestCase.java', 'extensions/resteasy-reactive/quarkus-resteasy-reactive-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/sse/SseResource.java', 'independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/MultiInvoker.java']
{'.java': 4}
4
4
0
0
4
24,228,613
4,770,578
618,073
5,662
2,123
349
49
1
2,640
378
637
62
1
1
1970-01-01T00:27:53
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,291
quarkusio/quarkus/30214/30046
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/30046
https://github.com/quarkusio/quarkus/pull/30214
https://github.com/quarkusio/quarkus/pull/30214
1
closes
MultiPartConfig in HTTP Vert.x extension is insufficiently documented
### Describe the bug Hello, I have one opinion (you can ignore that one) and one concern (IMO bug) regarding https://github.com/quarkusio/quarkus/pull/29729 documentation. **Opinion**: Please document this feature in more detail and ideally provide an example in docs. Documentation does not provide single example on `MultiPartConfig` and `fileContentTypes`. I understand you (and me) know what `MultiPartConfig#fileContentType` should be used for because we read this PR, but users didn't not, they only see this configuration property with text `A list of {@code ContentType} to indicate whether a given multipart field should be handled as a file part.` With context of #29729 that sentence is completely clear, but you can only find this in configuration properties list. **Concern** This PR added `MultiPartConfig` to Vert.x HTTP extension. `MultiPartConfig` only used by RESTEasy Reactive and ignored by every other extension (RESTEasy Classic, Reactive Routes, ...) while that fact is literally nowhere mentioned. How is it possible to have the configuration in Vert.X HTTP extension and do not mention it only works for RESTEasy Reactive? How should user know that? ### Expected behavior one of: - I expect `MultiPartConfig#fileContentType` configuration property works for RESTEasy Classic, Reactive Routes etc. - Document that it only works for RESTEasy Reactive ### Actual behavior - only works for RESTEasy Reactive - docs don't tell me that the property only works for single extension ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
e47a267e13819cf5ebd4322ad2b2c88b06209a34
30c51ab5ace3f1182b154886e00e508533b0950c
https://github.com/quarkusio/quarkus/compare/e47a267e13819cf5ebd4322ad2b2c88b06209a34...30c51ab5ace3f1182b154886e00e508533b0950c
diff --git a/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/MultiPartConfig.java b/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/MultiPartConfig.java index a0e262b28d6..43cfe26f7ed 100644 --- a/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/MultiPartConfig.java +++ b/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/MultiPartConfig.java @@ -15,7 +15,12 @@ public class MultiPartConfig { /** - * A list of {@code ContentType} to indicate whether a given multipart field should be handled as a file part. + * A comma-separated list of {@code ContentType} to indicate whether a given multipart field should be handled as a file + * part. + * + * You can use this setting to force HTTP-based extensions to parse a message part as a file based on its content type. + * + * For now, this setting only works when using RESTEasy Reactive. */ @ConfigItem @ConvertWith(TrimmedStringConverter.class)
['extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/MultiPartConfig.java']
{'.java': 1}
1
1
0
0
1
24,196,319
4,764,349
617,209
5,655
467
98
7
1
1,930
280
417
50
1
0
1970-01-01T00:27:52
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,292
quarkusio/quarkus/30157/30061
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/30061
https://github.com/quarkusio/quarkus/pull/30157
https://github.com/quarkusio/quarkus/pull/30157
1
fix
Adding Kotlin Tests Breaks Kotlin/Java project
### Describe the bug I posted a more in-depth description of the issue here last night: <https://github.com/quarkusio/quarkus/discussions/30049> The summary is: Adding a Kotlin test file breaks `quarkus dev`. Some of my resources mysteriously disappear and aren't available at runtime. ### Expected behavior I should be able to mix Java and Kotlin code in the same project and have everything work. One of the great advantages of Kotlin is that it's usually easy to gradually introduce it to a project without rewriting everything. (read: I'll have a *much* easier time getting my team to adopt this if Java and Kotlin play well together. 😄) ### Actual behavior Adding a(n empty!) Kotlin test file causes some of my resources to be (silently!) unavailable while running `quarkus dev`. ### How to Reproduce? ``` > quarkus version 2.15.1.Final > quarkus create app org.acme:rest-example --extension='resteasy-reactive-jackson' --gradle-kotlin-dsl > cd rest-example > quarkus dev # At this point, the example code works. # can access http://localhost:8080/hello # Save state: > git init . > git add . > git commit -m "initial code" > quarkus extension add kotlin ``` You'll also need to add Kotlin config to your build.gradle.kts as documented in: <https://quarkus.io/guides/kotlin#important-gradle-configuration-points> Now add a new REST endpoint in Kotlin so we can show how Java/Kotlin code *should* work together. ```kotlin // file: src/main/kotlin/org/acme/KotlinGreeting.kt package org.acme import javax.ws.rs.GET import javax.ws.rs.Path import javax.ws.rs.Produces import javax.ws.rs.core.MediaType @Path("/hello2") class KotlinGreeting( private var javaResource: GreetingResource ) { @GET @Produces(MediaType.TEXT_PLAIN) fun hello(): String { return "${javaResource.hello()} -- now in Kotlin!" } } ``` Verify this works by running `quarkus dev` and visiting `http://localhost:8080/hello2`. ``` > git add . > git commit -m "checkpoint: Java + Kotlin working" ``` Now add a new "test" file. (No actual test necessary) ```kotlin // file: test/kotlin/org/acme/KotlinGreetingTest.kt package org.acme // This file left intentionally blank. ``` Once again run `quarkus dev`. While the server starts up without error, neither `/hello` nor `/hello2` resources are loaded. And there are no errors to let you know something has gone wrong. ``` > git add . > git commit -m "checkpoint: broken" ``` I'll attach the zip file (including git history) here. [rest-example.zip](https://github.com/quarkusio/quarkus/files/10296136/rest-example.zip) ### Output of `uname -a` or `ver` Windows. :p But I also originally bumped into this on macOS. ### Output of `java -version` openjdk version "16.0.2" 2021-07-20 ### GraalVM version (if different from Java) n/a ### Quarkus version or git rev 2.15.1.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Gradle 7.5.1 ### Additional information _No response_
4dd3936da69d2d4bfa7826015445c29d60bf9a34
dad033640ceaf0a7c6ef80935d1e7e4a4782f356
https://github.com/quarkusio/quarkus/compare/4dd3936da69d2d4bfa7826015445c29d60bf9a34...dad033640ceaf0a7c6ef80935d1e7e4a4782f356
diff --git a/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusDev.java b/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusDev.java index e248cfc79fe..9a3ebcf051b 100644 --- a/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusDev.java +++ b/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusDev.java @@ -571,7 +571,7 @@ private void addLocalProject(ResolvedDependency project, GradleDevModeLauncher.B } } Path classesDir = classesDirs.isEmpty() ? null - : QuarkusGradleUtils.mergeClassesDirs(classesDirs, project.getWorkspaceModule().getBuildDir(), root, root); + : QuarkusGradleUtils.mergeClassesDirs(classesDirs, project.getWorkspaceModule().getBuildDir(), root, false); final Set<Path> resourcesSrcDirs = new LinkedHashSet<>(); // resourcesSrcDir may exist but if it's empty the resources output dir won't be created
['devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusDev.java']
{'.java': 1}
1
1
0
0
1
24,161,256
4,757,442
616,331
5,648
250
54
2
1
3,084
414
793
126
5
5
1970-01-01T00:27:52
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,293
quarkusio/quarkus/30141/20034
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/20034
https://github.com/quarkusio/quarkus/pull/30141
https://github.com/quarkusio/quarkus/pull/30141
1
fixes
@TestTransaction in combination with Junit5 @Nested does not roll back
### Describe the bug In a `@QuarkusTest` placing `@TestTransaction` on methods inside a Junit5 `@Nested` class does not roll back the transaction - the test data stays in the database. Moving the test method out of the `@Nested class` makes it work. ### Expected behavior _No response_ ### Actual behavior _No response_ ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.0.2.Final and latest ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
019b8299ae534b915f4bad9de627e9d51b46cd0a
57112e0e7e872d9023da807ed21f5a972dff869f
https://github.com/quarkusio/quarkus/compare/019b8299ae534b915f4bad9de627e9d51b46cd0a...57112e0e7e872d9023da807ed21f5a972dff869f
diff --git a/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/WrongAnnotationUsageProcessor.java b/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/WrongAnnotationUsageProcessor.java index d7597589eb6..e10d994a4e8 100644 --- a/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/WrongAnnotationUsageProcessor.java +++ b/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/WrongAnnotationUsageProcessor.java @@ -17,6 +17,7 @@ import org.jboss.jandex.IndexView; import io.quarkus.arc.deployment.ValidationPhaseBuildItem.ValidationErrorBuildItem; +import io.quarkus.arc.processor.Annotations; import io.quarkus.arc.processor.DotNames; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; @@ -26,7 +27,8 @@ public class WrongAnnotationUsageProcessor { @BuildStep void detect(ArcConfig config, ApplicationIndexBuildItem applicationIndex, CustomScopeAnnotationsBuildItem scopeAnnotations, - TransformedAnnotationsBuildItem transformedAnnotations, BuildProducer<ValidationErrorBuildItem> validationErrors) { + TransformedAnnotationsBuildItem transformedAnnotations, BuildProducer<ValidationErrorBuildItem> validationErrors, + InterceptorResolverBuildItem interceptorResolverBuildItem) { if (!config.detectWrongAnnotations) { return; @@ -90,6 +92,14 @@ public String apply(AnnotationInstance annotationInstance) { new IllegalStateException(String.format( "The %s class %s declares a producer but it must be ignored per the CDI rules", clazz.nestingType().toString(), clazz.name().toString())))); + } else if (Annotations.containsAny(classAnnotations, interceptorResolverBuildItem.getInterceptorBindings()) + || Annotations.containsAny(clazz.annotations(), + interceptorResolverBuildItem.getInterceptorBindings())) { + // detect interceptor bindings on nested classes + validationErrors.produce(new ValidationErrorBuildItem( + new IllegalStateException(String.format( + "The %s class %s declares an interceptor binding but it must be ignored per CDI rules", + clazz.nestingType().toString(), clazz.name().toString())))); } } }
['extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/WrongAnnotationUsageProcessor.java']
{'.java': 1}
1
1
0
0
1
24,149,806
4,755,047
616,009
5,647
1,103
158
12
1
705
110
177
39
0
0
1970-01-01T00:27:52
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,296
quarkusio/quarkus/29984/29976
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/29976
https://github.com/quarkusio/quarkus/pull/29984
https://github.com/quarkusio/quarkus/pull/29984
1
fixes
Custom ObjectMapper in application affects Kafka UI Dev service
### Describe the bug I have custom ObjectMapperCustomizer that I needed to convert all json payloads to use snake_case. ``` @Singleton public class ObjectMapperCustomizer implements io.quarkus.jackson.ObjectMapperCustomizer { public void customize(ObjectMapper mapper) { mapper.setSerializationInclusion(NON_NULL); mapper.setPropertyNamingStrategy(SNAKE_CASE); } } ``` This apparently affects the Kafka UI running as one of the dev services. How do I isolate kafka dev services from this? ### Expected behavior The Kafka UI dev service should function as expected ### Actual behavior Application's custom JsonMappers affects Kafka UI's payload and as a result renders the UI unusable ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
05a7c8b0b87f70e26363b8e136d0b4b3feff5621
0b76f7213266cb0849fb2bac97004ab35cadc771
https://github.com/quarkusio/quarkus/compare/05a7c8b0b87f70e26363b8e136d0b4b3feff5621...0b76f7213266cb0849fb2bac97004ab35cadc771
diff --git a/extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/ui/KafkaUiUtils.java b/extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/ui/KafkaUiUtils.java index 862fdcfeb2d..bc9b3ba525d 100644 --- a/extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/ui/KafkaUiUtils.java +++ b/extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/ui/KafkaUiUtils.java @@ -2,7 +2,12 @@ import static io.quarkus.kafka.client.runtime.ui.util.ConsumerFactory.createConsumer; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; @@ -17,7 +22,10 @@ import org.apache.kafka.common.TopicPartition; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.json.JsonMapper; import io.quarkus.kafka.client.runtime.KafkaAdminClient; import io.quarkus.kafka.client.runtime.ui.model.Order; @@ -37,12 +45,15 @@ public class KafkaUiUtils { private final Map<String, Object> config; - public KafkaUiUtils(KafkaAdminClient kafkaAdminClient, KafkaTopicClient kafkaTopicClient, ObjectMapper objectMapper, + public KafkaUiUtils(KafkaAdminClient kafkaAdminClient, KafkaTopicClient kafkaTopicClient, @Identifier("default-kafka-broker") Map<String, Object> config) { this.kafkaAdminClient = kafkaAdminClient; this.kafkaTopicClient = kafkaTopicClient; - this.objectMapper = objectMapper; this.config = config; + this.objectMapper = JsonMapper.builder() + .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS) + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .build(); } public KafkaInfo getKafkaInfo() throws ExecutionException, InterruptedException {
['extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/ui/KafkaUiUtils.java']
{'.java': 1}
1
1
0
0
1
24,088,221
4,742,698
614,647
5,635
839
147
17
1
1,100
146
234
52
0
1
1970-01-01T00:27:51
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,297
quarkusio/quarkus/29981/29956
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/29956
https://github.com/quarkusio/quarkus/pull/29981
https://github.com/quarkusio/quarkus/pull/29981
1
fixes
Hibernate reactive disregarding quarkus.hibernate-orm.jdbc.timezone
### Describe the bug I have the last couple of days been trying to understand why my code does not consider `TIMESTAMP WITH TIME ZONE` in my main postgresSQL application that uses hibernate reactive so I created two smaller applications to test just test how hibernate-orm and hibernate-reactive work in quarkus with time zones. First of I tried hibernate reactive and stumbled across the issue listed in #10768 on my own whilst running my `@QuarkusIntegrationTest` and `@QuarkusTest` and then changed my approach to use the normal “jdbc driver” to get flyway working to have it more like main PostgreSQL project. After the jdbc change I once of my test suits with `quarkus.hibernate-orm.jdbc.timezone` set to `UTC` with no effect whilst always running with `user.timezone=Etc/GMT-1` to simulate a consistent time zone, but neither of these settings helped ☹. So after that I created a `user.timezone=UTC` test which works since now both my postgres container and quarkus application now run in UTC. So then does it work in the normal quarkus hibernate-orm implementation? Well yeah everything works fine there when having `quarkus.hibernate-orm.jdbc.timezone` set to `UTC`. P.S. One thing I forgot to comment about in my findings is the code that converts a `TIMESTAMP WITH TIME ZONE` from a database field (that is stored in postgres as UTC) to UTC again without taking into regard the time zone part of the original value in the database before converting it to the java object with the user.timezone so… the conversion loses one hour in my GmtIT.java tests… 👏🎉🧨😂. But this is releated to the other issue that has already been created. P.S.S. Create a branch in the hibernate reactive application with no flyway. ### Expected behavior quarkus.hibernate-orm.jdbc.timezone works according to specificaiton and can take into account database timezone when converting ### Actual behavior Does nothing application boot timezone is used for all convertion of date and time ### How to Reproduce? Github repos with my test code: - [hibernate-reactive repo](https://github.com/agreedSkiing/test-hibernate-reactive-timezone-postgres) - [hibernate-orm repo]( https://github.com/agreedSkiing/test-hibernate-timezone-postgres) ### Output of `uname -a` or `ver` Linux DI-001000104447 4.19.128-microsoft-standard #1 SMP Tue Jun 23 12:58:10 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux ### Output of `java -version` java version "17.0.5" 2022-10-18 LTS Java(TM) SE Runtime Environment (build 17.0.5+9-LTS-191) Java HotSpot(TM) 64-Bit Server VM (build 17.0.5+9-LTS-191, mixed mode, sharing) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.15.0.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.6 (84538c9988a25aec085021c365c560670ad80f63) ### Additional information _No response_
1079861faf9ef0adc4ab239fe5b9d35566313e8f
aab1831220bc82daab9447948b23fa9a5f77f0ba
https://github.com/quarkusio/quarkus/compare/1079861faf9ef0adc4ab239fe5b9d35566313e8f...aab1831220bc82daab9447948b23fa9a5f77f0ba
diff --git a/extensions/hibernate-reactive/deployment/src/main/java/io/quarkus/hibernate/reactive/deployment/HibernateReactiveProcessor.java b/extensions/hibernate-reactive/deployment/src/main/java/io/quarkus/hibernate/reactive/deployment/HibernateReactiveProcessor.java index c5f5207fa3b..0fdcd1e39ab 100644 --- a/extensions/hibernate-reactive/deployment/src/main/java/io/quarkus/hibernate/reactive/deployment/HibernateReactiveProcessor.java +++ b/extensions/hibernate-reactive/deployment/src/main/java/io/quarkus/hibernate/reactive/deployment/HibernateReactiveProcessor.java @@ -310,6 +310,13 @@ private static ParsedPersistenceXmlDescriptor generateReactivePersistenceUnit( String.valueOf(persistenceUnitConfig.query.inClauseParameterPadding)); // JDBC + persistenceUnitConfig.jdbc.timezone.ifPresent( + timezone -> desc.getProperties().setProperty(AvailableSettings.JDBC_TIME_ZONE, timezone)); + + persistenceUnitConfig.jdbc.statementFetchSize.ifPresent( + fetchSize -> desc.getProperties().setProperty(AvailableSettings.STATEMENT_FETCH_SIZE, + String.valueOf(fetchSize))); + persistenceUnitConfig.jdbc.statementBatchSize.ifPresent( statementBatchSize -> desc.getProperties().setProperty(AvailableSettings.STATEMENT_BATCH_SIZE, String.valueOf(statementBatchSize)));
['extensions/hibernate-reactive/deployment/src/main/java/io/quarkus/hibernate/reactive/deployment/HibernateReactiveProcessor.java']
{'.java': 1}
1
1
0
0
1
24,088,362
4,742,730
614,649
5,635
390
64
7
1
2,920
413
740
49
2
0
1970-01-01T00:27:51
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,342
quarkusio/quarkus/28384/28377
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/28377
https://github.com/quarkusio/quarkus/pull/28384
https://github.com/quarkusio/quarkus/pull/28384
1
fixes
Log on startup with "Default CORS properties will be used, please use 'quarkus.http.cors' properties instead" without more information
### Describe the bug If I start a Quarkus application in production mode, with the smallrye-openapi extension enabled, I get this message on startup: ``` 2022-10-04 13:50:54,394 INFO [io.qua.sma.ope.run.OpenApiRecorder] (main) Default CORS properties will be used, please use 'quarkus.http.cors' properties instead ``` I find this confusing, as the message is not telling me what I did wrong (maybe forgot to set some properties, which ones?) nor exactly what is needed to solve it (which properties should I set, simply `quarkus.http.cors=true`? something more complex?). For the record, my `application.properties` is completely empty. ### Expected behavior Maybe the message should expand a bit on what's wrong and what should be done to solve the problem? If there *is* no problem (as the "INFO" level seems to suggest), maybe it should be rephrased from "please use [...]" to "if you want X, do Y"? ### Actual behavior ``` 2022-10-04 13:50:54,394 INFO [io.qua.sma.ope.run.OpenApiRecorder] (main) Default CORS properties will be used, please use 'quarkus.http.cors' properties instead ``` ### How to Reproduce? ``` quarkus create --extension resteasy,hibernate-orm-panache,jdbc-postgresql,smallrye-openapi cd code-with-quarkus ./mvnw clean package java -jar ./target/quarkus-app/quarkus-run.jar ``` ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information The log was apparently introduced in this commit by @sberyozkin: https://github.com/quarkusio/quarkus/commit/597440d6edbeee8850de0d6f34477dd606724287
404d64fb793b665225978746070e1f02abea9f9b
c78f626346f2d89395d8e29bcd904e8ed4ab1fb1
https://github.com/quarkusio/quarkus/compare/404d64fb793b665225978746070e1f02abea9f9b...c78f626346f2d89395d8e29bcd904e8ed4ab1fb1
diff --git a/extensions/smallrye-openapi/runtime/src/main/java/io/quarkus/smallrye/openapi/runtime/OpenApiRecorder.java b/extensions/smallrye-openapi/runtime/src/main/java/io/quarkus/smallrye/openapi/runtime/OpenApiRecorder.java index 53bac5ddfcf..50efcc3f86e 100644 --- a/extensions/smallrye-openapi/runtime/src/main/java/io/quarkus/smallrye/openapi/runtime/OpenApiRecorder.java +++ b/extensions/smallrye-openapi/runtime/src/main/java/io/quarkus/smallrye/openapi/runtime/OpenApiRecorder.java @@ -45,7 +45,10 @@ public void accept(Route route) { public Handler<RoutingContext> handler(OpenApiRuntimeConfig runtimeConfig) { if (runtimeConfig.enable) { if (!configuration.getValue().corsEnabled && LaunchMode.NORMAL == LaunchMode.current()) { - log.info("Default CORS properties will be used, please use 'quarkus.http.cors' properties instead"); + log.info( + "CORS filtering is disabled and cross-origin resource sharing is allowed without restriction, which is not recommended in production." + + " Please configure the CORS filter through 'quarkus.http.cors.*' properties." + + " For more information, see Quarkus HTTP CORS documentation"); } return new OpenApiHandler(configuration.getValue().corsEnabled); } else {
['extensions/smallrye-openapi/runtime/src/main/java/io/quarkus/smallrye/openapi/runtime/OpenApiRecorder.java']
{'.java': 1}
1
1
0
0
1
23,075,181
4,534,293
589,698
5,464
515
87
5
1
1,837
240
488
54
1
3
1970-01-01T00:27:44
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,341
quarkusio/quarkus/28412/28335
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/28335
https://github.com/quarkusio/quarkus/pull/28412
https://github.com/quarkusio/quarkus/pull/28412
1
fixes
Native awt build fails on Windows also when running with native-build-container
### Describe the bug Running the native build with `-Dquarkus.native.container-build=true` also fails on windows even though the native-build would be executed inside a linux docker container. ### Expected behavior The build should work inside a linux docker container ### Actual behavior Following error is thrown: ``` * What went wrong: Execution failed for task ':devtools:machine-learning:labeling-server:quarkusBuild'. > io.quarkus.builder.BuildException: Build failure: Build failed due to errors [error]: Build step io.quarkus.deployment.pkg.steps.NativeImageBuildStep#build threw an exception: java.lang.RuntimeException: Failed to build native image at io.quarkus.deployment.pkg.steps.NativeImageBuildStep.build(NativeImageBuildStep.java:281) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at io.quarkus.deployment.ExtensionLoader$3.execute(ExtensionLoader.java:909) at io.quarkus.builder.BuildContext.run(BuildContext.java:281) at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478) at java.base/java.lang.Thread.run(Thread.java:833) at org.jboss.threads.JBossThread.run(JBossThread.java:501) Caused by: java.lang.UnsupportedOperationException: Windows AWT integration is not ready in native-image and would result in java.lang.UnsatisfiedLinkError: no awt in java.library.path. at io.quarkus.deployment.pkg.steps.NativeImageBuildStep$NativeImageInvokerInfo$Builder.build(NativeImageBuildStep.java:883) at io.quarkus.deployment.pkg.steps.NativeImageBuildStep.build(NativeImageBuildStep.java:249) ... 11 more ``` ### How to Reproduce? * add `io.quarkus:quarkus-awt` * run ```sh gradlew quarkusBuild -Dquarkus.native.container-build=true -Dquarkus.package.type=native -Dquarkus.container-image.build=true ``` ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` 17 ### GraalVM version (if different from Java) 17 ### Quarkus version or git rev 2.13.0.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) gradlew 7.5.1 ### Additional information _No response_
7d551fda0b38db8c33f953957567d0b40d43a4ff
00392e75baaa66f0bc5ed9c36e7e25d3d7f66407
https://github.com/quarkusio/quarkus/compare/7d551fda0b38db8c33f953957567d0b40d43a4ff...00392e75baaa66f0bc5ed9c36e7e25d3d7f66407
diff --git a/core/deployment/src/main/java/io/quarkus/deployment/builditem/nativeimage/UnsupportedOSBuildItem.java b/core/deployment/src/main/java/io/quarkus/deployment/builditem/nativeimage/UnsupportedOSBuildItem.java index 04ba9d9ab52..159e406ecef 100644 --- a/core/deployment/src/main/java/io/quarkus/deployment/builditem/nativeimage/UnsupportedOSBuildItem.java +++ b/core/deployment/src/main/java/io/quarkus/deployment/builditem/nativeimage/UnsupportedOSBuildItem.java @@ -5,6 +5,7 @@ import static io.quarkus.dev.console.QuarkusConsole.IS_WINDOWS; import io.quarkus.builder.item.MultiBuildItem; +import io.quarkus.deployment.pkg.NativeConfig; /** * Native-image might not be supported for a particular @@ -30,4 +31,15 @@ public UnsupportedOSBuildItem(Os os, String error) { this.os = os; this.error = error; } + + public boolean triggerError(NativeConfig nativeConfig) { + return + // When the host OS is unsupported, it could have helped to + // run in a Linux builder image (e.g. an extension unsupported on Windows). + (os.active && !nativeConfig.isContainerBuild()) || + // If Linux is the OS the extension does not support, + // it fails in a container build regardless the host OS, + // because we have only Linux based builder images. + (nativeConfig.isContainerBuild() && os == Os.LINUX); + } } diff --git a/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildStep.java b/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildStep.java index be61fb022f7..dbedfb8aee9 100644 --- a/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildStep.java +++ b/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildStep.java @@ -891,7 +891,9 @@ public NativeImageInvokerInfo build() { } if (unsupportedOSes != null && !unsupportedOSes.isEmpty()) { - final String errs = unsupportedOSes.stream().filter(o -> o.os.active).map(o -> o.error) + final String errs = unsupportedOSes.stream() + .filter(o -> o.triggerError(nativeConfig)) + .map(o -> o.error) .collect(Collectors.joining(", ")); if (!errs.isEmpty()) { throw new UnsupportedOperationException(errs);
['core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildStep.java', 'core/deployment/src/main/java/io/quarkus/deployment/builditem/nativeimage/UnsupportedOSBuildItem.java']
{'.java': 2}
2
2
0
0
2
23,100,724
4,539,010
590,305
5,464
902
180
16
2
2,608
194
639
66
0
2
1970-01-01T00:27:45
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,340
quarkusio/quarkus/28419/28375
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/28375
https://github.com/quarkusio/quarkus/pull/28419
https://github.com/quarkusio/quarkus/pull/28419
1
fix
Quarkus fails when using jgitver
### Describe the bug Hi, It seems that Quarkus doesn't work properly when the maven project is using the [jgitver-maven-plugin](https://github.com/jgitver/jgitver-maven-plugin) - a maven plugin to automatically define the maven project version based on git branches as tags. Thanks. ### Expected behavior The `./mvnw quarkus:dev` should start Quarkus in development mode, instead of failing. ### Actual behavior Running `./mvnw quarkus:dev` fails with the following error: ``` Listening for transport dt_socket at address: 5005 Exception in thread "main" java.lang.NullPointerException: Cannot invoke "io.quarkus.deployment.dev.DevModeContext$ModuleInfo.getMain()" because the return value of "io.quarkus.deployment.dev.DevModeContext.getApplicationRoot()" is null at io.quarkus.deployment.dev.DevModeMain.start(DevModeMain.java:90) at io.quarkus.deploy [debug.txt](https://github.com/quarkusio/quarkus/files/9704780/debug.txt) ment.dev.DevModeMain.main(DevModeMain.java:62) ``` Output from running `./mvnw quarkus:dev -X`: [debug.txt](https://github.com/quarkusio/quarkus/files/9704782/debug.txt) ### How to Reproduce? 1. Create a Quarkus project with `quarkus create`. 2. Add the jgitver maven extension, by adding a file `.mvn/extensions.xml` to the project with the following content: ``` <extensions xmlns="http://maven.apache.org/EXTENSIONS/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/EXTENSIONS/1.0.0 http://maven.apache.org/xsd/core-extensions-1.0.0.xsd"> <extension> <groupId>fr.brouillard.oss</groupId> <artifactId>jgitver-maven-plugin</artifactId> <version>1.9.0</version> </extension> </extensions> ``` 3. Optional: Initialize the git repo and do a commit, just so that jgitver computes the version as `0.0.0-SNAPSHOT` instead of `0.0.0-NOT_A_GIT_REPOSITORY`: ``` git init git add . git commit -m "test" ``` 4. Run `./mvnw quarkus:dev`. ### Output of `uname -a` or `ver` Linux laptop-2220 5.15.0-48-generic #54~20.04.1-Ubuntu SMP Thu Sep 1 16:17:26 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux ### Output of `java -version` openjdk version "17.0.4" 2022-07-19 LTS OpenJDK Runtime Environment Corretto-17.0.4.8.1 (build 17.0.4+8-LTS) OpenJDK 64-Bit Server VM Corretto-17.0.4.8.1 (build 17.0.4+8-LTS, mixed mode, sharing) ### GraalVM version (if different from Java) N/A ### Quarkus version or git rev 2.13.0.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.6 (84538c9988a25aec085021c365c560670ad80f63) ### Additional information _No response_
f9dd29f6b14263f598728ad99a71d9a9b43187bd
a426f6a372fdfceaaee7d2e3c1342805aa6818df
https://github.com/quarkusio/quarkus/compare/f9dd29f6b14263f598728ad99a71d9a9b43187bd...a426f6a372fdfceaaee7d2e3c1342805aa6818df
diff --git a/core/deployment/src/main/java/io/quarkus/deployment/dev/QuarkusDevModeLauncher.java b/core/deployment/src/main/java/io/quarkus/deployment/dev/QuarkusDevModeLauncher.java index 7108a534536..b219f7e4e67 100644 --- a/core/deployment/src/main/java/io/quarkus/deployment/dev/QuarkusDevModeLauncher.java +++ b/core/deployment/src/main/java/io/quarkus/deployment/dev/QuarkusDevModeLauncher.java @@ -419,7 +419,6 @@ protected void prepare() throws Exception { devModeContext.setReleaseJavaVersion(releaseJavaVersion); devModeContext.setSourceJavaVersion(sourceJavaVersion); devModeContext.setTargetJvmVersion(targetJavaVersion); - devModeContext.getLocalArtifacts().addAll(localArtifacts); devModeContext.setApplicationRoot(main); devModeContext.getAdditionalModules().addAll(dependencies); diff --git a/devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java b/devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java index f2172937fda..387fcb3a42f 100644 --- a/devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java +++ b/devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java @@ -43,6 +43,7 @@ import org.apache.maven.execution.MavenSession; import org.apache.maven.model.BuildBase; import org.apache.maven.model.Dependency; +import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; import org.apache.maven.model.Profile; @@ -90,6 +91,8 @@ import io.quarkus.bootstrap.model.ApplicationModel; import io.quarkus.bootstrap.model.PathsCollection; import io.quarkus.bootstrap.resolver.BootstrapAppModelResolver; +import io.quarkus.bootstrap.resolver.maven.BootstrapMavenContext; +import io.quarkus.bootstrap.resolver.maven.BootstrapMavenContextConfig; import io.quarkus.bootstrap.resolver.maven.MavenArtifactResolver; import io.quarkus.bootstrap.resolver.maven.options.BootstrapMavenOptions; import io.quarkus.bootstrap.util.BootstrapUtils; @@ -759,7 +762,6 @@ private String getSourceEncoding() { } private void addProject(MavenDevModeLauncher.Builder builder, ResolvedDependency module, boolean root) throws Exception { - if (!module.isJar()) { return; } @@ -1084,30 +1086,37 @@ private QuarkusDevModeLauncher newLauncher() throws Exception { if (appModel != null) { bootstrapProvider.close(); } else { - final MavenArtifactResolver.Builder resolverBuilder = MavenArtifactResolver.builder() + final BootstrapMavenContextConfig<?> mvnConfig = BootstrapMavenContext.config() .setRemoteRepositories(repos) .setRemoteRepositoryManager(remoteRepositoryManager) .setWorkspaceDiscovery(true) .setPreferPomsFromWorkspace(true) .setCurrentProject(project.getFile().toString()); - // if it already exists, it may be a reload triggered by a change in a POM - // in which case we should not be using the original Maven session - boolean reinitializeMavenSession = Files.exists(appModelLocation); - if (reinitializeMavenSession) { + // if a serialized model is found, it may be a reload triggered by a change in a POM + // in which case we should not be using the original Maven session initialized with the previous POM version + if (Files.exists(appModelLocation)) { Files.delete(appModelLocation); // we can't re-use the repo system because we want to use our interpolating model builder // a use-case where it fails with the original repo system is when dev mode is launched with -Dquarkus.platform.version=xxx // overriding the version of the quarkus-bom in the pom.xml } else { - // we can re-use the original Maven session - resolverBuilder.setRepositorySystemSession(repoSession).setRepositorySystem(repoSystem); + // we can re-use the original Maven session and the system + mvnConfig.setRepositorySystemSession(repoSession).setRepositorySystem(repoSystem); + // there could be Maven extensions manipulating the project versions and models + // the ones returned from the Maven API could be different from the original pom.xml files + final Map<Path, Model> projectModels = new HashMap<>(session.getAllProjects().size()); + for (MavenProject mp : session.getAllProjects()) { + projectModels.put(mp.getBasedir().toPath(), mp.getOriginalModel()); + } + mvnConfig.setProjectModelProvider(projectModels::get); } - appModel = new BootstrapAppModelResolver(resolverBuilder.build()) + final BootstrapMavenContext mvnCtx = new BootstrapMavenContext(mvnConfig); + appModel = new BootstrapAppModelResolver(new MavenArtifactResolver(mvnCtx)) .setDevMode(true) .setCollectReloadableDependencies(!noDeps) - .resolveModel(ArtifactCoords.jar(project.getGroupId(), project.getArtifactId(), project.getVersion())); + .resolveModel(mvnCtx.getCurrentProject().getAppArtifact()); } // serialize the app model to avoid re-resolving it in the dev process diff --git a/devtools/maven/src/main/java/io/quarkus/maven/QuarkusBootstrapProvider.java b/devtools/maven/src/main/java/io/quarkus/maven/QuarkusBootstrapProvider.java index 78158655364..f340b2048d4 100644 --- a/devtools/maven/src/main/java/io/quarkus/maven/QuarkusBootstrapProvider.java +++ b/devtools/maven/src/main/java/io/quarkus/maven/QuarkusBootstrapProvider.java @@ -6,6 +6,8 @@ import java.io.Closeable; import java.io.File; import java.io.IOException; +import java.nio.file.Path; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -14,6 +16,7 @@ import java.util.concurrent.ExecutionException; import org.apache.maven.artifact.Artifact; +import org.apache.maven.model.Model; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.component.annotations.Component; @@ -132,16 +135,21 @@ private MavenArtifactResolver artifactResolver(QuarkusBootstrapMojo mojo, Launch throws MojoExecutionException { isWorkspaceDiscovery(mojo); try { - return MavenArtifactResolver.builder() - .setWorkspaceDiscovery( - mode == LaunchMode.DEVELOPMENT || mode == LaunchMode.TEST || isWorkspaceDiscovery(mojo)) + final MavenArtifactResolver.Builder builder = MavenArtifactResolver.builder() .setCurrentProject(mojo.mavenProject().getFile().toString()) .setPreferPomsFromWorkspace(mode == LaunchMode.DEVELOPMENT || mode == LaunchMode.TEST) .setRepositorySystem(repoSystem) .setRepositorySystemSession(mojo.repositorySystemSession()) .setRemoteRepositories(mojo.remoteRepositories()) - .setRemoteRepositoryManager(remoteRepoManager) - .build(); + .setRemoteRepositoryManager(remoteRepoManager); + if (mode == LaunchMode.DEVELOPMENT || mode == LaunchMode.TEST || isWorkspaceDiscovery(mojo)) { + final Map<Path, Model> projectModels = new HashMap<>(mojo.mavenSession().getAllProjects().size()); + for (MavenProject mp : mojo.mavenSession().getAllProjects()) { + projectModels.put(mp.getBasedir().toPath(), mp.getOriginalModel()); + } + builder.setWorkspaceDiscovery(true).setProjectModelProvider(projectModels::get); + } + return builder.build(); } catch (BootstrapMavenException e) { throw new MojoExecutionException("Failed to initialize Quarkus bootstrap Maven artifact resolver", e); } diff --git a/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/BootstrapMavenContext.java b/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/BootstrapMavenContext.java index b456a5c4b3c..22114d0a2b0 100644 --- a/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/BootstrapMavenContext.java +++ b/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/BootstrapMavenContext.java @@ -12,6 +12,7 @@ import java.util.List; import java.util.Map; import java.util.Properties; +import java.util.function.Function; import java.util.function.Supplier; import org.apache.commons.lang3.StringUtils; @@ -169,7 +170,7 @@ public BootstrapMavenContext(BootstrapMavenContextConfig<?> config) this.currentPom = currentProject.getRawModel().getPomFile().toPath(); this.workspace = config.currentProject.getWorkspace(); } else if (config.workspaceDiscovery) { - currentProject = resolveCurrentProject(); + currentProject = resolveCurrentProject(config.modelProvider); this.workspace = currentProject == null ? null : currentProject.getWorkspace(); if (workspace != null) { if (config.repoSession == null && repoSession != null && repoSession.getWorkspaceReader() == null) { @@ -315,9 +316,9 @@ public String getLocalRepo() throws BootstrapMavenException { return localRepo == null ? localRepo = resolveLocalRepo(getEffectiveSettings()) : localRepo; } - private LocalProject resolveCurrentProject() throws BootstrapMavenException { + private LocalProject resolveCurrentProject(Function<Path, Model> modelProvider) throws BootstrapMavenException { try { - return LocalProject.loadWorkspace(this); + return LocalProject.loadWorkspace(this, modelProvider); } catch (Exception e) { throw new BootstrapMavenException("Failed to load current project at " + getCurrentProjectPomOrNull(), e); } diff --git a/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/BootstrapMavenContextConfig.java b/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/BootstrapMavenContextConfig.java index efa4ffa77d9..8b645d5b0c2 100644 --- a/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/BootstrapMavenContextConfig.java +++ b/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/BootstrapMavenContextConfig.java @@ -5,7 +5,9 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; +import java.util.function.Function; +import org.apache.maven.model.Model; import org.eclipse.aether.RepositorySystem; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.impl.RemoteRepositoryManager; @@ -33,6 +35,7 @@ protected boolean preferPomsFromWorkspace; protected Boolean effectiveModelBuilder; protected Boolean wsModuleParentHierarchy; + protected Function<Path, Model> modelProvider; /** * Local repository location @@ -264,6 +267,20 @@ public T setWorkspaceModuleParentHierarchy(boolean wsModuleParentHierarchy) { return (T) this; } + /** + * When workspace discovery is enabled, this method allows to set a POM + * provider that would return a {@link org.apache.maven.model.Model} for + * a given workspace module directory. + * + * @param modelProvider POM provider + * @return this instance + */ + @SuppressWarnings("unchecked") + public T setProjectModelProvider(Function<Path, Model> modelProvider) { + this.modelProvider = modelProvider; + return (T) this; + } + private BootstrapMavenOptions getInitializedCliOptions() { return cliOptions == null ? cliOptions = BootstrapMavenOptions.newInstance() : cliOptions; } diff --git a/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/workspace/LocalProject.java b/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/workspace/LocalProject.java index 29e84613bfb..c2fa020ce57 100644 --- a/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/workspace/LocalProject.java +++ b/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/workspace/LocalProject.java @@ -47,6 +47,10 @@ */ public class LocalProject { + private static final String SRC_TEST_RESOURCES = "src/test/resources"; + + private static final String SRC_MAIN_RESOURCES = "src/main/resources"; + public static final String PROJECT_GROUPID = "${project.groupId}"; private static final String PROJECT_BASEDIR = "${project.basedir}"; @@ -78,7 +82,7 @@ public static LocalProject loadWorkspace(Path path) throws BootstrapMavenExcepti public static LocalProject loadWorkspace(Path path, boolean required) throws BootstrapMavenException { try { - return new WorkspaceLoader(null, path.normalize().toAbsolutePath()).load(); + return new WorkspaceLoader(null, path.normalize().toAbsolutePath(), null).load(); } catch (Exception e) { if (required) { throw e; @@ -96,12 +100,17 @@ public static LocalProject loadWorkspace(Path path, boolean required) throws Boo * @throws BootstrapMavenException in case of an error */ public static LocalProject loadWorkspace(BootstrapMavenContext ctx) throws BootstrapMavenException { + return loadWorkspace(ctx, null); + } + + public static LocalProject loadWorkspace(BootstrapMavenContext ctx, Function<Path, Model> modelProvider) + throws BootstrapMavenException { final Path currentProjectPom = ctx.getCurrentProjectPomOrNull(); if (currentProjectPom == null) { return null; } final Path rootProjectBaseDir = ctx.getRootProjectBaseDir(); - final WorkspaceLoader wsLoader = new WorkspaceLoader(ctx, currentProjectPom); + final WorkspaceLoader wsLoader = new WorkspaceLoader(ctx, currentProjectPom, modelProvider); if (rootProjectBaseDir != null && !rootProjectBaseDir.equals(currentProjectPom.getParent())) { wsLoader.setWorkspaceRootPom(rootProjectBaseDir.resolve(POM_XML)); @@ -257,11 +266,11 @@ public PathCollection getResourcesSourcesDirs() { final List<Resource> resources = rawModel.getBuild() == null ? List.of() : rawModel.getBuild().getResources(); if (resources.isEmpty()) { - return PathList.of(resolveRelativeToBaseDir(null, "src/main/resources")); + return PathList.of(resolveRelativeToBaseDir(null, SRC_MAIN_RESOURCES)); } return PathList.from(resources.stream() .map(Resource::getDirectory) - .map(resourcesDir -> resolveRelativeToBaseDir(resourcesDir, "src/main/resources")) + .map(resourcesDir -> resolveRelativeToBaseDir(resourcesDir, SRC_MAIN_RESOURCES)) .collect(Collectors.toCollection(LinkedHashSet::new))); } @@ -269,11 +278,11 @@ public PathCollection getTestResourcesSourcesDirs() { final List<Resource> resources = rawModel.getBuild() == null ? List.of() : rawModel.getBuild().getTestResources(); if (resources.isEmpty()) { - return PathList.of(resolveRelativeToBaseDir(null, "src/test/resources")); + return PathList.of(resolveRelativeToBaseDir(null, SRC_TEST_RESOURCES)); } return PathList.from(resources.stream() .map(Resource::getDirectory) - .map(resourcesDir -> resolveRelativeToBaseDir(resourcesDir, "src/test/resources")) + .map(resourcesDir -> resolveRelativeToBaseDir(resourcesDir, SRC_TEST_RESOURCES)) .collect(Collectors.toCollection(LinkedHashSet::new))); } @@ -302,7 +311,8 @@ public ResolvedDependency getAppArtifact() { } public ResolvedDependency getAppArtifact(String extension) { - return new ResolvedArtifactDependency(key.getGroupId(), key.getArtifactId(), "", extension, getVersion(), + return new ResolvedArtifactDependency(key.getGroupId(), key.getArtifactId(), ArtifactCoords.DEFAULT_CLASSIFIER, + extension, getVersion(), (PathCollection) null); } @@ -521,14 +531,14 @@ private Collection<SourceDir> collectMainResources(PathFilter filter) { final Path classesDir = getClassesDir(); if (resources.isEmpty()) { return List.of(new DefaultSourceDir( - new DirectoryPathTree(resolveRelativeToBaseDir(null, "src/main/resources")), + new DirectoryPathTree(resolveRelativeToBaseDir(null, SRC_MAIN_RESOURCES)), new DirectoryPathTree(classesDir, filter), Map.of())); } final List<SourceDir> sourceDirs = new ArrayList<>(resources.size()); for (Resource r : resources) { sourceDirs.add( new DefaultSourceDir( - new DirectoryPathTree(resolveRelativeToBaseDir(r.getDirectory(), "src/main/resources")), + new DirectoryPathTree(resolveRelativeToBaseDir(r.getDirectory(), SRC_MAIN_RESOURCES)), new DirectoryPathTree((r.getTargetPath() == null ? classesDir : classesDir.resolve(stripProjectBasedirPrefix(r.getTargetPath(), PROJECT_OUTPUT_DIR))), filter), @@ -543,14 +553,14 @@ private Collection<SourceDir> collectTestResources(PathFilter filter) { final Path testClassesDir = getTestClassesDir(); if (resources.isEmpty()) { return List.of(new DefaultSourceDir( - new DirectoryPathTree(resolveRelativeToBaseDir(null, "src/test/resources")), + new DirectoryPathTree(resolveRelativeToBaseDir(null, SRC_TEST_RESOURCES)), new DirectoryPathTree(testClassesDir, filter), Map.of())); } final List<SourceDir> sourceDirs = new ArrayList<>(resources.size()); for (Resource r : resources) { sourceDirs.add( new DefaultSourceDir( - new DirectoryPathTree(resolveRelativeToBaseDir(r.getDirectory(), "src/test/resources")), + new DirectoryPathTree(resolveRelativeToBaseDir(r.getDirectory(), SRC_TEST_RESOURCES)), new DirectoryPathTree((r.getTargetPath() == null ? testClassesDir : testClassesDir.resolve(stripProjectBasedirPrefix(r.getTargetPath(), PROJECT_OUTPUT_DIR))), filter), diff --git a/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/workspace/WorkspaceLoader.java b/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/workspace/WorkspaceLoader.java index 6a0cd9b5627..a30aad09d2f 100644 --- a/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/workspace/WorkspaceLoader.java +++ b/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/workspace/WorkspaceLoader.java @@ -8,6 +8,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.function.Function; import org.apache.maven.model.Model; import org.apache.maven.model.Parent; @@ -69,6 +70,7 @@ static Path locateCurrentProjectPom(Path path, boolean required) throws Bootstra private final Map<Path, LocalProject> projectCache = new HashMap<>(); private final Path currentProjectPom; private Path workspaceRootPom; + private Function<Path, Model> modelProvider; private ModelBuilder modelBuilder; private ModelResolver modelResolver; @@ -77,7 +79,9 @@ static Path locateCurrentProjectPom(Path path, boolean required) throws Bootstra private List<String> inactiveProfileIds; private List<Profile> profiles; - WorkspaceLoader(BootstrapMavenContext ctx, Path currentProjectPom) throws BootstrapMavenException { + WorkspaceLoader(BootstrapMavenContext ctx, Path currentProjectPom, Function<Path, Model> modelProvider) + throws BootstrapMavenException { + this.modelProvider = modelProvider; if (ctx != null && ctx.isEffectiveModelBuilder()) { modelBuilder = BootstrapModelBuilderFactory.getDefaultModelBuilder(); modelResolver = BootstrapModelResolver.newInstance(ctx, workspace); @@ -100,7 +104,7 @@ static Path locateCurrentProjectPom(Path path, boolean required) throws Bootstra private boolean isPom(Path p) { if (Files.exists(p) && !Files.isDirectory(p)) { try { - loadAndCacheRawModel(p); + rawModel(p); return true; } catch (BootstrapMavenException e) { // not a POM file @@ -115,7 +119,8 @@ private LocalProject project(Path pomFile) throws BootstrapMavenException { } private LocalProject loadAndCacheProject(Path pomFile) throws BootstrapMavenException { - final Model cachedRawModel = rawModelCache.get(pomFile.getParent()); + Model cachedRawModel = rawModelCache.getOrDefault(pomFile.getParent(), + modelProvider == null ? null : modelProvider.apply(pomFile.getParent())); final LocalProject project; if (modelBuilder != null) { ModelBuildingRequest req = new DefaultModelBuildingRequest(); @@ -148,7 +153,8 @@ private LocalProject loadAndCacheProject(Path pomFile) throws BootstrapMavenExce } private Model rawModel(Path pomFile) throws BootstrapMavenException { - final Model rawModel = rawModelCache.get(pomFile.getParent()); + final Model rawModel = rawModelCache.getOrDefault(pomFile.getParent(), + modelProvider == null ? null : modelProvider.apply(pomFile.getParent())); return rawModel == null ? loadAndCacheRawModel(pomFile) : rawModel; }
['independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/workspace/WorkspaceLoader.java', 'independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/BootstrapMavenContextConfig.java', 'independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/workspace/LocalProject.java', 'independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/BootstrapMavenContext.java', 'core/deployment/src/main/java/io/quarkus/deployment/dev/QuarkusDevModeLauncher.java', 'devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java', 'devtools/maven/src/main/java/io/quarkus/maven/QuarkusBootstrapProvider.java']
{'.java': 7}
7
7
0
0
7
23,079,814
4,535,252
589,836
5,465
8,156
1,470
118
7
2,680
265
809
79
7
3
1970-01-01T00:27:45
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,298
quarkusio/quarkus/29950/29919
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/29919
https://github.com/quarkusio/quarkus/pull/29950
https://github.com/quarkusio/quarkus/pull/29950
1
resolves
WebSocket auth on VertxCurrentContext not working
### Describe the bug Hello. In my comman we use auth on WebSocket class by this hack ``` @RouteFilter(401) void addAuthHeader(RoutingContext rc) { try { if (rc.request().headers().get("Sec-WebSocket-Protocol") != null) { String token = "Bearer " + rc.request().headers().get("Sec-WebSocket-Protocol").split(", ")[1]; rc.request().headers().add("Authorization", token); } } finally { rc.next(); } } ``` We make ws request such this ``` const ws = new WebSocket(`ws://localhost:8080/ws`, ["access_token", "token"]); ``` And WebSoket class such as ``` @ServerEndpoint( value = "/api/v1/notification-socket/{userId}", decoders = SocketMessageDecoder.class, encoders = SocketMessageEncoder.class ) @Authenticated public class WS { // ...... } ``` Last version when it works is **2.12.3.Final** It works by changes in this commit - [Add proper identity propagation to WebSockets](https://github.com/quarkusio/quarkus/pull/20157/commits/d6a421a5a2e433e6ea4aa966fc66842bebae40fd) - File WebsocketCoreRecorder After update to version 2.13 and higher it work only then used property `quarkus.vertx.customize-arc-context=false` In version 2.13 added changes from this commit [CDI context propagation improvements for the reactive stack](https://github.com/quarkusio/quarkus/pull/27443). Now where is two CurrentContext implementations - ThreadLocalCurrentContext (ws auth works) and VertxCurrentContext (ws auth not work) This code from WebsocketCoreRecorder ``` boolean required = !requestContext.isActive(); if (required) { requestContext.activate(); Principal p = session.getUserPrincipal(); if (p instanceof WebSocketPrincipal) { CurrentIdentityAssociation current = this.getCurrentIdentityAssociation(); if (current != null) { current.setIdentity(((WebSocketPrincipal)p).getSecurityIdentity()); } } } ``` When uses ThreadLocalCurrentContext - requestContext.isActive() is false, and principal added in context When uses VertxCurrentContext - requestContext.isActive() is always true, and user don`t added on context Maybe fix this place, or create fix VertxCurrentContext? Thank you for your job) ### Expected behavior _No response_ ### Actual behavior _No response_ ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.13+ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
fc20fb29136f9eb0f85bc89165d062b09a45313b
38e36caa2e24d6eec96e1e87c811e724741e67d6
https://github.com/quarkusio/quarkus/compare/fc20fb29136f9eb0f85bc89165d062b09a45313b...38e36caa2e24d6eec96e1e87c811e724741e67d6
diff --git a/extensions/websockets/client/runtime/src/main/java/io/quarkus/websockets/client/runtime/WebsocketCoreRecorder.java b/extensions/websockets/client/runtime/src/main/java/io/quarkus/websockets/client/runtime/WebsocketCoreRecorder.java index ca321461c59..670656f1a0a 100644 --- a/extensions/websockets/client/runtime/src/main/java/io/quarkus/websockets/client/runtime/WebsocketCoreRecorder.java +++ b/extensions/websockets/client/runtime/src/main/java/io/quarkus/websockets/client/runtime/WebsocketCoreRecorder.java @@ -169,12 +169,12 @@ public T call(C context, UndertowSession session) throws Exception { boolean required = !requestContext.isActive(); if (required) { requestContext.activate(); - Principal p = session.getUserPrincipal(); - if (p instanceof WebSocketPrincipal) { - var current = getCurrentIdentityAssociation(); - if (current != null) { - current.setIdentity(((WebSocketPrincipal) p).getSecurityIdentity()); - } + } + Principal p = session.getUserPrincipal(); + if (p instanceof WebSocketPrincipal) { + var current = getCurrentIdentityAssociation(); + if (current != null) { + current.setIdentity(((WebSocketPrincipal) p).getSecurityIdentity()); } } try {
['extensions/websockets/client/runtime/src/main/java/io/quarkus/websockets/client/runtime/WebsocketCoreRecorder.java']
{'.java': 1}
1
1
0
0
1
24,093,415
4,743,535
614,767
5,637
899
98
12
1
2,782
301
650
101
2
4
1970-01-01T00:27:51
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,299
quarkusio/quarkus/29948/29946
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/29946
https://github.com/quarkusio/quarkus/pull/29948
https://github.com/quarkusio/quarkus/pull/29948
1
fixes
NPE in KeycloakDevServicesProcessor again
### Describe the bug It seems that https://github.com/quarkusio/quarkus/issues/29312 was not properly fixed in 2.15.0.Final. I am now getting a similar, but slightly different NPE: ``` 2022-12-19 08:28:55,072 ERROR [io.qua.dep.dev.IsolatedDevModeMain] (main) Failed to start quarkus: java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors [error]: Build step io.quarkus.oidc.deployment.devservices.keycloak.KeycloakDevServicesProcessor#startKeycloakContainer threw an exception: java.lang.RuntimeException: java.lang.NullPointerException: Cannot invoke "java.util.List.isEmpty()" because "realmReps" is null at io.quarkus.oidc.deployment.devservices.keycloak.KeycloakDevServicesProcessor.startKeycloakContainer(KeycloakDevServicesProcessor.java:247) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at io.quarkus.deployment.ExtensionLoader$3.execute(ExtensionLoader.java:909) at io.quarkus.builder.BuildContext.run(BuildContext.java:281) at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478) at java.base/java.lang.Thread.run(Thread.java:833) at org.jboss.threads.JBossThread.run(JBossThread.java:501) Caused by: java.lang.NullPointerException: Cannot invoke "java.util.List.isEmpty()" because "realmReps" is null at io.quarkus.oidc.deployment.devservices.keycloak.KeycloakDevServicesProcessor.prepareConfiguration(KeycloakDevServicesProcessor.java:269) at io.quarkus.oidc.deployment.devservices.keycloak.KeycloakDevServicesProcessor.lambda$startContainer$5(KeycloakDevServicesProcessor.java:390) at java.base/java.util.Optional.map(Optional.java:260) at io.quarkus.oidc.deployment.devservices.keycloak.KeycloakDevServicesProcessor.startContainer(KeycloakDevServicesProcessor.java:388) at io.quarkus.oidc.deployment.devservices.keycloak.KeycloakDevServicesProcessor.startKeycloakContainer(KeycloakDevServicesProcessor.java:195) ... 11 more at io.quarkus.runner.bootstrap.AugmentActionImpl.runAugment(AugmentActionImpl.java:335) at io.quarkus.runner.bootstrap.AugmentActionImpl.createInitialRuntimeApplication(AugmentActionImpl.java:252) at io.quarkus.runner.bootstrap.AugmentActionImpl.createInitialRuntimeApplication(AugmentActionImpl.java:60) at io.quarkus.deployment.dev.IsolatedDevModeMain.firstStart(IsolatedDevModeMain.java:86) at io.quarkus.deployment.dev.IsolatedDevModeMain.accept(IsolatedDevModeMain.java:447) at io.quarkus.deployment.dev.IsolatedDevModeMain.accept(IsolatedDevModeMain.java:59) at io.quarkus.bootstrap.app.CuratedApplication.runInCl(CuratedApplication.java:149) at io.quarkus.bootstrap.app.CuratedApplication.runInAugmentClassLoader(CuratedApplication.java:104) at io.quarkus.deployment.dev.DevModeMain.start(DevModeMain.java:131) at io.quarkus.deployment.dev.DevModeMain.main(DevModeMain.java:62) Caused by: io.quarkus.builder.BuildException: Build failure: Build failed due to errors [error]: Build step io.quarkus.oidc.deployment.devservices.keycloak.KeycloakDevServicesProcessor#startKeycloakContainer threw an exception: java.lang.RuntimeException: java.lang.NullPointerException: Cannot invoke "java.util.List.isEmpty()" because "realmReps" is null at io.quarkus.oidc.deployment.devservices.keycloak.KeycloakDevServicesProcessor.startKeycloakContainer(KeycloakDevServicesProcessor.java:247) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at io.quarkus.deployment.ExtensionLoader$3.execute(ExtensionLoader.java:909) at io.quarkus.builder.BuildContext.run(BuildContext.java:281) at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478) at java.base/java.lang.Thread.run(Thread.java:833) at org.jboss.threads.JBossThread.run(JBossThread.java:501) Caused by: java.lang.NullPointerException: Cannot invoke "java.util.List.isEmpty()" because "realmReps" is null at io.quarkus.oidc.deployment.devservices.keycloak.KeycloakDevServicesProcessor.prepareConfiguration(KeycloakDevServicesProcessor.java:269) at io.quarkus.oidc.deployment.devservices.keycloak.KeycloakDevServicesProcessor.lambda$startContainer$5(KeycloakDevServicesProcessor.java:390) at java.base/java.util.Optional.map(Optional.java:260) at io.quarkus.oidc.deployment.devservices.keycloak.KeycloakDevServicesProcessor.startContainer(KeycloakDevServicesProcessor.java:388) at io.quarkus.oidc.deployment.devservices.keycloak.KeycloakDevServicesProcessor.startKeycloakContainer(KeycloakDevServicesProcessor.java:195) ... 11 more at io.quarkus.builder.Execution.run(Execution.java:123) at io.quarkus.builder.BuildExecutionBuilder.execute(BuildExecutionBuilder.java:79) at io.quarkus.deployment.QuarkusAugmentor.run(QuarkusAugmentor.java:160) at io.quarkus.runner.bootstrap.AugmentActionImpl.runAugment(AugmentActionImpl.java:331) ... 9 more Caused by: java.lang.RuntimeException: java.lang.NullPointerException: Cannot invoke "java.util.List.isEmpty()" because "realmReps" is null at io.quarkus.oidc.deployment.devservices.keycloak.KeycloakDevServicesProcessor.startKeycloakContainer(KeycloakDevServicesProcessor.java:247) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at io.quarkus.deployment.ExtensionLoader$3.execute(ExtensionLoader.java:909) at io.quarkus.builder.BuildContext.run(BuildContext.java:281) at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478) at java.base/java.lang.Thread.run(Thread.java:833) at org.jboss.threads.JBossThread.run(JBossThread.java:501) Caused by: java.lang.NullPointerException: Cannot invoke "java.util.List.isEmpty()" because "realmReps" is null at io.quarkus.oidc.deployment.devservices.keycloak.KeycloakDevServicesProcessor.prepareConfiguration(KeycloakDevServicesProcessor.java:269) at io.quarkus.oidc.deployment.devservices.keycloak.KeycloakDevServicesProcessor.lambda$startContainer$5(KeycloakDevServicesProcessor.java:390) at java.base/java.util.Optional.map(Optional.java:260) at io.quarkus.oidc.deployment.devservices.keycloak.KeycloakDevServicesProcessor.startContainer(KeycloakDevServicesProcessor.java:388) at io.quarkus.oidc.deployment.devservices.keycloak.KeycloakDevServicesProcessor.startKeycloakContainer(KeycloakDevServicesProcessor.java:195) ... 11 more ``` ### Expected behavior _No response_ ### Actual behavior _No response_ ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
fc20fb29136f9eb0f85bc89165d062b09a45313b
490aeb6291ec62e426eeef7bce108c745969769c
https://github.com/quarkusio/quarkus/compare/fc20fb29136f9eb0f85bc89165d062b09a45313b...490aeb6291ec62e426eeef7bce108c745969769c
diff --git a/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesProcessor.java b/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesProcessor.java index c7c1674c8f2..a9e4afbb5bb 100644 --- a/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesProcessor.java +++ b/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesProcessor.java @@ -266,7 +266,7 @@ private Map<String, String> prepareConfiguration( String clientAuthServerBaseUrl = hostURL != null ? hostURL : internalURL; String clientAuthServerUrl = realmsURL(clientAuthServerBaseUrl, realmName); - boolean createDefaultRealm = realmReps.isEmpty() && capturedDevServicesConfiguration.createRealm; + boolean createDefaultRealm = (realmReps == null || realmReps.isEmpty()) && capturedDevServicesConfiguration.createRealm; String oidcClientId = getOidcClientId(createDefaultRealm); String oidcClientSecret = getOidcClientSecret(createDefaultRealm); @@ -283,9 +283,11 @@ private Map<String, String> prepareConfiguration( createDefaultRealm(client, adminToken, clientAuthServerBaseUrl, users, oidcClientId, oidcClientSecret, errors); realmNames.add(realmName); } else { - for (RealmRepresentation realmRep : realmReps) { - createRealm(client, adminToken, clientAuthServerBaseUrl, realmRep, errors); - realmNames.add(realmRep.getRealm()); + if (realmReps != null) { + for (RealmRepresentation realmRep : realmReps) { + createRealm(client, adminToken, clientAuthServerBaseUrl, realmRep, errors); + realmNames.add(realmRep.getRealm()); + } } } } finally {
['extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesProcessor.java']
{'.java': 1}
1
1
0
0
1
24,093,415
4,743,535
614,767
5,637
755
139
10
1
8,139
339
1,929
122
1
1
1970-01-01T00:27:51
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,338
quarkusio/quarkus/28533/25809
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/25809
https://github.com/quarkusio/quarkus/pull/28533
https://github.com/quarkusio/quarkus/pull/28533
1
fixes
Important log message shown during Dev Services for Keycloak initialization is lost
### Describe the bug Not sure it is a bug, as I recall there was an issue related to some of the dev services related to the excessive logging. But in any case, I recall it was possible to see various log messages logged by `KeycloakDevServicesProcessor` but now it is all being collapsed and all I see is ``` -- 2022-05-26 12:38:41,657 INFO [io.qua.oid.dep.dev.key.KeycloakDevServicesProcessor] (build-37) Dev Services for Keycloak started. ``` For example, `KeycloakDevServicesProcessor` logs if it can not find the configured realm file [here](https://github.com/quarkusio/quarkus/blob/main/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesProcessor.java#L457), but it is not visible and the user has just spent a lot of time trying to figure out what went wrong in his replica of the `keycloak-authorization` quickstart which proved to be caused by a missing realm file. I'm not sure throwing the exception in case of a missing realm would be a good dev experience given that one way to fix it is to go to Keycloak Admin UI from DevConsole and import a realm there if one sees a message that no realm is found. ### Expected behavior I think the messages logged by various Dev Services processors themselves (such as `KeycloakDevSericesProcessor`) should be visible, while the test containers logging can indeed be collapsed to minimize the noise. ### Actual behavior _No response_ ### How to Reproduce? Go to the `security-keycloak-authorization-quickstart` in quarkus-quickstarts and change path to the realm to point to a non-existent location. `mvn quarkus-dev` will fail with error caused by the fact DevServices for Keycloak did not import it but no log message informing the user that the realm is missing will be shown ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
553a86806cf3b4431bd710fc1a5f389ac2bd9a53
6b5462713757405bcb9171a62926f23c4fcfca42
https://github.com/quarkusio/quarkus/compare/553a86806cf3b4431bd710fc1a5f389ac2bd9a53...6b5462713757405bcb9171a62926f23c4fcfca42
diff --git a/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesProcessor.java b/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesProcessor.java index 34a1a4cb091..31f90109de2 100644 --- a/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesProcessor.java +++ b/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesProcessor.java @@ -181,17 +181,24 @@ public DevServicesResultBuildItem startKeycloakContainer( } capturedDevServicesConfiguration = currentDevServicesConfiguration; StartupLogCompressor compressor = new StartupLogCompressor( - (launchMode.isTest() ? "(test) " : "") + "KeyCloak Dev Services Starting:", + (launchMode.isTest() ? "(test) " : "") + "Keycloak Dev Services Starting:", consoleInstalledBuildItem, loggingSetupBuildItem); if (vertxInstance == null) { vertxInstance = Vertx.vertx(); } try { + List<String> errors = new ArrayList<>(); + RunningDevService newDevService = startContainer(dockerStatusBuildItem, keycloakBuildItemBuildProducer, !devServicesSharedNetworkBuildItem.isEmpty(), - devServicesConfig.timeout); + devServicesConfig.timeout, + errors); if (newDevService == null) { - compressor.close(); + if (errors.isEmpty()) { + compressor.close(); + } else { + compressor.closeAndDumpCaptured(); + } return null; } @@ -227,10 +234,10 @@ public void run() { } capturedRealmFileLastModifiedDate = getRealmFileLastModifiedDate(capturedDevServicesConfiguration.realmPath); - if (devService == null) { - compressor.closeAndDumpCaptured(); - } else { + if (devService != null && errors.isEmpty()) { compressor.close(); + } else { + compressor.closeAndDumpCaptured(); } } catch (Throwable t) { compressor.closeAndDumpCaptured(); @@ -241,14 +248,14 @@ public void run() { return devService.toBuildItem(); } - private String startURL(String host, Integer port, boolean isKeyCloakX) { - return "http://" + host + ":" + port + (isKeyCloakX ? "" : "/auth"); + private String startURL(String host, Integer port, boolean isKeycloakX) { + return "http://" + host + ":" + port + (isKeycloakX ? "" : "/auth"); } private Map<String, String> prepareConfiguration( BuildProducer<KeycloakDevServicesConfigBuildItem> keycloakBuildItemBuildProducer, String internalURL, String hostURL, RealmRepresentation realmRep, - boolean keycloakX) { + boolean keycloakX, List<String> errors) { final String realmName = realmRep != null ? realmRep.getRealm() : getDefaultRealmName(); final String authServerInternalUrl = realmsURL(internalURL, realmName); @@ -266,9 +273,10 @@ private Map<String, String> prepareConfiguration( try { String adminToken = getAdminToken(client, clientAuthServerBaseUrl); if (createDefaultRealm) { - createDefaultRealm(client, adminToken, clientAuthServerBaseUrl, users, oidcClientId, oidcClientSecret); + createDefaultRealm(client, adminToken, clientAuthServerBaseUrl, users, oidcClientId, oidcClientSecret, + errors); } else if (realmRep != null && keycloakX) { - createRealm(client, adminToken, clientAuthServerBaseUrl, realmRep); + createRealm(client, adminToken, clientAuthServerBaseUrl, realmRep, errors); } } finally { client.close(); @@ -300,7 +308,8 @@ private String getDefaultRealmName() { private RunningDevService startContainer(DockerStatusBuildItem dockerStatusBuildItem, BuildProducer<KeycloakDevServicesConfigBuildItem> keycloakBuildItemBuildProducer, - boolean useSharedNetwork, Optional<Duration> timeout) { + boolean useSharedNetwork, Optional<Duration> timeout, + List<String> errors) { if (!capturedDevServicesConfiguration.enabled) { // explicitly disabled LOG.debug("Not starting Dev Services for Keycloak as it has been disabled in the config"); @@ -342,7 +351,8 @@ private RunningDevService startContainer(DockerStatusBuildItem dockerStatusBuild capturedDevServicesConfiguration.shared, capturedDevServicesConfiguration.javaOpts, capturedDevServicesConfiguration.startCommand, - capturedDevServicesConfiguration.showLogs); + capturedDevServicesConfiguration.showLogs, + errors); timeout.ifPresent(oidcContainer::withStartupTimeout); oidcContainer.start(); @@ -356,7 +366,8 @@ private RunningDevService startContainer(DockerStatusBuildItem dockerStatusBuild Map<String, String> configs = prepareConfiguration(keycloakBuildItemBuildProducer, internalUrl, hostUrl, oidcContainer.realmRep, - oidcContainer.keycloakX); + oidcContainer.keycloakX, + errors); return new RunningDevService(KEYCLOAK_CONTAINER_NAME, oidcContainer.getContainerId(), oidcContainer::close, configs); }; @@ -366,7 +377,7 @@ private RunningDevService startContainer(DockerStatusBuildItem dockerStatusBuild // TODO: this probably needs to be addressed Map<String, String> configs = prepareConfiguration(keycloakBuildItemBuildProducer, getSharedContainerUrl(containerAddress), - getSharedContainerUrl(containerAddress), null, false); + getSharedContainerUrl(containerAddress), null, false, errors); return new RunningDevService(KEYCLOAK_CONTAINER_NAME, containerAddress.getId(), null, configs); }) .orElseGet(defaultKeycloakContainerSupplier); @@ -395,10 +406,12 @@ private static class QuarkusOidcContainer extends GenericContainer<QuarkusOidcCo private RealmRepresentation realmRep; private final Optional<String> startCommand; private final boolean showLogs; + private final List<String> errors; public QuarkusOidcContainer(DockerImageName dockerImageName, OptionalInt fixedExposedPort, boolean useSharedNetwork, Optional<String> realmPath, String containerLabelValue, - boolean sharedContainer, Optional<String> javaOpts, Optional<String> startCommand, boolean showLogs) { + boolean sharedContainer, Optional<String> javaOpts, Optional<String> startCommand, boolean showLogs, + List<String> errors) { super(dockerImageName); this.useSharedNetwork = useSharedNetwork; @@ -418,6 +431,7 @@ public QuarkusOidcContainer(DockerImageName dockerImageName, OptionalInt fixedEx this.fixedExposedPort = fixedExposedPort; this.startCommand = startCommand; this.showLogs = showLogs; + this.errors = errors; super.setWaitStrategy(Wait.forLogMessage(".*Keycloak.*started.*", 1)); } @@ -468,7 +482,7 @@ protected void configure() { if (realmPath.isPresent()) { URL realmPathUrl = null; if ((realmPathUrl = Thread.currentThread().getContextClassLoader().getResource(realmPath.get())) != null) { - realmRep = readRealmFile(realmPathUrl, realmPath.get()); + realmRep = readRealmFile(realmPathUrl, realmPath.get(), errors); if (!keycloakX) { withClasspathResourceMapping(realmPath.get(), KEYCLOAK_DOCKER_REALM_PATH, BindMode.READ_ONLY); } @@ -478,9 +492,11 @@ protected void configure() { if (!keycloakX) { withFileSystemBind(realmPath.get(), KEYCLOAK_DOCKER_REALM_PATH, BindMode.READ_ONLY); } - realmRep = readRealmFile(filePath.toUri(), realmPath.get()); + realmRep = readRealmFile(filePath.toUri(), realmPath.get(), errors); } else { - LOG.debugf("Realm %s resource is not available", realmPath.get()); + errors.add(String.format("Realm %s resource is not available", realmPath.get())); + + LOG.errorf("Realm %s resource is not available", realmPath.get()); } } @@ -507,21 +523,23 @@ private Integer findRandomPort() { } } - private RealmRepresentation readRealmFile(URI uri, String realmPath) { + private RealmRepresentation readRealmFile(URI uri, String realmPath, List<String> errors) { try { - return readRealmFile(uri.toURL(), realmPath); + return readRealmFile(uri.toURL(), realmPath, errors); } catch (MalformedURLException ex) { // Will not happen as this method is called only when it is confirmed the file exists throw new RuntimeException(ex); } } - private RealmRepresentation readRealmFile(URL url, String realmPath) { + private RealmRepresentation readRealmFile(URL url, String realmPath, List<String> errors) { try { try (InputStream is = url.openStream()) { return JsonSerialization.readValue(is, RealmRepresentation.class); } } catch (IOException ex) { + errors.add(String.format("Realm %s resource can not be opened: %s", realmPath, ex.getMessage())); + LOG.errorf("Realm %s resource can not be opened: %s", realmPath, ex.getMessage()); } return null; @@ -578,7 +596,8 @@ private FileTime getRealmFileLastModifiedDate(Optional<String> realm) { private void createDefaultRealm(WebClient client, String token, String keycloakUrl, Map<String, String> users, String oidcClientId, - String oidcClientSecret) { + String oidcClientSecret, + List<String> errors) { RealmRepresentation realm = createDefaultRealmRep(); realm.getClients().add(createClient(oidcClientId, oidcClientSecret)); @@ -586,7 +605,7 @@ private void createDefaultRealm(WebClient client, String token, String keycloakU realm.getUsers().add(createUser(entry.getKey(), entry.getValue(), getUserRoles(entry.getKey()))); } - createRealm(client, token, keycloakUrl, realm); + createRealm(client, token, keycloakUrl, realm, errors); } private String getAdminToken(WebClient client, String keycloakUrl) { @@ -602,7 +621,8 @@ private String getAdminToken(WebClient client, String keycloakUrl) { return null; } - private void createRealm(WebClient client, String token, String keycloakUrl, RealmRepresentation realm) { + private void createRealm(WebClient client, String token, String keycloakUrl, RealmRepresentation realm, + List<String> errors) { try { LOG.tracef("Creating the realm %s", realm.getRealm()); HttpResponse<Buffer> createRealmResponse = client.postAbs(keycloakUrl + "/admin/realms") @@ -612,6 +632,10 @@ private void createRealm(WebClient client, String token, String keycloakUrl, Rea .await().atMost(oidcConfig.devui.webClientTimeout); if (createRealmResponse.statusCode() > 299) { + errors.add(String.format("Realm %s can not be created %d - %s ", realm.getRealm(), + createRealmResponse.statusCode(), + createRealmResponse.statusMessage())); + LOG.errorf("Realm %s can not be created %d - %s ", realm.getRealm(), createRealmResponse.statusCode(), createRealmResponse.statusMessage()); } @@ -635,6 +659,8 @@ private void createRealm(WebClient client, String token, String keycloakUrl, Rea }); realmStatusCodeUni.await().atMost(Duration.ofSeconds(10)); } catch (Throwable t) { + errors.add(String.format("Realm %s can not be created: %s", realm.getRealm(), t.getMessage())); + LOG.errorf("Realm %s can not be created: %s", realm.getRealm(), t.getMessage()); } }
['extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesProcessor.java']
{'.java': 1}
1
1
0
0
1
23,154,486
4,549,243
591,453
5,471
4,755
900
76
1
2,184
316
506
49
1
1
1970-01-01T00:27:45
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,337
quarkusio/quarkus/28542/28541
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/28541
https://github.com/quarkusio/quarkus/pull/28542
https://github.com/quarkusio/quarkus/pull/28542
1
fix
Regression in 2.13.2: NPE in `LocalProject` during `quarkus-maven-plugin:build` when activating `quarkus.bootstrap.workspace-discovery`
### Describe the bug Updating from 2.13.1 to 2.13.2 results in: ``` [ERROR] Failed to execute goal io.quarkus:quarkus-maven-plugin:2.13.2.Final:build (default) on project somecomp-server: Failed to build quarkus application: Failed to initialize Quarkus bootstrap Maven artifact resolver: Failed to load current project at /home/fmo/proj/someproj/somecomp/dev1/server/.flattened-pom.xml: Cannot invoke "java.io.File.toPath()" because the return value of "org.apache.maven.model.Model.getProjectDirectory()" is null -> [Help 1] ... Caused by: java.lang.NullPointerException: Cannot invoke "java.io.File.toPath()" because the return value of "org.apache.maven.model.Model.getProjectDirectory()" is null at io.quarkus.bootstrap.resolver.maven.workspace.LocalProject.<init> (LocalProject.java:172) at io.quarkus.bootstrap.resolver.maven.workspace.WorkspaceLoader.loadAndCacheProject (WorkspaceLoader.java:143) at io.quarkus.bootstrap.resolver.maven.workspace.WorkspaceLoader.project (WorkspaceLoader.java:118) at io.quarkus.bootstrap.resolver.maven.workspace.WorkspaceLoader.loadProject (WorkspaceLoader.java:178) at io.quarkus.bootstrap.resolver.maven.workspace.WorkspaceLoader.load (WorkspaceLoader.java:230) at io.quarkus.bootstrap.resolver.maven.workspace.LocalProject.loadWorkspace (LocalProject.java:118) at io.quarkus.bootstrap.resolver.maven.BootstrapMavenContext.resolveCurrentProject (BootstrapMavenContext.java:321) at io.quarkus.bootstrap.resolver.maven.BootstrapMavenContext.<init> (BootstrapMavenContext.java:173) at io.quarkus.bootstrap.resolver.maven.MavenArtifactResolver.<init> (MavenArtifactResolver.java:91) at io.quarkus.bootstrap.resolver.maven.MavenArtifactResolver$Builder.build (MavenArtifactResolver.java:75) at io.quarkus.maven.QuarkusBootstrapProvider$QuarkusMavenAppBootstrap.artifactResolver (QuarkusBootstrapProvider.java:152) at io.quarkus.maven.QuarkusBootstrapProvider$QuarkusMavenAppBootstrap.doBootstrap (QuarkusBootstrapProvider.java:206) at io.quarkus.maven.QuarkusBootstrapProvider$QuarkusMavenAppBootstrap.bootstrapApplication (QuarkusBootstrapProvider.java:284) at io.quarkus.maven.QuarkusBootstrapProvider.bootstrapApplication (QuarkusBootstrapProvider.java:86) at io.quarkus.maven.QuarkusBootstrapMojo.bootstrapApplication (QuarkusBootstrapMojo.java:272) at io.quarkus.maven.QuarkusBootstrapMojo.bootstrapApplication (QuarkusBootstrapMojo.java:268) at io.quarkus.maven.BuildMojo.doExecute (BuildMojo.java:130) at io.quarkus.maven.QuarkusBootstrapMojo.execute (QuarkusBootstrapMojo.java:154) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137) at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute2 (MojoExecutor.java:370) at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute (MojoExecutor.java:351) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:171) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:163) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117) at org.apache.maven.lifecycle.internal.builder.multithreaded.MultiThreadedBuilder$1.call (MultiThreadedBuilder.java:210) at org.apache.maven.lifecycle.internal.builder.multithreaded.MultiThreadedBuilder$1.call (MultiThreadedBuilder.java:195) at java.util.concurrent.FutureTask.run (FutureTask.java:264) at java.util.concurrent.Executors$RunnableAdapter.call (Executors.java:539) at java.util.concurrent.FutureTask.run (FutureTask.java:264) at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1136) at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:635) at java.lang.Thread.run (Thread.java:833) ``` ### Expected behavior No error ### Actual behavior Error during build ### How to Reproduce? n/a at this point ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` 17.0.4 ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Maven 3.8.6 ### Additional information Build happens via profile: ```xml <profile> <id>image-build</id> <properties> <!-- switch on early Quarkus workspace discovery for smaller layers --> <quarkus.bootstrap.workspace-discovery>true</quarkus.bootstrap.workspace-discovery> <quarkus.container-image.name>somecomp</quarkus.container-image.name> </properties> <build> <plugins> <plugin> <groupId>io.quarkus</groupId> <artifactId>quarkus-maven-plugin</artifactId> <executions> <execution> <goals> <goal>build</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> ``` Jib plugin is used to build the image (but it doesn't get that far).
5ff6805119c6b63a21996b3b7b58e6f181869f49
99d577733c5994f1eecb1818cadcaa3b430d0f48
https://github.com/quarkusio/quarkus/compare/5ff6805119c6b63a21996b3b7b58e6f181869f49...99d577733c5994f1eecb1818cadcaa3b430d0f48
diff --git a/devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java b/devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java index 387fcb3a42f..0d300ecc92a 100644 --- a/devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java +++ b/devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java @@ -43,7 +43,6 @@ import org.apache.maven.execution.MavenSession; import org.apache.maven.model.BuildBase; import org.apache.maven.model.Dependency; -import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; import org.apache.maven.model.Profile; @@ -121,8 +120,6 @@ @Mojo(name = "dev", defaultPhase = LifecyclePhase.PREPARE_PACKAGE, requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true) public class DevMojo extends AbstractMojo { - private static final String EXT_PROPERTIES_PATH = "META-INF/quarkus-extension.properties"; - private static final String KOTLIN_MAVEN_PLUGIN_GA = "org.jetbrains.kotlin:kotlin-maven-plugin"; /** @@ -1105,11 +1102,7 @@ private QuarkusDevModeLauncher newLauncher() throws Exception { mvnConfig.setRepositorySystemSession(repoSession).setRepositorySystem(repoSystem); // there could be Maven extensions manipulating the project versions and models // the ones returned from the Maven API could be different from the original pom.xml files - final Map<Path, Model> projectModels = new HashMap<>(session.getAllProjects().size()); - for (MavenProject mp : session.getAllProjects()) { - projectModels.put(mp.getBasedir().toPath(), mp.getOriginalModel()); - } - mvnConfig.setProjectModelProvider(projectModels::get); + mvnConfig.setProjectModelProvider(QuarkusBootstrapProvider.getProjectMap(session)::get); } final BootstrapMavenContext mvnCtx = new BootstrapMavenContext(mvnConfig); diff --git a/devtools/maven/src/main/java/io/quarkus/maven/QuarkusBootstrapProvider.java b/devtools/maven/src/main/java/io/quarkus/maven/QuarkusBootstrapProvider.java index f340b2048d4..2c4e876d7e1 100644 --- a/devtools/maven/src/main/java/io/quarkus/maven/QuarkusBootstrapProvider.java +++ b/devtools/maven/src/main/java/io/quarkus/maven/QuarkusBootstrapProvider.java @@ -16,6 +16,7 @@ import java.util.concurrent.ExecutionException; import org.apache.maven.artifact.Artifact; +import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Model; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.project.MavenProject; @@ -63,6 +64,16 @@ static ArtifactKey getProjectId(MavenProject project) { return ArtifactKey.ga(project.getGroupId(), project.getArtifactId()); } + static Map<Path, Model> getProjectMap(MavenSession session) { + final List<MavenProject> allProjects = session.getAllProjects(); + final Map<Path, Model> projectModels = new HashMap<>(allProjects.size()); + for (MavenProject mp : allProjects) { + mp.getOriginalModel().setPomFile(mp.getFile()); + projectModels.put(mp.getBasedir().toPath(), mp.getOriginalModel()); + } + return projectModels; + } + public RepositorySystem repositorySystem() { return repoSystem; } @@ -143,11 +154,7 @@ private MavenArtifactResolver artifactResolver(QuarkusBootstrapMojo mojo, Launch .setRemoteRepositories(mojo.remoteRepositories()) .setRemoteRepositoryManager(remoteRepoManager); if (mode == LaunchMode.DEVELOPMENT || mode == LaunchMode.TEST || isWorkspaceDiscovery(mojo)) { - final Map<Path, Model> projectModels = new HashMap<>(mojo.mavenSession().getAllProjects().size()); - for (MavenProject mp : mojo.mavenSession().getAllProjects()) { - projectModels.put(mp.getBasedir().toPath(), mp.getOriginalModel()); - } - builder.setWorkspaceDiscovery(true).setProjectModelProvider(projectModels::get); + builder.setWorkspaceDiscovery(true).setProjectModelProvider(getProjectMap(mojo.mavenSession())::get); } return builder.build(); } catch (BootstrapMavenException e) {
['devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java', 'devtools/maven/src/main/java/io/quarkus/maven/QuarkusBootstrapProvider.java']
{'.java': 2}
2
2
0
0
2
23,155,694
4,549,452
591,479
5,471
1,650
314
26
2
5,514
291
1,244
103
0
2
1970-01-01T00:27:45
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,336
quarkusio/quarkus/28565/28460
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/28460
https://github.com/quarkusio/quarkus/pull/28565
https://github.com/quarkusio/quarkus/pull/28565
1
fix
@Consumes ignored for sub-resource
### Describe the bug I have a main resource and a nested sub-resource which I want to be able PATCH (both of them) with "application/merge-json+patch" request content. Works for the main resource but @Consumes seems ignored in sub-resource. Maybe a bug or maybe something I don't quite understand ... ### Expected behavior Using my minimal-reproducer project : `curl -i -X PATCH -H "Content-Type: application/merge-json+patch" localhost:8080/main/1/sub/1 -d '{"test": true}'` Should return an HTTP 200. `curl -i -X PATCH -H "Content-Type: application/application/json" localhost:8080 -d '{"test": true}'` Should return an HTTP 415. ### Actual behavior Using my minimal-reproducer project : `curl -i -X PATCH -H "Content-Type: application/merge-json+patch" localhost:8080/main/1/sub/1 -d '{"test": true}'` Returns an HTTP 415. `curl -i -X PATCH -H "Content-Type: application/application/json" localhost:8080/main/1/sub/1 -d '{"test": true}'` Returns an HTTP 200. ### How to Reproduce? [minimal-reproducer.zip](https://github.com/quarkusio/quarkus/files/9741898/minimal-reproducer.zip) 1. Run the project with `./mvnw compile quarkus:dev` 2. Make a request with : `curl -i -X PATCH -H "Content-Type: application/merge-json+patch" localhost:8080/main/1/sub/1 -d '{"test": true}'` and `curl -i -X PATCH -H "Content-Type: application/application/json" localhost:8080/main/1/sub/1 -d '{"test": true}'` ### Output of `uname -a` or `ver` Linux myuser 5.15.0-48-generic #54~20.04.1-Ubuntu SMP Thu Sep 1 16:17:26 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux ### Output of `java -version` OpenJDK Runtime Environment (build 17+35-2724) OpenJDK 64-Bit Server VM (build 17+35-2724, mixed mode, sharing) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.13.1.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.6 (84538c9988a25aec085021c365c560670ad80f63) Maven home: /home/myuser/.m2/wrapper/dists/apache-maven-3.8.6-bin/67568434/apache-maven-3.8.6 Java version: 17, vendor: Oracle Corporation, runtime: /usr/lib/jvm/jdk-17 Default locale: en_US, platform encoding: UTF-8 OS name: "linux", version: "5.15.0-48-generic", arch: "amd64", family: "unix" ### Additional information I think @Consumes is ignored because header "application/json" works even if I define @Consumes(MediaType.TEXT_PLAIN) on sub-resource PATCH method. PATCH method for Main Resource is working fine. I am using quarkus-resteasy-reactive and quarkus-resteasy-reactive-jsonb. Maybe this is a JAX-RS/Resteasy issue, I don't know.
542e072afa051f630f6eb711a598c1786943fcb8
bfbfea6c47e3580095978a410e8b165328c76659
https://github.com/quarkusio/quarkus/compare/542e072afa051f630f6eb711a598c1786943fcb8...bfbfea6c47e3580095978a410e8b165328c76659
diff --git a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SimpleQuarkusRestTestCase.java b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SimpleQuarkusRestTestCase.java index 51ef18e647c..9dea4e08961 100644 --- a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SimpleQuarkusRestTestCase.java +++ b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SimpleQuarkusRestTestCase.java @@ -8,6 +8,7 @@ import java.util.function.Supplier; +import org.apache.http.HttpStatus; import org.hamcrest.Matchers; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; @@ -19,6 +20,7 @@ import io.quarkus.test.QuarkusUnitTest; import io.restassured.RestAssured; +import io.restassured.http.ContentType; import io.restassured.http.Headers; public class SimpleQuarkusRestTestCase { @@ -107,6 +109,12 @@ public void testSubResource() { .then().body(Matchers.equalTo("otherSub")); RestAssured.get("/simple/sub") .then().body(Matchers.equalTo("sub")); + + RestAssured.with() + .contentType(ContentType.JSON) + .body("{\\"test\\": true}") + .patch("/simple/sub/patch/text") + .then().statusCode(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE); } @Test diff --git a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SubResource.java b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SubResource.java index 00b37fdf42c..e1546a77d6f 100644 --- a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SubResource.java +++ b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SubResource.java @@ -1,7 +1,10 @@ package io.quarkus.resteasy.reactive.server.test.simple; +import javax.ws.rs.Consumes; import javax.ws.rs.GET; +import javax.ws.rs.PATCH; import javax.ws.rs.Path; +import javax.ws.rs.core.MediaType; public class SubResource { @@ -15,4 +18,11 @@ public String sub() { public String otherPath() { return "otherSub"; } + + @Path("patch/text") + @PATCH + @Consumes(MediaType.TEXT_PLAIN) + public String patchWithTextPlain(String patch) { + return "test-value: " + patch; + } } diff --git a/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/startup/RuntimeResourceDeployment.java b/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/startup/RuntimeResourceDeployment.java index 67118258789..1ca909d8bd1 100644 --- a/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/startup/RuntimeResourceDeployment.java +++ b/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/startup/RuntimeResourceDeployment.java @@ -312,8 +312,8 @@ public RuntimeResource buildResourceMethod(ResourceClass clazz, // we only need to parse the signature and create generic type when the declared type differs from the type genericType = TypeSignatureParser.parse(bodyParameter.signature); } - handlers.add(new RequestDeserializeHandler(typeClass, genericType, - consumesMediaTypes.isEmpty() ? null : consumesMediaTypes.get(0), serialisers, bodyParameterIndex)); + handlers.add(new RequestDeserializeHandler(typeClass, genericType, consumesMediaTypes, serialisers, + bodyParameterIndex)); } // given that we may inject form params in the endpoint we need to make sure we read the body before diff --git a/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/handlers/RequestDeserializeHandler.java b/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/handlers/RequestDeserializeHandler.java index 0203a0285b2..701946a95ca 100644 --- a/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/handlers/RequestDeserializeHandler.java +++ b/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/handlers/RequestDeserializeHandler.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.lang.annotation.Annotation; import java.lang.reflect.Type; +import java.util.Collections; import java.util.List; import javax.ws.rs.BadRequestException; @@ -17,6 +18,7 @@ import javax.ws.rs.ext.ReaderInterceptor; import org.jboss.logging.Logger; +import org.jboss.resteasy.reactive.common.util.MediaTypeHelper; import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext; import org.jboss.resteasy.reactive.server.core.ServerSerialisers; import org.jboss.resteasy.reactive.server.jaxrs.ReaderInterceptorContextImpl; @@ -29,30 +31,40 @@ public class RequestDeserializeHandler implements ServerRestHandler { private final Class<?> type; private final Type genericType; - private final MediaType mediaType; + private final List<MediaType> acceptableMediaTypes; private final ServerSerialisers serialisers; private final int parameterIndex; - public RequestDeserializeHandler(Class<?> type, Type genericType, MediaType mediaType, ServerSerialisers serialisers, + public RequestDeserializeHandler(Class<?> type, Type genericType, List<MediaType> acceptableMediaTypes, + ServerSerialisers serialisers, int parameterIndex) { this.type = type; this.genericType = genericType; - this.mediaType = mediaType; + this.acceptableMediaTypes = acceptableMediaTypes; this.serialisers = serialisers; this.parameterIndex = parameterIndex; } @Override public void handle(ResteasyReactiveRequestContext requestContext) throws Exception { - MediaType effectiveRequestType = mediaType; - String requestTypeString = requestContext.serverRequest().getRequestHeader(HttpHeaders.CONTENT_TYPE); - if (requestTypeString != null) { + MediaType effectiveRequestType = null; + Object requestType = requestContext.getHeader(HttpHeaders.CONTENT_TYPE, true); + if (requestType != null) { try { - effectiveRequestType = MediaType.valueOf(requestTypeString); + effectiveRequestType = MediaType.valueOf((String) requestType); } catch (Exception e) { throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).build()); } - } else if (effectiveRequestType == null) { + + // We need to verify media type for sub-resources, this mimics what is done in {@code ClassRoutingHandler} + if (MediaTypeHelper.getFirstMatch( + acceptableMediaTypes, + Collections.singletonList(effectiveRequestType)) == null) { + throw new NotSupportedException("The content-type header value did not match the value in @Consumes"); + } + } else if (!acceptableMediaTypes.isEmpty()) { + effectiveRequestType = acceptableMediaTypes.get(0); + } else { effectiveRequestType = MediaType.APPLICATION_OCTET_STREAM_TYPE; } List<MessageBodyReader<?>> readers = serialisers.findReaders(null, type, effectiveRequestType, RuntimeType.SERVER);
['extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SimpleQuarkusRestTestCase.java', 'extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SubResource.java', 'independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/startup/RuntimeResourceDeployment.java', 'independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/handlers/RequestDeserializeHandler.java']
{'.java': 4}
4
4
0
0
4
23,165,423
4,551,256
591,685
5,471
2,076
371
32
2
2,621
311
768
66
1
0
1970-01-01T00:27:45
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,399
quarkusio/quarkus/26570/26504
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/26504
https://github.com/quarkusio/quarkus/pull/26570
https://github.com/quarkusio/quarkus/pull/26570
1
fix
Container build with JIB do not start in remote-dev mode
### Describe the bug This is follow-up on https://github.com/quarkusio/quarkus/issues/26113 and I'm trying this on `main` as a fix as been provided. But in my case, it doesn't work at all now, the container can't start because of this exception : ```posh Exception in thread "main" java.nio.file.NoSuchFileException: /home/jboss/lib/deployment/deployment-class-path.dat at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92) at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111) at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:116) at java.base/sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:219) at java.base/java.nio.file.Files.newByteChannel(Files.java:371) at java.base/java.nio.file.Files.newByteChannel(Files.java:422) at java.base/java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:420) at java.base/java.nio.file.Files.newInputStream(Files.java:156) at io.quarkus.bootstrap.runner.DevModeMediator.doStart(DevModeMediator.java:39) at io.quarkus.bootstrap.runner.DevModeMediator.doDevMode(DevModeMediator.java:29) at io.quarkus.bootstrap.runner.QuarkusEntryPoint.doRun(QuarkusEntryPoint.java:45) at io.quarkus.bootstrap.runner.QuarkusEntryPoint.main(QuarkusEntryPoint.java:31) ``` ### Expected behavior remote-dev should work with images built with the JIB extension ### Actual behavior stacktrace provided above ### How to Reproduce? Create new app using 999-SNAPSHOT (main) with `quarkus-container-image-jib` extension and using this properties : ``` quarkus.package.type=mutable-jar quarkus.live-reload.password=secret ``` build the image and push it to a registry, then try to deploy it on a cluster with setting env var `QUARKUS_LAUNCH_DEVMODE=true` ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev main ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) mvn ### Additional information _No response_
63b93bf5de76135d7ec6d9d661419d62f0078458
485938f8650d8d580d6a39b9deb24bdcdeb9af54
https://github.com/quarkusio/quarkus/compare/63b93bf5de76135d7ec6d9d661419d62f0078458...485938f8650d8d580d6a39b9deb24bdcdeb9af54
diff --git a/extensions/container-image/container-image-jib/deployment/src/main/java/io/quarkus/container/image/jib/deployment/JibProcessor.java b/extensions/container-image/container-image-jib/deployment/src/main/java/io/quarkus/container/image/jib/deployment/JibProcessor.java index e54c923cafd..3e56a0aea0f 100644 --- a/extensions/container-image/container-image-jib/deployment/src/main/java/io/quarkus/container/image/jib/deployment/JibProcessor.java +++ b/extensions/container-image/container-image-jib/deployment/src/main/java/io/quarkus/container/image/jib/deployment/JibProcessor.java @@ -485,8 +485,7 @@ private JibContainerBuilder createContainerBuilderFromFastJar(String baseJvmImag Path deploymentPath = componentsPath.resolve(JarResultBuildStep.LIB) .resolve(JarResultBuildStep.DEPLOYMENT_LIB); addLayer(jibContainerBuilder, Collections.singletonList(deploymentPath), - workDirInContainer.resolve(JarResultBuildStep.LIB) - .resolve(JarResultBuildStep.DEPLOYMENT_LIB), + workDirInContainer.resolve(JarResultBuildStep.LIB), "fast-jar-deployment-libs", true, now); }
['extensions/container-image/container-image-jib/deployment/src/main/java/io/quarkus/container/image/jib/deployment/JibProcessor.java']
{'.java': 1}
1
1
0
0
1
22,014,569
4,310,314
561,611
5,238
242
39
3
1
2,197
184
540
65
1
2
1970-01-01T00:27:37
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,400
quarkusio/quarkus/26511/26502
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/26502
https://github.com/quarkusio/quarkus/pull/26511
https://github.com/quarkusio/quarkus/pull/26511
1
fix
Dependency Graph Walk leads to StackOverflowError
### Describe the bug Our `ConsumerPactTest` throws `java.lang.StackOverflowError`. I tracked this issue down to the #26411. ### Expected behavior No stack issues. ### Actual behavior _No response_ ### How to Reproduce? Reproducer: Steps to reproduce the behavior: 1. `git clone https://github.com/quarkus-qe/quarkus-test-suite` 2. `cd quarkus-test-suite/test-tooling/pact` 3. `mvn clean verify` ### Output of `uname -a` or `ver` Linux fedora 5.18.5-200.fc36.x86_64 #1 SMP PREEMPT_DYNAMIC Thu Jun 16 14:51:11 UTC 2022 x86_64 x86_64 x86_64 GNU/Lin ### Output of `java -version` openjdk version "17.0.3" 2022-04-19 OpenJDK Runtime Environment GraalVM CE 22.1.0 (build 17.0.3+7-jvmci-22.1-b06) OpenJDK 64-Bit Server VM GraalVM CE 22.1.0 (build 17.0.3+7-jvmci-22.1-b06, mixed mode, sharing) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 999-SNAPSHOT; HEAD d94c5a1d0a55787a2349cbb103a1f42771d23c0a ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.6 (84538c9988a25aec085021c365c560670ad80f63) ### Additional information _No response_
3bba499cd898cf966756e44fa96d2b5e40778b88
46fcb638ad063384e946b84f01233c99c9fc75fa
https://github.com/quarkusio/quarkus/compare/3bba499cd898cf966756e44fa96d2b5e40778b88...46fcb638ad063384e946b84f01233c99c9fc75fa
diff --git a/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/ApplicationDependencyTreeResolver.java b/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/ApplicationDependencyTreeResolver.java index 3f830e35f70..6a5121dee0e 100644 --- a/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/ApplicationDependencyTreeResolver.java +++ b/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/ApplicationDependencyTreeResolver.java @@ -286,13 +286,14 @@ private DependencyNode resolveRuntimeDeps(CollectRequest request) throws AppMode @Override public DependencyNode transformGraph(DependencyNode node, DependencyGraphTransformationContext context) throws RepositoryException { + final Set<ArtifactKey> visited = new HashSet<>(); for (DependencyNode c : node.getChildren()) { - walk(c); + walk(c, visited); } return resolver.getSession().getDependencyGraphTransformer().transformGraph(node, context); } - private void walk(DependencyNode node) { + private void walk(DependencyNode node, Set<ArtifactKey> visited) { if (node.getChildren().isEmpty()) { return; } @@ -300,8 +301,13 @@ private void walk(DependencyNode node) { .computeIfAbsent(DependencyUtils.getCoords(node.getArtifact()), k -> new HashSet<>(node.getChildren().size())); for (DependencyNode c : node.getChildren()) { - deps.add(getKey(c.getArtifact())); - walk(c); + final ArtifactKey key = getKey(c.getArtifact()); + if (!visited.add(key)) { + continue; + } + deps.add(key); + walk(c, visited); + visited.remove(key); } } });
['independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/ApplicationDependencyTreeResolver.java']
{'.java': 1}
1
1
0
0
1
21,974,620
4,303,058
560,717
5,231
702
102
14
1
1,172
138
393
44
1
0
1970-01-01T00:27:36
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,250
quarkusio/quarkus/31472/31469
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/31469
https://github.com/quarkusio/quarkus/pull/31472
https://github.com/quarkusio/quarkus/pull/31472
1
fixes
Warnings about lack of "Hibernate Validator", despite no validation annotations being used
### Describe the bug I have an application, which uses `quartz`,`agroal` and `hibernate-panache` and saves data into DB on regular intervals. After update to the latest 999-SNAPSHOT(1d45952917c72a12eed6b9351f6ecdca813637a8) it now shows multiple warnings about `jakarta.validation.NoProviderFoundException` being thrown. The application doesn't use any code from `javax.validation` or `jakarta.validation` packages. Adding `quarkus-hibernate-validator` solves this problem. Nothing of sorts is mentioned in the migration guide[1]. [1] https://docs.jboss.org/hibernate/orm/6.0/migration-guide/migration-guide.html ### Expected behavior The application should work without warnings, and should not require `quarkus-hibernate-validator` ### Actual behavior ``` (JPA Startup Thread) Error calling `jakarta.validation.Validation#buildDefaultValidatorFactory`: jakarta.validation.NoProviderFoundException: Unable to create a Configuration, because no Jakarta Bean Validation provider could be found. Add a provider like Hibernate Validator (RI) to your classpath. at jakarta.validation.Validation$GenericBootstrapImpl.configure(Validation.java:291) at jakarta.validation.Validation.buildDefaultValidatorFactory(Validation.java:103) at org.hibernate.boot.beanvalidation.TypeSafeActivator.getValidatorFactory(TypeSafeActivator.java:483) at org.hibernate.boot.beanvalidation.TypeSafeActivator.activate(TypeSafeActivator.java:83) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at org.hibernate.boot.beanvalidation.BeanValidationIntegrator.integrate(BeanValidationIntegrator.java:140) at org.hibernate.internal.SessionFactoryImpl.integrate(SessionFactoryImpl.java:451) at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:247) at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:200) at io.quarkus.hibernate.orm.runtime.boot.FastBootEntityManagerFactoryBuilder.build(FastBootEntityManagerFactoryBuilder.java:78) at io.quarkus.hibernate.orm.runtime.FastBootHibernatePersistenceProvider.createEntityManagerFactory(FastBootHibernatePersistenceProvider.java:73) at jakarta.persistence.Persistence.createEntityManagerFactory(Persistence.java:80) at jakarta.persistence.Persistence.createEntityManagerFactory(Persistence.java:55) at io.quarkus.hibernate.orm.runtime.JPAConfig$LazyPersistenceUnit.get(JPAConfig.java:167) at io.quarkus.hibernate.orm.runtime.JPAConfig$1.run(JPAConfig.java:68) at java.base/java.lang.Thread.run(Thread.java:833) ``` ### How to Reproduce? 1. ` git clone git@github.com:fedinskiy/beefy-scenarios.git -b reproducer/hibernate-6` 2. `beefy-scenarios/017-quartz-cluster` 3. `mvn clean verify #exceptions in logs` 4. add ``` <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-hibernate-validator</artifactId> </dependency>``` to pom.xml 5. Run `mvn clean verify # no exceptions in app logs ` 6. If command in step 3 uses ` -Dquarkus.platform.version=3.0.0.Alpha4`, then the app works even without `hibernate-validator` The app doesn't use any validation: `find src/ | xargs grep 'validation'` ### Output of `uname -a` or `ver` 6.0.18-300.fc37.x86_64 ### Output of `java -version` 17.0.5, vendor: GraalVM Community ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 1d45952917c72a12eed6b9351f6ecdca813637a8 ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.6 (84538c9988a25aec085021c365c560670ad80f63) ### Additional information Probably related to https://github.com/quarkusio/quarkus/pull/31235
cf9223e422079664a79e570bbb1e5d2e7b86ba83
bc142cafa61977994c732fed4f9068d3cb8c0758
https://github.com/quarkusio/quarkus/compare/cf9223e422079664a79e570bbb1e5d2e7b86ba83...bc142cafa61977994c732fed4f9068d3cb8c0758
diff --git a/extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/HibernateLogFilterBuildStep.java b/extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/HibernateLogFilterBuildStep.java index b5549222fa7..9014034a299 100644 --- a/extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/HibernateLogFilterBuildStep.java +++ b/extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/HibernateLogFilterBuildStep.java @@ -27,5 +27,12 @@ void setupLogFilters(BuildProducer<LogCleanupFilterBuildItem> filters) { filters.produce(new LogCleanupFilterBuildItem("org.hibernate.jpa.internal.util.LogHelper", "HHH000204")); filters.produce(new LogCleanupFilterBuildItem("SQL dialect", "HHH000400")); filters.produce(new LogCleanupFilterBuildItem("org.hibernate.orm.beans", "HHH10005002", "HHH10005004")); + // Disable info logging for Bean Validation implementation not being present: + // it is perfectly valid when set to auto. The error is logged in the caller if it has to be logged. + filters.produce(new LogCleanupFilterBuildItem("org.hibernate.boot.beanvalidation.TypeSafeActivator", + "Error calling ")); + // Silence incubating settings warnings as we will use some for compatibility + filters.produce(new LogCleanupFilterBuildItem("org.hibernate.orm.incubating", + "HHH90006001")); } }
['extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/HibernateLogFilterBuildStep.java']
{'.java': 1}
1
1
0
0
1
25,049,712
4,945,586
638,432
5,856
551
106
7
1
4,002
276
957
73
2
2
1970-01-01T00:27:57
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,251
quarkusio/quarkus/31436/31406
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/31406
https://github.com/quarkusio/quarkus/pull/31436
https://github.com/quarkusio/quarkus/pull/31436
1
fix
@ServerExceptionMapper doesn't support multiple exception types
### Describe the bug ``` @ServerExceptionMapper(value = {MyExceptionOne.class, MyExceptionTwo.class}) public Uni<Response> mapException(RuntimeException e) { return Uni.createFrom().item(() -> Response.status(Response.Status.CONFLICT) .entity(Map.of(MESSAGE, message)) .build();); } ``` ### Expected behavior multiple exception classes are supported ### Actual behavior ``` java.lang.RuntimeException: java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors [error]: Build step io.quarkus.resteasy.reactive.server.deployment.ResteasyReactiveScanningProcessor#handleCustomAnnotatedMethods threw an exception: java.lang.RuntimeException: Parameter 'e' of method 'mapException of class '...' is not allowed ``` ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` Darwin RDU-W4HVVTY7VT 21.4.0 Darwin Kernel Version 21.4.0 ### Output of `java -version` openjdk version "17.0.5" 2022-10-18 OpenJDK Runtime Environment GraalVM CE 22.3.0 (build 17.0.5+8-jvmci-22.3-b08) OpenJDK 64-Bit Server VM GraalVM CE 22.3.0 (build 17.0.5+8-jvmci-22.3-b08, mixed mode, sharing) ### GraalVM version (if different from Java) openjdk version "17.0.5" 2022-10-18 OpenJDK Runtime Environment GraalVM CE 22.3.0 (build 17.0.5+8-jvmci-22.3-b08) OpenJDK 64-Bit Server VM GraalVM CE 22.3.0 (build 17.0.5+8-jvmci-22.3-b08, mixed mode, sharing) ### Quarkus version or git rev 2.16.1.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) maven ### Additional information I see that this issue was fixed in https://github.com/quarkusio/quarkus/issues/20202, but it appeared again
4bee348b17430345c927e9c3e8eeec5ed08b5f4e
efa3e58fee290f226978a67e9e9ba8c3ab5eb670
https://github.com/quarkusio/quarkus/compare/4bee348b17430345c927e9c3e8eeec5ed08b5f4e...efa3e58fee290f226978a67e9e9ba8c3ab5eb670
diff --git a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/customexceptions/UniExceptionMapper.java b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/customexceptions/UniExceptionMapper.java index ee5f1e771f5..d86e45824db 100644 --- a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/customexceptions/UniExceptionMapper.java +++ b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/customexceptions/UniExceptionMapper.java @@ -9,7 +9,7 @@ public class UniExceptionMapper { @ServerExceptionMapper({ UniException.class, OtherUniException.class }) - Uni<Response> handleUni(Throwable t) { + Uni<Response> handleUni(UniException t) { return Uni.createFrom().deferred(() -> Uni.createFrom().item(Response.status(413).build())); } diff --git a/independent-projects/resteasy-reactive/server/processor/src/main/java/org/jboss/resteasy/reactive/server/processor/generation/exceptionmappers/ServerExceptionMapperGenerator.java b/independent-projects/resteasy-reactive/server/processor/src/main/java/org/jboss/resteasy/reactive/server/processor/generation/exceptionmappers/ServerExceptionMapperGenerator.java index 878d38bfada..2782c62bcbe 100644 --- a/independent-projects/resteasy-reactive/server/processor/src/main/java/org/jboss/resteasy/reactive/server/processor/generation/exceptionmappers/ServerExceptionMapperGenerator.java +++ b/independent-projects/resteasy-reactive/server/processor/src/main/java/org/jboss/resteasy/reactive/server/processor/generation/exceptionmappers/ServerExceptionMapperGenerator.java @@ -18,8 +18,8 @@ import static org.jboss.resteasy.reactive.server.processor.util.ResteasyReactiveServerDotNames.SIMPLIFIED_RESOURCE_INFO; import java.lang.reflect.Modifier; -import java.util.Arrays; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -123,7 +123,7 @@ public static Map<String, String> generatePerClassMapper(MethodInfo targetMethod Map<String, String> result = new HashMap<>(); boolean handlesMultipleExceptions = handledExceptionTypes.length > 1; - boolean handledContainsThrowable = Arrays.stream(handledExceptionTypes).anyMatch(t -> t.name().equals(THROWABLE)); + Set<String> commonHierarchyOfExceptions = getCommonHierarchyOfExceptions(handledExceptionTypes); for (Type handledExceptionType : handledExceptionTypes) { String generatedClassName = getGeneratedClassName(targetMethod, handledExceptionType); @@ -155,7 +155,7 @@ public static Map<String, String> generatePerClassMapper(MethodInfo targetMethod // RESTEasy Reactive toResponse(...) method generateRRResponse(targetMethod, targetClass, handledExceptionType, cc, rrToResponseDescriptor, - returnType, handlesMultipleExceptions, handledContainsThrowable, + returnType, handlesMultipleExceptions, commonHierarchyOfExceptions, (method, contextHandle) -> { ResultHandle endpointInstanceHandle = method.invokeVirtualMethod( ofMethod(ResteasyReactiveRequestContext.class, "getEndpointInstance", Object.class), @@ -173,7 +173,7 @@ public static Map<String, String> generatePerClassMapper(MethodInfo targetMethod // RESTEasy Reactive asyncResponse(...) method generateRRUniResponse(targetMethod, targetClass, handledExceptionType, cc, rrAsyncResponseDescriptor, - returnType, handlesMultipleExceptions, handledContainsThrowable, + returnType, handlesMultipleExceptions, commonHierarchyOfExceptions, (method, contextHandle) -> { ResultHandle endpointInstanceHandle = method.invokeVirtualMethod( ofMethod(ResteasyReactiveRequestContext.class, "getEndpointInstance", Object.class), @@ -251,7 +251,7 @@ public static Map<String, String> generateGlobalMapper(MethodInfo targetMethod, Map<String, String> result = new HashMap<>(); boolean handlesMultipleExceptions = handledExceptionTypes.length > 1; - boolean handledContainsThrowable = Arrays.stream(handledExceptionTypes).anyMatch(t -> t.name().equals(THROWABLE)); + Set<String> commonHierarchyOfExceptions = getCommonHierarchyOfExceptions(handledExceptionTypes); for (Type handledExceptionType : handledExceptionTypes) { String generatedClassName = getGeneratedClassName(targetMethod, handledExceptionType); @@ -311,7 +311,7 @@ public static Map<String, String> generateGlobalMapper(MethodInfo targetMethod, // RESTEasy Reactive toResponse(...) method generateRRResponse(targetMethod, targetClass, handledExceptionType, cc, rrToResponseDescriptor, - returnType, handlesMultipleExceptions, handledContainsThrowable, + returnType, handlesMultipleExceptions, commonHierarchyOfExceptions, (method, contextHandle) -> method.readInstanceField(delegateField, method.getThis()), unwrappableTypes); } else if (returnType == ReturnType.UNI_RESPONSE || returnType == ReturnType.UNI_REST_RESPONSE) { @@ -325,7 +325,7 @@ public static Map<String, String> generateGlobalMapper(MethodInfo targetMethod, // RESTEasy Reactive asyncResponse(...) method generateRRUniResponse(targetMethod, targetClass, handledExceptionType, cc, rrAsyncResponseDescriptor, - returnType, handlesMultipleExceptions, handledContainsThrowable, + returnType, handlesMultipleExceptions, commonHierarchyOfExceptions, (method, contextHandle) -> method.readInstanceField(delegateField, method.getThis()), unwrappableTypes); } else { @@ -352,20 +352,15 @@ private static Type[] getHandledExceptionTypes(MethodInfo targetMethod) { List<Type> methodParameters = targetMethod.parameterTypes(); for (Type methodParameter : methodParameters) { if (methodParameter.kind() == Type.Kind.CLASS) { - try { - Class<?> methodParameterClass = Class.forName(methodParameter.name().toString(), false, - Thread.currentThread().getContextClassLoader()); - if (Throwable.class.isAssignableFrom(methodParameterClass)) { - if (deducedHandledExceptionType != null) { - throw new IllegalArgumentException( - "Multiple method parameters found that extend 'Throwable'. When using '@ServerExceptionMapper', only one parameter can be of type 'Throwable'. Offending method is '" - + targetMethod.name() + "' of class '" - + targetMethod.declaringClass().name().toString() + "'"); - } - deducedHandledExceptionType = methodParameter; + Class<?> methodParameterClass = getClassByName(methodParameter.name().toString()); + if (methodParameterClass != null && Throwable.class.isAssignableFrom(methodParameterClass)) { + if (deducedHandledExceptionType != null) { + throw new IllegalArgumentException( + "Multiple method parameters found that extend 'Throwable'. When using '@ServerExceptionMapper', only one parameter can be of type 'Throwable'. Offending method is '" + + targetMethod.name() + "' of class '" + + targetMethod.declaringClass().name().toString() + "'"); } - } catch (ClassNotFoundException ignored) { - + deducedHandledExceptionType = methodParameter; } } } @@ -377,6 +372,36 @@ private static Type[] getHandledExceptionTypes(MethodInfo targetMethod) { return new Type[] { deducedHandledExceptionType }; } + private static Set<String> getCommonHierarchyOfExceptions(Type[] handledExceptions) { + Set<String> commonHierarchy = new HashSet<>(); + boolean first = true; + for (Type handledException : handledExceptions) { + Class<?> handledExceptionClass = getClassByName(handledException.name().toString()); + while (handledExceptionClass != null && !handledExceptionClass.equals(Throwable.class)) { + String handledExceptionClassName = handledExceptionClass.getName(); + if (first) { + commonHierarchy.add(handledExceptionClassName); + } else if (!commonHierarchy.contains(handledExceptionClassName)) { + commonHierarchy.remove(handledExceptionClassName); + } + + handledExceptionClass = handledExceptionClass.getSuperclass(); + } + + first = false; + } + + return commonHierarchy; + } + + private static Class<?> getClassByName(String className) { + try { + return Class.forName(className, false, Thread.currentThread().getContextClassLoader()); + } catch (ClassNotFoundException ignored) { + return null; + } + } + private static MethodDescriptor toResponseDescriptor(Type handledExceptionType, String generatedClassName) { return ofMethod(generatedClassName, "toResponse", Response.class.getName(), @@ -432,7 +457,7 @@ private static void generateRRResponseBridge(Type handledExceptionType, ClassCre private static void generateRRResponse(MethodInfo targetMethod, ClassInfo targetClass, Type handledExceptionType, ClassCreator cc, MethodDescriptor rrToResponseDescriptor, - ReturnType returnType, boolean handlesMultipleExceptions, boolean handledContainsThrowable, + ReturnType returnType, boolean handlesMultipleExceptions, Set<String> commonHierarchyOfExceptions, BiFunction<MethodCreator, ResultHandle, ResultHandle> targetInstanceHandleCreator, Set<DotName> unwrappableTypes) { MethodCreator mc = cc.getMethodCreator(rrToResponseDescriptor); ResultHandle exceptionHandle = mc.getMethodParam(0); @@ -452,7 +477,7 @@ private static void generateRRResponse(MethodInfo targetMethod, ClassInfo target } else { TargetMethodParamsInfo targetMethodParamsInfo = getTargetMethodParamsInfo(targetMethod, targetClass, handledExceptionType, mc, exceptionHandle, contextHandle, handlesMultipleExceptions, - handledContainsThrowable, unwrappableTypes); + commonHierarchyOfExceptions, unwrappableTypes); ResultHandle resultHandle = mc.invokeVirtualMethod( ofMethod(targetClass.name().toString(), targetMethod.name(), targetMethod.returnType().name().toString(), targetMethodParamsInfo.getTypes()), @@ -479,7 +504,7 @@ private static void generateRRUniResponseBridge(Type handledExceptionType, Class private static void generateRRUniResponse(MethodInfo targetMethod, ClassInfo targetClass, Type handledExceptionType, ClassCreator cc, MethodDescriptor rrAsyncResponseDescriptor, - ReturnType returnType, boolean handlesMultipleExceptions, boolean handledContainsThrowable, + ReturnType returnType, boolean handlesMultipleExceptions, Set<String> commonHierarchyOfExceptions, BiFunction<MethodCreator, ResultHandle, ResultHandle> targetInstanceHandleCreator, Set<DotName> unwrappableTypes) { MethodCreator mc = cc.getMethodCreator(rrAsyncResponseDescriptor); ResultHandle exceptionHandle = mc.getMethodParam(0); @@ -498,7 +523,7 @@ private static void generateRRUniResponse(MethodInfo targetMethod, ClassInfo tar } else { TargetMethodParamsInfo targetMethodParamsInfo = getTargetMethodParamsInfo(targetMethod, targetClass, handledExceptionType, mc, exceptionHandle, contextHandle, handlesMultipleExceptions, - handledContainsThrowable, unwrappableTypes); + commonHierarchyOfExceptions, unwrappableTypes); uniHandle = mc.invokeVirtualMethod( ofMethod(targetClass.name().toString(), targetMethod.name(), Uni.class.getName(), targetMethodParamsInfo.getTypes()), @@ -512,7 +537,7 @@ private static void generateRRUniResponse(MethodInfo targetMethod, ClassInfo tar private static TargetMethodParamsInfo getTargetMethodParamsInfo(MethodInfo targetMethod, ClassInfo targetClass, Type handledExceptionType, MethodCreator mc, ResultHandle exceptionHandle, ResultHandle contextHandle, - boolean handlesMultipleExceptions, boolean handledContainsThrowable, Set<DotName> unwrappableTypes) { + boolean handlesMultipleExceptions, Set<String> commonHierarchyOfExceptions, Set<DotName> unwrappableTypes) { List<Type> parameters = targetMethod.parameterTypes(); ResultHandle[] targetMethodParamHandles = new ResultHandle[parameters.size()]; String[] parameterTypes = new String[parameters.size()]; @@ -522,39 +547,19 @@ private static TargetMethodParamsInfo getTargetMethodParamsInfo(MethodInfo targe DotName paramDotName = parameter.name(); parameterTypes[i] = paramDotName.toString(); String parameterName = targetMethod.parameterName(i); - if (paramDotName.equals(handledExceptionType.name())) { - if (handlesMultipleExceptions) { + if (paramDotName.equals(THROWABLE)) { + targetMethodParamHandles[i] = exceptionHandle; + } else if (paramDotName.equals(handledExceptionType.name())) { + if (handlesMultipleExceptions && !commonHierarchyOfExceptions.contains(paramDotName.toString())) { throw new RuntimeException("Parameter '" + parameterName + "' of method '" + targetMethod.name() + " of class '" + targetClass.name() + "' cannot be of type '" + handledExceptionType.name() + "' because the method handles multiple exceptions. You can use '" - + (handledContainsThrowable ? Throwable.class.getName() : Exception.class.getName()) - + "' instead."); + + Throwable.class.getName() + "' instead."); } else { targetMethodParamHandles[i] = exceptionHandle; } - } else if (paramDotName.equals(THROWABLE)) { + } else if (commonHierarchyOfExceptions.contains(paramDotName.toString())) { targetMethodParamHandles[i] = exceptionHandle; - } else if (paramDotName.equals(EXCEPTION)) { - if (handlesMultipleExceptions) { - if (handledContainsThrowable) { - throw new RuntimeException("Parameter '" + parameterName + "' of method '" + targetMethod.name() - + " of class '" + targetClass.name() - + "' cannot be of type '" + handledExceptionType.name() - + "' because the method handles multiple exceptions. You can use '" + Exception.class.getName() - + "' instead."); - } else { - targetMethodParamHandles[i] = exceptionHandle; - } - } else { - if (handledContainsThrowable) { - throw new RuntimeException("Parameter '" + parameterName + "' of method '" + targetMethod.name() - + " of class '" + targetClass.name() - + "' cannot be of type '" + handledExceptionType.name() + "'. You can use '" - + Throwable.class.getName() + "' instead."); - } else { - targetMethodParamHandles[i] = exceptionHandle; - } - } } else if (paramDotName.equals(handledExceptionType.name())) { targetMethodParamHandles[i] = exceptionHandle; } else if (CONTAINER_REQUEST_CONTEXT.equals(paramDotName)
['independent-projects/resteasy-reactive/server/processor/src/main/java/org/jboss/resteasy/reactive/server/processor/generation/exceptionmappers/ServerExceptionMapperGenerator.java', 'extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/customexceptions/UniExceptionMapper.java']
{'.java': 2}
2
2
0
0
2
25,047,267
4,944,949
638,342
5,854
7,389
1,155
107
1
1,716
180
507
50
1
2
1970-01-01T00:27:57
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,252
quarkusio/quarkus/31422/26152
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/26152
https://github.com/quarkusio/quarkus/pull/31422
https://github.com/quarkusio/quarkus/pull/31422
1
fix
Resteasy Reactive: ContextResolver<ObjectMapper> not used
### Describe the bug When creating a RestClient with a `ContextResolver<ObjectMapper>` registered, this ContextResolver is never used and thus the wrong ObjectMapper (via CDI) is used. Other implementation approaches would be fine as well, but nothing seems to get this behaviour working. Multiple different ObjectMappers in the application do not seem to be supported. ### Expected behavior The ObjectMapper returned by a class that implements `ContextResolver<ObjectMapper>` used via `RestClientBuilder#register(Object)` is used in the given RestClient and only there. Multiple RestClients can use multiple different ObjectMappers. ### Actual behavior The ObjectMapper of the registered `ContextResolver` is not used at all. Instead an application scoped ObjectMapper bean is used in all RestClients. ### How to Reproduce? Run the following test class. The test should pass if matching the expected behaviour. ```java @QuarkusTest class MyClientTest { MyClient clientAllowsUnknown; MyClient clientDisallowsUnknown; WireMockServer wireMockServer = getWireMockServer(); @BeforeEach void setUp() throws MalformedURLException { wireMockServer.resetAll(); clientAllowsUnknown = RestClientBuilder.newBuilder() .baseUrl(new URL(wireMockServer.baseUrl())) .register(ClientObjectMapperUnknown.class) .build(MyClient.class); clientDisallowsUnknown = RestClientBuilder.newBuilder() .baseUrl(new URL(wireMockServer.baseUrl())) .register(ClientObjectMapperNoUnknown.class) .build(MyClient.class); } @Test void something_withAdditionalIgnoredProperties() { var json = "{ \\"value\\": \\"someValue\\", \\"secondValue\\": \\"toBeIgnored\\" }"; wireMockServer.stubFor( WireMock.get(WireMock.urlMatching("/something")) .willReturn(okJson(json))); var result = clientAllowsUnknown.something().await().indefinitely(); // FAIL_ON_UNKNOWN_PROPERTIES disabled assertThatCode(() -> new ClientObjectMapperUnknown().getContext(ObjectMapper.class).readValue(json, Something.class)) .doesNotThrowAnyException(); assertThat(result).isEqualTo(Something.builder().withValue("someValue").build()); // FAIL_ON_UNKNOWN_PROPERTIES enabled assertThatThrownBy(() -> new ClientObjectMapperNoUnknown().getContext(ObjectMapper.class).readValue(json, Something.class)) .isInstanceOf(JsonProcessingException.class); assertThatThrownBy(() -> clientDisallowsUnknown.something().await().indefinitely()) .isInstanceOf(JsonProcessingException.class); } @Path("/something") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public interface MyClient { @GET Uni<Something> something(); } @Value @Builder(toBuilder = true, setterPrefix = "with") @Jacksonized public static class Something { String value; } public static class ClientObjectMapperUnknown implements ContextResolver<ObjectMapper> { @Override public ObjectMapper getContext(Class<?> type) { return new ObjectMapper() .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); } } public static class ClientObjectMapperNoUnknown implements ContextResolver<ObjectMapper> { @Override public ObjectMapper getContext(Class<?> type) { return new ObjectMapper() .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .enable(SerializationFeature.FAIL_ON_EMPTY_BEANS); } } public static WireMockServer getWireMockServer() { var wireMockServer = new WireMockServer(options().port(getAvailableTcpPort(20000, 22000))); wireMockServer.start(); return wireMockServer; } public static int getAvailableTcpPort(int min, int max) { var ports = IntStream.range(min, max).boxed().collect(Collectors.toList()); Collections.shuffle(ports); // shuffle to get a random order and reduce the probability a port is already in use for (var port : ports) { try (ServerSocket serverSocket = new ServerSocket(port)) { return serverSocket.getLocalPort(); } catch (IOException e) { // try next } } throw new IllegalStateException(MessageFormat.format("Could not find a free TCP port in range {0}:{1}.", min, max)); } } ``` With ```xml <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-rest-client-reactive-jackson</artifactId> </dependency> <dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-resteasy-reactive</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> </dependency> ``` ### Output of `uname -a` or `ver` Darwin M042112251A.local 20.6.0 Darwin Kernel Version 20.6.0: Wed Nov 10 22:23:07 PST 2021; root:xnu-7195.141.14~1/RELEASE_X86_64 x86_64 ### Output of `java -version` openjdk version "11.0.14.1" 2022-02-08 OpenJDK Runtime Environment Temurin-11.0.14.1+1 (build 11.0.14.1+1) OpenJDK 64-Bit Server VM Temurin-11.0.14.1+1 (build 11.0.14.1+1, mixed mode) ### GraalVM version (if different from Java) not used ### Quarkus version or git rev 2.8.0.Final, 2.9.2.Final, 2.10.0.CR1 ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f) ### Additional information _No response_
88cfc7d6df4daf9a658fb723ea262a88285996bb
e05af28364c3bea101a8a8ee16e33d3321d2470f
https://github.com/quarkusio/quarkus/compare/88cfc7d6df4daf9a658fb723ea262a88285996bb...e05af28364c3bea101a8a8ee16e33d3321d2470f
diff --git a/extensions/resteasy-reactive/rest-client-reactive-jackson/runtime/src/main/java/io/quarkus/rest/client/reactive/jackson/runtime/serialisers/ClientJacksonMessageBodyWriter.java b/extensions/resteasy-reactive/rest-client-reactive-jackson/runtime/src/main/java/io/quarkus/rest/client/reactive/jackson/runtime/serialisers/ClientJacksonMessageBodyWriter.java index 1ba281fc8c3..98a52d39391 100644 --- a/extensions/resteasy-reactive/rest-client-reactive-jackson/runtime/src/main/java/io/quarkus/rest/client/reactive/jackson/runtime/serialisers/ClientJacksonMessageBodyWriter.java +++ b/extensions/resteasy-reactive/rest-client-reactive-jackson/runtime/src/main/java/io/quarkus/rest/client/reactive/jackson/runtime/serialisers/ClientJacksonMessageBodyWriter.java @@ -49,7 +49,7 @@ public void writeTo(Object o, Class<?> type, Type genericType, Annotation[] anno @Override public void handle(RestClientRequestContext requestContext) throws Exception { - this.context = context; + this.context = requestContext; } protected ObjectWriter getEffectiveWriter() { diff --git a/integration-tests/rest-client-reactive/src/test/java/io/quarkus/it/rest/client/ClientWithCustomObjectMapperTest.java b/integration-tests/rest-client-reactive/src/test/java/io/quarkus/it/rest/client/ClientWithCustomObjectMapperTest.java index b4a80c3a955..f925704718c 100644 --- a/integration-tests/rest-client-reactive/src/test/java/io/quarkus/it/rest/client/ClientWithCustomObjectMapperTest.java +++ b/integration-tests/rest-client-reactive/src/test/java/io/quarkus/it/rest/client/ClientWithCustomObjectMapperTest.java @@ -1,5 +1,6 @@ package io.quarkus.it.rest.client; +import static com.github.tomakehurst.wiremock.client.WireMock.ok; import static com.github.tomakehurst.wiremock.client.WireMock.okJson; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; import static org.assertj.core.api.Assertions.assertThat; @@ -8,9 +9,11 @@ import java.net.MalformedURLException; import java.net.URL; import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; @@ -40,6 +43,8 @@ public class ClientWithCustomObjectMapperTest { @BeforeEach public void setUp() throws MalformedURLException { + ClientObjectMapperUnknown.USED.set(false); + ClientObjectMapperNoUnknown.USED.set(false); wireMockServer = new WireMockServer(options().port(20001)); wireMockServer.start(); @@ -60,10 +65,10 @@ public void tearDown() { } @Test - void testCustomObjectMappersShouldBeUsed() { + void testCustomObjectMappersShouldBeUsedInReader() { var json = "{ \\"value\\": \\"someValue\\", \\"secondValue\\": \\"toBeIgnored\\" }"; wireMockServer.stubFor( - WireMock.get(WireMock.urlMatching("/get")) + WireMock.get(WireMock.urlMatching("/client")) .willReturn(okJson(json))); // FAIL_ON_UNKNOWN_PROPERTIES disabled @@ -75,12 +80,25 @@ void testCustomObjectMappersShouldBeUsed() { .isInstanceOf(ClientWebApplicationException.class); } - @Path("/get") + @Test + void testCustomObjectMappersShouldBeUsedInWriter() { + wireMockServer.stubFor( + WireMock.post(WireMock.urlMatching("/client")) + .willReturn(ok())); + + clientDisallowsUnknown.post(new Request()); + assertThat(ClientObjectMapperNoUnknown.USED.get()).isTrue(); + } + + @Path("/client") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public interface MyClient { @GET Uni<Request> get(); + + @POST + void post(Request request); } public static class Request { @@ -119,8 +137,11 @@ public int hashCode() { } public static class ClientObjectMapperUnknown implements ContextResolver<ObjectMapper> { + static final AtomicBoolean USED = new AtomicBoolean(false); + @Override public ObjectMapper getContext(Class<?> type) { + USED.set(true); return new ObjectMapper() .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); @@ -128,8 +149,12 @@ public ObjectMapper getContext(Class<?> type) { } public static class ClientObjectMapperNoUnknown implements ContextResolver<ObjectMapper> { + + static final AtomicBoolean USED = new AtomicBoolean(false); + @Override public ObjectMapper getContext(Class<?> type) { + USED.set(true); return new ObjectMapper() .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .enable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
['extensions/resteasy-reactive/rest-client-reactive-jackson/runtime/src/main/java/io/quarkus/rest/client/reactive/jackson/runtime/serialisers/ClientJacksonMessageBodyWriter.java', 'integration-tests/rest-client-reactive/src/test/java/io/quarkus/it/rest/client/ClientWithCustomObjectMapperTest.java']
{'.java': 2}
2
2
0
0
2
25,047,819
4,945,013
638,365
5,854
72
13
2
1
5,988
462
1,307
159
0
2
1970-01-01T00:27:57
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,253
quarkusio/quarkus/31294/31258
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/31258
https://github.com/quarkusio/quarkus/pull/31294
https://github.com/quarkusio/quarkus/pull/31294
1
fixes
Synchronize GraalVM upstream's and Quarkus'-only debug info stripping
### Describe the bug GraalVM 23.0 will gain functionality to [strip debuginfo](https://github.com/oracle/graal/pull/5691). This is turned on by default when debuginfo generation is being turned on. As a result, quarkus applications trying to turn on debuginfo and then trying to use it in a debugger results in a CRC mismatch when loading them with gdb (for example): ``` warning: the debug information found in "/disk/graal/upstream-sources/mandrel-integration-tests/apps/quarkus-full-microprofile/target/quarkus-native-image-source-jar/quarkus-runner.debug" does not match "/disk/graal/upstream-sources/mandrel-integration-tests/apps/quarkus-full-microprofile/target/quarkus-native-image-source-jar/quarkus-runner" (CRC mismatch). ``` This is caused by two `.gnu_debuglink` sections trying to get created. The first one by GraalVM, the second by quarkus's native image build steps. The second attempt will fail and then the debuginfo won't match the CRC. ### Expected behavior Either use upstream's feature or turn it off using `-H:-StripDebugInfo` and keep using quarkus's approach. ### Actual behavior Debuginfo isn't working. See: https://github.com/Karm/mandrel-integration-tests/issues/138 ### How to Reproduce? Build a quarkus up in native with a GraalVM 23.0.0 snapshot build with debuginfo. Try to debug the binary in gdb. Observe the CRC warning and debuginfo not usable for source-file-based break points. ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` 17.0.7+1 ### GraalVM version (if different from Java) 23.0.0 ### Quarkus version or git rev main ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
6cced964632d3a6b7710f73808906dbaa4f0f704
ad468ce6fb65b7f540edd7f237902a2ec9ec254e
https://github.com/quarkusio/quarkus/compare/6cced964632d3a6b7710f73808906dbaa4f0f704...ad468ce6fb65b7f540edd7f237902a2ec9ec254e
diff --git a/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildRunner.java b/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildRunner.java index c5acdbab3a9..a079197e631 100644 --- a/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildRunner.java +++ b/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildRunner.java @@ -47,7 +47,7 @@ public void addShutdownHook(Process buildNativeProcess) { } public Result build(List<String> args, String nativeImageName, String resultingExecutableName, Path outputDir, - boolean debugSymbolsEnabled, boolean processInheritIODisabled) + GraalVM.Version graalVMVersion, boolean debugSymbolsEnabled, boolean processInheritIODisabled) throws InterruptedException, IOException { preBuild(args); try { @@ -66,21 +66,27 @@ public Result build(List<String> args, String nativeImageName, String resultingE int exitCode = process.waitFor(); boolean objcopyExists = objcopyExists(); if (exitCode != 0) { - return new Result(exitCode, objcopyExists); + return new Result(exitCode); } - if (objcopyExists) { - if (debugSymbolsEnabled) { - splitDebugSymbols(nativeImageName, resultingExecutableName); + if (debugSymbolsEnabled && graalVMVersion.compareTo(GraalVM.Version.VERSION_23_0_0) < 0 && objcopyExists) { + // Need to explicitly split debug symbols prior to GraalVM/Mandrel 23.0 + splitDebugSymbols(nativeImageName, resultingExecutableName); + } + if (!(debugSymbolsEnabled && graalVMVersion.compareTo(GraalVM.Version.VERSION_23_0_0) >= 0)) { + // Strip debug symbols even if not generated by GraalVM/Mandrel, because the underlying JDK might + // contain them. Note, however, that starting with GraalVM/Mandrel 23.0 this is done by default when + // generating debug info, so we don't want to do it twice and print twice a warning if objcopy is not + // available. + if (objcopyExists) { + objcopy("--strip-debug", resultingExecutableName); + } else if (SystemUtils.IS_OS_LINUX) { + log.warn( + "objcopy executable not found in PATH. Debug symbols will therefore not be separated from the executable."); + log.warn("That also means that resulting native executable is larger as it embeds the debug symbols."); } - // Strip debug symbols regardless, because the underlying JDK might contain them - objcopy("--strip-debug", resultingExecutableName); - } else if (SystemUtils.IS_OS_LINUX) { - log.warn( - "objcopy executable not found in PATH. Debug symbols will therefore not be separated from the executable."); - log.warn("That also means that resulting native executable is larger as it embeds the debug symbols."); } - return new Result(0, objcopyExists); + return new Result(0); } finally { postBuild(); } @@ -148,19 +154,14 @@ static void runCommand(String[] command, String errorMsg, File workingDirectory) static class Result { private final int exitCode; - private final boolean objcopyExists; - public Result(int exitCode, boolean objcopyExists) { + public Result(int exitCode) { this.exitCode = exitCode; - this.objcopyExists = objcopyExists; } public int getExitCode() { return exitCode; } - public boolean isObjcopyExists() { - return objcopyExists; - } } } diff --git a/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildStep.java b/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildStep.java index 8da849d81a4..f1f391783e1 100644 --- a/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildStep.java +++ b/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildStep.java @@ -257,7 +257,7 @@ public NativeImageBuildItem build(NativeConfig nativeConfig, LocalesBuildTimeCon NativeImageBuildRunner.Result buildNativeResult = buildRunner.build(nativeImageArgs, nativeImageName, resultingExecutableName, outputDir, - nativeConfig.debug.enabled, + graalVMVersion, nativeConfig.debug.enabled, processInheritIODisabled.isPresent() || processInheritIODisabledBuildItem.isPresent()); if (buildNativeResult.getExitCode() != 0) { throw imageGenerationFailed(buildNativeResult.getExitCode(), nativeConfig.isContainerBuild()); @@ -265,9 +265,9 @@ public NativeImageBuildItem build(NativeConfig nativeConfig, LocalesBuildTimeCon IoUtils.copy(generatedExecutablePath, finalExecutablePath); Files.delete(generatedExecutablePath); if (nativeConfig.debug.enabled) { - if (buildNativeResult.isObjcopyExists()) { - final String symbolsName = String.format("%s.debug", nativeImageName); - Path generatedSymbols = outputDir.resolve(symbolsName); + final String symbolsName = String.format("%s.debug", nativeImageName); + Path generatedSymbols = outputDir.resolve(symbolsName); + if (generatedSymbols.toFile().exists()) { Path finalSymbolsPath = outputTargetBuildItem.getOutputDirectory().resolve(symbolsName); IoUtils.copy(generatedSymbols, finalSymbolsPath); Files.delete(generatedSymbols);
['core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildStep.java', 'core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildRunner.java']
{'.java': 2}
2
2
0
0
2
24,953,974
4,927,086
635,995
5,842
3,135
597
45
2
1,746
219
439
46
2
1
1970-01-01T00:27:56
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,477
quarkusio/quarkus/24154/24130
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24130
https://github.com/quarkusio/quarkus/pull/24154
https://github.com/quarkusio/quarkus/pull/24154
1
fixes
quarkus.oidc.tls.verification can not work in dev mode
### Describe the bug ```log 135=12:30:17 INFO [io.qu.oi.de.de.OidcDevConsoleProcessor] (build-61) OIDC Dev Console: discovering the provider metadata at https://10.32.1.215:8443/realms/bank/.well-known/openid-configuration 225=12:30:18 WARN [io.qu.de.st.CombinedIndexBuildStep] (build-71) Failed to index boolean: Class does not exist in ClassLoader QuarkusClassLoader:Deployment Class Loader: DEV@3fc79729 146=12:30:19 INFO [io.qu.oi.de.de.OidcDevConsoleProcessor] (build-61) OIDC metadata can not be discovered: java.util.concurrent.CompletionException: javax.net.ssl.SSLHandshakeException: Failed to create SSL co nnection ``` ### Expected behavior _No response_ ### Actual behavior _No response_ ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` Microsoft Windows [ 10.0.19043.1110] ### Output of `java -version` java version "11.0.7" 2020-04-14 LTS Java(TM) SE Runtime Environment 18.9 (build 11.0.7+8-LTS) Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.7+8-LTS, mixed mode) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.7.3.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
5a9db9d1b958061fdd02ffb9c39d87a59822ee1b
71bd9303598c8c9548ca3fa6b31ca6d5d11acb6e
https://github.com/quarkusio/quarkus/compare/5a9db9d1b958061fdd02ffb9c39d87a59822ee1b...71bd9303598c8c9548ca3fa6b31ca6d5d11acb6e
diff --git a/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/OidcDevServicesUtils.java b/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/OidcDevServicesUtils.java index 3f38775b5a5..5a277b381d8 100644 --- a/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/OidcDevServicesUtils.java +++ b/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/OidcDevServicesUtils.java @@ -8,6 +8,7 @@ import io.vertx.core.Vertx; import io.vertx.core.http.HttpHeaders; import io.vertx.core.json.JsonObject; +import io.vertx.ext.web.client.WebClientOptions; import io.vertx.mutiny.core.buffer.Buffer; import io.vertx.mutiny.ext.web.client.HttpRequest; import io.vertx.mutiny.ext.web.client.HttpResponse; @@ -19,7 +20,10 @@ private OidcDevServicesUtils() { } public static WebClient createWebClient(Vertx vertx) { - return WebClient.create(new io.vertx.mutiny.core.Vertx(vertx)); + WebClientOptions options = new WebClientOptions(); + options.setTrustAll(true); + options.setVerifyHost(false); + return WebClient.create(new io.vertx.mutiny.core.Vertx(vertx), options); } public static String getPasswordAccessToken(WebClient client,
['extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/OidcDevServicesUtils.java']
{'.java': 1}
1
1
0
0
1
19,994,298
3,869,288
508,259
4,885
339
69
6
1
1,260
143
380
45
1
1
1970-01-01T00:27:26
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,476
quarkusio/quarkus/24165/24166
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24166
https://github.com/quarkusio/quarkus/pull/24165
https://github.com/quarkusio/quarkus/pull/24165
1
resolves
[Qute] Custom default value is ignored in {config:boolean } rendering
### Describe the bug According to https://quarkus.io/guides/qute-reference#config, when you write `{config:boolean('quarkus.foo.boolean') ?: 'Not Found'}`, I was expecting it displays `Not Found` if `quarkus.foo.boolean` is not defined. But NOT_FOUND is rendered instead ### Expected behavior Display the user-defined default value ### Actual behavior Displays hard-coded NOT_FOUND ### How to Reproduce? Just paste {config:boolean('quarkus.foo.boolean') ?: 'Not Found'} in https://github.com/quarkusio/quarkus-quickstarts/blob/main/qute-quickstart/src/main/resources/templates/hello.html, run the app and access http://localhost:8080/hello ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
b718fba290e76502cfb8a93941c67d4e56071690
f9405c32f414eac49322c130f9164499ba128a89
https://github.com/quarkusio/quarkus/compare/b718fba290e76502cfb8a93941c67d4e56071690...f9405c32f414eac49322c130f9164499ba128a89
diff --git a/extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/extensions/ConfigTemplateExtensionsTest.java b/extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/extensions/ConfigTemplateExtensionsTest.java index 737b50c197b..9f0ffcb3b67 100644 --- a/extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/extensions/ConfigTemplateExtensionsTest.java +++ b/extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/extensions/ConfigTemplateExtensionsTest.java @@ -18,12 +18,12 @@ public class ConfigTemplateExtensionsTest { .withApplicationRoot((jar) -> jar .addAsResource(new StringAsset( "{config:foo}={config:property('foo')}\\n" + - "{config:nonExistent ?: 'NOT_FOUND'}={config:property('nonExistent') ?: 'NOT_FOUND'}\\n" + + "{config:nonExistent ?: 'Not found!'}={config:property('nonExistent') ?: 'Not found!'}\\n" + "{config:['foo.bar.baz']}={config:property('foo.bar.baz')}\\n" + "{config:['quarkus.qute.remove-standalone-lines']}={config:property('quarkus.qute.remove-standalone-lines')}\\n" + "{config:property(name)}\\n" + - "{config:boolean('foo.bool') ?: 'NOT_FOUND'} {config:boolean('foo.boolean') ?: 'NOT_FOUND'}\\n" + "{config:boolean('foo.bool') ?: 'Not found!'} {config:boolean('foo.boolean') ?: 'Not found!'}\\n" + "{config:integer('foo.bar.baz')}"), "templates/foo.html") @@ -35,11 +35,11 @@ public class ConfigTemplateExtensionsTest { @Test public void testGetProperty() { assertEquals("false=false\\n" + - "NOT_FOUND=NOT_FOUND\\n" + + "Not found!=Not found!\\n" + "11=11\\n" + "true=true\\n" + "false\\n" + - "true NOT_FOUND\\n" + + "true Not found!\\n" + "11", foo.data("name", "foo").render()); } diff --git a/independent-projects/qute/core/src/main/java/io/quarkus/qute/EvaluatorImpl.java b/independent-projects/qute/core/src/main/java/io/quarkus/qute/EvaluatorImpl.java index 3a49cd9baff..c3f8c030d49 100644 --- a/independent-projects/qute/core/src/main/java/io/quarkus/qute/EvaluatorImpl.java +++ b/independent-projects/qute/core/src/main/java/io/quarkus/qute/EvaluatorImpl.java @@ -86,13 +86,20 @@ public CompletionStage<Object> evaluate(Expression expression, ResolutionContext private CompletionStage<Object> resolveNamespace(EvalContext context, ResolutionContext resolutionContext, Iterator<Part> parts, Iterator<NamespaceResolver> resolvers, Expression expression) { + // Use the next matching namespace resolver NamespaceResolver resolver = resolvers.next(); return resolver.resolve(context).thenCompose(r -> { if (Results.isNotFound(r)) { + // Result not found if (resolvers.hasNext()) { + // Try the next matching resolver return resolveNamespace(context, resolutionContext, parts, resolvers, expression); } else { - if (strictRendering && !parts.hasNext()) { + // No other matching namespace resolver exist + if (parts.hasNext()) { + // Continue to the next part of the expression + return resolveReference(false, r, parts, resolutionContext, expression, 0); + } else if (strictRendering) { throw propertyNotFound(r, expression); } return Results.notFound(context);
['independent-projects/qute/core/src/main/java/io/quarkus/qute/EvaluatorImpl.java', 'extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/extensions/ConfigTemplateExtensionsTest.java']
{'.java': 2}
2
2
0
0
2
19,996,909
3,869,745
508,297
4,885
543
88
9
1
982
114
243
39
3
0
1970-01-01T00:27:26
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,475
quarkusio/quarkus/24169/24102
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24102
https://github.com/quarkusio/quarkus/pull/24169
https://github.com/quarkusio/quarkus/pull/24169
1
fixes
Query hangs on invalid URI
### Describe the bug While developping an app, I ended up forgetting about URI encoding the data and sent this: http://server:8081/query?q=g\\\\+\\\\+&dataOnly=true In the back end I saw this exception: ```java // Caused by: java.net.URISyntaxException: Illegal character in query at index 14: /query?q=g\\\\+\\\\+&dataOnly=true // ``` but in the front end I ended up having a timeout without any error ### Expected behavior The server doesn't hang and we have an error ### Actual behavior The server hangs until the client timeouts ### How to Reproduce? 1. Create an http reactive-reasteasy 2.6.3.Final app 2. Send a malformed request: http://server:8081/query?q=g\\\\+\\\\+&dataOnly=true ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.6.3.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
dad93ec08a3362a652749e5ea3e0678a07866457
137a70de649f6761b8ca0169dcce04dcf3540efb
https://github.com/quarkusio/quarkus/compare/dad93ec08a3362a652749e5ea3e0678a07866457...137a70de649f6761b8ca0169dcce04dcf3540efb
diff --git a/extensions/opentelemetry/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/VertxClientOpenTelemetryTest.java b/extensions/opentelemetry/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/VertxClientOpenTelemetryTest.java index d8f7f6334b1..e05898a19fb 100644 --- a/extensions/opentelemetry/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/VertxClientOpenTelemetryTest.java +++ b/extensions/opentelemetry/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/VertxClientOpenTelemetryTest.java @@ -114,6 +114,18 @@ void path() throws Exception { assertEquals(server.getParentSpanId(), client.getSpanId()); } + @Test + void uri() throws Exception { + HttpResponse<Buffer> response = WebClient.create(vertx) + .get(uri.getPort(), uri.getHost(), "/hello?q=g\\\\+\\\\+&dataOnly=true") + .send() + .toCompletionStage().toCompletableFuture() + .get(); + + List<SpanData> spans = spanExporter.getFinishedSpanItems(2); + assertEquals(2, spans.size()); + } + @ApplicationScoped public static class HelloRouter { @Inject diff --git a/extensions/opentelemetry/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/tracing/vertx/OpenTelemetryVertxTracer.java b/extensions/opentelemetry/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/tracing/vertx/OpenTelemetryVertxTracer.java index 63f08e75182..5d66ff56cf5 100644 --- a/extensions/opentelemetry/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/tracing/vertx/OpenTelemetryVertxTracer.java +++ b/extensions/opentelemetry/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/tracing/vertx/OpenTelemetryVertxTracer.java @@ -5,7 +5,6 @@ import static io.quarkus.opentelemetry.runtime.OpenTelemetryConfig.INSTRUMENTATION_NAME; import static io.quarkus.vertx.core.runtime.context.VertxContextSafetyToggle.setContextSafe; -import java.net.URI; import java.util.List; import java.util.Map; import java.util.function.BiConsumer; @@ -303,9 +302,8 @@ private ServerSpanNameExtractor( @Override public String extract(final HttpRequest httpRequest) { if (httpRequest instanceof HttpServerRequest) { - String path = URI.create(httpRequest.uri()).getPath(); - if (path != null && path.length() > 1) { - return path.substring(1); + if (httpRequest.uri() != null && httpRequest.uri().length() > 1) { + return httpRequest.uri().substring(1); } else { return "HTTP " + httpRequest.method(); }
['extensions/opentelemetry/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/VertxClientOpenTelemetryTest.java', 'extensions/opentelemetry/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/tracing/vertx/OpenTelemetryVertxTracer.java']
{'.java': 2}
2
2
0
0
2
19,736,026
3,821,368
501,835
4,833
342
68
6
1
1,069
147
274
51
2
1
1970-01-01T00:27:26
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,474
quarkusio/quarkus/24306/24287
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24287
https://github.com/quarkusio/quarkus/pull/24306
https://github.com/quarkusio/quarkus/pull/24306
1
fix
Gzip Compression Not Working over HTTPS
### Describe the bug I want to compress static resources in Quarkus like js, css, and image. I was activated configuration for compression **quarkus.http.enable-compression:true**. It's working perfectly on HTTP mode but does not working over https. ### Expected behavior Content will be compressed as GZIP over HTTPS ### Actual behavior No GZIP compression over HTTPS ### How to Reproduce? Steps to reproduce the behavior: 1. Git pull from [quarkus-demo](https://github.com/Herdi-73/quarkus-demo.git) I made earlier 2. Create certificate for enable SSL in localhost with [mkcert](https://web.dev/how-to-use-local-https/) 3. Compile with command mvn clean package -Dquarkus.profile=prod for running over HTTPS. If you want to test over HTTP please run with this command mvn quarkus:dev 4. Run quarkus app with this command java -jar target\\quarkus-app\\quarkus-run.jar 5. Finally, open your browser to access https://localhost or http://localhost:8080 and then please inspect element to check loaded resources details at Network tab ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
fc4151b4b0ca506cec2c02bb3ee10f00ef789fc5
8b9fffb3de0cb8a44d5dfc6c6cc1d8550dc0d8be
https://github.com/quarkusio/quarkus/compare/fc4151b4b0ca506cec2c02bb3ee10f00ef789fc5...8b9fffb3de0cb8a44d5dfc6c6cc1d8550dc0d8be
diff --git a/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxHttpRecorder.java b/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxHttpRecorder.java index 8d6e7068b48..e9616ef08ad 100644 --- a/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxHttpRecorder.java +++ b/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxHttpRecorder.java @@ -541,7 +541,8 @@ private static void doServerStart(Vertx vertx, HttpBuildTimeConfig httpBuildTime // Http server configuration HttpServerOptions httpServerOptions = createHttpServerOptions(httpConfiguration, launchMode, websocketSubProtocols); HttpServerOptions domainSocketOptions = createDomainSocketOptions(httpConfiguration, websocketSubProtocols); - HttpServerOptions sslConfig = createSslOptions(httpBuildTimeConfig, httpConfiguration, launchMode); + HttpServerOptions sslConfig = createSslOptions(httpBuildTimeConfig, httpConfiguration, launchMode, + websocketSubProtocols); if (httpConfiguration.insecureRequests != HttpConfiguration.InsecureRequests.ENABLED && sslConfig == null) { throw new IllegalStateException("Cannot set quarkus.http.redirect-insecure-requests without enabling SSL."); @@ -662,7 +663,7 @@ private static void setHttpServerTiming(InsecureRequests insecureRequests, HttpS * Get an {@code HttpServerOptions} for this server configuration, or null if SSL should not be enabled */ private static HttpServerOptions createSslOptions(HttpBuildTimeConfig buildTimeConfig, HttpConfiguration httpConfiguration, - LaunchMode launchMode) + LaunchMode launchMode, List<String> websocketSubProtocols) throws IOException { if (!httpConfiguration.hostEnabled) { return null; @@ -700,9 +701,6 @@ private static HttpServerOptions createSslOptions(HttpBuildTimeConfig buildTimeC serverOptions.setAlpnVersions(Arrays.asList(HttpVersion.HTTP_2, HttpVersion.HTTP_1_1)); } } - serverOptions.setMaxHeaderSize(httpConfiguration.limits.maxHeaderSize.asBigInteger().intValueExact()); - serverOptions.setMaxChunkSize(httpConfiguration.limits.maxChunkSize.asBigInteger().intValueExact()); - serverOptions.setMaxFormAttributeSize(httpConfiguration.limits.maxFormAttributeSize.asBigInteger().intValueExact()); setIdleTimeout(httpConfiguration, serverOptions); if (!certificates.isEmpty() && !keys.isEmpty()) { @@ -745,20 +743,34 @@ private static HttpServerOptions createSslOptions(HttpBuildTimeConfig buildTimeC } serverOptions.setSsl(true); serverOptions.setSni(sslConfig.sni); - serverOptions.setHost(httpConfiguration.host); int sslPort = httpConfiguration.determineSslPort(launchMode); // -2 instead of -1 (see http) to have vert.x assign two different random ports if both http and https shall be random serverOptions.setPort(sslPort == 0 ? -2 : sslPort); serverOptions.setClientAuth(buildTimeConfig.tlsClientAuth); - serverOptions.setReusePort(httpConfiguration.soReusePort); - serverOptions.setTcpQuickAck(httpConfiguration.tcpQuickAck); - serverOptions.setTcpCork(httpConfiguration.tcpCork); - serverOptions.setTcpFastOpen(httpConfiguration.tcpFastOpen); - serverOptions.setMaxInitialLineLength(httpConfiguration.limits.maxInitialLineLength); + + applyCommonOptions(serverOptions, httpConfiguration, websocketSubProtocols); return serverOptions; } + private static void applyCommonOptions(HttpServerOptions httpServerOptions, HttpConfiguration httpConfiguration, + List<String> websocketSubProtocols) { + httpServerOptions.setHost(httpConfiguration.host); + setIdleTimeout(httpConfiguration, httpServerOptions); + httpServerOptions.setMaxHeaderSize(httpConfiguration.limits.maxHeaderSize.asBigInteger().intValueExact()); + httpServerOptions.setMaxChunkSize(httpConfiguration.limits.maxChunkSize.asBigInteger().intValueExact()); + httpServerOptions.setMaxFormAttributeSize(httpConfiguration.limits.maxFormAttributeSize.asBigInteger().intValueExact()); + httpServerOptions.setWebSocketSubProtocols(websocketSubProtocols); + httpServerOptions.setReusePort(httpConfiguration.soReusePort); + httpServerOptions.setTcpQuickAck(httpConfiguration.tcpQuickAck); + httpServerOptions.setTcpCork(httpConfiguration.tcpCork); + httpServerOptions.setAcceptBacklog(httpConfiguration.acceptBacklog); + httpServerOptions.setTcpFastOpen(httpConfiguration.tcpFastOpen); + httpServerOptions.setCompressionSupported(httpConfiguration.enableCompression); + httpServerOptions.setDecompressionSupported(httpConfiguration.enableDecompression); + httpServerOptions.setMaxInitialLineLength(httpConfiguration.limits.maxInitialLineLength); + } + private static KeyStoreOptions createKeyStoreOptions(Path path, String password, Optional<String> fileType, Optional<String> provider, Optional<String> alias, Optional<String> aliasPassword) throws IOException { final String type; @@ -849,22 +861,11 @@ private static HttpServerOptions createHttpServerOptions(HttpConfiguration httpC } // TODO other config properties HttpServerOptions options = new HttpServerOptions(); - options.setHost(httpConfiguration.host); int port = httpConfiguration.determinePort(launchMode); options.setPort(port == 0 ? -1 : port); - setIdleTimeout(httpConfiguration, options); - options.setMaxHeaderSize(httpConfiguration.limits.maxHeaderSize.asBigInteger().intValueExact()); - options.setMaxChunkSize(httpConfiguration.limits.maxChunkSize.asBigInteger().intValueExact()); - options.setMaxFormAttributeSize(httpConfiguration.limits.maxFormAttributeSize.asBigInteger().intValueExact()); - options.setWebSocketSubProtocols(websocketSubProtocols); - options.setReusePort(httpConfiguration.soReusePort); - options.setTcpQuickAck(httpConfiguration.tcpQuickAck); - options.setTcpCork(httpConfiguration.tcpCork); - options.setAcceptBacklog(httpConfiguration.acceptBacklog); - options.setTcpFastOpen(httpConfiguration.tcpFastOpen); - options.setCompressionSupported(httpConfiguration.enableCompression); - options.setDecompressionSupported(httpConfiguration.enableDecompression); - options.setMaxInitialLineLength(httpConfiguration.limits.maxInitialLineLength); + + applyCommonOptions(options, httpConfiguration, websocketSubProtocols); + return options; } @@ -874,12 +875,9 @@ private static HttpServerOptions createDomainSocketOptions(HttpConfiguration htt return null; } HttpServerOptions options = new HttpServerOptions(); - options.setHost(httpConfiguration.domainSocket); - setIdleTimeout(httpConfiguration, options); - options.setMaxHeaderSize(httpConfiguration.limits.maxHeaderSize.asBigInteger().intValueExact()); - options.setMaxChunkSize(httpConfiguration.limits.maxChunkSize.asBigInteger().intValueExact()); - options.setMaxFormAttributeSize(httpConfiguration.limits.maxFormAttributeSize.asBigInteger().intValueExact()); - options.setWebSocketSubProtocols(websocketSubProtocols); + + applyCommonOptions(options, httpConfiguration, websocketSubProtocols); + return options; }
['extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxHttpRecorder.java']
{'.java': 1}
1
1
0
0
1
20,072,980
3,883,941
510,153
4,906
4,343
762
60
1
1,381
192
333
46
4
0
1970-01-01T00:27:27
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,472
quarkusio/quarkus/24355/24329
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24329
https://github.com/quarkusio/quarkus/pull/24355
https://github.com/quarkusio/quarkus/pull/24355
1
fixes
DevServices for Keycloak UI is broken on 2.8-main
### Describe the bug Regression has been introduced on `main`, after starting `mvn quarkus:dev` and going to `http://localhost:8080/q/dev/`, the OIDC card does not have a `Provider: Keycloak` link to `http://localhost:8080/q/dev/io.quarkus.quarkus-oidc/provider`. `http://localhost:8080/q/dev/io.quarkus.quarkus-oidc/provider` does respond if it is accessed directly but the UI is wrong there as well, `Service Path` field is shown alongside the expected `Log Into Single Page Application`. It took me a long time to trace it down to #23781. All works as expected with the immediately preceding commit (Stork doc improvements). The existing smoke test detects `http://localhost:8080/q/dev/io.quarkus.quarkus-oidc/provider` which is not sufficient, I think one of the OIDC devmode tests will need to be updated to check that `http://localhost:8080/q/dev` has a `Provider: Keycloak` string. ### Expected behavior OIDC Card has a `Provider: Keycloak` and the provider page should only have a `Log Into Single Page Application` option, as shown [here](https://quarkus.io/guides/security-openid-connect-dev-services#dev-services-for-keycloak) ### Actual behavior _No response_ ### How to Reproduce? Do `mvn quarkus:dev` in `quarkus-quickstarts/security-openid-connect-quickstart` and go to `http://localhost:8080/q/dev` and observe an empty OIDC card without `Provider: Keycloak`, then go to `http://localhost:8080/q/dev/io.quarkus.quarkus-oidc/provider` and see a redundant `Service Path` field ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
5d31bc54caf10eba573c1219f7c885a6c5515ce7
f8f9a705005125958bbe1bcdc7e2ab201e4c74fa
https://github.com/quarkusio/quarkus/compare/5d31bc54caf10eba573c1219f7c885a6c5515ce7...f8f9a705005125958bbe1bcdc7e2ab201e4c74fa
diff --git a/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevConsoleProcessor.java b/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevConsoleProcessor.java index bb080341ec9..16de5057247 100644 --- a/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevConsoleProcessor.java +++ b/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevConsoleProcessor.java @@ -31,20 +31,20 @@ public void setConfigProperties(BuildProducer<DevConsoleTemplateInfoBuildItem> d BuildProducer<DevConsoleRuntimeTemplateInfoBuildItem> devConsoleRuntimeInfo, Optional<KeycloakDevServicesConfigBuildItem> configProps, Capabilities capabilities, CurateOutcomeBuildItem curateOutcomeBuildItem) { - if (configProps.isPresent() && configProps.get().getProperties().containsKey("keycloak.url")) { - String keycloakUrl = (String) configProps.get().getProperties().get("keycloak.url"); - String realmUrl = keycloakUrl + "/realms/" + configProps.get().getProperties().get("keycloak.realm"); - - devConsoleInfo.produce(new DevConsoleTemplateInfoBuildItem("keycloakAdminUrl", keycloakUrl)); + if (configProps.isPresent() && configProps.get().getConfig().containsKey("keycloak.url")) { + devConsoleInfo.produce( + new DevConsoleTemplateInfoBuildItem("keycloakAdminUrl", configProps.get().getConfig().get("keycloak.url"))); devConsoleInfo.produce( - new DevConsoleTemplateInfoBuildItem("keycloakUsers", configProps.get().getProperties().get("oidc.users"))); + new DevConsoleTemplateInfoBuildItem("keycloakUsers", + configProps.get().getProperties().get("oidc.users"))); + String realmUrl = configProps.get().getConfig().get("quarkus.oidc.auth-server-url"); produceDevConsoleTemplateItems(capabilities, devConsoleInfo, devConsoleRuntimeInfo, curateOutcomeBuildItem, "Keycloak", - (String) configProps.get().getProperties().get("quarkus.oidc.application-type"), + (String) configProps.get().getConfig().get("quarkus.oidc.application-type"), oidcConfig.devui.grant.type.isPresent() ? oidcConfig.devui.grant.type.get().getGrantType() : keycloakConfig.devservices.grant.type.getGrantType(), realmUrl + "/protocol/openid-connect/auth", @@ -57,7 +57,7 @@ public void setConfigProperties(BuildProducer<DevConsoleTemplateInfoBuildItem> d @BuildStep(onlyIf = IsDevelopment.class) void invokeEndpoint(BuildProducer<DevConsoleRouteBuildItem> devConsoleRoute, Optional<KeycloakDevServicesConfigBuildItem> configProps) { - if (configProps.isPresent() && configProps.get().getProperties().containsKey("keycloak.url")) { + if (configProps.isPresent() && configProps.get().getConfig().containsKey("keycloak.url")) { @SuppressWarnings("unchecked") Map<String, String> users = (Map<String, String>) configProps.get().getProperties().get("oidc.users"); Duration webClientTimeout = oidcConfig.devui.webClienTimeout.isPresent() ? oidcConfig.devui.webClienTimeout.get() diff --git a/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesConfigBuildItem.java b/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesConfigBuildItem.java index 371725dc2c7..83d5ed3d4d5 100644 --- a/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesConfigBuildItem.java +++ b/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesConfigBuildItem.java @@ -6,13 +6,19 @@ public final class KeycloakDevServicesConfigBuildItem extends SimpleBuildItem { + private final Map<String, String> config; private final Map<String, Object> properties; - public KeycloakDevServicesConfigBuildItem(Map<String, Object> configProperties) { + public KeycloakDevServicesConfigBuildItem(Map<String, String> config, Map<String, Object> configProperties) { + this.config = config; this.properties = configProperties; } public Map<String, Object> getProperties() { return properties; } + + public Map<String, String> getConfig() { + return config; + } } diff --git a/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesProcessor.java b/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesProcessor.java index dcc9d6a47a4..5aa660ab496 100644 --- a/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesProcessor.java +++ b/extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesProcessor.java @@ -37,9 +37,9 @@ import org.testcontainers.containers.wait.strategy.Wait; import org.testcontainers.utility.DockerImageName; -import io.quarkus.deployment.Feature; import io.quarkus.deployment.IsDockerWorking; import io.quarkus.deployment.IsNormal; +import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.builditem.CuratedApplicationShutdownBuildItem; import io.quarkus.deployment.builditem.DevServicesResultBuildItem; @@ -78,8 +78,8 @@ public class KeycloakDevServicesProcessor { private static final String CLIENT_ID_CONFIG_KEY = CONFIG_PREFIX + "client-id"; private static final String CLIENT_SECRET_CONFIG_KEY = CONFIG_PREFIX + "credentials.secret"; private static final String KEYCLOAK_URL_KEY = "keycloak.url"; - private static final String KEYCLOAK_REALM_KEY = "keycloak.realm"; + private static final String KEYCLOAK_CONTAINER_NAME = "keycloak"; private static final int KEYCLOAK_PORT = 8080; private static final String KEYCLOAK_LEGACY_IMAGE_VERSION_PART = "-legacy"; @@ -121,6 +121,7 @@ public class KeycloakDevServicesProcessor { @BuildStep(onlyIfNot = IsNormal.class, onlyIf = { IsEnabled.class, GlobalDevServicesConfig.Enabled.class }) public DevServicesResultBuildItem startKeycloakContainer( + BuildProducer<KeycloakDevServicesConfigBuildItem> keycloakBuildItemBuildProducer, List<DevServicesSharedNetworkBuildItem> devServicesSharedNetworkBuildItem, Optional<OidcDevServicesBuildItem> oidcProviderBuildItem, KeycloakBuildTimeConfig config, @@ -168,7 +169,8 @@ public DevServicesResultBuildItem startKeycloakContainer( vertxInstance = Vertx.vertx(); } try { - RunningDevService newDevService = startContainer(!devServicesSharedNetworkBuildItem.isEmpty(), + RunningDevService newDevService = startContainer(keycloakBuildItemBuildProducer, + !devServicesSharedNetworkBuildItem.isEmpty(), devServicesConfig.timeout); if (newDevService == null) { compressor.close(); @@ -221,7 +223,9 @@ private String startURL(String host, Integer port, boolean isKeyCloakX) { return "http://" + host + ":" + port + (isKeyCloakX ? "" : "/auth"); } - private Map<String, String> prepareConfiguration(String internalURL, String hostURL, RealmRepresentation realmRep, + private Map<String, String> prepareConfiguration( + BuildProducer<KeycloakDevServicesConfigBuildItem> keycloakBuildItemBuildProducer, String internalURL, + String hostURL, RealmRepresentation realmRep, boolean keycloakX) { final String realmName = realmRep != null ? realmRep.getRealm() : getDefaultRealmName(); final String authServerInternalUrl = realmsURL(internalURL, realmName); @@ -249,6 +253,10 @@ private Map<String, String> prepareConfiguration(String internalURL, String host configProperties.put(APPLICATION_TYPE_CONFIG_KEY, oidcApplicationType); configProperties.put(CLIENT_ID_CONFIG_KEY, oidcClientId); configProperties.put(CLIENT_SECRET_CONFIG_KEY, oidcClientSecret); + + keycloakBuildItemBuildProducer + .produce(new KeycloakDevServicesConfigBuildItem(configProperties, Map.of(OIDC_USERS, users))); + return configProperties; } @@ -260,7 +268,8 @@ private String getDefaultRealmName() { return capturedDevServicesConfiguration.realmName.orElse("quarkus"); } - private RunningDevService startContainer(boolean useSharedNetwork, Optional<Duration> timeout) { + private RunningDevService startContainer(BuildProducer<KeycloakDevServicesConfigBuildItem> keycloakBuildItemBuildProducer, + boolean useSharedNetwork, Optional<Duration> timeout) { if (!capturedDevServicesConfiguration.enabled) { // explicitly disabled LOG.debug("Not starting Dev Services for Keycloak as it has been disabled in the config"); @@ -305,19 +314,21 @@ private RunningDevService startContainer(boolean useSharedNetwork, Optional<Dura String hostUrl = oidcContainer.useSharedNetwork ? startURL("localhost", oidcContainer.fixedExposedPort.getAsInt(), oidcContainer.keycloakX) : null; - Map<String, String> configs = prepareConfiguration(internalUrl, hostUrl, oidcContainer.realmRep, + + Map<String, String> configs = prepareConfiguration(keycloakBuildItemBuildProducer, internalUrl, hostUrl, + oidcContainer.realmRep, oidcContainer.keycloakX); - return new RunningDevService(Feature.KEYCLOAK_AUTHORIZATION.getName(), oidcContainer.getContainerId(), + return new RunningDevService(KEYCLOAK_CONTAINER_NAME, oidcContainer.getContainerId(), oidcContainer::close, configs); }; return maybeContainerAddress .map(containerAddress -> { // TODO: this probably needs to be addressed - Map<String, String> configs = prepareConfiguration(getSharedContainerUrl(containerAddress), + Map<String, String> configs = prepareConfiguration(keycloakBuildItemBuildProducer, + getSharedContainerUrl(containerAddress), getSharedContainerUrl(containerAddress), null, false); - return new RunningDevService(Feature.KEYCLOAK_AUTHORIZATION.getName(), - containerAddress.getId(), null, configs); + return new RunningDevService(KEYCLOAK_CONTAINER_NAME, containerAddress.getId(), null, configs); }) .orElseGet(defaultKeycloakContainerSupplier); }
['extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesProcessor.java', 'extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevServicesConfigBuildItem.java', 'extensions/oidc/deployment/src/main/java/io/quarkus/oidc/deployment/devservices/keycloak/KeycloakDevConsoleProcessor.java']
{'.java': 3}
3
3
0
0
3
20,094,848
3,888,177
510,651
4,912
4,306
843
55
3
1,876
230
476
43
8
0
1970-01-01T00:27:27
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,471
quarkusio/quarkus/24356/24322
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24322
https://github.com/quarkusio/quarkus/pull/24356
https://github.com/quarkusio/quarkus/pull/24356
1
fixes
Config like `mp.messaging.connector.smallrye-kafka.value.serializer` is ignored
### Describe the bug The build step `SmallRyeReactiveMessagingKafkaProcessor#defaultChannelConfiguration()` currently ignores checking for connector-level config like `mp.messaging.connector.smallrye-kafka.value.serializer`. As a result this configuration has no effect when added to the `application.properties` file because the generated channel-level `RunTimeConfigurationDefaultBuildItem` defaults take precedence. See also discussion in Zulip: https://quarkusio.zulipchat.com/#narrow/stream/187030-users/topic/.E2.9C.94.20Kafka.3A.20Apicurio.20for.20dev.20and.20Confluent.20for.20prod.20mode.3F ### Expected behavior Explicit connector-level config in `application.properties` should take precedence over generated channel-level defaults. The build step should probably check for the presence of such properties at build time to determine whether to generate a runtime default or not for a given channel's properties. #### Use case We are using Kafka with a schema registry and Avro encoded messages. In production the schema registry is the Confluent implementation and for development in dev mode we use Apicurio. This means that the serializer and deserializer implementation classes are different for production and non-production (i.e. test and development) launch modes. Further, since our application uses multiple channels, we would like to declare the Avro serializer and deserializer at the connector level, rather than individually for each channel. Doing it for each channel results in a lot of duplicated config. ### Actual behavior The explicit connector-level config (like `mp.messaging.connector.smallrye-kafka.value.serializer`) in the `application.properties` file is ignored, because the autodetection generates corresponding channel-level config which takes precedence. ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.7.4.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information
ea3688cab457dac977160ab9ef6a288559dcfc1c
231112452b0d55c93652618d8ce5755d74b9a880
https://github.com/quarkusio/quarkus/compare/ea3688cab457dac977160ab9ef6a288559dcfc1c...231112452b0d55c93652618d8ce5755d74b9a880
diff --git a/extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeDiscoveryState.java b/extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeDiscoveryState.java index cda62e4596c..555a611e175 100644 --- a/extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeDiscoveryState.java +++ b/extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeDiscoveryState.java @@ -8,6 +8,7 @@ import java.util.Set; import java.util.stream.Collectors; +import org.eclipse.microprofile.config.Config; import org.eclipse.microprofile.config.ConfigProvider; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; @@ -26,6 +27,11 @@ class DefaultSerdeDiscoveryState { private final Map<String, Boolean> isKafkaConnector = new HashMap<>(); private final Set<String> alreadyConfigured = new HashSet<>(); + private Boolean connectorHasKeySerializer; + private Boolean connectorHasValueSerializer; + private Boolean connectorHasKeyDeserializer; + private Boolean connectorHasValueDeserializer; + private Boolean hasConfluent; private Boolean hasApicurio1; private Boolean hasApicurio2; @@ -35,6 +41,10 @@ class DefaultSerdeDiscoveryState { this.index = index; } + Config getConfig() { + return ConfigProvider.getConfig(); + } + boolean isKafkaConnector(List<ConnectorManagedChannelBuildItem> channelsManagedByConnectors, boolean incoming, String channelName) { // First look in the channelsManagedByConnectors list @@ -48,13 +58,61 @@ boolean isKafkaConnector(List<ConnectorManagedChannelBuildItem> channelsManagedB String channelType = incoming ? "incoming" : "outgoing"; return isKafkaConnector.computeIfAbsent(channelType + "|" + channelName, ignored -> { String connectorKey = "mp.messaging." + channelType + "." + channelName + ".connector"; - String connector = ConfigProvider.getConfig() + String connector = getConfig() .getOptionalValue(connectorKey, String.class) .orElse("ignored"); return KafkaConnector.CONNECTOR_NAME.equals(connector); }); } + boolean shouldNotConfigure(String key) { + // if we know at build time that key/value [de]serializer is configured on the connector, + // we should NOT emit default configuration for key/value [de]serializer on the channel + // (in other words, only a user can explicitly override a connector configuration) + // + // more config properties could possibly be handled in the same way, but these should suffice for now + + if (key.startsWith("mp.messaging.outgoing.") && key.endsWith(".key.serializer")) { + if (connectorHasKeySerializer == null) { + connectorHasKeySerializer = getConfig() + .getOptionalValue("mp.messaging.connector." + KafkaConnector.CONNECTOR_NAME + ".key.serializer", + String.class) + .isPresent(); + } + return connectorHasKeySerializer; + } + if (key.startsWith("mp.messaging.outgoing.") && key.endsWith(".value.serializer")) { + if (connectorHasValueSerializer == null) { + connectorHasValueSerializer = getConfig() + .getOptionalValue("mp.messaging.connector." + KafkaConnector.CONNECTOR_NAME + ".value.serializer", + String.class) + .isPresent(); + } + return connectorHasValueSerializer; + } + + if (key.startsWith("mp.messaging.incoming.") && key.endsWith(".key.deserializer")) { + if (connectorHasKeyDeserializer == null) { + connectorHasKeyDeserializer = getConfig() + .getOptionalValue("mp.messaging.connector." + KafkaConnector.CONNECTOR_NAME + ".key.deserializer", + String.class) + .isPresent(); + } + return connectorHasKeyDeserializer; + } + if (key.startsWith("mp.messaging.incoming.") && key.endsWith(".value.deserializer")) { + if (connectorHasValueDeserializer == null) { + connectorHasValueDeserializer = getConfig() + .getOptionalValue("mp.messaging.connector." + KafkaConnector.CONNECTOR_NAME + ".value.deserializer", + String.class) + .isPresent(); + } + return connectorHasValueDeserializer; + } + + return false; + } + void ifNotYetConfigured(String key, Runnable runnable) { if (!alreadyConfigured.contains(key)) { alreadyConfigured.add(key); diff --git a/extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/SmallRyeReactiveMessagingKafkaProcessor.java b/extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/SmallRyeReactiveMessagingKafkaProcessor.java index 18513a1fb02..2770b0dc637 100644 --- a/extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/SmallRyeReactiveMessagingKafkaProcessor.java +++ b/extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/SmallRyeReactiveMessagingKafkaProcessor.java @@ -243,6 +243,10 @@ private void produceRuntimeConfigurationDefaultBuildItem(DefaultSerdeDiscoverySt return; } + if (discovery.shouldNotConfigure(key)) { + return; + } + discovery.ifNotYetConfigured(key, () -> { config.produce(new RunTimeConfigurationDefaultBuildItem(key, value)); }); diff --git a/extensions/smallrye-reactive-messaging-kafka/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeConfigTest.java b/extensions/smallrye-reactive-messaging-kafka/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeConfigTest.java index 328a837b928..86452bdc6d2 100644 --- a/extensions/smallrye-reactive-messaging-kafka/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeConfigTest.java +++ b/extensions/smallrye-reactive-messaging-kafka/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeConfigTest.java @@ -8,6 +8,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.concurrent.CompletionStage; import javax.inject.Inject; @@ -19,6 +20,7 @@ import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.header.Headers; import org.assertj.core.groups.Tuple; +import org.eclipse.microprofile.config.Config; import org.eclipse.microprofile.reactive.messaging.Channel; import org.eclipse.microprofile.reactive.messaging.Emitter; import org.eclipse.microprofile.reactive.messaging.Incoming; @@ -38,6 +40,8 @@ import io.quarkus.kafka.client.serialization.JsonbSerializer; import io.quarkus.kafka.client.serialization.ObjectMapperDeserializer; import io.quarkus.smallrye.reactivemessaging.deployment.items.ConnectorManagedChannelBuildItem; +import io.smallrye.config.SmallRyeConfigBuilder; +import io.smallrye.config.common.MapBackedConfigSource; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; import io.smallrye.reactive.messaging.MutinyEmitter; @@ -48,9 +52,18 @@ public class DefaultSerdeConfigTest { private static void doTest(Tuple[] expectations, Class<?>... classesToIndex) { + doTest(null, expectations, classesToIndex); + } + + private static void doTest(Config customConfig, Tuple[] expectations, Class<?>... classesToIndex) { List<RunTimeConfigurationDefaultBuildItem> configs = new ArrayList<>(); DefaultSerdeDiscoveryState discovery = new DefaultSerdeDiscoveryState(index(classesToIndex)) { + @Override + Config getConfig() { + return customConfig != null ? customConfig : super.getConfig(); + } + @Override boolean isKafkaConnector(List<ConnectorManagedChannelBuildItem> list, boolean incoming, String channelName) { return true; @@ -2467,4 +2480,69 @@ void channel10(List<Message<JacksonDto>> jacksonDto) { } + // --- + + @Test + public void connectorConfigNotOverriden() { + // @formatter:off + Tuple[] expectations1 = { + // "mp.messaging.outgoing.channel1.key.serializer" NOT expected, connector config exists + tuple("mp.messaging.outgoing.channel1.value.serializer", "org.apache.kafka.common.serialization.StringSerializer"), + + tuple("mp.messaging.incoming.channel2.key.deserializer", "org.apache.kafka.common.serialization.LongDeserializer"), + // "mp.messaging.incoming.channel2.value.deserializer" NOT expected, connector config exists + + tuple("mp.messaging.incoming.channel3.key.deserializer", "org.apache.kafka.common.serialization.LongDeserializer"), + // "mp.messaging.incoming.channel3.value.deserializer" NOT expected, connector config exists + // "mp.messaging.outgoing.channel4.key.serializer" NOT expected, connector config exists + tuple("mp.messaging.outgoing.channel4.value.serializer", "org.apache.kafka.common.serialization.StringSerializer"), + }; + + Tuple[] expectations2 = { + tuple("mp.messaging.outgoing.channel1.key.serializer", "org.apache.kafka.common.serialization.LongSerializer"), + // "mp.messaging.outgoing.channel1.value.serializer" NOT expected, connector config exists + + // "mp.messaging.incoming.channel2.key.deserializer" NOT expected, connector config exists + tuple("mp.messaging.incoming.channel2.value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"), + + // "mp.messaging.incoming.channel3.key.deserializer" NOT expected, connector config exists + tuple("mp.messaging.incoming.channel3.value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"), + tuple("mp.messaging.outgoing.channel4.key.serializer", "org.apache.kafka.common.serialization.LongSerializer"), + // "mp.messaging.outgoing.channel4.value.serializer" NOT expected, connector config exists + }; + // @formatter:on + + doTest(new SmallRyeConfigBuilder() + .withSources(new MapBackedConfigSource("test", Map.of( + "mp.messaging.connector.smallrye-kafka.key.serializer", "foo.Bar", + "mp.messaging.connector.smallrye-kafka.value.deserializer", "foo.Baz")) { + }) + .build(), expectations1, ConnectorConfigNotOverriden.class); + + doTest(new SmallRyeConfigBuilder() + .withSources(new MapBackedConfigSource("test", Map.of( + "mp.messaging.connector.smallrye-kafka.key.deserializer", "foo.Bar", + "mp.messaging.connector.smallrye-kafka.value.serializer", "foo.Baz")) { + }) + .build(), expectations2, ConnectorConfigNotOverriden.class); + } + + private static class ConnectorConfigNotOverriden { + @Outgoing("channel1") + Record<Long, String> method1() { + return null; + } + + @Incoming("channel2") + CompletionStage<?> method2(Record<Long, String> msg) { + return null; + } + + @Incoming("channel3") + @Outgoing("channel4") + Record<Long, String> method3(Record<Long, String> msg) { + return null; + } + } + }
['extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/SmallRyeReactiveMessagingKafkaProcessor.java', 'extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeDiscoveryState.java', 'extensions/smallrye-reactive-messaging-kafka/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeConfigTest.java']
{'.java': 3}
3
3
0
0
3
20,092,041
3,887,703
510,589
4,912
2,985
490
64
2
2,204
261
468
46
1
0
1970-01-01T00:27:27
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,470
quarkusio/quarkus/24398/24338
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24338
https://github.com/quarkusio/quarkus/pull/24398
https://github.com/quarkusio/quarkus/pull/24398
1
resolves
Removal of beans loads referenced classes
### Describe the bug I have following project structure: * commons (external module) * web (quarkus) The commons module includes hibernate-validator (and custom ConstraintValidators), which I just don't need for this project. I tried to simply add an exclusion on quarkus-hibernate-validator, to remove this extension. However, I got the exception from below. Apperantly, during removal of unused beans, the bean is initialized? ``` @ApplicationScoped public class FutureDayValidator implements ConstraintValidator<FutureDay, Date> { @Override public void initialize(FutureDay constraintAnnotation) { } @Override public boolean isValid(Date value, ConstraintValidatorContext context) { return false; } } ``` ### Expected behavior App starts, just with the ConstraintValidator removed. ### Actual behavior ``` 2022-03-16 08:22:17,682 ERROR [io.qua.dep.dev.IsolatedDevModeMain] (main) Failed to start quarkus: java.lang.RuntimeException: java.lang.NoClassDefFoundError: javax/validation/ConstraintValidator at io.quarkus.dev.appstate.ApplicationStateNotification.waitForApplicationStart(ApplicationStateNotification.java:51) at io.quarkus.runner.bootstrap.StartupActionImpl.runMainClass(StartupActionImpl.java:122) at io.quarkus.deployment.dev.IsolatedDevModeMain.firstStart(IsolatedDevModeMain.java:144) at io.quarkus.deployment.dev.IsolatedDevModeMain.accept(IsolatedDevModeMain.java:455) at io.quarkus.deployment.dev.IsolatedDevModeMain.accept(IsolatedDevModeMain.java:66) at io.quarkus.bootstrap.app.CuratedApplication.runInCl(CuratedApplication.java:140) at io.quarkus.bootstrap.app.CuratedApplication.runInAugmentClassLoader(CuratedApplication.java:96) at io.quarkus.deployment.dev.DevModeMain.start(DevModeMain.java:132) at io.quarkus.deployment.dev.DevModeMain.main(DevModeMain.java:62) Caused by: java.lang.NoClassDefFoundError: javax/validation/ConstraintValidator at java.base/java.lang.ClassLoader.defineClass1(Native Method) at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1012) at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:454) at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:414) at java.base/java.lang.Class.forName0(Native Method) at java.base/java.lang.Class.forName(Class.java:467) at io.quarkus.arc.setup.Default_ComponentsProvider.addRemovedBeans2(Unknown Source) at io.quarkus.arc.setup.Default_ComponentsProvider.getComponents(Unknown Source) at io.quarkus.arc.impl.ArcContainerImpl.<init>(ArcContainerImpl.java:118) at io.quarkus.arc.Arc.initialize(Arc.java:24) at io.quarkus.arc.runtime.ArcRecorder.getContainer(ArcRecorder.java:40) at io.quarkus.deployment.steps.ArcProcessor$generateResources686947423.deploy_0(Unknown Source) at io.quarkus.deployment.steps.ArcProcessor$generateResources686947423.deploy(Unknown Source) at io.quarkus.runner.ApplicationImpl.<clinit>(Unknown Source) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499) at java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:128) at java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:347) at java.base/java.lang.Class.newInstance(Class.java:645) at io.quarkus.runtime.Quarkus.run(Quarkus.java:66) at io.quarkus.runtime.Quarkus.run(Quarkus.java:41) at io.quarkus.runtime.Quarkus.run(Quarkus.java:120) at io.quarkus.runner.GeneratedMain.main(Unknown Source) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at io.quarkus.runner.bootstrap.StartupActionImpl$1.run(StartupActionImpl.java:103) at java.base/java.lang.Thread.run(Thread.java:833) Caused by: java.lang.ClassNotFoundException: javax.validation.ConstraintValidator at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520) at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:464) at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:414) at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:464) at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:414) ... 31 more ``` ### How to Reproduce? Download the reproducer: [removed-bean-classloading.zip](https://github.com/quarkusio/quarkus/files/8260177/removed-bean-classloading.zip) 1. mvn quarkus:dev 2. Exception happens 3. Remove exclusion on hibernate-validator in web/pom.xml 4. mvn quarkus:dev 5. It starts ### Output of `uname -a` or `ver` Microsoft Windows [Version 10.0.19044.1586] ### Output of `java -version` openjdk 17.0.2 2022-01-18 OpenJDK Runtime Environment Temurin-17.0.2+8 (build 17.0.2+8) OpenJDK 64-Bit Server VM Temurin-17.0.2+8 (build 17.0.2+8, mixed mode, sharing) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.7.4.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) Maven home: C:\\eclipse\\tools\\java\\maven Java version: 17.0.2, vendor: Eclipse Adoptium, runtime: C:\\eclipse\\tools\\java\\17 Default locale: de_DE, platform encoding: Cp1252 OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows" ### Additional information _No response_
ed08535c15671fccbbfb217c1414e01e6dd5c303
cf388350609ff4b108dacd09a187523d35b6fc4c
https://github.com/quarkusio/quarkus/compare/ed08535c15671fccbbfb217c1414e01e6dd5c303...cf388350609ff4b108dacd09a187523d35b6fc4c
diff --git a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ComponentsProviderGenerator.java b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ComponentsProviderGenerator.java index 9a2effe1669..475b0c7044a 100644 --- a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ComponentsProviderGenerator.java +++ b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ComponentsProviderGenerator.java @@ -9,12 +9,16 @@ import io.quarkus.arc.ComponentsProvider; import io.quarkus.arc.InjectableBean; import io.quarkus.arc.processor.ResourceOutput.Resource; +import io.quarkus.gizmo.AssignableResultHandle; +import io.quarkus.gizmo.BytecodeCreator; +import io.quarkus.gizmo.CatchBlockCreator; import io.quarkus.gizmo.ClassCreator; import io.quarkus.gizmo.ClassOutput; import io.quarkus.gizmo.FieldDescriptor; import io.quarkus.gizmo.MethodCreator; import io.quarkus.gizmo.MethodDescriptor; import io.quarkus.gizmo.ResultHandle; +import io.quarkus.gizmo.TryBlock; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; @@ -120,8 +124,10 @@ Collection<Resource> generate(String name, BeanDeployment beanDeployment, Map<Be // Break removed beans processing into multiple addRemovedBeans() methods ResultHandle removedBeansHandle = getComponents.newInstance(MethodDescriptor.ofConstructor(ArrayList.class)); + ResultHandle typeCacheHandle = getComponents.newInstance(MethodDescriptor.ofConstructor(HashMap.class)); if (detectUnusedFalsePositives) { - processRemovedBeans(componentsProvider, getComponents, removedBeansHandle, beanDeployment, classOutput); + processRemovedBeans(componentsProvider, getComponents, removedBeansHandle, typeCacheHandle, beanDeployment, + classOutput); } // Qualifier non-binding members @@ -232,9 +238,10 @@ private void processObservers(ClassCreator componentsProvider, MethodCreator get } private void processRemovedBeans(ClassCreator componentsProvider, MethodCreator getComponents, - ResultHandle removedBeansHandle, BeanDeployment beanDeployment, ClassOutput classOutput) { + ResultHandle removedBeansHandle, ResultHandle typeCacheHandle, BeanDeployment beanDeployment, + ClassOutput classOutput) { try (RemovedBeanAdder removedBeanAdder = new RemovedBeanAdder(componentsProvider, getComponents, removedBeansHandle, - classOutput)) { + typeCacheHandle, classOutput)) { for (BeanInfo remnovedBean : beanDeployment.getRemovedBeans()) { removedBeanAdder.addComponent(remnovedBean); } @@ -385,34 +392,40 @@ void addComponentInternal(ObserverInfo observer) { class RemovedBeanAdder extends ComponentAdder<BeanInfo> { private final ResultHandle removedBeansHandle; + private final ResultHandle typeCacheHandle; private final ClassOutput classOutput; private ResultHandle tccl; // Shared annotation literals for an individual addRemovedBeansX() method private final Map<AnnotationInstanceKey, ResultHandle> sharedQualifers; - // Shared java.lang.reflect.Type instances for an individual addRemovedBeansX() method - private final Map<org.jboss.jandex.Type, ResultHandle> sharedTypes; + + private final MapTypeCache typeCache; public RemovedBeanAdder(ClassCreator componentsProvider, MethodCreator getComponentsMethod, - ResultHandle removedBeansHandle, ClassOutput classOutput) { + ResultHandle removedBeansHandle, ResultHandle typeCacheHandle, ClassOutput classOutput) { super(getComponentsMethod, componentsProvider); this.removedBeansHandle = removedBeansHandle; + this.typeCacheHandle = typeCacheHandle; this.classOutput = classOutput; this.sharedQualifers = new HashMap<>(); - this.sharedTypes = new HashMap<>(); + this.typeCache = new MapTypeCache(); } @Override MethodCreator newAddMethod() { // Clear the shared maps for each addRemovedBeansX() method sharedQualifers.clear(); - sharedTypes.clear(); - MethodCreator addMethod = componentsProvider.getMethodCreator(ADD_REMOVED_BEANS + group++, void.class, List.class) + // private void addRemovedBeans1(List removedBeans, List typeCache) + MethodCreator addMethod = componentsProvider + .getMethodCreator(ADD_REMOVED_BEANS + group++, void.class, List.class, Map.class) .setModifiers(ACC_PRIVATE); // Get the TCCL - we will use it later ResultHandle currentThread = addMethod .invokeStaticMethod(MethodDescriptors.THREAD_CURRENT_THREAD); tccl = addMethod.invokeVirtualMethod(MethodDescriptors.THREAD_GET_TCCL, currentThread); + + typeCache.initialize(addMethod); + return addMethod; } @@ -420,8 +433,8 @@ MethodCreator newAddMethod() { void invokeAddMethod() { getComponentsMethod.invokeVirtualMethod( MethodDescriptor.ofMethod(componentsProvider.getClassName(), - addMethod.getMethodDescriptor().getName(), void.class, List.class), - getComponentsMethod.getThis(), removedBeansHandle); + addMethod.getMethodDescriptor().getName(), void.class, List.class, Map.class), + getComponentsMethod.getThis(), removedBeansHandle, typeCacheHandle); } @Override @@ -436,14 +449,20 @@ void addComponentInternal(BeanInfo removedBean) { // Skip java.lang.Object continue; } - ResultHandle typeHandle; + + TryBlock tryBlock = addMethod.tryBlock(); + CatchBlockCreator catchBlock = tryBlock.addCatch(Throwable.class); + catchBlock.invokeStaticInterfaceMethod( + MethodDescriptors.COMPONENTS_PROVIDER_UNABLE_TO_LOAD_REMOVED_BEAN_TYPE, + catchBlock.load(type.toString()), catchBlock.getCaughtException()); + AssignableResultHandle typeHandle = tryBlock.createVariable(Object.class); try { - typeHandle = Types.getTypeHandle(addMethod, type, tccl, sharedTypes); + Types.getTypeHandle(typeHandle, tryBlock, type, tccl, typeCache); } catch (IllegalArgumentException e) { throw new IllegalStateException( "Unable to construct the type handle for " + removedBean + ": " + e.getMessage()); } - addMethod.invokeInterfaceMethod(MethodDescriptors.SET_ADD, typesHandle, typeHandle); + tryBlock.invokeInterfaceMethod(MethodDescriptors.SET_ADD, typesHandle, typeHandle); } // Qualifiers @@ -513,6 +532,27 @@ void addComponentInternal(BeanInfo removedBean) { } + static class MapTypeCache implements Types.TypeCache { + + private ResultHandle mapHandle; + + @Override + public void initialize(MethodCreator method) { + this.mapHandle = method.getMethodParam(1); + } + + @Override + public ResultHandle get(org.jboss.jandex.Type type, BytecodeCreator bytecode) { + return bytecode.invokeInterfaceMethod(MethodDescriptors.MAP_GET, mapHandle, bytecode.load(type.toString())); + } + + @Override + public void put(org.jboss.jandex.Type type, ResultHandle value, BytecodeCreator bytecode) { + bytecode.invokeInterfaceMethod(MethodDescriptors.MAP_PUT, mapHandle, bytecode.load(type.toString()), value); + } + + } + static class BeanAdder extends ComponentAdder<BeanInfo> { private final Set<BeanInfo> processedBeans; diff --git a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/MethodDescriptors.java b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/MethodDescriptors.java index 06622c2f085..b1f8dfad9ed 100644 --- a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/MethodDescriptors.java +++ b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/MethodDescriptors.java @@ -3,6 +3,7 @@ import io.quarkus.arc.Arc; import io.quarkus.arc.ArcContainer; import io.quarkus.arc.ClientProxy; +import io.quarkus.arc.ComponentsProvider; import io.quarkus.arc.InjectableBean; import io.quarkus.arc.InjectableBean.Kind; import io.quarkus.arc.InjectableContext; @@ -80,6 +81,8 @@ public final class MethodDescriptors { public static final MethodDescriptor LIST_ADD = MethodDescriptor.ofMethod(List.class, "add", boolean.class, Object.class); + public static final MethodDescriptor LIST_GET = MethodDescriptor.ofMethod(List.class, "get", Object.class, int.class); + public static final MethodDescriptor OBJECT_EQUALS = MethodDescriptor.ofMethod(Object.class, "equals", boolean.class, Object.class); @@ -265,6 +268,10 @@ public final class MethodDescriptors { .ofMethod(Instances.class, "listOfHandles", List.class, InjectableBean.class, Type.class, Type.class, Set.class, CreationalContextImpl.class, Set.class, Member.class, int.class); + public static final MethodDescriptor COMPONENTS_PROVIDER_UNABLE_TO_LOAD_REMOVED_BEAN_TYPE = MethodDescriptor.ofMethod( + ComponentsProvider.class, "unableToLoadRemovedBeanType", + void.class, String.class, Throwable.class); + private MethodDescriptors() { } diff --git a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/Types.java b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/Types.java index 28284991d4e..50913ddd9bd 100644 --- a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/Types.java +++ b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/Types.java @@ -6,7 +6,10 @@ import io.quarkus.arc.impl.ParameterizedTypeImpl; import io.quarkus.arc.impl.TypeVariableImpl; import io.quarkus.arc.impl.WildcardTypeImpl; +import io.quarkus.gizmo.AssignableResultHandle; +import io.quarkus.gizmo.BranchResult; import io.quarkus.gizmo.BytecodeCreator; +import io.quarkus.gizmo.MethodCreator; import io.quarkus.gizmo.MethodDescriptor; import io.quarkus.gizmo.ResultHandle; import java.util.ArrayList; @@ -76,24 +79,26 @@ public static ResultHandle getTypeHandle(BytecodeCreator creator, Type type) { } public static ResultHandle getTypeHandle(BytecodeCreator creator, Type type, ResultHandle tccl) { - return getTypeHandle(creator, type, tccl, null); + AssignableResultHandle result = creator.createVariable(Object.class); + getTypeHandle(result, creator, type, tccl, null); + return result; } - static ResultHandle getTypeHandle(BytecodeCreator creator, Type type, ResultHandle tccl, - Map<Type, ResultHandle> sharedTypes) { - if (sharedTypes != null) { - ResultHandle sharedType = sharedTypes.get(type); - if (sharedType != null) { - return sharedType; - } + static void getTypeHandle(AssignableResultHandle variable, BytecodeCreator creator, Type type, ResultHandle tccl, + TypeCache cache) { + if (cache != null) { + ResultHandle cachedType = cache.get(type, creator); + BranchResult cachedNull = creator.ifNull(cachedType); + cachedNull.falseBranch().assign(variable, cachedType); + creator = cachedNull.trueBranch(); } if (Kind.CLASS.equals(type.kind())) { String className = type.asClassType().name().toString(); ResultHandle classHandle = doLoadClass(creator, className, tccl); - if (sharedTypes != null) { - sharedTypes.put(type, classHandle); + if (cache != null) { + cache.put(type, classHandle, creator); } - return classHandle; + creator.assign(variable, classHandle); } else if (Kind.TYPE_VARIABLE.equals(type.kind())) { // E.g. T -> new TypeVariableImpl("T") TypeVariable typeVariable = type.asTypeVariable(); @@ -104,69 +109,85 @@ static ResultHandle getTypeHandle(BytecodeCreator creator, Type type, ResultHand } else { boundsHandle = creator.newArray(java.lang.reflect.Type.class, creator.load(bounds.size())); for (int i = 0; i < bounds.size(); i++) { - creator.writeArrayValue(boundsHandle, i, getTypeHandle(creator, bounds.get(i), tccl, sharedTypes)); + AssignableResultHandle boundHandle = creator.createVariable(Object.class); + getTypeHandle(boundHandle, creator, bounds.get(i), tccl, cache); + creator.writeArrayValue(boundsHandle, i, boundHandle); } } ResultHandle typeVariableHandle = creator.newInstance( MethodDescriptor.ofConstructor(TypeVariableImpl.class, String.class, java.lang.reflect.Type[].class), creator.load(typeVariable.identifier()), boundsHandle); - if (sharedTypes != null) { - sharedTypes.put(typeVariable, typeVariableHandle); + if (cache != null) { + cache.put(typeVariable, typeVariableHandle, creator); } - return typeVariableHandle; + creator.assign(variable, typeVariableHandle); } else if (Kind.PARAMETERIZED_TYPE.equals(type.kind())) { // E.g. List<String> -> new ParameterizedTypeImpl(List.class, String.class) - return getParameterizedType(creator, tccl, type.asParameterizedType(), sharedTypes); + getParameterizedType(variable, creator, tccl, type.asParameterizedType(), cache); } else if (Kind.ARRAY.equals(type.kind())) { Type componentType = type.asArrayType().component(); // E.g. String[] -> new GenericArrayTypeImpl(String.class) + AssignableResultHandle componentTypeHandle = creator.createVariable(Object.class); + getTypeHandle(componentTypeHandle, creator, componentType, tccl, cache); ResultHandle arrayHandle = creator.newInstance( MethodDescriptor.ofConstructor(GenericArrayTypeImpl.class, java.lang.reflect.Type.class), - getTypeHandle(creator, componentType, tccl, sharedTypes)); - if (sharedTypes != null) { - sharedTypes.put(type, arrayHandle); + componentTypeHandle); + if (cache != null) { + cache.put(type, arrayHandle, creator); } - return arrayHandle; + creator.assign(variable, arrayHandle); } else if (Kind.WILDCARD_TYPE.equals(type.kind())) { // E.g. ? extends Number -> WildcardTypeImpl.withUpperBound(Number.class) WildcardType wildcardType = type.asWildcardType(); ResultHandle wildcardHandle; if (wildcardType.superBound() == null) { + AssignableResultHandle extendsBoundHandle = creator.createVariable(Object.class); + getTypeHandle(extendsBoundHandle, creator, wildcardType.extendsBound(), tccl, cache); wildcardHandle = creator.invokeStaticMethod( MethodDescriptor.ofMethod(WildcardTypeImpl.class, "withUpperBound", java.lang.reflect.WildcardType.class, java.lang.reflect.Type.class), - getTypeHandle(creator, wildcardType.extendsBound(), tccl, sharedTypes)); + extendsBoundHandle); } else { + AssignableResultHandle superBoundHandle = creator.createVariable(Object.class); + getTypeHandle(superBoundHandle, creator, wildcardType.superBound(), tccl, cache); wildcardHandle = creator.invokeStaticMethod( MethodDescriptor.ofMethod(WildcardTypeImpl.class, "withLowerBound", java.lang.reflect.WildcardType.class, java.lang.reflect.Type.class), - getTypeHandle(creator, wildcardType.superBound(), tccl, sharedTypes)); + superBoundHandle); } - if (sharedTypes != null) { - sharedTypes.put(wildcardType, wildcardHandle); + if (cache != null) { + cache.put(wildcardType, wildcardHandle, creator); } - return wildcardHandle; + creator.assign(variable, wildcardHandle); } else if (Kind.PRIMITIVE.equals(type.kind())) { switch (type.asPrimitiveType().primitive()) { case INT: - return creator.loadClassFromTCCL(int.class); + creator.assign(variable, creator.loadClassFromTCCL(int.class)); + break; case LONG: - return creator.loadClassFromTCCL(long.class); + creator.assign(variable, creator.loadClassFromTCCL(long.class)); + break; case BOOLEAN: - return creator.loadClassFromTCCL(boolean.class); + creator.assign(variable, creator.loadClassFromTCCL(boolean.class)); + break; case BYTE: - return creator.loadClassFromTCCL(byte.class); + creator.assign(variable, creator.loadClassFromTCCL(byte.class)); + break; case CHAR: - return creator.loadClassFromTCCL(char.class); + creator.assign(variable, creator.loadClassFromTCCL(char.class)); + break; case DOUBLE: - return creator.loadClassFromTCCL(double.class); + creator.assign(variable, creator.loadClassFromTCCL(double.class)); + break; case FLOAT: - return creator.loadClassFromTCCL(float.class); + creator.assign(variable, creator.loadClassFromTCCL(float.class)); + break; case SHORT: - return creator.loadClassFromTCCL(short.class); + creator.assign(variable, creator.loadClassFromTCCL(short.class)); + break; default: throw new IllegalArgumentException("Unsupported primitive type: " + type); } @@ -175,37 +196,46 @@ static ResultHandle getTypeHandle(BytecodeCreator creator, Type type, ResultHand } } - static ResultHandle getParameterizedType(BytecodeCreator creator, ResultHandle tccl, - ParameterizedType parameterizedType, Map<Type, ResultHandle> sharedTypes) { + static void getParameterizedType(AssignableResultHandle variable, BytecodeCreator creator, ResultHandle tccl, + ParameterizedType parameterizedType, TypeCache cache) { List<Type> arguments = parameterizedType.arguments(); ResultHandle typeArgsHandle = creator.newArray(java.lang.reflect.Type.class, creator.load(arguments.size())); for (int i = 0; i < arguments.size(); i++) { - creator.writeArrayValue(typeArgsHandle, i, getTypeHandle(creator, arguments.get(i), tccl, sharedTypes)); + AssignableResultHandle argumentHandle = creator.createVariable(Object.class); + getTypeHandle(argumentHandle, creator, arguments.get(i), tccl, cache); + creator.writeArrayValue(typeArgsHandle, i, argumentHandle); } Type rawType = Type.create(parameterizedType.name(), Kind.CLASS); ResultHandle rawTypeHandle = null; - if (sharedTypes != null) { - rawTypeHandle = sharedTypes.get(rawType); + if (cache != null) { + rawTypeHandle = cache.get(rawType, creator); } if (rawTypeHandle == null) { rawTypeHandle = doLoadClass(creator, parameterizedType.name().toString(), tccl); - if (sharedTypes != null) { - sharedTypes.put(rawType, rawTypeHandle); + if (cache != null) { + cache.put(rawType, rawTypeHandle, creator); } } ResultHandle parameterizedTypeHandle = creator.newInstance( MethodDescriptor.ofConstructor(ParameterizedTypeImpl.class, java.lang.reflect.Type.class, java.lang.reflect.Type[].class), rawTypeHandle, typeArgsHandle); - if (sharedTypes != null) { - sharedTypes.put(parameterizedType, parameterizedTypeHandle); + if (cache != null) { + cache.put(parameterizedType, parameterizedTypeHandle, creator); } - return parameterizedTypeHandle; + creator.assign(variable, parameterizedTypeHandle); + } + + public static void getParameterizedType(AssignableResultHandle variable, BytecodeCreator creator, ResultHandle tccl, + ParameterizedType parameterizedType) { + getParameterizedType(variable, creator, tccl, parameterizedType, null); } public static ResultHandle getParameterizedType(BytecodeCreator creator, ResultHandle tccl, ParameterizedType parameterizedType) { - return getParameterizedType(creator, tccl, parameterizedType, null); + AssignableResultHandle result = creator.createVariable(Object.class); + getParameterizedType(result, creator, tccl, parameterizedType, null); + return result; } private static ResultHandle doLoadClass(BytecodeCreator creator, String className, ResultHandle tccl) { @@ -546,4 +576,26 @@ static boolean containsTypeVariable(Type type) { return false; } + interface TypeCache { + + void initialize(MethodCreator method); + + /** + * + * @param type + * @param bytecode + * @return the cached value or {@code null} + */ + ResultHandle get(Type type, BytecodeCreator bytecode); + + /** + * + * @param type + * @param value + * @param bytecode + */ + void put(Type type, ResultHandle value, BytecodeCreator bytecode); + + } + } diff --git a/independent-projects/arc/runtime/src/main/java/io/quarkus/arc/ComponentsProvider.java b/independent-projects/arc/runtime/src/main/java/io/quarkus/arc/ComponentsProvider.java index af2f893e657..6ef91d6baa2 100644 --- a/independent-projects/arc/runtime/src/main/java/io/quarkus/arc/ComponentsProvider.java +++ b/independent-projects/arc/runtime/src/main/java/io/quarkus/arc/ComponentsProvider.java @@ -1,10 +1,18 @@ package io.quarkus.arc; +import org.jboss.logging.Logger; + /** * Service provider interface used to colllect the runtime components. */ public interface ComponentsProvider { + static Logger LOG = Logger.getLogger(ComponentsProvider.class); + Components getComponents(); + static void unableToLoadRemovedBeanType(String type, Throwable problem) { + LOG.warnf("Unable to load removed bean type [%s]: %s", type, problem.toString()); + } + } \\ No newline at end of file
['independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/MethodDescriptors.java', 'independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/Types.java', 'independent-projects/arc/runtime/src/main/java/io/quarkus/arc/ComponentsProvider.java', 'independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ComponentsProviderGenerator.java']
{'.java': 4}
4
4
0
0
4
20,107,371
3,890,528
510,982
4,921
12,399
2,287
223
4
6,591
358
1,585
123
1
2
1970-01-01T00:27:27
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,469
quarkusio/quarkus/24440/24229
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24229
https://github.com/quarkusio/quarkus/pull/24440
https://github.com/quarkusio/quarkus/pull/24440
1
fix
Continuous testing is not picking up custom JUnit extension from same module
### Describe the bug A Junit extension, e.g. a `org.junit.jupiter.api.extension.BeforeAllCallback`, that is registered via `src/test/resources/META-INF/services/org.junit.jupiter.api.extension.Extension` is not picked up when `mvn quarkus:test` (CT) is run in that module. If CT is run in another module that depends on the module that contains the extension, everything works as expected! ### Expected behavior "local" extension is run ### Actual behavior "local" extension is not run/found ### How to Reproduce? [q_ct-junitext.zip](https://github.com/quarkusio/quarkus/files/8222903/q_ct-junitext.zip) - `mvn verify` ✔️ - run test in Eclipse ✔️ - `mvn quarkus:test` ❌ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` 17.0.2, vendor: BellSoft ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.7.3.Final and 2.7.4.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.4 ### Additional information ℹ️ There is no issue when the extension is registered via `@ExtendWith(...)`!
ee867bcdd2fac7e54c8a4ac9318da3b57e0dbcc0
d052ee29ee310b5661308ed2d7d728b9b921d2b3
https://github.com/quarkusio/quarkus/compare/ee867bcdd2fac7e54c8a4ac9318da3b57e0dbcc0...d052ee29ee310b5661308ed2d7d728b9b921d2b3
diff --git a/core/deployment/src/main/java/io/quarkus/deployment/dev/testing/JunitTestRunner.java b/core/deployment/src/main/java/io/quarkus/deployment/dev/testing/JunitTestRunner.java index 4898fccee5e..328d1a12e2b 100644 --- a/core/deployment/src/main/java/io/quarkus/deployment/dev/testing/JunitTestRunner.java +++ b/core/deployment/src/main/java/io/quarkus/deployment/dev/testing/JunitTestRunner.java @@ -195,6 +195,7 @@ public FilterResult apply(TestDescriptor testDescriptor) { return new Runnable() { @Override public void run() { + final ClassLoader origCl = Thread.currentThread().getContextClassLoader(); try { synchronized (JunitTestRunner.this) { testsRunning = true; @@ -222,6 +223,8 @@ public void quarkusStarting() { Map<String, Map<UniqueId, TestResult>> resultsByClass = new HashMap<>(); AtomicReference<TestIdentifier> currentNonDynamicTest = new AtomicReference<>(); + + Thread.currentThread().setContextClassLoader(tcl); launcher.execute(testPlan, new TestExecutionListener() { @Override @@ -396,6 +399,7 @@ public void reportingEntryPublished(TestIdentifier testIdentifier, ReportEntry e throw new RuntimeException(e); } } finally { + Thread.currentThread().setContextClassLoader(origCl); synchronized (JunitTestRunner.this) { testsRunning = false; if (aborted) {
['core/deployment/src/main/java/io/quarkus/deployment/dev/testing/JunitTestRunner.java']
{'.java': 1}
1
1
0
0
1
20,126,718
3,893,749
511,387
4,923
256
33
4
1
1,153
146
310
45
1
0
1970-01-01T00:27:27
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,467
quarkusio/quarkus/24475/24473
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24473
https://github.com/quarkusio/quarkus/pull/24475
https://github.com/quarkusio/quarkus/pull/24475
1
fixes
Redis Shared Dev Services Failed to Connect
### Describe the bug When trying to use Red Dev Services, the second quarkus runtime will fail to connect to the initial redis container due to unsupported redis connection string scheme. ### Expected behavior A successful connection to the shared redis container. ### Actual behavior The connection fails with the following error: java.lang.IllegalArgumentException: Unsupported Redis connection string scheme [localhost] ### How to Reproduce? Reproducer: https://github.com/AdlerFleurant/quarkus-dev-demo Steps to reproduce the behavior (use 3 separate command line tabs): 1. `./gradlew inventory-incoming:quarkusDev` 2. `./gradlew inventory:quarkusDev` 3. `curl http://localhost:8080/entry` Wait for each command to start successfully, before proceeding to the next. After running the third command, the second tab will output an error starting with: java.lang.IllegalArgumentException: Unsupported Redis connection string scheme [localhost] ### Output of `uname -a` or `ver` Darwin xxxxxxx-xxx 21.4.0 Darwin Kernel Version 21.4.0: Mon Feb 21 20:35:58 PST 2022; root:xnu-8020.101.4~2/RELEASE_ARM64_T6000 arm64 ### Output of `java -version` openjdk version "17.0.2" 2022-01-18 OpenJDK Runtime Environment (build 17.0.2+8-86) OpenJDK 64-Bit Server VM (build 17.0.2+8-86, mixed mode, sharing) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.7.5 ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) ------------------------------------------------------------ Gradle 7.4.1 ------------------------------------------------------------ Build time: 2022-03-09 15:04:47 UTC Revision: 36dc52588e09b4b72f2010bc07599e0ee0434e2e Kotlin: 1.5.31 Groovy: 3.0.9 Ant: Apache Ant(TM) version 1.10.11 compiled on July 10 2021 JVM: 17.0.2 (Oracle Corporation 17.0.2+8-86) OS: Mac OS X 12.3 aarch64 ### Additional information _No response_
619288dfa9b11ee6591b8beace4810abef4ac468
db01117e214ff3c7a3063ad527cb3ed0fb693ee8
https://github.com/quarkusio/quarkus/compare/619288dfa9b11ee6591b8beace4810abef4ac468...db01117e214ff3c7a3063ad527cb3ed0fb693ee8
diff --git a/extensions/redis-client/deployment/src/main/java/io/quarkus/redis/client/deployment/DevServicesRedisProcessor.java b/extensions/redis-client/deployment/src/main/java/io/quarkus/redis/client/deployment/DevServicesRedisProcessor.java index 5933c445164..dad2345df6b 100644 --- a/extensions/redis-client/deployment/src/main/java/io/quarkus/redis/client/deployment/DevServicesRedisProcessor.java +++ b/extensions/redis-client/deployment/src/main/java/io/quarkus/redis/client/deployment/DevServicesRedisProcessor.java @@ -184,8 +184,11 @@ private RunningDevService startContainer(String connectionName, DevServicesConfi }; return redisContainerLocator.locateContainer(devServicesConfig.serviceName, devServicesConfig.shared, launchMode) - .map(containerAddress -> new RunningDevService(Feature.REDIS_CLIENT.getName(), containerAddress.getId(), - null, configPrefix + RedisConfig.HOSTS_CONFIG_NAME, containerAddress.getUrl())) + .map(containerAddress -> { + String redisUrl = REDIS_SCHEME + containerAddress.getUrl(); + return new RunningDevService(Feature.REDIS_CLIENT.getName(), containerAddress.getId(), + null, configPrefix + RedisConfig.HOSTS_CONFIG_NAME, redisUrl); + }) .orElseGet(defaultRedisServerSupplier); }
['extensions/redis-client/deployment/src/main/java/io/quarkus/redis/client/deployment/DevServicesRedisProcessor.java']
{'.java': 1}
1
1
0
0
1
20,168,345
3,901,497
512,304
4,933
571
96
7
1
1,966
231
534
51
2
0
1970-01-01T00:27:27
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,466
quarkusio/quarkus/24478/24380
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24380
https://github.com/quarkusio/quarkus/pull/24478
https://github.com/quarkusio/quarkus/pull/24478
1
fix
Last-Modified response header is not properly handled in QuarkusTests using MockHttpEventServer
### Describe the bug I am using RestAssured in a QuarkusTest to test a RestEasy resource endpoint that returns a response containing the header: `Last-Modified: Tue, 26 Oct 2021 01:01:01 GMT` The test goes as follows: ``` @Test void verifyLastModifiedHeader() { RestAssured.given() .accept(JSON) .when() .get("/my-endpoint") .then() .statusCode(200) .header("Last-Modified", "Tue, 26 Oct 2021 01:01:01 GMT"); } ``` The test fails with the following output: > java.lang.AssertionError: 1 expectation failed. Expected header "Last-Modified" was not "Tue, 26 Oct 2021 01:01:01 GMT", was "26 Oct 2021 01:01:01 GMT". Headers are: content-length=84 Access-Control-Allow-Origin=* Access-Control-Allow-Methods=GET Last-Modified=Tue Last-Modified=26 Oct 2021 01:01:01 GMT This seems to be due to the MockHttpEventServer splitting all response headers on `","`. This is logical for multivalue headers, but for Last-Modified (and other related headers such as If-Modified-Since) this behaviour is incorrect. ### Expected behavior _No response_ ### Actual behavior _No response_ ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` openjdk version "17" 2021-09-14 ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.7.5 ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Gradle 7.2 ### Additional information _No response_
ffb8fa04749ef66240c0619a66eb4e8cf03a35a4
8c16bc375ce3e11c1472132d398cd989c6062818
https://github.com/quarkusio/quarkus/compare/ffb8fa04749ef66240c0619a66eb4e8cf03a35a4...8c16bc375ce3e11c1472132d398cd989c6062818
diff --git a/extensions/amazon-lambda-http/http-event-server/src/main/java/io/quarkus/amazon/lambda/runtime/MockHttpEventServer.java b/extensions/amazon-lambda-http/http-event-server/src/main/java/io/quarkus/amazon/lambda/runtime/MockHttpEventServer.java index 25b9106e7f7..9ee81290fab 100644 --- a/extensions/amazon-lambda-http/http-event-server/src/main/java/io/quarkus/amazon/lambda/runtime/MockHttpEventServer.java +++ b/extensions/amazon-lambda-http/http-event-server/src/main/java/io/quarkus/amazon/lambda/runtime/MockHttpEventServer.java @@ -117,8 +117,13 @@ public void processResponse(RoutingContext ctx, RoutingContext pending, Buffer b HttpServerResponse response = pending.response(); if (res.getHeaders() != null) { for (Map.Entry<String, String> header : res.getHeaders().entrySet()) { - for (String val : header.getValue().split(",")) { - response.headers().add(header.getKey(), val); + if (canHaveCommaValue(header.getKey())) { + response.headers().add(header.getKey(), header.getValue()); + + } else { + for (String val : header.getValue().split(",")) { + response.headers().add(header.getKey(), val); + } } } } diff --git a/extensions/amazon-lambda-http/http-event-server/src/test/java/io/quarkus/amazon/lambda/runtime/EventServerTest.java b/extensions/amazon-lambda-http/http-event-server/src/test/java/io/quarkus/amazon/lambda/runtime/EventServerTest.java index 83104912800..9a7b50c9a38 100644 --- a/extensions/amazon-lambda-http/http-event-server/src/test/java/io/quarkus/amazon/lambda/runtime/EventServerTest.java +++ b/extensions/amazon-lambda-http/http-event-server/src/test/java/io/quarkus/amazon/lambda/runtime/EventServerTest.java @@ -79,4 +79,45 @@ public void testServer() throws Exception { Assertions.assertEquals("Hi", lambdaResponse.readEntity(String.class)); lambdaResponse.close(); } + + @Test + public void testDateHeaders() throws Exception { + Client client = ClientBuilder.newBuilder().build(); + WebTarget base = client.target("http://localhost:" + MockEventServer.DEFAULT_PORT); + Future<Response> lambdaInvoke = base.request().async() + .post(Entity.text("Hello World")); + + Response next = base.path(MockEventServer.NEXT_INVOCATION).request().get(); + Assertions.assertEquals(200, next.getStatus()); + String requestId = next.getHeaderString(AmazonLambdaApi.LAMBDA_RUNTIME_AWS_REQUEST_ID); + String traceId = next.getHeaderString(AmazonLambdaApi.LAMBDA_TRACE_HEADER_KEY); + Assertions.assertNotNull(requestId); + Assertions.assertNotNull(traceId); + String json = next.readEntity(String.class); + APIGatewayV2HTTPEvent event = eventReader.readValue(json); + Assertions.assertEquals("text/plain", event.getHeaders().get("Content-Type")); + Assertions.assertEquals("Hello World", event.getBody()); + next.close(); + + APIGatewayV2HTTPResponse res = new APIGatewayV2HTTPResponse(); + res.setStatusCode(201); + res.setHeaders(new HashMap()); + res.getHeaders().put("Content-Type", "text/plain"); + res.getHeaders().put("Last-Modified", "Tue, 26 Oct 2021 01:01:01 GMT"); + res.getHeaders().put("Expires", "Tue, 26 Oct 2021 01:01:01 GMT"); + res.getHeaders().put("Date", "Tue, 26 Oct 2021 01:01:01 GMT"); + res.setBody("Hi"); + Response sendResponse = base.path(MockEventServer.INVOCATION).path(requestId).path("response") + .request().post(Entity.json(resWriter.writeValueAsString(res))); + Assertions.assertEquals(204, sendResponse.getStatus()); + sendResponse.close(); + + Response lambdaResponse = lambdaInvoke.get(); + Assertions.assertEquals(201, lambdaResponse.getStatus()); + Assertions.assertEquals("Hi", lambdaResponse.readEntity(String.class)); + Assertions.assertEquals("Tue, 26 Oct 2021 01:01:01 GMT", lambdaResponse.getStringHeaders().getFirst("Last-Modified")); + Assertions.assertEquals("Tue, 26 Oct 2021 01:01:01 GMT", lambdaResponse.getStringHeaders().getFirst("Expires")); + Assertions.assertEquals("Tue, 26 Oct 2021 01:01:01 GMT", lambdaResponse.getStringHeaders().getFirst("Date")); + lambdaResponse.close(); + } } diff --git a/extensions/amazon-lambda-rest/rest-event-server/src/test/java/io/quarkus/amazon/lambda/runtime/EventServerTest.java b/extensions/amazon-lambda-rest/rest-event-server/src/test/java/io/quarkus/amazon/lambda/runtime/EventServerTest.java index 508ea7e4bba..b5e9cc32502 100644 --- a/extensions/amazon-lambda-rest/rest-event-server/src/test/java/io/quarkus/amazon/lambda/runtime/EventServerTest.java +++ b/extensions/amazon-lambda-rest/rest-event-server/src/test/java/io/quarkus/amazon/lambda/runtime/EventServerTest.java @@ -22,6 +22,7 @@ import io.quarkus.amazon.lambda.http.model.AwsProxyRequest; import io.quarkus.amazon.lambda.http.model.AwsProxyResponse; +import io.quarkus.amazon.lambda.http.model.Headers; public class EventServerTest { @@ -80,4 +81,47 @@ public void testServer() throws Exception { Assertions.assertEquals("Hi", lambdaResponse.readEntity(String.class)); lambdaResponse.close(); } + + @Test + public void testDateHeaders() throws Exception { + Client client = ClientBuilder.newBuilder().build(); + WebTarget base = client.target("http://localhost:" + MockEventServer.DEFAULT_PORT); + Future<Response> lambdaInvoke = base.request().async() + .post(Entity.text("Hello World")); + + Response next = base.path(MockEventServer.NEXT_INVOCATION).request().get(); + Assertions.assertEquals(200, next.getStatus()); + String requestId = next.getHeaderString(AmazonLambdaApi.LAMBDA_RUNTIME_AWS_REQUEST_ID); + String traceId = next.getHeaderString(AmazonLambdaApi.LAMBDA_TRACE_HEADER_KEY); + Assertions.assertNotNull(requestId); + Assertions.assertNotNull(traceId); + String json = next.readEntity(String.class); + AwsProxyRequest event = eventReader.readValue(json); + Assertions.assertEquals("text/plain", event.getMultiValueHeaders().getFirst("Content-Type")); + Assertions.assertEquals("Hello World", event.getBody()); + next.close(); + + AwsProxyResponse res = new AwsProxyResponse(); + res.setStatusCode(201); + res.setMultiValueHeaders(new Headers()); + res.getMultiValueHeaders().add("Content-Type", "text/plain"); + res.getMultiValueHeaders().add("Last-Modified", "Tue, 26 Oct 2021 01:01:01 GMT"); + res.getMultiValueHeaders().add("Expires", "Tue, 26 Oct 2021 01:01:01 GMT"); + res.getMultiValueHeaders().add("Date", "Tue, 26 Oct 2021 01:01:01 GMT"); + res.setBody("Hi"); + Response sendResponse = base.path(MockEventServer.INVOCATION).path(requestId).path("response") + .request().post(Entity.json(resWriter.writeValueAsString(res))); + Assertions.assertEquals(204, sendResponse.getStatus()); + sendResponse.close(); + + Response lambdaResponse = lambdaInvoke.get(); + Assertions.assertEquals(201, lambdaResponse.getStatus()); + Assertions.assertEquals("Hi", lambdaResponse.readEntity(String.class)); + Assertions.assertTrue(lambdaResponse.getStringHeaders().containsKey("Content-Type")); + Assertions.assertEquals("Tue, 26 Oct 2021 01:01:01 GMT", lambdaResponse.getStringHeaders().getFirst("Last-Modified")); + Assertions.assertEquals("Tue, 26 Oct 2021 01:01:01 GMT", lambdaResponse.getStringHeaders().getFirst("Expires")); + Assertions.assertEquals("Tue, 26 Oct 2021 01:01:01 GMT", lambdaResponse.getStringHeaders().getFirst("Date")); + lambdaResponse.close(); + } + } diff --git a/extensions/amazon-lambda/event-server/src/main/java/io/quarkus/amazon/lambda/runtime/MockEventServer.java b/extensions/amazon-lambda/event-server/src/main/java/io/quarkus/amazon/lambda/runtime/MockEventServer.java index 5429ea1d805..95330ea6dc2 100644 --- a/extensions/amazon-lambda/event-server/src/main/java/io/quarkus/amazon/lambda/runtime/MockEventServer.java +++ b/extensions/amazon-lambda/event-server/src/main/java/io/quarkus/amazon/lambda/runtime/MockEventServer.java @@ -2,6 +2,9 @@ import java.io.Closeable; import java.io.IOException; +import java.util.HashSet; +import java.util.Locale; +import java.util.Set; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; @@ -40,6 +43,21 @@ public class MockEventServer implements Closeable { public static final String NEXT_INVOCATION = BASE_PATH + AmazonLambdaApi.API_PATH_INVOCATION_NEXT; public static final String POST_EVENT = BASE_PATH; public static final String CONTINUE = "100-continue"; + private static final Set<String> COMMA_VALUE_HEADERS; + + static { + COMMA_VALUE_HEADERS = new HashSet<>(); + COMMA_VALUE_HEADERS.add("date"); + COMMA_VALUE_HEADERS.add("last-modified"); + COMMA_VALUE_HEADERS.add("expires"); + COMMA_VALUE_HEADERS.add("if-modified-since"); + COMMA_VALUE_HEADERS.add("if-unmodified-since"); + } + + public static boolean canHaveCommaValue(String header) { + return COMMA_VALUE_HEADERS.contains(header.toLowerCase(Locale.ROOT)); + } + final AtomicBoolean closed = new AtomicBoolean(); public MockEventServer() {
['extensions/amazon-lambda-http/http-event-server/src/test/java/io/quarkus/amazon/lambda/runtime/EventServerTest.java', 'extensions/amazon-lambda-rest/rest-event-server/src/test/java/io/quarkus/amazon/lambda/runtime/EventServerTest.java', 'extensions/amazon-lambda-http/http-event-server/src/main/java/io/quarkus/amazon/lambda/runtime/MockHttpEventServer.java', 'extensions/amazon-lambda/event-server/src/main/java/io/quarkus/amazon/lambda/runtime/MockEventServer.java']
{'.java': 4}
4
4
0
0
4
20,166,552
3,901,169
512,258
4,932
1,137
200
27
2
1,626
198
417
67
0
1
1970-01-01T00:27:27
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,465
quarkusio/quarkus/24491/10402
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/10402
https://github.com/quarkusio/quarkus/pull/24491
https://github.com/quarkusio/quarkus/pull/24491
1
fix
RemoteControlledSampler fails with "No strategy present in response. Not updating sampler." in native mode
**Describe the bug** When using Jaeger tracing by adding: `io.quarkus:quarkus-jaeger`, tracing seems to work, but a periodic error message is in the log, when using native mode. I assume that updating the strategy is broken as well. **Expected behavior** Same as JVM mode: No error message. Update works. **Actual behavior** ~~~ 2020-07-01T11:31:05.711Z ERROR [RemoteControlledSampler] No strategy present in response. Not updating sampler. ~~~ **To Reproduce** Steps to reproduce the behavior: 1. Enable tracing 2. Check the logs 3. **Environment (please complete the following information):** - Output of `uname -a` or `ver`: - Output of `java -version`: - GraalVM version (if different from Java): - Quarkus version or git rev: - Build tool (ie. output of `mvnw --version` or `gradlew --version`):
7dcdbdb864d992922a470c39ca47af7acf6f207d
d6bffc0d25f3aadef54172ebe87d1b238f51e7ec
https://github.com/quarkusio/quarkus/compare/7dcdbdb864d992922a470c39ca47af7acf6f207d...d6bffc0d25f3aadef54172ebe87d1b238f51e7ec
diff --git a/extensions/jaeger/deployment/src/main/java/io/quarkus/jaeger/deployment/JaegerProcessor.java b/extensions/jaeger/deployment/src/main/java/io/quarkus/jaeger/deployment/JaegerProcessor.java index 06e9e0308f6..a45fd1c9dea 100644 --- a/extensions/jaeger/deployment/src/main/java/io/quarkus/jaeger/deployment/JaegerProcessor.java +++ b/extensions/jaeger/deployment/src/main/java/io/quarkus/jaeger/deployment/JaegerProcessor.java @@ -62,6 +62,8 @@ public ReflectiveClassBuildItem reflectiveClasses() { "io.jaegertracing.internal.samplers.http.ProbabilisticSamplingStrategy", "io.jaegertracing.internal.samplers.http.RateLimitingSamplingStrategy", "io.jaegertracing.internal.samplers.http.SamplingStrategyResponse") - .finalFieldsWritable(true).build(); + .fields(true) + .finalFieldsWritable(true) + .build(); } }
['extensions/jaeger/deployment/src/main/java/io/quarkus/jaeger/deployment/JaegerProcessor.java']
{'.java': 1}
1
1
0
0
1
20,168,978
3,901,684
512,319
4,934
154
25
4
1
848
120
220
29
0
0
1970-01-01T00:27:28
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,464
quarkusio/quarkus/24512/24260
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24260
https://github.com/quarkusio/quarkus/pull/24512
https://github.com/quarkusio/quarkus/pull/24512
1
close
Gradle quarkusGenerateCode task with composite build dependency causes jar does not exist
### Describe the bug Our gradle composite build intermittently fails with dependent jars not existing (see below sample output). It always fails on the quarkusGenerateCode task of a module that depends on a jar produced by the included build. We don't usually run this task directly, but running it directly reproduces the issue much more consistently. ``` > Task :service-mocks:aws-orchestration-mock:quarkusGenerateCode FAILED preparing quarkus application FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':service-mocks:aws-orchestration-mock:quarkusGenerateCode'. > [...]/quarkus-composite-build-issue/common/common-util/build/libs/common-util-1.0.jar does not exist ``` ### Expected behavior I should be able to run the gradle quarkusGenerateCode task and dependencies should correctly be resolved prior to execution. ### Actual behavior quarkusGenerateCode task fails with an error indicating the composite build dependency jar does not exist ### How to Reproduce? From the root of the attached project if you run the gradle command: `./gradlew :common:common-util:clean :services:acme-service:clean :services:acme-service:quarkusGenerateCode` It should reproduce the issue. There is a commented out line in `services/acme-service/build.gradle` that adds an explicit dependency on the included composite build's jar task that can be used as a workaround. [quarkus-composite-build-issue.zip](https://github.com/quarkusio/quarkus/files/8227922/quarkus-composite-build-issue.zip) ### Output of `uname -a` or `ver` Darwin Kernel Version 21.3.0 ### Output of `java -version` openjdk version "11.0.11" ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.7.4.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Gradle 7.4 ### Additional information _No response_
4b0bbdb73655f64e6272f5e60810942917b86810
426a9e9c9892a36c205c1c72a1c5d3b78bbb846c
https://github.com/quarkusio/quarkus/compare/4b0bbdb73655f64e6272f5e60810942917b86810...426a9e9c9892a36c205c1c72a1c5d3b78bbb846c
diff --git a/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/QuarkusPlugin.java b/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/QuarkusPlugin.java index dc53392336a..cef5d097ac7 100644 --- a/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/QuarkusPlugin.java +++ b/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/QuarkusPlugin.java @@ -198,9 +198,25 @@ public void execute(Task test) { TaskProvider<Task> testClassesTask = tasks.named(JavaPlugin.TEST_CLASSES_TASK_NAME); TaskProvider<Task> testResourcesTask = tasks.named(JavaPlugin.PROCESS_TEST_RESOURCES_TASK_NAME); - quarkusGenerateCode.configure(task -> task.dependsOn(resourcesTask)); - quarkusGenerateCodeDev.configure(task -> task.dependsOn(resourcesTask)); - quarkusGenerateCodeTests.configure(task -> task.dependsOn(resourcesTask)); + quarkusGenerateCode.configure(task -> { + task.dependsOn(resourcesTask); + task.setCompileClasspath( + project.getConfigurations().getByName( + ApplicationDeploymentClasspathBuilder.getBaseRuntimeConfigName(LaunchMode.NORMAL))); + }); + quarkusGenerateCodeDev.configure(task -> { + task.dependsOn(resourcesTask); + task.setCompileClasspath( + project.getConfigurations().getByName( + ApplicationDeploymentClasspathBuilder + .getBaseRuntimeConfigName(LaunchMode.DEVELOPMENT))); + }); + quarkusGenerateCodeTests.configure(task -> { + task.dependsOn(resourcesTask); + task.setCompileClasspath( + project.getConfigurations().getByName( + ApplicationDeploymentClasspathBuilder.getBaseRuntimeConfigName(LaunchMode.TEST))); + }); quarkusDev.configure(task -> { task.dependsOn(classesTask, resourcesTask, testClassesTask, testResourcesTask, diff --git a/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusGenerateCode.java b/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusGenerateCode.java index 623c20a54dd..0021c5ea005 100644 --- a/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusGenerateCode.java +++ b/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusGenerateCode.java @@ -15,7 +15,7 @@ import java.util.function.Consumer; import org.gradle.api.GradleException; -import org.gradle.api.file.FileCollection; +import org.gradle.api.artifacts.Configuration; import org.gradle.api.plugins.JavaPluginConvention; import org.gradle.api.tasks.CompileClasspath; import org.gradle.api.tasks.InputFiles; @@ -42,6 +42,7 @@ public class QuarkusGenerateCode extends QuarkusTask { public static final String INIT_AND_RUN = "initAndRun"; private Set<Path> sourcesDirectories; + private Configuration compileClasspath; private Consumer<Path> sourceRegistrar = (p) -> { }; private boolean test = false; @@ -57,8 +58,12 @@ public QuarkusGenerateCode() { * @return resolved compile classpath */ @CompileClasspath - public FileCollection getClasspath() { - return QuarkusGradleUtils.getSourceSet(getProject(), SourceSet.MAIN_SOURCE_SET_NAME).getCompileClasspath(); + public Configuration getClasspath() { + return compileClasspath; + } + + public void setCompileClasspath(Configuration compileClasspath) { + this.compileClasspath = compileClasspath; } @InputFiles
['devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusGenerateCode.java', 'devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/QuarkusPlugin.java']
{'.java': 2}
2
2
0
0
2
20,189,733
3,905,679
512,849
4,939
2,019
304
33
2
1,910
232
460
58
1
1
1970-01-01T00:27:28
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,463
quarkusio/quarkus/24534/24384
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24384
https://github.com/quarkusio/quarkus/pull/24534
https://github.com/quarkusio/quarkus/pull/24534
1
fix
Hot reload does not build multi module project in correct order
### Describe the bug I have a multi module project, where I get exceptions on hot reload. If I only change one module at a time (and hot reload), no exception is thrown. If i change multiple modules at the same time however, I get the exception from below. In a related bug, #23164, only one additionalModule existed other than the applicationArchive. #24187 was the fix for that situation. However, in my real world applications, I have a few modules more.. about 20 of them iirc. My project structure looks like this: parent - service (business logic) - rest (web stuff, has dependency on service) - backend (module containing the quarkus plugin, has dependency on rest) Doing a change in service (e.g. adding a method), using the new method in rest, and then reloading the changes in these 2 modules causes the exception. ### Expected behavior Hot reload works flawlessly even when changing multiple modules at once. ### Actual behavior ``` Listening for transport dt_socket at address: 5005 __ ____ __ _____ ___ __ ____ ______ --/ __ \\/ / / / _ | / _ \\/ //_/ / / / __/ -/ /_/ / /_/ / __ |/ , _/ ,< / /_/ /\\ \\ --\\___\\_\\____/_/ |_/_/|_/_/|_|\\____/___/ 2022-03-17 20:17:21,863 INFO [io.quarkus] (Quarkus Main Thread) backend 1.0.0-SNAPSHOT on JVM (powered by Quarkus 999-SNAPSHOT) started in 1.481s. Listening on: http://localhost:8080 2022-03-17 20:17:21,875 INFO [io.quarkus] (Quarkus Main Thread) Profile dev activated. Live Coding activated. 2022-03-17 20:17:21,876 INFO [io.quarkus] (Quarkus Main Thread) Installed features: [cdi, resteasy-reactive, smallrye-context-propagation, vertx] -- Compilation Failed: C:\\Users\\Martin\\IdeaProjects\\ap-test\\rest\\src\\main\\java\\org\\acme\\rest\\ExampleResource.java:24: error: method greet in class org.acme.service.ExampleService cannot be applied to given types; return service.greet("Quarkus"); ^ required: java.lang.String,java.lang.String found: java.lang.String reason: actual and formal argument lists differ in length ``` ### How to Reproduce? Download the reproducer: [ap-test.zip](https://github.com/quarkusio/quarkus/files/8291575/ap-test.zip) 1. mvn clean compile quarkus:dev 2. open dev ui - this works 3. In org.acme.service.ExampleService, adder another parameter to greet() 4. In org.acme.rest.ExampleResource, change the resource to call the changed greet method. 5. reload the dev ui 6. compilation error from above happens 7. Stop quarkus 8. mvn clean compile quarkus:dev 9. open dev ui - this works. The source itself is compileable by maven, but not by quarkus. ### Output of `uname -a` or `ver` Microsoft Windows [Version 10.0.22000.556] ### Output of `java -version` openjdk 17.0.1 2021-10-19 OpenJDK Runtime Environment Temurin-17.0.1+12 (build 17.0.1+12) OpenJDK 64-Bit Server VM Temurin-17.0.1+12 (build 17.0.1+12, mixed mode, sharing) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.7.5.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.3 (ff8e977a158738155dc465c6a97ffaf31982d739) Maven home: C:\\tools\\java\\maven Java version: 17.0.1, vendor: Eclipse Adoptium, runtime: C:\\tools\\java\\17-temurin Default locale: de_DE, platform encoding: Cp1252 OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows" ### Additional information _No response_
afba0c25e84be4ac121e14d035a5a79758ab652a
8e7c98aa1eeb9e5a457aa07b7edddc5cd9dd28c5
https://github.com/quarkusio/quarkus/compare/afba0c25e84be4ac121e14d035a5a79758ab652a...8e7c98aa1eeb9e5a457aa07b7edddc5cd9dd28c5
diff --git a/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildStep.java b/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildStep.java index bcf1759c005..844727aad0f 100644 --- a/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildStep.java +++ b/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildStep.java @@ -42,7 +42,6 @@ import io.quarkus.deployment.pkg.builditem.ProcessInheritIODisabled; import io.quarkus.deployment.pkg.builditem.ProcessInheritIODisabledBuildItem; import io.quarkus.deployment.steps.LocaleProcessor; -import io.quarkus.maven.dependency.GACTV; import io.quarkus.maven.dependency.ResolvedDependency; import io.quarkus.runtime.LocalesBuildTimeConfig; @@ -313,7 +312,7 @@ private void copyJarSourcesToLib(OutputTargetBuildItem outputTargetBuildItem, } for (ResolvedDependency depArtifact : curateOutcomeBuildItem.getApplicationModel().getRuntimeDependencies()) { - if (depArtifact.getType().equals(GACTV.TYPE_JAR)) { + if (depArtifact.isJar()) { for (Path resolvedDep : depArtifact.getResolvedPaths()) { if (!Files.isDirectory(resolvedDep)) { // Do we need to handle transformed classes? diff --git a/independent-projects/bootstrap/app-model/src/main/java/io/quarkus/maven/dependency/ArtifactCoords.java b/independent-projects/bootstrap/app-model/src/main/java/io/quarkus/maven/dependency/ArtifactCoords.java index 58ce084b729..1ba8bd4f7ed 100644 --- a/independent-projects/bootstrap/app-model/src/main/java/io/quarkus/maven/dependency/ArtifactCoords.java +++ b/independent-projects/bootstrap/app-model/src/main/java/io/quarkus/maven/dependency/ArtifactCoords.java @@ -18,6 +18,10 @@ public interface ArtifactCoords { ArtifactKey getKey(); + default boolean isJar() { + return TYPE_JAR.equals(getType()); + } + default String toGACTVString() { return getGroupId() + ":" + getArtifactId() + ":" + getClassifier() + ":" + getType() + ":" + getVersion(); } @@ -28,7 +32,7 @@ default String toCompactCoords() { if (!getClassifier().isEmpty()) { b.append(getClassifier()).append(':'); } - if (!TYPE_JAR.equals(getType())) { + if (!isJar()) { b.append(getType()).append(':'); } b.append(getVersion()); diff --git a/independent-projects/bootstrap/core/src/main/java/io/quarkus/bootstrap/app/CuratedApplication.java b/independent-projects/bootstrap/core/src/main/java/io/quarkus/bootstrap/app/CuratedApplication.java index 129541af447..d6b826942f4 100644 --- a/independent-projects/bootstrap/core/src/main/java/io/quarkus/bootstrap/app/CuratedApplication.java +++ b/independent-projects/bootstrap/core/src/main/java/io/quarkus/bootstrap/app/CuratedApplication.java @@ -8,7 +8,6 @@ import io.quarkus.bootstrap.model.AppModel; import io.quarkus.bootstrap.model.ApplicationModel; import io.quarkus.bootstrap.util.BootstrapUtils; -import io.quarkus.maven.dependency.ArtifactCoords; import io.quarkus.maven.dependency.ArtifactKey; import io.quarkus.maven.dependency.ResolvedDependency; import io.quarkus.paths.OpenPathTree; @@ -150,7 +149,7 @@ private Object runInCl(String consumerName, Map<String, Object> params, QuarkusC } private synchronized void processCpElement(ResolvedDependency artifact, Consumer<ClassPathElement> consumer) { - if (!artifact.getType().equals(ArtifactCoords.TYPE_JAR)) { + if (!artifact.isJar()) { //avoid the need for this sort of check in multiple places consumer.accept(ClassPathElement.EMPTY); return; @@ -337,8 +336,7 @@ public QuarkusClassLoader createDeploymentClassLoader() { } } for (ResolvedDependency dependency : appModel.getDependencies()) { - if (dependency.isRuntimeCp() && - dependency.getType().equals(ArtifactCoords.TYPE_JAR) && + if (dependency.isRuntimeCp() && dependency.isJar() && (dependency.isReloadable() && appModel.getReloadableWorkspaceDependencies().contains(dependency.getKey()) || configuredClassLoading.reloadableArtifacts.contains(dependency.getKey()))) { processCpElement(dependency, element -> addCpElement(builder, dependency, element)); @@ -375,8 +373,7 @@ public QuarkusClassLoader createRuntimeClassLoader(ClassLoader base, Map<String, } } for (ResolvedDependency dependency : appModel.getDependencies()) { - if (dependency.isRuntimeCp() && - dependency.getType().equals(ArtifactCoords.TYPE_JAR) && + if (dependency.isRuntimeCp() && dependency.isJar() && (dependency.isReloadable() && appModel.getReloadableWorkspaceDependencies().contains(dependency.getKey()) || configuredClassLoading.reloadableArtifacts.contains(dependency.getKey()))) { processCpElement(dependency, element -> addCpElement(builder, dependency, element)); diff --git a/independent-projects/bootstrap/core/src/main/java/io/quarkus/bootstrap/devmode/DependenciesFilter.java b/independent-projects/bootstrap/core/src/main/java/io/quarkus/bootstrap/devmode/DependenciesFilter.java index 388c6db0fda..622d4a5ed3a 100644 --- a/independent-projects/bootstrap/core/src/main/java/io/quarkus/bootstrap/devmode/DependenciesFilter.java +++ b/independent-projects/bootstrap/core/src/main/java/io/quarkus/bootstrap/devmode/DependenciesFilter.java @@ -1,10 +1,13 @@ package io.quarkus.bootstrap.devmode; import io.quarkus.bootstrap.model.ApplicationModel; -import io.quarkus.maven.dependency.GACTV; +import io.quarkus.maven.dependency.ArtifactKey; +import io.quarkus.maven.dependency.Dependency; import io.quarkus.maven.dependency.ResolvedDependency; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.jboss.logging.Logger; public class DependenciesFilter { @@ -12,30 +15,86 @@ public class DependenciesFilter { private static final Logger log = Logger.getLogger(DependenciesFilter.class); public static List<ResolvedDependency> getReloadableModules(ApplicationModel appModel) { - final List<ResolvedDependency> reloadable = new ArrayList<>(); - if (appModel.getApplicationModule() != null) { - reloadable.add(appModel.getAppArtifact()); - } + final Map<ArtifactKey, WorkspaceDependencies> modules = new HashMap<>(); appModel.getDependencies().forEach(d -> { if (d.isReloadable()) { - reloadable.add(d); + modules.put(d.getKey(), new WorkspaceDependencies(d)); } else if (d.isWorkspaceModule()) { //if this project also contains Quarkus extensions we do no want to include these in the discovery //a bit of an edge case, but if you try and include a sample project with your extension you will //run into problems without this final StringBuilder msg = new StringBuilder(); - msg.append("Local Quarkus extension dependency "); - msg.append(d.getGroupId()).append(":").append(d.getArtifactId()).append(":"); - if (!d.getClassifier().isEmpty()) { - msg.append(d.getClassifier()).append(":"); - } - if (!GACTV.TYPE_JAR.equals(d.getType())) { - msg.append(d.getType()).append(":"); - } - msg.append(d.getVersion()).append(" will not be hot-reloadable"); + msg.append("Local Quarkus extension dependency ").append(d.toCompactCoords()) + .append(" will not be hot-reloadable"); log.warn(msg.toString()); } }); - return reloadable; + if (modules.isEmpty()) { + return appModel.getApplicationModule() == null ? List.of() : List.of(appModel.getAppArtifact()); + } + + if (appModel.getApplicationModule() != null) { + modules.put(appModel.getAppArtifact().getKey(), new WorkspaceDependencies(appModel.getAppArtifact())); + } + + // Here we are sorting the reloadable dependencies according to their interdependencies to make sure + // they are compiled in the correct order + + for (WorkspaceDependencies ad : modules.values()) { + for (Dependency dd : ad.artifact.getWorkspaceModule().getDirectDependencies()) { + final WorkspaceDependencies dep = modules.get(dd.getKey()); + if (dep != null) { + ad.addDependency(dep); + } + } + } + + final List<ResolvedDependency> sorted = new ArrayList<>(); + int toBeSorted; + do { + toBeSorted = 0; + for (WorkspaceDependencies ad : modules.values()) { + if (ad.sorted) { + continue; + } + if (ad.hasNotSortedDependencies()) { + ++toBeSorted; + continue; + } + ad.sorted = true; + sorted.add(ad.artifact); + } + } while (toBeSorted > 0); + + return sorted; + } + + private static class WorkspaceDependencies { + final ResolvedDependency artifact; + List<WorkspaceDependencies> deps; + boolean sorted; + + WorkspaceDependencies(ResolvedDependency artifact) { + this.artifact = artifact; + } + + boolean hasNotSortedDependencies() { + if (deps == null) { + return false; + } + for (WorkspaceDependencies d : deps) { + if (!d.sorted) { + return true; + } + } + return false; + } + + void addDependency(WorkspaceDependencies dep) { + if (deps == null) { + deps = new ArrayList<>(); + } + deps.add(dep); + } } } diff --git a/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/workspace/LocalProject.java b/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/workspace/LocalProject.java index 25cd99bc9c5..e3b46676c41 100644 --- a/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/workspace/LocalProject.java +++ b/independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/workspace/LocalProject.java @@ -374,7 +374,8 @@ public WorkspaceModule toWorkspaceModule() { moduleBuilder.setDependencyConstraints(getRawModel().getDependencyManagement() == null ? Collections.emptyList() : toArtifactDependencies(getRawModel().getDependencyManagement().getDependencies())); - moduleBuilder.setDependencies(toArtifactDependencies(getRawModel().getDependencies())); + final Model model = modelBuildingResult == null ? rawModel : modelBuildingResult.getEffectiveModel(); + moduleBuilder.setDependencies(toArtifactDependencies(model.getDependencies())); return this.module = moduleBuilder.build(); } diff --git a/integration-tests/maven/src/test/java/io/quarkus/maven/it/DevMojoIT.java b/integration-tests/maven/src/test/java/io/quarkus/maven/it/DevMojoIT.java index b1c1c028676..f8c7e7f4b2d 100644 --- a/integration-tests/maven/src/test/java/io/quarkus/maven/it/DevMojoIT.java +++ b/integration-tests/maven/src/test/java/io/quarkus/maven/it/DevMojoIT.java @@ -1194,6 +1194,39 @@ public void testThatDependencyInParentIsEvaluated() throws IOException, MavenInv runAndCheck(); } + @Test + public void testModuleCompileOrder() throws IOException, MavenInvocationException { + testDir = initProject("projects/multimodule-parent-dep", "projects/multimodule-compile-order"); + runAndCheck("-Dquarkus.bootstrap.effective-model-builder"); + + assertThat(DevModeTestUtils.getHttpResponse("/app/hello/")).isEqualTo("hello"); + + // modify classes in all the modules and make sure they are compiled in a correct order + File resource = new File(testDir, "level0/src/main/java/org/acme/level0/Level0Service.java"); + filter(resource, Collections.singletonMap("getGreeting()", "getGreeting(String name)")); + filter(resource, Collections.singletonMap("return greeting;", "return greeting + \\" \\" + name;")); + + resource = new File(testDir, "level1/src/main/java/org/acme/level1/Level1Service.java"); + filter(resource, Collections.singletonMap("getGreetingFromLevel0()", "getGreetingFromLevel0(String name)")); + filter(resource, Collections.singletonMap("level0Service.getGreeting()", "level0Service.getGreeting(name)")); + + resource = new File(testDir, "level2/submodule/src/main/java/org/acme/level2/submodule/Level2Service.java"); + filter(resource, Collections.singletonMap("getGreetingFromLevel1()", "getGreetingFromLevel1(String name)")); + filter(resource, + Collections.singletonMap("level1Service.getGreetingFromLevel0()", "level1Service.getGreetingFromLevel0(name)")); + + resource = new File(testDir, "runner/src/main/java/org/acme/rest/HelloResource.java"); + filter(resource, Collections.singletonMap("level0Service.getGreeting()", + "level0Service.getGreeting(\\"world\\")")); + filter(resource, Collections.singletonMap("level2Service.getGreetingFromLevel1()", + "level2Service.getGreetingFromLevel1(\\"world\\")")); + + await() + .pollDelay(300, TimeUnit.MILLISECONDS) + .atMost(1, TimeUnit.MINUTES) + .until(() -> DevModeTestUtils.getHttpResponse("/app/hello").contains("hello world")); + } + @Test public void testThatGenerateCodeGoalIsNotTriggeredIfNotConfigured() throws IOException, MavenInvocationException { testDir = initProject("projects/classic-no-generate");
['core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildStep.java', 'independent-projects/bootstrap/core/src/main/java/io/quarkus/bootstrap/devmode/DependenciesFilter.java', 'independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/workspace/LocalProject.java', 'independent-projects/bootstrap/app-model/src/main/java/io/quarkus/maven/dependency/ArtifactCoords.java', 'independent-projects/bootstrap/core/src/main/java/io/quarkus/bootstrap/app/CuratedApplication.java', 'integration-tests/maven/src/test/java/io/quarkus/maven/it/DevMojoIT.java']
{'.java': 6}
6
6
0
0
6
20,245,980
3,916,918
514,295
4,955
4,641
863
112
5
4,439
463
1,018
85
2
1
1970-01-01T00:27:28
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,460
quarkusio/quarkus/24587/16429
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/16429
https://github.com/quarkusio/quarkus/pull/24587
https://github.com/quarkusio/quarkus/pull/24587
1
fixes
gradle quarkusBuild has error : SRCFG00035: Failed to load resource
Since upgrading from to 1.13.x, run below command ``` ./gradlew quarkusBuild -Dquarkus.package.type=uber-jar -Dorg.gradle.jvmargs=-Xmx256m ``` Gradle made a error: SRCFG00035: Failed to load resource, full stacktrace is: ``` > Task :processResources > Task :classes start copy some files... > Task :inspectClassesForKotlinIC > Task :jar > Task :quarkusBuild building quarkus jar > Task :quarkusBuild FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':quarkusBuild'. > java.lang.IllegalStateException: SRCFG00035: Failed to load resource * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. ``` My system jdk version : ``` openjdk 11.0.10 2021-01-19 OpenJDK Runtime Environment 18.9 (build 11.0.10+9) OpenJDK 64-Bit Server VM 18.9 (build 11.0.10+9, mixed mode, sharing) ``` when I use `adoptjdk15-openj9` or downgrade quarkus version to `1.12.2.Final`, it' all fine.
4f5dfa504bf1fe856c6be1cf53a442159bcadc32
694e9743ed57c408c873f2be6aa22270cbc0fa52
https://github.com/quarkusio/quarkus/compare/4f5dfa504bf1fe856c6be1cf53a442159bcadc32...694e9743ed57c408c873f2be6aa22270cbc0fa52
diff --git a/extensions/config-yaml/runtime/src/main/java/io/quarkus/config/yaml/runtime/ApplicationYamlConfigSourceLoader.java b/extensions/config-yaml/runtime/src/main/java/io/quarkus/config/yaml/runtime/ApplicationYamlConfigSourceLoader.java index 2f063642c30..9badce01571 100644 --- a/extensions/config-yaml/runtime/src/main/java/io/quarkus/config/yaml/runtime/ApplicationYamlConfigSourceLoader.java +++ b/extensions/config-yaml/runtime/src/main/java/io/quarkus/config/yaml/runtime/ApplicationYamlConfigSourceLoader.java @@ -3,6 +3,7 @@ import java.io.IOException; import java.net.URI; import java.net.URL; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; @@ -45,8 +46,12 @@ public static class InFileSystem extends ApplicationYamlConfigSourceLoader imple @Override public List<ConfigSource> getConfigSources(final ClassLoader classLoader) { List<ConfigSource> configSources = new ArrayList<>(); - configSources.addAll(loadConfigSources("config/application.yaml", 265, classLoader)); - configSources.addAll(loadConfigSources("config/application.yml", 265, classLoader)); + configSources.addAll(loadConfigSources( + Paths.get(System.getProperty("user.dir"), "config", "application.yaml").toUri().toString(), 265, + classLoader)); + configSources.addAll( + loadConfigSources(Paths.get(System.getProperty("user.dir"), "config", "application.yml").toUri().toString(), + 265, classLoader)); return configSources; }
['extensions/config-yaml/runtime/src/main/java/io/quarkus/config/yaml/runtime/ApplicationYamlConfigSourceLoader.java']
{'.java': 1}
1
1
0
0
1
20,251,200
3,917,919
514,438
4,953
646
115
9
1
1,059
144
318
37
0
3
1970-01-01T00:27:28
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,459
quarkusio/quarkus/24628/24452
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24452
https://github.com/quarkusio/quarkus/pull/24628
https://github.com/quarkusio/quarkus/pull/24628
1
close
CDI issue with avro after migration to Quarkus 2.7
### Describe the bug We have a Quarkus application with **Java** and **Kotlin** sources. This component contains an avro file used to produce messages for Kafka Gradle build of this application works perfectly with Quarkus 2.6 (2.6.3.Final) But after migration to Quarkus 2.7 (2.7.5.Final), gradle build fails with some dependencies injection issues (see below) It seems that some classes generated from Kotlin sources are not found by @Inject annotation used in classes generated from Java sources. If we remove avro generation from this component, gradle build works fine. ### Expected behavior > Task :quarkusBuild Caching disabled for task ':quarkusBuild' because: Build cache is disabled Task ':quarkusBuild' is not up-to-date because: Task has failed previously. building quarkus jar > Task :quarkusBuild Quarkus augmentation completed in 6991ms :quarkusBuild (Thread[Execution worker for ':',5,main]) completed. Took 8.685 secs. :assemble (Thread[Execution worker for ':',5,main]) started. > Task :assemble Skipping task ':assemble' as it has no actions. :assemble (Thread[Execution worker for ':',5,main]) completed. Took 0.0 secs. :check (Thread[Execution worker for ':',5,main]) started. > Task :check Skipping task ':check' as it has no actions. :check (Thread[Execution worker for ':',5,main]) completed. Took 0.0 secs. :build (Thread[Execution worker for ':',5,main]) started. > Task :build Skipping task ':build' as it has no actions. :build (Thread[Execution worker for ':',5,main]) completed. Took 0.0 secs. BUILD SUCCESSFUL ### Actual behavior > Task :quarkusBuild FAILED :quarkusBuild (Thread[Execution worker for ':',5,main]) completed. Took 10.161 secs. FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':quarkusBuild'. > io.quarkus.builder.BuildException: Build failure: Build failed due to errors [error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: Found 8 deployment problems: Unsatisfied dependency for type xxx.xxx.MonitoringEventService and qualifiers [@Default] - java member: xxx.xxx.XxxxService#monitoringEventService - declared on CLASS bean [types=[xxx.xxx.XxxxService, java.lang.Object], qualifiers=[@Default, @Any], target=xxx.xxx.XxxxService] ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` 11.0.10 ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.7.5.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
c6c2788cfcc9139842b0e7257c674ed710412a55
e74ba9fee2c922640f287facedc1655838353217
https://github.com/quarkusio/quarkus/compare/c6c2788cfcc9139842b0e7257c674ed710412a55...e74ba9fee2c922640f287facedc1655838353217
diff --git a/devtools/gradle/gradle-model/src/main/java/io/quarkus/gradle/tooling/GradleApplicationModelBuilder.java b/devtools/gradle/gradle-model/src/main/java/io/quarkus/gradle/tooling/GradleApplicationModelBuilder.java index 8027eb438f7..89561b107a9 100644 --- a/devtools/gradle/gradle-model/src/main/java/io/quarkus/gradle/tooling/GradleApplicationModelBuilder.java +++ b/devtools/gradle/gradle-model/src/main/java/io/quarkus/gradle/tooling/GradleApplicationModelBuilder.java @@ -156,11 +156,12 @@ public static ResolvedDependency getProjectArtifact(Project project, LaunchMode private static void collectDestinationDirs(Collection<SourceDir> sources, final PathList.Builder paths) { for (SourceDir src : sources) { if (!Files.exists(src.getOutputDir())) { - return; + continue; } + final Path path = src.getOutputDir(); if (paths.contains(path)) { - return; + continue; } paths.add(path); }
['devtools/gradle/gradle-model/src/main/java/io/quarkus/gradle/tooling/GradleApplicationModelBuilder.java']
{'.java': 1}
1
1
0
0
1
20,280,892
3,923,318
515,163
4,964
105
12
5
1
2,752
343
695
85
0
0
1970-01-01T00:27:28
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,458
quarkusio/quarkus/24645/24613
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24613
https://github.com/quarkusio/quarkus/pull/24645
https://github.com/quarkusio/quarkus/pull/24645
1
fixes
Regression: Quarkus-cli create app doesn't auto-detect Host java version
### Describe the bug When you create an app with `Quarkus-cli 2.6.3` the tool detects the java version that is running in the developer environment and the resulted app has the same java version as the host. This feature is broken in `Quarkus 2.7.5.Final` Reproducer: Quarkus 2.6.3 Install quarkus-cli 2.6.3: `jbang app install --name qs2.6.3 io.quarkus:quarkus-cli:2.6.3.Final:runner ` Create app: `qs2.6.3 create app app` The pom has the same Java version as the host machine. Quarkus 2.7.5 Install quarkus-cli 2.6.3: `jbang app install --name qs2.7.5 io.quarkus:quarkus-cli:2.7.5.Final:runner ` Create app: `qs2.7.5 create app app` Pom Java version:`<maven.compiler.release>11</maven.compiler.release> ` Expected version: `17` ### Output of `java -version` openjdk 17.0.1 2021-10-19 OpenJDK Runtime Environment Temurin-17.0.1+12 (build 17.0.1+12) OpenJDK 64-Bit Server VM Temurin-17.0.1+12 (build 17.0.1+12, mixed mode, sharing)
0de2c19c79713b6889c69435c23e2786869a3db1
be33427db39f867304eb995c12fe7e1d6fd6f6c2
https://github.com/quarkusio/quarkus/compare/0de2c19c79713b6889c69435c23e2786869a3db1...be33427db39f867304eb995c12fe7e1d6fd6f6c2
diff --git a/devtools/cli/src/main/java/io/quarkus/cli/create/TargetLanguageGroup.java b/devtools/cli/src/main/java/io/quarkus/cli/create/TargetLanguageGroup.java index ee88757a6f0..2ac56d3063b 100644 --- a/devtools/cli/src/main/java/io/quarkus/cli/create/TargetLanguageGroup.java +++ b/devtools/cli/src/main/java/io/quarkus/cli/create/TargetLanguageGroup.java @@ -1,8 +1,8 @@ package io.quarkus.cli.create; import java.util.ArrayList; -import java.util.List; import java.util.Set; +import java.util.stream.Collectors; import io.quarkus.cli.common.OutputOptionMixin; import io.quarkus.devtools.project.BuildTool; @@ -17,13 +17,13 @@ public class TargetLanguageGroup { static class VersionCandidates extends ArrayList<String> { VersionCandidates() { - super(List.copyOf(CreateProjectHelper.JAVA_VERSIONS_LTS)); + super(CreateProjectHelper.JAVA_VERSIONS_LTS.stream().map(String::valueOf).collect(Collectors.toList())); } } @CommandLine.Option(names = { - "--java" }, description = "Target Java version.\\n Valid values: ${COMPLETION-CANDIDATES}", completionCandidates = VersionCandidates.class, defaultValue = CreateProjectHelper.DEFAULT_JAVA_VERSION) - String javaVersion = CreateProjectHelper.DEFAULT_JAVA_VERSION; + "--java" }, description = "Target Java version.\\n Valid values: ${COMPLETION-CANDIDATES}", completionCandidates = VersionCandidates.class, defaultValue = CreateProjectHelper.DETECT_JAVA_RUNTIME_VERSION) + String javaVersion = CreateProjectHelper.DETECT_JAVA_RUNTIME_VERSION; @CommandLine.Option(names = { "--kotlin" }, description = "Use Kotlin") boolean kotlin = false; diff --git a/independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/codestarts/jbang/QuarkusJBangCodestartProjectInputBuilder.java b/independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/codestarts/jbang/QuarkusJBangCodestartProjectInputBuilder.java index e91d362d1db..e9018cdfc93 100644 --- a/independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/codestarts/jbang/QuarkusJBangCodestartProjectInputBuilder.java +++ b/independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/codestarts/jbang/QuarkusJBangCodestartProjectInputBuilder.java @@ -84,7 +84,8 @@ public boolean noJBangWrapper() { public QuarkusJBangCodestartProjectInput build() { if (!this.containsData("java")) { - this.addData(NestedMaps.unflatten(Map.of("java.version", CreateProjectHelper.DEFAULT_JAVA_VERSION))); + this.addData(NestedMaps + .unflatten(Map.of("java.version", String.valueOf(CreateProjectHelper.determineBestJavaLtsVersion())))); } return new QuarkusJBangCodestartProjectInput(this); } diff --git a/independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/project/codegen/CreateProjectHelper.java b/independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/project/codegen/CreateProjectHelper.java index 8127af5766a..a8371290c75 100644 --- a/independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/project/codegen/CreateProjectHelper.java +++ b/independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/project/codegen/CreateProjectHelper.java @@ -8,10 +8,13 @@ import java.nio.file.Path; import java.util.Collection; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -19,9 +22,11 @@ public class CreateProjectHelper { - public static final Set<String> JAVA_VERSIONS_LTS = Set.of("11", "17"); - public static final String DEFAULT_JAVA_VERSION = "11"; - private static final Pattern JAVA_VERSION_PATTERN = Pattern.compile("(?:1\\\\.)?(\\\\d+)(?:\\\\..*)?"); + // ordering is important here, so let's keep them ordered + public static final SortedSet<Integer> JAVA_VERSIONS_LTS = new TreeSet<>(List.of(11, 17)); + private static final int DEFAULT_JAVA_VERSION = 11; + public static final String DETECT_JAVA_RUNTIME_VERSION = "<<detect java runtime version>>"; + private static final Pattern JAVA_VERSION_PATTERN = Pattern.compile("(\\\\d+)(?:\\\\..*)?"); public static final String DEFAULT_GROUP_ID = "org.acme"; public static final String DEFAULT_ARTIFACT_ID = "code-with-quarkus"; @@ -79,16 +84,36 @@ public static SourceType determineSourceType(Set<String> extensions) { public static void setJavaVersion(Map<String, Object> values, String javaTarget) { requireNonNull(values, "Must provide values"); - Matcher matcher = JAVA_VERSION_PATTERN - .matcher(javaTarget != null ? javaTarget : System.getProperty("java.version", "")); + Integer javaFeatureVersionTarget = null; - if (matcher.matches()) { - String versionExtracted = matcher.group(1); - String version = JAVA_VERSIONS_LTS.contains(versionExtracted) ? versionExtracted : DEFAULT_JAVA_VERSION; - values.put(ProjectGenerator.JAVA_TARGET, version); - } else { - values.put(ProjectGenerator.JAVA_TARGET, DEFAULT_JAVA_VERSION); + if (javaTarget != null && !DETECT_JAVA_RUNTIME_VERSION.equals(javaTarget)) { + // Probably too much as we should push only the feature version but let's be as thorough as we used to be + Matcher matcher = JAVA_VERSION_PATTERN.matcher(javaTarget); + if (matcher.matches()) { + javaFeatureVersionTarget = Integer.valueOf(matcher.group(1)); + } + } + + if (javaFeatureVersionTarget == null) { + javaFeatureVersionTarget = Runtime.version().feature(); + } + + values.put(ProjectGenerator.JAVA_TARGET, String.valueOf(determineBestJavaLtsVersion(javaFeatureVersionTarget))); + } + + public static int determineBestJavaLtsVersion() { + return determineBestJavaLtsVersion(Runtime.version().feature()); + } + + public static int determineBestJavaLtsVersion(int runtimeVersion) { + int bestLtsVersion = DEFAULT_JAVA_VERSION; + for (int ltsVersion : JAVA_VERSIONS_LTS) { + if (ltsVersion > runtimeVersion) { + break; + } + bestLtsVersion = ltsVersion; } + return bestLtsVersion; } public static Set<String> sanitizeExtensions(Set<String> extensions) { diff --git a/independent-projects/tools/devtools-common/src/test/java/io/quarkus/devtools/project/codegen/CreateProjectHelperTest.java b/independent-projects/tools/devtools-common/src/test/java/io/quarkus/devtools/project/codegen/CreateProjectHelperTest.java index 3c1e4169877..8e0dc592e7c 100644 --- a/independent-projects/tools/devtools-common/src/test/java/io/quarkus/devtools/project/codegen/CreateProjectHelperTest.java +++ b/independent-projects/tools/devtools-common/src/test/java/io/quarkus/devtools/project/codegen/CreateProjectHelperTest.java @@ -11,7 +11,7 @@ class CreateProjectHelperTest { @Test public void givenJavaVersion17ShouldReturn17() { Map<String, Object> values = new HashMap<>(); - values.put("nonull", "nonull"); + values.put("nonnull", "nonnull"); CreateProjectHelper.setJavaVersion(values, "17"); assertEquals("17", values.get("java_target")); @@ -20,9 +20,46 @@ public void givenJavaVersion17ShouldReturn17() { @Test public void givenJavaVersion16ShouldReturn11() { Map<String, Object> values = new HashMap<>(); - values.put("nonull", "nonull"); + values.put("nonnull", "nonnull"); CreateProjectHelper.setJavaVersion(values, "16.0.1"); assertEquals("11", values.get("java_target")); } + + @Test + public void givenJavaVersion11ShouldReturn11() { + Map<String, Object> values = new HashMap<>(); + values.put("nonnull", "nonnull"); + + CreateProjectHelper.setJavaVersion(values, "11"); + assertEquals("11", values.get("java_target")); + } + + @Test + public void givenJavaVersion18ShouldReturn17() { + Map<String, Object> values = new HashMap<>(); + values.put("nonnull", "nonnull"); + + CreateProjectHelper.setJavaVersion(values, "18"); + assertEquals("17", values.get("java_target")); + } + + @Test + public void givenAutoDetectShouldReturnAppropriateVersion() { + Map<String, Object> values = new HashMap<>(); + values.put("nonnull", "nonnull"); + + CreateProjectHelper.setJavaVersion(values, CreateProjectHelper.DETECT_JAVA_RUNTIME_VERSION); + assertEquals(String.valueOf(CreateProjectHelper.determineBestJavaLtsVersion(Runtime.version().feature())), + values.get("java_target")); + } + + @Test + public void testDetermineBestLtsVersion() { + assertEquals(11, CreateProjectHelper.determineBestJavaLtsVersion(8)); + assertEquals(11, CreateProjectHelper.determineBestJavaLtsVersion(11)); + assertEquals(11, CreateProjectHelper.determineBestJavaLtsVersion(12)); + assertEquals(17, CreateProjectHelper.determineBestJavaLtsVersion(17)); + assertEquals(17, CreateProjectHelper.determineBestJavaLtsVersion(18)); + } } diff --git a/independent-projects/tools/devtools-testing/src/test/java/io/quarkus/devtools/codestarts/jbang/QuarkusJBangCodestartGenerationTest.java b/independent-projects/tools/devtools-testing/src/test/java/io/quarkus/devtools/codestarts/jbang/QuarkusJBangCodestartGenerationTest.java index ee3ec9669f8..4c36f4f26db 100644 --- a/independent-projects/tools/devtools-testing/src/test/java/io/quarkus/devtools/codestarts/jbang/QuarkusJBangCodestartGenerationTest.java +++ b/independent-projects/tools/devtools-testing/src/test/java/io/quarkus/devtools/codestarts/jbang/QuarkusJBangCodestartGenerationTest.java @@ -6,10 +6,12 @@ import static io.quarkus.devtools.testing.SnapshotTesting.assertThatDirectoryTreeMatchSnapshots; import static io.quarkus.devtools.testing.SnapshotTesting.assertThatMatchSnapshot; +import io.quarkus.devtools.codestarts.utils.NestedMaps; import io.quarkus.devtools.testing.SnapshotTesting; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Map; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; @@ -29,6 +31,9 @@ void generateDefaultProject(TestInfo testInfo) throws Throwable { .putData(QUARKUS_BOM_GROUP_ID, "io.quarkus") .putData(QUARKUS_BOM_ARTIFACT_ID, "quarkus-bom") .putData(QUARKUS_BOM_VERSION, "999-MOCK") + // define the version here as it is now autodetecting the best LTS version at runtime + // and we want a static version for the snapshots + .addData(NestedMaps.unflatten(Map.of("java.version", "11"))) .build(); final Path projectDir = testDirPath.resolve("default"); getCatalog().createProject(input).generate(projectDir); @@ -43,6 +48,9 @@ void generatePicocliProject(TestInfo testInfo) throws Throwable { .putData(QUARKUS_BOM_GROUP_ID, "io.quarkus") .putData(QUARKUS_BOM_ARTIFACT_ID, "quarkus-bom") .putData(QUARKUS_BOM_VERSION, "999-MOCK") + // define the version here as it is now autodetecting the best LTS version at runtime + // and we want a static version for the snapshots + .addData(NestedMaps.unflatten(Map.of("java.version", "11"))) .build(); final Path projectDir = testDirPath.resolve("picocli"); getCatalog().createProject(input).generate(projectDir);
['devtools/cli/src/main/java/io/quarkus/cli/create/TargetLanguageGroup.java', 'independent-projects/tools/devtools-common/src/test/java/io/quarkus/devtools/project/codegen/CreateProjectHelperTest.java', 'independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/codestarts/jbang/QuarkusJBangCodestartProjectInputBuilder.java', 'independent-projects/tools/devtools-testing/src/test/java/io/quarkus/devtools/codestarts/jbang/QuarkusJBangCodestartGenerationTest.java', 'independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/project/codegen/CreateProjectHelper.java']
{'.java': 5}
5
5
0
0
5
20,278,341
3,922,706
515,116
4,964
3,551
729
58
3
975
123
342
28
0
0
1970-01-01T00:27:28
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,457
quarkusio/quarkus/24651/24542
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24542
https://github.com/quarkusio/quarkus/pull/24651
https://github.com/quarkusio/quarkus/pull/24651
1
fix
Update quarkus.quartz.datasource documentation
### Describe the bug The documentation https://github.com/quarkusio/quarkus/blob/main/extensions/quartz/runtime/src/main/java/io/quarkus/quartz/runtime/QuartzBuildTimeConfig.java#L46 is referring to `db` store which has long been deprecated and removed. We should update the javadoc to refer to `jdbc-tx` or `jdbc-cmt` job stores instead. ### Expected behavior There is no mention of `db` store in the Quarkus documentation ### Actual behavior `db` store is still mentioned ### How to Reproduce? Go to https://quarkus.io/guides/quartz#quarkus-quartz_quarkus.quartz.datasource and observe the `db` in the description. ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
c5650f9eb103f237252a3438058cb416b41c96ba
c52f7b187ef96428e2052869cd364f7e050e4bfe
https://github.com/quarkusio/quarkus/compare/c5650f9eb103f237252a3438058cb416b41c96ba...c52f7b187ef96428e2052869cd364f7e050e4bfe
diff --git a/extensions/quartz/runtime/src/main/java/io/quarkus/quartz/runtime/QuartzBuildTimeConfig.java b/extensions/quartz/runtime/src/main/java/io/quarkus/quartz/runtime/QuartzBuildTimeConfig.java index cda45a3e349..380c283e4fe 100644 --- a/extensions/quartz/runtime/src/main/java/io/quarkus/quartz/runtime/QuartzBuildTimeConfig.java +++ b/extensions/quartz/runtime/src/main/java/io/quarkus/quartz/runtime/QuartzBuildTimeConfig.java @@ -43,7 +43,7 @@ public class QuartzBuildTimeConfig { /** * The name of the datasource to use. * <p> - * Optionally needed when using the `db` store type. + * Optionally needed when using the `jdbc-tx` or `jdbc-cmt` store types. * If not specified, defaults to using the default datasource. */ @ConfigItem(name = "datasource")
['extensions/quartz/runtime/src/main/java/io/quarkus/quartz/runtime/QuartzBuildTimeConfig.java']
{'.java': 1}
1
1
0
0
1
20,278,656
3,922,836
515,164
4,966
135
34
2
1
959
120
242
40
2
0
1970-01-01T00:27:28
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,456
quarkusio/quarkus/24665/24646
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24646
https://github.com/quarkusio/quarkus/pull/24665
https://github.com/quarkusio/quarkus/pull/24665
1
fixes
Async Events behave inconsistently on Exceptions
### Describe the bug If an event is fired (and observed) asynchronously, the returned CompletionStage behaves differently in the case of exceptions depending on the number of observers that threw exceptions. This violates the [CDI Spec, 10.5.1](https://jakarta.ee/specifications/cdi/3.0/jakarta-cdi-spec-3.0.html#async_exception). ### Expected behavior Both test methods should be green. ### Actual behavior The test case `testSingleFailure` fails, because the `CompletionStage` contains the `IllegalArgumentException` directly instead of a `CompletionException` containing the `IllegalArgumentException` as the spec requires. ``` java.lang.AssertionError: Expecting actual throwable to be an instance of: java.util.concurrent.CompletionException but was: java.lang.IllegalArgumentException at com.example.EventTest$Observer1.failOn42And47(EventDecoratorTest.java:71) at com.example.EventTest_Observer1_Observer_failOn42And47_df18bd4f87120ec5a98ebc09b259d85482e10edc.notify(Unknown Source) at io.quarkus.arc.impl.EventImpl$Notifier.notifyObservers(EventImpl.java:320) ...(10 remaining lines not displayed - this can be changed with Assertions.setMaxStackTraceElementsDisplayed) at com.example.EventTest.testSingleFailure(EventDecoratorTest.java:43) ``` ### How to Reproduce? ``` // imports @QuarkusTest class EventTest { @Inject Observer1 observer1; @Inject Observer2 observer2; @Inject Event<Integer> event; @Test void testSingleFailure() throws InterruptedException, TimeoutException { final CompletionStage<Integer> stage = event.fireAsync(42); try { stage.toCompletableFuture().get(30, TimeUnit.SECONDS); failBecauseExceptionWasNotThrown(ExecutionException.class); } catch (ExecutionException ex) { assertThat(ex.getCause()).isInstanceOf(CompletionException.class) .extracting(Throwable::getSuppressed, as(ARRAY)) .hasSize(1) .hasAtLeastOneElementOfType(IllegalArgumentException.class); } } @Test void testTwoFailures() throws InterruptedException, TimeoutException { final CompletionStage<Integer> stage = event.fireAsync(47); try { stage.toCompletableFuture().get(30, TimeUnit.SECONDS); failBecauseExceptionWasNotThrown(ExecutionException.class); } catch (ExecutionException ex) { assertThat(ex.getCause()).isInstanceOf(CompletionException.class) .extracting(Throwable::getSuppressed, as(ARRAY)) .hasSize(2) .hasAtLeastOneElementOfType(IllegalArgumentException.class) .hasAtLeastOneElementOfType(IllegalStateException.class); } } @ApplicationScoped static class Observer1 { void failOn42And47(@ObservesAsync int value) { if (value == 42 || value == 47) { throw new IllegalArgumentException(); } } } @ApplicationScoped static class Observer2 { void failOn47(@ObservesAsync int value) { if (value == 47) { throw new IllegalStateException(); } } } } ``` ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` 11.0.11, vendor: AdoptOpenJDK, runtime: C:\\Program Files\\AdoptOpenJDK\\jdk-11.0.11.9-hotspot ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.7.5.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.1 (05c21c65bdfed0f71a2f2ada8b84da59348c4c5d) ### Additional information _No response_
1dafb4feb8442c7c36a43ee886447b51123e8c9d
cfa320453feb51704516c77ee046e90292fe718b
https://github.com/quarkusio/quarkus/compare/1dafb4feb8442c7c36a43ee886447b51123e8c9d...cfa320453feb51704516c77ee046e90292fe718b
diff --git a/independent-projects/arc/runtime/src/main/java/io/quarkus/arc/impl/EventImpl.java b/independent-projects/arc/runtime/src/main/java/io/quarkus/arc/impl/EventImpl.java index 9168cd4469b..efe44c3c54d 100644 --- a/independent-projects/arc/runtime/src/main/java/io/quarkus/arc/impl/EventImpl.java +++ b/independent-projects/arc/runtime/src/main/java/io/quarkus/arc/impl/EventImpl.java @@ -207,9 +207,10 @@ private void handleExceptions(ObserverExceptionHandler handler) { exception = new CompletionException(handledExceptions.get(0)); } else { exception = new CompletionException(null); - for (Throwable handledException : handledExceptions) { - exception.addSuppressed(handledException); - } + } + // always add exceptions into suppressed + for (Throwable handledException : handledExceptions) { + exception.addSuppressed(handledException); } throw exception; } diff --git a/independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/observers/async/AsyncObserverExceptionTest.java b/independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/observers/async/AsyncObserverExceptionTest.java index ca43f015c20..781111b9ccf 100644 --- a/independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/observers/async/AsyncObserverExceptionTest.java +++ b/independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/observers/async/AsyncObserverExceptionTest.java @@ -2,19 +2,21 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import io.quarkus.arc.Arc; import io.quarkus.arc.ArcContainer; import io.quarkus.arc.test.ArcTestContainer; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionStage; import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.ExecutionException; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; import javax.annotation.PostConstruct; import javax.annotation.Priority; import javax.enterprise.context.Dependent; @@ -31,20 +33,30 @@ public class AsyncObserverExceptionTest { public ArcTestContainer container = new ArcTestContainer(StringProducer.class, StringObserver.class); @Test - public void testAsyncObservers() throws InterruptedException, ExecutionException, TimeoutException { + public void testAsyncObserversSingleException() throws InterruptedException { ArcContainer container = Arc.container(); StringProducer producer = container.instance(StringProducer.class).get(); StringObserver observer = container.instance(StringObserver.class).get(); - BlockingQueue<Object> synchronizer = new LinkedBlockingQueue<>(); + final List<Throwable> suppressed = new ArrayList<>(); + BlockingQueue<Throwable> synchronizer = new LinkedBlockingQueue<>(); producer.produceAsync("pong").exceptionally(ex -> { + Arrays.stream(ex.getSuppressed()).forEach(t -> suppressed.add(t)); synchronizer.add(ex); return ex.getMessage(); }); - Object exception = synchronizer.poll(10, TimeUnit.SECONDS); + Throwable exception = synchronizer.poll(10, TimeUnit.SECONDS); + + // assert suppressed exception is always present + assertEquals(1, suppressed.size()); + assertTrue(suppressed.get(0) instanceof RuntimeException); + + // assert actual exception, always a CompletionException assertNotNull(exception); - assertTrue(exception instanceof RuntimeException); + assertTrue(exception instanceof CompletionException); + // in case of single exception in event chain, the cause is the exception + assertTrue(exception.getCause() instanceof RuntimeException); List<String> events = observer.getEvents(); assertEquals(2, events.size()); @@ -52,6 +64,40 @@ public void testAsyncObservers() throws InterruptedException, ExecutionException assertEquals("async2::pong", events.get(1)); } + @Test + public void testAsyncObserversMultipleExceptions() throws InterruptedException { + ArcContainer container = Arc.container(); + StringProducer producer = container.instance(StringProducer.class).get(); + StringObserver observer = container.instance(StringObserver.class).get(); + + final List<Throwable> suppressed = new ArrayList<>(); + BlockingQueue<Throwable> synchronizer = new LinkedBlockingQueue<>(); + producer.produceAsync("ping").exceptionally(ex -> { + Arrays.stream(ex.getSuppressed()).forEach(t -> suppressed.add(t)); + synchronizer.add(ex); + return ex.getMessage(); + }); + + Throwable exception = synchronizer.poll(10, TimeUnit.SECONDS); + + // assert all suppressed exceptions are present + assertEquals(2, suppressed.size()); + assertTrue(suppressed.get(0) instanceof RuntimeException); + assertTrue(suppressed.get(1) instanceof IllegalStateException); + + // assert actual exception, always a CompletionException + assertNotNull(exception); + assertTrue(exception instanceof CompletionException); + // in case of multiple exceptions in event chain, the cause is expected to be null + assertNull(exception.getCause()); + + List<String> events = observer.getEvents(); + assertEquals(3, events.size()); + assertEquals("async1::ping", events.get(0)); + assertEquals("async2::ping", events.get(1)); + assertEquals("async3::ping", events.get(2)); + } + @Singleton static class StringObserver { @@ -71,6 +117,13 @@ void observeAsync2(@ObservesAsync @Priority(2) String value) { events.add("async2::" + value); } + void observeAsync3(@ObservesAsync @Priority(3) String value) { + if (value.equals("ping")) { + events.add("async3::" + value); + throw new IllegalStateException("nok"); + } + } + List<String> getEvents() { return events; }
['independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/observers/async/AsyncObserverExceptionTest.java', 'independent-projects/arc/runtime/src/main/java/io/quarkus/arc/impl/EventImpl.java']
{'.java': 2}
2
2
0
0
2
20,280,268
3,923,158
515,213
4,967
351
52
7
1
3,790
291
848
121
1
2
1970-01-01T00:27:28
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,455
quarkusio/quarkus/24693/24322
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24322
https://github.com/quarkusio/quarkus/pull/24693
https://github.com/quarkusio/quarkus/pull/24693
1
fixes
Config like `mp.messaging.connector.smallrye-kafka.value.serializer` is ignored
### Describe the bug The build step `SmallRyeReactiveMessagingKafkaProcessor#defaultChannelConfiguration()` currently ignores checking for connector-level config like `mp.messaging.connector.smallrye-kafka.value.serializer`. As a result this configuration has no effect when added to the `application.properties` file because the generated channel-level `RunTimeConfigurationDefaultBuildItem` defaults take precedence. See also discussion in Zulip: https://quarkusio.zulipchat.com/#narrow/stream/187030-users/topic/.E2.9C.94.20Kafka.3A.20Apicurio.20for.20dev.20and.20Confluent.20for.20prod.20mode.3F ### Expected behavior Explicit connector-level config in `application.properties` should take precedence over generated channel-level defaults. The build step should probably check for the presence of such properties at build time to determine whether to generate a runtime default or not for a given channel's properties. #### Use case We are using Kafka with a schema registry and Avro encoded messages. In production the schema registry is the Confluent implementation and for development in dev mode we use Apicurio. This means that the serializer and deserializer implementation classes are different for production and non-production (i.e. test and development) launch modes. Further, since our application uses multiple channels, we would like to declare the Avro serializer and deserializer at the connector level, rather than individually for each channel. Doing it for each channel results in a lot of duplicated config. ### Actual behavior The explicit connector-level config (like `mp.messaging.connector.smallrye-kafka.value.serializer`) in the `application.properties` file is ignored, because the autodetection generates corresponding channel-level config which takes precedence. ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.7.4.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information
9aa0739ea58bc19172390eaf493c1a69778091f9
366ea7430df9939292cd0ac7f4dae3df7c503a93
https://github.com/quarkusio/quarkus/compare/9aa0739ea58bc19172390eaf493c1a69778091f9...366ea7430df9939292cd0ac7f4dae3df7c503a93
diff --git a/extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeDiscoveryState.java b/extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeDiscoveryState.java index cda62e4596c..555a611e175 100644 --- a/extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeDiscoveryState.java +++ b/extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeDiscoveryState.java @@ -8,6 +8,7 @@ import java.util.Set; import java.util.stream.Collectors; +import org.eclipse.microprofile.config.Config; import org.eclipse.microprofile.config.ConfigProvider; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationTarget; @@ -26,6 +27,11 @@ class DefaultSerdeDiscoveryState { private final Map<String, Boolean> isKafkaConnector = new HashMap<>(); private final Set<String> alreadyConfigured = new HashSet<>(); + private Boolean connectorHasKeySerializer; + private Boolean connectorHasValueSerializer; + private Boolean connectorHasKeyDeserializer; + private Boolean connectorHasValueDeserializer; + private Boolean hasConfluent; private Boolean hasApicurio1; private Boolean hasApicurio2; @@ -35,6 +41,10 @@ class DefaultSerdeDiscoveryState { this.index = index; } + Config getConfig() { + return ConfigProvider.getConfig(); + } + boolean isKafkaConnector(List<ConnectorManagedChannelBuildItem> channelsManagedByConnectors, boolean incoming, String channelName) { // First look in the channelsManagedByConnectors list @@ -48,13 +58,61 @@ boolean isKafkaConnector(List<ConnectorManagedChannelBuildItem> channelsManagedB String channelType = incoming ? "incoming" : "outgoing"; return isKafkaConnector.computeIfAbsent(channelType + "|" + channelName, ignored -> { String connectorKey = "mp.messaging." + channelType + "." + channelName + ".connector"; - String connector = ConfigProvider.getConfig() + String connector = getConfig() .getOptionalValue(connectorKey, String.class) .orElse("ignored"); return KafkaConnector.CONNECTOR_NAME.equals(connector); }); } + boolean shouldNotConfigure(String key) { + // if we know at build time that key/value [de]serializer is configured on the connector, + // we should NOT emit default configuration for key/value [de]serializer on the channel + // (in other words, only a user can explicitly override a connector configuration) + // + // more config properties could possibly be handled in the same way, but these should suffice for now + + if (key.startsWith("mp.messaging.outgoing.") && key.endsWith(".key.serializer")) { + if (connectorHasKeySerializer == null) { + connectorHasKeySerializer = getConfig() + .getOptionalValue("mp.messaging.connector." + KafkaConnector.CONNECTOR_NAME + ".key.serializer", + String.class) + .isPresent(); + } + return connectorHasKeySerializer; + } + if (key.startsWith("mp.messaging.outgoing.") && key.endsWith(".value.serializer")) { + if (connectorHasValueSerializer == null) { + connectorHasValueSerializer = getConfig() + .getOptionalValue("mp.messaging.connector." + KafkaConnector.CONNECTOR_NAME + ".value.serializer", + String.class) + .isPresent(); + } + return connectorHasValueSerializer; + } + + if (key.startsWith("mp.messaging.incoming.") && key.endsWith(".key.deserializer")) { + if (connectorHasKeyDeserializer == null) { + connectorHasKeyDeserializer = getConfig() + .getOptionalValue("mp.messaging.connector." + KafkaConnector.CONNECTOR_NAME + ".key.deserializer", + String.class) + .isPresent(); + } + return connectorHasKeyDeserializer; + } + if (key.startsWith("mp.messaging.incoming.") && key.endsWith(".value.deserializer")) { + if (connectorHasValueDeserializer == null) { + connectorHasValueDeserializer = getConfig() + .getOptionalValue("mp.messaging.connector." + KafkaConnector.CONNECTOR_NAME + ".value.deserializer", + String.class) + .isPresent(); + } + return connectorHasValueDeserializer; + } + + return false; + } + void ifNotYetConfigured(String key, Runnable runnable) { if (!alreadyConfigured.contains(key)) { alreadyConfigured.add(key); diff --git a/extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/SmallRyeReactiveMessagingKafkaProcessor.java b/extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/SmallRyeReactiveMessagingKafkaProcessor.java index 18513a1fb02..2770b0dc637 100644 --- a/extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/SmallRyeReactiveMessagingKafkaProcessor.java +++ b/extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/SmallRyeReactiveMessagingKafkaProcessor.java @@ -243,6 +243,10 @@ private void produceRuntimeConfigurationDefaultBuildItem(DefaultSerdeDiscoverySt return; } + if (discovery.shouldNotConfigure(key)) { + return; + } + discovery.ifNotYetConfigured(key, () -> { config.produce(new RunTimeConfigurationDefaultBuildItem(key, value)); }); diff --git a/extensions/smallrye-reactive-messaging-kafka/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeConfigTest.java b/extensions/smallrye-reactive-messaging-kafka/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeConfigTest.java index 328a837b928..ba94e489267 100644 --- a/extensions/smallrye-reactive-messaging-kafka/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeConfigTest.java +++ b/extensions/smallrye-reactive-messaging-kafka/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeConfigTest.java @@ -8,6 +8,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.concurrent.CompletionStage; import javax.inject.Inject; @@ -19,6 +20,8 @@ import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.header.Headers; import org.assertj.core.groups.Tuple; +import org.eclipse.microprofile.config.Config; +import org.eclipse.microprofile.config.spi.ConfigProviderResolver; import org.eclipse.microprofile.reactive.messaging.Channel; import org.eclipse.microprofile.reactive.messaging.Emitter; import org.eclipse.microprofile.reactive.messaging.Incoming; @@ -38,6 +41,8 @@ import io.quarkus.kafka.client.serialization.JsonbSerializer; import io.quarkus.kafka.client.serialization.ObjectMapperDeserializer; import io.quarkus.smallrye.reactivemessaging.deployment.items.ConnectorManagedChannelBuildItem; +import io.smallrye.config.SmallRyeConfigBuilder; +import io.smallrye.config.common.MapBackedConfigSource; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; import io.smallrye.reactive.messaging.MutinyEmitter; @@ -48,20 +53,36 @@ public class DefaultSerdeConfigTest { private static void doTest(Tuple[] expectations, Class<?>... classesToIndex) { + doTest(null, expectations, classesToIndex); + } + + private static void doTest(Config customConfig, Tuple[] expectations, Class<?>... classesToIndex) { List<RunTimeConfigurationDefaultBuildItem> configs = new ArrayList<>(); DefaultSerdeDiscoveryState discovery = new DefaultSerdeDiscoveryState(index(classesToIndex)) { + @Override + Config getConfig() { + return customConfig != null ? customConfig : super.getConfig(); + } + @Override boolean isKafkaConnector(List<ConnectorManagedChannelBuildItem> list, boolean incoming, String channelName) { return true; } }; - new SmallRyeReactiveMessagingKafkaProcessor().discoverDefaultSerdeConfig(discovery, Collections.emptyList(), - configs::add, null, null); - - assertThat(configs) - .extracting(RunTimeConfigurationDefaultBuildItem::getKey, RunTimeConfigurationDefaultBuildItem::getValue) - .containsExactlyInAnyOrder(expectations); + try { + new SmallRyeReactiveMessagingKafkaProcessor().discoverDefaultSerdeConfig(discovery, Collections.emptyList(), + configs::add, null, null); + + assertThat(configs) + .extracting(RunTimeConfigurationDefaultBuildItem::getKey, RunTimeConfigurationDefaultBuildItem::getValue) + .containsExactlyInAnyOrder(expectations); + } finally { + // must not leak the Config instance associated to the system classloader + if (customConfig == null) { + ConfigProviderResolver.instance().releaseConfig(discovery.getConfig()); + } + } } private static IndexView index(Class<?>... classes) { @@ -2467,4 +2488,69 @@ void channel10(List<Message<JacksonDto>> jacksonDto) { } + // --- + + @Test + public void connectorConfigNotOverriden() { + // @formatter:off + Tuple[] expectations1 = { + // "mp.messaging.outgoing.channel1.key.serializer" NOT expected, connector config exists + tuple("mp.messaging.outgoing.channel1.value.serializer", "org.apache.kafka.common.serialization.StringSerializer"), + + tuple("mp.messaging.incoming.channel2.key.deserializer", "org.apache.kafka.common.serialization.LongDeserializer"), + // "mp.messaging.incoming.channel2.value.deserializer" NOT expected, connector config exists + + tuple("mp.messaging.incoming.channel3.key.deserializer", "org.apache.kafka.common.serialization.LongDeserializer"), + // "mp.messaging.incoming.channel3.value.deserializer" NOT expected, connector config exists + // "mp.messaging.outgoing.channel4.key.serializer" NOT expected, connector config exists + tuple("mp.messaging.outgoing.channel4.value.serializer", "org.apache.kafka.common.serialization.StringSerializer"), + }; + + Tuple[] expectations2 = { + tuple("mp.messaging.outgoing.channel1.key.serializer", "org.apache.kafka.common.serialization.LongSerializer"), + // "mp.messaging.outgoing.channel1.value.serializer" NOT expected, connector config exists + + // "mp.messaging.incoming.channel2.key.deserializer" NOT expected, connector config exists + tuple("mp.messaging.incoming.channel2.value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"), + + // "mp.messaging.incoming.channel3.key.deserializer" NOT expected, connector config exists + tuple("mp.messaging.incoming.channel3.value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"), + tuple("mp.messaging.outgoing.channel4.key.serializer", "org.apache.kafka.common.serialization.LongSerializer"), + // "mp.messaging.outgoing.channel4.value.serializer" NOT expected, connector config exists + }; + // @formatter:on + + doTest(new SmallRyeConfigBuilder() + .withSources(new MapBackedConfigSource("test", Map.of( + "mp.messaging.connector.smallrye-kafka.key.serializer", "foo.Bar", + "mp.messaging.connector.smallrye-kafka.value.deserializer", "foo.Baz")) { + }) + .build(), expectations1, ConnectorConfigNotOverriden.class); + + doTest(new SmallRyeConfigBuilder() + .withSources(new MapBackedConfigSource("test", Map.of( + "mp.messaging.connector.smallrye-kafka.key.deserializer", "foo.Bar", + "mp.messaging.connector.smallrye-kafka.value.serializer", "foo.Baz")) { + }) + .build(), expectations2, ConnectorConfigNotOverriden.class); + } + + private static class ConnectorConfigNotOverriden { + @Outgoing("channel1") + Record<Long, String> method1() { + return null; + } + + @Incoming("channel2") + CompletionStage<?> method2(Record<Long, String> msg) { + return null; + } + + @Incoming("channel3") + @Outgoing("channel4") + Record<Long, String> method3(Record<Long, String> msg) { + return null; + } + } + }
['extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/SmallRyeReactiveMessagingKafkaProcessor.java', 'extensions/smallrye-reactive-messaging-kafka/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeDiscoveryState.java', 'extensions/smallrye-reactive-messaging-kafka/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/kafka/deployment/DefaultSerdeConfigTest.java']
{'.java': 3}
3
3
0
0
3
20,288,566
3,924,733
515,413
4,969
2,985
490
64
2
2,204
261
468
46
1
0
1970-01-01T00:27:28
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,454
quarkusio/quarkus/24698/24626
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24626
https://github.com/quarkusio/quarkus/pull/24698
https://github.com/quarkusio/quarkus/pull/24698
1
fixes
Resteasy reactive with Http 1.1 Pipelining raising exception since quarkus 2.4.0
### Describe the bug In a quarkus 2.7.5 app running with docker I've noticed the following errors: ``` 2022-03-29 09:05:30,993 ERROR [io.qua.ver.cor.run.VertxCoreRecorder] (vert.x-eventloop-thread-1) Uncaught exception received by Vert.x: java.lang.IllegalStateException: Can't set the context safety flag: the current context is not a duplicated context at io.quarkus.vertx.core.runtime.context.VertxContextSafetyToggle.setContextSafe(VertxContextSafetyToggle.java:107) at io.quarkus.vertx.core.runtime.context.VertxContextSafetyToggle.setCurrentContextSafe(VertxContextSafetyToggle.java:94) at io.quarkus.vertx.http.runtime.VertxHttpRecorder$12.handle(VertxHttpRecorder.java:504) at io.quarkus.vertx.http.runtime.VertxHttpRecorder$12.handle(VertxHttpRecorder.java:501) at io.quarkus.vertx.http.runtime.VertxHttpRecorder$1.handle(VertxHttpRecorder.java:161) at io.quarkus.vertx.http.runtime.VertxHttpRecorder$1.handle(VertxHttpRecorder.java:143) at io.vertx.core.http.impl.Http1xServerRequestHandler.handle(Http1xServerRequestHandler.java:67) at io.vertx.core.http.impl.Http1xServerRequestHandler.handle(Http1xServerRequestHandler.java:30) at io.vertx.core.http.impl.Http1xServerConnection.lambda$handleNext$1(Http1xServerConnection.java:225) at io.vertx.core.impl.EventLoopContext.emit(EventLoopContext.java:50) at io.vertx.core.impl.ContextImpl.emit(ContextImpl.java:274) at io.vertx.core.impl.EventLoopContext.emit(EventLoopContext.java:22) at io.vertx.core.http.impl.Http1xServerConnection.handleNext(Http1xServerConnection.java:222) at io.vertx.core.http.impl.Http1xServerConnection.responseComplete(Http1xServerConnection.java:207) at io.vertx.core.http.impl.Http1xServerResponse.end(Http1xServerResponse.java:418) at io.vertx.core.http.impl.Http1xServerResponse.end(Http1xServerResponse.java:391) at io.quarkus.vertx.http.runtime.filters.AbstractResponseWrapper.end(AbstractResponseWrapper.java:223) at org.jboss.resteasy.reactive.server.vertx.ResteasyReactiveOutputStream.write(ResteasyReactiveOutputStream.java:100) at org.jboss.resteasy.reactive.server.vertx.ResteasyReactiveOutputStream.writeBlocking(ResteasyReactiveOutputStream.java:224) at org.jboss.resteasy.reactive.server.vertx.ResteasyReactiveOutputStream.close(ResteasyReactiveOutputStream.java:270) at io.quarkus.resteasy.reactive.jackson.runtime.serialisers.BasicServerJacksonMessageBodyWriter.writeResponse(BasicServerJacksonMessageBodyWriter.java:44) at org.jboss.resteasy.reactive.server.core.ServerSerialisers.invokeWriter(ServerSerialisers.java:207) at org.jboss.resteasy.reactive.server.core.ServerSerialisers.invokeWriter(ServerSerialisers.java:178) at org.jboss.resteasy.reactive.server.core.serialization.FixedEntityWriter.write(FixedEntityWriter.java:26) at org.jboss.resteasy.reactive.server.handlers.ResponseWriterHandler.handle(ResponseWriterHandler.java:33) at org.jboss.resteasy.reactive.server.handlers.ResponseWriterHandler.handle(ResponseWriterHandler.java:15) at org.jboss.resteasy.reactive.common.core.AbstractResteasyReactiveContext.run(AbstractResteasyReactiveContext.java:141) at org.jboss.resteasy.reactive.server.vertx.VertxResteasyReactiveRequestContext$1$1.handle(VertxResteasyReactiveRequestContext.java:73) at org.jboss.resteasy.reactive.server.vertx.VertxResteasyReactiveRequestContext$1$1.handle(VertxResteasyReactiveRequestContext.java:70) at io.vertx.core.impl.AbstractContext.dispatch(AbstractContext.java:100) at io.vertx.core.impl.AbstractContext.dispatch(AbstractContext.java:63) at io.vertx.core.impl.EventLoopContext.lambda$runOnContext$0(EventLoopContext.java:38) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:469) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:500) at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986) at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.base/java.lang.Thread.run(Thread.java:829) ``` I think this is due to the client using pipelining, I can reproduce the error running in dev mode with the simplest endpoint possible ``` package org.acme; import io.smallrye.mutiny.Uni; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import org.jboss.logging.Logger; @Path("/") public class Endpoint { @Inject Logger logger; @GET public Uni<String> endpoint() { logger.info("Api called"); return Uni.createFrom().item("Hello"); } } ``` Sending 2 requests with ``` echo -en "GET / HTTP/1.1\\r\\nHost: localhost\\r\\n\\r\\nGET / HTTP/1.1\\r\\nHost: localhost\\r\\n\\r\\n" | nc localhost 8080 ``` On version 2.7.5.Final / 2.8.0.CR1 results in: ``` 2022-03-30 10:25:32,902 INFO [io.quarkus] (Quarkus Main Thread) code-with-quarkus 1.0.0-SNAPSHOT on JVM (powered by Quarkus 2.7.5.Final) started in 1.332s. Listening on: http://localhost:8080 2022-03-30 10:25:32,915 INFO [io.quarkus] (Quarkus Main Thread) Profile dev activated. Live Coding activated. 2022-03-30 10:25:32,916 INFO [io.quarkus] (Quarkus Main Thread) Installed features: [cdi, resteasy-reactive, smallrye-context-propagation, vertx] 2022-03-30 10:25:38,721 INFO [org.acm.Endpoint] (vert.x-eventloop-thread-23) Api called 2022-03-30 10:25:38,736 ERROR [io.qua.ver.cor.run.VertxCoreRecorder] (vert.x-eventloop-thread-23) Uncaught exception received by Vert.x: java.lang.IllegalStateException: Can't set the context safety flag: the current context is not a duplicated context at io.quarkus.vertx.core.runtime.context.VertxContextSafetyToggle.setContextSafe(VertxContextSafetyToggle.java:107) at io.quarkus.vertx.core.runtime.context.VertxContextSafetyToggle.setCurrentContextSafe(VertxContextSafetyToggle.java:94) at io.quarkus.vertx.http.runtime.VertxHttpRecorder$12.handle(VertxHttpRecorder.java:504) at io.quarkus.vertx.http.runtime.VertxHttpRecorder$12.handle(VertxHttpRecorder.java:501) at io.quarkus.vertx.http.runtime.VertxHttpRecorder$1.handle(VertxHttpRecorder.java:161) at io.quarkus.vertx.http.runtime.VertxHttpRecorder$1.handle(VertxHttpRecorder.java:143) at io.vertx.core.http.impl.Http1xServerRequestHandler.handle(Http1xServerRequestHandler.java:67) at io.vertx.core.http.impl.Http1xServerRequestHandler.handle(Http1xServerRequestHandler.java:30) at io.vertx.core.http.impl.Http1xServerConnection.lambda$handleNext$1(Http1xServerConnection.java:225) at io.vertx.core.impl.EventLoopContext.emit(EventLoopContext.java:50) at io.vertx.core.impl.ContextImpl.emit(ContextImpl.java:274) at io.vertx.core.impl.EventLoopContext.emit(EventLoopContext.java:22) at io.vertx.core.http.impl.Http1xServerConnection.handleNext(Http1xServerConnection.java:222) at io.vertx.core.http.impl.Http1xServerConnection.responseComplete(Http1xServerConnection.java:207) at io.vertx.core.http.impl.Http1xServerResponse.end(Http1xServerResponse.java:418) at io.vertx.core.http.impl.Http1xServerResponse.end(Http1xServerResponse.java:391) at io.vertx.core.http.impl.Http1xServerResponse.end(Http1xServerResponse.java:370) at org.jboss.resteasy.reactive.server.vertx.VertxResteasyReactiveRequestContext.end(VertxResteasyReactiveRequestContext.java:349) at org.jboss.resteasy.reactive.server.providers.serialisers.ServerStringMessageBodyHandler.writeResponse(ServerStringMessageBodyHandler.java:26) at org.jboss.resteasy.reactive.server.core.ServerSerialisers.invokeWriter(ServerSerialisers.java:207) at org.jboss.resteasy.reactive.server.core.ServerSerialisers.invokeWriter(ServerSerialisers.java:178) at org.jboss.resteasy.reactive.server.core.serialization.FixedEntityWriter.write(FixedEntityWriter.java:26) at org.jboss.resteasy.reactive.server.handlers.ResponseWriterHandler.handle(ResponseWriterHandler.java:32) at org.jboss.resteasy.reactive.server.handlers.ResponseWriterHandler.handle(ResponseWriterHandler.java:15) at org.jboss.resteasy.reactive.common.core.AbstractResteasyReactiveContext.run(AbstractResteasyReactiveContext.java:141) at org.jboss.resteasy.reactive.server.handlers.RestInitialHandler.beginProcessing(RestInitialHandler.java:49) at org.jboss.resteasy.reactive.server.vertx.ResteasyReactiveVertxHandler.handle(ResteasyReactiveVertxHandler.java:17) at org.jboss.resteasy.reactive.server.vertx.ResteasyReactiveVertxHandler.handle(ResteasyReactiveVertxHandler.java:7) at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1212) at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:163) at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:141) at io.quarkus.vertx.http.runtime.VertxHttpRecorder$5.handle(VertxHttpRecorder.java:380) at io.quarkus.vertx.http.runtime.VertxHttpRecorder$5.handle(VertxHttpRecorder.java:358) at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1212) at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:163) at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:141) at io.quarkus.vertx.http.runtime.devmode.VertxHttpHotReplacementSetup$5.handle(VertxHttpHotReplacementSetup.java:196) at io.quarkus.vertx.http.runtime.devmode.VertxHttpHotReplacementSetup$5.handle(VertxHttpHotReplacementSetup.java:185) at io.vertx.core.impl.future.FutureImpl$3.onSuccess(FutureImpl.java:141) at io.vertx.core.impl.future.FutureBase.lambda$emitSuccess$0(FutureBase.java:54) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:469) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:503) at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986) at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.base/java.lang.Thread.run(Thread.java:829) ``` On quarkus 2.3.1 or lower this doesn't happen, quarkus 2.4.0 is the first version where this happens as far as I can tell. ### Expected behavior HTTP 1.1 pipelined requests should not fail ### Actual behavior The second HTTP 1.1 pipelined request fails with an exception and the response for the second request is never sent ### How to Reproduce? 1. Create a GET point on / path 2. Start quarkus >= 2.4.0 in dev mode with `quarkus:dev` 3. Send 2 http pipelined requests with `echo -en "GET / HTTP/1.1\\r\\nHost: localhost\\r\\n\\r\\nGET / HTTP/1.1\\r\\nHost: localhost\\r\\n\\r\\n" | nc localhost 8080` ### Output of `uname -a` or `ver` Linux g8 5.13.0-37-generic #42-Ubuntu SMP Tue Mar 15 14:34:06 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux ### Output of `java -version` openjdk version "17.0.2" 2022-01-18 OpenJDK Runtime Environment (build 17.0.2+8-Ubuntu-122.10) OpenJDK 64-Bit Server VM (build 17.0.2+8-Ubuntu-122.10, mixed mode, sharing) ### GraalVM version (if different from Java) NA ### Quarkus version or git rev 2.4.0, 2.7.5, 2.8.0.CR1 ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) ### Additional information _No response_
e30c14f1b3444d8bd43de3151a25cfd1bd0a0215
fc801a2cf5098f09e21b106e99b3060bb201cbd6
https://github.com/quarkusio/quarkus/compare/e30c14f1b3444d8bd43de3151a25cfd1bd0a0215...fc801a2cf5098f09e21b106e99b3060bb201cbd6
diff --git a/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxHttpRecorder.java b/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxHttpRecorder.java index e9616ef08ad..cfb398cc681 100644 --- a/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxHttpRecorder.java +++ b/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxHttpRecorder.java @@ -501,8 +501,22 @@ public void handle(HttpServerRequest event) { root = new Handler<HttpServerRequest>() { @Override public void handle(HttpServerRequest event) { - setCurrentContextSafe(true); - delegate.handle(new ResumingRequestWrapper(event)); + if (!VertxContext.isOnDuplicatedContext()) { + // Vert.x should call us on a duplicated context. + // But in the case of pipelined requests, it does not. + // See https://github.com/quarkusio/quarkus/issues/24626. + Context context = VertxContext.createNewDuplicatedContext(); + context.runOnContext(new Handler<Void>() { + @Override + public void handle(Void x) { + setCurrentContextSafe(true); + delegate.handle(new ResumingRequestWrapper(event)); + } + }); + } else { + setCurrentContextSafe(true); + delegate.handle(new ResumingRequestWrapper(event)); + } } }; if (httpConfiguration.recordRequestStartTime) {
['extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/VertxHttpRecorder.java']
{'.java': 1}
1
1
0
0
1
20,297,591
3,926,391
515,614
4,972
996
151
18
1
11,765
560
2,996
170
1
4
1970-01-01T00:27:28
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,249
quarkusio/quarkus/31477/31449
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/31449
https://github.com/quarkusio/quarkus/pull/31477
https://github.com/quarkusio/quarkus/pull/31477
1
fixes
Qute: VarArgs processing error with 1 element
### Describe the bug @mkouba I'm submitting this based on your suggesting to file here in Quarkus to fix https://github.com/quarkiverse/quarkus-renarde/issues/102 I have a method on my User class which is a RenardeUser, etc. I have a method called `hasUserRole(String... roleNames)` that I'd like to pass in a list of roles to check from my Qute templates in a single method call instead of multiple calls. This works IF I pass in a list of roles like `{#if inject:user && inject:user.hasUserRole("webadmin", "admin", "support")}` but I get an exception during RUNTIME if I try to pass in a single value, ie. `{#if inject:user && inject:user.hasUserRole("admin")}` The project compiles and starts up just fine but dies when I access the page with the single permission check. ``` 2023-02-26 17:27:11,348 ERROR [org.jbo.res.rea.com.cor.AbstractResteasyReactiveContext] (executor-thread-1) Request failed: java.lang.ClassCastException: class java.lang.String cannot be cast to class [Ljava.lang.String; (java.lang.String and [Ljava.lang.String; are in module java.base of loader 'bootstrap') ``` ### Expected behavior VarAgs with a single parameter should also work ### Actual behavior Get the error: ``` 2023-02-26 17:27:11,348 ERROR [org.jbo.res.rea.com.cor.AbstractResteasyReactiveContext] (executor-thread-1) Request failed: java.lang.ClassCastException: class java.lang.String cannot be cast to class [Ljava.lang.String; (java.lang.String and [Ljava.lang.String; are in module java.base of loader 'bootstrap') ``` ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.16.1.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
cb1c4f0f6183bb2a09d0f86ad9b2256599b0421a
ed1f03a804de5979b8ae8df63971142d23422f7a
https://github.com/quarkusio/quarkus/compare/cb1c4f0f6183bb2a09d0f86ad9b2256599b0421a...ed1f03a804de5979b8ae8df63971142d23422f7a
diff --git a/extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/varargs/VarargsMethodTest.java b/extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/varargs/VarargsMethodTest.java index 0cf8f640c66..957bae5ac11 100644 --- a/extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/varargs/VarargsMethodTest.java +++ b/extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/varargs/VarargsMethodTest.java @@ -2,7 +2,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals; +import java.util.Arrays; + import jakarta.inject.Inject; +import jakarta.inject.Named; +import jakarta.inject.Singleton; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.junit.jupiter.api.Test; @@ -22,7 +26,13 @@ public class VarargsMethodTest { .addAsResource(new StringAsset("{foo.getStr}:{foo.getStr('foo','bar','baz')}"), "templates/foo.txt") .addAsResource(new StringAsset("{fmt.format('a','b','c')}"), - "templates/bar.txt")); + "templates/bar.txt") + .addAsResource(new StringAsset("{foo.getInt}:{foo.getInt(1)}:{foo.getInt(1,2,3)}"), + "templates/baz.txt") + .addAsResource( + new StringAsset( + "{cdi:qux.getBoolean(1)}:{cdi:qux.getBoolean(1, true, false)}:{cdi:qux.getBoolean(2, false)}"), + "templates/qux.txt"));; @Inject Template foo; @@ -30,15 +40,24 @@ public class VarargsMethodTest { @Inject Template bar; + @Inject + Template baz; + + @Inject + Template qux; + @Test public void testVarargs() { assertEquals("ok:foo:bar baz", foo.data("foo", new Foo()).render()); assertEquals(" b a", bar.data("fmt", "%2$2s%1$2s").render()); + assertEquals("[]:[1]:[1, 2, 3]", baz.data("foo", new Foo()).render()); + assertEquals("1 []:1 [true, false]:2 [false]", qux.render()); } @TemplateData(properties = false) public static class Foo { + // This one is ignored String getStr(String foo) { return foo; } @@ -52,6 +71,10 @@ public String getStr(String foo, String... args) { return foo + String.format(":%s %s", args[0], args[1]); } + public String getInt(int... args) { + return Arrays.toString(args); + } + @TemplateExtension static String format(String fmt, Object... args) { return String.format(fmt, args); @@ -59,4 +82,14 @@ static String format(String fmt, Object... args) { } + @Named + @Singleton + public static class Qux { + + public String getBoolean(int first, Boolean... args) { + return first + " " + Arrays.toString(args); + } + + } + } diff --git a/independent-projects/qute/generator/src/main/java/io/quarkus/qute/generator/ValueResolverGenerator.java b/independent-projects/qute/generator/src/main/java/io/quarkus/qute/generator/ValueResolverGenerator.java index fe00046e029..05e62a4f268 100644 --- a/independent-projects/qute/generator/src/main/java/io/quarkus/qute/generator/ValueResolverGenerator.java +++ b/independent-projects/qute/generator/src/main/java/io/quarkus/qute/generator/ValueResolverGenerator.java @@ -690,21 +690,41 @@ private void matchMethod(MethodInfo method, ClassInfo clazz, MethodCreator resol exception.invokeVirtualMethod(Descriptors.COMPLETABLE_FUTURE_COMPLETE_EXCEPTIONALLY, whenRet, exception.getCaughtException()); + ResultHandle[] realParamsHandle = paramsHandle; + if (isVarArgs(method)) { + // For varargs the number of results may be higher than the number of method params + // First get the regular params + realParamsHandle = new ResultHandle[parameterTypes.size()]; + for (int i = 0; i < parameterTypes.size() - 1; i++) { + ResultHandle resultHandle = tryCatch.invokeVirtualMethod(Descriptors.EVALUATED_PARAMS_GET_RESULT, + whenEvaluatedParams, tryCatch.load(i)); + realParamsHandle[i] = resultHandle; + } + // Then we need to create an array for the last argument + Type varargsParam = parameterTypes.get(parameterTypes.size() - 1); + ResultHandle componentType = tryCatch + .loadClass(varargsParam.asArrayType().component().name().toString()); + ResultHandle varargsResults = tryCatch.invokeVirtualMethod(Descriptors.EVALUATED_PARAMS_GET_VARARGS_RESULTS, + evaluatedParams, tryCatch.load(parameterTypes.size()), componentType); + // E.g. String, String, String -> String, String[] + realParamsHandle[parameterTypes.size() - 1] = varargsResults; + } + if (Modifier.isStatic(method.flags())) { if (Modifier.isInterface(clazz.flags())) { tryCatch.assign(invokeRet, - tryCatch.invokeStaticInterfaceMethod(MethodDescriptor.of(method), paramsHandle)); + tryCatch.invokeStaticInterfaceMethod(MethodDescriptor.of(method), realParamsHandle)); } else { tryCatch.assign(invokeRet, - tryCatch.invokeStaticMethod(MethodDescriptor.of(method), paramsHandle)); + tryCatch.invokeStaticMethod(MethodDescriptor.of(method), realParamsHandle)); } } else { if (Modifier.isInterface(clazz.flags())) { tryCatch.assign(invokeRet, - tryCatch.invokeInterfaceMethod(MethodDescriptor.of(method), whenBase, paramsHandle)); + tryCatch.invokeInterfaceMethod(MethodDescriptor.of(method), whenBase, realParamsHandle)); } else { tryCatch.assign(invokeRet, - tryCatch.invokeVirtualMethod(MethodDescriptor.of(method), whenBase, paramsHandle)); + tryCatch.invokeVirtualMethod(MethodDescriptor.of(method), whenBase, realParamsHandle)); } }
['extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/varargs/VarargsMethodTest.java', 'independent-projects/qute/generator/src/main/java/io/quarkus/qute/generator/ValueResolverGenerator.java']
{'.java': 2}
2
2
0
0
2
25,049,712
4,945,586
638,432
5,856
2,144
387
28
1
1,920
252
479
58
1
2
1970-01-01T00:27:57
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,247
quarkusio/quarkus/31581/31558
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/31558
https://github.com/quarkusio/quarkus/pull/31581
https://github.com/quarkusio/quarkus/pull/31581
1
fixes
JUnit @Nested Inner Classes with @BeforeAll and @Transactional annotations fail on initialization after upgrading to 2.16.3.Final
### Describe the bug After upgrading from version `2.15.3.Final` to `2.16.3.Final`, Tests on Inner Classes annotated with `@Nested` and methods annotated with `@BeforeAll` and `@Transactional` fail on initialization. ### Expected behavior Tests on Inner Classes annotated with JUnit @Nested annotation should keep working as in the previous version (`2.15.3.Final`). ### Actual behavior After upgrading from version 2.15.3.Final to 2.16.3.Final, Tests on Inner Classes annotated with `@Nested` and methods annotated with `@BeforeAll` and `@Transactional` fail on initialization. ```shell java.lang.RuntimeException: java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors [error]: Build step io.quarkus.arc.deployment.ArcProcessor#generateResources threw an exception: javax.enterprise.inject.spi.DeploymentException: Found 2 deployment problems: [1] The INNER class org.acme.FruitResourceTest$AnotherFruitInnerClass declares an interceptor binding but it must be ignored per CDI rules [2] The INNER class org.acme.FruitResourceTest$AFruitInnerClass declares an interceptor binding but it must be ignored per CDI rules at io.quarkus.arc.processor.BeanDeployment.processErrors(BeanDeployment.java:1231) at io.quarkus.arc.processor.BeanProcessor.processValidationErrors(BeanProcessor.java:161) at io.quarkus.arc.deployment.ArcProcessor.generateResources(ArcProcessor.java:559) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at io.quarkus.deployment.ExtensionLoader$3.execute(ExtensionLoader.java:909) at io.quarkus.builder.BuildContext.run(BuildContext.java:281) at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478) at java.base/java.lang.Thread.run(Thread.java:833) at org.jboss.threads.JBossThread.run(JBossThread.java:501) Suppressed: java.lang.IllegalStateException: The INNER class org.acme.FruitResourceTest$AnotherFruitInnerClass declares an interceptor binding but it must be ignored per CDI rules at io.quarkus.arc.deployment.WrongAnnotationUsageProcessor.detect(WrongAnnotationUsageProcessor.java:100) ... 11 more Suppressed: java.lang.IllegalStateException: The INNER class org.acme.FruitResourceTest$AFruitInnerClass declares an interceptor binding but it must be ignored per CDI rules at io.quarkus.arc.deployment.WrongAnnotationUsageProcessor.detect(WrongAnnotationUsageProcessor.java:100) ... 11 more ``` ## Test Class: ```java package org.acme; import io.quarkus.test.common.QuarkusTestResource; import io.quarkus.test.junit.QuarkusTest; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import javax.transaction.Transactional; import static io.restassured.RestAssured.given; import static org.hamcrest.CoreMatchers.containsString; import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS; @QuarkusTest @QuarkusTestResource(PostgresTestResource.class) @TestInstance(PER_CLASS) class FruitResourceTest { @BeforeAll void doSomeImportantStuffBeforeAllTests() { // } @Nested @DisplayName("This is a special Test in an Inner class") @TestInstance(PER_CLASS) class AFruitInnerClass { @BeforeAll // Commenting out @Transactional annotations makes tests to pass. @Transactional static void doSomeImportantStuffBeforeAllTests() { // } @Test void testGetFruitByIdEndpoint() { given() .when().get("/fruits/1") .then() .statusCode(200) .body(containsString("Banana")); } } @Nested @DisplayName("This is a special Test in an Inner class") @TestInstance(PER_CLASS) class AnotherFruitInnerClass { @BeforeAll // Commenting out @Transactional annotations makes tests to pass. @Transactional static void doSomeImportantStuffBeforeAllTests() { // } @Test void testGetFruitByIdEndpointAgain() { given() .when().get("/fruits/1") .then() .statusCode(200) .body(containsString("Banana")); } } } ``` ### How to Reproduce? Steps to reproduce the issue: Reproducer repository: https://github.com/fernandobalieiro/quarkus-nested-test-error 1. `git clone https://github.com/fernandobalieiro/quarkus-nested-test-error` 2. `cd quarkus-nested-test-error` 3. Run `./mvnw clean test ` 4. Tests will fail with the following result: ```shell [INFO] [INFO] Results: [INFO] [ERROR] Errors: [ERROR] FruitResourceTest » Runtime java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors [error]: Build step io.quarkus.arc.deployment.ArcProcessor#generateResources threw an exception: javax.enterprise.inject.spi.DeploymentException: Found 2 deployment problems: [1] The INNER class org.acme.FruitResourceTest$AnotherFruitInnerClass declares an interceptor binding but it must be ignored per CDI rules [2] The INNER class org.acme.FruitResourceTest$AFruitInnerClass declares an interceptor binding but it must be ignored per CDI rules at io.quarkus.arc.processor.BeanDeployment.processErrors(BeanDeployment.java:1231) at io.quarkus.arc.processor.BeanProcessor.processValidationErrors(BeanProcessor.java:161) at io.quarkus.arc.deployment.ArcProcessor.generateResources(ArcProcessor.java:559) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at io.quarkus.deployment.ExtensionLoader$3.execute(ExtensionLoader.java:909) at io.quarkus.builder.BuildContext.run(BuildContext.java:281) at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478) at java.base/java.lang.Thread.run(Thread.java:833) at org.jboss.threads.JBossThread.run(JBossThread.java:501) Suppressed: java.lang.IllegalStateException: The INNER class org.acme.FruitResourceTest$AnotherFruitInnerClass declares an interceptor binding but it must be ignored per CDI rules at io.quarkus.arc.deployment.WrongAnnotationUsageProcessor.detect(WrongAnnotationUsageProcessor.java:100) ... 11 more Suppressed: java.lang.IllegalStateException: The INNER class org.acme.FruitResourceTest$AFruitInnerClass declares an interceptor binding but it must be ignored per CDI rules at io.quarkus.arc.deployment.WrongAnnotationUsageProcessor.detect(WrongAnnotationUsageProcessor.java:100) ... 11 more [INFO] [ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0 [INFO] [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 15.029 s [INFO] Finished at: 2023-03-02T17:26:30Z [INFO] ------------------------------------------------------------------------ ``` ### Output of `uname -a` or `ver` Linux neo 5.19.0-35-generic #36~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Fri Feb 17 15:17:25 UTC 2 x86_64 x86_64 x86_64 GNU/Linux ### Output of `java -version` openjdk 17.0.1 2021-10-19 OpenJDK Runtime Environment GraalVM CE 21.3.0 (build 17.0.1+12-jvmci-21.3-b05) OpenJDK 64-Bit Server VM GraalVM CE 21.3.0 (build 17.0.1+12-jvmci-21.3-b05, mixed mode, sharing) ### GraalVM version (if different from Java) CE 21.3.0 (build 17.0.1+12-jvmci-21.3-b05, mixed mode, sharing) ### Quarkus version or git rev 2.16.3.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) Maven home: /home/neo/.m2/wrapper/dists/apache-maven-3.8.4-bin/52ccbt68d252mdldqsfsn03jlf/apache-maven-3.8.4 Java version: 17.0.2, vendor: GraalVM Community, runtime: /home/neo/.asdf/installs/java/graalvm-22.0.0.2+java17 Default locale: en_US, platform encoding: UTF-8 OS name: "linux", version: "5.19.0-35-generic", arch: "amd64", family: "unix" ### Additional information _No response_
c9d19099ea1dd87f9ee375aa6424a0d9f691ddb4
5d3a353c1b0cc92b15c41ae8d1f7f08ac9d7d4f3
https://github.com/quarkusio/quarkus/compare/c9d19099ea1dd87f9ee375aa6424a0d9f691ddb4...5d3a353c1b0cc92b15c41ae8d1f7f08ac9d7d4f3
diff --git a/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/WrongAnnotationUsageProcessor.java b/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/WrongAnnotationUsageProcessor.java index a68213e6271..5bbd2bdfcc3 100644 --- a/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/WrongAnnotationUsageProcessor.java +++ b/extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/WrongAnnotationUsageProcessor.java @@ -13,7 +13,9 @@ import org.jboss.jandex.ClassInfo; import org.jboss.jandex.ClassInfo.NestingType; import org.jboss.jandex.DotName; +import org.jboss.jandex.FieldInfo; import org.jboss.jandex.IndexView; +import org.jboss.jandex.MethodInfo; import io.quarkus.arc.deployment.ValidationPhaseBuildItem.ValidationErrorBuildItem; import io.quarkus.arc.processor.Annotations; @@ -72,35 +74,66 @@ void detect(ArcConfig config, ApplicationIndexBuildItem applicationIndex, Custom NestingType nestingType = clazz.nestingType(); if (NestingType.ANONYMOUS == nestingType || NestingType.LOCAL == nestingType || (NestingType.INNER == nestingType && !Modifier.isStatic(clazz.flags()))) { - // Annotations declared on the class, incl. the annotations added via transformers - Collection<AnnotationInstance> classAnnotations = transformedAnnotations.getAnnotations(clazz); - if (classAnnotations.isEmpty() && clazz.annotationsMap().isEmpty()) { - continue; - } - if (scopeAnnotations.isScopeIn(classAnnotations)) { + // Annotations declared on the class level, incl. the annotations added via transformers + Collection<AnnotationInstance> classLevelAnnotations = transformedAnnotations.getAnnotations(clazz); + if (scopeAnnotations.isScopeIn(classLevelAnnotations)) { validationErrors.produce(new ValidationErrorBuildItem( new IllegalStateException(String.format( "The %s class %s has a scope annotation but it must be ignored per the CDI rules", clazz.nestingType().toString(), clazz.name().toString())))); - } else if (clazz.annotationsMap().containsKey(DotNames.OBSERVES)) { - validationErrors.produce(new ValidationErrorBuildItem( - new IllegalStateException(String.format( - "The %s class %s declares an observer method but it must be ignored per the CDI rules", - clazz.nestingType().toString(), clazz.name().toString())))); - } else if (clazz.annotationsMap().containsKey(DotNames.PRODUCES)) { - validationErrors.produce(new ValidationErrorBuildItem( - new IllegalStateException(String.format( - "The %s class %s declares a producer but it must be ignored per the CDI rules", - clazz.nestingType().toString(), clazz.name().toString())))); - } else if (Annotations.containsAny(classAnnotations, interceptorResolverBuildItem.getInterceptorBindings()) - || Annotations.containsAny(clazz.annotations(), - interceptorResolverBuildItem.getInterceptorBindings())) { - // detect interceptor bindings on nested classes + } else if (Annotations.containsAny(classLevelAnnotations, + interceptorResolverBuildItem.getInterceptorBindings())) { + // detect interceptor bindings declared at nested class level validationErrors.produce(new ValidationErrorBuildItem( new IllegalStateException(String.format( "The %s class %s declares an interceptor binding but it must be ignored per CDI rules", clazz.nestingType().toString(), clazz.name().toString())))); } + + // iterate over methods and verify those + // note that since JDK 16, you can have static method inside inner non-static class + for (MethodInfo methodInfo : clazz.methods()) { + // annotations declared on method level, incl. the annotations added via transformers + Collection<AnnotationInstance> methodAnnotations = transformedAnnotations.getAnnotations(methodInfo); + if (methodAnnotations.isEmpty()) { + continue; + } + if (Annotations.contains(methodAnnotations, DotNames.OBSERVES) + || Annotations.contains(methodAnnotations, DotNames.OBSERVES_ASYNC)) { + validationErrors.produce(new ValidationErrorBuildItem( + new IllegalStateException(String.format( + "The method %s in the %s class %s declares an observer method but it must be ignored per the CDI rules", + methodInfo.name(), clazz.nestingType().toString(), clazz.name().toString())))); + } else if (Annotations.contains(methodAnnotations, DotNames.PRODUCES)) { + validationErrors.produce(new ValidationErrorBuildItem( + new IllegalStateException(String.format( + "The method %s in the %s class %s declares a producer but it must be ignored per the CDI rules", + methodInfo.name(), clazz.nestingType().toString(), clazz.name().toString())))); + } else if (!Modifier.isStatic(methodInfo.flags()) && Annotations.containsAny(methodAnnotations, + interceptorResolverBuildItem.getInterceptorBindings())) { + // detect interceptor bindings declared at nested class methods + validationErrors.produce(new ValidationErrorBuildItem( + new IllegalStateException(String.format( + "The method %s in the %s class %s declares an interceptor binding but it must be ignored per CDI rules", + methodInfo.name(), clazz.nestingType().toString(), clazz.name().toString())))); + } + + } + + // iterate over all fields, check for incorrect producer declarations + for (FieldInfo fieldInfo : clazz.fields()) { + // annotations declared on field level, incl. the annotations added via transformers + Collection<AnnotationInstance> fieldAnnotations = transformedAnnotations.getAnnotations(fieldInfo); + if (fieldAnnotations.isEmpty()) { + continue; + } + if (Annotations.contains(fieldAnnotations, DotNames.PRODUCES)) { + validationErrors.produce(new ValidationErrorBuildItem( + new IllegalStateException(String.format( + "The field %s in the %s class %s declares a producer but it must be ignored per the CDI rules", + fieldInfo.name(), clazz.nestingType().toString(), clazz.name().toString())))); + } + } } } }
['extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/WrongAnnotationUsageProcessor.java']
{'.java': 1}
1
1
0
0
1
25,382,259
5,011,241
646,564
5,956
5,759
862
73
1
9,342
661
2,271
193
2
3
1970-01-01T00:27:57
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,401
quarkusio/quarkus/26499/25850
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/25850
https://github.com/quarkusio/quarkus/pull/26499
https://github.com/quarkusio/quarkus/pull/26499
1
fixes
Quarkus Liquibase MongoDB extension properties not used
### Describe the bug Quarkus Liquibase extension doesn't respect quarkus mongodb properties as it is expected. Liquibase extension only uses 3 properties: - `connection string`, - `username` - `password`. This can be checked in `io.quarkus.liquibase.mongodb.LiquibaseMongodbFactory` in `createLiquibase` method. This will lead to an error on application startup if you are using quarkus properties for MongoDB configuration, for an example `quarkus.mongodb.credentials.auth-source` or `quarkus.mongodb.database` instead of adding all this params to connection string. ### Expected behavior Quarkus mongodb properties are repsected by `quarkus-liquibase-mongodb` extension ### Actual behavior Application throws error on starup. This error will showup if authSource and db not present in connString. ``` com.mongodb.MongoCommandException: Command failed with error 18 (AuthenticationFailed) ``` This error will showup if authSource present in connString but no db specified. ``` java.lang.IllegalArgumentException: Database not specified in URL at liquibase.ext.mongodb.database.MongoConnection.open(MongoConnection.java:110) at liquibase.database.ConnectionServiceFactory.create(ConnectionServiceFactory.java:32) at liquibase.database.DatabaseFactory.openConnection(DatabaseFactory.java:214) at liquibase.database.DatabaseFactory.openConnection(DatabaseFactory.java:176) at liquibase.database.DatabaseFactory.openDatabase(DatabaseFactory.java:141) at liquibase.database.DatabaseFactory.openDatabase(DatabaseFactory.java:130) at io.quarkus.liquibase.mongodb.LiquibaseMongodbFactory.createLiquibase(LiquibaseMongodbFactory.java:42) at io.quarkus.liquibase.mongodb.LiquibaseMongodbFactory_959fd9b7b35a536942315a4e37b512f2717c8f52_Synthetic_ClientProxy.createLiquibase(Unknown Source) at io.quarkus.liquibase.mongodb.runtime.LiquibaseMongodbRecorder.doStartActions(LiquibaseMongodbRecorder.java:47) at io.quarkus.deployment.steps.LiquibaseMongodbProcessor$startLiquibase1869009359.deploy_0(Unknown Source) at io.quarkus.deployment.steps.LiquibaseMongodbProcessor$startLiquibase1869009359.deploy(Unknown Source) at io.quarkus.runner.ApplicationImpl.doStart(Unknown Source) at io.quarkus.runtime.Application.start(Application.java:101) at io.quarkus.runtime.ApplicationLifecycleManager.run(ApplicationLifecycleManager.java:103) at io.quarkus.runtime.Quarkus.run(Quarkus.java:67) at io.quarkus.runtime.Quarkus.run(Quarkus.java:41) at io.quarkus.runtime.Quarkus.run(Quarkus.java:120) at io.quarkus.runner.GeneratedMain.main(Unknown Source) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at io.quarkus.runner.bootstrap.StartupActionImpl$1.run(StartupActionImpl.java:103) at java.base/java.lang.Thread.run(Thread.java:829) ``` ### How to Reproduce? Use quarkus mongodb settings and setup `quarkus-liquibase-mongodb` extension ```yaml quarkus: mongodb: tls: false connection-string: ${MONGODB_CON_STRING:mongodb://localhost:27017} database: customDB credentials: auth-source: ${MONGODB_AUTH_SOURCE} username: ${MONGODB_USERNAME} password: ${MONGODB_PASSWORD} liquibase-mongodb: migrate-at-start: true change-log: db/changelog.json ``` ### Output of `uname -a` or `ver` Darwin Kernel Version 21.1.0 ### Output of `java -version` openjdk version "11.0.12" 2021-07-20 OpenJDK Runtime Environment Homebrew (build 11.0.12+0) OpenJDK 64-Bit Server VM Homebrew (build 11.0.12+0, mixed mode) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.9.2.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Gradle 7.4.2 ### Additional information _No response_
4805844c7ad36bec066e752ce388b2a34ebe906b
983f0478282842a49ce3928065a39de6e37b86ff
https://github.com/quarkusio/quarkus/compare/4805844c7ad36bec066e752ce388b2a34ebe906b...983f0478282842a49ce3928065a39de6e37b86ff
diff --git a/extensions/liquibase-mongodb/runtime/src/main/java/io/quarkus/liquibase/mongodb/LiquibaseMongodbFactory.java b/extensions/liquibase-mongodb/runtime/src/main/java/io/quarkus/liquibase/mongodb/LiquibaseMongodbFactory.java index 63a314da7f8..caa81f0ff47 100644 --- a/extensions/liquibase-mongodb/runtime/src/main/java/io/quarkus/liquibase/mongodb/LiquibaseMongodbFactory.java +++ b/extensions/liquibase-mongodb/runtime/src/main/java/io/quarkus/liquibase/mongodb/LiquibaseMongodbFactory.java @@ -39,12 +39,15 @@ public Liquibase createLiquibase() { "Config property 'quarkus.mongodb.database' must be defined when no database " + "exist in the connection string")); } + if (mongoClientConfig.credentials.authSource.isPresent()) { + connectionString += "?authSource=" + mongoClientConfig.credentials.authSource.get(); + } + Database database = DatabaseFactory.getInstance().openDatabase(connectionString, this.mongoClientConfig.credentials.username.orElse(null), this.mongoClientConfig.credentials.password.orElse(null), null, resourceAccessor); - ; if (database != null) { liquibaseMongodbConfig.liquibaseCatalogName.ifPresent(database::setLiquibaseCatalogName); liquibaseMongodbConfig.liquibaseSchemaName.ifPresent(database::setLiquibaseSchemaName);
['extensions/liquibase-mongodb/runtime/src/main/java/io/quarkus/liquibase/mongodb/LiquibaseMongodbFactory.java']
{'.java': 1}
1
1
0
0
1
22,068,900
4,320,662
562,903
5,245
206
32
5
1
4,058
289
982
95
0
3
1970-01-01T00:27:36
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,246
quarkusio/quarkus/31630/31267
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/31267
https://github.com/quarkusio/quarkus/pull/31630
https://github.com/quarkusio/quarkus/pull/31630
1
fixes
Issue with id population when using MongoDb with Panache in native
### Describe the bug When persisting an entity in mongodb, it should populate the id. It is working launching quarkus in dev mode, but when I build it natively id keeps being null. ### Expected behavior When persisting, it should populate the value of the generated _id in mongodb. ### Actual behavior Value is null after persisting ### How to Reproduce? Get repo: https://github.com/ZimiZones/mongodb-id-generation Launch MongoDb: `docker run --rm -d --name mongo -p 27017:27017 mongo:6.0.4` Launch in dev: `quarkus dev` Send request: `curl --location 'http://localhost:8080/fasta_dbs'` It should return: {"id":"something here","name":"random name"} It is working! Build natively: ./gradlew build -Dquarkus.package.type=native -Dquarkus.native.container-build=true Launch and run the same request. Record had been created in mongodb but you will have an error because id is null. ### Output of `uname -a` or `ver` Linux WSL ### Output of `java -version` 17.0.4 ### GraalVM version (if different from Java) 22.3.1.r17-grl ### Quarkus version or git rev 2.16.2.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Gradle 8.0 ### Additional information _No response_
fdd65c47aecf93f9a324348206287e63bc24caa8
be154567f906fe876cc52dff136e1f35ace044a9
https://github.com/quarkusio/quarkus/compare/fdd65c47aecf93f9a324348206287e63bc24caa8...be154567f906fe876cc52dff136e1f35ace044a9
diff --git a/extensions/mongodb-client/deployment/src/main/java/io/quarkus/mongodb/deployment/MongoClientProcessor.java b/extensions/mongodb-client/deployment/src/main/java/io/quarkus/mongodb/deployment/MongoClientProcessor.java index add4b85f039..4d8fc91bfa4 100644 --- a/extensions/mongodb-client/deployment/src/main/java/io/quarkus/mongodb/deployment/MongoClientProcessor.java +++ b/extensions/mongodb-client/deployment/src/main/java/io/quarkus/mongodb/deployment/MongoClientProcessor.java @@ -161,11 +161,13 @@ List<ReflectiveClassBuildItem> addExtensionPointsToNative(CodecProviderBuildItem reflectiveClassNames.addAll(commandListeners.getCommandListenerClassNames()); List<ReflectiveClassBuildItem> reflectiveClass = reflectiveClassNames.stream() - .map(s -> new ReflectiveClassBuildItem(true, true, false, s)) + .map(s -> ReflectiveClassBuildItem.builder(s).methods(true).build()) .collect(Collectors.toCollection(ArrayList::new)); // ChangeStreamDocument needs to be registered for reflection with its fields. - reflectiveClass.add(new ReflectiveClassBuildItem(true, true, true, ChangeStreamDocument.class.getName())); - reflectiveClass.add(new ReflectiveClassBuildItem(true, true, false, UpdateDescription.class.getName())); + reflectiveClass.add(ReflectiveClassBuildItem.builder(ChangeStreamDocument.class).methods(true).fields(true).build()); + reflectiveClass.add(ReflectiveClassBuildItem.builder(UpdateDescription.class).methods(true).build()); + // ObjectId is often used on identifier, so we also register it + reflectiveClass.add(ReflectiveClassBuildItem.builder(ObjectId.class).methods(true).fields(true).build()); return reflectiveClass; } diff --git a/extensions/panache/mongodb-panache-common/deployment/src/main/java/io/quarkus/mongodb/panache/deployment/BasePanacheMongoResourceProcessor.java b/extensions/panache/mongodb-panache-common/deployment/src/main/java/io/quarkus/mongodb/panache/deployment/BasePanacheMongoResourceProcessor.java index b36e8f46a0e..09ef71fb729 100644 --- a/extensions/panache/mongodb-panache-common/deployment/src/main/java/io/quarkus/mongodb/panache/deployment/BasePanacheMongoResourceProcessor.java +++ b/extensions/panache/mongodb-panache-common/deployment/src/main/java/io/quarkus/mongodb/panache/deployment/BasePanacheMongoResourceProcessor.java @@ -279,7 +279,7 @@ protected void processEntities(CombinedIndexBuildItem index, transformers.produce(new BytecodeTransformerBuildItem(modelClass, entityEnhancer)); //register for reflection entity classes - reflectiveClass.produce(new ReflectiveClassBuildItem(true, true, modelClass)); + reflectiveClass.produce(ReflectiveClassBuildItem.builder(modelClass).fields(true).methods(true).build()); // Register for building the property mapping cache propertyMappingClass.produce(new PropertyMappingClassBuildStep(modelClass));
['extensions/panache/mongodb-panache-common/deployment/src/main/java/io/quarkus/mongodb/panache/deployment/BasePanacheMongoResourceProcessor.java', 'extensions/mongodb-client/deployment/src/main/java/io/quarkus/mongodb/deployment/MongoClientProcessor.java']
{'.java': 2}
2
2
0
0
2
25,397,938
5,014,208
646,820
5,957
1,030
205
10
2
1,274
170
338
61
2
0
1970-01-01T00:27:58
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,217
quarkusio/quarkus/32525/32288
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/32288
https://github.com/quarkusio/quarkus/pull/32525
https://github.com/quarkusio/quarkus/pull/32525
1
fixes
Quarkus 3.0.0.CR1/CR2 project - quarkus-maven-plugin:update fails, unable to resolve quarkus-update-recipes
### Describe the bug Quarkus 3.0.0.CR1 project - quarkus-maven-plugin:update fails with `Failed to resolve version for io.quarkus:quarkus-update-recipes:jar:LATEST` error. ``` mvn quarkus:update [INFO] Scanning for projects... [INFO] [INFO] ---------------------< org.acme:code-with-quarkus >--------------------- [INFO] Building code-with-quarkus 1.0.0-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- quarkus-maven-plugin:3.0.0.CR1:update (default-cli) @ code-with-quarkus --- [WARNING] quarkus:update goal is experimental, its options and output might change in future versions [INFO] Instructions to update this project from '3.0.0.CR1' to '2.16.5.Final': [INFO] [INFO] Recommended Quarkus platform BOM updates: [INFO] Update: io.quarkus.platform:quarkus-bom:pom:3.0.0.CR1 -> 2.16.5.Final [INFO] [INFO] ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO] ------------------------------------------------------------------------ [INFO] Total time: 2.536 s [INFO] Finished at: 2023-03-31T08:59:13+02:00 [INFO] ------------------------------------------------------------------------ [ERROR] Failed to execute goal io.quarkus.platform:quarkus-maven-plugin:3.0.0.CR1:update (default-cli) on project code-with-quarkus: Execution default-cli of goal io.quarkus.platform:quarkus-maven-plugin:3.0.0.CR1:update failed: Failed to resolve artifact: io.quarkus:quarkus-update-recipes:LATEST: Failed to resolve artifact io.quarkus:quarkus-update-recipes:jar:LATEST: Failed to resolve version for io.quarkus:quarkus-update-recipes:jar:LATEST: Could not find metadata io.quarkus:quarkus-update-recipes/maven-metadata.xml in local (/Users/rsvoboda/.m2/repository) -> [Help 1] [ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/PluginExecutionException ``` ### Expected behavior Command finishes successfully ### Actual behavior Command fails ### How to Reproduce? Download app from https://code.quarkus.io/?S=io.quarkus.platform%3A3.0 run `mvn quarkus:update` ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` Java 17 ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 3.0.0.CR1 ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
0c7eece4e39b9d17fda7da05470532fc423d619c
ae5e4fb4355f1185097f887787f2de13cb2fd463
https://github.com/quarkusio/quarkus/compare/0c7eece4e39b9d17fda7da05470532fc423d619c...ae5e4fb4355f1185097f887787f2de13cb2fd463
diff --git a/devtools/cli/src/main/java/io/quarkus/cli/Update.java b/devtools/cli/src/main/java/io/quarkus/cli/Update.java index c017b3ba91b..7cd4237227f 100644 --- a/devtools/cli/src/main/java/io/quarkus/cli/Update.java +++ b/devtools/cli/src/main/java/io/quarkus/cli/Update.java @@ -15,7 +15,7 @@ public class Update extends BaseBuildCommand implements Callable<Integer> { @CommandLine.ArgGroup(order = 0, heading = "%nTarget Quarkus version:%n", multiplicity = "0..1") TargetQuarkusVersionGroup targetQuarkusVersion = new TargetQuarkusVersionGroup(); - @CommandLine.ArgGroup(order = 1, heading = "%nRewrite:%n") + @CommandLine.ArgGroup(order = 1, heading = "%nRewrite:%n", exclusive = false) RewriteGroup rewrite = new RewriteGroup(); @CommandLine.Option(order = 2, names = { "--per-module" }, description = "Display information per project module.") diff --git a/devtools/cli/src/main/java/io/quarkus/cli/build/GradleRunner.java b/devtools/cli/src/main/java/io/quarkus/cli/build/GradleRunner.java index f0737db487a..9611986e102 100644 --- a/devtools/cli/src/main/java/io/quarkus/cli/build/GradleRunner.java +++ b/devtools/cli/src/main/java/io/quarkus/cli/build/GradleRunner.java @@ -163,7 +163,7 @@ public Integer updateProject(TargetQuarkusVersionGroup targetQuarkusVersion, Rew args.add(targetQuarkusVersion.platformVersion); } if (!StringUtil.isNullOrEmpty(targetQuarkusVersion.streamId)) { - args.add("--streamId"); + args.add("--stream"); args.add(targetQuarkusVersion.streamId); } if (rewrite.pluginVersion != null) { diff --git a/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusUpdate.java b/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusUpdate.java index 724ef304309..d5ef9326ac4 100644 --- a/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusUpdate.java +++ b/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusUpdate.java @@ -29,7 +29,7 @@ public abstract class QuarkusUpdate extends QuarkusPlatformTask { private String rewritePluginVersion = QuarkusUpdateCommand.DEFAULT_GRADLE_REWRITE_PLUGIN_VERSION; - private String rewriteUpdateRecipesVersion; + private String rewriteUpdateRecipesVersion = null; @Input @Optional @@ -93,7 +93,7 @@ public String getTargetStreamId() { return targetStreamId; } - @Option(description = "A target stream id, for example: 2.0", option = "streamId") + @Option(description = "A target stream, for example: 2.0", option = "stream") public void setStreamId(String targetStreamId) { this.targetStreamId = targetStreamId; } @@ -141,7 +141,12 @@ public void logUpdates() { final UpdateProject invoker = new UpdateProject(quarkusProject); invoker.latestCatalog(targetCatalog); - invoker.rewritePluginVersion(rewritePluginVersion); + if (rewriteUpdateRecipesVersion != null) { + invoker.rewriteUpdateRecipesVersion(rewriteUpdateRecipesVersion); + } + if (rewritePluginVersion != null) { + invoker.rewritePluginVersion(rewritePluginVersion); + } invoker.targetPlatformVersion(targetPlatformVersion); invoker.rewriteDryRun(rewriteDryRun); invoker.noRewrite(noRewrite); diff --git a/devtools/maven/src/main/java/io/quarkus/maven/UpdateMojo.java b/devtools/maven/src/main/java/io/quarkus/maven/UpdateMojo.java index 902e0027559..98ddc7105a3 100644 --- a/devtools/maven/src/main/java/io/quarkus/maven/UpdateMojo.java +++ b/devtools/maven/src/main/java/io/quarkus/maven/UpdateMojo.java @@ -15,6 +15,7 @@ import io.quarkus.devtools.commands.data.QuarkusCommandException; import io.quarkus.devtools.commands.data.QuarkusCommandOutcome; import io.quarkus.devtools.project.QuarkusProject; +import io.quarkus.devtools.project.QuarkusProjectHelper; import io.quarkus.devtools.project.update.QuarkusUpdateCommand; import io.quarkus.maven.dependency.ArtifactCoords; import io.quarkus.registry.RegistryResolutionException; @@ -91,7 +92,7 @@ protected void validateParameters() throws MojoExecutionException { @Override protected void processProjectState(QuarkusProject quarkusProject) throws MojoExecutionException { - + QuarkusProjectHelper.setArtifactResolver(artifactResolver()); final ExtensionCatalog targetCatalog; try { if (platformVersion != null) { @@ -120,7 +121,7 @@ protected void processProjectState(QuarkusProject quarkusProject) throws MojoExe invoker.rewritePluginVersion(rewritePluginVersion); } if (rewriteUpdateRecipesVersion != null) { - invoker.rewritePluginVersion(rewriteUpdateRecipesVersion); + invoker.rewriteUpdateRecipesVersion(rewriteUpdateRecipesVersion); } invoker.rewriteDryRun(rewriteDryRun); invoker.noRewrite(noRewrite); diff --git a/independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/commands/handlers/UpdateProjectCommandHandler.java b/independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/commands/handlers/UpdateProjectCommandHandler.java index 95a3ee6914e..e66706a7ea6 100644 --- a/independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/commands/handlers/UpdateProjectCommandHandler.java +++ b/independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/commands/handlers/UpdateProjectCommandHandler.java @@ -83,6 +83,8 @@ public QuarkusCommandOutcome execute(QuarkusCommandInvocation invocation) throws QuarkusProjectHelper.artifactResolver(), updateRecipesVersion, request); final String rewritePluginVersion = invocation.getValue(UpdateProject.REWRITE_PLUGIN_VERSION); final boolean rewriteDryRun = invocation.getValue(UpdateProject.REWRITE_DRY_RUN, false); + invocation.log().warn( + "The update feature does not yet handle updates of the extension versions. If needed, update your extensions manually."); QuarkusUpdateCommand.handle( invocation.log(), quarkusProject.getExtensionManager().getBuildTool(),
['devtools/cli/src/main/java/io/quarkus/cli/Update.java', 'independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/commands/handlers/UpdateProjectCommandHandler.java', 'devtools/maven/src/main/java/io/quarkus/maven/UpdateMojo.java', 'devtools/cli/src/main/java/io/quarkus/cli/build/GradleRunner.java', 'devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusUpdate.java']
{'.java': 5}
5
5
0
0
5
26,242,211
5,176,582
667,954
6,183
1,293
269
22
5
2,714
266
718
71
2
1
1970-01-01T00:28:01
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,218
quarkusio/quarkus/32520/32519
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/32519
https://github.com/quarkusio/quarkus/pull/32520
https://github.com/quarkusio/quarkus/pull/32520
1
fix
Generating Role or ClusterRole resources with empty API group property produces invalid manifests
### Describe the bug When generating a Role or a ClusterRole resource like: ``` quarkus.kubernetes.rbac.cluster-roles.secret-reader.policy-rules.0.resources=secrets quarkus.kubernetes.rbac.cluster-roles.secret-reader.policy-rules.0.verbs=get,watch,list ``` Produces the following resource: ```yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: secret-reader rules: - resources: - secrets verbs: - get - watch - list ``` This is invalid because the `apiGroups` field in the rule is mandatory and it's not added by default (because it's null). ### Expected behavior When users do not set the `api-groups`, it should use a list with an empty element, to produce: ```yaml apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: secret-reader rules: - resources: - secrets apiGroups: [""] verbs: - get - watch - list ``` More context in this comment: https://github.com/quarkusio/quarkus/pull/31797#issuecomment-1497311563 ### Actual behavior _No response_ ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
cbdf77bf8b4046d1f885442bd8742493560000a7
34dd1cbc3fcb1759ba82823f66751896a336277f
https://github.com/quarkusio/quarkus/compare/cbdf77bf8b4046d1f885442bd8742493560000a7...34dd1cbc3fcb1759ba82823f66751896a336277f
diff --git a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesCommonHelper.java b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesCommonHelper.java index 1eac16be796..ec91ba8b7f9 100644 --- a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesCommonHelper.java +++ b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesCommonHelper.java @@ -104,6 +104,7 @@ public class KubernetesCommonHelper { private static final String[] PROMETHEUS_ANNOTATION_TARGETS = { "Service", "Deployment", "DeploymentConfig" }; private static final String DEFAULT_ROLE_NAME_VIEW = "view"; + private static final List<String> LIST_WITH_EMPTY = List.of(""); public static Optional<Project> createProject(ApplicationInfoBuildItem app, Optional<CustomProjectRootBuildItem> customProjectRoot, OutputTargetBuildItem outputTarget, @@ -1011,7 +1012,7 @@ private static List<PolicyRule> toPolicyRulesList(Map<String, PolicyRuleConfig> return policyRules.values() .stream() .map(it -> new PolicyRuleBuilder() - .withApiGroups(it.apiGroups.orElse(null)) + .withApiGroups(it.apiGroups.orElse(LIST_WITH_EMPTY)) .withNonResourceURLs(it.nonResourceUrls.orElse(null)) .withResourceNames(it.resourceNames.orElse(null)) .withResources(it.resources.orElse(null)) diff --git a/integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/KubernetesWithRbacFullTest.java b/integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/KubernetesWithRbacFullTest.java index 3ff3de62fb5..e93f96d6054 100644 --- a/integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/KubernetesWithRbacFullTest.java +++ b/integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/KubernetesWithRbacFullTest.java @@ -61,6 +61,7 @@ public void assertGeneratedResources() throws IOException { Role podWriterRole = getRoleByName(kubernetesList, "pod-writer"); assertEquals(APP_NAMESPACE, podWriterRole.getMetadata().getNamespace()); assertThat(podWriterRole.getRules()).satisfiesOnlyOnce(r -> { + assertThat(r.getApiGroups()).containsExactly(""); assertThat(r.getResources()).containsExactly("pods"); assertThat(r.getVerbs()).containsExactly("update"); }); @@ -69,6 +70,7 @@ public void assertGeneratedResources() throws IOException { Role podReaderRole = getRoleByName(kubernetesList, "pod-reader"); assertEquals("projectb", podReaderRole.getMetadata().getNamespace()); assertThat(podReaderRole.getRules()).satisfiesOnlyOnce(r -> { + assertThat(r.getApiGroups()).containsExactly(""); assertThat(r.getResources()).containsExactly("pods"); assertThat(r.getVerbs()).containsExactly("get", "watch", "list"); }); @@ -76,6 +78,7 @@ public void assertGeneratedResources() throws IOException { // secret-reader assertions ClusterRole secretReaderRole = getClusterRoleByName(kubernetesList, "secret-reader"); assertThat(secretReaderRole.getRules()).satisfiesOnlyOnce(r -> { + assertThat(r.getApiGroups()).containsExactly(""); assertThat(r.getResources()).containsExactly("secrets"); assertThat(r.getVerbs()).containsExactly("get", "watch", "list"); });
['extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesCommonHelper.java', 'integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/KubernetesWithRbacFullTest.java']
{'.java': 2}
2
2
0
0
2
26,238,676
5,175,993
667,875
6,181
214
41
3
1
1,491
175
378
79
1
3
1970-01-01T00:28:01
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,219
quarkusio/quarkus/32501/32500
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/32500
https://github.com/quarkusio/quarkus/pull/32501
https://github.com/quarkusio/quarkus/pull/32501
1
fixes
`YamlMetadataGenerator` emits yaml with line splits
### Describe the bug The doc metadata yaml, which is generated by `YamlMetadataGenerator` contains blocks like this: ``` - title: Infinispan Client Extension Reference Guide filename: infinispan-client-reference.adoc summary: "Infinispan is an in memory distributed data store and cache server that\\ \\ offers flexible deployment options and robust capabilities for storing, managing,\\ \\ and processing data." ``` https://github.com/quarkusio/quarkusio.github.io/blob/develop/_data/versioned/main/index/quarkus.yaml#L44-L48 I'm working on Japanese localization project https://github.com/quarkusio/ja.quarkus.io, and the localization tool `po4a` cannot parse the YAML that contains line splits. (Please note it is not line breaks, it's line splits for formatting) This issue prevents translating [the Guides index page](https://ja.quarkus.io/guides/). The yaml is identical to this, and this representation can be parsed by po4a. ``` - title: Infinispan Client Extension Reference Guide filename: infinispan-client-reference.adoc summary: "Infinispan is an in memory distributed data store and cache server that offers flexible deployment options and robust capabilities for storing, managing, and processing data." ``` It would nice if the `YamlMetadataGenerator` emits the yaml without line splits by disabling the Jackson Yaml's `YAMLGenerator.Feature.SPLIT_LINES`. For more information, please refer the discussion in the Zulip chat: https://quarkusio.zulipchat.com/#narrow/stream/187030-users/topic/quarkus.2Eyaml.20on.20docs.20repo.20is.20bad.20indenting/near/326354873 ### Expected behavior `YamlMetadataGenerator` generates yaml without line splits. ``` - title: Infinispan Client Extension Reference Guide filename: infinispan-client-reference.adoc summary: "Infinispan is an in memory distributed data store and cache server that offers flexible deployment options and robust capabilities for storing, managing, and processing data." ``` ### Actual behavior `YamlMetadataGenerator` generates yaml with line splits. ``` - title: Infinispan Client Extension Reference Guide filename: infinispan-client-reference.adoc summary: "Infinispan is an in memory distributed data store and cache server that\\ \\ offers flexible deployment options and robust capabilities for storing, managing,\\ \\ and processing data." ``` https ### How to Reproduce? Reproducer: 1. run `./mvnw -f docs clean install` 2. Please check the generated yaml `docs/target/indexByType.yaml` ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 0100232204b86ac87d9a373f6c2030a77bea1684 ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
0100232204b86ac87d9a373f6c2030a77bea1684
00be8a9d063605435e2c2263e761070177e8a852
https://github.com/quarkusio/quarkus/compare/0100232204b86ac87d9a373f6c2030a77bea1684...00be8a9d063605435e2c2263e761070177e8a852
diff --git a/docs/src/main/java/io/quarkus/docs/generation/YamlMetadataGenerator.java b/docs/src/main/java/io/quarkus/docs/generation/YamlMetadataGenerator.java index 79a46bdf22d..f7b6a52138f 100644 --- a/docs/src/main/java/io/quarkus/docs/generation/YamlMetadataGenerator.java +++ b/docs/src/main/java/io/quarkus/docs/generation/YamlMetadataGenerator.java @@ -108,7 +108,10 @@ public boolean test(String p) { } public void writeYamlFiles() throws StreamWriteException, DatabindException, IOException { - ObjectMapper om = new ObjectMapper(new YAMLFactory().enable(YAMLGenerator.Feature.MINIMIZE_QUOTES)); + ObjectMapper om = new ObjectMapper( + new YAMLFactory() + .enable(YAMLGenerator.Feature.MINIMIZE_QUOTES) + .disable(YAMLGenerator.Feature.SPLIT_LINES)); Map<String, DocMetadata> metadata = index.metadataByFile(); om.writeValue(targetDir.resolve("indexByType.yaml").toFile(), index);
['docs/src/main/java/io/quarkus/docs/generation/YamlMetadataGenerator.java']
{'.java': 1}
1
1
0
0
1
26,201,643
5,169,359
666,943
6,173
332
53
5
1
2,941
342
699
79
4
4
1970-01-01T00:28:00
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,220
quarkusio/quarkus/32490/32418
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/32418
https://github.com/quarkusio/quarkus/pull/32490
https://github.com/quarkusio/quarkus/pull/32490
1
closes
Native build with jib and gradle fails on quarkus 3.0.0.CR1
### Describe the bug Trying to build a simple quarkus app with jib fails with following exception: On my windows developer system: ``` Starting Gradle Daemon... Gradle Daemon started in 1 s 520 ms > Task :processResources UP-TO-DATE > Task :quarkusGenerateCode UP-TO-DATE > Task :quarkusGenerateCodeDev UP-TO-DATE > Task :compileJava UP-TO-DATE > Task :classes UP-TO-DATE > Task :jar > Task :quarkusGenerateCodeTests UP-TO-DATE > Task :compileTestJava UP-TO-DATE > Task :processTestResources NO-SOURCE > Task :testClasses UP-TO-DATE > Task :compileIntegrationTestJava UP-TO-DATE > Task :processIntegrationTestResources NO-SOURCE > Task :integrationTestClasses UP-TO-DATE 22.3.0.1-Final-java17: Pulling from quarkus/ubi-quarkus-mandrel ... Digest: sha256:5f24fe7559dd5ed8f5765ea44de42395c7ae13f8ea48f75dd4ca3a67c3a91486 Status: Downloaded newer image for quay.io/quarkus/ubi-quarkus-mandrel:22.3.0.1-Final-java17 quay.io/quarkus/ubi-quarkus-mandrel:22.3.0.1-Final-java17 ======================================================================================================================== GraalVM Native Image: Generating 'health-server-undefined-runner' (executable)... ======================================================================================================================== [1/7] Initializing... (17.8s @ 0.31GB) Version info: 'GraalVM 22.3.0.1-Final Java 17 Mandrel Distribution' Java version info: '17.0.5+8' C compiler: gcc (redhat, x86_64, 8.5.0) Garbage collector: Serial GC 2 user-specific feature(s) - io.quarkus.runner.Feature: Auto-generated class by Quarkus from the existing extensions - io.quarkus.runtime.graal.DisableLoggingFeature: Disables INFO logging during the analysis phase [2/7] Performing analysis... [*******] (46.7s @ 2.16GB) 12,258 (89.78%) of 13,653 classes reachable 17,695 (59.23%) of 29,876 fields reachable 62,061 (56.41%) of 110,018 methods reachable 585 classes, 136 fields, and 2,960 methods registered for reflection 63 classes, 68 fields, and 55 methods registered for JNI access 4 native libraries: dl, pthread, rt, z [3/7] Building universe... (6.3s @ 4.51GB) [4/7] Parsing methods... [**] (4.2s @ 4.65GB) [5/7] Inlining methods... [***] (2.2s @ 2.83GB) [6/7] Compiling methods... [******] (32.5s @ 2.81GB) [7/7] Creating image... (5.2s @ 1.10GB) 22.93MB (47.92%) for code area: 40,468 compilation units 24.60MB (51.41%) for image heap: 303,638 objects and 17 resources 327.06KB ( 0.67%) for other data 47.84MB in total ------------------------------------------------------------------------------------------------------------------------ Top 10 packages in code area: Top 10 object types in image heap: 1.64MB sun.security.ssl 5.16MB byte[] for code metadata 1.05MB java.util 2.93MB java.lang.Class 741.65KB java.lang.invoke 2.77MB java.lang.String 718.51KB com.sun.crypto.provider 2.52MB byte[] for general heap data 491.66KB io.netty.buffer 2.30MB byte[] for java.lang.String 472.69KB java.lang 1.03MB com.oracle.svm.core.hub.DynamicHubCompanion 450.59KB sun.security.x509 689.06KB java.util.HashMap$Node 422.53KB java.util.concurrent 674.94KB byte[] for reflection metadata 413.01KB io.vertx.core.http.impl 560.07KB byte[] for embedded resources 395.60KB java.io 546.27KB java.lang.String[] 15.93MB for 462 more packages 4.72MB for 3029 more object types ------------------------------------------------------------------------------------------------------------------------ 4.8s (3.9% of total time) in 36 GCs | Peak RSS: 5.86GB | CPU load: 5.79 ------------------------------------------------------------------------------------------------------------------------ Produced artifacts: /project/health-server-undefined-runner (executable) /project/health-server-undefined-runner-build-output-stats.json (json) /project/health-server-undefined-runner-timing-stats.json (raw) /project/health-server-undefined-runner.build_artifacts.txt (txt) ======================================================================================================================== Finished generating 'health-server-undefined-runner' in 2m 0s. LOCALAPPDATA environment is invalid or missing > Task :quarkusAppPartsBuild FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':quarkusAppPartsBuild'. > There was a failure while executing work items > A failure occurred while executing io.quarkus.gradle.tasks.worker.BuildWorker > io.quarkus.builder.BuildException: Build failure: Build failed due to errors [error]: Build step io.quarkus.container.image.jib.deployment.JibProcessor#buildFromNative threw an exception: java.lang.RuntimeException: Unable to create container image at io.quarkus.container.image.jib.deployment.JibProcessor.containerize(JibProcessor.java:255) at io.quarkus.container.image.jib.deployment.JibProcessor.buildFromNative(JibProcessor.java:221) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at io.quarkus.deployment.ExtensionLoader$3.execute(ExtensionLoader.java:909) at io.quarkus.builder.BuildContext.run(BuildContext.java:282) at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2513) at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1538) at java.base/java.lang.Thread.run(Thread.java:833) at org.jboss.threads.JBossThread.run(JBossThread.java:501) Caused by: com.google.cloud.tools.jib.api.CacheDirectoryCreationException: Could not create cache directory at com.google.cloud.tools.jib.api.Containerizer.getApplicationLayersCacheDirectory(Containerizer.java:366) at com.google.cloud.tools.jib.api.JibContainerBuilder.toBuildContext(JibContainerBuilder.java:728) at com.google.cloud.tools.jib.api.JibContainerBuilder.containerize(JibContainerBuilder.java:604) at io.quarkus.container.image.jib.deployment.JibProcessor.containerize(JibProcessor.java:248) ... 12 more Caused by: java.nio.file.AccessDeniedException: C:\\WINDOWS\\jib-core-application-layers-cache at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:89) at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103) at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108) at java.base/sun.nio.fs.WindowsFileSystemProvider.createDirectory(WindowsFileSystemProvider.java:521) at java.base/java.nio.file.Files.createDirectory(Files.java:700) at java.base/java.nio.file.Files.createAndCheckIsDirectory(Files.java:807) at java.base/java.nio.file.Files.createDirectories(Files.java:793) at com.google.cloud.tools.jib.api.Containerizer.getApplicationLayersCacheDirectory(Containerizer.java:364) ... 15 more * Try: > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. > Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 3m 10s 9 actionable tasks: 2 executed, 7 up-to-date ``` On the github runners: ``` Starting a Gradle Daemon (subsequent builds will be faster) > Task :processResources > Task :quarkusGenerateCode > Task :quarkusGenerateCodeDev > Task :compileJava > Task :classes > Task :jar > Task :quarkusGenerateCodeTests > Task :compileTestJava > Task :processTestResources NO-SOURCE > Task :testClasses > Task :compileIntegrationTestJava > Task :processIntegrationTestResources NO-SOURCE > Task :integrationTestClasses 22.3.0.1-Final-java17: Pulling from quarkus/ubi-quarkus-mandrel Digest: sha256:5f24fe7559dd5ed8f5765ea44de42395c7ae13f8ea[48](https://github.com/QUMEA/health-server/actions/runs/4609842386/jobs/8147536859?pr=45#step:7:50)f75dd4ca3a67c3a91486 Status: Image is up to date for quay.io/quarkus/ubi-quarkus-mandrel:22.3.0.1-Final-java17 quay.io/quarkus/ubi-quarkus-mandrel:22.3.0.1-Final-java17 ======================================================================================================================== GraalVM Native Image: Generating 'health-server-undefined-runner' (executable)... ======================================================================================================================== [1/7] Initializing... (10.3s @ 0.32GB) Version info: 'GraalVM 22.3.0.1-Final Java 17 Mandrel Distribution' Java version info: '17.0.5+8' C compiler: gcc (redhat, x86_64, 8.5.0) Garbage collector: Serial GC 2 user-specific feature(s) - io.quarkus.runner.Feature: Auto-generated class by Quarkus from the existing extensions - io.quarkus.runtime.graal.DisableLoggingFeature: Disables INFO logging during the analysis phase > Task :quarkusAppPartsBuild [2/7] Performing analysis... [******] (116.3s @ 2.22GB) 12,252 (89.78%) of 13,647 classes reachable 17,695 (59.23%) of 29,876 fields reachable 62,0[49](https://github.com/QUMEA/health-server/actions/runs/4609842386/jobs/8147536859?pr=45#step:7:51) (56.41%) of 110,001 methods reachable 579 classes, 136 fields, and 2,954 methods registered for reflection 63 classes, 68 fields, and 55 methods registered for JNI access 4 native libraries: dl, pthread, rt, z [3/7] Building universe... (15.8s @ 1.65GB) [4/7] Parsing methods... [****] (13.4s @ 2.46GB) [5/7] Inlining methods... [***] (7.3s @ 1.31GB) [6/7] Compiling methods... [**********] (98.7s @ 1.36GB) [7/7] Creating image... (6.9s @ 2.11GB) 22.92MB (47.92%) for code area: 40,462 compilation units 24.59MB (51.41%) for image heap: 302,027 objects and 17 resources 328.64KB ( 0.67%) for other data 47.84MB in total ------------------------------------------------------------------------------------------------------------------------ Top 10 packages in code area: Top 10 object types in image heap: 1.64MB sun.security.ssl 5.16MB byte[] for code metadata 1.05MB java.util 2.92MB java.lang.Class 740.89KB java.lang.invoke 2.76MB java.lang.String 718.[50](https://github.com/QUMEA/health-server/actions/runs/4609842386/jobs/8147536859?pr=45#step:7:52)KB com.sun.crypto.provider 2.[51](https://github.com/QUMEA/health-server/actions/runs/4609842386/jobs/8147536859?pr=45#step:7:53)MB byte[] for general heap data 491.83KB io.netty.buffer 2.29MB byte[] for java.lang.String 472.72KB java.lang 1.03MB com.oracle.svm.core.hub.DynamicHubCompanion 450.59KB sun.security.x509 697.92KB java.util.HashMap$Node 422.44KB java.util.concurrent 674.[54](https://github.com/QUMEA/health-server/actions/runs/4609842386/jobs/8147536859?pr=45#step:7:56)KB byte[] for reflection metadata 412.95KB io.vertx.core.http.impl 560.07KB byte[] for embedded resources 395.58KB java.io 540.70KB java.lang.String[] 15.93MB for 462 more packages 4.68MB for 3028 more object types ------------------------------------------------------------------------------------------------------------------------ 13.5s (4.9% of total time) in [55](https://github.com/QUMEA/health-server/actions/runs/4609842386/jobs/8147536859?pr=45#step:7:57) GCs | Peak RSS: 3.38GB | CPU load: 1.[92](https://github.com/QUMEA/health-server/actions/runs/4609842386/jobs/8147536859?pr=45#step:7:94) ------------------------------------------------------------------------------------------------------------------------ Produced artifacts: /project/health-server-undefined-runner (executable) /project/health-server-undefined-runner-build-output-stats.json (json) /project/health-server-undefined-runner-timing-stats.json (raw) /project/health-server-undefined-runner.build_artifacts.txt (txt) ======================================================================================================================== Finished generating 'health-server-undefined-runner' in 4m 36s. Base image 'quay.io/quarkus/quarkus-micro-image:2.0' does not use a specific image digest - build may not be reproducible > Task :quarkusAppPartsBuild FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':quarkusAppPartsBuild'. > There was a failure while executing work items > A failure occurred while executing io.quarkus.gradle.tasks.worker.BuildWorker > java.lang.NullPointerException (no error message) * Try: > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. > Run with --scan to get full insights. ``` ### Expected behavior Just works as with quarkus 2.x ### Actual behavior _No response_ ### How to Reproduce? Try to build and run native quarkusIntTest together with the `io.quarkus:quarkus-container-image-jib` extension ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` 17 ### GraalVM version (if different from Java) 22.3.0.1 ### Quarkus version or git rev 3.0.0.CR1 ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Gradle 8.0 ### Additional information _No response_
501aa17e5f87e9eb355d03cecb9674bdb5842b9c
9df8ba7f899046dc9d21aa02401de4875c34fbad
https://github.com/quarkusio/quarkus/compare/501aa17e5f87e9eb355d03cecb9674bdb5842b9c...9df8ba7f899046dc9d21aa02401de4875c34fbad
diff --git a/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/worker/BuildWorker.java b/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/worker/BuildWorker.java index 25054b8134b..00a31cffb9a 100644 --- a/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/worker/BuildWorker.java +++ b/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/worker/BuildWorker.java @@ -59,7 +59,7 @@ public void execute() { LOGGER.warn("AugmentResult.results = null"); } else { LOGGER.info("AugmentResult.results = {}", results.stream().map(ArtifactResult::getPath) - .map(Object::toString).collect(Collectors.joining("\\n ", "\\n ", ""))); + .map(r -> r == null ? "null" : r.toString()).collect(Collectors.joining("\\n ", "\\n ", ""))); } JarResult jar = result.getJar(); LOGGER.info("AugmentResult:");
['devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/worker/BuildWorker.java']
{'.java': 1}
1
1
0
0
1
26,199,967
5,169,086
666,917
6,173
233
51
2
1
15,595
1,092
3,675
250
8
2
1970-01-01T00:28:00
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,221
quarkusio/quarkus/32481/32449
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/32449
https://github.com/quarkusio/quarkus/pull/32481
https://github.com/quarkusio/quarkus/pull/32481
1
fixes
Multitenancy OIDC permit tenant enumeration
### Describe the bug We have a multi tenant application which programmatically choose the tenant based in the URL path. However, unauthorized users are able to find out tenant names because if the OIDC server is down (not exists in this case) it return a 500 error messag. But if OIDC server exists it will return a 401. ### Expected behavior To avoid tenant enumeration both requests should return the same status code (401 or 404). ### Actual behavior The framework return 500 if server is down (or not exits) ### How to Reproduce? 1. Create a project with OIDC and Keycloak as dev service. 2. Configure a multi tenant architecture to [resolve tenant in URL path](https://quarkus.io/guides/security-openid-connect-multitenancy#tenant-config-resolver). 3. Try to access a nonexistence tenant with any credentials, it will return 500 4. Try to access a existence tenant with any credentials, it will return 401 ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information I tried to workaround the issue by using exception mapper but it not worked. (Method was not called)
4746a6925eea344c6ee2ea80cf5ee1e1c8801c4b
a6ee7a34b8faafa4fa8b8291f0566050e5b41285
https://github.com/quarkusio/quarkus/compare/4746a6925eea344c6ee2ea80cf5ee1e1c8801c4b...a6ee7a34b8faafa4fa8b8291f0566050e5b41285
diff --git a/extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/CodeFlowDevModeTestCase.java b/extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/CodeFlowDevModeTestCase.java index 00e003db3d7..410c8ee4f92 100644 --- a/extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/CodeFlowDevModeTestCase.java +++ b/extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/CodeFlowDevModeTestCase.java @@ -124,6 +124,18 @@ private void useTenantConfigResolver() throws IOException, InterruptedException assertEquals("tenant-config-resolver:alice", page.getBody().asNormalizedText()); webClient.getCookieManager().clearCookies(); + try { + webClient.getPage("http://localhost:8080/protected/tenant/null-tenant"); + fail("401 status error is expected"); + } catch (FailingHttpStatusCodeException ex) { + assertEquals(401, ex.getStatusCode()); + } + try { + webClient.getPage("http://localhost:8080/protected/tenant/unknown-tenant"); + fail("401 status error is expected"); + } catch (FailingHttpStatusCodeException ex) { + assertEquals(401, ex.getStatusCode()); + } } } diff --git a/extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/CustomTenantConfigResolver.java b/extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/CustomTenantConfigResolver.java index 9bba5cbd1c8..4b88cadd8a7 100644 --- a/extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/CustomTenantConfigResolver.java +++ b/extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/CustomTenantConfigResolver.java @@ -22,6 +22,9 @@ public Uni<OidcTenantConfig> resolve(RoutingContext context, OidcRequestContext< config.setApplicationType(ApplicationType.WEB_APP); return Uni.createFrom().item(config); } + if (context.request().path().endsWith("/null-tenant")) { + return null; + } return Uni.createFrom().nullItem(); } diff --git a/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/DefaultTenantConfigResolver.java b/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/DefaultTenantConfigResolver.java index 721ab284016..946a02998de 100644 --- a/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/DefaultTenantConfigResolver.java +++ b/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/DefaultTenantConfigResolver.java @@ -185,7 +185,12 @@ private Uni<OidcTenantConfig> getDynamicTenantConfig(RoutingContext context) { if (tenantConfigResolver.isResolvable()) { Uni<OidcTenantConfig> oidcConfig = context.get(CURRENT_DYNAMIC_TENANT_CONFIG); if (oidcConfig == null) { - oidcConfig = tenantConfigResolver.get().resolve(context, blockingRequestContext).memoize().indefinitely(); + oidcConfig = tenantConfigResolver.get().resolve(context, blockingRequestContext); + if (oidcConfig == null) { + //shouldn't happen, but guard against it anyway + oidcConfig = Uni.createFrom().nullItem(); + } + oidcConfig = oidcConfig.memoize().indefinitely(); if (oidcConfig == null) { //shouldn't happen, but guard against it anyway oidcConfig = Uni.createFrom().nullItem();
['extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/CustomTenantConfigResolver.java', 'extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/DefaultTenantConfigResolver.java', 'extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/CodeFlowDevModeTestCase.java']
{'.java': 3}
3
3
0
0
3
26,198,741
5,168,814
666,886
6,173
483
92
7
1
1,350
212
314
42
1
0
1970-01-01T00:28:00
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,222
quarkusio/quarkus/32386/32203
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/32203
https://github.com/quarkusio/quarkus/pull/32386
https://github.com/quarkusio/quarkus/pull/32386
1
fix
Do not print stack-trace in LogStreamBroadcaster.recordHistory
### Describe the bug ```posh java.lang.InterruptedException at java.base/java.util.concurrent.locks.ReentrantLock$Sync.lockInterruptibly(ReentrantLock.java:159) at java.base/java.util.concurrent.locks.ReentrantLock.lockInterruptibly(ReentrantLock.java:372) at java.base/java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:432) at io.quarkus.devui.runtime.logstream.LogStreamBroadcaster.recordHistory(LogStreamBroadcaster.java:33) at io.quarkus.devui.runtime.logstream.LogStreamBroadcaster.onNext(LogStreamBroadcaster.java:21) at io.quarkus.devui.runtime.logstream.LogStreamBroadcaster_ClientProxy.onNext(Unknown Source) at io.quarkus.devui.runtime.logstream.MutinyLogHandler.doPublish(MutinyLogHandler.java:31) at org.jboss.logmanager.ExtHandler.publish(ExtHandler.java:66) at org.jboss.logmanager.ExtHandler.publishToNestedHandlers(ExtHandler.java:97) at io.quarkus.bootstrap.logging.QuarkusDelayedHandler.doPublish(QuarkusDelayedHandler.java:81) at org.jboss.logmanager.ExtHandler.publish(ExtHandler.java:66) at org.jboss.logmanager.LoggerNode.publish(LoggerNode.java:327) at org.jboss.logmanager.LoggerNode.publish(LoggerNode.java:334) at org.jboss.logmanager.LoggerNode.publish(LoggerNode.java:334) at org.jboss.logmanager.LoggerNode.publish(LoggerNode.java:334) at org.jboss.logmanager.LoggerNode.publish(LoggerNode.java:334) at org.jboss.logmanager.LoggerNode.publish(LoggerNode.java:334) at org.jboss.logmanager.LoggerNode.publish(LoggerNode.java:334) at org.jboss.logmanager.Logger.logRaw(Logger.java:750) ... at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635) at java.base/java.lang.Thread.run(Thread.java:833) ``` This is perfectly OK, but the stacktrace should not be printed to the console by default in io.quarkus.devui.runtime.logstream.LogStreamBroadcaster: ```java private void recordHistory(final JsonObject message) { synchronized (this) { try { if (history.remainingCapacity() == 0) { history.take(); } history.add(message); } catch (InterruptedException ex) { ex.printStackTrace(); // <------- REMOVE THIS Thread.currentThread().interrupt(); } } } ``` ### Expected behavior No stacktrace in console logging ### Actual behavior stacktrace is printed on console ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
10faad0c3adb40a7d64ef16c69c7ef5749a89eb4
869fdbd5f6c020d0fa009787e29fae277e9215f0
https://github.com/quarkusio/quarkus/compare/10faad0c3adb40a7d64ef16c69c7ef5749a89eb4...869fdbd5f6c020d0fa009787e29fae277e9215f0
diff --git a/extensions/vertx-http/runtime/src/main/java/io/quarkus/devui/runtime/logstream/LogStreamBroadcaster.java b/extensions/vertx-http/runtime/src/main/java/io/quarkus/devui/runtime/logstream/LogStreamBroadcaster.java index c250718564f..dd505f861c9 100644 --- a/extensions/vertx-http/runtime/src/main/java/io/quarkus/devui/runtime/logstream/LogStreamBroadcaster.java +++ b/extensions/vertx-http/runtime/src/main/java/io/quarkus/devui/runtime/logstream/LogStreamBroadcaster.java @@ -34,7 +34,6 @@ private void recordHistory(final JsonObject message) { } history.add(message); } catch (InterruptedException ex) { - ex.printStackTrace(); Thread.currentThread().interrupt(); } }
['extensions/vertx-http/runtime/src/main/java/io/quarkus/devui/runtime/logstream/LogStreamBroadcaster.java']
{'.java': 1}
1
1
0
0
1
26,130,557
5,155,430
665,280
6,161
38
4
1
1
3,130
179
660
82
0
2
1970-01-01T00:28:00
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,223
quarkusio/quarkus/32319/32289
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/32289
https://github.com/quarkusio/quarkus/pull/32319
https://github.com/quarkusio/quarkus/pull/32319
1
fixes
Quarkus 3.0.0.Alpha4 introduces a performance regression
### Describe the bug A drop in mean throughput performance has been spotted while validating Camel Quarkus 3.0.0-M1 staging release upstream: ``` 2.16.0 | 30m | 38804.35 req/s [+0.00%] | 22357.99 req/s [+0.00%] | OK | 3.0.0-M1 | 30m | 38857.07 req/s [+0.14%] | 21166.75 req/s [-5.33%] | Potential performance regression | ``` After investigation, it looks like the regression has been introduced when we switched to Quarkus 3.0.0.Alpha4. From this version onward, there is a noticeable log related to direct buffers that could be a good candidate to explain the regression as shown below: ``` 2023-03-29 19:32:02,511 INFO [io.net.uti.int.PlatformDependent] (Thread-1) Your platform does not provide complete low-level API for accessing direct buffers reliably. Unless explicitly requested, heap buffer will always be preferred to avoid potential system instability. ``` And we see in the native-image command line that a new argument has been introduced: `-J-Dio.netty.noUnsafe=true` This new behavior comes from commit below: https://github.com/quarkusio/quarkus/commit/ca155cae76c7caf7d6c4bbf27e9ac22305d2dbf0 I've then tested with `-Dquarkus.native.additional-build-args=-J-Dio.netty.noUnsafe=false` and the performance regression is gone. Somehow, it could mean that netty could not use unsafe and so couldn't use direct buffers. In the end resulting in a performance penalty. ### Expected behavior _No response_ ### Actual behavior _No response_ ### How to Reproduce? The simplest way to to reproduce would be to run the Camel Quarkus performance regression tool, something like: ``` git clone git@github.com:apache/camel-quarkus.git git checkout aa942c217a3dab5900ff175964641b798ccc62b5 mvn clean install -Dquickly cd tooling/performance-regression java -jar target/quarkus-app/quarkus-run.jar -an 2.16.0 3.0.0-SNAPSHOT ``` After 45 minutes run on a machine equally loaded over that period, it should print a report like: ``` Camel Quarkus Throughput Performance Increase Compared to Previous Version Camel Quarkus version | Duration | JVM req/s [%increase] | Native req/s [%increase] | Status | ------------------------------------------------------------------------------------------------------------------------------------ 2.16.0 | 30m | 38804.35 req/s [+0.00%] | 22357.99 req/s [+0.00%] | OK | 3.0.0-SNAPSHOT | 30m | 38857.07 req/s [+0.14%] | 21166.75 req/s [-5.33%] | Potential performance regression | ``` ### Output of `uname -a` or `ver` Linux me.csb 4.18.0-425.13.1.el8_7.x86_64 #1 SMP Thu Feb 2 13:01:45 EST 2023 x86_64 x86_64 x86_64 GNU/Linux ### Output of `java -version` 22.3.1.0-Final Mandrel Distribution (Java Version 17.0.6+10) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 3.0.0.Alpha4 ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) 3.8.7 ### Additional information _No response_
34accfcd59171845a4e79605dacf24205767caee
54a4d81e70c261bd7abf82e2893f5bd7be5577d7
https://github.com/quarkusio/quarkus/compare/34accfcd59171845a4e79605dacf24205767caee...54a4d81e70c261bd7abf82e2893f5bd7be5577d7
diff --git a/extensions/netty/deployment/src/main/java/io/quarkus/netty/deployment/NettyProcessor.java b/extensions/netty/deployment/src/main/java/io/quarkus/netty/deployment/NettyProcessor.java index 13171bec796..365f1ac191f 100644 --- a/extensions/netty/deployment/src/main/java/io/quarkus/netty/deployment/NettyProcessor.java +++ b/extensions/netty/deployment/src/main/java/io/quarkus/netty/deployment/NettyProcessor.java @@ -31,7 +31,6 @@ import io.quarkus.deployment.builditem.nativeimage.RuntimeReinitializedClassBuildItem; import io.quarkus.deployment.builditem.nativeimage.UnsafeAccessedFieldBuildItem; import io.quarkus.deployment.logging.LogCleanupFilterBuildItem; -import io.quarkus.deployment.pkg.steps.NativeOrNativeSourcesBuild; import io.quarkus.netty.BossEventLoopGroup; import io.quarkus.netty.MainEventLoopGroup; import io.quarkus.netty.runtime.EmptyByteBufStub; @@ -78,7 +77,7 @@ public SystemPropertyBuildItem setNettyMachineId() { return new SystemPropertyBuildItem("io.netty.machineId", nettyMachineId); } - @BuildStep(onlyIf = NativeOrNativeSourcesBuild.class) + @BuildStep NativeImageConfigBuildItem build( NettyBuildTimeConfig config, BuildProducer<ReflectiveClassBuildItem> reflectiveClass, @@ -95,8 +94,6 @@ NativeImageConfigBuildItem build( String maxOrder = calculateMaxOrder(config.allocatorMaxOrder, minMaxOrderBuildItems, false); NativeImageConfigBuildItem.Builder builder = NativeImageConfigBuildItem.builder() - // disable unsafe usage to allow io.netty.internal.PlarformDependent0 to be reinitialized without issues - .addNativeImageSystemProperty("io.netty.noUnsafe", "true") // Use small chunks to avoid a lot of wasted space. Default is 16mb * arenas (derived from core count) // Since buffers are cached to threads, the malloc overhead is temporary anyway .addNativeImageSystemProperty("io.netty.allocator.maxOrder", maxOrder) @@ -112,14 +109,8 @@ NativeImageConfigBuildItem build( .addRuntimeInitializedClass("io.netty.buffer.ByteBufUtil") // The default channel id uses the process id, it should not be cached in the native image. .addRuntimeInitializedClass("io.netty.channel.DefaultChannelId") - // Make sure to re-initialize platform dependent classes/values at runtime - .addRuntimeReinitializedClass("io.netty.util.internal.PlatformDependent") - .addRuntimeReinitializedClass("io.netty.util.internal.PlatformDependent0") .addNativeImageSystemProperty("io.netty.leakDetection.level", "DISABLED"); - // Also set io.netty.noUnsafe at runtime - systemProperties.produce(new SystemPropertyBuildItem("io.netty.noUnsafe", "true")); - if (QuarkusClassLoader.isClassPresentAtRuntime("io.netty.handler.codec.http.HttpObjectEncoder")) { builder .addRuntimeInitializedClass("io.netty.handler.codec.http.HttpObjectEncoder") @@ -168,7 +159,8 @@ NativeImageConfigBuildItem build( log.debug("Not registering Netty native kqueue classes as they were not found"); } - return builder.build(); + return builder //TODO: make configurable + .build(); } @BuildStep
['extensions/netty/deployment/src/main/java/io/quarkus/netty/deployment/NettyProcessor.java']
{'.java': 1}
1
1
0
0
1
24,322,287
4,789,524
620,172
5,679
870
171
14
1
3,212
382
879
73
1
4
1970-01-01T00:28:00
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,224
quarkusio/quarkus/32309/32246
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/32246
https://github.com/quarkusio/quarkus/pull/32309
https://github.com/quarkusio/quarkus/pull/32309
1
fixes
Quarkus doesn't detect Docker rootless anymore
### Describe the bug Starting from ``2.16.4.Final``, Quarkus cannot detect ```Docker rootless``` anymore. Reason for that is a faulty implemenation in ``ContainerRuntimeUtil.getRootlessStateFor``: ```java private static boolean getRootlessStateFor(ContainerRuntime containerRuntime) { ...... try (InputStream inputStream = rootlessProcess.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) { Predicate<String> stringPredicate; // Docker includes just "rootless" under SecurityOptions, while podman includes "rootless: <boolean>" ---> if (containerRuntime == ContainerRuntime.DOCKER) { <-- ContainerRuntime.DOCKER is null stringPredicate = line -> line.trim().equals("rootless"); } else { stringPredicate = line -> line.trim().equals("rootless: true"); } return bufferedReader.lines().anyMatch(stringPredicate); } ..... } /** * Supported Container runtimes */ public enum ContainerRuntime { DOCKER, PODMAN; private final boolean rootless; ContainerRuntime() { this.rootless = getRootlessStateFor(this); } public String getExecutableName() { return this.name().toLowerCase(); } public boolean isRootless() { return rootless; } } ``` This condition ``containerRuntime == ContainerRuntime.DOCKER`` always evaluates to false, since ContainerRuntime.DOCKER is null. That's because ``getRootlessStateFor`` is being called during constructor execution of ContainerRuntime. Thus we end up in the ``podman`` case, even when ``Docker`` is being detected! ### Expected behavior Quarkus should detect ``Docker rootless`` properly :-) ### Actual behavior Quarkus native container builds aren't working on Docker rootless anymore, because the rootless detection fails. Therefor the container isn't started as root, but rather non root which leads to file permission issues .. ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` 5.4.228 ...... x86_64 x86_64 x86_64 GNU/Linux ### Output of `java -version` 17 ### GraalVM version (if different from Java) GraalVM 22.3.0 Java 17 CE ### Quarkus version or git rev 2.16.4.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Maven 3.8.6 ### Additional information ``` Docker version 20.10.22, build 3a2c30b runner@....:/$ docker info Client: Context: default Debug Mode: false Server: Containers: 0 Running: 0 Paused: 0 Stopped: 0 Images: 0 Server Version: 20.10.22 Storage Driver: vfs Logging Driver: json-file Cgroup Driver: none Cgroup Version: 1 Plugins: Volume: local Network: bridge host ipvlan macvlan null overlay Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog Swarm: inactive Runtimes: io.containerd.runc.v2 io.containerd.runtime.v1.linux runc Default Runtime: runc Init Binary: docker-init containerd version: 78f51771157abb6c9ed224c22013cdf09962315d runc version: v1.1.4-0-g5fd4c4d1 init version: de40ad0 Security Options: seccomp Profile: default **rootless** Kernel Version: 5.4.228-132.418.amzn2.x86_64 Operating System: Ubuntu 22.04.1 LTS (containerized) OSType: linux Architecture: x86_64 CPUs: 4 Total Memory: 15.34GiB Name: ...... Docker Root Dir: /home/runner/.local/share/docker Debug Mode: false Registry: https://index.docker.io/v1/ Labels: ... Experimental: false Insecure Registries: 127.0.0.0/8 Live Restore Enabled: false Product License: Community Engine WARNING: Running in rootless-mode without cgroups. To enable cgroups in rootless-mode, you need to boot the system in cgroup v2 mode. ```
5f5f11880a5b38f538adc0fac12fe9f15e3982a1
f2f24bed7f45e832e34458fc783b270be7007839
https://github.com/quarkusio/quarkus/compare/5f5f11880a5b38f538adc0fac12fe9f15e3982a1...f2f24bed7f45e832e34458fc783b270be7007839
diff --git a/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildContainerRunner.java b/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildContainerRunner.java index ef53e1b4f7b..ccca09727a2 100644 --- a/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildContainerRunner.java +++ b/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildContainerRunner.java @@ -42,8 +42,7 @@ public boolean isContainer() { @Override public void setup(boolean processInheritIODisabled) { - if (containerRuntime == ContainerRuntimeUtil.ContainerRuntime.DOCKER - || containerRuntime == ContainerRuntimeUtil.ContainerRuntime.PODMAN) { + if (containerRuntime != ContainerRuntimeUtil.ContainerRuntime.UNAVAILABLE) { log.infof("Using %s to run the native image builder", containerRuntime.getExecutableName()); // we pull the docker image in order to give users an indication of which step the process is at // it's not strictly necessary we do this, however if we don't the subsequent version command diff --git a/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildLocalContainerRunner.java b/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildLocalContainerRunner.java index e9f1c1125ef..c5e50652d4d 100644 --- a/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildLocalContainerRunner.java +++ b/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildLocalContainerRunner.java @@ -1,8 +1,6 @@ package io.quarkus.deployment.pkg.steps; import static io.quarkus.deployment.pkg.steps.LinuxIDUtil.getLinuxID; -import static io.quarkus.runtime.util.ContainerRuntimeUtil.ContainerRuntime.DOCKER; -import static io.quarkus.runtime.util.ContainerRuntimeUtil.ContainerRuntime.PODMAN; import java.nio.file.Path; import java.util.ArrayList; @@ -21,14 +19,14 @@ public NativeImageBuildLocalContainerRunner(NativeConfig nativeConfig) { super(nativeConfig); if (SystemUtils.IS_OS_LINUX) { final ArrayList<String> containerRuntimeArgs = new ArrayList<>(Arrays.asList(baseContainerRuntimeArgs)); - if (containerRuntime == DOCKER && containerRuntime.isRootless()) { + if (containerRuntime.isDocker() && containerRuntime.isRootless()) { Collections.addAll(containerRuntimeArgs, "--user", String.valueOf(0)); } else { String uid = getLinuxID("-ur"); String gid = getLinuxID("-gr"); if (uid != null && gid != null && !uid.isEmpty() && !gid.isEmpty()) { Collections.addAll(containerRuntimeArgs, "--user", uid + ":" + gid); - if (containerRuntime == PODMAN && containerRuntime.isRootless()) { + if (containerRuntime.isPodman() && containerRuntime.isRootless()) { // Needed to avoid AccessDeniedExceptions containerRuntimeArgs.add("--userns=keep-id"); } @@ -47,7 +45,7 @@ protected List<String> getContainerRuntimeBuildArgs(Path outputDir) { } final String selinuxBindOption; - if (SystemUtils.IS_OS_MAC && containerRuntime == PODMAN) { + if (SystemUtils.IS_OS_MAC && containerRuntime.isPodman()) { selinuxBindOption = ""; } else { selinuxBindOption = ":z"; diff --git a/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/UpxCompressionBuildStep.java b/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/UpxCompressionBuildStep.java index 9174db0e4c7..a4880647973 100644 --- a/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/UpxCompressionBuildStep.java +++ b/core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/UpxCompressionBuildStep.java @@ -126,8 +126,7 @@ private boolean runUpxInContainer(NativeImageBuildItem nativeImage, NativeConfig String gid = getLinuxID("-gr"); if (uid != null && gid != null && !uid.isEmpty() && !gid.isEmpty()) { Collections.addAll(commandLine, "--user", uid + ":" + gid); - if (containerRuntime == ContainerRuntimeUtil.ContainerRuntime.PODMAN - && containerRuntime.isRootless()) { + if (containerRuntime.isPodman() && containerRuntime.isRootless()) { // Needed to avoid AccessDeniedExceptions commandLine.add("--userns=keep-id"); } diff --git a/core/runtime/src/main/java/io/quarkus/runtime/util/ContainerRuntimeUtil.java b/core/runtime/src/main/java/io/quarkus/runtime/util/ContainerRuntimeUtil.java index 1ae65cc8a5b..c2d254d25ed 100644 --- a/core/runtime/src/main/java/io/quarkus/runtime/util/ContainerRuntimeUtil.java +++ b/core/runtime/src/main/java/io/quarkus/runtime/util/ContainerRuntimeUtil.java @@ -31,10 +31,7 @@ private ContainerRuntimeUtil() { } /** - * @return {@link ContainerRuntime#DOCKER} if it's available, or {@link ContainerRuntime#PODMAN} - * if the podman - * executable exists in the environment or if the docker executable is an alias to podman, - * or {@link ContainerRuntime#UNAVAILABLE} if no container runtime is available and the required arg is false. + * @return a fully resolved {@link ContainerRuntime} indicating if Docker or Podman is available and in rootless mode or not * @throws IllegalStateException if no container runtime was found to build the image */ public static ContainerRuntime detectContainerRuntime() { @@ -42,66 +39,88 @@ public static ContainerRuntime detectContainerRuntime() { } public static ContainerRuntime detectContainerRuntime(boolean required) { - final ContainerRuntime containerRuntime = loadContainerRuntimeFromSystemProperty(); + ContainerRuntime containerRuntime = loadContainerRuntimeFromSystemProperty(); if (containerRuntime != null) { return containerRuntime; - } else { - // Docker version 19.03.14, build 5eb3275d40 - String dockerVersionOutput; - boolean dockerAvailable; - // Check if Podman is installed - // podman version 2.1.1 - String podmanVersionOutput; - boolean podmanAvailable; - if (CONTAINER_EXECUTABLE != null) { - if (CONTAINER_EXECUTABLE.trim().equalsIgnoreCase("docker")) { - dockerVersionOutput = getVersionOutputFor(ContainerRuntime.DOCKER); - dockerAvailable = dockerVersionOutput.contains("Docker version"); - if (dockerAvailable) { - storeContainerRuntimeInSystemProperty(ContainerRuntime.DOCKER); - return ContainerRuntime.DOCKER; - } - } - if (CONTAINER_EXECUTABLE.trim().equalsIgnoreCase("podman")) { - podmanVersionOutput = getVersionOutputFor(ContainerRuntime.PODMAN); - podmanAvailable = podmanVersionOutput.startsWith("podman version"); - if (podmanAvailable) { - storeContainerRuntimeInSystemProperty(ContainerRuntime.PODMAN); - return ContainerRuntime.PODMAN; - } + } + + ContainerRuntime containerRuntimeEnvironment = getContainerRuntimeEnvironment(); + if (containerRuntimeEnvironment == ContainerRuntime.UNAVAILABLE) { + storeContainerRuntimeInSystemProperty(ContainerRuntime.UNAVAILABLE); + + if (required) { + throw new IllegalStateException("No container runtime was found. " + + "Make sure you have either Docker or Podman installed in your environment."); + } + + return ContainerRuntime.UNAVAILABLE; + } + + // we have a working container environment, let's resolve it fully + containerRuntime = fullyResolveContainerRuntime(containerRuntimeEnvironment); + + storeContainerRuntimeInSystemProperty(containerRuntime); + + return containerRuntime; + } + + private static ContainerRuntime getContainerRuntimeEnvironment() { + // Docker version 19.03.14, build 5eb3275d40 + String dockerVersionOutput; + boolean dockerAvailable; + // Check if Podman is installed + // podman version 2.1.1 + String podmanVersionOutput; + boolean podmanAvailable; + + if (CONTAINER_EXECUTABLE != null) { + if (CONTAINER_EXECUTABLE.trim().equalsIgnoreCase("docker")) { + dockerVersionOutput = getVersionOutputFor(ContainerRuntime.DOCKER); + dockerAvailable = dockerVersionOutput.contains("Docker version"); + if (dockerAvailable) { + return ContainerRuntime.DOCKER; } - log.warn("quarkus.native.container-runtime config property must be set to either podman or docker " + - "and the executable must be available. Ignoring it."); } - dockerVersionOutput = getVersionOutputFor(ContainerRuntime.DOCKER); - dockerAvailable = dockerVersionOutput.contains("Docker version"); - if (dockerAvailable) { - // Check if "docker" is an alias to "podman" - if (dockerVersionOutput.startsWith("podman version") || - dockerVersionOutput.startsWith("podman.exe version")) { - storeContainerRuntimeInSystemProperty(ContainerRuntime.PODMAN); + if (CONTAINER_EXECUTABLE.trim().equalsIgnoreCase("podman")) { + podmanVersionOutput = getVersionOutputFor(ContainerRuntime.PODMAN); + podmanAvailable = podmanVersionOutput.startsWith("podman version"); + if (podmanAvailable) { return ContainerRuntime.PODMAN; } - storeContainerRuntimeInSystemProperty(ContainerRuntime.DOCKER); - return ContainerRuntime.DOCKER; } - podmanVersionOutput = getVersionOutputFor(ContainerRuntime.PODMAN); - podmanAvailable = podmanVersionOutput.startsWith("podman version") || - podmanVersionOutput.startsWith("podman.exe version"); - if (podmanAvailable) { - storeContainerRuntimeInSystemProperty(ContainerRuntime.PODMAN); + log.warn("quarkus.native.container-runtime config property must be set to either podman or docker " + + "and the executable must be available. Ignoring it."); + } + + dockerVersionOutput = getVersionOutputFor(ContainerRuntime.DOCKER); + dockerAvailable = dockerVersionOutput.contains("Docker version"); + if (dockerAvailable) { + // Check if "docker" is an alias to "podman" + if (dockerVersionOutput.startsWith("podman version") || + dockerVersionOutput.startsWith("podman.exe version")) { return ContainerRuntime.PODMAN; } + return ContainerRuntime.DOCKER; + } + podmanVersionOutput = getVersionOutputFor(ContainerRuntime.PODMAN); + podmanAvailable = podmanVersionOutput.startsWith("podman version") || + podmanVersionOutput.startsWith("podman.exe version"); + if (podmanAvailable) { + return ContainerRuntime.PODMAN; + } - storeContainerRuntimeInSystemProperty(ContainerRuntime.UNAVAILABLE); + return ContainerRuntime.UNAVAILABLE; + } - if (required) { - throw new IllegalStateException("No container runtime was found. " - + "Make sure you have either Docker or Podman installed in your environment."); - } + private static ContainerRuntime fullyResolveContainerRuntime(ContainerRuntime containerRuntimeEnvironment) { + boolean rootless = getRootlessStateFor(containerRuntimeEnvironment); - return ContainerRuntime.UNAVAILABLE; + if (!rootless) { + return containerRuntimeEnvironment; } + + return containerRuntimeEnvironment == ContainerRuntime.DOCKER ? ContainerRuntime.DOCKER_ROOTLESS + : ContainerRuntime.PODMAN_ROOTLESS; } private static ContainerRuntime loadContainerRuntimeFromSystemProperty() { @@ -195,16 +214,19 @@ private static boolean getRootlessStateFor(ContainerRuntime containerRuntime) { * Supported Container runtimes */ public enum ContainerRuntime { - DOCKER("docker" + (OS.current() == OS.WINDOWS ? ".exe" : "")), - PODMAN("podman" + (OS.current() == OS.WINDOWS ? ".exe" : "")), - UNAVAILABLE(null); + DOCKER("docker", false), + DOCKER_ROOTLESS("docker", true), + PODMAN("podman", false), + PODMAN_ROOTLESS("podman", true), + UNAVAILABLE(null, false); - private Boolean rootless; + private final String executableName; - private String executableName; + private final boolean rootless; - ContainerRuntime(String executableName) { - this.executableName = executableName; + ContainerRuntime(String executableName, boolean rootless) { + this.executableName = executableName + (OS.current() == OS.WINDOWS ? ".exe" : ""); + this.rootless = rootless; } public String getExecutableName() { @@ -215,17 +237,15 @@ public String getExecutableName() { return executableName; } + public boolean isDocker() { + return this == DOCKER || this == DOCKER_ROOTLESS; + } + + public boolean isPodman() { + return this == PODMAN || this == PODMAN_ROOTLESS; + } + public boolean isRootless() { - if (rootless != null) { - return rootless; - } else { - if (this != ContainerRuntime.UNAVAILABLE) { - rootless = getRootlessStateFor(this); - } else { - throw new IllegalStateException("No container runtime was found. " - + "Make sure you have either Docker or Podman installed in your environment."); - } - } return rootless; }
['core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildLocalContainerRunner.java', 'core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/NativeImageBuildContainerRunner.java', 'core/deployment/src/main/java/io/quarkus/deployment/pkg/steps/UpxCompressionBuildStep.java', 'core/runtime/src/main/java/io/quarkus/runtime/util/ContainerRuntimeUtil.java']
{'.java': 4}
4
4
0
0
4
26,269,957
5,182,364
668,580
6,188
9,478
1,756
170
4
4,106
427
995
136
1
3
1970-01-01T00:28:00
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,225
quarkusio/quarkus/32278/32152
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/32152
https://github.com/quarkusio/quarkus/pull/32278
https://github.com/quarkusio/quarkus/pull/32278
1
fixes
Quarkus 2.13 test extension tests fail with the 22.3 mandrel builder image
### Describe the bug The integration tests fail with the 22.3 mandrel builder image. Filing this for tracking purposes: ``` [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running io.quarkus.it.extension.ClasspathInGraalITCase Executing "/home/runner/work/mandrel/mandrel/quarkus/integration-tests/test-extension/tests/target/quarkus-integration-test-test-extension-tests-999-SNAPSHOT-runner -Dquarkus.http.port=8081 -Dquarkus.http.ssl-port=8444 -Dtest.url=http://localhost:8081 -Dquarkus.log.file.path=/home/runner/work/mandrel/mandrel/quarkus/integration-tests/test-extension/tests/target/quarkus.log -Dquarkus.log.file.enable=true" Mar 25, 2023 2:19:24 AM io.quarkus.runtime.ApplicationLifecycleManager run ERROR: Failed to start application (with profile prod) java.lang.ClassNotFoundException: io.quarkus.extest.runtime.config.RunTimeConfigBuilder at java.base@17.0.6/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:52) at java.base@17.0.6/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188) at java.base@17.0.6/java.lang.ClassLoader.loadClass(ClassLoader.java:132) at io.quarkus.runtime.configuration.ConfigUtils.configBuilder(ConfigUtils.java:189) at io.quarkus.runtime.generated.Config.readConfig(Unknown Source) at io.quarkus.deployment.steps.RuntimeConfigSetup.deploy(Unknown Source) at io.quarkus.runner.ApplicationImpl.doStart(Unknown Source) at io.quarkus.runtime.Application.start(Application.java:101) at io.quarkus.runtime.ApplicationLifecycleManager.run(ApplicationLifecycleManager.java:110) at io.quarkus.runtime.Quarkus.run(Quarkus.java:70) at io.quarkus.runtime.Quarkus.run(Quarkus.java:43) at io.quarkus.runtime.Quarkus.run(Quarkus.java:123) at io.quarkus.runner.GeneratedMain.main(Unknown Source) ``` ### Expected behavior Test extension tests pass with the builder image. ### Actual behavior Test throws `ClassNotFoundException` at boot. ### How to Reproduce? Run integration tests extension tests with the 22.3 builder image. ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information See https://github.com/graalvm/mandrel/actions/runs/4516801805/jobs/7955690955#step:11:1120
ae4f5673759bbb231790f620fc1d7bdedc1790ed
28ea5889386030b7cf7a76b0effd2f1b95ad0446
https://github.com/quarkusio/quarkus/compare/ae4f5673759bbb231790f620fc1d7bdedc1790ed...28ea5889386030b7cf7a76b0effd2f1b95ad0446
diff --git a/core/deployment/src/main/java/io/quarkus/deployment/steps/ConfigGenerationBuildStep.java b/core/deployment/src/main/java/io/quarkus/deployment/steps/ConfigGenerationBuildStep.java index 33453e60485..3d48d5f38f6 100644 --- a/core/deployment/src/main/java/io/quarkus/deployment/steps/ConfigGenerationBuildStep.java +++ b/core/deployment/src/main/java/io/quarkus/deployment/steps/ConfigGenerationBuildStep.java @@ -265,6 +265,11 @@ void generateConfigClass( runtimeMappings.addAll(configItem.getReadResult().getBuildTimeRunTimeMappings()); runtimeMappings.addAll(configItem.getReadResult().getRunTimeMappings()); + Set<String> runtimeConfigBuilderClassNames = runTimeConfigBuilders.stream() + .map(RunTimeConfigBuilderBuildItem::getBuilderClassName).collect(toSet()); + reflectiveClass + .produce(new ReflectiveClassBuildItem(false, false, runtimeConfigBuilderClassNames.toArray(new String[0]))); + RunTimeConfigurationGenerator.GenerateOperation .builder() .setBuildTimeReadResult(configItem.getReadResult()) @@ -285,8 +290,7 @@ void generateConfigClass( .setRuntimeConfigSourceProviders(discoveredConfigSourceProviders) .setRuntimeConfigSourceFactories(discoveredConfigSourceFactories) .setRuntimeConfigMappings(runtimeMappings) - .setRuntimeConfigBuilders( - runTimeConfigBuilders.stream().map(RunTimeConfigBuilderBuildItem::getBuilderClassName).collect(toSet())) + .setRuntimeConfigBuilders(runtimeConfigBuilderClassNames) .build() .run(); }
['core/deployment/src/main/java/io/quarkus/deployment/steps/ConfigGenerationBuildStep.java']
{'.java': 1}
1
1
0
0
1
22,788,604
4,462,594
582,200
5,410
578
107
8
1
2,563
172
624
63
2
1
1970-01-01T00:28:00
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,227
quarkusio/quarkus/32208/32193
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/32193
https://github.com/quarkusio/quarkus/pull/32208
https://github.com/quarkusio/quarkus/pull/32208
1
fix
Kubernetes config now requires explicit `view-secrets` authorization to access secrets that is not needed
### Describe the bug I have application that uses the Quarkus Kubernetes config extension access OpenShift secret. When migrating to Quarkus 3.0, deployment fails over missing `view-secrets` authorization. I only access secrets that I created in namespace I also created with the same OpenShift user that I use for deployment, therefore I have sufficient rights to access the secrets. This worked in Quarkus 2.16. ### Expected behavior Steps to reproduce worked with `stream=2.16` (also don't set `999-SNAPSHOT`), I'd like them to work again or have the change in behavior in https://github.com/quarkusio/quarkus/wiki/Migration-Guide-3.0#kubernetesopenshift. ### Actual behavior Deployment fails ``` ... Caused by: java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors 18:49:09,959 INFO mvn: [error]: Build step io.quarkus.kubernetes.deployment.KubernetesDeployer#deploy threw an exception: io.fabric8.kubernetes.client.KubernetesClientException: Failure executing: POST at: https://edited/apis/rbac.authorization.k8s.io/v1/namespaces/ts-dgbcvqufsb/rolebindings. Message: roles.rbac.authorization.k8s.io "view-secrets" not found. Received status: Status(apiVersion=v1, code=404, details=StatusDetails(causes=[], group=rbac.authorization.k8s.io, kind=roles, name=view-secrets, retryAfterSeconds=null, uid=null, additionalProperties={}), kind=Status, message=roles.rbac.authorization.k8s.io "view-secrets" not found, metadata=ListMeta(_continue=null, remainingItemCount=null, resourceVersion=null, selfLink=null, additionalProperties={}), reason=NotFound, status=Failure, additionalProperties={}). 18:49:09,959 INFO mvn: at io.fabric8.kubernetes.client.KubernetesClientException.copyAsCause(KubernetesClientException.java:238) 18:49:09,959 INFO mvn: at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.waitForResult(OperationSupport.java:546) 18:49:09,959 INFO mvn: at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.handleResponse(OperationSupport.java:566) 18:49:09,960 INFO mvn: at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.handleCreate(OperationSupport.java:350) 18:49:09,960 INFO mvn: at io.fabric8.kubernetes.client.dsl.internal.BaseOperation.handleCreate(BaseOperation.java:707) 18:49:09,960 INFO mvn: at io.fabric8.kubernetes.client.dsl.internal.BaseOperation.handleCreate(BaseOperation.java:93) 18:49:09,960 INFO mvn: at io.fabric8.kubernetes.client.dsl.internal.CreateOnlyResourceOperation.create(CreateOnlyResourceOperation.java:42) 18:49:09,960 INFO mvn: at io.fabric8.kubernetes.client.utils.internal.CreateOrReplaceHelper.createOrReplace(CreateOrReplaceHelper.java:51) 18:49:09,960 INFO mvn: at io.fabric8.kubernetes.client.dsl.internal.BaseOperation.createOrReplace(BaseOperation.java:310) 18:49:09,960 INFO mvn: at io.fabric8.kubernetes.client.dsl.internal.BaseOperation.createOrReplace(BaseOperation.java:93) 18:49:09,960 INFO mvn: at io.fabric8.kubernetes.client.extension.ResourceAdapter.createOrReplace(ResourceAdapter.java:124) 18:49:09,960 INFO mvn: at io.quarkus.kubernetes.deployment.KubernetesDeployer.deployResource(KubernetesDeployer.java:259) 18:49:09,960 INFO mvn: at io.quarkus.kubernetes.deployment.KubernetesDeployer.lambda$deploy$4(KubernetesDeployer.java:219) 18:49:09,960 INFO mvn: at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183) 18:49:09,960 INFO mvn: at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177) 18:49:09,960 INFO mvn: at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655) 18:49:09,960 INFO mvn: at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) 18:49:09,960 INFO mvn: at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) 18:49:09,960 INFO mvn: at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150) 18:49:09,961 INFO mvn: at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173) 18:49:09,961 INFO mvn: at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) 18:49:09,961 INFO mvn: at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497) 18:49:09,961 INFO mvn: at io.quarkus.kubernetes.deployment.KubernetesDeployer.deploy(KubernetesDeployer.java:218) 18:49:09,961 INFO mvn: at io.quarkus.kubernetes.deployment.KubernetesDeployer.deploy(KubernetesDeployer.java:142) 18:49:09,961 INFO mvn: at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 18:49:09,961 INFO mvn: at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 18:49:09,961 INFO mvn: at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 18:49:09,961 INFO mvn: at java.base/java.lang.reflect.Method.invoke(Method.java:566) 18:49:09,961 INFO mvn: at io.quarkus.deployment.ExtensionLoader$3.execute(ExtensionLoader.java:909) 18:49:09,961 INFO mvn: at io.quarkus.builder.BuildContext.run(BuildContext.java:282) 18:49:09,961 INFO mvn: at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) 18:49:09,961 INFO mvn: at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2513) 18:49:09,961 INFO mvn: at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1538) 18:49:09,962 INFO mvn: at java.base/java.lang.Thread.run(Thread.java:829) 18:49:09,962 INFO mvn: at org.jboss.threads.JBossThread.run(JBossThread.java:501) 18:49:09,962 INFO mvn: Caused by: io.fabric8.kubernetes.client.KubernetesClientException: Failure executing: POST at: https://edited/apis/rbac.authorization.k8s.io/v1/namespaces/ts-dgbcvqufsb/rolebindings. Message: roles.rbac.authorization.k8s.io "view-secrets" not found. Received status: Status(apiVersion=v1, code=404, details=StatusDetails(causes=[], group=rbac.authorization.k8s.io, kind=roles, name=view-secrets, retryAfterSeconds=null, uid=null, additionalProperties={}), kind=Status, message=roles.rbac.authorization.k8s.io "view-secrets" not found, metadata=ListMeta(_continue=null, remainingItemCount=null, resourceVersion=null, selfLink=null, additionalProperties={}), reason=NotFound, status=Failure, additionalProperties={}). 18:49:09,962 INFO mvn: at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.requestFailure(OperationSupport.java:701) 18:49:09,962 INFO mvn: at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.requestFailure(OperationSupport.java:681) 18:49:09,962 INFO mvn: at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.assertResponseCode(OperationSupport.java:630) 18:49:09,962 INFO mvn: at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.lambda$handleResponse$0(OperationSupport.java:591) 18:49:09,962 INFO mvn: at java.base/java.util.concurrent.CompletableFuture$UniApply.tryFire(CompletableFuture.java:642) 18:49:09,962 INFO mvn: at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506) 18:49:09,962 INFO mvn: at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2073) 18:49:09,962 INFO mvn: at io.fabric8.kubernetes.client.http.StandardHttpClient.lambda$completeOrCancel$5(StandardHttpClient.java:120) 18:49:09,962 INFO mvn: at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:859) 18:49:09,962 INFO mvn: at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:837) 18:49:09,962 INFO mvn: at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506) 18:49:09,962 INFO mvn: at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2073) 18:49:09,962 INFO mvn: at io.fabric8.kubernetes.client.http.ByteArrayBodyHandler.onBodyDone(ByteArrayBodyHandler.java:52) 18:49:09,962 INFO mvn: at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:859) 18:49:09,962 INFO mvn: at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:837) 18:49:09,962 INFO mvn: at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506) 18:49:09,963 INFO mvn: at java.base/java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:2073) 18:49:09,963 INFO mvn: at io.fabric8.kubernetes.client.vertx.VertxHttpRequest.lambda$null$1(VertxHttpRequest.java:122) 18:49:09,963 INFO mvn: at io.vertx.core.impl.ContextInternal.dispatch(ContextInternal.java:264) 18:49:09,963 INFO mvn: at io.vertx.core.impl.ContextInternal.dispatch(ContextInternal.java:246) 18:49:09,963 INFO mvn: at io.vertx.core.http.impl.HttpEventHandler.handleEnd(HttpEventHandler.java:76) 18:49:09,963 INFO mvn: at io.vertx.core.http.impl.HttpClientResponseImpl.handleEnd(HttpClientResponseImpl.java:250) 18:49:09,963 INFO mvn: at io.vertx.core.http.impl.Http1xClientConnection$StreamImpl.lambda$new$0(Http1xClientConnection.java:398) 18:49:09,963 INFO mvn: at io.vertx.core.streams.impl.InboundBuffer.handleEvent(InboundBuffer.java:239) 18:49:09,963 INFO mvn: at io.vertx.core.streams.impl.InboundBuffer.write(InboundBuffer.java:129) 18:49:09,963 INFO mvn: at io.vertx.core.http.impl.Http1xClientConnection$StreamImpl.handleEnd(Http1xClientConnection.java:645) 18:49:09,963 INFO mvn: at io.vertx.core.impl.EventLoopContext.execute(EventLoopContext.java:76) 18:49:09,963 INFO mvn: at io.vertx.core.impl.ContextBase.execute(ContextBase.java:232) 18:49:09,963 INFO mvn: at io.vertx.core.http.impl.Http1xClientConnection.handleResponseEnd(Http1xClientConnection.java:879) 18:49:09,963 INFO mvn: at io.vertx.core.http.impl.Http1xClientConnection.handleHttpMessage(Http1xClientConnection.java:751) 18:49:09,963 INFO mvn: at io.vertx.core.http.impl.Http1xClientConnection.handleMessage(Http1xClientConnection.java:715) 18:49:09,963 INFO mvn: at io.vertx.core.net.impl.ConnectionBase.read(ConnectionBase.java:157) 18:49:09,963 INFO mvn: at io.vertx.core.net.impl.VertxHandler.channelRead(VertxHandler.java:153) 18:49:09,963 INFO mvn: at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:442) 18:49:09,963 INFO mvn: at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420) 18:49:09,963 INFO mvn: at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412) 18:49:09,963 INFO mvn: at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:436) 18:49:09,964 INFO mvn: at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:346) 18:49:09,964 INFO mvn: at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:318) 18:49:09,964 INFO mvn: at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:251) 18:49:09,964 INFO mvn: at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:442) 18:49:09,964 INFO mvn: at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420) 18:49:09,964 INFO mvn: at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412) 18:49:09,964 INFO mvn: at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1373) 18:49:09,964 INFO mvn: at io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1236) 18:49:09,964 INFO mvn: at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1285) 18:49:09,964 INFO mvn: at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:529) 18:49:09,964 INFO mvn: at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:468) 18:49:09,964 INFO mvn: at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:290) 18:49:09,964 INFO mvn: at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:444) 18:49:09,964 INFO mvn: at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420) 18:49:09,964 INFO mvn: at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412) 18:49:09,964 INFO mvn: at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) 18:49:09,964 INFO mvn: at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:440) 18:49:09,964 INFO mvn: at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420) 18:49:09,964 INFO mvn: at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) 18:49:09,964 INFO mvn: at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166) 18:49:09,964 INFO mvn: at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:788) 18:49:09,965 INFO mvn: at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:724) 18:49:09,965 INFO mvn: at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:650) 18:49:09,965 INFO mvn: at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:562) 18:49:09,965 INFO mvn: at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997) 18:49:09,965 INFO mvn: at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) 18:49:09,965 INFO mvn: at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) 18:49:09,965 INFO mvn: at java.base/java.lang.Thread.run(Thread.java:829) 18:49:09,965 INFO mvn: ... ``` ### How to Reproduce? Steps to reproduce: 1. `oc new-project mvavrik-debug` 2. `quarkus create app secret-reproducer -x openshift,resteasy-reactive,kubernetes-config --stream=3.0` 3. `cd secret-reproducer/` 4. ``` cat <<EOF > ./secret apiVersion: v1 kind: Secret metadata: name: app-config stringData: application.properties: | msg=So Long, and Thanks for All the Fish EOF ``` 5. `oc apply -f secret` 6. `mvn clean verify -Dquarkus.platform.version=999-SNAPSHOT -Dquarkus.platform.group-id=io.quarkus -Dquarkus.kubernetes.deployment-target=openshift -Dquarkus.kubernetes.deploy=true -Dquarkus.kubernetes-client.trust-certs=true -Dquarkus.kubernetes-config.enabled=true -Dquarkus.kubernetes.config.secrets.enabled=true -Dquarkus.kubernetes-config.secrets=app-config -Dquarkus.kubernetes-config.secrets.enabled=true` ### Output of `uname -a` or `ver` Linux ### Output of `java -version` openjdk 17.0.8 ### GraalVM version (if different from Java) OpenJDK Runtime Environment GraalVM CE 22.3 ### Quarkus version or git rev 999-SNAPSHOT ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.6 ### Additional information Tested with OpenShift 4.12 (Kubernetes version v1.25.4+18eadca) and 4.8.
34da5133fd7dd9997d1cc7d52f80bbf81cd27a17
f3d8aafdb59b34be44552a9342e6b144bdc554b7
https://github.com/quarkusio/quarkus/compare/34da5133fd7dd9997d1cc7d52f80bbf81cd27a17...f3d8aafdb59b34be44552a9342e6b144bdc554b7
diff --git a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddClusterRoleResourceDecorator.java b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddClusterRoleResourceDecorator.java index 2074e4fd122..d1309151483 100644 --- a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddClusterRoleResourceDecorator.java +++ b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddClusterRoleResourceDecorator.java @@ -7,6 +7,7 @@ import java.util.List; import java.util.Map; +import io.dekorate.kubernetes.decorator.Decorator; import io.dekorate.kubernetes.decorator.ResourceProvidingDecorator; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; import io.fabric8.kubernetes.api.model.ObjectMeta; @@ -45,4 +46,9 @@ public void visit(KubernetesListBuilder list) { .endMetadata() .withRules(rules)); } + + @Override + public Class<? extends Decorator>[] before() { + return new Class[] { AddRoleBindingResourceDecorator.class }; + } } diff --git a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddRoleResourceDecorator.java b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddRoleResourceDecorator.java index 752efe7fd2b..632b3bca7bc 100644 --- a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddRoleResourceDecorator.java +++ b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddRoleResourceDecorator.java @@ -7,6 +7,7 @@ import java.util.List; import java.util.Map; +import io.dekorate.kubernetes.decorator.Decorator; import io.dekorate.kubernetes.decorator.ResourceProvidingDecorator; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; import io.fabric8.kubernetes.api.model.ObjectMeta; @@ -48,4 +49,9 @@ public void visit(KubernetesListBuilder list) { .endMetadata() .withRules(rules)); } + + @Override + public Class<? extends Decorator>[] before() { + return new Class[] { AddRoleBindingResourceDecorator.class }; + } } diff --git a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddServiceAccountResourceDecorator.java b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddServiceAccountResourceDecorator.java index b8fb1f0eb8d..f6f90801b36 100644 --- a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddServiceAccountResourceDecorator.java +++ b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddServiceAccountResourceDecorator.java @@ -5,6 +5,7 @@ import java.util.HashMap; import java.util.Map; +import io.dekorate.kubernetes.decorator.Decorator; import io.dekorate.kubernetes.decorator.ResourceProvidingDecorator; import io.fabric8.kubernetes.api.model.KubernetesListBuilder; import io.fabric8.kubernetes.api.model.ObjectMeta; @@ -43,4 +44,9 @@ public void visit(KubernetesListBuilder list) { .endMetadata() .endServiceAccountItem(); } + + @Override + public Class<? extends Decorator>[] before() { + return new Class[] { AddRoleBindingResourceDecorator.class }; + } } diff --git a/integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/KubernetesWithRbacFullTest.java b/integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/KubernetesWithRbacFullTest.java index 80ee1df0689..3ff3de62fb5 100644 --- a/integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/KubernetesWithRbacFullTest.java +++ b/integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/KubernetesWithRbacFullTest.java @@ -5,9 +5,12 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; +import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -40,9 +43,16 @@ public class KubernetesWithRbacFullTest { @Test public void assertGeneratedResources() throws IOException { - final Path kubernetesDir = prodModeTestResults.getBuildDir().resolve("kubernetes"); - List<HasMetadata> kubernetesList = DeserializationUtil - .deserializeAsList(kubernetesDir.resolve("kubernetes.yml")); + final Path kubernetesFile = prodModeTestResults.getBuildDir().resolve("kubernetes").resolve("kubernetes.yml"); + + // ensure rbac resources are generated in order: having the RoleBinding resource at the end: + String kubernetesFileContent = Files.readString(kubernetesFile); + int lastIndexOfRoleRefKind = lastIndexOfKind(kubernetesFileContent, "Role", "ClusterRole", "ServiceAccount"); + int firstIndexOfRoleBinding = kubernetesFileContent.indexOf("kind: RoleBinding"); + assertTrue(lastIndexOfRoleRefKind < firstIndexOfRoleBinding, "RoleBinding resource is created before " + + "the Role/ClusterRole/ServiceAccount resource!"); + + List<HasMetadata> kubernetesList = DeserializationUtil.deserializeAsList(kubernetesFile); Deployment deployment = getDeploymentByName(kubernetesList, APP_NAME); assertEquals(APP_NAMESPACE, deployment.getMetadata().getNamespace()); @@ -84,6 +94,21 @@ public void assertGeneratedResources() throws IOException { assertEquals("projectc", subject.getNamespace()); } + private int lastIndexOfKind(String content, String... kinds) { + int index = Integer.MIN_VALUE; + for (String kind : kinds) { + Matcher matcher = Pattern.compile("(?m)^kind: " + kind).matcher(content); + if (matcher.find()) { + int lastIndexOfKind = matcher.end(); + if (lastIndexOfKind > index) { + index = lastIndexOfKind; + } + } + } + + return index; + } + private Deployment getDeploymentByName(List<HasMetadata> kubernetesList, String name) { return getResourceByName(kubernetesList, Deployment.class, name); }
['extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddClusterRoleResourceDecorator.java', 'integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/KubernetesWithRbacFullTest.java', 'extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddRoleResourceDecorator.java', 'extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/AddServiceAccountResourceDecorator.java']
{'.java': 4}
4
4
0
0
4
26,080,822
5,145,971
664,134
6,155
594
129
18
3
15,548
827
4,243
164
3
2
1970-01-01T00:28:00
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,228
quarkusio/quarkus/32207/32135
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/32135
https://github.com/quarkusio/quarkus/pull/32207
https://github.com/quarkusio/quarkus/pull/32207
1
fix
Quarkus-openshift fails to properly deploy applications which use management interface
### Describe the bug I have an application, which uses separate management interface[1] and deployed on Openshift via quarkus-openshift extension[2]. Both main and management interfaces are not accessible after deployment. [1] https://github.com/quarkusio/quarkus/pull/30506 [2] https://quarkus.io/guides/deploying-to-openshift ### Expected behavior Quarkus openshift extension should deploy an application is completely working state. ### Actual behavior see below ### How to Reproduce? 1. Clone: `git clone git@github.com:fedinskiy/reproducer.git -b openshift-extension-management` 2. Create new openshift project `oc new-project fvd-test-management` 3. Deploy the app according to manual: `mvn clean install -Dquarkus.kubernetes.deploy=true -Dquarkus.openshift.route.expose=true -Dquarkus.kubernetes-client.trust-certs=true` Log contains something like `[INFO] [io.quarkus.kubernetes.deployment.KubernetesDeployer] The deployed application can be accessed at: http://openshift-quickstart-fvd-test-management.apps.ocp4-12.rest.of.url` 4. Check the app ``` [fedinskiy@localhost reproducer]$ curl -v http://openshift-quickstart-fvd-test-management.apps.ocp4-12 <omitted for brevity> > User-Agent: curl/7.85.0 < HTTP/1.0 503 Service Unavailable ``` For comparison: 1. `oc new-project fvd-test-old` 2. `echo "" > src/main/resources/application.properties` 3. `mvn clean install -Dquarkus.kubernetes.deploy=true -Dquarkus.openshift.route.expose=true -Dquarkus.kubernetes-client.trust-certs=true` 4. The application can be accessed: ` curl http://openshift-quickstart-fvd-test-old.apps.ocp4-12<omitted>` ### Output of `uname -a` or `ver` 6.0.18-300.fc37.x86_64 ### Output of `java -version` 17.0.5, vendor: GraalVM Community ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 3.0.0.Beta1 ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.6 (84538c9988a25aec085021c365c560670ad80f63) ### Additional information ``` $ oc version Client Version: 4.11.0-202208020706.p0.g7075089.assembly.stream-7075089 Kustomize Version: v4.5.4 Kubernetes Version: v1.25.4+18eadca ```
2d2e1cf4d3c15c250fdd960f868371757b5f77fe
7765b20d8c3390f4ba12b17647edfec82a3a4ba7
https://github.com/quarkusio/quarkus/compare/2d2e1cf4d3c15c250fdd960f868371757b5f77fe...7765b20d8c3390f4ba12b17647edfec82a3a4ba7
diff --git a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/ApplyHttpGetActionPortDecorator.java b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/ApplyHttpGetActionPortDecorator.java index 1afe6e7aa81..75c08c859ed 100644 --- a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/ApplyHttpGetActionPortDecorator.java +++ b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/ApplyHttpGetActionPortDecorator.java @@ -6,8 +6,7 @@ import java.util.Map; import java.util.Optional; -import io.dekorate.kubernetes.decorator.AddLivenessProbeDecorator; -import io.dekorate.kubernetes.decorator.AddReadinessProbeDecorator; +import io.dekorate.kubernetes.decorator.AbstractAddProbeDecorator; import io.dekorate.kubernetes.decorator.AddSidecarDecorator; import io.dekorate.kubernetes.decorator.Decorator; import io.dekorate.kubernetes.decorator.ResourceProvidingDecorator; @@ -106,7 +105,6 @@ public void visit(HTTPGetActionFluent<?> action) { @Override public Class<? extends Decorator>[] after() { - return new Class[] { ResourceProvidingDecorator.class, AddSidecarDecorator.class, - AddLivenessProbeDecorator.class, AddReadinessProbeDecorator.class }; + return new Class[] { ResourceProvidingDecorator.class, AddSidecarDecorator.class, AbstractAddProbeDecorator.class }; } } diff --git a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/Constants.java b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/Constants.java index 47aa05a3db0..101d3a5ff7a 100644 --- a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/Constants.java +++ b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/Constants.java @@ -59,6 +59,10 @@ public final class Constants { public static final int MIN_NODE_PORT_VALUE = 30000; public static final int MAX_NODE_PORT_VALUE = 31999; + public static final String LIVENESS_PROBE = "livenessProbe"; + public static final String READINESS_PROBE = "readinessProbe"; + public static final String STARTUP_PROBE = "startupProbe"; + private Constants() { } } diff --git a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/DevClusterHelper.java b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/DevClusterHelper.java index 3e837624d5e..77bc359390b 100644 --- a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/DevClusterHelper.java +++ b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/DevClusterHelper.java @@ -2,10 +2,13 @@ package io.quarkus.kubernetes.deployment; import static io.quarkus.kubernetes.deployment.Constants.KUBERNETES; +import static io.quarkus.kubernetes.deployment.Constants.LIVENESS_PROBE; import static io.quarkus.kubernetes.deployment.Constants.MAX_NODE_PORT_VALUE; import static io.quarkus.kubernetes.deployment.Constants.MAX_PORT_NUMBER; import static io.quarkus.kubernetes.deployment.Constants.MIN_NODE_PORT_VALUE; import static io.quarkus.kubernetes.deployment.Constants.MIN_PORT_NUMBER; +import static io.quarkus.kubernetes.deployment.Constants.READINESS_PROBE; +import static io.quarkus.kubernetes.deployment.Constants.STARTUP_PROBE; import java.math.BigInteger; import java.nio.charset.StandardCharsets; @@ -128,15 +131,15 @@ public static List<DecoratorBuildItem> createDecorators(String clusterKind, //Probe port handling result.add( - KubernetesCommonHelper.createProbeHttpPortDecorator(name, clusterKind, "livenessProbe", config.livenessProbe, + KubernetesCommonHelper.createProbeHttpPortDecorator(name, clusterKind, LIVENESS_PROBE, config.livenessProbe, portName, ports)); result.add( - KubernetesCommonHelper.createProbeHttpPortDecorator(name, clusterKind, "readinessProbe", config.readinessProbe, + KubernetesCommonHelper.createProbeHttpPortDecorator(name, clusterKind, READINESS_PROBE, config.readinessProbe, portName, ports)); result.add( - KubernetesCommonHelper.createProbeHttpPortDecorator(name, clusterKind, "startupProbe", config.startupProbe, + KubernetesCommonHelper.createProbeHttpPortDecorator(name, clusterKind, STARTUP_PROBE, config.startupProbe, portName, ports)); diff --git a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/OpenshiftProcessor.java b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/OpenshiftProcessor.java index 5bbb03e9828..199b54be052 100644 --- a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/OpenshiftProcessor.java +++ b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/OpenshiftProcessor.java @@ -2,10 +2,13 @@ package io.quarkus.kubernetes.deployment; import static io.quarkus.kubernetes.deployment.Constants.DEFAULT_S2I_IMAGE_NAME; +import static io.quarkus.kubernetes.deployment.Constants.LIVENESS_PROBE; import static io.quarkus.kubernetes.deployment.Constants.OPENSHIFT; import static io.quarkus.kubernetes.deployment.Constants.OPENSHIFT_APP_RUNTIME; import static io.quarkus.kubernetes.deployment.Constants.QUARKUS; +import static io.quarkus.kubernetes.deployment.Constants.READINESS_PROBE; import static io.quarkus.kubernetes.deployment.Constants.ROUTE; +import static io.quarkus.kubernetes.deployment.Constants.STARTUP_PROBE; import static io.quarkus.kubernetes.deployment.OpenshiftConfig.OpenshiftFlavor.v3; import static io.quarkus.kubernetes.spi.KubernetesDeploymentTargetBuildItem.DEFAULT_PRIORITY; @@ -310,15 +313,15 @@ public List<DecoratorBuildItem> createDecorators(ApplicationInfoBuildItem applic } // Probe port handling - result.add(KubernetesCommonHelper.createProbeHttpPortDecorator(name, OPENSHIFT, "livenssProbe", config.livenessProbe, + result.add(KubernetesCommonHelper.createProbeHttpPortDecorator(name, OPENSHIFT, LIVENESS_PROBE, config.livenessProbe, portName, ports)); result.add( - KubernetesCommonHelper.createProbeHttpPortDecorator(name, OPENSHIFT, "readinessProbe", config.readinessProbe, + KubernetesCommonHelper.createProbeHttpPortDecorator(name, OPENSHIFT, READINESS_PROBE, config.readinessProbe, portName, ports)); result.add( - KubernetesCommonHelper.createProbeHttpPortDecorator(name, OPENSHIFT, "startupProbe", config.startupProbe, + KubernetesCommonHelper.createProbeHttpPortDecorator(name, OPENSHIFT, STARTUP_PROBE, config.startupProbe, portName, ports)); diff --git a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/VanillaKubernetesProcessor.java b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/VanillaKubernetesProcessor.java index 031d4a9e953..ca88fe0eff3 100644 --- a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/VanillaKubernetesProcessor.java +++ b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/VanillaKubernetesProcessor.java @@ -5,6 +5,9 @@ import static io.quarkus.kubernetes.deployment.Constants.DEPLOYMENT_VERSION; import static io.quarkus.kubernetes.deployment.Constants.INGRESS; import static io.quarkus.kubernetes.deployment.Constants.KUBERNETES; +import static io.quarkus.kubernetes.deployment.Constants.LIVENESS_PROBE; +import static io.quarkus.kubernetes.deployment.Constants.READINESS_PROBE; +import static io.quarkus.kubernetes.deployment.Constants.STARTUP_PROBE; import static io.quarkus.kubernetes.spi.KubernetesDeploymentTargetBuildItem.VANILLA_KUBERNETES_PRIORITY; import java.util.ArrayList; @@ -252,15 +255,15 @@ public List<DecoratorBuildItem> createDecorators(ApplicationInfoBuildItem applic // Probe port handling result.add( - KubernetesCommonHelper.createProbeHttpPortDecorator(name, KUBERNETES, "livenessProbe", config.livenessProbe, + KubernetesCommonHelper.createProbeHttpPortDecorator(name, KUBERNETES, LIVENESS_PROBE, config.livenessProbe, portName, ports)); result.add( - KubernetesCommonHelper.createProbeHttpPortDecorator(name, KUBERNETES, "readinessProbe", config.readinessProbe, + KubernetesCommonHelper.createProbeHttpPortDecorator(name, KUBERNETES, READINESS_PROBE, config.readinessProbe, portName, ports)); result.add( - KubernetesCommonHelper.createProbeHttpPortDecorator(name, KUBERNETES, "startupProbe", config.startupProbe, + KubernetesCommonHelper.createProbeHttpPortDecorator(name, KUBERNETES, STARTUP_PROBE, config.startupProbe, portName, ports));
['extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/DevClusterHelper.java', 'extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/Constants.java', 'extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/VanillaKubernetesProcessor.java', 'extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/OpenshiftProcessor.java', 'extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/ApplyHttpGetActionPortDecorator.java']
{'.java': 5}
5
5
0
0
5
26,080,095
5,145,799
664,123
6,155
3,633
750
37
5
2,190
213
626
66
5
2
1970-01-01T00:28:00
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,229
quarkusio/quarkus/32199/32194
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/32194
https://github.com/quarkusio/quarkus/pull/32199
https://github.com/quarkusio/quarkus/pull/32199
1
fixes
@RestCookie/@RestHeader (and relative @*Param) applied to Temporal parameter lead to deployment failure
### Describe the bug ```java @Path("/hello") public class GreetingResource { @Inject ObjectMapper mapper; @Path("{path}") @GET @Produces(MediaType.APPLICATION_JSON) public String hello(@RestQuery("query") Instant query, @RestPath("path") Instant path, @RestHeader("header") Instant header, @RestCookie("cookie") Instant cookie) throws IOException {} } ``` header and cookie extracted as `java.time.temporal.*` produce and invalid build ```posh Build step io.quarkus.resteasy.reactive.server.deployment.ResteasyReactiveProcessor#setupEndpoints threw an exception: java.lang.RuntimeException: java.lang.RuntimeException: Failed to process method 'org.acme.GreetingResource#hello' at org.jboss.resteasy.reactive.common.processor.EndpointIndexer.createEndpoints(EndpointIndexer.java:323) at io.quarkus.resteasy.reactive.server.deployment.ResteasyReactiveProcessor.setupEndpoints(ResteasyReactiveProcessor.java:633) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) at io.quarkus.deployment.ExtensionLoader$3.execute(ExtensionLoader.java:909) at io.quarkus.builder.BuildContext.run(BuildContext.java:[281](https://github.com/luca-bassoricci/code-with-quarkus/actions/runs/4544958243/jobs/8011773735#step:4:282)) at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478) at java.base/java.lang.Thread.run(Thread.java:833) at org.jboss.threads.JBossThread.run(JBossThread.java:501) Caused by: java.lang.RuntimeException: Failed to process method 'org.acme.GreetingResource#hello' at org.jboss.resteasy.reactive.common.processor.EndpointIndexer.createResourceMethod(EndpointIndexer.java:765) at org.jboss.resteasy.reactive.common.processor.EndpointIndexer.createEndpoints(EndpointIndexer.java:412) at org.jboss.resteasy.reactive.common.processor.EndpointIndexer.createEndpoints(EndpointIndexer.java:[290](https://github.com/luca-bassoricci/code-with-quarkus/actions/runs/4544958243/jobs/8011773735#step:4:291)) ... 12 more Caused by: java.lang.RuntimeException: Could not create converter for java.time.Instant for method java.lang.String hello(java.time.Instant query, java.time.Instant path, java.time.Instant header, java.time.Instant cookie) throws java.io.IOException on class org.acme.GreetingResource of type HEADER at org.jboss.resteasy.reactive.server.processor.ServerEndpointIndexer.handleOtherParam(ServerEndpointIndexer.java:367) at org.jboss.resteasy.reactive.server.processor.ServerEndpointIndexer.handleOtherParam(ServerEndpointIndexer.java:96) at org.jboss.resteasy.reactive.common.processor.EndpointIndexer.extractParameterInfo(EndpointIndexer.java:1407) at org.jboss.resteasy.reactive.common.processor.EndpointIndexer.createResourceMethod(EndpointIndexer.java:592) ... 14 more Caused by: java.lang.RuntimeException: Failed to find converter for java.time.Instant at org.jboss.resteasy.reactive.server.processor.generation.converters.GeneratedConverterIndexerExtension.extractConverterImpl(GeneratedConverterIndexerExtension.java:106) at org.jboss.resteasy.reactive.server.processor.ServerEndpointIndexer.extractConverter(ServerEndpointIndexer.java:564) at org.jboss.resteasy.reactive.server.processor.ServerEndpointIndexer.handleOtherParam(ServerEndpointIndexer.java:363) ... 17 more ``` ### Expected behavior A valid build with data extracted from header/cookie as Temporal value. ### Actual behavior Invalid build ### How to Reproduce? Reproducer at https://github.com/luca-bassoricci/code-with-quarkus; just build to reproduce the error ### Output of `uname -a` or `ver` Windows 11 ### Output of `java -version` temurin 17 ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.16.5.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
34da5133fd7dd9997d1cc7d52f80bbf81cd27a17
335e4924d8a01809ba1b0b6bb25ca29805827342
https://github.com/quarkusio/quarkus/compare/34da5133fd7dd9997d1cc7d52f80bbf81cd27a17...335e4924d8a01809ba1b0b6bb25ca29805827342
diff --git a/independent-projects/resteasy-reactive/common/processor/src/main/java/org/jboss/resteasy/reactive/common/processor/EndpointIndexer.java b/independent-projects/resteasy-reactive/common/processor/src/main/java/org/jboss/resteasy/reactive/common/processor/EndpointIndexer.java index 3ab31b32824..05b7f10dc15 100644 --- a/independent-projects/resteasy-reactive/common/processor/src/main/java/org/jboss/resteasy/reactive/common/processor/EndpointIndexer.java +++ b/independent-projects/resteasy-reactive/common/processor/src/main/java/org/jboss/resteasy/reactive/common/processor/EndpointIndexer.java @@ -1382,7 +1382,8 @@ && isParameterContainerType(paramType.asClassType())) { handlePathSegmentParam(builder); typeHandled = true; } else if (SUPPORT_TEMPORAL_PARAMS.contains(paramType.name()) - && (type == ParameterType.PATH || type == ParameterType.QUERY || type == ParameterType.FORM)) { + && (type == ParameterType.PATH || type == ParameterType.QUERY || type == ParameterType.FORM + || type == ParameterType.COOKIE || type == ParameterType.HEADER)) { elementType = paramType.name().toString(); handleTemporalParam(builder, paramType.name(), anns, currentMethodInfo); typeHandled = true; diff --git a/independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/InstantParamTest.java b/independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/InstantParamTest.java index 220a56196dd..c6fe44fe32f 100644 --- a/independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/InstantParamTest.java +++ b/independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/InstantParamTest.java @@ -4,9 +4,14 @@ import java.time.Instant; import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import org.hamcrest.Matchers; +import org.jboss.resteasy.reactive.RestCookie; +import org.jboss.resteasy.reactive.RestForm; +import org.jboss.resteasy.reactive.RestHeader; +import org.jboss.resteasy.reactive.RestPath; import org.jboss.resteasy.reactive.RestQuery; import org.jboss.resteasy.reactive.server.vertx.test.framework.ResteasyReactiveUnitTest; import org.jboss.shrinkwrap.api.ShrinkWrap; @@ -24,11 +29,37 @@ public class InstantParamTest { .addClasses(HelloResource.class)); @Test - public void test() { + public void instantAsQueryParam() { RestAssured.get("/hello?instant=1984-08-08T01:02:03Z") .then().statusCode(200).body(Matchers.equalTo("hello#1984-08-09T01:02:03Z")); } + @Test + public void instantAsPathParam() { + RestAssured.get("/hello/1984-08-08T01:02:03Z") + .then().statusCode(200).body(Matchers.equalTo("hello@1984-08-09T01:02:03Z")); + } + + @Test + public void instantAsFormParam() { + RestAssured.given().formParam("instant", "1984-08-08T01:02:03Z").post("/hello") + .then().statusCode(200).body(Matchers.equalTo("hello:1984-08-09T01:02:03Z")); + } + + @Test + public void instantAsHeader() { + RestAssured.with().header("instant", "1984-08-08T01:02:03Z") + .get("/hello/header") + .then().statusCode(200).body(Matchers.equalTo("hello=1984-08-09T01:02:03Z")); + } + + @Test + public void instantAsCookie() { + RestAssured.with().cookie("instant", "1984-08-08T01:02:03Z") + .get("/hello/cookie") + .then().statusCode(200).body(Matchers.equalTo("hello/1984-08-09T01:02:03Z")); + } + @Path("hello") public static class HelloResource { @@ -36,6 +67,29 @@ public static class HelloResource { public String helloQuery(@RestQuery Instant instant) { return "hello#" + instant.plus(Duration.ofDays(1)).toString(); } + + @GET + @Path("{instant}") + public String helloPath(@RestPath Instant instant) { + return "hello@" + instant.plus(Duration.ofDays(1)).toString(); + } + + @POST + public String helloForm(@RestForm Instant instant) { + return "hello:" + instant.plus(Duration.ofDays(1)).toString(); + } + + @GET + @Path("cookie") + public String helloCookie(@RestCookie Instant instant) { + return "hello/" + instant.plus(Duration.ofDays(1)).toString(); + } + + @GET + @Path("header") + public String helloHeader(@RestHeader Instant instant) { + return "hello=" + instant.plus(Duration.ofDays(1)).toString(); + } } } diff --git a/independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/LocalDateParamTest.java b/independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/LocalDateParamTest.java index f3b59f8d673..c98a886a8e8 100644 --- a/independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/LocalDateParamTest.java +++ b/independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/LocalDateParamTest.java @@ -3,8 +3,10 @@ import java.time.LocalDate; import java.time.format.DateTimeFormatter; +import jakarta.ws.rs.CookieParam; import jakarta.ws.rs.FormParam; import jakarta.ws.rs.GET; +import jakarta.ws.rs.HeaderParam; import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; @@ -43,6 +45,20 @@ public void localDateAsFormParam() { .then().statusCode(200).body(Matchers.equalTo("hello:1995-09-22")); } + @Test + public void localDateAsHeader() { + RestAssured.with().header("date", "08-08-1984") + .get("/hello/header") + .then().statusCode(200).body(Matchers.equalTo("hello=1984-08-08")); + } + + @Test + public void localDateAsCookie() { + RestAssured.with().cookie("date", "08-08-1984") + .get("/hello/cookie") + .then().statusCode(200).body(Matchers.equalTo("hello/1984-08-08")); + } + @Path("hello") public static class HelloResource { @@ -62,6 +78,20 @@ public String helloForm( @FormParam("date") @DateFormat(dateTimeFormatterProvider = CustomDateTimeFormatterProvider.class) LocalDate date) { return "hello:" + date; } + + @GET + @Path("cookie") + public String helloCookie( + @CookieParam("date") @DateFormat(pattern = "dd-MM-yyyy") LocalDate date) { + return "hello/" + date; + } + + @GET + @Path("header") + public String helloHeader( + @HeaderParam("date") @DateFormat(pattern = "dd-MM-yyyy") LocalDate date) { + return "hello=" + date; + } } public static class CustomDateTimeFormatterProvider implements DateFormat.DateTimeFormatterProvider { diff --git a/independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/LocalDateTimeParamTest.java b/independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/LocalDateTimeParamTest.java index d69a18a11d5..7c4e9cb8e84 100644 --- a/independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/LocalDateTimeParamTest.java +++ b/independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/LocalDateTimeParamTest.java @@ -11,6 +11,8 @@ import org.hamcrest.Matchers; import org.jboss.resteasy.reactive.DateFormat; +import org.jboss.resteasy.reactive.RestCookie; +import org.jboss.resteasy.reactive.RestHeader; import org.jboss.resteasy.reactive.RestPath; import org.jboss.resteasy.reactive.RestQuery; import org.jboss.resteasy.reactive.server.vertx.test.framework.ResteasyReactiveUnitTest; @@ -55,6 +57,20 @@ public void localDateTimeAsFormParam() { .then().statusCode(200).body(Matchers.equalTo("hello:22")); } + @Test + public void localDateTimeAsHeader() { + RestAssured.with().header("date", "1984-08-08 01:02:03") + .get("/hello/header") + .then().statusCode(200).body(Matchers.equalTo("hello=1984-08-08T01:02:03")); + } + + @Test + public void localDateTimeAsCookie() { + RestAssured.with().cookie("date", "1984-08-08 01:02:03") + .get("/hello/cookie") + .then().statusCode(200).body(Matchers.equalTo("hello/1984-08-08T01:02:03")); + } + @Path("hello") public static class HelloResource { @@ -80,6 +96,18 @@ public String helloForm( @FormParam("date") @DateFormat(dateTimeFormatterProvider = CustomDateTimeFormatterProvider.class) LocalDateTime date) { return "hello:" + date.getDayOfMonth(); } + + @Path("cookie") + @GET + public String helloCookie(@RestCookie @DateFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime date) { + return "hello/" + date; + } + + @Path("header") + @GET + public String helloHeader(@RestHeader @DateFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime date) { + return "hello=" + date; + } } public static class CustomDateTimeFormatterProvider implements DateFormat.DateTimeFormatterProvider {
['independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/InstantParamTest.java', 'independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/LocalDateParamTest.java', 'independent-projects/resteasy-reactive/common/processor/src/main/java/org/jboss/resteasy/reactive/common/processor/EndpointIndexer.java', 'independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/LocalDateTimeParamTest.java']
{'.java': 4}
4
4
0
0
4
26,080,822
5,145,971
664,134
6,155
314
66
3
1
4,425
243
1,024
87
3
2
1970-01-01T00:28:00
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,230
quarkusio/quarkus/32110/32037
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/32037
https://github.com/quarkusio/quarkus/pull/32110
https://github.com/quarkusio/quarkus/pull/32110
1
fixes
Set-Cookie Header is Split when using OIDC together with AWS Lambda
### Describe the bug I think I have a similar problem to #25580. I am trying to use the quarkus-oidc extension together with an AWS Lambda deployment using quarkus-amazon-lambda-http. When I remove the quarkus-amazon-lambda-http dependency from the project, everything works fine. However when it is included in the dependencies so the Mock Lambda Event Server is used in dev mode, the q_auth-Cookie breaks (in two parts). This is part of the headers that Quarkus responds with: ``` < set-cookie: q_auth=6b6a7588-802f-49ea-a276-64e6bac263d1|/auth/authenticateAndRedirect?url=http%3A%2F%2Flocalhost%3A3000%2F; Max-Age=1800; Expires=Wed < set-cookie: 22 Mar 2023 13:44:01 GMT; Path=/; HTTPOnly ``` As you can see, the comma that is used within the expiration value now is interpreted by the AWS Lambda Mock Server (and probably also the real one) as the separating character between two header values. ### Expected behavior _No response_ ### Actual behavior _No response_ ### How to Reproduce? Steps to reproduce: 1. Go to https://code.quarkus.io, select "AWS Lambda HTTP" as well as "OpenID Connect" and download and extract the ZIP 2. Change maven.compiler.release to 11 (probably not necessary, I just did not have the required java version installed) 3. Add the following to the `application.properties`: ``` quarkus.oidc.application-type=web_app # Enforce OIDC usage for all paths quarkus.http.auth.permission.authenticated.paths=/* quarkus.http.auth.permission.authenticated.policy=authenticated ``` 4. Run `./mvnw quarkus:dev` 5. Execute `curl localhost:8080 -v` Now you can see two set-cookie headers, of which at least the second one looks broken ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_ (edited to add missing reproduction step)
125f884d2e755d143003381cad2c6b3deebf8d51
736ba35acdebace0bdc6395e9147c42e3bdebbf1
https://github.com/quarkusio/quarkus/compare/125f884d2e755d143003381cad2c6b3deebf8d51...736ba35acdebace0bdc6395e9147c42e3bdebbf1
diff --git a/extensions/amazon-lambda-http/http-event-server/src/main/java/io/quarkus/amazon/lambda/runtime/MockHttpEventServer.java b/extensions/amazon-lambda-http/http-event-server/src/main/java/io/quarkus/amazon/lambda/runtime/MockHttpEventServer.java index e7b438422ea..69fe6e67955 100644 --- a/extensions/amazon-lambda-http/http-event-server/src/main/java/io/quarkus/amazon/lambda/runtime/MockHttpEventServer.java +++ b/extensions/amazon-lambda-http/http-event-server/src/main/java/io/quarkus/amazon/lambda/runtime/MockHttpEventServer.java @@ -128,6 +128,11 @@ public void processResponse(RoutingContext ctx, RoutingContext pending, Buffer b } } } + if (res.getCookies() != null) { + for (String cookie : res.getCookies()) { + response.headers().add("set-cookie", cookie); + } + } response.setStatusCode(res.getStatusCode()); String body = res.getBody(); if (body != null) { diff --git a/extensions/amazon-lambda-http/runtime/src/main/java/io/quarkus/amazon/lambda/http/LambdaHttpHandler.java b/extensions/amazon-lambda-http/runtime/src/main/java/io/quarkus/amazon/lambda/http/LambdaHttpHandler.java index c7c9b7f1092..8b5c2654937 100644 --- a/extensions/amazon-lambda-http/runtime/src/main/java/io/quarkus/amazon/lambda/http/LambdaHttpHandler.java +++ b/extensions/amazon-lambda-http/runtime/src/main/java/io/quarkus/amazon/lambda/http/LambdaHttpHandler.java @@ -108,6 +108,11 @@ public void handleMessage(Object msg) { if (allForName == null || allForName.isEmpty()) { continue; } + // Handle cookies separately to preserve commas in the header values + if ("set-cookie".equals(name)) { + responseBuilder.setCookies(allForName); + continue; + } final StringBuilder sb = new StringBuilder(); for (Iterator<String> valueIterator = allForName.iterator(); valueIterator.hasNext();) { sb.append(valueIterator.next());
['extensions/amazon-lambda-http/runtime/src/main/java/io/quarkus/amazon/lambda/http/LambdaHttpHandler.java', 'extensions/amazon-lambda-http/http-event-server/src/main/java/io/quarkus/amazon/lambda/runtime/MockHttpEventServer.java']
{'.java': 2}
2
2
0
0
2
25,888,282
5,106,508
658,880
6,087
509
74
10
2
2,103
283
533
63
1
2
1970-01-01T00:27:59
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,232
quarkusio/quarkus/32093/32079
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/32079
https://github.com/quarkusio/quarkus/pull/32093
https://github.com/quarkusio/quarkus/pull/32093
1
fix
Quarkus JaCoCo extension fails to start Gradle daemon
### Describe the bug The `io.quarkus:quarkus-jacoco` extension fails to execute when run in an Azure DevOps pipeline using the Gradle wrapper because it is unable to start the Gradle daemon in this environment: ``` ... Caused by: org.gradle.api.GradleException: Could not start Gradle daemon. Caused by: java.lang.UnsupportedOperationException: Cannot convert relative path ?/.gradle/daemon/7.5.1 to an absolute file. ``` Running `./gradlew build` locally works without any issues and produces the expected code coverage reports, running the same build command in our CI environment fails. ### Expected behavior The Quarkus JaCoCo extension is able to create a code coverage report in our CI environment as well. ### Actual behavior Running `./gradlew build` fails with the following exception: ``` ... java.lang.RuntimeException: java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors [error]: Build step io.quarkus.jacoco.deployment.JacocoProcessor#transformerBuildItem threw an exception: org.gradle.tooling.GradleConnectionException: Could not fetch model of type 'ApplicationModel' using connection to Gradle distribution 'https://services.gradle.org/distributions/gradle-7.5.1-bin.zip'. Caused by: org.gradle.api.GradleException: Could not start Gradle daemon. Caused by: java.lang.UnsupportedOperationException: Cannot convert relative path ?/.gradle/daemon/7.5.1 to an absolute file. ``` ### How to Reproduce? Add the Quarkus JaCoCo extension to a project und execute `./gradlew build` in an Azure DevOps pipeline. ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` openjdk version "17.0.6" 2023-01-17 LTS OpenJDK Runtime Environment SapMachine (build 17.0.6+0-LTS) OpenJDK 64-Bit Server VM SapMachine (build 17.0.6+0-LTS, mixed mode, sharing) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.16.5.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Gradle 7.5.1 Build time: 2022-08-05 21:17:56 UTC Revision: d1daa0cbf1a0103000b71484e1dbfe096e095918 ### Additional information Content of `gradle.properties` file: ``` quarkusPlatformGroupId=io.quarkus.platform quarkusPlatformArtifactId=quarkus-bom quarkusPlatformVersion=2.16.5.Final quarkusPluginId=io.quarkus quarkusPluginVersion=2.16.5.Final version=1.0.0 ```
5d57b2782adc96cad16367ecd7f0b28398ce66f4
be495a101191bc58b7ffbe0ba5be67d3a0bc9716
https://github.com/quarkusio/quarkus/compare/5d57b2782adc96cad16367ecd7f0b28398ce66f4...be495a101191bc58b7ffbe0ba5be67d3a0bc9716
diff --git a/test-framework/jacoco/deployment/src/main/java/io/quarkus/jacoco/deployment/JacocoProcessor.java b/test-framework/jacoco/deployment/src/main/java/io/quarkus/jacoco/deployment/JacocoProcessor.java index be25c4ca054..c7273df4b8f 100644 --- a/test-framework/jacoco/deployment/src/main/java/io/quarkus/jacoco/deployment/JacocoProcessor.java +++ b/test-framework/jacoco/deployment/src/main/java/io/quarkus/jacoco/deployment/JacocoProcessor.java @@ -16,7 +16,6 @@ import org.jboss.jandex.ClassInfo; import io.quarkus.bootstrap.model.ApplicationModel; -import io.quarkus.bootstrap.utils.BuildToolHelper; import io.quarkus.bootstrap.workspace.SourceDir; import io.quarkus.deployment.ApplicationArchive; import io.quarkus.deployment.IsTest; @@ -105,17 +104,7 @@ public byte[] apply(String className, byte[] bytes) { info.classFiles = classes; Set<String> sources = new HashSet<>(); - ApplicationModel model; - if (BuildToolHelper.isMavenProject(targetdir.toPath())) { - model = curateOutcomeBuildItem.getApplicationModel(); - } else if (BuildToolHelper.isGradleProject(targetdir.toPath())) { - //this seems counter productive, but we want the dev mode model and not the test model - //as the test model will include the test classes that we don't want in the report - model = BuildToolHelper.enableGradleAppModelForDevMode(targetdir.toPath()); - } else { - throw new RuntimeException("Cannot determine project type generating Jacoco report"); - } - + final ApplicationModel model = curateOutcomeBuildItem.getApplicationModel(); if (model.getApplicationModule() != null) { addProjectModule(model.getAppArtifact(), config, info, includes, excludes, classes, sources); }
['test-framework/jacoco/deployment/src/main/java/io/quarkus/jacoco/deployment/JacocoProcessor.java']
{'.java': 1}
1
1
0
0
1
25,881,799
5,105,219
658,701
6,083
838
156
13
1
2,466
274
658
69
1
3
1970-01-01T00:27:59
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,233
quarkusio/quarkus/32088/31717
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/31717
https://github.com/quarkusio/quarkus/pull/32088
https://github.com/quarkusio/quarkus/pull/32088
1
fixes
Quarkus OIDC Session Cookie not deleted in case of 401 unauthorized
### Describe the bug In case the verification of the oidc session cookie fails (for instance because the id token is malformed, expired, ...), then the server response with an http 401. however, the server is not deleting the session cookie. hence all subsequent requests also fail with 401 without the change for the user to recover. Only deleting the session cookie or waiting for it to expire is possible. ### Expected behavior If the server response with http 401, then the server also deletes the q_session cookie. ### Actual behavior If the server response with http 401, then the (invalid) q_session cookie is not deleted automatically. ### How to Reproduce? 1) Login into your web application 2) manipulate the session cookie 3) perform another activity in the web application ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.16.3.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
5d57b2782adc96cad16367ecd7f0b28398ce66f4
298b0080634d15368d9f3a174994bf993d03e106
https://github.com/quarkusio/quarkus/compare/5d57b2782adc96cad16367ecd7f0b28398ce66f4...298b0080634d15368d9f3a174994bf993d03e106
diff --git a/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/CodeAuthenticationMechanism.java b/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/CodeAuthenticationMechanism.java index 55396274e51..0dde01e5b97 100644 --- a/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/CodeAuthenticationMechanism.java +++ b/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/CodeAuthenticationMechanism.java @@ -321,8 +321,13 @@ public Uni<? extends SecurityIdentity> apply(Throwable t) { if (!expired) { LOG.errorf("ID token verification failure: %s", t.getCause()); - return Uni.createFrom() - .failure(new AuthenticationCompletionException(t.getCause())); + return removeSessionCookie(context, configContext.oidcConfig) + .replaceWith(Uni.createFrom() + .failure(t + .getCause() instanceof AuthenticationCompletionException + ? t.getCause() + : new AuthenticationCompletionException( + t.getCause()))); } // Token has expired, try to refresh if (session.getRefreshToken() == null) { diff --git a/integration-tests/oidc-code-flow/src/test/java/io/quarkus/it/keycloak/CodeFlowTest.java b/integration-tests/oidc-code-flow/src/test/java/io/quarkus/it/keycloak/CodeFlowTest.java index abe8b76675f..a67cd4eb3f9 100644 --- a/integration-tests/oidc-code-flow/src/test/java/io/quarkus/it/keycloak/CodeFlowTest.java +++ b/integration-tests/oidc-code-flow/src/test/java/io/quarkus/it/keycloak/CodeFlowTest.java @@ -564,6 +564,22 @@ public void testIdTokenInjection() throws IOException { page = webClient.getPage("http://localhost:8081/web-app"); assertEquals("alice", page.getBody().asNormalizedText()); + + Cookie sessionCookie = getSessionCookie(webClient, null); + assertNotNull(sessionCookie); + webClient.getCookieManager().clearCookies(); + webClient.getCookieManager().addCookie(new Cookie(sessionCookie.getDomain(), sessionCookie.getName(), + "1|2|3")); + sessionCookie = getSessionCookie(webClient, null); + assertEquals("1|2|3", sessionCookie.getValue()); + + try { + webClient.getPage("http://localhost:8081/web-app"); + fail("401 status error is expected"); + } catch (FailingHttpStatusCodeException ex) { + assertEquals(401, ex.getStatusCode()); + assertNull(getSessionCookie(webClient, null)); + } webClient.getCookieManager().clearCookies(); } }
['integration-tests/oidc-code-flow/src/test/java/io/quarkus/it/keycloak/CodeFlowTest.java', 'extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/CodeAuthenticationMechanism.java']
{'.java': 2}
2
2
0
0
2
25,881,799
5,105,219
658,701
6,083
920
71
9
1
1,126
180
252
41
0
0
1970-01-01T00:27:59
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,234
quarkusio/quarkus/32069/32065
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/32065
https://github.com/quarkusio/quarkus/pull/32069
https://github.com/quarkusio/quarkus/pull/32069
1
fix
List of AWT runtime initialized classes not observable for other extensions
### Describe the bug In Quarkiverse CXF we are performing some special actions at build time based on whether SOAP service interfaces reference build time initiliazed classes. To do that, we observe `RuntimeInitializedClassBuildItem` and `RuntimeInitializedPackageBuildItem`. `java.awt.Image` is a prime example for passing binary content to WebServices, however our Processor, it is not able to find out that `quarkus-awt` is actually setting it for runtime init, because it does so via GraalVM Features. I wonder whether `io.quarkus.awt.runtime.graal.AwtFeature` and `DarwinAwtFeature` could be transformed to a Quarkus BuildStep producing some `RuntimeInitializedPackageBuildItem` s?
3c22fa33328aa6f0cb8ebf938a2ee90fae47d30d
9764218cf2161f9e515df3e681d4f8e944eb7f5e
https://github.com/quarkusio/quarkus/compare/3c22fa33328aa6f0cb8ebf938a2ee90fae47d30d...9764218cf2161f9e515df3e681d4f8e944eb7f5e
diff --git a/extensions/awt/deployment/src/main/java/io/quarkus/awt/deployment/AwtProcessor.java b/extensions/awt/deployment/src/main/java/io/quarkus/awt/deployment/AwtProcessor.java index 091b3084502..df7c1571466 100644 --- a/extensions/awt/deployment/src/main/java/io/quarkus/awt/deployment/AwtProcessor.java +++ b/extensions/awt/deployment/src/main/java/io/quarkus/awt/deployment/AwtProcessor.java @@ -2,7 +2,8 @@ import static io.quarkus.deployment.builditem.nativeimage.UnsupportedOSBuildItem.Os.WINDOWS; -import io.quarkus.awt.runtime.graal.AwtFeature; +import java.util.stream.Stream; + import io.quarkus.awt.runtime.graal.DarwinAwtFeature; import io.quarkus.deployment.Feature; import io.quarkus.deployment.annotations.BuildProducer; @@ -13,6 +14,7 @@ import io.quarkus.deployment.builditem.nativeimage.NativeImageResourcePatternsBuildItem; import io.quarkus.deployment.builditem.nativeimage.NativeMinimalJavaVersionBuildItem; import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem; +import io.quarkus.deployment.builditem.nativeimage.RuntimeInitializedPackageBuildItem; import io.quarkus.deployment.builditem.nativeimage.UnsupportedOSBuildItem; import io.quarkus.deployment.pkg.steps.NativeBuild; import io.quarkus.deployment.pkg.steps.NativeOrNativeSourcesBuild; @@ -26,7 +28,6 @@ FeatureBuildItem feature() { @BuildStep(onlyIf = NativeOrNativeSourcesBuild.class) void nativeImageFeatures(BuildProducer<NativeImageFeatureBuildItem> nativeImageFeatures) { - nativeImageFeatures.produce(new NativeImageFeatureBuildItem(AwtFeature.class)); nativeImageFeatures.produce(new NativeImageFeatureBuildItem(DarwinAwtFeature.class)); } @@ -197,4 +198,21 @@ JniRuntimeAccessBuildItem setupJava2DClasses() { "sun.java2d.SunGraphics2D", "sun.java2d.SurfaceData"); } + + @BuildStep + void runtimeInitializedClasses(BuildProducer<RuntimeInitializedPackageBuildItem> runtimeInitilizedPackages) { + /* + * Note that this initialization is not enough if user wants to deserialize actual images + * (e.g. from XML). AWT Extension must be loaded for decoding JDK supported image formats. + */ + Stream.of("com.sun.imageio", + "java.awt", + "javax.imageio", + "sun.awt", + "sun.font", + "sun.java2d") + .map(RuntimeInitializedPackageBuildItem::new) + .forEach(runtimeInitilizedPackages::produce); + } + } diff --git a/extensions/awt/runtime/src/main/java/io/quarkus/awt/runtime/graal/AwtFeature.java b/extensions/awt/runtime/src/main/java/io/quarkus/awt/runtime/graal/AwtFeature.java deleted file mode 100644 index 34b8606751d..00000000000 --- a/extensions/awt/runtime/src/main/java/io/quarkus/awt/runtime/graal/AwtFeature.java +++ /dev/null @@ -1,22 +0,0 @@ -package io.quarkus.awt.runtime.graal; - -import org.graalvm.nativeimage.hosted.Feature; -import org.graalvm.nativeimage.hosted.RuntimeClassInitialization; - -/** - * Note that this initialization is not enough if user wants to deserialize actual images - * (e.g. from XML). AWT Extension must be loaded for decoding JDK supported image formats. - */ -public class AwtFeature implements Feature { - @Override - public void afterRegistration(AfterRegistrationAccess access) { - // Quarkus run time init for AWT - RuntimeClassInitialization.initializeAtRunTime( - "com.sun.imageio", - "java.awt", - "javax.imageio", - "sun.awt", - "sun.font", - "sun.java2d"); - } -}
['extensions/awt/deployment/src/main/java/io/quarkus/awt/deployment/AwtProcessor.java', 'extensions/awt/runtime/src/main/java/io/quarkus/awt/runtime/graal/AwtFeature.java']
{'.java': 2}
2
2
0
0
2
25,877,513
5,104,359
658,600
6,081
1,717
341
44
2
698
89
156
8
0
0
1970-01-01T00:27:59
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,235
quarkusio/quarkus/32061/32032
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/32032
https://github.com/quarkusio/quarkus/pull/32061
https://github.com/quarkusio/quarkus/pull/32061
1
fix
PartFilename does not work for InputStream
### Describe the bug I use quarkus-rest-client-reactive to send a multipart rest request. This is the model I use: ``` public class GreetingModel { @FormParam("file") @PartType(value = MediaType.APPLICATION_OCTET_STREAM) @PartFilename("static-file-name") public InputStream file; } ``` When I send this request, the filename of the part is not transmitted. It works if I change the type from InputStream to byte array. Imo. This annotation should be usable on every type, not only for byte array, or at least an error message should be printed. ### Expected behavior file name is transmitted for inputstream. ### Actual behavior null is received for the filename ### How to Reproduce? Reproducer: [rcr-remove-filter (2).zip](https://github.com/quarkusio/quarkus/files/11038862/rcr-remove-filter.2.zip) 1. mvn quarkus:dev 2. open http://localhost:8080/hello/2 in a browser 3. null|Hello is returned 4. Change the GreetingModel to use a byte[] instead of inputstream 5. open http://localhost:8080/hello/2 in a browser 6. static-file-name|Hello is printed ### Output of `uname -a` or `ver` MINGW64_NT-10.0-19044 NANBCHL9NG3 3.3.6-341.x86_64 2022-09-05 20:28 UTC x86_64 Msys ### Output of `java -version` openjdk 17.0.4 2022-07-19 OpenJDK Runtime Environment Temurin-17.0.4+8 (build 17.0.4+8) OpenJDK 64-Bit Server VM Temurin-17.0.4+8 (build 17.0.4+8, mixed mode, sharing) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.16.4.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) Maven home: C:\\eclipse\\tools\\java\\maven Java version: 17.0.4, vendor: Eclipse Adoptium, runtime: C:\\eclipse\\tools\\java\\17 Default locale: de_DE, platform encoding: Cp1252 OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows" ### Additional information _No response_
286cf2c568b542cb157a2746e299508dd27ba531
4717c905aee995c240f06918553a4f8febc76956
https://github.com/quarkusio/quarkus/compare/286cf2c568b542cb157a2746e299508dd27ba531...4717c905aee995c240f06918553a4f8febc76956
diff --git a/extensions/resteasy-reactive/jaxrs-client-reactive/deployment/src/main/java/io/quarkus/jaxrs/client/reactive/deployment/JaxrsClientReactiveProcessor.java b/extensions/resteasy-reactive/jaxrs-client-reactive/deployment/src/main/java/io/quarkus/jaxrs/client/reactive/deployment/JaxrsClientReactiveProcessor.java index 7f671a29636..73d84c07354 100644 --- a/extensions/resteasy-reactive/jaxrs-client-reactive/deployment/src/main/java/io/quarkus/jaxrs/client/reactive/deployment/JaxrsClientReactiveProcessor.java +++ b/extensions/resteasy-reactive/jaxrs-client-reactive/deployment/src/main/java/io/quarkus/jaxrs/client/reactive/deployment/JaxrsClientReactiveProcessor.java @@ -17,6 +17,7 @@ import java.io.Closeable; import java.io.File; +import java.io.InputStream; import java.lang.reflect.Modifier; import java.nio.file.Path; import java.util.AbstractMap; @@ -1649,6 +1650,9 @@ private void handleMultipartField(String formParamName, String partType, String } else if (type.equals(Path.class.getName())) { // and so is path addFile(ifValueNotNull, multipartForm, formParamName, partType, partFilename, fieldValue); + } else if (type.equals(InputStream.class.getName())) { + // and so is path + addInputStream(ifValueNotNull, multipartForm, formParamName, partType, partFilename, fieldValue, type); } else if (type.equals(Buffer.class.getName())) { // and buffer addBuffer(ifValueNotNull, multipartForm, formParamName, partType, partFilename, fieldValue, errorLocation); @@ -1663,8 +1667,12 @@ private void handleMultipartField(String formParamName, String partType, String fieldValue); addBuffer(ifValueNotNull, multipartForm, formParamName, partType, partFilename, buffer, errorLocation); } else if (parameterGenericType.equals(MULTI_BYTE_SIGNATURE)) { - addMultiAsFile(ifValueNotNull, multipartForm, formParamName, partType, fieldValue, errorLocation); + addMultiAsFile(ifValueNotNull, multipartForm, formParamName, partType, partFilename, fieldValue, errorLocation); } else if (partType != null) { + if (partFilename != null) { + log.warnf("Using the @PartFilename annotation is unsupported on the type '%s'. Problematic field is: '%s'", + partType, formParamName); + } // assume POJO: addPojo(ifValueNotNull, multipartForm, formParamName, partType, fieldValue, type); } else { @@ -1677,6 +1685,17 @@ private void handleMultipartField(String formParamName, String partType, String } } + private void addInputStream(BytecodeCreator methodCreator, AssignableResultHandle multipartForm, String formParamName, + String partType, String partFilename, ResultHandle fieldValue, String type) { + methodCreator.assign(multipartForm, + methodCreator.invokeVirtualMethod(MethodDescriptor.ofMethod(QuarkusMultipartForm.class, "entity", + QuarkusMultipartForm.class, String.class, String.class, Object.class, String.class, Class.class), + multipartForm, methodCreator.load(formParamName), methodCreator.load(partFilename), fieldValue, + methodCreator.load(partType), + // FIXME: doesn't support generics + methodCreator.loadClassFromTCCL(type))); + } + private void addPojo(BytecodeCreator methodCreator, AssignableResultHandle multipartForm, String formParamName, String partType, ResultHandle fieldValue, String type) { methodCreator.assign(multipartForm, @@ -1780,12 +1799,17 @@ private void addString(BytecodeCreator methodCreator, AssignableResultHandle mul } private void addMultiAsFile(BytecodeCreator methodCreator, AssignableResultHandle multipartForm, String formParamName, - String partType, + String partType, String partFilename, ResultHandle multi, String errorLocation) { // they all default to plain/text except buffers/byte[]/Multi<Byte>/File/Path if (partType == null) { partType = MediaType.APPLICATION_OCTET_STREAM; } + String filename = partFilename; + if (filename == null) { + filename = formParamName; + } + if (partType.equalsIgnoreCase(MediaType.APPLICATION_OCTET_STREAM)) { methodCreator.assign(multipartForm, // MultipartForm#binaryFileUpload(String name, String filename, Multi<Byte> content, String mediaType); @@ -1794,7 +1818,7 @@ private void addMultiAsFile(BytecodeCreator methodCreator, AssignableResultHandl MethodDescriptor.ofMethod(QuarkusMultipartForm.class, "multiAsBinaryFileUpload", QuarkusMultipartForm.class, String.class, String.class, Multi.class, String.class), - multipartForm, methodCreator.load(formParamName), methodCreator.load(formParamName), + multipartForm, methodCreator.load(formParamName), methodCreator.load(filename), multi, methodCreator.load(partType))); } else { methodCreator.assign(multipartForm, @@ -1804,7 +1828,7 @@ private void addMultiAsFile(BytecodeCreator methodCreator, AssignableResultHandl MethodDescriptor.ofMethod(QuarkusMultipartForm.class, "multiAsTextFileUpload", QuarkusMultipartForm.class, String.class, String.class, Multi.class, String.class), - multipartForm, methodCreator.load(formParamName), methodCreator.load(formParamName), + multipartForm, methodCreator.load(formParamName), methodCreator.load(filename), multi, methodCreator.load(partType))); } } diff --git a/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/multipart/MultipartFilenameTest.java b/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/multipart/MultipartFilenameTest.java index e4e8aa704f8..74c00adfe85 100644 --- a/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/multipart/MultipartFilenameTest.java +++ b/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/multipart/MultipartFilenameTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import java.io.BufferedReader; +import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -10,6 +11,7 @@ import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.util.ArrayList; import java.util.stream.Collectors; import jakarta.enterprise.context.ApplicationScoped; @@ -29,6 +31,7 @@ import io.quarkus.test.QuarkusUnitTest; import io.quarkus.test.common.http.TestHTTPResource; +import io.smallrye.mutiny.Multi; public class MultipartFilenameTest { @@ -72,6 +75,39 @@ void shouldUseFileNameFromAnnotationUsingString() { assertThat(client.postMultipartWithPartFilenameUsingString(form)).isEqualTo("clientFile:file content"); } + @Test + void shouldUseFileNameFromAnnotationUsingByteArray() { + Client client = RestClientBuilder.newBuilder().baseUri(baseUri).build(Client.class); + + ClientFormUsingByteArray form = new ClientFormUsingByteArray(); + form.file = "file content".getBytes(StandardCharsets.UTF_8); + assertThat(client.postMultipartWithPartFilenameUsingByteArray(form)).isEqualTo("clientFile:file content"); + } + + @Test + void shouldUseFileNameFromAnnotationUsingInputStream() { + Client client = RestClientBuilder.newBuilder().baseUri(baseUri).build(Client.class); + + ClientFormUsingInputStream form = new ClientFormUsingInputStream(); + form.file = new ByteArrayInputStream("file content".getBytes(StandardCharsets.UTF_8)); + assertThat(client.postMultipartWithPartFilenameUsingInputStream(form)).isEqualTo("clientFile:file content"); + } + + @Test + void shouldUseFileNameFromAnnotationUsingMultiByte() { + Client client = RestClientBuilder.newBuilder().baseUri(baseUri).build(Client.class); + + var list = new ArrayList<Byte>(); + var array = "file content".getBytes(StandardCharsets.UTF_8); + for (var b : array) { + list.add(b); + } + + ClientFormUsingMultiByte form = new ClientFormUsingMultiByte(); + form.file = Multi.createFrom().items(list.stream()); + assertThat(client.postMultipartWithPartFilenameUsingMultiByte(form)).isEqualTo("clientFile:file content"); + } + @Test void shouldCopyFileContentToString() throws IOException { Client client = RestClientBuilder.newBuilder().baseUri(baseUri).build(Client.class); @@ -121,7 +157,7 @@ public String upload(@MultipartForm FormData form) { } @POST - @Path("/using-string") + @Path("/using-form-data") @Consumes(MediaType.MULTIPART_FORM_DATA) public String uploadWithFileContentUsingString(@MultipartForm FormData form) throws IOException { return form.myFile.fileName() + ":" + Files.readString(form.myFile.uploadedFile()); @@ -185,10 +221,25 @@ public interface Client { String postMultipartWithPartFilename(@MultipartForm ClientFormUsingFile clientForm); @POST - @Path("/using-string") + @Path("/using-form-data") @Consumes(MediaType.MULTIPART_FORM_DATA) String postMultipartWithPartFilenameUsingString(@MultipartForm ClientFormUsingString clientForm); + @POST + @Path("/using-form-data") + @Consumes(MediaType.MULTIPART_FORM_DATA) + String postMultipartWithPartFilenameUsingByteArray(@MultipartForm ClientFormUsingByteArray clientForm); + + @POST + @Path("/using-form-data") + @Consumes(MediaType.MULTIPART_FORM_DATA) + String postMultipartWithPartFilenameUsingInputStream(@MultipartForm ClientFormUsingInputStream clientForm); + + @POST + @Path("/using-form-data") + @Consumes(MediaType.MULTIPART_FORM_DATA) + String postMultipartWithPartFilenameUsingMultiByte(@MultipartForm ClientFormUsingMultiByte clientForm); + @POST @Path("/file-content") @Consumes(MediaType.MULTIPART_FORM_DATA) @@ -228,4 +279,31 @@ public static class ClientFormUsingString { @PartFilename(FILE_NAME) public String file; } + + public static class ClientFormUsingByteArray { + public static final String FILE_NAME = "clientFile"; + + @FormParam("myFile") + @PartType(MediaType.APPLICATION_OCTET_STREAM) + @PartFilename(FILE_NAME) + public byte[] file; + } + + public static class ClientFormUsingInputStream { + public static final String FILE_NAME = "clientFile"; + + @FormParam("myFile") + @PartType(MediaType.APPLICATION_OCTET_STREAM) + @PartFilename(FILE_NAME) + public InputStream file; + } + + public static class ClientFormUsingMultiByte { + public static final String FILE_NAME = "clientFile"; + + @FormParam("myFile") + @PartType(MediaType.APPLICATION_OCTET_STREAM) + @PartFilename(FILE_NAME) + public Multi<Byte> file; + } } diff --git a/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/multipart/QuarkusMultipartForm.java b/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/multipart/QuarkusMultipartForm.java index 2a082ffa09e..36ce207fcab 100644 --- a/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/multipart/QuarkusMultipartForm.java +++ b/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/multipart/QuarkusMultipartForm.java @@ -50,7 +50,11 @@ public QuarkusMultipartForm attribute(String name, String value, String filename } public QuarkusMultipartForm entity(String name, Object entity, String mediaType, Class<?> type) { - pojos.add(new PojoFieldData(name, entity, mediaType, type, parts.size())); + return entity(name, null, entity, mediaType, type); + } + + public QuarkusMultipartForm entity(String name, String filename, Object entity, String mediaType, Class<?> type) { + pojos.add(new PojoFieldData(name, filename, entity, mediaType, type, parts.size())); parts.add(null); // make place for ^ return this; } @@ -132,19 +136,22 @@ public void preparePojos(RestClientRequestContext context) throws IOException { break; } } - parts.set(pojo.position, new QuarkusMultipartFormDataPart(pojo.name, value, pojo.mediaType, pojo.type)); + parts.set(pojo.position, + new QuarkusMultipartFormDataPart(pojo.name, pojo.filename, value, pojo.mediaType, pojo.type)); } } public static class PojoFieldData { private final String name; + private final String filename; private final Object entity; private final String mediaType; private final Class<?> type; private final int position; - public PojoFieldData(String name, Object entity, String mediaType, Class<?> type, int position) { + public PojoFieldData(String name, String filename, Object entity, String mediaType, Class<?> type, int position) { this.name = name; + this.filename = filename; this.entity = entity; this.mediaType = mediaType; this.type = type; diff --git a/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/multipart/QuarkusMultipartFormDataPart.java b/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/multipart/QuarkusMultipartFormDataPart.java index c5f8b9e70e3..64b46f9f3f6 100644 --- a/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/multipart/QuarkusMultipartFormDataPart.java +++ b/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/multipart/QuarkusMultipartFormDataPart.java @@ -20,7 +20,12 @@ public class QuarkusMultipartFormDataPart { private final Multi<Byte> multiByteContent; public QuarkusMultipartFormDataPart(String name, Buffer content, String mediaType, Class<?> type) { + this(name, null, content, mediaType, type); + } + + public QuarkusMultipartFormDataPart(String name, String filename, Buffer content, String mediaType, Class<?> type) { this.name = name; + this.filename = filename; this.content = content; this.mediaType = mediaType; this.type = type; @@ -37,7 +42,6 @@ public QuarkusMultipartFormDataPart(String name, Buffer content, String mediaTyp } this.isObject = true; this.value = null; - this.filename = null; this.pathname = null; this.text = false; } diff --git a/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/multipart/QuarkusMultipartFormUpload.java b/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/multipart/QuarkusMultipartFormUpload.java index 03514b349e5..21bb2a23db3 100644 --- a/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/multipart/QuarkusMultipartFormUpload.java +++ b/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/multipart/QuarkusMultipartFormUpload.java @@ -68,8 +68,12 @@ public FileUpload createFileUpload(HttpRequest request, String name, String file if (formDataPart.isAttribute()) { encoder.addBodyAttribute(formDataPart.name(), formDataPart.value()); } else if (formDataPart.isObject()) { - MemoryFileUpload data = new MemoryFileUpload(formDataPart.name(), "", formDataPart.mediaType(), - formDataPart.isText() ? null : "binary", null, formDataPart.content().length()); + MemoryFileUpload data = new MemoryFileUpload(formDataPart.name(), + formDataPart.filename() != null ? formDataPart.filename() : "", + formDataPart.mediaType(), + formDataPart.isText() ? null : "binary", + null, + formDataPart.content().length()); data.setContent(formDataPart.content().getByteBuf()); encoder.addBodyHttpData(data); } else if (formDataPart.multiByteContent() != null) {
['extensions/resteasy-reactive/jaxrs-client-reactive/deployment/src/main/java/io/quarkus/jaxrs/client/reactive/deployment/JaxrsClientReactiveProcessor.java', 'independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/multipart/QuarkusMultipartFormDataPart.java', 'independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/multipart/QuarkusMultipartForm.java', 'extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/multipart/MultipartFilenameTest.java', 'independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/multipart/QuarkusMultipartFormUpload.java']
{'.java': 5}
5
5
0
0
5
25,875,563
5,104,013
658,564
6,081
3,967
759
59
4
1,956
243
594
64
3
1
1970-01-01T00:27:59
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,236
quarkusio/quarkus/32060/32059
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/32059
https://github.com/quarkusio/quarkus/pull/32060
https://github.com/quarkusio/quarkus/pull/32060
1
fix
`quarkus-jaxb` loads entity classes at build time even though no default JAXBContext will be created within the application
### Describe the bug I am working on a test within Quarkiverse CXF that makes sure that SOAP service methods having runtime initialized arguments work. Those arguments typically have JAXB annotations and so they are catched by JaxbProcessor when collecting classes for the default JAXBContext. If some of those arguments has (for whatever reason) runtime init set, then the native build fails with the following exception: ``` [WARN] [stderr] Error: Classes that should be initialized at run time got initialized during image building: [WARN] [stderr] at org.graalvm.nativeimage.builder/com.oracle.svm.core.util.UserError.abort(UserError.java:73) [WARN] [stderr] io.quarkiverse.cxf.client.it.rtinit.Result the class was requested to be initialized at run time (from command line with 'io.quarkiverse.cxf.client.it.rtinit.Result'). To see why io.quarkiverse.cxf.client.it.rtinit.Result got initialized use --trace-class-initialization=io.quarkiverse.cxf.client.it.rtinit.Result [WARN] [stderr] at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.classinitialization.ProvenSafeClassInitializationSupport.checkDelayedInitialization(ProvenSafeClassInitializationSupport.java:273) [WARN] [stderr] at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.classinitialization.ClassInitializationFeature.duringAnalysis(ClassInitializationFeature.java:164) [INFO] [stdout] ------------------------------------------------------------------------------------------------------------------------ [WARN] [stderr] io.quarkiverse.cxf.client.it.rtinit.Operands the class was requested to be initialized at run time (from command line with 'io.quarkiverse.cxf.client.it.rtinit.Operands'). io.quarkus.runner.ApplicationImpl caused initialization of this class with the following trace: [WARN] [stderr] at io.quarkiverse.cxf.client.it.rtinit.Operands.<clinit>(Operands.java) [WARN] [stderr] at java.lang.Class.forName0(Unknown Source) [WARN] [stderr] at java.lang.Class.forName(Class.java:467) [WARN] [stderr] at io.quarkus.deployment.steps.JaxbProcessor$setupJaxbContextConfig1556898737.deploy_0(Unknown Source) [WARN] [stderr] at io.quarkus.deployment.steps.JaxbProcessor$setupJaxbContextConfig1556898737.deploy(Unknown Source) [WARN] [stderr] at io.quarkus.runner.ApplicationImpl.<clinit>(Unknown Source) [WARN] [stderr] [WARN] [stderr] To see how the classes got initialized, use --trace-class-initialization=io.quarkiverse.cxf.client.it.rtinit.Result [WARN] [stderr] com.oracle.svm.core.util.UserError$UserException: Classes that should be initialized at run time got initialized during image building: [WARN] [stderr] at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.lambda$runPointsToAnalysis$10(NativeImageGenerator.java:748) [WARN] [stderr] io.quarkiverse.cxf.client.it.rtinit.Result the class was requested to be initialized at run time (from command line with 'io.quarkiverse.cxf.client.it.rtinit.Result'). To see why io.quarkiverse.cxf.client.it.rtinit.Result got initialized use --trace-class-initialization=io.quarkiverse.cxf.client.it.rtinit.Result [WARN] [stderr] at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.FeatureHandler.forEachFeature(FeatureHandler.java:85) [WARN] [stderr] at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.lambda$runPointsToAnalysis$11(NativeImageGenerator.java:748) [WARN] [stderr] at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.AbstractAnalysisEngine.runAnalysis(AbstractAnalysisEngine.java:162) [WARN] [stderr] io.quarkiverse.cxf.client.it.rtinit.Operands the class was requested to be initialized at run time (from command line with 'io.quarkiverse.cxf.client.it.rtinit.Operands'). io.quarkus.runner.ApplicationImpl caused initialization of this class with the following trace: [WARN] [stderr] at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.runPointsToAnalysis(NativeImageGenerator.java:745) [WARN] [stderr] at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.doRun(NativeImageGenerator.java:578) [WARN] [stderr] at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.run(NativeImageGenerator.java:535) [WARN] [stderr] at io.quarkiverse.cxf.client.it.rtinit.Operands.<clinit>(Operands.java) [WARN] [stderr] at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.buildImage(NativeImageGeneratorRunner.java:403) [INFO] [stdout] 1.4s (4.8% of total time) in 26 GCs | Peak RSS: 4.61GB | CPU load: 11.88 [WARN] [stderr] at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.build(NativeImageGeneratorRunner.java:580) [WARN] [stderr] at java.lang.Class.forName0(Unknown Source) [INFO] [stdout] ======================================================================================================================== [WARN] [stderr] at java.lang.Class.forName(Class.java:467) [INFO] [stdout] Failed generating 'quarkus-cxf-integration-test-client-2.0.0-SNAPSHOT-runner' after 29.2s. [WARN] [stderr] at io.quarkus.deployment.steps.JaxbProcessor$setupJaxbContextConfig1556898737.deploy_0(Unknown Source) [WARN] [stderr] at io.quarkus.deployment.steps.JaxbProcessor$setupJaxbContextConfig1556898737.deploy(Unknown Source) [WARN] [stderr] at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.main(NativeImageGeneratorRunner.java:128) [WARN] [stderr] at io.quarkus.runner.ApplicationImpl.<clinit>(Unknown Source) ``` See the first commit of this PR for a reproducer: https://github.com/quarkiverse/quarkus-cxf/pull/771/commits I guess SOAP service methods having a runtime initialized argument will be a rather rare, but still possible case that we should support in Quarkus CXF. In the test the runtime init is forced via `quarkus.native.additional-build-args=--initialize-at-run-time=io.quarkiverse.cxf.client.it.rtinit.Operands` In https://github.com/quarkusio/quarkus/pull/31666 we made the runtime validation of the default JAXBContext required only if the application actually uses the default JAXBContext - i.e. if there is at least one injection point for it. Clearly, if a the default JAXBContext would be used by the application, then this issue is expected. But OTOH, I believe, that when the default JAXBContext is not required by the application, then the classes for it should not be loaded at build time. Fixing this seems to be quite easy and I am going to send a PR to see whether it really works for all existing JAXB tests. ### Expected behavior _No response_ ### Actual behavior _No response_ ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
286cf2c568b542cb157a2746e299508dd27ba531
e86129c8191d60cc90044394accf1067ef4e4204
https://github.com/quarkusio/quarkus/compare/286cf2c568b542cb157a2746e299508dd27ba531...e86129c8191d60cc90044394accf1067ef4e4204
diff --git a/extensions/jaxb/deployment/src/main/java/io/quarkus/jaxb/deployment/JaxbProcessor.java b/extensions/jaxb/deployment/src/main/java/io/quarkus/jaxb/deployment/JaxbProcessor.java index 41ca49b5206..29255342e9a 100644 --- a/extensions/jaxb/deployment/src/main/java/io/quarkus/jaxb/deployment/JaxbProcessor.java +++ b/extensions/jaxb/deployment/src/main/java/io/quarkus/jaxb/deployment/JaxbProcessor.java @@ -314,14 +314,6 @@ FilteredJaxbClassesToBeBoundBuildItem filterBoundClasses( return builder.build(); } - @BuildStep - @Record(ExecutionTime.STATIC_INIT) - void setupJaxbContextConfig( - FilteredJaxbClassesToBeBoundBuildItem filteredClassesToBeBound, - JaxbContextConfigRecorder jaxbContextConfig) { - jaxbContextConfig.addClassesToBeBound(filteredClassesToBeBound.getClasses()); - } - @BuildStep @Record(ExecutionTime.STATIC_INIT) void validateDefaultJaxbContext( @@ -335,6 +327,7 @@ void validateDefaultJaxbContext( final Set<BeanInfo> beans = beanResolver .resolveBeans(Type.create(DotName.createSimple(JAXBContext.class), org.jboss.jandex.Type.Kind.CLASS)); if (!beans.isEmpty()) { + jaxbContextConfig.addClassesToBeBound(filteredClassesToBeBound.getClasses()); final BeanInfo bean = beanResolver.resolveAmbiguity(beans); if (bean.isDefaultBean()) { /*
['extensions/jaxb/deployment/src/main/java/io/quarkus/jaxb/deployment/JaxbProcessor.java']
{'.java': 1}
1
1
0
0
1
25,875,563
5,104,013
658,564
6,081
417
96
9
1
7,252
577
1,697
92
2
1
1970-01-01T00:27:59
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,237
quarkusio/quarkus/31984/31930
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/31930
https://github.com/quarkusio/quarkus/pull/31984
https://github.com/quarkusio/quarkus/pull/31984
1
closes
Native build fails for JWT
### Describe the bug Error while building natively for quarkus-smallrye-jwt-build when present as dependency with error: ``` io.quarkus.smallrye.jwt.build.runtime.graalvm.Target_org_jose4j_jwk_OctetKeyPairJsonWebKey is not loaded. Error: Substitution target for io.quarkus.smallrye.jwt.build.runtime.graalvm.Target_org_jose4j_jwk_OctetKeyPairJsonWebKey is not loaded. Use field `onlyWith` in the `TargetClass` annotation to make substitution only active when needed. com.oracle.svm.core.util.UserError$UserException: Substitution target for io.quarkus.smallrye.jwt.build.runtime.graalvm.Target_org_jose4j_jwk_OctetKeyPairJsonWebKey is not loaded. Use field `onlyWith` in the `TargetClass` annotation to make substitution only active when needed. ``` ### Expected behavior Native build to pass ### Actual behavior Build fails on graalvm-ce-java11-22.3.0/bin/native-image for quarkus version 2.16.4 ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` Linux quarkus-native-postgres-1sr26 4.18.0-305.72.1.el8_4.x86_64 #1 SMP Thu Nov 17 09:15:11 EST 2022 x86_64 x86_64 x86_64 GNU/Linux ### Output of `java -version` graalvm-ce-java11-22.3.0 ### GraalVM version (if different from Java) graalvm-ce-java11-22.3.0 ### Quarkus version or git rev 2.16.4 ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.6.2 (Red Hat 3.6.2-7) ### Additional information _No response_
03ccd2e5da2cb2dc67c3560382570d950d7f1730
1b143e9660c9cac7e5d0a3f76e43f9e232c0e9f5
https://github.com/quarkusio/quarkus/compare/03ccd2e5da2cb2dc67c3560382570d950d7f1730...1b143e9660c9cac7e5d0a3f76e43f9e232c0e9f5
diff --git a/extensions/smallrye-jwt-build/runtime/src/main/java/io/quarkus/smallrye/jwt/build/runtime/graalvm/Substitutions.java b/extensions/smallrye-jwt-build/runtime/src/main/java/io/quarkus/smallrye/jwt/build/runtime/graalvm/Substitutions.java index 4d09817c95d..c7e868d0b0a 100644 --- a/extensions/smallrye-jwt-build/runtime/src/main/java/io/quarkus/smallrye/jwt/build/runtime/graalvm/Substitutions.java +++ b/extensions/smallrye-jwt-build/runtime/src/main/java/io/quarkus/smallrye/jwt/build/runtime/graalvm/Substitutions.java @@ -5,25 +5,34 @@ import com.oracle.svm.core.annotate.Substitute; import com.oracle.svm.core.annotate.TargetClass; -@TargetClass(className = "org.jose4j.jwk.OctetKeyPairJsonWebKey", onlyWith = JavaVersionLessThan17.class) +@TargetClass(className = "org.jose4j.jwk.OctetKeyPairJsonWebKey", onlyWith = JavaVersionLessThan17andOctetKeyPairOnClasspath.class) final class Target_org_jose4j_jwk_OctetKeyPairJsonWebKey { @Substitute public Target_org_jose4j_jwk_OctetKeyPairJsonWebKey(java.security.PublicKey publicKey) { + throw new UnsupportedOperationException( + "OctetKeyPairJsonWebKey depends on EdECPrivateKeySpec which is not available in Java < 15"); } @Substitute Target_org_jose4j_jwk_OctetKeyPairUtil subtypeKeyUtil() { - return null; + throw new UnsupportedOperationException( + "OctetKeyPairJsonWebKey depends on EdECPrivateKeySpec which is not available in Java < 15"); } } -@TargetClass(className = "org.jose4j.keys.OctetKeyPairUtil", onlyWith = JavaVersionLessThan17.class) +@TargetClass(className = "org.jose4j.keys.OctetKeyPairUtil", onlyWith = JavaVersionLessThan17andOctetKeyPairOnClasspath.class) final class Target_org_jose4j_jwk_OctetKeyPairUtil { } -class JavaVersionLessThan17 implements BooleanSupplier { +class JavaVersionLessThan17andOctetKeyPairOnClasspath implements BooleanSupplier { @Override public boolean getAsBoolean() { - return Runtime.version().version().get(0) < 17; + try { + Class.forName("org.jose4j.jwk.OctetKeyPairJsonWebKey"); + Class.forName("org.jose4j.jwk.OctetKeyPairUtil"); + return Runtime.version().version().get(0) < 17; + } catch (ClassNotFoundException e) { + return false; + } } }
['extensions/smallrye-jwt-build/runtime/src/main/java/io/quarkus/smallrye/jwt/build/runtime/graalvm/Substitutions.java']
{'.java': 1}
1
1
0
0
1
25,723,381
5,075,499
654,458
6,028
1,302
315
19
1
1,483
155
436
48
0
1
1970-01-01T00:27:59
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,238
quarkusio/quarkus/31931/31866
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/31866
https://github.com/quarkusio/quarkus/pull/31931
https://github.com/quarkusio/quarkus/pull/31931
1
fix
The behavior of the @RestHeader annotation is different from the @HeaderParam annotation when the parameter is of type List
The @RestHeader javadoc says : ``` /* * Equivalent of HeaderParam but with optional name. */ ``` And the javadoc of HeaderParam say that : ``` /** * Binds the value(s) of a HTTP header to a resource method parameter, * resource class field, or resource class bean property. A default value * can be specified using the {@link DefaultValue} annotation. * * The type {@code T} of the annotated parameter, field or property * must either: * <ol> * <li>Be a primitive type</li> * <li>Have a constructor that accepts a single {@code String} argument</li> * <li>Have a static method named {@code valueOf} or {@code fromString} * that accepts a single * {@code String} argument (see, for example, {@link Integer#valueOf(String)})</li> * <li>Have a registered implementation of {@link javax.ws.rs.ext.ParamConverterProvider} * JAX-RS extension SPI that returns a {@link javax.ws.rs.ext.ParamConverter} * instance capable of a "from string" conversion for the type.</li> * <li>Be {@code List<T>}, {@code Set<T>} or * {@code SortedSet<T>}, where {@code T} satisfies 2, 3 or 4 above. * The resulting collection is read-only.</li> * </ol> * * / ``` But the behavior of @RestHeader is different when the parameter is a List : by example a method like that : Response getSomething(@RestHeader("Prefer") List<String> prefers); Throw this kind of exception : ClassCast class java.util.ImmutableCollections$List12 cannot be cast to class java.lang.String (java.util.ImmutableCollections$List12 and java.lang.String are in module java.base of loader 'bootstrap') since 2.8 and it can be reproduced in 3.0.0.Alpha5
351fcd3bf43b23af4851b35934f9554edef64276
41aba276f020d510c9a2a0435ad9ad332ebf0a97
https://github.com/quarkusio/quarkus/compare/351fcd3bf43b23af4851b35934f9554edef64276...41aba276f020d510c9a2a0435ad9ad332ebf0a97
diff --git a/extensions/resteasy-reactive/jaxrs-client-reactive/deployment/src/main/java/io/quarkus/jaxrs/client/reactive/deployment/JaxrsClientReactiveProcessor.java b/extensions/resteasy-reactive/jaxrs-client-reactive/deployment/src/main/java/io/quarkus/jaxrs/client/reactive/deployment/JaxrsClientReactiveProcessor.java index 5d9b42b7faa..643efbc6a83 100644 --- a/extensions/resteasy-reactive/jaxrs-client-reactive/deployment/src/main/java/io/quarkus/jaxrs/client/reactive/deployment/JaxrsClientReactiveProcessor.java +++ b/extensions/resteasy-reactive/jaxrs-client-reactive/deployment/src/main/java/io/quarkus/jaxrs/client/reactive/deployment/JaxrsClientReactiveProcessor.java @@ -941,7 +941,7 @@ A more full example of generated client (with sub-resource) can is at the bottom MethodDescriptor handleHeaderDescriptor = MethodDescriptor.ofMethod(name, method.getName() + "$$" + methodIndex + "$$handleHeader$$" + paramIdx, Invocation.Builder.class, - Invocation.Builder.class, param.type); + Invocation.Builder.class, param.declaredType); MethodCreator handleHeaderMethod = classContext.classCreator.getMethodCreator( handleHeaderDescriptor).setModifiers(Modifier.PRIVATE); @@ -1358,7 +1358,7 @@ private void handleSubResourceMethod(List<JaxrsClientReactiveEnricherBuildItem> subMethod.getName() + "$$" + subMethodIndex + "$$handleHeader$$param" + inheritedParamIndex + "$" + subParamField.paramIndex, Invocation.Builder.class, - Invocation.Builder.class, param.type); + Invocation.Builder.class, param.declaredType); MethodCreator handleHeaderMethod = subContext.classCreator.getMethodCreator( handleHeaderDescriptor).setModifiers(Modifier.PRIVATE); @@ -1464,7 +1464,7 @@ private void handleSubResourceMethod(List<JaxrsClientReactiveEnricherBuildItem> MethodDescriptor handleHeaderDescriptor = MethodDescriptor.ofMethod(subName, subMethod.getName() + "$$" + subMethodIndex + "$$handleHeader$$" + paramIdx, Invocation.Builder.class, - Invocation.Builder.class, param.type); + Invocation.Builder.class, param.declaredType); MethodCreator handleHeaderMethod = subContext.classCreator.getMethodCreator( handleHeaderDescriptor).setModifiers(Modifier.PRIVATE); diff --git a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SimpleQuarkusRestResource.java b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SimpleQuarkusRestResource.java index ec39fe9b197..857e2bb420b 100644 --- a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SimpleQuarkusRestResource.java +++ b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SimpleQuarkusRestResource.java @@ -2,9 +2,13 @@ import java.math.BigDecimal; import java.util.Arrays; +import java.util.Collection; import java.util.List; +import java.util.Set; +import java.util.SortedSet; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; +import java.util.stream.Collectors; import jakarta.inject.Inject; import jakarta.json.JsonArray; @@ -143,6 +147,42 @@ public Response filters(@Context HttpHeaders headers, @RestHeader("filter-reques return Response.ok().header("filter-request", header).build(); } + @GET + @Path("header-param-list") + public Object headerParamWithList(@HeaderParam("header") List list) { + return collectionToString(list); + } + + @GET + @Path("rest-header-list") + public Object restHeaderWithList(@RestHeader List header) { + return collectionToString(header); + } + + @GET + @Path("header-param-set") + public Object headerParamWithSet(@HeaderParam("header") Set list) { + return collectionToString(list); + } + + @GET + @Path("rest-header-set") + public Object restHeaderWithSet(@RestHeader Set header) { + return collectionToString(header); + } + + @GET + @Path("header-param-sorted-set") + public Object headerParamWithSortedSet(@HeaderParam("header") SortedSet list) { + return collectionToString(list); + } + + @GET + @Path("rest-header-sorted-set") + public String restHeaderWithSortedSet(@RestHeader SortedSet header) { + return collectionToString(header); + } + @GET @Path("feature-filters") public Response featureFilters(@Context HttpHeaders headers) { @@ -380,4 +420,8 @@ public String simplifiedResourceInfo(@Context SimpleResourceInfo simplifiedResou public String bigDecimalConverter(BigDecimal val) { return val.toString(); } + + private String collectionToString(Collection list) { + return (String) list.stream().map(Object::toString).collect(Collectors.joining(", ")); + } } diff --git a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SimpleQuarkusRestTestCase.java b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SimpleQuarkusRestTestCase.java index ecadb812402..0281067a255 100644 --- a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SimpleQuarkusRestTestCase.java +++ b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SimpleQuarkusRestTestCase.java @@ -17,6 +17,8 @@ import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.OS; import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import io.quarkus.test.QuarkusUnitTest; import io.restassured.RestAssured; @@ -313,6 +315,34 @@ public void testHeaderParamInCtor() { .then().body(Matchers.is(emptyString())); } + @ParameterizedTest + @ValueSource(strings = { + "rest-header-list", + "rest-header-set", + "rest-header-sorted-set" + }) + public void testRestHeaderUsingCollection(String path) { + RestAssured.with().header("header", "a", "b") + .get("/simple/" + path) + .then() + .statusCode(HttpStatus.SC_OK) + .body(Matchers.equalTo("a, b")); + } + + @ParameterizedTest + @ValueSource(strings = { + "header-param-list", + "header-param-set", + "header-param-sorted-set" + }) + public void testHeaderParamUsingCollection(String path) { + RestAssured.with().header("header", "a", "b") + .get("/simple/" + path) + .then() + .statusCode(HttpStatus.SC_OK) + .body(Matchers.equalTo("a, b")); + } + @Test public void testFormMap() { RestAssured diff --git a/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/headers/HeaderTest.java b/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/headers/HeaderTest.java index 2884a22184d..b13b8e5ca6d 100644 --- a/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/headers/HeaderTest.java +++ b/extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/headers/HeaderTest.java @@ -3,6 +3,13 @@ import static org.assertj.core.api.Assertions.assertThat; import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.stream.Collectors; import jakarta.enterprise.context.ApplicationScoped; import jakarta.ws.rs.GET; @@ -40,6 +47,15 @@ void testNullHeaders() { assertThat(client.cookieSub("bar", null).send(null, "bar4", "dummy")).isEqualTo("bar:null:null:bar4:X-My-Header/dummy"); } + @Test + void testHeadersWithCollections() { + String expected = "a, b, c, d"; + Client client = RestClientBuilder.newBuilder().baseUri(baseUri).build(Client.class); + assertThat(client.headersList(List.of("a", "b"), List.of("c", "d"))).isEqualTo(expected); + assertThat(client.headersSet(Set.of("a", "b"), Set.of("c", "d"))).isEqualTo(expected); + assertThat(client.headersSet(new TreeSet(List.of("a", "b")), new TreeSet(List.of("c", "d")))).isEqualTo(expected); + } + @Path("/") @ApplicationScoped public static class Resource { @@ -51,12 +67,50 @@ public String returnHeaders(@HeaderParam("foo") String header, @HeaderParam("foo return header + ":" + header2 + ":" + header3 + ":" + header4 + ":" + myHeaderName + "/" + headers.getHeaderString("X-My-Header"); } + + @GET + @Path("/headers-list") + public String headersList(@HeaderParam("foo") List foo, @RestHeader List header) { + return joiningCollections(foo, header); + } + + @GET + @Path("/headers-set") + public String headersSet(@HeaderParam("foo") Set foo, @RestHeader Set header) { + return joiningCollections(foo, header); + } + + @GET + @Path("/headers-sorted-set") + public String headersSortedSet(@HeaderParam("foo") SortedSet foo, @RestHeader SortedSet header) { + return joiningCollections(foo, header); + } + + private String joiningCollections(Collection... collections) { + List<String> allHeaders = new ArrayList<>(); + for (Collection collection : collections) { + collection.forEach(v -> allHeaders.add((String) v)); + } + return allHeaders.stream().collect(Collectors.joining(", ")); + } } public interface Client { @Path("/") SubClient cookieSub(@HeaderParam("foo") String cookie, @HeaderParam("foo2") String cookie2); + + @GET + @Path("/headers-list") + String headersList(@HeaderParam("foo") List foo, @RestHeader List header); + + @GET + @Path("/headers-set") + String headersSet(@HeaderParam("foo") Set foo, @RestHeader Set header); + + @GET + @Path("/headers-sorted-set") + String headersSortedSet(@HeaderParam("foo") SortedSet foo, @RestHeader SortedSet header); } public interface SubClient { diff --git a/extensions/resteasy-reactive/rest-client-reactive/runtime/src/main/java/io/quarkus/rest/client/reactive/runtime/MicroProfileRestClientRequestFilter.java b/extensions/resteasy-reactive/rest-client-reactive/runtime/src/main/java/io/quarkus/rest/client/reactive/runtime/MicroProfileRestClientRequestFilter.java index 9f1600b450c..a1c2486c662 100644 --- a/extensions/resteasy-reactive/rest-client-reactive/runtime/src/main/java/io/quarkus/rest/client/reactive/runtime/MicroProfileRestClientRequestFilter.java +++ b/extensions/resteasy-reactive/rest-client-reactive/runtime/src/main/java/io/quarkus/rest/client/reactive/runtime/MicroProfileRestClientRequestFilter.java @@ -1,6 +1,7 @@ package io.quarkus.rest.client.reactive.runtime; import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.Map; @@ -81,11 +82,13 @@ public void filter(ResteasyReactiveClientRequestContext requestContext) { } } - private static List<String> castToListOfStrings(List<Object> values) { + private static List<String> castToListOfStrings(Collection<Object> values) { List<String> result = new ArrayList<>(); for (Object value : values) { if (value instanceof String) { result.add((String) value); + } else if (value instanceof Collection) { + result.addAll(castToListOfStrings((Collection<Object>) value)); } else { result.add(String.valueOf(value)); } diff --git a/independent-projects/resteasy-reactive/common/processor/src/main/java/org/jboss/resteasy/reactive/common/processor/EndpointIndexer.java b/independent-projects/resteasy-reactive/common/processor/src/main/java/org/jboss/resteasy/reactive/common/processor/EndpointIndexer.java index 20a679649c4..005dfc9cbcb 100644 --- a/independent-projects/resteasy-reactive/common/processor/src/main/java/org/jboss/resteasy/reactive/common/processor/EndpointIndexer.java +++ b/independent-projects/resteasy-reactive/common/processor/src/main/java/org/jboss/resteasy/reactive/common/processor/EndpointIndexer.java @@ -1359,13 +1359,28 @@ && isParameterContainerType(paramType.asClassType())) { elementType = paramType.name().toString(); handleTemporalParam(builder, paramType.name(), anns, currentMethodInfo); typeHandled = true; - } else if (paramType.name().equals(LIST) && (type == ParameterType.QUERY)) { // RESTEasy Classic handles the non-generic List type + } else if (paramType.name().equals(LIST) && (type == ParameterType.QUERY + || type == ParameterType.HEADER)) { // RESTEasy Classic handles the non-generic List type elementType = String.class.getName(); typeHandled = true; builder.setSingle(false); if (convertible) { handleListParam(existingConverters, errorLocation, hasRuntimeConverters, builder, elementType); } + } else if (paramType.name().equals(SET) && type == ParameterType.HEADER) { // RESTEasy Classic handles the non-generic Set type + elementType = String.class.getName(); + typeHandled = true; + builder.setSingle(false); + if (convertible) { + handleSetParam(existingConverters, errorLocation, hasRuntimeConverters, builder, elementType); + } + } else if (paramType.name().equals(SORTED_SET) && type == ParameterType.HEADER) { // RESTEasy Classic handles the non-generic SortedSet type + elementType = String.class.getName(); + typeHandled = true; + builder.setSingle(false); + if (convertible) { + handleSortedSetParam(existingConverters, errorLocation, hasRuntimeConverters, builder, elementType); + } } else if (paramType.kind() == Kind.ARRAY) { ArrayType at = paramType.asArrayType(); typeHandled = true;
['extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SimpleQuarkusRestTestCase.java', 'extensions/resteasy-reactive/jaxrs-client-reactive/deployment/src/main/java/io/quarkus/jaxrs/client/reactive/deployment/JaxrsClientReactiveProcessor.java', 'extensions/resteasy-reactive/rest-client-reactive/deployment/src/test/java/io/quarkus/rest/client/reactive/headers/HeaderTest.java', 'independent-projects/resteasy-reactive/common/processor/src/main/java/org/jboss/resteasy/reactive/common/processor/EndpointIndexer.java', 'extensions/resteasy-reactive/rest-client-reactive/runtime/src/main/java/io/quarkus/rest/client/reactive/runtime/MicroProfileRestClientRequestFilter.java', 'extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/simple/SimpleQuarkusRestResource.java']
{'.java': 6}
6
6
0
0
6
25,691,704
5,069,047
653,760
6,016
1,987
358
28
3
1,670
238
410
46
0
2
1970-01-01T00:27:59
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,239
quarkusio/quarkus/31770/31624
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/31624
https://github.com/quarkusio/quarkus/pull/31770
https://github.com/quarkusio/quarkus/pull/31770
1
fixes
native compilation : quarkus-jdbc-oracle with elasticsearch-java strange behaviour
### Describe the bug Hello, I'm trying to compile in native mode my project using - quay.io/quarkus/ubi-quarkus-graalvmce-builder-image:22.3-java17 as nativeBuilder - quarkus 2.16.3.Final - quarkus-jdbc-oracle - quarkus-elasticsearch-rest-client - elasticsearch-java But it fail. I can't figure out the problem. I've tried to add --initialize-at-run-time args but it doesn't change anything. I'm already using elasticsearch-java in native mode (8.1.2 not 8.6.2) with some initialize-at-run-time and register for reflection it works but the problem seem to come from the jdbc-oracle. ### Expected behavior Compilation without error or at least not the oracle-jdbc one. ### Actual behavior With the actual configuration I get this error : ``` #15 766.0 Error: Classes that should be initialized at run time got initialized during image building: #15 766.0 oracle.jdbc.driver.BlockSource$ThreadedCachingBlockSource$BlockReleaser the class was requested to be initialized at run time (from feature io.quarkus.runner.Feature.beforeAnalysis with 'BlockSource$ThreadedCachingBlockSource$BlockReleaser.class'). oracle.jdbc.driver.BlockSource$ThreadedCachingBlockSource caused initialization of this class with the following trace: ``` More detail stack on the project readme : https://github.com/xrobert35/quarkus-oracle-jdbc-error-example/blob/master/README.md ### How to Reproduce? I've made a simplified project to reproduce Step 1. ```shell https://github.com/xrobert35/quarkus-oracle-jdbc-error-example docker build -t <name> . --no-cache ``` ### Output of `uname -a` or `ver` docker windows or WSL docker ### Output of `java -version` Java Version 17.0.6+10-jvmci-22.3-b13 ### GraalVM version (if different from Java) 22.3 ### Quarkus version or git rev 2.16.3.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Docker ### Additional information ### Some strange behaviour - If you remove the use of ElasticsearchClient (including the import) in TestService **the compilation will work**. (So I suppose the real problem could be the creation of the ElasticsearchClient (in the TestOracleJDBCConfig file), but : - If you change quarkus-jdbc-oracle to quarkus-jdbc-postgresql and change to db-king to postgresql and I let the ElasticsearchClient **the compilation will work**
c0fc995631a35fa9e31fe741520078c556525cff
77062838587b25c6c8a18dddda6e26f2995348b7
https://github.com/quarkusio/quarkus/compare/c0fc995631a35fa9e31fe741520078c556525cff...77062838587b25c6c8a18dddda6e26f2995348b7
diff --git a/extensions/jdbc/jdbc-oracle/deployment/src/main/java/io/quarkus/jdbc/oracle/deployment/OracleMetadataOverrides.java b/extensions/jdbc/jdbc-oracle/deployment/src/main/java/io/quarkus/jdbc/oracle/deployment/OracleMetadataOverrides.java index fbabaecceb2..892ef190c53 100644 --- a/extensions/jdbc/jdbc-oracle/deployment/src/main/java/io/quarkus/jdbc/oracle/deployment/OracleMetadataOverrides.java +++ b/extensions/jdbc/jdbc-oracle/deployment/src/main/java/io/quarkus/jdbc/oracle/deployment/OracleMetadataOverrides.java @@ -9,6 +9,7 @@ import io.quarkus.deployment.builditem.nativeimage.NativeImageAllowIncompleteClasspathBuildItem; import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem; import io.quarkus.deployment.builditem.nativeimage.RuntimeInitializedClassBuildItem; +import io.quarkus.deployment.builditem.nativeimage.RuntimeReinitializedClassBuildItem; import io.quarkus.maven.dependency.ArtifactKey; /** @@ -66,7 +67,8 @@ void build(BuildProducer<ReflectiveClassBuildItem> reflectiveClass) { } @BuildStep - void runtimeInitializeDriver(BuildProducer<RuntimeInitializedClassBuildItem> runtimeInitialized) { + void runtimeInitializeDriver(BuildProducer<RuntimeInitializedClassBuildItem> runtimeInitialized, + BuildProducer<RuntimeReinitializedClassBuildItem> runtimeReinitialized) { //These re-implement all the "--initialize-at-build-time" arguments found in the native-image.properties : // Override: the original metadata marks the drivers as "runtime initialized" but this makes it incompatible with @@ -93,10 +95,14 @@ void runtimeInitializeDriver(BuildProducer<RuntimeInitializedClassBuildItem> run runtimeInitialized.produce(new RuntimeInitializedClassBuildItem("oracle.net.nt.TcpMultiplexer")); runtimeInitialized.produce(new RuntimeInitializedClassBuildItem("oracle.net.nt.TcpMultiplexer")); runtimeInitialized.produce(new RuntimeInitializedClassBuildItem("oracle.net.nt.TcpMultiplexer$LazyHolder")); - runtimeInitialized - .produce(new RuntimeInitializedClassBuildItem("oracle.jdbc.driver.BlockSource$ThreadedCachingBlockSource")); - runtimeInitialized.produce(new RuntimeInitializedClassBuildItem( + + // Needs to be REinitialized to avoid problems when also using the Elasticsearch Java client + // See https://github.com/quarkusio/quarkus/issues/31624#issuecomment-1457706253 + runtimeReinitialized.produce(new RuntimeReinitializedClassBuildItem( + "oracle.jdbc.driver.BlockSource$ThreadedCachingBlockSource")); + runtimeReinitialized.produce(new RuntimeReinitializedClassBuildItem( "oracle.jdbc.driver.BlockSource$ThreadedCachingBlockSource$BlockReleaser")); + runtimeInitialized.produce(new RuntimeInitializedClassBuildItem("oracle.jdbc.xa.client.OracleXADataSource")); runtimeInitialized.produce(new RuntimeInitializedClassBuildItem("oracle.jdbc.replay.OracleXADataSourceImpl")); runtimeInitialized.produce(new RuntimeInitializedClassBuildItem("oracle.jdbc.datasource.OracleXAConnection")); diff --git a/extensions/jdbc/jdbc-oracle/deployment/src/main/java/io/quarkus/jdbc/oracle/deployment/OracleNativeImage.java b/extensions/jdbc/jdbc-oracle/deployment/src/main/java/io/quarkus/jdbc/oracle/deployment/OracleNativeImage.java index 8778e677ca1..51053a2fb07 100644 --- a/extensions/jdbc/jdbc-oracle/deployment/src/main/java/io/quarkus/jdbc/oracle/deployment/OracleNativeImage.java +++ b/extensions/jdbc/jdbc-oracle/deployment/src/main/java/io/quarkus/jdbc/oracle/deployment/OracleNativeImage.java @@ -3,7 +3,6 @@ import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem; -import io.quarkus.deployment.builditem.nativeimage.RuntimeInitializedClassBuildItem; /** * @author Sanne Grinovero <sanne@hibernate.org> @@ -35,10 +34,4 @@ void reflection(BuildProducer<ReflectiveClassBuildItem> reflectiveClass) { reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, "com.sun.jndi.rmi.registry.RegistryContextFactory")); } - @BuildStep - void runtimeInitialization(BuildProducer<RuntimeInitializedClassBuildItem> runtimeInitializedClass) { - runtimeInitializedClass - .produce(new RuntimeInitializedClassBuildItem("oracle.jdbc.driver.BlockSource$ThreadedCachingBlockSource")); - } - }
['extensions/jdbc/jdbc-oracle/deployment/src/main/java/io/quarkus/jdbc/oracle/deployment/OracleNativeImage.java', 'extensions/jdbc/jdbc-oracle/deployment/src/main/java/io/quarkus/jdbc/oracle/deployment/OracleMetadataOverrides.java']
{'.java': 2}
2
2
0
0
2
25,499,904
5,033,524
649,418
5,986
1,416
268
21
2
2,367
290
601
68
2
2
1970-01-01T00:27:58
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,241
quarkusio/quarkus/31737/26180
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/26180
https://github.com/quarkusio/quarkus/pull/31737
https://github.com/quarkusio/quarkus/pull/31737
1
fix
OpenShift binary build targeting to another namespace failing
### Describe the bug We have Jenkins running in OpenShift project/namespace (jenkins-namespace) and we have also another namespace(s) where Quarkus applications are deployed. Jenkins is running with Service Account "jenkins" which has access to another namespaces but implicitly "jenkins-namespace" is selected for it. When I try: `mvn clean package -Dquarkus.openshift.namespace=target-namespace-name -Dquarkus.kubernetes.deploy=true` then correct namespace is set in openshift.yaml, but OpenshiftProcessor is then trying to start build in user's current namespace (jenkins-namespace): `[INFO] [io.quarkus.container.image.openshift.deployment.OpenshiftProcessor] Starting (in-cluster) container image build for jar using: BINARY on server: https://serverUrl/ in namespace:jenkins-namespace.` This behaviour could be workarounded by calling `oc project target-namespace-name` beforehand. ### Expected behavior Application is deployed in namespace which is defined by `quarkus.openshift.namespace` property ### Actual behavior Build failure ### How to Reproduce? ``` bash oc project jenkins-namespace mvn clean package -Dquarkus.openshift.namespace=target-namespace-name -Dquarkus.kubernetes.deploy=true ``` ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
bbb56f92d755ac529c4df04147639d88ed2dda39
a88471214e99408f12c99b93b4d858cf64ea857f
https://github.com/quarkusio/quarkus/compare/bbb56f92d755ac529c4df04147639d88ed2dda39...a88471214e99408f12c99b93b4d858cf64ea857f
diff --git a/extensions/container-image/container-image-openshift/deployment/src/main/java/io/quarkus/container/image/openshift/deployment/OpenshiftProcessor.java b/extensions/container-image/container-image-openshift/deployment/src/main/java/io/quarkus/container/image/openshift/deployment/OpenshiftProcessor.java index 3b735804542..f6d78bd7e16 100644 --- a/extensions/container-image/container-image-openshift/deployment/src/main/java/io/quarkus/container/image/openshift/deployment/OpenshiftProcessor.java +++ b/extensions/container-image/container-image-openshift/deployment/src/main/java/io/quarkus/container/image/openshift/deployment/OpenshiftProcessor.java @@ -1,5 +1,6 @@ package io.quarkus.container.image.openshift.deployment; +import static io.quarkus.container.image.openshift.deployment.OpenshiftUtils.getNamespace; import static io.quarkus.container.image.openshift.deployment.OpenshiftUtils.mergeConfig; import static io.quarkus.container.util.PathsUtil.findMainSourcesRoot; import static io.quarkus.deployment.pkg.steps.JarResultBuildStep.DEFAULT_FAST_JAR_DIRECTORY_NAME; @@ -264,7 +265,7 @@ public void openshiftBuildFromJar(OpenshiftConfig openshiftConfig, return; } - try (KubernetesClient kubernetesClient = kubernetesClientBuilder.buildClient()) { + try (KubernetesClient kubernetesClient = buildClient(kubernetesClientBuilder)) { String namespace = Optional.ofNullable(kubernetesClient.getNamespace()).orElse("default"); LOG.info("Starting (in-cluster) container image build for jar using: " + config.buildStrategy + " on server: " + kubernetesClient.getMasterUrl() + " in namespace:" + namespace + "."); @@ -324,7 +325,7 @@ public void openshiftBuildFromNative(OpenshiftConfig openshiftConfig, S2iConfig return; } - try (KubernetesClient kubernetesClient = kubernetesClientBuilder.buildClient()) { + try (KubernetesClient kubernetesClient = buildClient(kubernetesClientBuilder)) { String namespace = Optional.ofNullable(kubernetesClient.getNamespace()).orElse("default"); LOG.info("Starting (in-cluster) container image build for jar using: " + config.buildStrategy + " on server: " @@ -543,6 +544,11 @@ private static KubernetesClientBuilder newClientBuilderWithoutHttp2(Config confi return new KubernetesClientBuilder().withConfig(configuration).withHttpClientFactory(httpClientFactory); } + private static KubernetesClient buildClient(KubernetesClientBuildItem kubernetesClientBuilder) { + getNamespace().ifPresent(kubernetesClientBuilder.getConfig()::setNamespace); + return kubernetesClientBuilder.buildClient(); + } + // visible for test static String concatUnixPaths(String... elements) { StringBuilder result = new StringBuilder(); diff --git a/extensions/container-image/container-image-openshift/deployment/src/main/java/io/quarkus/container/image/openshift/deployment/OpenshiftUtils.java b/extensions/container-image/container-image-openshift/deployment/src/main/java/io/quarkus/container/image/openshift/deployment/OpenshiftUtils.java index 1a3a6c04eac..461c63097c1 100644 --- a/extensions/container-image/container-image-openshift/deployment/src/main/java/io/quarkus/container/image/openshift/deployment/OpenshiftUtils.java +++ b/extensions/container-image/container-image-openshift/deployment/src/main/java/io/quarkus/container/image/openshift/deployment/OpenshiftUtils.java @@ -28,6 +28,9 @@ */ public class OpenshiftUtils { + private static final String OPENSHIFT_NAMESPACE = "quarkus.openshift.namespace"; + private static final String KUBERNETES_NAMESPACE = "quarkus.kubernetes.namespace"; + /** * Wait for the references ImageStreamTags to become available. * @@ -142,4 +145,12 @@ public static OpenshiftConfig mergeConfig(OpenshiftConfig openshiftConfig, S2iCo return result; } + + /** + * @return the openshift namespace set in the OpenShift extension. + */ + public static Optional<String> getNamespace() { + return ConfigProvider.getConfig().getOptionalValue(OPENSHIFT_NAMESPACE, String.class) + .or(() -> ConfigProvider.getConfig().getOptionalValue(KUBERNETES_NAMESPACE, String.class)); + } }
['extensions/container-image/container-image-openshift/deployment/src/main/java/io/quarkus/container/image/openshift/deployment/OpenshiftUtils.java', 'extensions/container-image/container-image-openshift/deployment/src/main/java/io/quarkus/container/image/openshift/deployment/OpenshiftProcessor.java']
{'.java': 2}
2
2
0
0
2
25,456,805
5,025,177
648,376
5,977
1,236
245
21
2
1,558
183
356
48
1
1
1970-01-01T00:27:58
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,242
quarkusio/quarkus/31728/30744
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/30744
https://github.com/quarkusio/quarkus/pull/31728
https://github.com/quarkusio/quarkus/pull/31728
1
fixes
[Quarkus Native] ClassNotFoundException: com.github.benmanes.caffeine.cache.SSSW
### Describe the bug Using the Cache API with ``caffeine`` leads to the following exception when running ``Quarkus 2.16.0.Final`` in ```native``` mode: ``` 2023-01-31 13:56:54,211 ERROR [io.qua.run.Application] (main) Failed to start application (with profile [prod]): java.lang.ClassNotFoundException: com.github.benmanes.caffeine.cache.SSSW at java.base@17.0.5/java.lang.Class.forName(DynamicHub.java:1132) at java.base@17.0.5/java.lang.Class.forName(DynamicHub.java:1105) at com.github.benmanes.caffeine.cache.LocalCacheFactory.loadFactory(LocalCacheFactory.java:84) at com.github.benmanes.caffeine.cache.LocalCacheFactory.newBoundedLocalCache(LocalCacheFactory.java:40) at com.github.benmanes.caffeine.cache.BoundedLocalCache$BoundedLocalAsyncCache.<init>(BoundedLocalCache.java:4216) at com.github.benmanes.caffeine.cache.Caffeine.buildAsync(Caffeine.java:1096) at io.quarkus.cache.runtime.caffeine.CaffeineCacheImpl.<init>(CaffeineCacheImpl.java:71) at io.quarkus.cache.runtime.caffeine.CaffeineCacheManagerBuilder$1.get(CaffeineCacheManagerBuilder.java:56) at io.quarkus.cache.runtime.caffeine.CaffeineCacheManagerBuilder$1.get(CaffeineCacheManagerBuilder.java:34) at io.quarkus.cache.CacheManager_7ace4235729bbc654ace276b403267860dc707de_Synthetic_Bean.createSynthetic(Unknown Source) at io.quarkus.cache.CacheManager_7ace4235729bbc654ace276b403267860dc707de_Synthetic_Bean.create(Unknown Source) at io.quarkus.cache.CacheManager_7ace4235729bbc654ace276b403267860dc707de_Synthetic_Bean.create(Unknown Source) at io.quarkus.arc.impl.AbstractSharedContext.createInstanceHandle(AbstractSharedContext.java:113) at io.quarkus.arc.impl.AbstractSharedContext$1.get(AbstractSharedContext.java:37) at io.quarkus.arc.impl.AbstractSharedContext$1.get(AbstractSharedContext.java:34) at io.quarkus.arc.impl.LazyValue.get(LazyValue.java:26) at io.quarkus.arc.impl.ComputingCache.computeIfAbsent(ComputingCache.java:69) at io.quarkus.arc.impl.AbstractSharedContext.get(AbstractSharedContext.java:34) at io.quarkus.arc.impl.ClientProxies.getApplicationScopedDelegate(ClientProxies.java:21) at io.quarkus.cache.CacheManager_7ace4235729bbc654ace276b403267860dc707de_Synthetic_ClientProxy.arc$delegate(Unknown Source) at io.quarkus.cache.CacheManager_7ace4235729bbc654ace276b403267860dc707de_Synthetic_ClientProxy.getCacheNames(Unknown Source) at io.quarkus.cache.runtime.CacheManagerInitializer.onStartup(CacheManagerInitializer.java:14) at java.base@17.0.5/java.lang.reflect.Method.invoke(Method.java:568) at io.quarkus.arc.impl.Reflections.invokeMethod(Reflections.java:170) at io.quarkus.cache.runtime.CacheManagerInitializer_Observer_onStartup_8dc69ad76cf9cc31e6928ed65580a8d3fd18a734.notify(Unknown Source) at io.quarkus.arc.impl.EventImpl$Notifier.notifyObservers(EventImpl.java:328) at io.quarkus.arc.impl.EventImpl$Notifier.notify(EventImpl.java:310) at io.quarkus.arc.impl.EventImpl.fire(EventImpl.java:78) at io.quarkus.arc.runtime.ArcRecorder.fireLifecycleEvent(ArcRecorder.java:131) at io.quarkus.arc.runtime.ArcRecorder.handleLifecycleEvents(ArcRecorder.java:100) at io.quarkus.deployment.steps.LifecycleEventsBuildStep$startupEvent1144526294.deploy_0(Unknown Source) at io.quarkus.deployment.steps.LifecycleEventsBuildStep$startupEvent1144526294.deploy(Unknown Source) at io.quarkus.runner.ApplicationImpl.doStart(Unknown Source) at io.quarkus.runtime.Application.start(Application.java:101) at io.quarkus.runtime.ApplicationLifecycleManager.run(ApplicationLifecycleManager.java:108) at io.quarkus.runtime.Quarkus.run(Quarkus.java:71) at io.quarkus.runtime.Quarkus.run(Quarkus.java:44) at io.quarkus.runtime.Quarkus.run(Quarkus.java:124) at io.quarkus.runner.GeneratedMain.main(Unknown Source) ``` ### Expected behavior _No response_ ### Actual behavior This issue is related to the ``native`` mode only. The ``JVM`` mode is working just fine. It also looks like it's just an issue with ```2.16.0.Final```, with ```2.15.3.Final``` everything works as expected, even in the ``native`` mode. ### How to Reproduce? 1. Define a ``Quarkus 2.16.0.Final`` dependency 2. Add the ``@CacheResult`` annotation to an interceptable method 3. Run your app in ``native`` mode ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` openjdk 17.0.2 2022-01-18 ### GraalVM version (if different from Java) GraalVM 22.3.0 Java 17 CE ### Quarkus version or git rev Quarkus 2.16.0.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) mvn ### Additional information The native build is conducted with the help of ``quay.io/quarkus/ubi-quarkus-native-image:22.3-java17``
3d53ddf3c8612504f325bd23ea6d07f65040ac0e
8746898ebbf3861c7ab4b300a2ac91ee0d2ba09f
https://github.com/quarkusio/quarkus/compare/3d53ddf3c8612504f325bd23ea6d07f65040ac0e...8746898ebbf3861c7ab4b300a2ac91ee0d2ba09f
diff --git a/extensions/caffeine/runtime/src/main/java/io/quarkus/caffeine/runtime/graal/CacheConstructorsFeature.java b/extensions/caffeine/runtime/src/main/java/io/quarkus/caffeine/runtime/graal/CacheConstructorsFeature.java index 8456a80860c..ac2bf2db5b4 100644 --- a/extensions/caffeine/runtime/src/main/java/io/quarkus/caffeine/runtime/graal/CacheConstructorsFeature.java +++ b/extensions/caffeine/runtime/src/main/java/io/quarkus/caffeine/runtime/graal/CacheConstructorsFeature.java @@ -80,6 +80,8 @@ public static String[] typesNeedingConstructorsRegistered() { "com.github.benmanes.caffeine.cache.PSMS", "com.github.benmanes.caffeine.cache.PSW", "com.github.benmanes.caffeine.cache.PSMW", + "com.github.benmanes.caffeine.cache.PSAMW", + "com.github.benmanes.caffeine.cache.PSAWMW", "com.github.benmanes.caffeine.cache.PSWMS", "com.github.benmanes.caffeine.cache.PSWMW", "com.github.benmanes.caffeine.cache.SILMS", @@ -88,6 +90,7 @@ public static String[] typesNeedingConstructorsRegistered() { "com.github.benmanes.caffeine.cache.SSLMS", "com.github.benmanes.caffeine.cache.SSMS", "com.github.benmanes.caffeine.cache.SSMSA", + "com.github.benmanes.caffeine.cache.SSMSAW", "com.github.benmanes.caffeine.cache.SSMSW", "com.github.benmanes.caffeine.cache.SSW", }; @@ -102,6 +105,7 @@ public static String[] typesNeedingConstructorsRegisteredWhenRecordingStats() { "com.github.benmanes.caffeine.cache.SSSMS", "com.github.benmanes.caffeine.cache.SSSMSA", "com.github.benmanes.caffeine.cache.SSSMSW", + "com.github.benmanes.caffeine.cache.SSSMSAW", "com.github.benmanes.caffeine.cache.SSSW" }; }
['extensions/caffeine/runtime/src/main/java/io/quarkus/caffeine/runtime/graal/CacheConstructorsFeature.java']
{'.java': 1}
1
1
0
0
1
25,460,564
5,025,732
648,444
5,977
247
66
4
1
4,974
259
1,312
84
0
4
1970-01-01T00:27:58
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,243
quarkusio/quarkus/31726/31722
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/31722
https://github.com/quarkusio/quarkus/pull/31726
https://github.com/quarkusio/quarkus/pull/31726
1
fix
Multiple duplicate traces when deploying into Kubernetes
### Describe the bug When performing a deployment to Kubernetes, I can see these duplicate traces: ``` [INFO] [io.quarkus.kubernetes.deployment.KubernetesDeploy] Kubernetes API Server at 'https://127.0.0.1:38293/' successfully contacted. [INFO] [io.quarkus.kubernetes.deployment.KubernetesDeploy] Kubernetes API Server at 'https://127.0.0.1:38293/' successfully contacted. [INFO] [io.quarkus.kubernetes.deployment.KubernetesDeploy] Kubernetes API Server at 'https://127.0.0.1:38293/' successfully contacted. [INFO] [io.quarkus.kubernetes.deployment.KubernetesDeploy] Kubernetes API Server at 'https://127.0.0.1:38293/' successfully contacted. [INFO] [io.quarkus.deployment.pkg.steps.JarResultBuildStep] The decompiled output can be found at: /home/jcarvaja/sources/personal/quarkus-examples/kubernetes-docker/target/decompiled ``` ### Expected behavior This trace should be printed only once. ### Actual behavior _No response_ ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
bbb56f92d755ac529c4df04147639d88ed2dda39
3093492e8e88dcbcc455f8f2ff62f4de24b97708
https://github.com/quarkusio/quarkus/compare/bbb56f92d755ac529c4df04147639d88ed2dda39...3093492e8e88dcbcc455f8f2ff62f4de24b97708
diff --git a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesDeploy.java b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesDeploy.java index 7961676eab0..d2acba0da79 100644 --- a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesDeploy.java +++ b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesDeploy.java @@ -65,7 +65,7 @@ private Result doCheck(KubernetesClientBuildItem clientBuilder) { + masterURL + "' could not be determined. Please ensure that a valid token is being used.")); } - log.info("Kubernetes API Server at '" + masterURL + "' successfully contacted."); + log.debugf("Kubernetes API Server at '" + masterURL + "' successfully contacted."); log.debugf("Kubernetes Version: %s.%s", version.getMajor(), version.getMinor()); serverFound = true; return Result.enabled(); diff --git a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesDeployer.java b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesDeployer.java index 0bc527a2f9d..d98164e5551 100644 --- a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesDeployer.java +++ b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesDeployer.java @@ -72,7 +72,7 @@ public void selectDeploymentTarget(ContainerImageInfoBuildItem containerImageInf Optional<String> activeContainerImageCapability = ContainerImageCapabilitiesUtil .getActiveContainerImageCapability(capabilities); - //If container image actions are explicilty disabled block deployment even if a container image capability is not present. + //If container image actions are explicitly disabled block deployment even if a container image capability is not present. if (!containerImageConfig.isBuildExplicitlyDisabled() && !containerImageConfig.isPushExplicitlyDisabled() && activeContainerImageCapability.isEmpty()) { // we can't throw an exception here, because it could prevent the Kubernetes resources from being generated
['extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesDeploy.java', 'extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesDeployer.java']
{'.java': 2}
2
2
0
0
2
25,456,805
5,025,177
648,376
5,977
454
80
4
2
1,312
136
330
47
4
1
1970-01-01T00:27:58
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,453
quarkusio/quarkus/24711/24704
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24704
https://github.com/quarkusio/quarkus/pull/24711
https://github.com/quarkusio/quarkus/pull/24711
1
close
Gradle quarkusIntTest and testNative tasks should not depend on check
### Describe the bug The `quarkusIntTest` and `testNative` gradle tasks add a dependency on `check`. I believe this dependency is backwards - `check` should instead depend on the `Test` tasks. This causes a circular dependency issue with our build because we run a `jacocoCoverageVerification` task after all test tasks and `jacocoCoverageVerification` is set as a dependency of `check`. Relevant gradle configuration snippet ``` tasks.register('jacocoCoverageVerification') { ... } check.dependsOn(jacocoCoverageVerification) tasks.withType(Test) { task -> jacocoCoverageVerification.dependsOn(task) } ``` Error output ``` Circular dependency between the following tasks: :check \\--- :jacocoCoverageVerification +--- :quarkusIntTest | \\--- :check (*) \\--- :testNative \\--- :check (*) ``` ### Expected behavior `check` should depend on the registered `Test` tasks ### Actual behavior `Test` tasks depend on `check` ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` Darwin Kernel Version 21.3.0 ### Output of `java -version` openjdk version "11.0.11" ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.8.0.CR1 ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Gradle 7.4.2 ### Additional information _No response_
9aab340b4d9a1890a1d821e43fdcfd77d7c95662
17b51b899350bd1f5af5d72e88298015f3a00c43
https://github.com/quarkusio/quarkus/compare/9aab340b4d9a1890a1d821e43fdcfd77d7c95662...17b51b899350bd1f5af5d72e88298015f3a00c43
diff --git a/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/QuarkusPlugin.java b/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/QuarkusPlugin.java index cef5d097ac7..c3d56ef8604 100644 --- a/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/QuarkusPlugin.java +++ b/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/QuarkusPlugin.java @@ -20,7 +20,6 @@ import org.gradle.api.artifacts.ConfigurationContainer; import org.gradle.api.artifacts.ProjectDependency; import org.gradle.api.plugins.BasePlugin; -import org.gradle.api.plugins.JavaBasePlugin; import org.gradle.api.plugins.JavaPlugin; import org.gradle.api.plugins.JavaPluginConvention; import org.gradle.api.tasks.SourceSet; @@ -263,7 +262,7 @@ public void execute(Task test) { tasks.register(INTEGRATION_TEST_TASK_NAME, Test.class, intTestTask -> { intTestTask.setGroup("verification"); intTestTask.setDescription("Runs Quarkus integration tests"); - intTestTask.dependsOn(quarkusBuild, tasks.named(JavaBasePlugin.CHECK_TASK_NAME)); + intTestTask.dependsOn(quarkusBuild, tasks.named(JavaPlugin.TEST_TASK_NAME)); intTestTask.setClasspath(intTestSourceSet.getRuntimeClasspath()); intTestTask.setTestClassesDirs(intTestSourceSet.getOutput().getClassesDirs()); }); @@ -283,7 +282,7 @@ public void execute(Task test) { tasks.register(TEST_NATIVE_TASK_NAME, Test.class, testNative -> { testNative.setDescription("Runs native image tests"); testNative.setGroup("verification"); - testNative.dependsOn(quarkusBuild, tasks.named(JavaBasePlugin.CHECK_TASK_NAME)); + testNative.dependsOn(quarkusBuild, tasks.named(JavaPlugin.TEST_TASK_NAME)); testNative.setTestClassesDirs(project.files(nativeTestSourceSet.getOutput().getClassesDirs(), intTestSourceSet.getOutput().getClassesDirs())); diff --git a/integration-tests/gradle/src/test/java/io/quarkus/gradle/IntegrationTestBuildTest.java b/integration-tests/gradle/src/test/java/io/quarkus/gradle/IntegrationTestBuildTest.java index c1745dba95a..1145c1a07f1 100644 --- a/integration-tests/gradle/src/test/java/io/quarkus/gradle/IntegrationTestBuildTest.java +++ b/integration-tests/gradle/src/test/java/io/quarkus/gradle/IntegrationTestBuildTest.java @@ -15,7 +15,6 @@ public void shouldRunIntegrationTestAsPartOfBuild() throws Exception { BuildResult buildResult = runGradleWrapper(projectDir, "clean", "quarkusIntTest"); assertThat(buildResult.getTasks().get(":test")).isEqualTo(BuildResult.SUCCESS_OUTCOME); - assertThat(buildResult.getTasks().get(":check")).isEqualTo(BuildResult.SUCCESS_OUTCOME); assertThat(buildResult.getTasks().get(":quarkusIntTest")).isEqualTo(BuildResult.SUCCESS_OUTCOME); }
['devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/QuarkusPlugin.java', 'integration-tests/gradle/src/test/java/io/quarkus/gradle/IntegrationTestBuildTest.java']
{'.java': 2}
2
2
0
0
2
20,297,884
3,926,453
515,619
4,972
462
95
5
1
1,374
177
350
64
0
2
1970-01-01T00:27:28
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,450
quarkusio/quarkus/24732/24712
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/24712
https://github.com/quarkusio/quarkus/pull/24732
https://github.com/quarkusio/quarkus/pull/24732
1
resolves
dev mode Startup time regression between 2.7.5.Final and 2.8.0.CR1
### Describe the bug I noticed a slight regression in dev mode startup time between 2.7.5.Final and 2.8.0.CR1. A bit of testing showed cf388350609ff4b108dacd09a187523d35b6fc4c (#24398) as main contributor. average of 3 runs: 2.8.0.CR1 mvn quarkus:dev: 2170ms force restart (s) 532ms 2.7.5.Final mvn quarkus:dev: 1850ms force restart (s) 189ms 2.8.0.Final and 2.8.0.CR1 behave the same regarding dev mode startup time. ### Expected behavior _No response_ ### Actual behavior _No response_ ### How to Reproduce? Download the reproducer, or just generate any quarkus app: [profiling.zip](https://github.com/quarkusio/quarkus/files/8403295/profiling.zip) mvn quarkus:dev. Take not about the reported startup time. change version to 2.7.5.Final mvn quarkus:dev. Take not about the reported startup time. Way faster. ### Output of `uname -a` or `ver` Microsoft Windows [Version 10.0.22000.556] ### Output of `java -version` openjdk 17.0.1 2021-10-19 OpenJDK Runtime Environment Temurin-17.0.1+12 (build 17.0.1+12) OpenJDK 64-Bit Server VM Temurin-17.0.1+12 (build 17.0.1+12, mixed mode, sharing) ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.7.5.Final, 2.8.0.CR1 ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.3 (ff8e977a158738155dc465c6a97ffaf31982d739) Maven home: C:\\tools\\java\\maven Java version: 17.0.1, vendor: Eclipse Adoptium, runtime: C:\\tools\\java\\17-temurin Default locale: de_DE, platform encoding: Cp1252 OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows" ### Additional information _No response_
0dbe4345642825cc59ab060775506a9c0cf646e9
3133199cbb457886e53e8a11131ef35561da01ce
https://github.com/quarkusio/quarkus/compare/0dbe4345642825cc59ab060775506a9c0cf646e9...3133199cbb457886e53e8a11131ef35561da01ce
diff --git a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ComponentsProviderGenerator.java b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ComponentsProviderGenerator.java index 8107dcdf3a8..2a2a4564505 100644 --- a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ComponentsProviderGenerator.java +++ b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ComponentsProviderGenerator.java @@ -410,6 +410,11 @@ public RemovedBeanAdder(ClassCreator componentsProvider, MethodCreator getCompon this.typeCache = new MapTypeCache(); } + @Override + protected int groupLimit() { + return 5; + } + @Override MethodCreator newAddMethod() { // Clear the shared maps for each addRemovedBeansX() method @@ -687,7 +692,7 @@ public void close() { void addComponent(T component) { - if (addMethod == null || componentsAdded >= GROUP_LIMIT) { + if (addMethod == null || componentsAdded >= groupLimit()) { if (addMethod != null) { addMethod.returnValue(null); } @@ -709,6 +714,10 @@ void addComponent(T component) { abstract void addComponentInternal(T component); + protected int groupLimit() { + return GROUP_LIMIT; + } + } // This wrapper is needed because AnnotationInstance#equals() compares the annotation target
['independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ComponentsProviderGenerator.java']
{'.java': 1}
1
1
0
0
1
20,298,500
3,926,524
515,632
4,972
321
62
11
1
1,693
206
559
57
1
0
1970-01-01T00:27:29
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,430
quarkusio/quarkus/25442/23939
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/23939
https://github.com/quarkusio/quarkus/pull/25442
https://github.com/quarkusio/quarkus/pull/25442
1
fixes
Optional not working with @QueryParam in BeanParam
### Describe the bug When using @QueryParam in conjunction with @BeanParam Optional fields are not working. I'm using resteasy-reactive ### Expected behavior We can automatically wrap null in Optional to have a nicer developper experience and have our code behave in BeanParam the same way it does with plain controller ### Actual behavior We have a null instead of an Optional.empty() ### How to Reproduce? Reproducer: 1. Create a quarkus project with version 2.7.2.Final 2. Add the reasteasy-reactive and resteasy-reactive-jackson extension 3. Create a controller using a BeanParam and a Bean to receive the params here the bean: ```java @AllArgsConstructor @NoArgsConstructor @Getter @Setter @Slf4j public class PageQuery { public static final Integer DEFAULT_PAGE = 0; public static final Integer DEFAULT_SIZE = 10; public static final Integer MAX_SIZE = 10; @QueryParam("page") private Optional<Integer> rawPage; @QueryParam("size") private Optional<Integer> rawSize; @QueryParam("sort") private Optional<String> sort; /** * Transforms the POJO to a Pageable for easy use with Spring repository * * @return */ public Pageable toPageable() { final var page = rawPage.orElse(DEFAULT_PAGE); // we limit the max size here final var size = Integer.max(rawPage.orElse(DEFAULT_SIZE), MAX_SIZE); log.info("page: " + rawPage + ", size: " + rawSize+ ", " + sort); return sort.map(s -> { final var r = s.split(","); final var column = r[0]; final var direction = Sort.Direction.fromString(r[1]); return PageRequest.of(page, size, Sort.by(direction, column)); }).orElse(PageRequest.of(page, size)); } } ``` 4. Use it in a Controller with the @BeanParam annotation ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.7.2.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) maven ### Additional information _No response_
1e6a7c1b63bf7acde0adec4189ce131234111aab
0f598a0d09a622574556e1de3ad85f7e2d422c94
https://github.com/quarkusio/quarkus/compare/1e6a7c1b63bf7acde0adec4189ce131234111aab...0f598a0d09a622574556e1de3ad85f7e2d422c94
diff --git a/independent-projects/resteasy-reactive/server/processor/src/main/java/org/jboss/resteasy/reactive/server/processor/scanning/ClassInjectorTransformer.java b/independent-projects/resteasy-reactive/server/processor/src/main/java/org/jboss/resteasy/reactive/server/processor/scanning/ClassInjectorTransformer.java index 13d5a2033bd..0612350b0c8 100644 --- a/independent-projects/resteasy-reactive/server/processor/src/main/java/org/jboss/resteasy/reactive/server/processor/scanning/ClassInjectorTransformer.java +++ b/independent-projects/resteasy-reactive/server/processor/src/main/java/org/jboss/resteasy/reactive/server/processor/scanning/ClassInjectorTransformer.java @@ -356,10 +356,13 @@ private void injectParameterWithConverter(MethodVisitor injectMethod, String met } // push the parameter value loadParameter(injectMethod, methodName, extractor, extraSingleParameter, extraEncodedParam, encoded); - Label valueWasNull = new Label(); - // dup to test it - injectMethod.visitInsn(Opcodes.DUP); - injectMethod.visitJumpInsn(Opcodes.IFNULL, valueWasNull); + Label valueWasNull = null; + if (!extractor.isOptional()) { + valueWasNull = new Label(); + // dup to test it + injectMethod.visitInsn(Opcodes.DUP); + injectMethod.visitJumpInsn(Opcodes.IFNULL, valueWasNull); + } convertParameter(injectMethod, extractor, fieldInfo); // inject this (for the put field) before the injected value injectMethod.visitIntInsn(Opcodes.ALOAD, 0); @@ -377,8 +380,10 @@ private void injectParameterWithConverter(MethodVisitor injectMethod, String met Label endLabel = new Label(); injectMethod.visitJumpInsn(Opcodes.GOTO, endLabel); - // if the value was null, we don't set it - injectMethod.visitLabel(valueWasNull); + if (valueWasNull != null) { + // if the value was null, we don't set it + injectMethod.visitLabel(valueWasNull); + } // we have a null value for the object we wanted to inject on the stack injectMethod.visitInsn(Opcodes.POP); diff --git a/independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/SimpleBeanParam.java b/independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/SimpleBeanParam.java index 0e3275bab85..4914d832f7d 100644 --- a/independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/SimpleBeanParam.java +++ b/independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/SimpleBeanParam.java @@ -1,6 +1,7 @@ package org.jboss.resteasy.reactive.server.vertx.test.simple; import java.util.List; +import java.util.Optional; import javax.ws.rs.BeanParam; import javax.ws.rs.DefaultValue; import javax.ws.rs.HeaderParam; @@ -62,6 +63,15 @@ public class SimpleBeanParam { @QueryParam("query") List<MyParameter> myParameterList; + @QueryParam("missing") + Optional<String> missingOptionalString; + + @QueryParam("query") + Optional<String> optionalQuery; + + @QueryParam("query") + Optional<ParameterWithFromString> optionalParameterWithFromString; + public void check(String path) { Assertions.assertEquals("one-query", query); Assertions.assertEquals("one-query", privateQuery); @@ -84,5 +94,8 @@ public void check(String path) { Assertions.assertEquals(42, missingPrimitiveParamWithDefaultValue); Assertions.assertEquals("one-queryone-query", myParameter.toString()); Assertions.assertEquals("one-queryone-query", myParameterList.get(0).toString()); + Assertions.assertTrue(missingOptionalString.isEmpty()); + Assertions.assertEquals("one-query", optionalQuery.get()); + Assertions.assertEquals("ParameterWithFromString[val=one-query]", optionalParameterWithFromString.get().toString()); } }
['independent-projects/resteasy-reactive/server/processor/src/main/java/org/jboss/resteasy/reactive/server/processor/scanning/ClassInjectorTransformer.java', 'independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/SimpleBeanParam.java']
{'.java': 2}
2
2
0
0
2
20,545,659
3,973,841
521,678
5,009
784
158
17
1
2,217
283
512
88
0
1
1970-01-01T00:27:32
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,429
quarkusio/quarkus/25443/25444
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/25444
https://github.com/quarkusio/quarkus/pull/25443
https://github.com/quarkusio/quarkus/pull/25443
1
fixes
Fix comparison in ensureProjectCoords method in AppModelGradleResolver class
### Describe the bug In the method ensureProjectCoords, appArtifact.getGroupId() and appArtifact.getVersion() are compared against themselves in an if statement, when they should be compared to project.getGroup() and project.getVersion() respectively. ``` if (project.getName().equals(appArtifact.getArtifactId()) && appArtifact.getGroupId().equals(appArtifact.getGroupId()) && appArtifact.getVersion().equals(appArtifact.getVersion())) { return; } ``` ### Expected behavior _No response_ ### Actual behavior _No response_ ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` _No response_ ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev _No response_ ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
1e6a7c1b63bf7acde0adec4189ce131234111aab
e6063b7f1c6c85b8fff9844e2e263ce51631ebc2
https://github.com/quarkusio/quarkus/compare/1e6a7c1b63bf7acde0adec4189ce131234111aab...e6063b7f1c6c85b8fff9844e2e263ce51631ebc2
diff --git a/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/AppModelGradleResolver.java b/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/AppModelGradleResolver.java index 478c34ea9cc..5aef8898fc8 100644 --- a/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/AppModelGradleResolver.java +++ b/devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/AppModelGradleResolver.java @@ -167,8 +167,8 @@ public ApplicationModel resolveManagedModel(ArtifactCoords appArtifact, protected void ensureProjectCoords(ArtifactCoords appArtifact) throws AppModelResolverException { if (project.getName().equals(appArtifact.getArtifactId()) - && appArtifact.getGroupId().equals(appArtifact.getGroupId()) - && appArtifact.getVersion().equals(appArtifact.getVersion())) { + && project.getGroup().toString().equals(appArtifact.getGroupId()) + && project.getVersion().toString().equals(appArtifact.getVersion())) { return; } throw new AppModelResolverException(
['devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/AppModelGradleResolver.java']
{'.java': 1}
1
1
0
0
1
20,545,659
3,973,841
521,678
5,009
329
52
4
1
928
107
199
47
0
1
1970-01-01T00:27:32
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,428
quarkusio/quarkus/25478/25455
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/25455
https://github.com/quarkusio/quarkus/pull/25478
https://github.com/quarkusio/quarkus/pull/25478
1
fixes
Unused `quarkus-smallrye-graphql` extension break Quarkus scenario in combination with other extensions
### Describe the bug ### JDK17 / Quarkus Upstream When I add the extension `quarkus-smallrye-graphql` to [this](https://github.com/quarkus-qe/quarkus-jdkspecifics/tree/main/jdk17/jaxrs-panache) project I am getting the following error: ``` 16:11:43,967 INFO [app] 16:11:42,936 HTTP Request to /fruits failed, error id: 47c7fa9e-ab25-4f7c-89b3-30ccda5106b9-1: javax.validation.ValidationException: HV000149: An exception occurred during message interpolation 16:11:43,968 INFO [app] at org.hibernate.validator.internal.engine.validationcontext.AbstractValidationContext.interpolate(AbstractValidationContext.java:331) 16:11:43,969 INFO [app] at org.hibernate.validator.internal.engine.validationcontext.AbstractValidationContext.addConstraintFailure(AbstractValidationContext.java:231) 16:11:43,969 INFO [app] at org.hibernate.validator.internal.engine.validationcontext.ParameterExecutableValidationContext.addConstraintFailure(ParameterExecutableValidationContext.java:38) 16:11:43,970 INFO [app] at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:79) 16:11:43,971 INFO [app] at org.hibernate.validator.internal.metadata.core.MetaConstraint.doValidateConstraint(MetaConstraint.java:130) 16:11:43,971 INFO [app] at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:123) 16:11:43,972 INFO [app] at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:555) 16:11:43,972 INFO [app] at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForSingleDefaultGroupElement(ValidatorImpl.java:518) 16:11:43,973 INFO [app] at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:488) 16:11:43,973 INFO [app] at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:450) 16:11:43,974 INFO [app] at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:400) 16:11:43,974 INFO [app] at org.hibernate.validator.internal.engine.ValidatorImpl.validateCascadedAnnotatedObjectForCurrentGroup(ValidatorImpl.java:629) 16:11:43,975 INFO [app] at org.hibernate.validator.internal.engine.ValidatorImpl.validateCascadedConstraints(ValidatorImpl.java:590) 16:11:43,975 INFO [app] at org.hibernate.validator.internal.engine.ValidatorImpl.validateParametersInContext(ValidatorImpl.java:880) 16:11:43,976 INFO [app] at org.hibernate.validator.internal.engine.ValidatorImpl.validateParameters(ValidatorImpl.java:283) 16:11:43,976 INFO [app] at org.hibernate.validator.internal.engine.ValidatorImpl.validateParameters(ValidatorImpl.java:235) 16:11:43,977 INFO [app] at io.quarkus.hibernate.validator.runtime.interceptor.AbstractMethodValidationInterceptor.validateMethodInvocation(AbstractMethodValidationInterceptor.java:60) 16:11:43,978 INFO [app] at io.quarkus.hibernate.validator.runtime.jaxrs.JaxrsEndPointValidationInterceptor.validateMethodInvocation(JaxrsEndPointValidationInterceptor.java:35) 16:11:43,978 INFO [app] at io.quarkus.hibernate.validator.runtime.jaxrs.JaxrsEndPointValidationInterceptor_Bean.intercept(Unknown Source) 16:11:43,979 INFO [app] at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41) 16:11:43,979 INFO [app] at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:50) 16:11:43,980 INFO [app] at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:133) 16:11:43,980 INFO [app] at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:104) 16:11:43,981 INFO [app] at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired.doIntercept(TransactionalInterceptorRequired.java:38) 16:11:43,981 INFO [app] at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.intercept(TransactionalInterceptorBase.java:58) 16:11:43,981 INFO [app] at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired.intercept(TransactionalInterceptorRequired.java:32) 16:11:43,982 INFO [app] at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequired_Bean.intercept(Unknown Source) 16:11:43,982 INFO [app] at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41) 16:11:43,982 INFO [app] at io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:41) 16:11:43,983 INFO [app] at io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:32) 16:11:43,983 INFO [app] at io.quarkus.ts.jdk17.resources.FruitsResource_Subclass.add(Unknown Source) 16:11:43,983 INFO [app] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 16:11:43,984 INFO [app] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) 16:11:43,984 INFO [app] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 16:11:43,984 INFO [app] at java.base/java.lang.reflect.Method.invoke(Method.java:568) 16:11:43,985 INFO [app] at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:170) 16:11:43,985 INFO [app] at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:130) 16:11:43,985 INFO [app] at org.jboss.resteasy.core.ResourceMethodInvoker.internalInvokeOnTarget(ResourceMethodInvoker.java:660) 16:11:43,985 INFO [app] at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTargetAfterFilter(ResourceMethodInvoker.java:524) 16:11:43,986 INFO [app] at org.jboss.resteasy.core.ResourceMethodInvoker.lambda$invokeOnTarget$2(ResourceMethodInvoker.java:474) 16:11:43,986 INFO [app] at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364) 16:11:43,986 INFO [app] at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:476) 16:11:43,987 INFO [app] at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:434) 16:11:43,987 INFO [app] at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:408) 16:11:43,987 INFO [app] at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:69) 16:11:43,988 INFO [app] at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:492) 16:11:43,988 INFO [app] at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:261) 16:11:43,988 INFO [app] at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:161) 16:11:43,988 INFO [app] at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364) 16:11:43,989 INFO [app] at org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:164) 16:11:43,989 INFO [app] at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:247) 16:11:43,989 INFO [app] at io.quarkus.resteasy.runtime.standalone.RequestDispatcher.service(RequestDispatcher.java:73) 16:11:43,989 INFO [app] at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.dispatch(VertxRequestHandler.java:151) 16:11:43,990 INFO [app] at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler$1.run(VertxRequestHandler.java:91) 16:11:43,990 INFO [app] at io.quarkus.vertx.core.runtime.VertxCoreRecorder$14.runWith(VertxCoreRecorder.java:548) 16:11:43,990 INFO [app] at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) 16:11:43,991 INFO [app] at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478) 16:11:43,991 INFO [app] at org.jboss.threads.DelegatingRunnable.run(DelegatingRunnable.java:29) 16:11:43,991 INFO [app] at org.jboss.threads.ThreadLocalResettingRunnable.run(ThreadLocalResettingRunnable.java:29) 16:11:43,991 INFO [app] at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) 16:11:43,991 INFO [app] at java.base/java.lang.Thread.run(Thread.java:833) 16:11:43,992 INFO [app] Caused by: java.lang.NullPointerException: Cannot invoke "io.smallrye.graphql.execution.context.SmallRyeContext.unwrap(java.lang.Class)" because "smallRyeContext" is null 16:11:43,992 INFO [app] at io.quarkus.smallrye.graphql.runtime.SmallRyeGraphQLLocaleResolver.getHeaders(SmallRyeGraphQLLocaleResolver.java:53) 16:11:43,992 INFO [app] at io.quarkus.smallrye.graphql.runtime.SmallRyeGraphQLLocaleResolver.getAcceptableLanguages(SmallRyeGraphQLLocaleResolver.java:40) 16:11:43,992 INFO [app] at io.quarkus.smallrye.graphql.runtime.SmallRyeGraphQLLocaleResolver.resolve(SmallRyeGraphQLLocaleResolver.java:27) 16:11:43,993 INFO [app] at io.quarkus.hibernate.validator.runtime.locale.LocaleResolversWrapper.resolve(LocaleResolversWrapper.java:27) 16:11:43,993 INFO [app] at org.hibernate.validator.messageinterpolation.AbstractMessageInterpolator.interpolate(AbstractMessageInterpolator.java:343) 16:11:43,993 INFO [app] at org.hibernate.validator.internal.engine.validationcontext.AbstractValidationContext.interpolate(AbstractValidationContext.java:322) 16:11:43,993 INFO [app] ... 60 more ``` **Note that the extension `quarkus-smallrye-graphql` is not used.** Works with Quarkus 2.8.3.Final and previous Quarkus upstream Versions (999-SNAPSHOT) around 7 days older than the current version. [DailyBuilds](https://github.com/quarkus-qe/quarkus-jdkspecifics/actions) [Scenario]( https://github.com/quarkus-qe/quarkus-jdkspecifics) `git clone git@github.com:quarkus-qe/quarkus-jdkspecifics.git` Success: `mvn clean verify -Dquarkus.platform.version=2.8.3.Final -PJDK17 -pl jdk17/jaxrs-panache` Fail: `mvn clean verify -PJDK17 -pl jdk17/jaxrs-panache` PR that fixes this issue: https://github.com/quarkus-qe/quarkus-jdkspecifics/pull/31 If you want to reproduce the issue, be sure that `quarkus-smallrye-graphql` is on `jdk17/jaxrs-panache` pom.xml ### Output of `java -version` openjdk version "17.0.1" 2021-10-19 OpenJDK Runtime Environment Temurin-17.0.1+12 (build 17.0.1+12) OpenJDK 64-Bit Server VM Temurin-17.0.1+12 (build 17.0.1+12, mixed mode, sharing) ### Quarkus version or git rev 999-SNAPSHOT
bd8d92b7b77311c612b76232084e9c3e2b16b02c
3319c8a59d195ee0d3fb8636fa4f61a6d0a243b1
https://github.com/quarkusio/quarkus/compare/bd8d92b7b77311c612b76232084e9c3e2b16b02c...3319c8a59d195ee0d3fb8636fa4f61a6d0a243b1
diff --git a/extensions/smallrye-graphql/runtime/src/main/java/io/quarkus/smallrye/graphql/runtime/SmallRyeGraphQLLocaleResolver.java b/extensions/smallrye-graphql/runtime/src/main/java/io/quarkus/smallrye/graphql/runtime/SmallRyeGraphQLLocaleResolver.java index 0244db42e3c..0bba02a64c0 100644 --- a/extensions/smallrye-graphql/runtime/src/main/java/io/quarkus/smallrye/graphql/runtime/SmallRyeGraphQLLocaleResolver.java +++ b/extensions/smallrye-graphql/runtime/src/main/java/io/quarkus/smallrye/graphql/runtime/SmallRyeGraphQLLocaleResolver.java @@ -50,7 +50,11 @@ private Optional<List<Locale.LanguageRange>> getAcceptableLanguages() { @SuppressWarnings("unchecked") private Map<String, List<String>> getHeaders() { SmallRyeContext smallRyeContext = SmallRyeContextManager.getCurrentSmallRyeContext(); - DataFetchingEnvironment dfe = smallRyeContext.unwrap(DataFetchingEnvironment.class); - return (Map<String, List<String>>) dfe.getGraphQlContext().get("httpHeaders"); + if (smallRyeContext != null) { + DataFetchingEnvironment dfe = smallRyeContext.unwrap(DataFetchingEnvironment.class); + return (Map<String, List<String>>) dfe.getGraphQlContext().get("httpHeaders"); + } else { + return null; + } } }
['extensions/smallrye-graphql/runtime/src/main/java/io/quarkus/smallrye/graphql/runtime/SmallRyeGraphQLLocaleResolver.java']
{'.java': 1}
1
1
0
0
1
20,554,378
3,975,502
521,855
5,009
466
99
8
1
11,103
504
2,910
103
4
1
1970-01-01T00:27:32
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,427
quarkusio/quarkus/25512/23573
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/23573
https://github.com/quarkusio/quarkus/pull/25512
https://github.com/quarkusio/quarkus/pull/25512
1
fixes
Confusing, if not downright wrong, warning message
### Describe the bug I run my app in dev mode. I change a build time property in `application.properties` and the application properly restarts but I get the following warning in the console: ```java 2022-02-10 09:57:08,244 WARN [io.qua.run.con.ConfigRecorder] (Quarkus Main Thread) Build time property cannot be changed at runtime: - quarkus.operator-sdk.crd.apply was 'true' at build time and is now 'false' ``` What is this message trying to tell me? What is the state of my property, i.e. is it `true` or is it `false`? ### Expected behavior A clear message as to what happened. ### Actual behavior The currently ambiguous or wrong message. ### How to Reproduce? _No response_ ### Output of `uname -a` or `ver` _No response_ ### Output of `java -version` 11 ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.7.0.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) _No response_ ### Additional information _No response_
277df2a3cfa249db5bb1c1c7a05719c28c7187ee
f1a68bd1cecd1d68668f430bb668b51c77d46438
https://github.com/quarkusio/quarkus/compare/277df2a3cfa249db5bb1c1c7a05719c28c7187ee...f1a68bd1cecd1d68668f430bb668b51c77d46438
diff --git a/core/runtime/src/main/java/io/quarkus/runtime/configuration/ConfigRecorder.java b/core/runtime/src/main/java/io/quarkus/runtime/configuration/ConfigRecorder.java index aaec129f11e..e898813ee45 100644 --- a/core/runtime/src/main/java/io/quarkus/runtime/configuration/ConfigRecorder.java +++ b/core/runtime/src/main/java/io/quarkus/runtime/configuration/ConfigRecorder.java @@ -34,8 +34,8 @@ public void handleConfigChange(Map<String, String> buildTimeConfig) { if (mismatches == null) { mismatches = new ArrayList<>(); } - mismatches.add(" - " + entry.getKey() + " is set to '" + entry.getValue() - + "' but it is build time fixed to '" + val.get() + "'. Did you change the property " + mismatches.add(" - " + entry.getKey() + " is set to '" + val.get() + + "' but it is build time fixed to '" + entry.getValue() + "'. Did you change the property " + entry.getKey() + " after building the application?"); } }
['core/runtime/src/main/java/io/quarkus/runtime/configuration/ConfigRecorder.java']
{'.java': 1}
1
1
0
0
1
20,570,693
3,978,912
522,537
5,011
419
88
4
1
1,021
158
260
47
0
1
1970-01-01T00:27:32
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0
2,423
quarkusio/quarkus/25638/23534
quarkusio
quarkus
https://github.com/quarkusio/quarkus/issues/23534
https://github.com/quarkusio/quarkus/pull/25638
https://github.com/quarkusio/quarkus/pull/25638
1
fix
RolesAllowed overrides OpenAPI definitions for 401 and 403 responses
### Describe the bug I noticed the when I added `APIResponse` annotations to my REST endpoint to document the 401 and 403 responses, the OpenAPI documentation overrides my descriptions, and instead shows "Not Authorized" (401) and "Not Allowed" (403). I've traced this down to using the `RolesAllowed` annotation. If I use `Authenticated`, or no annotation at all, then the documentation reflects the `APIResponse` annotations. ### Expected behavior OpenAPI documentation should be using the provided `APIResponse` annotations to document the 401 and 403 endpoint responses. ### Actual behavior OpenAPI documentation is using hard-coded "Not Authorized" and "Not Allowed" response descriptions for the 401 and 403 response status codes. This appears to be coming from https://github.com/quarkusio/quarkus/blob/e21e338d19ef3d15e2eec07cd2fd613a76375565/extensions/smallrye-openapi/deployment/src/main/java/io/quarkus/smallrye/openapi/deployment/filter/AutoRolesAllowedFilter.java#L80 ### How to Reproduce? See attached reproducer. 1. Run in dev mode (./mvnw clean compile quarkus:dev) 2. check the OpenAPI documentation at http://localhost:8080/q/openapi.json 3. Note that the 401 and 403 documentation use the references 4. Change the GreetingResource class to use the RolesAllowed annotation (either at the class or method level, doesn't matter) 5. refresh the OpenAPI documentation 6. Note that the 401 and 403 documentation is now ignoring the references, and is instead hard-coded to "Not Authorized" and "Not Allowed" ### Output of `uname -a` or `ver` Linux laverne 5.11.0-40-generic #44~20.04.2-Ubuntu SMP Tue Oct 26 18:07:44 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux ### Output of `java -version` openjdk version "11.0.13" 2021-10-19 ### GraalVM version (if different from Java) _No response_ ### Quarkus version or git rev 2.7.1.Final ### Build tool (ie. output of `mvnw --version` or `gradlew --version`) Apache Maven 3.8.4 (9b656c72d54e5bacbed989b64718c159fe39b537) ### Additional information _No response_
7d6f687585be23e70db868e54e1d743ff55d2a13
f19c59c49a3b9ab2e25cca50217dfbc04aa58a62
https://github.com/quarkusio/quarkus/compare/7d6f687585be23e70db868e54e1d743ff55d2a13...f19c59c49a3b9ab2e25cca50217dfbc04aa58a62
diff --git a/extensions/smallrye-openapi/deployment/src/main/java/io/quarkus/smallrye/openapi/deployment/filter/AutoRolesAllowedFilter.java b/extensions/smallrye-openapi/deployment/src/main/java/io/quarkus/smallrye/openapi/deployment/filter/AutoRolesAllowedFilter.java old mode 100644 new mode 100755 index 60a3bc946c8..aab73cd9abb --- a/extensions/smallrye-openapi/deployment/src/main/java/io/quarkus/smallrye/openapi/deployment/filter/AutoRolesAllowedFilter.java +++ b/extensions/smallrye-openapi/deployment/src/main/java/io/quarkus/smallrye/openapi/deployment/filter/AutoRolesAllowedFilter.java @@ -95,7 +95,9 @@ public void filterOpenAPI(OpenAPI openAPI) { operation = operation.addSecurityRequirement(securityRequirement); APIResponses responses = operation.getResponses(); for (APIResponseImpl response : getSecurityResponses()) { - responses.addAPIResponse(response.getResponseCode(), response); + if (!responses.hasAPIResponse(response.getResponseCode())) { + responses.addAPIResponse(response.getResponseCode(), response); + } } operation = operation.responses(responses); } else if (hasAuthenticatedMethodReferences() @@ -105,7 +107,9 @@ public void filterOpenAPI(OpenAPI openAPI) { operation = operation.addSecurityRequirement(securityRequirement); APIResponses responses = operation.getResponses(); for (APIResponseImpl response : getSecurityResponses()) { - responses.addAPIResponse(response.getResponseCode(), response); + if (!responses.hasAPIResponse(response.getResponseCode())) { + responses.addAPIResponse(response.getResponseCode(), response); + } } operation = operation.responses(responses); } diff --git a/extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/AutoSecurityRolesAllowedTestCase.java b/extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/AutoSecurityRolesAllowedTestCase.java index c17095d201d..a9d4b797170 100644 --- a/extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/AutoSecurityRolesAllowedTestCase.java +++ b/extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/AutoSecurityRolesAllowedTestCase.java @@ -55,4 +55,78 @@ public void testAutoSecurityRequirement() { } + @Test + public void testOpenAPIAnnotations() { + RestAssured.given().header("Accept", "application/json") + .when().get("/q/openapi") + .then() + .log().body() + .and() + .body("paths.'/resource2/test-security/classLevel/1'.get.responses.401.description", + Matchers.equalTo("Not Authorized")) + .and() + .body("paths.'/resource2/test-security/classLevel/1'.get.responses.403.description", + Matchers.equalTo("Not Allowed")) + .and() + .body("paths.'/resource2/test-security/classLevel/2'.get.responses.401.description", + Matchers.equalTo("Not Authorized")) + .and() + .body("paths.'/resource2/test-security/classLevel/2'.get.responses.403.description", + Matchers.equalTo("Not Allowed")) + .and() + .body("paths.'/resource2/test-security/classLevel/3'.get.responses.401.description", + Matchers.nullValue()) + .and() + .body("paths.'/resource2/test-security/classLevel/3'.get.responses.403.description", + Matchers.nullValue()) + .and() + .body("paths.'/resource2/test-security/classLevel/4'.get.responses.401.description", + Matchers.equalTo("Who are you?")) + .and() + .body("paths.'/resource2/test-security/classLevel/4'.get.responses.403.description", + Matchers.equalTo("You cannot do that.")) + .and() + .body("paths.'/resource2/test-security/naked'.get.responses.401.description", + Matchers.equalTo("Not Authorized")) + .and() + .body("paths.'/resource2/test-security/naked'.get.responses.403.description", + Matchers.equalTo("Not Allowed")) + .and() + .body("paths.'/resource2/test-security/annotated'.get.responses.401.description", + Matchers.nullValue()) + .and() + .body("paths.'/resource2/test-security/annotated'.get.responses.403.description", + Matchers.nullValue()) + .and() + .body("paths.'/resource2/test-security/methodLevel/1'.get.responses.401.description", + Matchers.equalTo("Not Authorized")) + .and() + .body("paths.'/resource2/test-security/methodLevel/1'.get.responses.403.description", + Matchers.equalTo("Not Allowed")) + .and() + .body("paths.'/resource2/test-security/methodLevel/2'.get.responses.401.description", + Matchers.equalTo("Not Authorized")) + .and() + .body("paths.'/resource2/test-security/methodLevel/2'.get.responses.403.description", + Matchers.equalTo("Not Allowed")) + .and() + .body("paths.'/resource2/test-security/methodLevel/public'.get.responses.401.description", + Matchers.nullValue()) + .and() + .body("paths.'/resource2/test-security/methodLevel/public'.get.responses.403.description", + Matchers.nullValue()) + .and() + .body("paths.'/resource2/test-security/annotated/documented'.get.responses.401.description", + Matchers.equalTo("Who are you?")) + .and() + .body("paths.'/resource2/test-security/annotated/documented'.get.responses.403.description", + Matchers.equalTo("You cannot do that.")) + .and() + .body("paths.'/resource2/test-security/methodLevel/3'.get.responses.401.description", + Matchers.equalTo("Who are you?")) + .and() + .body("paths.'/resource2/test-security/methodLevel/3'.get.responses.403.description", + Matchers.equalTo("You cannot do that.")); + } + } diff --git a/extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/OpenApiResourceSecuredAtClassLevel.java b/extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/OpenApiResourceSecuredAtClassLevel.java old mode 100644 new mode 100755 index fe0e2d7b1aa..2d6749566c6 --- a/extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/OpenApiResourceSecuredAtClassLevel.java +++ b/extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/OpenApiResourceSecuredAtClassLevel.java @@ -4,6 +4,8 @@ import javax.ws.rs.GET; import javax.ws.rs.Path; +import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; +import org.eclipse.microprofile.openapi.annotations.responses.APIResponses; import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement; import org.eclipse.microprofile.openapi.annotations.servers.Server; import org.eclipse.microprofile.openapi.annotations.tags.Tag; @@ -35,4 +37,14 @@ public String secureEndpoint3() { return "secret"; } + @APIResponses({ + @APIResponse(responseCode = "401", description = "Who are you?"), + @APIResponse(responseCode = "403", description = "You cannot do that.") + }) + @GET + @Path("/test-security/classLevel/4") + public String secureEndpoint4() { + return "secret"; + } + } diff --git a/extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/OpenApiResourceSecuredAtMethodLevel.java b/extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/OpenApiResourceSecuredAtMethodLevel.java old mode 100644 new mode 100755 index af31dad4c85..ff3e17182fa --- a/extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/OpenApiResourceSecuredAtMethodLevel.java +++ b/extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/OpenApiResourceSecuredAtMethodLevel.java @@ -4,6 +4,8 @@ import javax.ws.rs.GET; import javax.ws.rs.Path; +import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; +import org.eclipse.microprofile.openapi.annotations.responses.APIResponses; import org.eclipse.microprofile.openapi.annotations.security.SecurityRequirement; import org.eclipse.microprofile.openapi.annotations.servers.Server; import org.eclipse.microprofile.openapi.annotations.tags.Tag; @@ -50,4 +52,27 @@ public String publicEndpoint() { return "boo"; } + @APIResponses({ + @APIResponse(responseCode = "401", description = "Who are you?"), + @APIResponse(responseCode = "403", description = "You cannot do that.") + }) + @GET + @Path("/test-security/annotated/documented") + @RolesAllowed("admin") + @SecurityRequirement(name = "JWTCompanyAuthentication") + public String secureEndpointWithSecurityAnnotationAndDocument() { + return "secret"; + } + + @APIResponses({ + @APIResponse(responseCode = "401", description = "Who are you?"), + @APIResponse(responseCode = "403", description = "You cannot do that.") + }) + @GET + @Path("/test-security/methodLevel/3") + @RolesAllowed("admin") + public String secureEndpoint3() { + return "secret"; + } + }
['extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/OpenApiResourceSecuredAtClassLevel.java', 'extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/AutoSecurityRolesAllowedTestCase.java', 'extensions/smallrye-openapi/deployment/src/main/java/io/quarkus/smallrye/openapi/deployment/filter/AutoRolesAllowedFilter.java', 'extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/OpenApiResourceSecuredAtMethodLevel.java']
{'.java': 4}
4
4
0
0
4
20,625,638
3,989,622
523,984
5,019
717
72
8
1
2,045
262
544
46
2
0
1970-01-01T00:27:32
12,047
Java
{'Java': 45174846, 'HTML': 1260641, 'Kotlin': 726044, 'JavaScript': 519044, 'Shell': 51146, 'Groovy': 25140, 'ANTLR': 23342, 'Batchfile': 13971, 'Mustache': 13199, 'Scala': 9778, 'FreeMarker': 8106, 'CSS': 5346, 'Dockerfile': 660, 'PLpgSQL': 109}
Apache License 2.0