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] | stars
int64 10
44.3k
| language
stringclasses 8
values | languages
stringclasses 296
values | license
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,770 | quarkusio/quarkus/16793/16754 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/16754 | https://github.com/quarkusio/quarkus/pull/16793 | https://github.com/quarkusio/quarkus/pull/16793 | 1 | fixes | 404 error from resources declared in javax.ws.rs.core.Application#getClasses | I'm trying to upgrade to **1.13.2.Final** and use the ability to limit the JAX-RS resources introduced by [this](https://github.com/quarkusio/quarkus/pull/14207) feature, but the declared resources in the overriden ``javax.ws.rs.core.Application#getClasses`` method return 404 error. If i do not override ``getClasses`` (or return an empty set, which as far as i understand is equivalent), the endpoints work as expected.
#### To Reproduce
You can use [this](https://github.com/blxbrgld/jaxrs-application) sample. ``/api/test`` is the endpoint that returns the 404 error. | 71230a1cc10fef7299bbb1393e2d2c6056e80f88 | ae36b2ed429ec2d5fe70deb410abae8a07231bb5 | https://github.com/quarkusio/quarkus/compare/71230a1cc10fef7299bbb1393e2d2c6056e80f88...ae36b2ed429ec2d5fe70deb410abae8a07231bb5 | diff --git a/extensions/resteasy-classic/resteasy-server-common/deployment/src/main/java/io/quarkus/resteasy/server/common/deployment/ResteasyServerCommonProcessor.java b/extensions/resteasy-classic/resteasy-server-common/deployment/src/main/java/io/quarkus/resteasy/server/common/deployment/ResteasyServerCommonProcessor.java
index cf5e28f75f0..c149679b7ab 100755
--- a/extensions/resteasy-classic/resteasy-server-common/deployment/src/main/java/io/quarkus/resteasy/server/common/deployment/ResteasyServerCommonProcessor.java
+++ b/extensions/resteasy-classic/resteasy-server-common/deployment/src/main/java/io/quarkus/resteasy/server/common/deployment/ResteasyServerCommonProcessor.java
@@ -13,6 +13,7 @@
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiFunction;
@@ -236,7 +237,8 @@ public void build(
final Collection<AnnotationInstance> allPaths;
if (filterClasses) {
allPaths = paths.stream().filter(
- annotationInstance -> keepEnclosingClass(allowedClasses, excludedClasses, annotationInstance))
+ annotationInstance -> keepAnnotation(beanArchiveIndexBuildItem.getIndex(), allowedClasses, excludedClasses,
+ annotationInstance))
.collect(Collectors.toList());
} else {
allPaths = new ArrayList<>(paths);
@@ -889,21 +891,32 @@ private static Set<String> getExcludedClasses(List<BuildTimeConditionBuildItem>
}
/**
- * @param allowedClasses the classes returned by the methods {@link Application#getClasses()} and
- * {@link Application#getSingletons()} to keep.
- * @param excludedClasses the classes that have been annotated wih unsuccessful build time conditions and that
+ * @param index the Jandex index view from which the class information is extracted.
+ * @param allowedClasses the classes to keep provided by the methods {@link Application#getClasses()} and
+ * {@link Application#getSingletons()}.
+ * @param excludedClasses the classes that have been annotated with unsuccessful build time conditions and that
* need to be excluded from the list of paths.
- * @param annotationInstance the annotation instance from which the enclosing class will be extracted.
- * @return {@code true} if the enclosing class of the annotation is part of the allowed classes if not empty
- * or if is not part of the excluded classes, {@code false} otherwise.
+ * @param annotationInstance the annotation instance to test.
+ * @return {@code true} if the enclosing class of the annotation is a concrete class and is part of the allowed
+ * classes, or is an interface and at least one concrete implementation is included, or is an abstract class
+ * and at least one concrete sub class is included, or is not part of the excluded classes, {@code false} otherwise.
*/
- private static boolean keepEnclosingClass(Set<String> allowedClasses, Set<String> excludedClasses,
+ private static boolean keepAnnotation(IndexView index, Set<String> allowedClasses, Set<String> excludedClasses,
AnnotationInstance annotationInstance) {
- final String className = JandexUtil.getEnclosingClass(annotationInstance).toString();
+ final ClassInfo classInfo = JandexUtil.getEnclosingClass(annotationInstance);
+ final String className = classInfo.toString();
if (allowedClasses.isEmpty()) {
// No allowed classes have been set, meaning that only excluded classes have been provided.
// Keep the enclosing class only if not excluded
return !excludedClasses.contains(className);
+ } else if (Modifier.isAbstract(classInfo.flags())) {
+ // Only keep the annotation if a concrete implementation or a sub class has been included
+ return (Modifier.isInterface(classInfo.flags()) ? index.getAllKnownImplementors(classInfo.name())
+ : index.getAllKnownSubclasses(classInfo.name()))
+ .stream()
+ .filter(clazz -> !Modifier.isAbstract(clazz.flags()))
+ .map(Objects::toString)
+ .anyMatch(allowedClasses::contains);
}
return allowedClasses.contains(className);
}
diff --git a/extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/root/ApplicationTest.java b/extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/root/ApplicationTest.java
index a8613bd142b..e00eb8b9058 100644
--- a/extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/root/ApplicationTest.java
+++ b/extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/root/ApplicationTest.java
@@ -38,7 +38,10 @@ class ApplicationTest {
static QuarkusUnitTest runner = new QuarkusUnitTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.addClasses(
- ResourceTest1.class, ResourceTest2.class, ResponseFilter1.class, ResponseFilter2.class,
+ IResourceTest.class, ResourceInheritedInterfaceTest.class,
+ AResourceTest.class, ResourceInheritedClassTest.class,
+ ResourceTest1.class, ResourceTest2.class,
+ ResponseFilter1.class, ResponseFilter2.class,
ResponseFilter3.class, ResponseFilter4.class, ResponseFilter5.class, ResponseFilter6.class,
Feature1.class, Feature2.class, DynamicFeature1.class, DynamicFeature2.class,
ExceptionMapper1.class, ExceptionMapper2.class, AppTest.class));
@@ -76,6 +79,79 @@ void should_not_call_ok_of_resource_2() {
.statusCode(Response.Status.SERVICE_UNAVAILABLE.getStatusCode());
}
+ @DisplayName("Should access to path inherited from an interface")
+ @Test
+ void should_call_inherited_from_interface() {
+ when()
+ .get("/rt-i/ok")
+ .then()
+ .statusCode(Response.Status.OK.getStatusCode())
+ .body(Matchers.is("ok-i"));
+ }
+
+ @DisplayName("Should access to path inherited from a class where method is implemented")
+ @Test
+ void should_call_inherited_from_class_implemented() {
+ when()
+ .get("/rt-a/ok-1")
+ .then()
+ .statusCode(Response.Status.OK.getStatusCode())
+ .body(Matchers.is("ok-a-1"));
+ }
+
+ @DisplayName("Should access to path inherited from a class where method is overridden")
+ @Test
+ void should_call_inherited_from_class_overridden() {
+ when()
+ .get("/rt-a/ok-2")
+ .then()
+ .statusCode(Response.Status.OK.getStatusCode())
+ .body(Matchers.is("ok-a-2"));
+ }
+
+ @Path("rt-i")
+ public interface IResourceTest {
+
+ @GET
+ @Path("ok")
+ String ok();
+ }
+
+ public static class ResourceInheritedInterfaceTest implements IResourceTest {
+
+ @Override
+ public String ok() {
+ return "ok-i";
+ }
+ }
+
+ @Path("rt-a")
+ public abstract static class AResourceTest {
+
+ @GET
+ @Path("ok-1")
+ public abstract String ok1();
+
+ @GET
+ @Path("ok-2")
+ public String ok2() {
+ return "ok-a";
+ }
+ }
+
+ public static class ResourceInheritedClassTest extends AResourceTest {
+
+ @Override
+ public String ok1() {
+ return "ok-a-1";
+ }
+
+ @Override
+ public String ok2() {
+ return "ok-a-2";
+ }
+ }
+
@Path("rt-1")
public static class ResourceTest1 {
@@ -224,6 +300,7 @@ public static class AppTest extends Application {
public Set<Class<?>> getClasses() {
return new HashSet<>(
Arrays.asList(
+ ResourceInheritedInterfaceTest.class, ResourceInheritedClassTest.class,
ResourceTest1.class, Feature1.class, ExceptionMapper1.class));
}
| ['extensions/resteasy-classic/resteasy-server-common/deployment/src/main/java/io/quarkus/resteasy/server/common/deployment/ResteasyServerCommonProcessor.java', 'extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/root/ApplicationTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 16,120,404 | 3,136,495 | 416,367 | 4,412 | 2,758 | 504 | 31 | 1 | 575 | 72 | 148 | 4 | 2 | 0 | 2021-04-26T07:50:06 | 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,771 | quarkusio/quarkus/16777/16429 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/16429 | https://github.com/quarkusio/quarkus/pull/16777 | https://github.com/quarkusio/quarkus/pull/16777 | 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.
| 82477c6476ccf4aa8facdf49f776cb09e185a4be | 814be9658b46085868ec887f845eb7d8e7d00a62 | https://github.com/quarkusio/quarkus/compare/82477c6476ccf4aa8facdf49f776cb09e185a4be...814be9658b46085868ec887f845eb7d8e7d00a62 | diff --git a/core/runtime/src/main/java/io/quarkus/runtime/configuration/ApplicationPropertiesConfigSourceLoader.java b/core/runtime/src/main/java/io/quarkus/runtime/configuration/ApplicationPropertiesConfigSourceLoader.java
index f5ac2de74bf..e605e035d9a 100644
--- a/core/runtime/src/main/java/io/quarkus/runtime/configuration/ApplicationPropertiesConfigSourceLoader.java
+++ b/core/runtime/src/main/java/io/quarkus/runtime/configuration/ApplicationPropertiesConfigSourceLoader.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;
@@ -48,7 +49,9 @@ protected ConfigSource loadConfigSource(final URL url, final int ordinal) throws
@Override
public List<ConfigSource> getConfigSources(final ClassLoader classLoader) {
- return loadConfigSources("config/application.properties", classLoader);
+ return loadConfigSources(
+ Paths.get(System.getProperty("user.dir"), "config", "application.properties").toUri().toString(),
+ classLoader);
}
@Override
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 96c0d87fa16..8f9ba413581 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
@@ -1,7 +1,6 @@
package io.quarkus.runtime.configuration;
import static io.smallrye.config.AbstractLocationConfigSourceFactory.SMALLRYE_LOCATIONS;
-import static io.smallrye.config.DotEnvConfigSourceProvider.dotEnvSources;
import static io.smallrye.config.ProfileConfigSourceInterceptor.SMALLRYE_PROFILE;
import static io.smallrye.config.ProfileConfigSourceInterceptor.SMALLRYE_PROFILE_PARENT;
import static io.smallrye.config.PropertiesConfigSourceProvider.classPathSources;
@@ -10,6 +9,7 @@
import java.io.IOException;
import java.net.URL;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
@@ -100,7 +100,9 @@ public OptionalInt getPriority() {
builder.addDefaultInterceptors();
if (runTime) {
builder.addDefaultSources();
- builder.withSources(dotEnvSources(classLoader));
+ builder.withSources(
+ new DotEnvConfigSourceProvider(Paths.get(System.getProperty("user.dir"), ".env").toUri().toString())
+ .getConfigSources(classLoader));
} else {
final List<ConfigSource> sources = new ArrayList<>();
sources.addAll(classPathSources(META_INF_MICROPROFILE_CONFIG_PROPERTIES, classLoader));
@@ -190,7 +192,7 @@ public String getName() {
*/
static class BuildTimeDotEnvConfigSourceProvider extends DotEnvConfigSourceProvider {
public BuildTimeDotEnvConfigSourceProvider() {
- super();
+ super(Paths.get(System.getProperty("user.dir"), ".env").toUri().toString());
}
public BuildTimeDotEnvConfigSourceProvider(final String location) { | ['core/runtime/src/main/java/io/quarkus/runtime/configuration/ConfigUtils.java', 'core/runtime/src/main/java/io/quarkus/runtime/configuration/ApplicationPropertiesConfigSourceLoader.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 15,489,869 | 3,016,720 | 400,919 | 4,279 | 802 | 140 | 13 | 2 | 1,059 | 144 | 318 | 37 | 0 | 3 | 2021-04-23T23:21: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,772 | quarkusio/quarkus/16766/16765 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/16765 | https://github.com/quarkusio/quarkus/pull/16766 | https://github.com/quarkusio/quarkus/pull/16766 | 1 | fix | kafka-client : Detected a MBean server in the image heap | ## Describe the bug
In some cases, org.apache.kafka.common.metrics.JmxReporter.reconfigure is called, implying the usage of MBean server.
Native executable can not be build.
### Expected behavior
All methods accessing to MBeanServer shall be substituted.
### Actual behavior
reconfigure method is causing this kind of error during native build :
`Error: Detected a MBean server in the image heap. This is currently not supported, but could be changed in the future. Management beans are registered in many global caches that would need to be cleared and properly re-built at image build time. Class of disallowed object: com.sun.jmx.mbeanserver.JmxMBeanServer To see how this object got instantiated use --trace-object-instantiation=com.sun.jmx.mbeanserver.JmxMBeanServer. The object was probably created by a class initializer and is reachable from a static field. You can request class initialization at image runtime by using the option --initialize-at-run-time=<class-name>. Or you can write your own initialization methods and call them explicitly from your main entry point.
Trace: Object was reached by
indexing into array
constant java.lang.Object[]@fde425e reached by
reading field java.util.ArrayList.elementData of
constant java.util.ArrayList@1a67ab17 reached by
scanning method javax.management.MBeanServerFactory.addMBeanServer(MBeanServerFactory.java:418)
Call path from entry point to javax.management.MBeanServerFactory.addMBeanServer(MBeanServer):
at javax.management.MBeanServerFactory.addMBeanServer(MBeanServerFactory.java:418)
at javax.management.MBeanServerFactory.createMBeanServer(MBeanServerFactory.java:232)
at javax.management.MBeanServerFactory.createMBeanServer(MBeanServerFactory.java:192)
at com.oracle.svm.core.jdk.management.ManagementSupport.getPlatformMBeanServer(ManagementSupport.java:250)
at com.oracle.svm.core.jdk.management.Target_java_lang_management_ManagementFactory.getPlatformMBeanServer(Target_java_lang_management_ManagementFactory.java:45)
at org.apache.kafka.common.metrics.JmxReporter.reregister(JmxReporter.java:227)
at org.apache.kafka.common.metrics.JmxReporter.lambda$reconfigure$1(JmxReporter.java:113)
at org.apache.kafka.common.metrics.JmxReporter$$Lambda$1649/0x00000007c2ad1840.accept(Unknown Source)
`
## To Reproduce
Stacktrace is incomplete and not easily reproductible.
## Environment (please complete the following information):
### Output of `uname -a` or `ver`
Linux XXX 5.8.0-50-generic #56~20.04.1-Ubuntu SMP Mon Apr 12 21:46:35 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
### Output of `java -version`
openjdk version "11.0.10" 2021-01-19
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.10+9)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.10+9, mixed mode)
### GraalVM version (if different from Java)
Using quarkus.native.container-build
### Quarkus version or git rev
1.13.2
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
Maven home: /home/gla/.sdkman/candidates/maven/current
Java version: 11.0.10, vendor: AdoptOpenJDK, runtime: /home/gla/.sdkman/candidates/java/11.0.10.hs-adpt
Default locale: fr_FR, platform encoding: UTF-8
OS name: "linux", version: "5.8.0-50-generic", arch: "amd64", family: "unix"
| 65b88195f8efe5746e3a88f06fbc0176496be4b7 | 4c926d19865c832e959a850ac05614a2002aec72 | https://github.com/quarkusio/quarkus/compare/65b88195f8efe5746e3a88f06fbc0176496be4b7...4c926d19865c832e959a850ac05614a2002aec72 | diff --git a/extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/graal/SubstituteSnappy.java b/extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/graal/SubstituteSnappy.java
index 8dbe699c096..e29267a9e71 100644
--- a/extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/graal/SubstituteSnappy.java
+++ b/extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/graal/SubstituteSnappy.java
@@ -5,6 +5,7 @@
import java.lang.invoke.MethodHandle;
import java.util.List;
+import java.util.Map;
import java.util.function.BooleanSupplier;
import org.apache.kafka.common.metrics.JmxReporter;
@@ -91,6 +92,11 @@ public static synchronized void unregisterAppInfo(String prefix, String id, Metr
@TargetClass(value = JmxReporter.class)
final class JMXReporting {
+ @Substitute
+ public void reconfigure(Map<String, ?> configs) {
+
+ }
+
@Substitute
public void init(List<KafkaMetric> metrics) {
| ['extensions/kafka-client/runtime/src/main/java/io/quarkus/kafka/client/runtime/graal/SubstituteSnappy.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 16,084,147 | 3,129,533 | 415,543 | 4,403 | 105 | 24 | 6 | 1 | 3,365 | 317 | 850 | 60 | 0 | 0 | 2021-04-23T15:00: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,774 | quarkusio/quarkus/16672/16661 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/16661 | https://github.com/quarkusio/quarkus/pull/16672 | https://github.com/quarkusio/quarkus/pull/16672 | 1 | close | QuarkusGenerateCode gradle task is not incremental | ## Describe the bug
When running `quarkusBuild` or `quarkusDev`, it triggers `quarkusGenerateCode` task. This tasks is always ran, even when no change happen.
### Expected behavior
The task should be `UP-TO-DATE`, if no changes happen to
### Actual behavior
The task always is always ran
## To Reproduce
Steps to reproduce the behavior:
1. Create a simple project
2. run `./gradlew quarkusBuild` multiple times, it never will be `UP-TO-DATE`.
| 6ddda1f2d13205de9670e940bdb4aabb3e706e3b | b11b716787b586b35cf72c42b2ff84670a0d8eb7 | https://github.com/quarkusio/quarkus/compare/6ddda1f2d13205de9670e940bdb4aabb3e706e3b...b11b716787b586b35cf72c42b2ff84670a0d8eb7 | diff --git a/devtools/gradle/src/main/java/io/quarkus/gradle/QuarkusPlugin.java b/devtools/gradle/src/main/java/io/quarkus/gradle/QuarkusPlugin.java
index b8dee8f1741..f61804ee4a8 100644
--- a/devtools/gradle/src/main/java/io/quarkus/gradle/QuarkusPlugin.java
+++ b/devtools/gradle/src/main/java/io/quarkus/gradle/QuarkusPlugin.java
@@ -153,11 +153,9 @@ public void execute(Task test) {
compileJavaTask.getOptions().setAnnotationProcessorPath(annotationProcessorConfig);
compileJavaTask.dependsOn(quarkusGenerateCode);
- quarkusGenerateCode.setSourceRegistrar(compileJavaTask::source);
JavaCompile compileTestJavaTask = (JavaCompile) tasks.getByName(JavaPlugin.COMPILE_TEST_JAVA_TASK_NAME);
compileTestJavaTask.dependsOn(quarkusGenerateCodeTests);
- quarkusGenerateCodeTests.setSourceRegistrar(compileTestJavaTask::source);
Task classesTask = tasks.getByName(JavaPlugin.CLASSES_TASK_NAME);
Task resourcesTask = tasks.getByName(JavaPlugin.PROCESS_RESOURCES_TASK_NAME);
@@ -204,27 +202,24 @@ public void execute(Task test) {
tasks.withType(Test.class).forEach(configureTestTask);
tasks.withType(Test.class).whenTaskAdded(configureTestTask::accept);
- sourceSets.create(QuarkusGenerateCode.QUARKUS_GENERATED_SOURCES).getOutput()
+ SourceSet generatedSourceSet = sourceSets.create(QuarkusGenerateCode.QUARKUS_GENERATED_SOURCES);
+ generatedSourceSet.getOutput()
.dir(QuarkusGenerateCode.QUARKUS_GENERATED_SOURCES);
- sourceSets.create(QuarkusGenerateCode.QUARKUS_TEST_GENERATED_SOURCES).getOutput()
+ SourceSet generatedTestSourceSet = sourceSets.create(QuarkusGenerateCode.QUARKUS_TEST_GENERATED_SOURCES);
+ generatedTestSourceSet.getOutput()
.dir(QuarkusGenerateCode.QUARKUS_TEST_GENERATED_SOURCES);
+
+ // Register the quarkus-generated-code
+ for (String provider : QuarkusGenerateCode.CODE_GENERATION_PROVIDER) {
+ mainSourceSet.getJava().srcDir(new File(generatedSourceSet.getJava().getOutputDir(), provider));
+ testSourceSet.getJava().srcDir(new File(generatedTestSourceSet.getJava().getOutputDir(), provider));
+ }
+
});
project.getPlugins().withId("org.jetbrains.kotlin.jvm", plugin -> {
tasks.getByName("compileKotlin").dependsOn(quarkusGenerateCode);
tasks.getByName("compileTestKotlin").dependsOn(quarkusGenerateCodeTests);
-
- // Register the quarkus-generated-code
- SourceSetContainer sourceSets = project.getConvention().getPlugin(JavaPluginConvention.class)
- .getSourceSets();
- SourceSet mainSourceSet = sourceSets.getByName(SourceSet.MAIN_SOURCE_SET_NAME);
- SourceSet testSourceSet = sourceSets.getByName(SourceSet.TEST_SOURCE_SET_NAME);
- SourceSet generatedSourceSet = sourceSets.getByName(QuarkusGenerateCode.QUARKUS_GENERATED_SOURCES);
- SourceSet generatedTestSourceSet = sourceSets.getByName(QuarkusGenerateCode.QUARKUS_TEST_GENERATED_SOURCES);
- for (String provider : QuarkusGenerateCode.CODE_GENERATION_PROVIDER) {
- mainSourceSet.getJava().srcDir(new File(generatedSourceSet.getJava().getOutputDir(), provider));
- testSourceSet.getJava().srcDir(new File(generatedTestSourceSet.getJava().getOutputDir(), provider));
- }
});
}
diff --git a/devtools/gradle/src/main/java/io/quarkus/gradle/tasks/QuarkusGenerateCode.java b/devtools/gradle/src/main/java/io/quarkus/gradle/tasks/QuarkusGenerateCode.java
index 0b1dbb5537e..6ec53119ea6 100644
--- a/devtools/gradle/src/main/java/io/quarkus/gradle/tasks/QuarkusGenerateCode.java
+++ b/devtools/gradle/src/main/java/io/quarkus/gradle/tasks/QuarkusGenerateCode.java
@@ -1,10 +1,13 @@
package io.quarkus.gradle.tasks;
+import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
+import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
@@ -16,6 +19,8 @@
import org.gradle.api.plugins.Convention;
import org.gradle.api.plugins.JavaPluginConvention;
import org.gradle.api.tasks.CompileClasspath;
+import org.gradle.api.tasks.InputFiles;
+import org.gradle.api.tasks.OutputDirectories;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.TaskAction;
@@ -33,10 +38,12 @@ public class QuarkusGenerateCode extends QuarkusTask {
public static final String QUARKUS_TEST_GENERATED_SOURCES = "quarkus-test-generated-sources";
// TODO dynamically load generation provider, or make them write code directly in quarkus-generated-sources
public static final String[] CODE_GENERATION_PROVIDER = new String[] { "grpc", "avdl", "avpr", "avsc" };
+ public static final String[] CODE_GENERATION_INPUT = new String[] { "proto", "avro" };
public static final String INIT_AND_RUN = "initAndRun";
private Set<Path> sourcesDirectories;
- private Consumer<Path> sourceRegistrar;
+ private Consumer<Path> sourceRegistrar = (p) -> {
+ };
private boolean test = false;
public QuarkusGenerateCode() {
@@ -53,6 +60,29 @@ public FileCollection getClasspath() {
return QuarkusGradleUtils.getSourceSet(getProject(), SourceSet.MAIN_SOURCE_SET_NAME).getCompileClasspath();
}
+ @InputFiles
+ public Set<File> getInputDirectory() {
+ Set<File> inputDirectories = new HashSet<>();
+
+ final String inputSourceSetName = test ? SourceSet.TEST_SOURCE_SET_NAME : SourceSet.MAIN_SOURCE_SET_NAME;
+ Path src = getProject().getProjectDir().toPath().resolve("src").resolve(inputSourceSetName);
+
+ for (String input : CODE_GENERATION_INPUT) {
+ Path providerSrcDir = src.resolve(input);
+ if (Files.exists(providerSrcDir)) {
+ inputDirectories.add(providerSrcDir.toFile());
+ }
+ }
+
+ return inputDirectories;
+ }
+
+ @OutputDirectories
+ public FileCollection getGeneratedOutputDirectory() {
+ final String generatedSourceSetName = test ? QUARKUS_TEST_GENERATED_SOURCES : QUARKUS_GENERATED_SOURCES;
+ return QuarkusGradleUtils.getSourceSet(getProject(), generatedSourceSetName).getOutput().getDirs();
+ }
+
@TaskAction
public void prepareQuarkus() {
getLogger().lifecycle("preparing quarkus application");
@@ -118,10 +148,6 @@ public void setSourcesDirectories(Set<Path> sourcesDirectories) {
this.sourcesDirectories = sourcesDirectories;
}
- public void setSourceRegistrar(Consumer<Path> sourceRegistrar) {
- this.sourceRegistrar = sourceRegistrar;
- }
-
public void setTest(boolean test) {
this.test = test;
}
diff --git a/integration-tests/gradle/src/test/java/io/quarkus/gradle/builder/QuarkusModelBuilderTest.java b/integration-tests/gradle/src/test/java/io/quarkus/gradle/builder/QuarkusModelBuilderTest.java
index da308b09bf3..251bcb0baaa 100644
--- a/integration-tests/gradle/src/test/java/io/quarkus/gradle/builder/QuarkusModelBuilderTest.java
+++ b/integration-tests/gradle/src/test/java/io/quarkus/gradle/builder/QuarkusModelBuilderTest.java
@@ -77,8 +77,8 @@ private void assertWorkspace(WorkspaceModule workspaceModule, File projectDir) {
new File(projectDir, "build/classes/java/test"));
final SourceSet sourceSourceSet = workspaceModule.getSourceSourceSet();
assertEquals(new File(projectDir, "src/main/resources"), sourceSourceSet.getResourceDirectory());
- assertEquals(1, sourceSourceSet.getSourceDirectories().size());
- assertEquals(new File(projectDir, "src/main/java"), sourceSourceSet.getSourceDirectories().iterator().next());
+ assertEquals(5, sourceSourceSet.getSourceDirectories().size());
+ assertThat(sourceSourceSet.getSourceDirectories()).contains(new File(projectDir, "src/main/java"));
}
private File getResourcesProject(String projectName) throws URISyntaxException, IOException { | ['integration-tests/gradle/src/test/java/io/quarkus/gradle/builder/QuarkusModelBuilderTest.java', 'devtools/gradle/src/main/java/io/quarkus/gradle/QuarkusPlugin.java', 'devtools/gradle/src/main/java/io/quarkus/gradle/tasks/QuarkusGenerateCode.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 16,091,351 | 3,130,988 | 415,692 | 4,403 | 3,552 | 708 | 63 | 2 | 470 | 69 | 121 | 18 | 0 | 0 | 2021-04-21T07:23: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,800 | quarkusio/quarkus/16021/15821 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15821 | https://github.com/quarkusio/quarkus/pull/16021 | https://github.com/quarkusio/quarkus/pull/16021 | 1 | fixes | Quarkus Vault problem | ## Describe the bug
I have a small application with 2 rest endpoints and vault. Authentication method for vault is username/password
After 10-15 mins running app throws exception on API calls because it try to resolve "resteasy.original.webapplicationexception.behavior" property. And when it comes to vault source it couldn't authenticate second time. Thrown exception:
The current thread cannot be blocked: vert.x-eventloop-thread-8
### Expected behavior
resteasy.original.webapplicationexception.behavior has default value. shouldn't be taken from vault.
vault also shouldn't throw this exception
### Actual behavior
vault throws exception:
ERROR [io.qua.ver.htt.run.QuarkusErrorHandler] (vert.x-eventloop-thread-8) HTTP Request to ... failed, error id: 180723b6-de12-4517-af3d-878cd0bb010c-1: java.lang.IllegalStateException: The current thread cannot be blocked: vert.x-eventloop-thread-8
at io.smallrye.mutiny.operators.UniBlockingAwait.await(UniBlockingAwait.java:29)
at io.smallrye.mutiny.groups.UniAwait.atMost(UniAwait.java:61)
at io.quarkus.vault.runtime.client.VertxVaultClient.exec(VertxVaultClient.java:472)
at io.quarkus.vault.runtime.client.VertxVaultClient.exec(VertxVaultClient.java:457)
at io.quarkus.vault.runtime.client.VertxVaultClient.get(VertxVaultClient.java:438)
at io.quarkus.vault.runtime.client.VertxVaultClient.lookupSelf(VertxVaultClient.java:213)
at io.quarkus.vault.runtime.VaultAuthManager.validate(VaultAuthManager.java:107)
at io.quarkus.vault.runtime.VaultAuthManager.login(VaultAuthManager.java:89)
at io.quarkus.vault.runtime.VaultAuthManager.login(VaultAuthManager.java:78)
at io.quarkus.vault.runtime.VaultAuthManager.getClientToken(VaultAuthManager.java:62)
at io.quarkus.vault.runtime.VaultKvManager.readSecret(VaultKvManager.java:32)
at io.quarkus.vault.runtime.VaultKvManager_ClientProxy.readSecret(VaultKvManager_ClientProxy.zig:222)
at io.quarkus.vault.runtime.config.VaultConfigSource.fetchSecrets(VaultConfigSource.java:85)
at io.quarkus.vault.runtime.config.VaultConfigSource.lambda$fetchSecrets$2(VaultConfigSource.java:81)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at io.quarkus.vault.runtime.config.VaultConfigSource.fetchSecrets(VaultConfigSource.java:81)
at io.quarkus.vault.runtime.config.VaultConfigSource.lambda$getSecretConfig$0(VaultConfigSource.java:65)
at java.base/java.util.Optional.ifPresent(Optional.java:183)
at io.quarkus.vault.runtime.config.VaultConfigSource.getSecretConfig(VaultConfigSource.java:65)
at io.quarkus.vault.runtime.config.VaultConfigSource.getValue(VaultConfigSource.java:51)
at io.smallrye.config.ConfigValueConfigSourceWrapper.getConfigValue(ConfigValueConfigSourceWrapper.java:20)
at io.smallrye.config.SmallRyeConfigSourceInterceptor.getValue(SmallRyeConfigSourceInterceptor.java:26)
at io.smallrye.config.SmallRyeConfigSourceInterceptorContext.proceed(SmallRyeConfigSourceInterceptorContext.java:20)
at io.smallrye.config.SmallRyeConfigSourceInterceptor.getValue(SmallRyeConfigSourceInterceptor.java:27)
at io.smallrye.config.SmallRyeConfigSourceInterceptorContext.proceed(SmallRyeConfigSourceInterceptorContext.java:20)
at io.smallrye.config.SmallRyeConfigSourceInterceptor.getValue(SmallRyeConfigSourceInterceptor.java:27)
at io.smallrye.config.SmallRyeConfigSourceInterceptorContext.proceed(SmallRyeConfigSourceInterceptorContext.java:20)
at io.smallrye.config.SmallRyeConfigSourceInterceptor.getValue(SmallRyeConfigSourceInterceptor.java:27)
at io.smallrye.config.SmallRyeConfigSourceInterceptorContext.proceed(SmallRyeConfigSourceInterceptorContext.java:20)
at io.smallrye.config.SecretKeysConfigSourceInterceptor.getValue(SecretKeysConfigSourceInterceptor.java:22)
at io.smallrye.config.SmallRyeConfigSourceInterceptorContext.proceed(SmallRyeConfigSourceInterceptorContext.java:20)
at io.smallrye.config.ProfileConfigSourceInterceptor.getProfileValue(ProfileConfigSourceInterceptor.java:84)
at io.smallrye.config.ProfileConfigSourceInterceptor.getValue(ProfileConfigSourceInterceptor.java:65)
at io.smallrye.config.SmallRyeConfigSourceInterceptorContext.proceed(SmallRyeConfigSourceInterceptorContext.java:20)
at io.smallrye.config.ExpressionConfigSourceInterceptor.getValue(ExpressionConfigSourceInterceptor.java:26)
at io.smallrye.config.ExpressionConfigSourceInterceptor.getValue(ExpressionConfigSourceInterceptor.java:18)
at io.smallrye.config.SmallRyeConfigSourceInterceptorContext.proceed(SmallRyeConfigSourceInterceptorContext.java:20)
at io.smallrye.config.SmallRyeConfig.getConfigValue(SmallRyeConfig.java:192)
at io.smallrye.config.SmallRyeConfig.getValue(SmallRyeConfig.java:149)
at io.smallrye.config.SmallRyeConfig.getOptionalValue(SmallRyeConfig.java:209)
at org.jboss.resteasy.microprofile.client.DefaultResponseExceptionMapper.handles(DefaultResponseExceptionMapper.java:27)
at org.jboss.resteasy.microprofile.client.ExceptionMapping.filter(ExceptionMapping.java:62)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.filterResponse(ClientInvocation.java:718)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:492)
at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invokeSync(ClientInvoker.java:149)
at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientInvoker.invoke(ClientInvoker.java:112)
at org.jboss.resteasy.client.jaxrs.internal.proxy.ClientProxy.invoke(ClientProxy.java:76)
at com.sun.proxy.$Proxy77.readUserRoles(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 org.jboss.resteasy.microprofile.client.ProxyInvocationHandler.invoke(ProxyInvocationHandler.java:147)
at com.sun.proxy.$Proxy80.readUserRoles(Unknown Source)
at ch.skycell.security.keycloak.SkyMindKeycloakClient_0f71c4ae6073cff1d752acbd9d4726bd23713289_Synthetic_ClientProxy.readUserRoles(SkyMindKeycloakClient_0f71c4ae6073cff1d752acbd9d4726bd23713289_Synthetic_ClientProxy.zig:131)
at ch.skycell.security.rolesaugmentor.RolesAugmentor.build(RolesAugmentor.java:41)
at ch.skycell.security.rolesaugmentor.RolesAugmentor.augment(RolesAugmentor.java:32)
at ch.skycell.security.rolesaugmentor.RolesAugmentor_ClientProxy.augment(RolesAugmentor_ClientProxy.zig:189)
at io.quarkus.security.runtime.QuarkusIdentityProviderManagerImpl.handleIdentityFromProvider(QuarkusIdentityProviderManagerImpl.java:167)
at io.quarkus.security.runtime.QuarkusIdentityProviderManagerImpl.access$500(QuarkusIdentityProviderManagerImpl.java:30)
at io.quarkus.security.runtime.QuarkusIdentityProviderManagerImpl$2.apply(QuarkusIdentityProviderManagerImpl.java:112)
at io.quarkus.security.runtime.QuarkusIdentityProviderManagerImpl$2.apply(QuarkusIdentityProviderManagerImpl.java:109)
at io.smallrye.mutiny.operators.UniOnItemTransformToUni.invokeAndSubstitute(UniOnItemTransformToUni.java:31)
at io.smallrye.mutiny.operators.UniOnItemTransformToUni$2.onItem(UniOnItemTransformToUni.java:74)
at io.smallrye.mutiny.context.ContextPropagationUniInterceptor$1.lambda$onItem$1(ContextPropagationUniInterceptor.java:31)
at io.smallrye.context.impl.wrappers.SlowContextualExecutor.execute(SlowContextualExecutor.java:19)
at io.smallrye.mutiny.context.ContextPropagationUniInterceptor$1.onItem(ContextPropagationUniInterceptor.java:31)
at io.smallrye.mutiny.operators.UniSerializedSubscriber.onItem(UniSerializedSubscriber.java:85)
at io.smallrye.mutiny.context.ContextPropagationUniInterceptor$1.lambda$onItem$1(ContextPropagationUniInterceptor.java:31)
at io.smallrye.context.impl.wrappers.SlowContextualExecutor.execute(SlowContextualExecutor.java:19)
at io.smallrye.mutiny.context.ContextPropagationUniInterceptor$1.onItem(ContextPropagationUniInterceptor.java:31)
at io.smallrye.mutiny.operators.uni.builders.DefaultUniEmitter.complete(DefaultUniEmitter.java:36)
at io.quarkus.smallrye.jwt.runtime.auth.MpJwtValidator$1.accept(MpJwtValidator.java:54)
at io.quarkus.smallrye.jwt.runtime.auth.MpJwtValidator$1.accept(MpJwtValidator.java:49)
at io.smallrye.mutiny.operators.uni.builders.UniCreateWithEmitter.subscribing(UniCreateWithEmitter.java:24)
at io.smallrye.mutiny.operators.UniSerializedSubscriber.subscribe(UniSerializedSubscriber.java:49)
at io.smallrye.mutiny.operators.AbstractUni.subscribe(AbstractUni.java:31)
at io.smallrye.mutiny.context.ContextPropagationUniInterceptor$2.lambda$subscribing$0(ContextPropagationUniInterceptor.java:47)
at io.smallrye.context.impl.wrappers.SlowContextualExecutor.execute(SlowContextualExecutor.java:19)
at io.smallrye.mutiny.context.ContextPropagationUniInterceptor$2.subscribing(ContextPropagationUniInterceptor.java:47)
at io.smallrye.mutiny.operators.UniSerializedSubscriber.subscribe(UniSerializedSubscriber.java:58)
at io.smallrye.mutiny.operators.UniSerializedSubscriber.subscribe(UniSerializedSubscriber.java:52)
at io.smallrye.mutiny.operators.AbstractUni.subscribe(AbstractUni.java:31)
at io.smallrye.mutiny.operators.UniOnItemTransformToUni.subscribing(UniOnItemTransformToUni.java:65)
at io.smallrye.mutiny.operators.UniSerializedSubscriber.subscribe(UniSerializedSubscriber.java:49)
at io.smallrye.mutiny.operators.AbstractUni.subscribe(AbstractUni.java:31)
at io.smallrye.mutiny.context.ContextPropagationUniInterceptor$2.lambda$subscribing$0(ContextPropagationUniInterceptor.java:47)
at io.smallrye.context.impl.wrappers.SlowContextualExecutor.execute(SlowContextualExecutor.java:19)
at io.smallrye.mutiny.context.ContextPropagationUniInterceptor$2.subscribing(ContextPropagationUniInterceptor.java:47)
at io.smallrye.mutiny.operators.UniSerializedSubscriber.subscribe(UniSerializedSubscriber.java:58)
at io.smallrye.mutiny.operators.UniSerializedSubscriber.subscribe(UniSerializedSubscriber.java:52)
at io.smallrye.mutiny.operators.AbstractUni.subscribe(AbstractUni.java:31)
at io.smallrye.mutiny.operators.UniMemoizeOp.subscribing(UniMemoizeOp.java:70)
at io.smallrye.mutiny.operators.UniSerializedSubscriber.subscribe(UniSerializedSubscriber.java:49)
at io.smallrye.mutiny.operators.AbstractUni.subscribe(AbstractUni.java:31)
at io.smallrye.mutiny.context.ContextPropagationUniInterceptor$2.lambda$subscribing$0(ContextPropagationUniInterceptor.java:47)
at io.smallrye.context.impl.wrappers.SlowContextualExecutor.execute(SlowContextualExecutor.java:19)
at io.smallrye.mutiny.context.ContextPropagationUniInterceptor$2.subscribing(ContextPropagationUniInterceptor.java:47)
at io.smallrye.mutiny.operators.UniSerializedSubscriber.subscribe(UniSerializedSubscriber.java:58)
at io.smallrye.mutiny.operators.UniSerializedSubscriber.subscribe(UniSerializedSubscriber.java:52)
at io.smallrye.mutiny.groups.UniSubscribe.withSubscriber(UniSubscribe.java:50)
at io.quarkus.vertx.http.runtime.security.HttpSecurityRecorder$2.handle(HttpSecurityRecorder.java:104)
at io.quarkus.vertx.http.runtime.security.HttpSecurityRecorder$2.handle(HttpSecurityRecorder.java:51)
at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1038)
at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:137)
at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:132)
at io.quarkus.vertx.http.runtime.cors.CORSFilter.handle(CORSFilter.java:92)
at io.quarkus.vertx.http.runtime.cors.CORSFilter.handle(CORSFilter.java:18)
at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1038)
at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:137)
at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:132)
at io.quarkus.vertx.http.runtime.devmode.VertxHttpHotReplacementSetup$3.handle(VertxHttpHotReplacementSetup.java:86)
at io.quarkus.vertx.http.runtime.devmode.VertxHttpHotReplacementSetup$3.handle(VertxHttpHotReplacementSetup.java:75)
at io.vertx.core.impl.ContextImpl.lambda$null$0(ContextImpl.java:327)
at io.vertx.core.impl.ContextImpl.executeTask(ContextImpl.java:366)
at io.vertx.core.impl.EventLoopContext.lambda$executeAsync$0(EventLoopContext.java:38)
at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:500)
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
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:834)
### Configuration
```properties
quarkus.vault.url=http://url
quarkus.vault.authentication.userpass.username=user
quarkus.vault.authentication.userpass.password=pass
quarkus.vault.kv-secret-engine-mount-path=space
quarkus.vault.secret-config-kv-path=app
```
### Quarkus 1.12.2
| ff70524e983ea787126bdc797605585f0490f24e | 70d565c6f9fb93fc3fe791caca5eba173345d349 | https://github.com/quarkusio/quarkus/compare/ff70524e983ea787126bdc797605585f0490f24e...70d565c6f9fb93fc3fe791caca5eba173345d349 | diff --git a/extensions/vault/runtime/src/main/java/io/quarkus/vault/runtime/config/VaultConfigSource.java b/extensions/vault/runtime/src/main/java/io/quarkus/vault/runtime/config/VaultConfigSource.java
index 439f467bb61..745067cd0e7 100644
--- a/extensions/vault/runtime/src/main/java/io/quarkus/vault/runtime/config/VaultConfigSource.java
+++ b/extensions/vault/runtime/src/main/java/io/quarkus/vault/runtime/config/VaultConfigSource.java
@@ -4,6 +4,7 @@
import static java.util.Collections.emptyMap;
import static java.util.stream.Collectors.toMap;
+import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -14,6 +15,7 @@
import io.quarkus.arc.Arc;
import io.quarkus.vault.VaultKVSecretEngine;
+import io.smallrye.mutiny.infrastructure.Infrastructure;
public class VaultConfigSource implements ConfigSource {
@@ -58,6 +60,11 @@ private Map<String, String> getSecretConfig() {
return cacheEntry.getValue();
}
+ if (!Infrastructure.canCallerThreadBeBlocked()) {
+ // running in a non blocking thread, best effort to return cached values if any
+ return cacheEntry != null ? cacheEntry.getValue() : Collections.emptyMap();
+ }
+
Map<String, String> properties = new HashMap<>();
try { | ['extensions/vault/runtime/src/main/java/io/quarkus/vault/runtime/config/VaultConfigSource.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 15,483,702 | 3,015,594 | 401,071 | 4,279 | 342 | 64 | 7 | 1 | 13,307 | 363 | 3,157 | 151 | 1 | 1 | 2021-03-25T17:22:41 | 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,847 | quarkusio/quarkus/15045/15032 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15032 | https://github.com/quarkusio/quarkus/pull/15045 | https://github.com/quarkusio/quarkus/pull/15045 | 1 | fixes | [Bug] Since 1.11.3 problems reading application.yaml | **Describe the bug**
Quarkus wants to populate a %prod variable while it is running in %dev
1.11.2 was fine
Now with 1.11.3 quarkus wants, that the env variables in %prod are valid while running in %dev
**Expected behavior**
Ignoring the missing environmental variable
**Actual behavior**
`Could not expand value mail.pw in property %prod.quarkus.mailer.password"`
**To Reproduce**
Link to a small reproducer (preferably a Maven project if the issue is not Gradle-specific).
Or attach an archive containing the reproducer to the issue.
Steps to reproduce the behavior:
1. Executing the application
**Configuration**
```properties
# Add your application.properties here, if applicable.
mp:
openapi:
scan:
disable: true
quarkus:
datasource:
db-kind: postgresql
hibernate-orm:
database:
generation: update
http:
root-path: /example-interface-v2/api/v2
"%dev":
quarkus:
datasource:
jdbc:
url: jdbc:postgresql://localhost:5432/TestDB
password: benutzer
username: benutzer
hibernate-orm:
database:
generation: update # Duplicated code line to insert 'drop-and-create' if needed to import the import.sql
log:
min-level: DEBUG
console:
enable: true
format: "%d{HH:mm:ss} %-5p [%c{2.}] (%t) %s%e%n"
color: true
darken: 1
json:
pretty-print: true
http:
port: 8005
mailer:
from: [email protected]
host: smtp.example.de
password: ''
port: 465
ssl: true
username: [email protected]
"%test":
quarkus:
datasource:
db-kind: h2
jdbc:
url: jdbc:h2:mem:test
password: example
username: example
hibernate-orm:
database:
generation: drop-and-create
http:
test-port: 8805
"%prod":
quarkus:
datasource:
jdbc:
url: jdbc:postgresql://${postgres.uri}:${postgres.port}/${postgres.db}
password: ${postgres.password}
username: ${postgres.user}
http:
port: 8082
mailer:
from: [email protected]
host: smtp.example.de
password: ${mail.pw}
port: 465
ssl: true
username: [email protected]
```
**Screenshots**
N/A
**Environment (please complete the following information):**
- Output of `uname -a` or `ver`:
`Linux example-linux 5.8.0-43-generic #49~20.04.1-Ubuntu SMP Fri Feb 5 09:57:56 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux`
- Output of `java -version`:
```
openjdk version "11.0.10" 2021-01-19
OpenJDK Runtime Environment (build 11.0.10+9-Ubuntu-0ubuntu1.20.04)
OpenJDK 64-Bit Server VM (build 11.0.10+9-Ubuntu-0ubuntu1.20.04, mixed mode, sharing)
```
- Quarkus version or git rev: `1.11.3`
- Build tool (ie. output of `mvnw --version` or `gradlew --version`):
```
------------------------------------------------------------
Gradle 6.8
------------------------------------------------------------
Build time: 2021-01-08 16:38:46 UTC
Revision: b7e82460c5373e194fb478a998c4fcfe7da53a7e
Kotlin: 1.4.20
Groovy: 2.5.12
Ant: Apache Ant(TM) version 1.10.9 compiled on September 27 2020
JVM: 11.0.10 (Ubuntu 11.0.10+9-Ubuntu-0ubuntu1.20.04)
OS: Linux 5.8.0-43-generic amd64
```
**Additional context**
If I remove the %prod section my application runs well in %dev mode
Stacktrace
```
{
"timestamp": "2021-02-12T11:07:14.032+01:00",
"sequence": 7490,
"loggerClassName": "org.jboss.logging.Logger",
"loggerName": "io.quarkus.runtime.Application",
"level": "ERROR",
"message": "Failed to start application (with profile dev)",
"threadName": "Quarkus Main Thread",
"threadId": 94,
"mdc": {
},
"ndc": "",
"hostName": "example-linux",
"processName": "example-interface-backend-v2-dev.jar",
"processId": 102797,
"exception": {
"refId": 1,
"exceptionType": "java.util.NoSuchElementException",
"message": "SRCFG00011: Could not expand value mail.pw in property %prod.quarkus.mailer.password",
"frames": [
{
"class": "io.smallrye.config.ExpressionConfigSourceInterceptor",
"method": "lambda$getValue$0",
"line": 44
},
{
"class": "io.smallrye.common.expression.ExpressionNode",
"method": "emit",
"line": 22
},
{
"class": "io.smallrye.common.expression.Expression",
"method": "evaluateException",
"line": 56
},
{
"class": "io.smallrye.common.expression.Expression",
"method": "evaluate",
"line": 70
},
{
"class": "io.smallrye.config.ExpressionConfigSourceInterceptor",
"method": "getValue",
"line": 37
},
{
"class": "io.smallrye.config.ExpressionConfigSourceInterceptor",
"method": "getValue",
"line": 18
},
{
"class": "io.smallrye.config.SmallRyeConfigSourceInterceptorContext",
"method": "proceed",
"line": 20
},
{
"class": "io.smallrye.config.SmallRyeConfig",
"method": "getConfigValue",
"line": 192
},
{
"class": "io.quarkus.vertx.http.runtime.devmode.ConfigDescriptionsSupplier",
"method": "get",
"line": 44
},
{
"class": "io.quarkus.vertx.http.runtime.devmode.ConfigDescriptionsSupplier",
"method": "get",
"line": 13
},
{
"class": "io.quarkus.vertx.http.runtime.devmode.DevConsoleRecorder",
"method": "addInfo",
"line": 37
},
{
"class": "io.quarkus.deployment.steps.DevConsoleProcessor$runtimeTemplates-308161071",
"method": "deploy_9",
"line": 21438
},
{
"class": "io.quarkus.deployment.steps.DevConsoleProcessor$runtimeTemplates-308161071",
"method": "deploy",
"line": 85
},
{
"class": "io.quarkus.runner.ApplicationImpl",
"method": "doStart",
"line": 872
},
{
"class": "io.quarkus.runtime.Application",
"method": "start",
"line": 90
},
{
"class": "io.quarkus.runtime.ApplicationLifecycleManager",
"method": "run",
"line": 97
},
{
"class": "io.quarkus.runtime.Quarkus",
"method": "run",
"line": 66
},
{
"class": "io.quarkus.runtime.Quarkus",
"method": "run",
"line": 42
},
{
"class": "io.quarkus.runtime.Quarkus",
"method": "run",
"line": 119
},
{
"class": "io.quarkus.runner.GeneratedMain",
"method": "main",
"line": 29
},
{
"class": "jdk.internal.reflect.NativeMethodAccessorImpl",
"method": "invoke0"
},
{
"class": "jdk.internal.reflect.NativeMethodAccessorImpl",
"method": "invoke",
"line": 62
},
{
"class": "jdk.internal.reflect.DelegatingMethodAccessorImpl",
"method": "invoke",
"line": 43
},
{
"class": "java.lang.reflect.Method",
"method": "invoke",
"line": 566
},
{
"class": "io.quarkus.runner.bootstrap.StartupActionImpl$3",
"method": "run",
"line": 134
},
{
"class": "java.lang.Thread",
"method": "run",
"line": 834
}
]
}
}
``` | d3c5f118eec2aa81d73350569a3a49d2108308c4 | 14250e609ee561682cc5519ea56b92b7fb2c85f9 | https://github.com/quarkusio/quarkus/compare/d3c5f118eec2aa81d73350569a3a49d2108308c4...14250e609ee561682cc5519ea56b92b7fb2c85f9 | diff --git a/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/devmode/ConfigDescriptionsSupplier.java b/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/devmode/ConfigDescriptionsSupplier.java
index cc78c079960..d2306c581df 100644
--- a/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/devmode/ConfigDescriptionsSupplier.java
+++ b/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/devmode/ConfigDescriptionsSupplier.java
@@ -1,5 +1,7 @@
package io.quarkus.vertx.http.runtime.devmode;
+import static io.smallrye.config.Expressions.withoutExpansion;
+
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -36,13 +38,15 @@ public List<ConfigDescription> get() {
}
}
- for (String propertyName : current.getPropertyNames()) {
- if (properties.contains(propertyName)) {
- continue;
- }
+ withoutExpansion(() -> {
+ for (String propertyName : current.getPropertyNames()) {
+ if (properties.contains(propertyName)) {
+ continue;
+ }
- configDescriptions.add(new ConfigDescription(propertyName, null, null, current.getConfigValue(propertyName)));
- }
+ configDescriptions.add(new ConfigDescription(propertyName, null, null, current.getConfigValue(propertyName)));
+ }
+ });
Collections.sort(configDescriptions);
return configDescriptions; | ['extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/devmode/ConfigDescriptionsSupplier.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 14,664,802 | 2,858,491 | 380,737 | 4,038 | 730 | 108 | 16 | 1 | 8,660 | 611 | 2,048 | 282 | 0 | 4 | 2021-02-12T17:34:35 | 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,836 | quarkusio/quarkus/15390/15357 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15357 | https://github.com/quarkusio/quarkus/pull/15390 | https://github.com/quarkusio/quarkus/pull/15390 | 1 | fixes | RESTEasy Reactive: Chained Sub resources Result in 405 Method not allowed | Describe the bug
Trying to access a chain of sub resources results in a 405 method not allowed. This works perfectly on normal resteasy.
Expected behavior
The sub resources should be located and called
Actual behavior
a 405 is returned
To Reproduce
git clone https://github.com/bcluap/quarkus-examples.git
cd quarkus-examples/resteasy-reactive
mvn clean test
Configuration
Nothing abnormal
Screenshots
Run the reproducer to see failures. Change the pom to non-reactive mode and all tests pass
Environment (please complete the following information):
This is not environment-specific
999-SNAPSHOT and before
Additional context
The project also includes another unrelated bug - uriinfo.getRequestUri.tostring has the query params duplicated
| 118293c6ec2f1f9897ba21f269f612eb673f94c5 | 01284d3d9491d89961da1b8f59e0fab53b75a4fd | https://github.com/quarkusio/quarkus/compare/118293c6ec2f1f9897ba21f269f612eb673f94c5...01284d3d9491d89961da1b8f59e0fab53b75a4fd | diff --git a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/main/java/io/quarkus/resteasy/reactive/server/deployment/ResteasyReactiveProcessor.java b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/main/java/io/quarkus/resteasy/reactive/server/deployment/ResteasyReactiveProcessor.java
index 28a8bfc452e..3abf4d6d562 100644
--- a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/main/java/io/quarkus/resteasy/reactive/server/deployment/ResteasyReactiveProcessor.java
+++ b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/main/java/io/quarkus/resteasy/reactive/server/deployment/ResteasyReactiveProcessor.java
@@ -401,6 +401,15 @@ private boolean hasAnnotation(MethodInfo method, short paramPosition, DotName an
toScan.add(classInfo);
}
}
+ //sub resources can also have just a path annotation
+ //if they are 'intermediate' sub resources
+ for (AnnotationInstance instance : index.getAnnotations(ResteasyReactiveDotNames.PATH)) {
+ if (instance.target().kind() == AnnotationTarget.Kind.METHOD) {
+ MethodInfo method = instance.target().asMethod();
+ ClassInfo classInfo = method.declaringClass();
+ toScan.add(classInfo);
+ }
+ }
while (!toScan.isEmpty()) {
ClassInfo classInfo = toScan.poll();
if (scannedResources.containsKey(classInfo.name()) || | ['extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/main/java/io/quarkus/resteasy/reactive/server/deployment/ResteasyReactiveProcessor.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 14,930,088 | 2,909,449 | 387,173 | 4,097 | 522 | 94 | 9 | 1 | 772 | 99 | 160 | 27 | 1 | 0 | 2021-03-01T21:56:15 | 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,827 | quarkusio/quarkus/15576/15571 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15571 | https://github.com/quarkusio/quarkus/pull/15576 | https://github.com/quarkusio/quarkus/pull/15576 | 1 | fixes | GraphQL queries returning Collection.class are broken in native mode | Any time I attempt to perform a GraphQL query returning a `Collection<Something>` (it works correctly with `List<Something>`) against Quarkus in native mode, I get this
```
2021-03-09 10:43:52,601 ERROR [io.sma.graphql] (vert.x-worker-thread-0) SRGQL012000: Data Fetching Error: java.lang.RuntimeException: Can not load class [java.util.Collection]
at io.quarkus.smallrye.graphql.runtime.spi.QuarkusClassloadingService.loadClass(QuarkusClassloadingService.java:47)
at io.smallrye.graphql.execution.datafetcher.CollectionCreator.newCollection(CollectionCreator.java:27)
at io.smallrye.graphql.execution.datafetcher.helper.AbstractHelper.recursiveTransformCollection(AbstractHelper.java:203)
at io.smallrye.graphql.execution.datafetcher.helper.AbstractHelper.recursiveTransform(AbstractHelper.java:72)
at io.smallrye.graphql.execution.datafetcher.helper.FieldHelper.transformResponse(FieldHelper.java:32)
at io.smallrye.graphql.execution.datafetcher.DefaultDataFetcher.invokeAndTransform(DefaultDataFetcher.java:39)
at io.smallrye.graphql.execution.datafetcher.AbstractDataFetcher.get(AbstractDataFetcher.java:62)
at graphql.execution.ExecutionStrategy.fetchField(ExecutionStrategy.java:270)
at graphql.execution.ExecutionStrategy.resolveFieldWithInfo(ExecutionStrategy.java:203)
at graphql.execution.AsyncExecutionStrategy.execute(AsyncExecutionStrategy.java:60)
at graphql.execution.Execution.executeOperation(Execution.java:165)
at graphql.execution.Execution.execute(Execution.java:104)
at graphql.GraphQL.execute(GraphQL.java:557)
at graphql.GraphQL.parseValidateAndExecute(GraphQL.java:482)
at graphql.GraphQL.executeAsync(GraphQL.java:446)
at graphql.GraphQL.execute(GraphQL.java:377)
at io.smallrye.graphql.execution.ExecutionService.execute(ExecutionService.java:130)
at io.quarkus.smallrye.graphql.runtime.SmallRyeGraphQLExecutionHandler.doRequest(SmallRyeGraphQLExecutionHandler.java:176)
at io.quarkus.smallrye.graphql.runtime.SmallRyeGraphQLExecutionHandler.doRequest(SmallRyeGraphQLExecutionHandler.java:169)
at io.quarkus.smallrye.graphql.runtime.SmallRyeGraphQLExecutionHandler.handlePost(SmallRyeGraphQLExecutionHandler.java:112)
at io.quarkus.smallrye.graphql.runtime.SmallRyeGraphQLExecutionHandler.doHandle(SmallRyeGraphQLExecutionHandler.java:93)
at io.quarkus.smallrye.graphql.runtime.SmallRyeGraphQLExecutionHandler.handle(SmallRyeGraphQLExecutionHandler.java:64)
at io.quarkus.smallrye.graphql.runtime.SmallRyeGraphQLExecutionHandler.handle(SmallRyeGraphQLExecutionHandler.java:37)
at io.vertx.ext.web.impl.BlockingHandlerDecorator.lambda$handle$0(BlockingHandlerDecorator.java:48)
at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$2(ContextImpl.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:834)
at com.oracle.svm.core.thread.JavaThreads.threadStartRoutine(JavaThreads.java:519)
at com.oracle.svm.core.posix.thread.PosixJavaThreads.pthreadStartRoutine(PosixJavaThreads.java:192)
Caused by: java.security.PrivilegedActionException: java.lang.ClassNotFoundException: java.util.Collection
at java.security.AccessController.doPrivileged(AccessController.java:122)
at io.quarkus.smallrye.graphql.runtime.spi.QuarkusClassloadingService.loadClass(QuarkusClassloadingService.java:41)
... 30 more
Caused by: java.lang.ClassNotFoundException: java.util.Collection
at com.oracle.svm.core.hub.ClassForNameSupport.forName(ClassForNameSupport.java:60)
at java.lang.Class.forName(DynamicHub.java:1260)
at io.smallrye.graphql.spi.ClassloadingService.loadClass(ClassloadingService.java:66)
at io.quarkus.smallrye.graphql.runtime.spi.QuarkusClassloadingService.lambda$loadClass$0(QuarkusClassloadingService.java:43)
at java.security.AccessController.doPrivileged(AccessController.java:120)
... 31 more
``` | 4a9153a8e781b23c0fc7a13dc0eee1a57ac84a45 | 9397de4fc049edd113ed1a3282c96aa9e13e35f6 | https://github.com/quarkusio/quarkus/compare/4a9153a8e781b23c0fc7a13dc0eee1a57ac84a45...9397de4fc049edd113ed1a3282c96aa9e13e35f6 | diff --git a/extensions/smallrye-graphql/deployment/src/main/java/io/quarkus/smallrye/graphql/deployment/SmallRyeGraphQLProcessor.java b/extensions/smallrye-graphql/deployment/src/main/java/io/quarkus/smallrye/graphql/deployment/SmallRyeGraphQLProcessor.java
index 50a616dc55d..177613933e3 100644
--- a/extensions/smallrye-graphql/deployment/src/main/java/io/quarkus/smallrye/graphql/deployment/SmallRyeGraphQLProcessor.java
+++ b/extensions/smallrye-graphql/deployment/src/main/java/io/quarkus/smallrye/graphql/deployment/SmallRyeGraphQLProcessor.java
@@ -268,6 +268,7 @@ private Class[] getGraphQLJavaClasses() {
classes.add(graphql.schema.GraphQLSchema.class);
classes.add(graphql.schema.GraphQLTypeReference.class);
classes.add(List.class);
+ classes.add(Collection.class);
return classes.toArray(new Class[] {});
}
diff --git a/integration-tests/smallrye-graphql/src/main/java/io/quarkus/it/smallrye/graphql/GreetingResource.java b/integration-tests/smallrye-graphql/src/main/java/io/quarkus/it/smallrye/graphql/GreetingResource.java
index d5dcd75dab4..e3708cb98a7 100644
--- a/integration-tests/smallrye-graphql/src/main/java/io/quarkus/it/smallrye/graphql/GreetingResource.java
+++ b/integration-tests/smallrye-graphql/src/main/java/io/quarkus/it/smallrye/graphql/GreetingResource.java
@@ -2,6 +2,7 @@
import java.time.LocalTime;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.List;
import org.eclipse.microprofile.config.inject.ConfigProperty;
@@ -36,6 +37,13 @@ public Greetings load(Greetings greetings) {
public List<Greeting> buildInOptions(@Source Greeting greeting) {
List<Greeting> options = new ArrayList<>();
options.add(new Hello());
+ return options;
+ }
+
+ @Name("options2")
+ // make sure that returning Collection.class does not break native mode
+ public Collection<Greeting> buildInOptionsCollection(@Source Greeting greeting) {
+ List<Greeting> options = new ArrayList<>();
options.add(new Morning());
return options;
}
diff --git a/integration-tests/smallrye-graphql/src/test/java/io/quarkus/it/smallrye/graphql/GreetingResourceTest.java b/integration-tests/smallrye-graphql/src/test/java/io/quarkus/it/smallrye/graphql/GreetingResourceTest.java
index fb313728f51..9ff8af8a1d9 100644
--- a/integration-tests/smallrye-graphql/src/test/java/io/quarkus/it/smallrye/graphql/GreetingResourceTest.java
+++ b/integration-tests/smallrye-graphql/src/test/java/io/quarkus/it/smallrye/graphql/GreetingResourceTest.java
@@ -22,6 +22,9 @@ void testEndpoint() {
" options{\\n" +
" message\\n" +
" }\\n" +
+ " options2{\\n" +
+ " message\\n" +
+ " }\\n" +
" }\\n" +
" farewell:farewell{\\n" +
" type\\n" + | ['integration-tests/smallrye-graphql/src/main/java/io/quarkus/it/smallrye/graphql/GreetingResource.java', 'extensions/smallrye-graphql/deployment/src/main/java/io/quarkus/smallrye/graphql/deployment/SmallRyeGraphQLProcessor.java', 'integration-tests/smallrye-graphql/src/test/java/io/quarkus/it/smallrye/graphql/GreetingResourceTest.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 15,183,210 | 2,958,088 | 393,410 | 4,178 | 39 | 6 | 1 | 1 | 4,057 | 133 | 922 | 46 | 0 | 1 | 2021-03-09T11:15:39 | 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,828 | quarkusio/quarkus/15564/15448 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15448 | https://github.com/quarkusio/quarkus/pull/15564 | https://github.com/quarkusio/quarkus/pull/15564 | 1 | fixes | Kafka Schema Registry with basic authentication not working in native mode | **Describe the bug**
When accessing schema registry in **native mode**, the basic authentication is not working and I am getting 401 unauthorized. It works good in the JVM mode
In Native mode below properties are not honored.
```properties
kafka.basic.auth.credentials.source=USER_INFO
kafka.basic.auth.user.info=user:pass
```
stacktrace
```java
2021-03-03 18:43:05,304 ERROR [io.sma.rea.mes.kafka] (vert.x-eventloop-thread-1) SRMSG18206: Unable to write to Kafka from channel movies (topic: movies): org.apache.kafka.common.errors.InvalidConfigurationException: Unauthorized; error code: 401
```
**Expected behavior**
Schema registry with basic authentication works in native mode similar to JVM mode
**Configuration**
```properties
kafka.bootstrap.servers=somehost.us-east4.gcp.confluent.cloud:9092
kafka.security.protocol=SASL_SSL
kafka.sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule \\
required username='secretuser' \\
password='pass';
kafka.sasl.mechanism=PLAIN
kafka.acks=all
kafka.schema.registry.url=https://someurl.confluent.cloud
kafka.basic.auth.credentials.source=USER_INFO
kafka.basic.auth.user.info=user:pass
mp.messaging.outgoing.movies.connector=smallrye-kafka
mp.messaging.outgoing.movies.topic=movies
mp.messaging.outgoing.movies.value.serializer=io.confluent.kafka.serializers.KafkaAvroSerializer
mp.messaging.outgoing.movies.schema.registry.url=${kafka.schema.registry.url}
mp.messaging.outgoing.movies.specific.avro.reader=true
mp.messaging.incoming.movies-from-kafka.connector=smallrye-kafka
mp.messaging.incoming.movies-from-kafka.topic=movies
mp.messaging.incoming.movies-from-kafka.value.deserializer=io.confluent.kafka.serializers.KafkaAvroDeserializer
mp.messaging.incoming.movies-from-kafka.auto.offset.reset=earliest
mp.messaging.incoming.movies-from-kafka.enable.auto.commit=false
mp.messaging.incoming.movies-from-kafka.group.id=movies
mp.messaging.incoming.movies-from-kafka.schema.registry.url=${kafka.schema.registry.url}
mp.messaging.incoming.movies-from-kafka.specific.avro.reader=true
```
**Screenshots**
(If applicable, add screenshots to help explain your problem.)
**Environment (please complete the following information):**
- Output of `uname -a` or `ver`: Linux x64
- Output of `java -version`: Java 11
- GraalVM version (if different from Java):
- Quarkus version or git rev: 1.12.0.Final
- Build tool (ie. output of `mvnw --version` or `gradlew --version`): mvnw
**Additional context**
(Add any other context about the problem here.)
| 557d96cedfbd8b8f7117c3bb74d650822f705b89 | 9a63be3aebfa1e1c6445f20f911a3cfe899568cd | https://github.com/quarkusio/quarkus/compare/557d96cedfbd8b8f7117c3bb74d650822f705b89...9a63be3aebfa1e1c6445f20f911a3cfe899568cd | diff --git a/extensions/kafka-client/deployment/src/main/java/io/quarkus/kafka/client/deployment/KafkaProcessor.java b/extensions/kafka-client/deployment/src/main/java/io/quarkus/kafka/client/deployment/KafkaProcessor.java
index 52886b8f806..93a0b67886b 100644
--- a/extensions/kafka-client/deployment/src/main/java/io/quarkus/kafka/client/deployment/KafkaProcessor.java
+++ b/extensions/kafka-client/deployment/src/main/java/io/quarkus/kafka/client/deployment/KafkaProcessor.java
@@ -62,6 +62,7 @@
import io.quarkus.deployment.builditem.nativeimage.NativeImageResourceBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveHierarchyBuildItem;
+import io.quarkus.deployment.builditem.nativeimage.ServiceProviderBuildItem;
import io.quarkus.deployment.pkg.NativeConfig;
import io.quarkus.kafka.client.runtime.KafkaRecorder;
import io.quarkus.kafka.client.runtime.KafkaRuntimeConfigProducer;
@@ -117,6 +118,7 @@ void contributeClassesToIndex(BuildProducer<AdditionalIndexedClassesBuildItem> a
public void build(
KafkaBuildTimeConfig config,
CombinedIndexBuildItem indexBuildItem, BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
+ BuildProducer<ServiceProviderBuildItem> serviceProviders,
BuildProducer<NativeImageProxyDefinitionBuildItem> proxies,
Capabilities capabilities, BuildProducer<UnremovableBeanBuildItem> beans,
BuildProducer<NativeImageResourceBuildItem> nativeLibs, NativeConfig nativeConfig) {
@@ -172,7 +174,7 @@ public void build(
reflectiveClass.produce(new ReflectiveClassBuildItem(true, false, "java.nio.DirectByteBuffer"));
reflectiveClass.produce(new ReflectiveClassBuildItem(true, false, "sun.misc.Cleaner"));
- handleAvro(reflectiveClass, proxies);
+ handleAvro(reflectiveClass, proxies, serviceProviders);
handleOpenTracing(reflectiveClass, capabilities);
handleStrimziOAuth(reflectiveClass);
if (config.snappyEnabled) {
@@ -253,7 +255,8 @@ private void handleStrimziOAuth(BuildProducer<ReflectiveClassBuildItem> reflecti
}
private void handleAvro(BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
- BuildProducer<NativeImageProxyDefinitionBuildItem> proxies) {
+ BuildProducer<NativeImageProxyDefinitionBuildItem> proxies,
+ BuildProducer<ServiceProviderBuildItem> serviceProviders) {
// Avro - for both Confluent and Apicurio
try {
Class.forName("io.confluent.kafka.serializers.KafkaAvroDeserializer", false,
@@ -292,6 +295,18 @@ private void handleAvro(BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
//ignore, Confluent Avro is not in the classpath
}
+ try {
+ Class.forName("io.confluent.kafka.schemaregistry.client.security.basicauth.BasicAuthCredentialProvider", false,
+ Thread.currentThread().getContextClassLoader());
+ serviceProviders
+ .produce(new ServiceProviderBuildItem(
+ "io.confluent.kafka.schemaregistry.client.security.basicauth.BasicAuthCredentialProvider",
+ "io.confluent.kafka.schemaregistry.client.security.basicauth.SaslBasicAuthCredentialProvider",
+ "io.confluent.kafka.schemaregistry.client.security.basicauth.UrlBasicAuthCredentialProvider",
+ "io.confluent.kafka.schemaregistry.client.security.basicauth.UserInfoCredentialProvider"));
+ } catch (ClassNotFoundException e) {
+ // ignore, Confluent schema registry client not in the classpath
+ }
try {
Class.forName("io.apicurio.registry.utils.serde.AvroKafkaDeserializer", false,
Thread.currentThread().getContextClassLoader()); | ['extensions/kafka-client/deployment/src/main/java/io/quarkus/kafka/client/deployment/KafkaProcessor.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 15,039,141 | 2,931,723 | 390,207 | 4,141 | 1,404 | 260 | 19 | 1 | 2,598 | 177 | 608 | 68 | 1 | 3 | 2021-03-09T07:28:12 | 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,829 | quarkusio/quarkus/15554/15551 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15551 | https://github.com/quarkusio/quarkus/pull/15554 | https://github.com/quarkusio/quarkus/pull/15554 | 1 | fix | Missing description for generated health OpenAPI responses | **Describe the bug**
According to the validator https://apitools.dev/swagger-parser/online/ (and also that in the Azure API Management) the OpenAPI definition generated by the Quarkus Health extension are invalid. The API responses don't have any description.
**Expected behavior**
The individual API responses should each have their description. Like in this extract:
```yaml
get:
tags:
- MicroProfile Health
summary: An aggregated view of the Liveness and Readiness of this application
description: Check the health of the application
operationId: microprofile_health_root
responses:
"200":
description: OK
content:
application/json:
schema:
$ref: '#/components/schemas/HealthCheckResponse'
"503":
description: Service Unavailable
content:
application/json:
schema:
$ref: '#/components/schemas/HealthCheckResponse'
"500":
description: Internal Error
content:
application/json:
schema:
$ref: '#/components/schemas/HealthCheckResponse'
```
**Actual behavior**
Here is an extract of what gets generated:
```yaml
get:
tags:
- MicroProfile Health
summary: An aggregated view of the Liveness and Readiness of this application
description: Check the health of the application
operationId: microprofile_health_root
responses:
"200":
content:
application/json:
schema:
$ref: '#/components/schemas/HealthCheckResponse'
"503":
content:
application/json:
schema:
$ref: '#/components/schemas/HealthCheckResponse'
"500":
content:
application/json:
schema:
$ref: '#/components/schemas/HealthCheckResponse'
```
**To Reproduce**
Create a project including the OpenAPI and Health extensions.
**Configuration**
```properties
quarkus.health.openapi.included=true
```
**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`):
**Additional context**
To be honest I have not yet checked the specs myself, but since two tools reported errors I was assuming that they are correct.
| e3f44c069c60c556ea32c5a773f6cd574c032075 | 8d3352559105da08d62100598be211ccb7bed668 | https://github.com/quarkusio/quarkus/compare/e3f44c069c60c556ea32c5a773f6cd574c032075...8d3352559105da08d62100598be211ccb7bed668 | diff --git a/extensions/smallrye-health/deployment/src/main/java/io/quarkus/smallrye/health/deployment/HealthOpenAPIFilter.java b/extensions/smallrye-health/deployment/src/main/java/io/quarkus/smallrye/health/deployment/HealthOpenAPIFilter.java
index de652acb153..96051e54fbc 100644
--- a/extensions/smallrye-health/deployment/src/main/java/io/quarkus/smallrye/health/deployment/HealthOpenAPIFilter.java
+++ b/extensions/smallrye-health/deployment/src/main/java/io/quarkus/smallrye/health/deployment/HealthOpenAPIFilter.java
@@ -125,14 +125,15 @@ private Operation createReadinessOperation() {
private APIResponses createAPIResponses() {
APIResponses responses = new APIResponsesImpl();
- responses.addAPIResponse("200", createAPIResponse());
- responses.addAPIResponse("503", createAPIResponse());
- responses.addAPIResponse("500", createAPIResponse());
+ responses.addAPIResponse("200", createAPIResponse("OK"));
+ responses.addAPIResponse("503", createAPIResponse("Service Unavailable"));
+ responses.addAPIResponse("500", createAPIResponse("Internal Server Error"));
return responses;
}
- private APIResponse createAPIResponse() {
+ private APIResponse createAPIResponse(String description) {
APIResponse response = new APIResponseImpl();
+ response.setDescription(description);
response.setContent(createContent());
return response;
} | ['extensions/smallrye-health/deployment/src/main/java/io/quarkus/smallrye/health/deployment/HealthOpenAPIFilter.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 15,037,614 | 2,931,337 | 390,158 | 4,141 | 584 | 107 | 9 | 1 | 2,634 | 244 | 524 | 80 | 1 | 3 | 2021-03-08T20:28:16 | 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,831 | quarkusio/quarkus/15508/15487 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15487 | https://github.com/quarkusio/quarkus/pull/15508 | https://github.com/quarkusio/quarkus/pull/15508 | 1 | fixes | OpenShift plugin not deploying the Quarkus App (Regression Issue) | **Describe the bug**
This is a regression issue caused by this commit: https://github.com/quarkusio/quarkus/commit/588db63138715a4e1e2a112676ab9ece2fab36ca
When using the OpenShift Quarkus extension to deploy our Quarkus app:
```
mvn package -Dquarkus.kubernetes.deploy=true
```
Then, the BuildConfig and the Build are triggered in OpenShift and when the Build instance finished, It's deleted (see the commit changes). Then, the DeploymentConfig does not trigger the application startup spite of the image stream is there. For some reason, the DeploymentConfig depends on the build instance to not be deleted.
After reverting the changes in https://github.com/quarkusio/quarkus/commit/588db63138715a4e1e2a112676ab9ece2fab36ca, the Build instance is not deleted and hence everything works fine.
**To Reproduce**
For your Quarkus application:
```
mvn package -Dquarkus.kubernetes.deploy=true
```
The application will not be deployed into OpenShift. The same works for 1.12.0.Final and also by reverting the commit: https://github.com/quarkusio/quarkus/commit/588db63138715a4e1e2a112676ab9ece2fab36ca
**Environment (please complete the following information):**
- OpenShift: 4.6
- Quarkus version or git rev: 1.12.1.Final, 999-SNAPSHOT
**Additional context**
(Add any other context about the problem here.)
| c315109f97b0698443ab949fe864bc8cb53c1838 | 6b7bf736e3d0241393aec9e862c3bb5750f3ff46 | https://github.com/quarkusio/quarkus/compare/c315109f97b0698443ab949fe864bc8cb53c1838...6b7bf736e3d0241393aec9e862c3bb5750f3ff46 | 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 00515e0b537..59f0bc43ac1 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
@@ -1,6 +1,7 @@
package io.quarkus.kubernetes.deployment;
+import static io.quarkus.kubernetes.deployment.Constants.KNATIVE;
import static io.quarkus.kubernetes.deployment.Constants.KUBERNETES;
import static io.quarkus.kubernetes.deployment.Constants.MINIKUBE;
import static io.quarkus.kubernetes.deployment.Constants.OPENSHIFT;
@@ -174,7 +175,11 @@ private DeploymentResultBuildItem deploy(DeploymentTargetEntry deploymentTarget,
try (FileInputStream fis = new FileInputStream(manifest)) {
KubernetesList list = Serialization.unmarshalAsList(fis);
distinct(list.getItems()).forEach(i -> {
- client.resource(i).inNamespace(namespace).deletingExisting().createOrReplace();
+ if (KNATIVE.equals(deploymentTarget.getName().toLowerCase())) {
+ client.resource(i).inNamespace(namespace).deletingExisting().createOrReplace();
+ } else {
+ client.resource(i).inNamespace(namespace).createOrReplace();
+ }
log.info("Applied: " + i.getKind() + " " + i.getMetadata().getName() + ".");
});
| ['extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesDeployer.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 15,034,868 | 2,930,825 | 390,103 | 4,141 | 472 | 82 | 7 | 1 | 1,344 | 156 | 358 | 29 | 3 | 2 | 2021-03-05T18:46: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,833 | quarkusio/quarkus/15446/15440 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15440 | https://github.com/quarkusio/quarkus/pull/15446 | https://github.com/quarkusio/quarkus/pull/15446 | 1 | fixes | OIDC Client stopped working and fails with 500 Internal Server | **Describe the bug**
Having this configuration:
```
# Security
quarkus.oidc.auth-server-url=http://localhost:8180/auth/realms/test-realm
quarkus.oidc.client-id=test-application-client
quarkus.oidc.credentials.secret=test-application-client-secret
quarkus.http.auth.permission.authenticated.paths=/*
quarkus.http.auth.permission.authenticated.policy=authenticated
org.eclipse.microprofile.rest.client.propagateHeaders=Authorization
# OIDC Client Configuration
quarkus.oidc-client.auth-server-url=http://localhost:8180/auth/realms/test-realm
quarkus.oidc-client.client-id=test-application-client
quarkus.oidc-client.credentials.secret=test-application-client-secret
```
And this REALM configuration for Keycloak:
```
"clients": [
{
"clientId": "test-application-client",
"enabled": true,
"protocol": "openid-connect",
"standardFlowEnabled": true,
"implicitFlowEnabled": false,
"directAccessGrantsEnabled": true,
"serviceAccountsEnabled": true,
"clientAuthenticatorType": "client-secret",
"secret": "test-application-client-secret",
"redirectUris": [
"*"
]
}
```
When running our application, it fails with the next exception:
```
2021-03-03 15:34:06,728 ERROR [io.qua.ver.htt.run.QuarkusErrorHandler] (vert.x-eventloop-thread-14) HTTP Request to /rest-pong failed, error id: b24d56d4-cfff-46e3-95e2-b9739e981896-5: io.vertx.core.VertxException: Invalid url: null
at io.vertx.ext.web.client.impl.WebClientBase.requestAbs(WebClientBase.java:256)
at io.vertx.ext.web.client.impl.WebClientBase.requestAbs(WebClientBase.java:246)
at io.vertx.ext.web.client.impl.WebClientBase.postAbs(WebClientBase.java:176)
at io.vertx.mutiny.ext.web.client.WebClient.postAbs(WebClient.java:334)
at io.quarkus.oidc.runtime.OidcProviderClient.getHttpResponse(OidcProviderClient.java:95)
at io.quarkus.oidc.runtime.OidcProviderClient.introspectToken(OidcProviderClient.java:63)
at io.quarkus.oidc.runtime.OidcProvider.introspectToken(OidcProvider.java:115)
at io.quarkus.oidc.runtime.OidcIdentityProvider.introspectTokenUni(OidcIdentityProvider.java:275)
at io.quarkus.oidc.runtime.OidcIdentityProvider.verifyTokenUni(OidcIdentityProvider.java:251)
at io.quarkus.oidc.runtime.OidcIdentityProvider.createSecurityIdentityWithOidcServer(OidcIdentityProvider.java:122)
at io.quarkus.oidc.runtime.OidcIdentityProvider.access$200(OidcIdentityProvider.java:34)
at io.quarkus.oidc.runtime.OidcIdentityProvider$3.apply(OidcIdentityProvider.java:115)
at io.quarkus.oidc.runtime.OidcIdentityProvider$3.apply(OidcIdentityProvider.java:109)
```
Our project was working fine before these changes were merged: https://github.com/quarkusio/quarkus/pull/14953. So, this is a regression issue.
**To Reproduce**
1- git clone https://github.com/quarkus-qe/beefy-scenarios
2- cd beefy-scenarios/013-quarkus-oidc-restclient
4- mvn clean install (it needs to have built quarkus master locally)
**Environment (please complete the following information):**
- Quarkus version or git rev: 999-SNAPSHOT
| b6fd09a619a24fedd23101d972643e7018bc7cf6 | c37df00b056234d809b8eec9a30f8a3453b149c5 | https://github.com/quarkusio/quarkus/compare/b6fd09a619a24fedd23101d972643e7018bc7cf6...c37df00b056234d809b8eec9a30f8a3453b149c5 | diff --git a/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/OidcConfigurationMetadata.java b/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/OidcConfigurationMetadata.java
index e77d507217a..00c6aa56c18 100644
--- a/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/OidcConfigurationMetadata.java
+++ b/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/OidcConfigurationMetadata.java
@@ -3,6 +3,14 @@
import io.vertx.core.json.JsonObject;
public class OidcConfigurationMetadata {
+ private static final String ISSUER = "issuer";
+ private static final String TOKEN_ENDPOINT = "token_endpoint";
+ private static final String INTROSPECTION_ENDPOINT = "introspection_endpoint";
+ private static final String AUTHORIZATION_ENDPOINT = "authorization_endpoint";
+ private static final String JWKS_ENDPOINT = "jwks_uri";
+ private static final String USERINFO_ENDPOINT = "userinfo_endpoint";
+ private static final String END_SESSION_ENDPOINT = "end_session_endpoint";
+
private final String tokenUri;
private final String introspectionUri;
private final String authorizationUri;
@@ -28,13 +36,13 @@ public OidcConfigurationMetadata(String tokenUri,
}
public OidcConfigurationMetadata(JsonObject wellKnownConfig) {
- this.tokenUri = wellKnownConfig.getString("token_endpoint");
- this.introspectionUri = wellKnownConfig.getString("token_introspection_endpoint");
- this.authorizationUri = wellKnownConfig.getString("authorization_endpoint");
- this.jsonWebKeySetUri = wellKnownConfig.getString("jwks_uri");
- this.userInfoUri = wellKnownConfig.getString("userinfo_endpoint");
- this.endSessionUri = wellKnownConfig.getString("end_session_endpoint");
- this.issuer = wellKnownConfig.getString("issuer");
+ this.tokenUri = wellKnownConfig.getString(TOKEN_ENDPOINT);
+ this.introspectionUri = wellKnownConfig.getString(INTROSPECTION_ENDPOINT);
+ this.authorizationUri = wellKnownConfig.getString(AUTHORIZATION_ENDPOINT);
+ this.jsonWebKeySetUri = wellKnownConfig.getString(JWKS_ENDPOINT);
+ this.userInfoUri = wellKnownConfig.getString(USERINFO_ENDPOINT);
+ this.endSessionUri = wellKnownConfig.getString(END_SESSION_ENDPOINT);
+ this.issuer = wellKnownConfig.getString(ISSUER);
}
public String getTokenUri() {
diff --git a/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/OidcIdentityProvider.java b/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/OidcIdentityProvider.java
index ed943b65899..038ff30a244 100644
--- a/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/OidcIdentityProvider.java
+++ b/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/OidcIdentityProvider.java
@@ -141,10 +141,10 @@ public Uni<SecurityIdentity> apply(TokenVerificationResult result, Throwable t)
tokenJson = OidcUtils.decodeJwtContent(tokenCred.getToken());
}
if (tokenJson != null) {
- OidcUtils.validatePrimaryJwtTokenType(resolvedContext.oidcConfig.token, tokenJson);
- JsonObject rolesJson = getRolesJson(vertxContext, resolvedContext, tokenCred, tokenJson,
- userInfo);
try {
+ OidcUtils.validatePrimaryJwtTokenType(resolvedContext.oidcConfig.token, tokenJson);
+ JsonObject rolesJson = getRolesJson(vertxContext, resolvedContext, tokenCred, tokenJson,
+ userInfo);
SecurityIdentity securityIdentity = validateAndCreateIdentity(vertxContext, tokenCred,
resolvedContext.oidcConfig,
tokenJson, rolesJson, userInfo);
@@ -154,7 +154,7 @@ public Uni<SecurityIdentity> apply(TokenVerificationResult result, Throwable t)
return Uni.createFrom().item(securityIdentity);
}
} catch (Throwable ex) {
- return Uni.createFrom().failure(ex);
+ return Uni.createFrom().failure(new AuthenticationFailedException(ex));
}
} else if (tokenCred instanceof IdTokenCredential
|| tokenCred instanceof AccessTokenCredential
diff --git a/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/OidcRecorder.java b/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/OidcRecorder.java
index 2c1d2c69ea9..e6bb891ba32 100644
--- a/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/OidcRecorder.java
+++ b/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/OidcRecorder.java
@@ -160,10 +160,6 @@ private Uni<TenantConfigContext> createTenantContext(Vertx vertx, OidcTenantConf
}
}
- final long connectionRetryCount = OidcCommonUtils.getConnectionRetryCount(oidcConfig);
- if (connectionRetryCount > 1) {
- LOG.infof("Connecting to IDP for up to %d times every 2 seconds", connectionRetryCount);
- }
return createOidcProvider(oidcConfig, tlsConfig, vertx)
.onItem().transform(p -> new TenantConfigContext(p, oidcConfig));
}
diff --git a/integration-tests/oidc-tenancy/src/main/java/io/quarkus/it/keycloak/OidcResource.java b/integration-tests/oidc-tenancy/src/main/java/io/quarkus/it/keycloak/OidcResource.java
index 9bd0f16d2a0..0d4b3e0b263 100644
--- a/integration-tests/oidc-tenancy/src/main/java/io/quarkus/it/keycloak/OidcResource.java
+++ b/integration-tests/oidc-tenancy/src/main/java/io/quarkus/it/keycloak/OidcResource.java
@@ -41,7 +41,7 @@ public String discovery() {
final String baseUri = ui.getBaseUriBuilder().path("oidc").build().toString();
return "{" +
" \\"token_endpoint\\":" + "\\"" + baseUri + "/token\\"," +
- " \\"token_introspection_endpoint\\":" + "\\"" + baseUri + "/introspect\\"," +
+ " \\"introspection_endpoint\\":" + "\\"" + baseUri + "/introspect\\"," +
" \\"jwks_uri\\":" + "\\"" + baseUri + "/jwks\\"" +
" }";
}
diff --git a/integration-tests/oidc-wiremock/src/test/java/io/quarkus/it/keycloak/KeycloakTestResource.java b/integration-tests/oidc-wiremock/src/test/java/io/quarkus/it/keycloak/KeycloakTestResource.java
index 405bcfdceba..a1eda7a792c 100644
--- a/integration-tests/oidc-wiremock/src/test/java/io/quarkus/it/keycloak/KeycloakTestResource.java
+++ b/integration-tests/oidc-wiremock/src/test/java/io/quarkus/it/keycloak/KeycloakTestResource.java
@@ -41,7 +41,7 @@ public Map<String, String> start() {
.withBody("{\\n" +
" \\"jwks_uri\\": \\"" + server.baseUrl()
+ "/auth/realms/quarkus/protocol/openid-connect/certs\\",\\n" +
- " \\"token_introspection_endpoint\\": \\"" + server.baseUrl()
+ " \\"introspection_endpoint\\": \\"" + server.baseUrl()
+ "/auth/realms/quarkus/protocol/openid-connect/token/introspect\\",\\n"
+ "\\"issuer\\" : \\"https://server.example.com\\""
+ "}")));
diff --git a/integration-tests/oidc/src/test/java/io/quarkus/it/keycloak/BearerTokenAuthorizationTest.java b/integration-tests/oidc/src/test/java/io/quarkus/it/keycloak/BearerTokenAuthorizationTest.java
index a6e266bddf5..b5a88e6f758 100644
--- a/integration-tests/oidc/src/test/java/io/quarkus/it/keycloak/BearerTokenAuthorizationTest.java
+++ b/integration-tests/oidc/src/test/java/io/quarkus/it/keycloak/BearerTokenAuthorizationTest.java
@@ -133,13 +133,21 @@ public void testDeniedAccessAdminResource() {
}
@Test
- public void testDeniedNoBearerToken() {
+ public void testVerificationFailedNoBearerToken() {
RestAssured.given()
.when().get("/api/users/me").then()
.statusCode(401);
}
+ @Test
+ public void testVerificationFailedInvalidToken() {
+ RestAssured.given().auth().oauth2("123")
+ .when().get("/api/users/me").then()
+ .statusCode(401);
+ }
+
//see https://github.com/quarkusio/quarkus/issues/5809
+ @Test
@RepeatedTest(20)
public void testOidcAndVertxHandler() {
RestAssured.given().auth().oauth2(getAccessToken("alice")) | ['extensions/oidc/runtime/src/main/java/io/quarkus/oidc/OidcConfigurationMetadata.java', 'integration-tests/oidc/src/test/java/io/quarkus/it/keycloak/BearerTokenAuthorizationTest.java', 'integration-tests/oidc-tenancy/src/main/java/io/quarkus/it/keycloak/OidcResource.java', 'extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/OidcIdentityProvider.java', 'extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/OidcRecorder.java', 'integration-tests/oidc-wiremock/src/test/java/io/quarkus/it/keycloak/KeycloakTestResource.java'] | {'.java': 6} | 6 | 6 | 0 | 0 | 6 | 15,031,445 | 2,930,145 | 390,019 | 4,139 | 2,556 | 471 | 34 | 3 | 3,121 | 163 | 806 | 67 | 4 | 3 | 2021-03-03T17:12:10 | 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,834 | quarkusio/quarkus/15412/12355 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/12355 | https://github.com/quarkusio/quarkus/pull/15412 | https://github.com/quarkusio/quarkus/pull/15412 | 1 | resolves | NullPointerException when rendering Qute templates as XML | **Describe the bug**
```
Caused by: java.lang.NullPointerException
at io.quarkus.qute.runtime.TemplateProducer$InjectableTemplateInstanceImpl.templateInstance(TemplateProducer.java:168)
at io.quarkus.qute.runtime.TemplateProducer$InjectableTemplateInstanceImpl.render(TemplateProducer.java:149)
at micro.apps.greeting.GreetingResource.hello(GreetingResource.java:30)
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 org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:167)
at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:130)
at org.jboss.resteasy.core.ResourceMethodInvoker.internalInvokeOnTarget(ResourceMethodInvoker.java:638)
at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTargetAfterFilter(ResourceMethodInvoker.java:504)
at org.jboss.resteasy.core.ResourceMethodInvoker.lambda$invokeOnTarget$2(ResourceMethodInvoker.java:454)
at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364)
at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:456)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:417)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:391)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:68)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:488)
... 20 more
```
**Expected behavior**
Render the template
**Actual behavior**
NullPointerException is thrown
**To Reproduce**
[greeting-quarkus.zip](https://github.com/quarkusio/quarkus/files/5286885/greeting-quarkus.zip)
Steps to reproduce the behavior:
1. Run `mvn quarkus:dev` in the attached project above
2. `curl http://localhost:8080/greeting` and you should see the error
**Environment (please complete the following information):**
- Output of `uname -a` or `ver`: Fedora 32
- Output of `java -version`: 11
- GraalVM version (if different from Java): Not used
- Quarkus version or git rev: 1.8.1.Final
- Build tool (ie. output of `mvnw --version` or `gradlew --version`):
```
Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
Maven home: /home/linuxbrew/.linuxbrew/Cellar/maven/3.6.3/libexec
Java version: 11.0.8, vendor: N/A, runtime: /home/ggastald/.sdkman/candidates/java/11.0.8-open
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "5.8.7-200.fc32.x86_64", arch: "amd64", family: "unix"
``` | 172446c920decdf3fc32f03613a486fa63b20c35 | 2c14a4f97e333532a896eb2e1879444489cd4c1f | https://github.com/quarkusio/quarkus/compare/172446c920decdf3fc32f03613a486fa63b20c35...2c14a4f97e333532a896eb2e1879444489cd4c1f | diff --git a/extensions/qute/deployment/src/main/java/io/quarkus/qute/deployment/QuteProcessor.java b/extensions/qute/deployment/src/main/java/io/quarkus/qute/deployment/QuteProcessor.java
index ae0c4a11281..1b642f5e560 100644
--- a/extensions/qute/deployment/src/main/java/io/quarkus/qute/deployment/QuteProcessor.java
+++ b/extensions/qute/deployment/src/main/java/io/quarkus/qute/deployment/QuteProcessor.java
@@ -84,6 +84,7 @@
import io.quarkus.devconsole.spi.DevConsoleRouteBuildItem;
import io.quarkus.gizmo.ClassOutput;
import io.quarkus.panache.common.deployment.PanacheEntityClassesBuildItem;
+import io.quarkus.qute.CheckedTemplate;
import io.quarkus.qute.Engine;
import io.quarkus.qute.EngineBuilder;
import io.quarkus.qute.Expression;
@@ -104,7 +105,6 @@
import io.quarkus.qute.UserTagSectionHelper;
import io.quarkus.qute.Variant;
import io.quarkus.qute.WhenSectionHelper;
-import io.quarkus.qute.api.CheckedTemplate;
import io.quarkus.qute.api.ResourcePath;
import io.quarkus.qute.deployment.TemplatesAnalysisBuildItem.TemplateAnalysis;
import io.quarkus.qute.deployment.TypeCheckExcludeBuildItem.TypeCheck;
@@ -212,10 +212,11 @@ AdditionalBeanBuildItem additionalBeans() {
}
@BuildStep
- List<CheckedTemplateBuildItem> collectTemplateTypeInfo(BeanArchiveIndexBuildItem index,
+ List<CheckedTemplateBuildItem> collectCheckedTemplates(BeanArchiveIndexBuildItem index,
BuildProducer<BytecodeTransformerBuildItem> transformers,
List<TemplatePathBuildItem> templatePaths,
- List<CheckedTemplateAdapterBuildItem> templateAdaptorBuildItems) {
+ List<CheckedTemplateAdapterBuildItem> templateAdaptorBuildItems,
+ QuteConfig config) {
List<CheckedTemplateBuildItem> ret = new ArrayList<>();
Map<DotName, CheckedTemplateAdapter> adaptors = new HashMap<>();
@@ -246,6 +247,20 @@ List<CheckedTemplateBuildItem> collectTemplateTypeInfo(BeanArchiveIndexBuildItem
checkedTemplateAnnotations.addAll(index.getIndex().getAnnotations(Names.CHECKED_TEMPLATE_OLD));
checkedTemplateAnnotations.addAll(index.getIndex().getAnnotations(Names.CHECKED_TEMPLATE));
+ // Build a set of file paths for validation
+ Set<String> filePaths = new HashSet<String>();
+ for (TemplatePathBuildItem templatePath : templatePaths) {
+ String path = templatePath.getPath();
+ filePaths.add(path);
+ // Also add version without suffix from the path
+ // For example for "items.html" also add "items"
+ for (String suffix : config.suffixes) {
+ if (path.endsWith(suffix)) {
+ filePaths.add(path.substring(0, path.length() - (suffix.length() + 1)));
+ }
+ }
+ }
+
for (AnnotationInstance annotation : checkedTemplateAnnotations) {
if (annotation.target().kind() != Kind.CLASS) {
continue;
@@ -293,7 +308,23 @@ List<CheckedTemplateBuildItem> collectTemplateTypeInfo(BeanArchiveIndexBuildItem
templatePath, methodInfo.declaringClass().name(), methodInfo,
checkedTemplateMethod.declaringClass().name(), checkedTemplateMethod));
}
- checkTemplatePath(templatePath, templatePaths, classInfo, methodInfo);
+ if (!filePaths.contains(templatePath)) {
+ List<String> startsWith = new ArrayList<>();
+ for (String filePath : filePaths) {
+ if (filePath.startsWith(templatePath)) {
+ startsWith.add(filePath);
+ }
+ }
+ if (startsWith.isEmpty()) {
+ throw new TemplateException(
+ "No template matching the path " + templatePath + " could be found for: "
+ + classInfo.name() + "." + methodInfo.name());
+ } else {
+ throw new TemplateException(
+ startsWith + " match the path " + templatePath
+ + " but the file suffix is not configured via the quarkus.qute.suffixes property");
+ }
+ }
Map<String, String> bindings = new HashMap<>();
List<Type> parameters = methodInfo.parameters();
@@ -318,26 +349,6 @@ List<CheckedTemplateBuildItem> collectTemplateTypeInfo(BeanArchiveIndexBuildItem
return ret;
}
- private void checkTemplatePath(String templatePath, List<TemplatePathBuildItem> templatePaths, ClassInfo enclosingClass,
- MethodInfo methodInfo) {
- for (TemplatePathBuildItem templatePathBuildItem : templatePaths) {
- // perfect match
- if (templatePathBuildItem.getPath().equals(templatePath)) {
- return;
- }
- // if our templatePath is "Foo/hello", make it match "Foo/hello.txt"
- // if they're not equal and they start with our path, there must be something left after
- if (templatePathBuildItem.getPath().startsWith(templatePath)
- // check that we have an extension, let variant matching work later
- && templatePathBuildItem.getPath().charAt(templatePath.length()) == '.') {
- return;
- }
- }
- throw new TemplateException(
- "Declared template " + templatePath + " could not be found. Either add it or delete its declaration in "
- + enclosingClass.name().toString('.') + "." + methodInfo.name());
- }
-
@BuildStep
TemplatesAnalysisBuildItem analyzeTemplates(List<TemplatePathBuildItem> templatePaths,
List<CheckedTemplateBuildItem> checkedTemplates, List<MessageBundleMethodBuildItem> messageBundleMethods) {
@@ -1054,7 +1065,8 @@ void validateTemplateInjectionPoints(QuteConfig config, List<TemplatePathBuildIt
if (name != null) {
// For "@Inject Template items" we try to match "items"
// For "@Location("github/pulls") Template pulls" we try to match "github/pulls"
- if (filePaths.stream().noneMatch(path -> path.endsWith(name))) {
+ // For "@Location("foo/bar/baz.txt") Template baz" we try to match "foo/bar/baz.txt"
+ if (!filePaths.contains(name)) {
validationErrors.produce(new ValidationErrorBuildItem(
new TemplateException("No template found for " + injectionPoint.getTargetInfo())));
}
diff --git a/extensions/resteasy-qute/deployment/src/test/java/io/quarkus/qute/resteasy/deployment/MissingTemplateTest.java b/extensions/resteasy-qute/deployment/src/test/java/io/quarkus/qute/resteasy/deployment/MissingTemplateTest.java
index 99e063bafd4..f6cf3a3dbba 100644
--- a/extensions/resteasy-qute/deployment/src/test/java/io/quarkus/qute/resteasy/deployment/MissingTemplateTest.java
+++ b/extensions/resteasy-qute/deployment/src/test/java/io/quarkus/qute/resteasy/deployment/MissingTemplateTest.java
@@ -1,11 +1,13 @@
package io.quarkus.qute.resteasy.deployment;
+import static org.junit.jupiter.api.Assertions.fail;
+
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
-import org.wildfly.common.Assert;
+import io.quarkus.qute.TemplateException;
import io.quarkus.test.QuarkusUnitTest;
public class MissingTemplateTest {
@@ -15,13 +17,10 @@ public class MissingTemplateTest {
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.addClass(MissingTemplateResource.class)
.addAsResource("templates/MissingTemplateResource/hello.txt"))
- .assertException(t -> {
- t.printStackTrace();
- Assert.assertTrue(t.getMessage().contains(
- "Declared template MissingTemplateResource/missingTemplate could not be found. Either add it or delete its declaration in io.quarkus.qute.resteasy.deployment.MissingTemplateResource$Templates.missingTemplate"));
- });
+ .setExpectedException(TemplateException.class);
@Test
public void emptyTest() {
+ fail();
}
}
diff --git a/extensions/resteasy-reactive/quarkus-resteasy-reactive-qute/deployment/src/test/java/io/quarkus/resteasy/reactive/qute/deployment/MissingTemplateTest.java b/extensions/resteasy-reactive/quarkus-resteasy-reactive-qute/deployment/src/test/java/io/quarkus/resteasy/reactive/qute/deployment/MissingTemplateTest.java
index d9f8ad56ebd..c17fda7ce45 100644
--- a/extensions/resteasy-reactive/quarkus-resteasy-reactive-qute/deployment/src/test/java/io/quarkus/resteasy/reactive/qute/deployment/MissingTemplateTest.java
+++ b/extensions/resteasy-reactive/quarkus-resteasy-reactive-qute/deployment/src/test/java/io/quarkus/resteasy/reactive/qute/deployment/MissingTemplateTest.java
@@ -1,11 +1,13 @@
package io.quarkus.resteasy.reactive.qute.deployment;
+import static org.junit.jupiter.api.Assertions.fail;
+
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
-import org.wildfly.common.Assert;
+import io.quarkus.qute.TemplateException;
import io.quarkus.test.QuarkusUnitTest;
public class MissingTemplateTest {
@@ -15,13 +17,10 @@ public class MissingTemplateTest {
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.addClass(MissingTemplateResource.class)
.addAsResource("templates/MissingTemplateResource/hello.txt"))
- .assertException(t -> {
- t.printStackTrace();
- Assert.assertTrue(t.getMessage().contains(
- "Declared template MissingTemplateResource/missingTemplate could not be found. Either add it or delete its declaration in io.quarkus.resteasy.reactive.qute.deployment.MissingTemplateResource$Templates.missingTemplate"));
- });
+ .setExpectedException(TemplateException.class);
@Test
public void emptyTest() {
+ fail();
}
} | ['extensions/resteasy-qute/deployment/src/test/java/io/quarkus/qute/resteasy/deployment/MissingTemplateTest.java', 'extensions/resteasy-reactive/quarkus-resteasy-reactive-qute/deployment/src/test/java/io/quarkus/resteasy/reactive/qute/deployment/MissingTemplateTest.java', 'extensions/qute/deployment/src/main/java/io/quarkus/qute/deployment/QuteProcessor.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 14,963,764 | 2,916,965 | 388,020 | 4,099 | 3,542 | 640 | 62 | 1 | 2,901 | 163 | 722 | 53 | 2 | 2 | 2021-03-02T15:24:02 | 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,835 | quarkusio/quarkus/15396/15389 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15389 | https://github.com/quarkusio/quarkus/pull/15396 | https://github.com/quarkusio/quarkus/pull/15396 | 1 | fixes | ENVs required in prod profile break dev profile but only when using the built artifact | **Describe the bug**
Quarkus tries to resolve ENVs for profiles which are not active. This breaks other profiles. This only happens with the built jar. It works fine with the `quarkus:dev` plugin.
Example:
Empty Quarkus project with `%prod.quarkus.http.port=${HTTP_PORT}` as the only configuration in `application.properties` breaks every other profile when running from jar if `HTTP_PORT` is not exported.
**Expected behavior**
If `HTTP_PORT` is not set application should start fine with any profile but `prod`. `HTTP_PORT` is only required in `prod`.
**Actual behavior**
Quarkus tries to resolve `HTTP_PORT` regardless of the active profile and fails to start.
```
QUARKUS_PROFILE=foo java -jar target/quarkus-app/quarkus-run.jar
One or more configuration errors have prevented the application from starting. The errors are:
- SRCFG00011: Could not expand value HTTP_PORT in property quarkus.http.port
```
**To Reproduce**
https://github.com/atamanroman/quarkus-profile-dev-prod-repro
Steps to reproduce here:
https://github.com/atamanroman/quarkus-profile-dev-prod-repro/blob/main/README.md
**Additional context**
This issue was opened after discussion in [this zulip thread](https://quarkusio.zulipchat.com/#narrow/stream/187030-users/topic/ENVs.20required.20in.20prod.20profile.20break.20dev).
| dad1c1118f47c9c2bf9c4fdb55c90fef4a7bdcde | 8d85f2299f4b0565fee348bed5bba5a711032a1e | https://github.com/quarkusio/quarkus/compare/dad1c1118f47c9c2bf9c4fdb55c90fef4a7bdcde...8d85f2299f4b0565fee348bed5bba5a711032a1e | diff --git a/core/deployment/src/main/java/io/quarkus/deployment/configuration/BuildTimeConfigurationReader.java b/core/deployment/src/main/java/io/quarkus/deployment/configuration/BuildTimeConfigurationReader.java
index 109885691ee..48572a88c31 100644
--- a/core/deployment/src/main/java/io/quarkus/deployment/configuration/BuildTimeConfigurationReader.java
+++ b/core/deployment/src/main/java/io/quarkus/deployment/configuration/BuildTimeConfigurationReader.java
@@ -296,7 +296,7 @@ ReadResult run() {
nameBuilder.setLength(len);
}
// sweep-up
- for (String propertyName : config.getPropertyNames()) {
+ for (String propertyName : getAllProperties()) {
if (propertyName.equals(ConfigSource.CONFIG_ORDINAL)) {
continue;
}
@@ -718,6 +718,19 @@ private Converter<?> getConverter(SmallRyeConfig config, Field field, ConverterT
convByType.put(valueType, converter);
return converter;
}
+
+ /**
+ * We collect all properties from ConfigSources, because Config#getPropertyNames exclude the active profiled
+ * properties, meaning that the property is written in the default config source unprofiled. This may cause
+ * issues if we run with a different profile and fallback to defaults.
+ */
+ private Set<String> getAllProperties() {
+ Set<String> properties = new HashSet<>();
+ for (ConfigSource configSource : config.getConfigSources()) {
+ properties.addAll(configSource.getPropertyNames());
+ }
+ return properties;
+ }
}
public static final class ReadResult {
diff --git a/extensions/arc/deployment/src/test/java/io/quarkus/arc/test/config/ConfigDefaultValues.java b/extensions/arc/deployment/src/test/java/io/quarkus/arc/test/config/ConfigDefaultValuesTest.java
similarity index 63%
rename from extensions/arc/deployment/src/test/java/io/quarkus/arc/test/config/ConfigDefaultValues.java
rename to extensions/arc/deployment/src/test/java/io/quarkus/arc/test/config/ConfigDefaultValuesTest.java
index 9de4efe466e..b37b7083c23 100644
--- a/extensions/arc/deployment/src/test/java/io/quarkus/arc/test/config/ConfigDefaultValues.java
+++ b/extensions/arc/deployment/src/test/java/io/quarkus/arc/test/config/ConfigDefaultValuesTest.java
@@ -15,12 +15,17 @@
import io.quarkus.test.QuarkusUnitTest;
-public class ConfigDefaultValues {
+public class ConfigDefaultValuesTest {
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
- .addAsResource(new StringAsset("config_ordinal=1000\\n" +
- "my.prop=1234\\n"), "application.properties"));
+ .addAsResource(new StringAsset(
+ "config_ordinal=1000\\n" +
+ "my.prop=1234\\n" +
+ "%prod.my.prop=1234\\n" +
+ "%dev.my.prop=5678\\n" +
+ "%test.my.prop=1234"),
+ "application.properties"));
@Inject
Config config;
@@ -38,6 +43,17 @@ void configDefaultValues() {
assertEquals("1234", applicationProperties.getValue("my.prop"));
}
+ @Test
+ void profileDefaultValues() {
+ ConfigSource defaultValues = getConfigSourceByName("PropertiesConfigSource[source=Specified default values]");
+ assertNotNull(defaultValues);
+ assertEquals("1234", defaultValues.getValue("my.prop"));
+ assertEquals("1234", defaultValues.getValue("%prod.my.prop"));
+ assertEquals("5678", defaultValues.getValue("%dev.my.prop"));
+ assertEquals("1234", defaultValues.getValue("%test.my.prop"));
+ assertEquals("1234", config.getValue("my.prop", String.class));
+ }
+
private ConfigSource getConfigSourceByName(String name) {
for (ConfigSource configSource : config.getConfigSources()) {
if (configSource.getName().contains(name)) { | ['core/deployment/src/main/java/io/quarkus/deployment/configuration/BuildTimeConfigurationReader.java', 'extensions/arc/deployment/src/test/java/io/quarkus/arc/test/config/ConfigDefaultValues.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 14,950,138 | 2,913,946 | 387,682 | 4,097 | 780 | 132 | 15 | 1 | 1,352 | 145 | 327 | 35 | 3 | 1 | 2021-03-02T01:09:03 | 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,803 | quarkusio/quarkus/15942/15852 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15852 | https://github.com/quarkusio/quarkus/pull/15942 | https://github.com/quarkusio/quarkus/pull/15942 | 1 | fixes | RESTEasy Reactive: UniInvoker signatures are wrong | Due to how we implement it, all its return types are `Uni<?>` instead of the more useful `Uni<R>` for methods like `<R> get(Class<R>)`, forcing users to cast the return types to the right type:
```java
UniInvoker invocation = target.request().rx(UniInvoker.class);
Uni<String> ret = (Uni<String>) invocation.get(String.class);
```
This is because we implemented it with:
```java
public class UniInvoker extends AbstractRxInvoker<Uni<?>> {}
...
public abstract class AbstractRxInvoker<T> implements RxInvoker<T> {
@Override
public <R> T get(Class<R> responseType) {
return method("GET", responseType);
}
}
```
Now, for some reason the JAXRS interface is:
```java
public interface RxInvoker<T> {
public <R> T get(Class<R> responseType);
}
```
Which is pretty useless. We could mitigate this by making `UniInvoker` generic.
Or we could do like for `MultiInvoker` (for some reason this does pass the Java type system):
```java
public class MultiInvoker extends AbstractRxInvoker<Multi<?>> {
@SuppressWarnings("unchecked")
@Override
public <R> Multi<R> get(Class<R> responseType) {
return (Multi<R>) super.get(responseType);
}
}
```
Perhaps we should do both (generify and fix the signature via that weirdly allowed covariant override)? | 3a8c2eaad9f4e766bc9ef1f125103a1bf3fcf032 | 76409e1b274f8b0ed6710e16eac20a2efb200251 | https://github.com/quarkusio/quarkus/compare/3a8c2eaad9f4e766bc9ef1f125103a1bf3fcf032...76409e1b274f8b0ed6710e16eac20a2efb200251 | diff --git a/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/UniInvoker.java b/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/UniInvoker.java
index 335231f54d8..ab96cb7ab95 100644
--- a/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/UniInvoker.java
+++ b/independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/UniInvoker.java
@@ -3,6 +3,7 @@
import io.smallrye.mutiny.Uni;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.GenericType;
+import javax.ws.rs.core.Response;
public class UniInvoker extends AbstractRxInvoker<Uni<?>> {
@@ -18,4 +19,123 @@ public <R> Uni<R> method(String name, Entity<?> entity, GenericType<R> responseT
return Uni.createFrom().completionStage(invoker.method(name, entity, responseType));
}
+ @Override
+ public Uni<Response> get() {
+ return (Uni<Response>) super.get();
+ }
+
+ @Override
+ public <T> Uni<T> get(Class<T> responseType) {
+ return (Uni<T>) super.get(responseType);
+ }
+
+ @Override
+ public <T> Uni<T> get(GenericType<T> responseType) {
+ return (Uni<T>) super.get(responseType);
+ }
+
+ @Override
+ public Uni<Response> put(Entity<?> entity) {
+ return (Uni<Response>) super.put(entity);
+ }
+
+ @Override
+ public <T> Uni<T> put(Entity<?> entity, Class<T> clazz) {
+ return (Uni<T>) super.put(entity, clazz);
+ }
+
+ @Override
+ public <T> Uni<T> put(Entity<?> entity, GenericType<T> type) {
+ return (Uni<T>) super.put(entity, type);
+ }
+
+ @Override
+ public Uni<Response> post(Entity<?> entity) {
+ return (Uni<Response>) super.post(entity);
+ }
+
+ @Override
+ public <T> Uni<T> post(Entity<?> entity, Class<T> clazz) {
+ return (Uni<T>) super.post(entity, clazz);
+ }
+
+ @Override
+ public <T> Uni<T> post(Entity<?> entity, GenericType<T> type) {
+ return (Uni<T>) super.post(entity, type);
+ }
+
+ @Override
+ public Uni<Response> delete() {
+ return (Uni<Response>) super.delete();
+ }
+
+ @Override
+ public <T> Uni<T> delete(Class<T> responseType) {
+ return (Uni<T>) super.delete(responseType);
+ }
+
+ @Override
+ public <T> Uni<T> delete(GenericType<T> responseType) {
+ return (Uni<T>) super.delete(responseType);
+ }
+
+ @Override
+ public Uni<Response> head() {
+ return (Uni<Response>) super.head();
+ }
+
+ @Override
+ public Uni<Response> options() {
+ return (Uni<Response>) super.options();
+ }
+
+ @Override
+ public <T> Uni<T> options(Class<T> responseType) {
+ return (Uni<T>) super.options(responseType);
+ }
+
+ @Override
+ public <T> Uni<T> options(GenericType<T> responseType) {
+ return (Uni<T>) super.options(responseType);
+ }
+
+ @Override
+ public Uni<Response> trace() {
+ return (Uni<Response>) super.trace();
+ }
+
+ @Override
+ public <T> Uni<T> trace(Class<T> responseType) {
+ return (Uni<T>) super.trace(responseType);
+ }
+
+ @Override
+ public <T> Uni<T> trace(GenericType<T> responseType) {
+ return (Uni<T>) super.trace(responseType);
+ }
+
+ @Override
+ public Uni<Response> method(String name) {
+ return (Uni<Response>) super.method(name);
+ }
+
+ @Override
+ public <T> Uni<T> method(String name, Class<T> responseType) {
+ return (Uni<T>) super.method(name, responseType);
+ }
+
+ @Override
+ public <T> Uni<T> method(String name, GenericType<T> responseType) {
+ return (Uni<T>) super.method(name, responseType);
+ }
+
+ @Override
+ public Uni<Response> method(String name, Entity<?> entity) {
+ return (Uni<Response>) super.method(name, entity);
+ }
+
+ @Override
+ public <T> Uni<T> method(String name, Entity<?> entity, Class<T> responseType) {
+ return (Uni<T>) super.method(name, entity, responseType);
+ }
} | ['independent-projects/resteasy-reactive/client/runtime/src/main/java/org/jboss/resteasy/reactive/client/impl/UniInvoker.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 15,405,752 | 3,000,239 | 399,026 | 4,248 | 3,210 | 763 | 120 | 1 | 1,336 | 166 | 301 | 46 | 0 | 4 | 2021-03-23T06:11:46 | 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,838 | quarkusio/quarkus/15366/15351 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15351 | https://github.com/quarkusio/quarkus/pull/15366 | https://github.com/quarkusio/quarkus/pull/15366 | 1 | fix | Blocking @ConsumeEvent only uses single worker thread since 1.11.X | ### Description
Greetings,
while upgrading our Quarkus services from 1.10.4 to 1.11.3 we noticed that the behaviour of the Vert.x event bus significally changed. The event bus does not utilize more than one thread from the worker thread pool and the execution of multiple events is therefore not concurrent as it was prior to 1.11.X.
I could not find any hints in the changelogs or the migration guide why the behaviour changed.
If this new behaviour is indeed expectec, how can we handle the conccurrent execution of events if we do not want to use reactive style code?
### Expected behavior
ConsumeEvent with `blocking=true` should utilize all available worker pool threads and execute events concrrently.
### Actual behavior
The execution of events seems to only use a single worker thread and does not execute events concurrently.
### Example Code
Bean with some long running job:
```
@Dependent
public class SomeJobClass {
private static final Logger LOG = Logger.getLogger(SomeJobClass.class);
public void longRunningJob(String test) {
LOG.info("Executing");
try {
Thread.sleep(1000l);
} catch (InterruptedException e) {
e.printStackTrace();
}
LOG.info("finished");
}
}
```
The class containing the consumer:
```
@ApplicationScoped
public class ConsumerClass {
@Inject
SomeJobClass importer;
@ConsumeEvent(value = "test", blocking = true)
void test(String event) {
importer.longRunningJob(event);
}
}
```
Send 2 events:
```
@Test
@DisplayName("Some Test")
void testConcurrentEvents() throws InterruptedException {
eventBus.send("test", "1");
eventBus.send("test", "1");
Thread.sleep(3000l);
}
```
Log output with Quarkus 1.11.2.FINAL:
```
2021-02-26 13:53:29,994 INFO [foo] (vert.x-worker-thread-0) Executing
2021-02-26 13:53:30,997 INFO [foo] (vert.x-worker-thread-0) finished
2021-02-26 13:53:30,998 INFO [foo] (vert.x-worker-thread-0) Executing
2021-02-26 13:53:32,002 INFO [foo] (vert.x-worker-thread-0) finished
```
Log output with Quarkus 1.10.5.FINAL:
```
2021-02-26 14:02:19,345 INFO [foo] (vert.x-worker-thread-0) Executing
2021-02-26 14:02:19,345 INFO [foo] (vert.x-worker-thread-1) Executing
2021-02-26 14:02:20,349 INFO [foo] (vert.x-worker-thread-0) finished
2021-02-26 14:02:20,349 INFO [foo] (vert.x-worker-thread-1) finished
```
The logs show that the execution with version 1.11.2.FINAL was not concurrent and is using only `vert.x-worker-thread-0`.
| 4058da77acf5858d89dd95cb9af09053121adb9c | 7ecaa92110c65cd9391c8c4e1e0b321d8139ae71 | https://github.com/quarkusio/quarkus/compare/4058da77acf5858d89dd95cb9af09053121adb9c...7ecaa92110c65cd9391c8c4e1e0b321d8139ae71 | diff --git a/extensions/vertx/deployment/src/main/java/io/quarkus/vertx/deployment/EventBusConsumer.java b/extensions/vertx/deployment/src/main/java/io/quarkus/vertx/deployment/EventBusConsumer.java
index 57b90701781..b5d97cbe628 100644
--- a/extensions/vertx/deployment/src/main/java/io/quarkus/vertx/deployment/EventBusConsumer.java
+++ b/extensions/vertx/deployment/src/main/java/io/quarkus/vertx/deployment/EventBusConsumer.java
@@ -109,6 +109,13 @@ static String generateInvoker(BeanInfo bean, MethodInfo method,
isBlocking.returnValue(isBlocking.load(true));
}
+ AnnotationValue orderedValue = consumeEvent.value("ordered");
+ boolean ordered = orderedValue != null && orderedValue.asBoolean();
+ if (ordered) {
+ MethodCreator isOrdered = invokerCreator.getMethodCreator("isOrdered", boolean.class);
+ isOrdered.returnValue(isOrdered.load(true));
+ }
+
implementConstructor(bean, invokerCreator, beanField, containerField);
implementInvoke(bean, method, invokerCreator, beanField.getFieldDescriptor(), containerField.getFieldDescriptor());
diff --git a/extensions/vertx/runtime/src/main/java/io/quarkus/vertx/ConsumeEvent.java b/extensions/vertx/runtime/src/main/java/io/quarkus/vertx/ConsumeEvent.java
index 0020c381a43..e9a870edb29 100644
--- a/extensions/vertx/runtime/src/main/java/io/quarkus/vertx/ConsumeEvent.java
+++ b/extensions/vertx/runtime/src/main/java/io/quarkus/vertx/ConsumeEvent.java
@@ -83,12 +83,19 @@
*/
boolean blocking() default false;
+ /**
+ * @return {@code true} if the <em>blocking</em> consumption of the event must be ordered, meaning that the method
+ * won't be called concurrently. Instead it serializes all the invocations based on the event order.
+ * {@code ordered} must be used in conjunction with {@code blocking=true} or {@code @Blocking}.
+ * @see io.vertx.core.Vertx#executeBlocking(io.vertx.core.Handler, boolean, io.vertx.core.Handler)
+ */
+ boolean ordered() default false;
+
/**
*
* @return {@code null} if it should use a default MessageCodec
* @see io.quarkus.vertx.LocalEventBusCodec
*/
- @SuppressWarnings("rawtypes")
Class<? extends MessageCodec> codec() default LocalEventBusCodec.class;
}
diff --git a/extensions/vertx/runtime/src/main/java/io/quarkus/vertx/runtime/EventConsumerInvoker.java b/extensions/vertx/runtime/src/main/java/io/quarkus/vertx/runtime/EventConsumerInvoker.java
index 6320aa80243..38acccc6168 100644
--- a/extensions/vertx/runtime/src/main/java/io/quarkus/vertx/runtime/EventConsumerInvoker.java
+++ b/extensions/vertx/runtime/src/main/java/io/quarkus/vertx/runtime/EventConsumerInvoker.java
@@ -18,6 +18,10 @@ public boolean isBlocking() {
return false;
}
+ public boolean isOrdered() {
+ return false;
+ }
+
public void invoke(Message<Object> message) throws Exception {
ManagedContext requestContext = Arc.container().requestContext();
if (requestContext.isActive()) {
diff --git a/extensions/vertx/runtime/src/main/java/io/quarkus/vertx/runtime/VertxRecorder.java b/extensions/vertx/runtime/src/main/java/io/quarkus/vertx/runtime/VertxRecorder.java
index b340eabd863..54de1a6856f 100644
--- a/extensions/vertx/runtime/src/main/java/io/quarkus/vertx/runtime/VertxRecorder.java
+++ b/extensions/vertx/runtime/src/main/java/io/quarkus/vertx/runtime/VertxRecorder.java
@@ -98,7 +98,7 @@ public void handle(Promise<Object> event) {
}
event.complete();
}
- }, null);
+ }, invoker.isOrdered(), null);
} else {
try {
invoker.invoke(m); | ['extensions/vertx/runtime/src/main/java/io/quarkus/vertx/runtime/VertxRecorder.java', 'extensions/vertx/runtime/src/main/java/io/quarkus/vertx/runtime/EventConsumerInvoker.java', 'extensions/vertx/deployment/src/main/java/io/quarkus/vertx/deployment/EventBusConsumer.java', 'extensions/vertx/runtime/src/main/java/io/quarkus/vertx/ConsumeEvent.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 14,920,351 | 2,907,569 | 386,938 | 4,094 | 1,044 | 207 | 22 | 4 | 2,598 | 304 | 692 | 80 | 0 | 5 | 2021-03-01T09:11:34 | 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,839 | quarkusio/quarkus/15365/15104 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15104 | https://github.com/quarkusio/quarkus/pull/15365 | https://github.com/quarkusio/quarkus/pull/15365 | 1 | close | llegalAccessError with Panache MongoDB and Gradle | **Describe the bug**
Following this ticket https://github.com/quarkusio/quarkus/issues/12514
The bug has been fixed with Maven in the 1.11.0.Final but still exist if we use Gradle instead.
**Expected behavior**
The application should be able to access the entities with MongoDb.
**Actual behavior**
An exception is raised:
```
java.lang.IllegalAccessError: class org.acme.ExampleResource tried to access protected field org.acme.db.TestEntity.name
```
while the field is public.
**To Reproduce**
Sample repo: https://github.com/avdev4j/quarkus-mongo-gradle
- Clone the repo: `git clone [email protected]:avdev4j/quarkus-mongo-gradle.git`
- Run tests:` ./gradlew test`
- testHelloEndpoint() will fail with the following error:
<details><pre>
ExampleResourceTest STANDARD_ERROR
Feb 16, 2021 10:44:02 AM io.quarkus.bootstrap.runner.Timing printStartupTime
INFO: Quarkus 1.11.3.Final on JVM started in 6.314s. Listening on: http://localhost:8081
Feb 16, 2021 10:44:02 AM io.quarkus.bootstrap.runner.Timing printStartupTime
INFO: Profile test activated.
Feb 16, 2021 10:44:02 AM io.quarkus.bootstrap.runner.Timing printStartupTime
INFO: Installed features: [cdi, mongodb-client, mongodb-panache, mutiny, resteasy, smallrye-context-propagation]
ExampleResourceTest > testHelloEndpoint() STANDARD_ERROR
Feb 16, 2021 10:44:03 AM io.quarkus.vertx.http.runtime.QuarkusErrorHandler handle
ERROR: HTTP Request to /hello failed, error id: 3986bfb1-8405-43f6-b48b-6bafe1a2689b-1
org.jboss.resteasy.spi.UnhandledException: java.lang.IllegalAccessError: class org.acme.ExampleResource tried to access protected field org.acme.db.TestEntity.name (org.acme.ExampleResource and org.acme.db.TestEntity are in unnamed module of loader io.quarkus.bootstrap.classloading.QuarkusClassLoader @17d70d9e)
at org.jboss.resteasy.core.ExceptionHandler.handleApplicationException(ExceptionHandler.java:106)
at org.jboss.resteasy.core.ExceptionHandler.handleException(ExceptionHandler.java:372)
at org.jboss.resteasy.core.SynchronousDispatcher.writeException(SynchronousDispatcher.java:218)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:519)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:261)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:161)
at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364)
at org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:164)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:247)
at io.quarkus.resteasy.runtime.standalone.RequestDispatcher.service(RequestDispatcher.java:73)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.dispatch(VertxRequestHandler.java:138)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.access$000(VertxRequestHandler.java:41)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler$1.run(VertxRequestHandler.java:93)
at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2415)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1452)
at org.jboss.threads.DelegatingRunnable.run(DelegatingRunnable.java:29)
at org.jboss.threads.ThreadLocalResettingRunnable.run(ThreadLocalResettingRunnable.java:29)
at java.base/java.lang.Thread.run(Thread.java:834)
at org.jboss.threads.JBossThread.run(JBossThread.java:501)
Caused by: java.lang.IllegalAccessError: class org.acme.ExampleResource tried to access protected field org.acme.db.TestEntity.name (org.acme.ExampleResource and org.acme.db.TestEntity are in unnamed module of loader io.quarkus.bootstrap.classloading.QuarkusClassLoader @17d70d9e)
at org.acme.ExampleResource.hello(ExampleResource.java:17)
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 org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:170)
at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:130)
at org.jboss.resteasy.core.ResourceMethodInvoker.internalInvokeOnTarget(ResourceMethodInvoker.java:643)
at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTargetAfterFilter(ResourceMethodInvoker.java:507)
at org.jboss.resteasy.core.ResourceMethodInvoker.lambda$invokeOnTarget$2(ResourceMethodInvoker.java:457)
at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364)
at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:459)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:419)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:393)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:68)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:492)
... 15 more
</pre></details>
**Configuration**
application.properties is empty
**Screenshots**
(If applicable, add screenshots to help explain your problem.)
**Environment (please complete the following information):**
- Output of `uname -a` or `ver`:
`Darwin MacBook-Pro.local 20.3.0 Darwin Kernel Version 20.3.0: Thu Jan 21 00:07:06 PST 2021; root:xnu-7195.81.3~1/RELEASE_X86_64 x86_64`
- Output of `java -version`: `openjdk version "11.0.7" 2020-04-14`
- GraalVM version (if different from Java): /
- Quarkus version or git rev: `1.11.3.FInal`
- Build tool (ie. output of `mvnw --version` or `gradlew --version`):
```
------------------------------------------------------------
Gradle 6.5.1
------------------------------------------------------------
Build time: 2020-06-30 06:32:47 UTC
Revision: 66bc713f7169626a7f0134bf452abde51550ea0a
Kotlin: 1.3.72
Groovy: 2.5.11
Ant: Apache Ant(TM) version 1.10.7 compiled on September 1 2019
JVM: 11.0.7 (AdoptOpenJDK 11.0.7+10)
OS: Mac OS X 10.16 x86_64
```
**Additional context**
(Add any other context about the problem here.)
cc @danielpetisme | 3c79a053c3583179845cff5f0751f886b8beb8db | de6b5b5760b06edc0f0061ebff14985ee09dad11 | https://github.com/quarkusio/quarkus/compare/3c79a053c3583179845cff5f0751f886b8beb8db...de6b5b5760b06edc0f0061ebff14985ee09dad11 | diff --git a/devtools/gradle/src/main/java/io/quarkus/gradle/QuarkusPlugin.java b/devtools/gradle/src/main/java/io/quarkus/gradle/QuarkusPlugin.java
index 3d3b31f50b1..3169d956afb 100644
--- a/devtools/gradle/src/main/java/io/quarkus/gradle/QuarkusPlugin.java
+++ b/devtools/gradle/src/main/java/io/quarkus/gradle/QuarkusPlugin.java
@@ -138,7 +138,14 @@ public void execute(Task test) {
JavaPlugin.class,
javaPlugin -> {
project.afterEvaluate(this::afterEvaluate);
+ ConfigurationContainer configurations = project.getConfigurations();
JavaCompile compileJavaTask = (JavaCompile) tasks.getByName(JavaPlugin.COMPILE_JAVA_TASK_NAME);
+
+ // By default, gradle looks for annotation processors in the annotationProcessor configuration.
+ // This configure the compile task to look for annotation processors in the compileClasspath.
+ compileJavaTask.getOptions().setAnnotationProcessorPath(
+ configurations.getByName(JavaPlugin.COMPILE_CLASSPATH_CONFIGURATION_NAME));
+
compileJavaTask.dependsOn(quarkusGenerateCode);
quarkusGenerateCode.setSourceRegistrar(compileJavaTask::source);
@@ -171,8 +178,6 @@ public void execute(Task test) {
.plus(mainSourceSet.getOutput())
.plus(testSourceSet.getOutput()));
- ConfigurationContainer configurations = project.getConfigurations();
-
// create a custom configuration for devmode
configurations.create(DEV_MODE_CONFIGURATION_NAME).extendsFrom(
configurations.getByName(JavaPlugin.COMPILE_ONLY_CONFIGURATION_NAME), | ['devtools/gradle/src/main/java/io/quarkus/gradle/QuarkusPlugin.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 14,955,568 | 2,914,983 | 387,800 | 4,096 | 600 | 80 | 9 | 1 | 6,837 | 397 | 1,696 | 107 | 3 | 2 | 2021-03-01T08:21: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,842 | quarkusio/quarkus/15212/15187 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15187 | https://github.com/quarkusio/quarkus/pull/15212 | https://github.com/quarkusio/quarkus/pull/15212 | 1 | fixes | GRPC client stream onMessage and onClose executes on different threads | When calling client grpc service method form blocking code(no matter if its blocking or async client). Stream close will be executed on worker thread, but on message event will be executed on event-loop thread. So client stream usually closed before able to reads any message
**Expected behavior**
OnMessage and OnClose executed in correct order
**To Reproduce**
https://drive.google.com/file/d/16xdsSuSV4V9pQAJt_HDYoppgqsAGOGoX/view?usp=sharing
Steps to reproduce the behavior:
archive contains single UT that reproduce incorrect behavior.
For more details you will need to debug class `io.grpc.stub.ClientCall.BlockingResponseStream.QueuingListener` to see threads
**Environment (please complete the following information):**
- Output of `uname -a` or `ver`: Linux andrii-PC 5.4.0-65-generic #73-Ubuntu SMP Mon Jan 18 17:25:17 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
- Output of `java -version`: openjdk version "11.0.9" 2020-10-20
- GraalVM version (if different from Java): OpenJDK Runtime Environment GraalVM CE 20.3.0 (build 11.0.9+10-jvmci-20.3-b06)
- Quarkus version or git rev: 1.11.3
- Build tool (ie. output of `mvnw --version` or `gradlew --version`): maven 3.6.3 or gradle 6.5.1
| 2b56bc6c0084518ed84aa24b23dbf3ed1f1b5ec3 | 664c16f81528e28d4b4745efde0b6d13cbbf82e8 | https://github.com/quarkusio/quarkus/compare/2b56bc6c0084518ed84aa24b23dbf3ed1f1b5ec3...664c16f81528e28d4b4745efde0b6d13cbbf82e8 | diff --git a/extensions/grpc/runtime/src/main/java/io/quarkus/grpc/runtime/supports/IOThreadClientInterceptor.java b/extensions/grpc/runtime/src/main/java/io/quarkus/grpc/runtime/supports/IOThreadClientInterceptor.java
index d4e49736fca..f067033e631 100644
--- a/extensions/grpc/runtime/src/main/java/io/quarkus/grpc/runtime/supports/IOThreadClientInterceptor.java
+++ b/extensions/grpc/runtime/src/main/java/io/quarkus/grpc/runtime/supports/IOThreadClientInterceptor.java
@@ -23,10 +23,19 @@ public void start(Listener<RespT> responseListener, Metadata headers) {
super.start(new ForwardingClientCallListener.SimpleForwardingClientCallListener<RespT>(responseListener) {
@Override
public void onMessage(RespT message) {
+ runInContextIfNeed(() -> super.onMessage(message));
+ }
+
+ @Override
+ public void onClose(Status status, Metadata trailers) {
+ runInContextIfNeed(() -> super.onClose(status, trailers));
+ }
+
+ private void runInContextIfNeed(Runnable fun) {
if (context != null) {
- context.runOnContext(unused -> super.onMessage(message));
+ context.runOnContext(unused -> fun.run());
} else {
- super.onMessage(message);
+ fun.run();
}
}
}, headers); | ['extensions/grpc/runtime/src/main/java/io/quarkus/grpc/runtime/supports/IOThreadClientInterceptor.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 14,774,575 | 2,880,016 | 383,408 | 4,062 | 641 | 94 | 13 | 1 | 1,224 | 158 | 352 | 19 | 1 | 0 | 2021-02-20T09:10:55 | 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,843 | quarkusio/quarkus/15158/15114 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15114 | https://github.com/quarkusio/quarkus/pull/15158 | https://github.com/quarkusio/quarkus/pull/15158 | 1 | fixes | RESTEasy Reactive: Sub resource Path Params more than 2 levels back are not passed correctly | Describe the bug
Sub resource path params are not bound correctly in a scenario with more than two sub resource levels.
E.g. if path /trees/{treeId}/branches/{branchId}/leaves/{leafId} is handled by a sub resource "LeavesResource" which uses @PathParam("treeId") and @PathParam("branchId") and @PathParam("leafId") then treeId is not injected while the other two are.
Expected behavior
Multiple levels should be supported. The correct behaviour is found in standard resteasy.
Actual behavior
The value is not injected causing difficult to track bugs.
To Reproduce
git clone https://github.com/bcluap/quarkus-examples.git
cd quarkus-examples/resteasy-reactive
mvn clean test
Configuration
Nothing abnormal
Screenshots
Run the reproducer to see failures. Change the pom to non-reactive mode and all tests pass
Environment (please complete the following information):
This is not environment-specific
999-SNAPSHOT and before
Additional context
NA | 7a9b3565d196abc1f7c76bfa5cda35018f20332a | 7beab6dc93bdb9f5c322b23f5218d44b546a18b9 | https://github.com/quarkusio/quarkus/compare/7a9b3565d196abc1f7c76bfa5cda35018f20332a...7beab6dc93bdb9f5c322b23f5218d44b546a18b9 | diff --git a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resource/basic/SubResourceRequestFilterTest.java b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resource/basic/SubResourceRequestFilterTest.java
index a7f3f37a7b7..2daf58362e5 100644
--- a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resource/basic/SubResourceRequestFilterTest.java
+++ b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resource/basic/SubResourceRequestFilterTest.java
@@ -31,28 +31,42 @@ public class SubResourceRequestFilterTest {
@Override
public JavaArchive get() {
JavaArchive war = ShrinkWrap.create(JavaArchive.class);
- war.addClasses(RestResource.class, RestSubResource.class, SingleExecutionFilter.class);
+ war.addClasses(RestResource.class, RestSubResource.class, SingleExecutionFilter.class,
+ MiddleRestResource.class);
return war;
}
});
@Test
- public void testAbortingRequestFilter() {
- RestAssured.get("/sub-resource/geo")
+ public void testSubResourceFilter() {
+ RestAssured.get("/sub-resource/Bob/Builder")
.then()
.header("single-filter", Matchers.equalTo("once"))
- .body(Matchers.equalTo("geo"))
+ .body(Matchers.equalTo("Bob Builder"))
.statusCode(200);
}
@Path("/")
public static class RestResource {
+ @Inject
+ MiddleRestResource restSubResource;
+
+ @Path("sub-resource/{first}")
+ public MiddleRestResource hello(String first) {
+ return restSubResource;
+ }
+ }
+
+ @ApplicationScoped
+ @Path("/")
+ public static class MiddleRestResource {
+
@Inject
RestSubResource restSubResource;
- @Path("sub-resource/{name}")
- public RestSubResource hello(String name) {
+ @Path("{last}")
+ public RestSubResource hello() {
return restSubResource;
}
}
@@ -61,8 +75,8 @@ public RestSubResource hello(String name) {
public static class RestSubResource {
@GET
- public Response hello(HttpHeaders headers, @RestPath String name) {
- return Response.ok(name).header("single-filter", headers.getHeaderString("single-filter")).build();
+ public Response hello(HttpHeaders headers, @RestPath String first, @RestPath String last) {
+ return Response.ok(first + " " + last).header("single-filter", headers.getHeaderString("single-filter")).build();
}
}
diff --git a/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/ResteasyReactiveRequestContext.java b/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/ResteasyReactiveRequestContext.java
index 0b875e61aee..4b39cb27921 100644
--- a/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/ResteasyReactiveRequestContext.java
+++ b/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/ResteasyReactiveRequestContext.java
@@ -58,11 +58,11 @@
*/
private Object[] parameters;
private RuntimeResource target;
+
/**
- * When a subresource has been located and the processing has been restarted (and thus target point to the new subresource),
- * this field contains the target that resulted in the offloading to the new target
+ * info about path params and other data about previously matched sub resource locators
*/
- private RuntimeResource locatorTarget;
+ private PreviousResource previousResource;
/**
* The parameter values extracted from the path.
@@ -79,11 +79,6 @@
* Note: those are decoded.
*/
private Object pathParamValues;
- /**
- * When a subresource has been located and the processing has been restarted (and thus target point to the new subresource),
- * this field contains the pathParamValues of the target that resulted in the offloading to the new target
- */
- private Object locatorPathParamValues;
private UriInfo uriInfo;
/**
@@ -178,8 +173,7 @@ public void restart(RuntimeResource target, boolean setLocatorTarget) {
position = 0;
parameters = new Object[target.getParameterTypes().length];
if (setLocatorTarget) {
- this.locatorTarget = this.target;
- this.locatorPathParamValues = this.pathParamValues;
+ previousResource = new PreviousResource(this.target, pathParamValues, previousResource);
}
this.target = target;
}
@@ -222,10 +216,6 @@ public String getPathParam(int index) {
return doGetPathParam(index, pathParamValues);
}
- public String getLocatorPathParam(int index) {
- return doGetPathParam(index, locatorPathParamValues);
- }
-
private String doGetPathParam(int index, Object pathParamValues) {
if (pathParamValues instanceof String[]) {
return ((String[]) pathParamValues)[index];
@@ -320,10 +310,6 @@ public RuntimeResource getTarget() {
return target;
}
- public RuntimeResource getLocatorTarget() {
- return locatorTarget;
- }
-
public void mapExceptionIfPresent() {
// this is called from the abort chain, but we can abort because we have a Response, or because
// we got an exception
@@ -928,4 +914,76 @@ public ResteasyReactiveResourceInfo getResteasyReactiveResourceInfo() {
protected abstract Executor getEventLoop();
public abstract Runnable registerTimer(long millis, Runnable task);
+
+ public String getResourceLocatorPathParam(String name) {
+ return getResourceLocatorPathParam(name, previousResource);
+ }
+
+ private String getResourceLocatorPathParam(String name, PreviousResource previousResource) {
+ if (previousResource == null) {
+ return null;
+ }
+
+ int index = 0;
+ URITemplate classPath = previousResource.locatorTarget.getClassPath();
+ if (classPath != null) {
+ for (URITemplate.TemplateComponent component : classPath.components) {
+ if (component.name != null) {
+ if (component.name.equals(name)) {
+ return doGetPathParam(index, previousResource.locatorPathParamValues);
+ }
+ index++;
+ } else if (component.names != null) {
+ for (String nm : component.names) {
+ if (nm.equals(name)) {
+ return doGetPathParam(index, previousResource.locatorPathParamValues);
+ }
+ }
+ index++;
+ }
+ }
+ }
+ for (URITemplate.TemplateComponent component : previousResource.locatorTarget.getPath().components) {
+ if (component.name != null) {
+ if (component.name.equals(name)) {
+ return doGetPathParam(index, previousResource.locatorPathParamValues);
+ }
+ index++;
+ } else if (component.names != null) {
+ for (String nm : component.names) {
+ if (nm.equals(name)) {
+ return doGetPathParam(index, previousResource.locatorPathParamValues);
+ }
+ }
+ index++;
+ }
+ }
+ return getResourceLocatorPathParam(name, previousResource.prev);
+ }
+
+ static class PreviousResource {
+
+ public PreviousResource(RuntimeResource locatorTarget, Object locatorPathParamValues, PreviousResource prev) {
+ this.locatorTarget = locatorTarget;
+ this.locatorPathParamValues = locatorPathParamValues;
+ this.prev = prev;
+ }
+
+ /**
+ * When a subresource has been located and the processing has been restarted (and thus target point to the new
+ * subresource),
+ * this field contains the target that resulted in the offloading to the new target
+ */
+ private final RuntimeResource locatorTarget;
+
+ /**
+ * When a subresource has been located and the processing has been restarted (and thus target point to the new
+ * subresource),
+ * this field contains the pathParamValues of the target that resulted in the offloading to the new target
+ */
+ private final Object locatorPathParamValues;
+
+ private final PreviousResource prev;
+
+ }
}
diff --git a/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/parameters/LocatableResourcePathParamExtractor.java b/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/parameters/LocatableResourcePathParamExtractor.java
index 76bb46097e2..835be0b5153 100644
--- a/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/parameters/LocatableResourcePathParamExtractor.java
+++ b/independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/parameters/LocatableResourcePathParamExtractor.java
@@ -1,7 +1,6 @@
package org.jboss.resteasy.reactive.server.core.parameters;
import org.jboss.resteasy.reactive.server.core.ResteasyReactiveRequestContext;
-import org.jboss.resteasy.reactive.server.mapping.URITemplate;
public class LocatableResourcePathParamExtractor implements ParameterExtractor {
@@ -13,48 +12,7 @@ public LocatableResourcePathParamExtractor(String name) {
@Override
public Object extractParameter(ResteasyReactiveRequestContext context) {
- int index = findPathParamIndex(context.getLocatorTarget().getClassPath(), context.getLocatorTarget().getPath());
- if (index >= 0) {
- return context.getLocatorPathParam(index);
- }
- return null;
- }
-
- private int findPathParamIndex(URITemplate classPathTemplate, URITemplate methodPathTemplate) {
- int index = 0;
- if (classPathTemplate != null) {
- for (URITemplate.TemplateComponent component : classPathTemplate.components) {
- if (component.name != null) {
- if (component.name.equals(this.name)) {
- return index;
- }
- index++;
- } else if (component.names != null) {
- for (String nm : component.names) {
- if (nm.equals(this.name)) {
- return index;
- }
- }
- index++;
- }
- }
- }
- for (URITemplate.TemplateComponent component : methodPathTemplate.components) {
- if (component.name != null) {
- if (component.name.equals(this.name)) {
- return index;
- }
- index++;
- } else if (component.names != null) {
- for (String nm : component.names) {
- if (nm.equals(this.name)) {
- return index;
- }
- }
- index++;
- }
- }
- return -1;
+ return context.getResourceLocatorPathParam(name);
}
} | ['extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resource/basic/SubResourceRequestFilterTest.java', 'independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/ResteasyReactiveRequestContext.java', 'independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/parameters/LocatableResourcePathParamExtractor.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 14,719,059 | 2,868,894 | 381,992 | 4,049 | 5,854 | 1,004 | 138 | 2 | 977 | 122 | 215 | 27 | 1 | 0 | 2021-02-18T03:50: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,844 | quarkusio/quarkus/15092/14991 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/14991 | https://github.com/quarkusio/quarkus/pull/15092 | https://github.com/quarkusio/quarkus/pull/15092 | 1 | fixes | Classloading error with QuarkusMock regression in 1.12.0.CR1 | **Describe the bug**
I upgraded from `1.11.2` to `1.12.0.CR1`, and I get the following error in my unit tests:
```
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 10.123 s <<< FAILURE! - in com.xx.arte.ocpdeploy.deploy.noreg.DeployNoRegFtuTest
[ERROR] com.xx.arte.ocpdeploy.deploy.noreg.DeployNoRegFtuTest.noreg Time elapsed: 1.327 s <<< ERROR!
java.lang.ClassCastException: class org.mockito.codegen.VaultSystemBackendEngine$MockitoMock$192437934 cannot be cast to class io.quarkus.vault.runtime.VaultSystemBackendManager (org.mockito.codegen.VaultSystemBackendEngine$MockitoMock$192437934 is in
unnamed module of loader net.bytebuddy.dynamic.loading.MultipleParentClassLoader @36d1793a; io.quarkus.vault.runtime.VaultSystemBackendManager is in unnamed module of loader io.quarkus.bootstrap.classloading.QuarkusClassLoader @6b08b323)
at com.xx.arte.ocpdeploy.deploy.noreg.DeployNoRegFtuTest.noreg(DeployNoRegFtuTest.java:21)
```
I don't have a stacktrace other than the line of the test.
**Expected behavior**
No regression. Mock works as expected.
**Actual behavior**
The unit test fails with the above exception.
**To Reproduce**
I don't have yet an independent reproducer. Here is the code in my application that is causing the issue:
```
@BeforeAll
public static void mockVaultSystemBackendEngine() {
VaultSystemBackendEngine sys = Mockito.mock(VaultSystemBackendEngine.class);
VaultHealthStatus vaultHealthStatus = new VaultHealthStatus();
vaultHealthStatus.setInitialized(true);
Mockito.when(sys.healthStatus()).thenReturn(vaultHealthStatus);
QuarkusMock.installMockForType(sys, VaultSystemBackendEngine.class);
}
```
**Environment (please complete the following information):**
- Output of `uname -a` or `ver`: `Microsoft Windows [Version 10.0.17763.1697]`
- Output of `java -version`: `openjdk version "11.0.1-redhat" 2018-10-16 LTS`
- GraalVM version (if different from Java): N/A
- Quarkus version or git rev: `1.12.0.CR1`
- Build tool (ie. output of `mvnw --version` or `gradlew --version`): `Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)`
| c16567ce465794c9cb076670331894424b4864e2 | 8305da83c21061dbaf32cabefa83c16ba1a77e08 | https://github.com/quarkusio/quarkus/compare/c16567ce465794c9cb076670331894424b4864e2...8305da83c21061dbaf32cabefa83c16ba1a77e08 | diff --git a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ClientProxyGenerator.java b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ClientProxyGenerator.java
index 7e8718e6295..4410f808f41 100644
--- a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ClientProxyGenerator.java
+++ b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ClientProxyGenerator.java
@@ -118,7 +118,7 @@ Collection<Resource> generate(BeanInfo bean, String beanClassName,
FieldCreator beanField = clientProxy.getFieldCreator(BEAN_FIELD, DescriptorUtils.extToInt(beanClassName))
.setModifiers(ACC_PRIVATE | ACC_FINAL);
if (mockable) {
- clientProxy.getFieldCreator(MOCK_FIELD, Object.class).setModifiers(ACC_PRIVATE | ACC_VOLATILE);
+ clientProxy.getFieldCreator(MOCK_FIELD, providerType.descriptorName()).setModifiers(ACC_PRIVATE | ACC_VOLATILE);
}
FieldCreator contextField = null;
if (BuiltinScope.APPLICATION.is(bean.getScope())) {
@@ -133,7 +133,7 @@ Collection<Resource> generate(BeanInfo bean, String beanClassName,
implementGetContextualInstance(clientProxy, providerType);
implementGetBean(clientProxy, beanField.getFieldDescriptor());
if (mockable) {
- implementMockMethods(clientProxy);
+ implementMockMethods(clientProxy, providerType);
}
for (MethodInfo method : getDelegatingMethods(bean, bytecodeTransformerConsumer, transformUnproxyableClasses)) {
@@ -231,17 +231,19 @@ Collection<Resource> generate(BeanInfo bean, String beanClassName,
return classOutput.getResources();
}
- private void implementMockMethods(ClassCreator clientProxy) {
+ private void implementMockMethods(ClassCreator clientProxy, ProviderType providerType) {
MethodCreator clear = clientProxy
.getMethodCreator(MethodDescriptor.ofMethod(clientProxy.getClassName(), CLEAR_MOCK_METHOD_NAME, void.class));
- clear.writeInstanceField(FieldDescriptor.of(clientProxy.getClassName(), MOCK_FIELD, Object.class), clear.getThis(),
+ clear.writeInstanceField(FieldDescriptor.of(clientProxy.getClassName(), MOCK_FIELD, providerType.descriptorName()),
+ clear.getThis(),
clear.loadNull());
clear.returnValue(null);
MethodCreator set = clientProxy
.getMethodCreator(
MethodDescriptor.ofMethod(clientProxy.getClassName(), SET_MOCK_METHOD_NAME, void.class, Object.class));
- set.writeInstanceField(FieldDescriptor.of(clientProxy.getClassName(), MOCK_FIELD, Object.class), set.getThis(),
+ set.writeInstanceField(FieldDescriptor.of(clientProxy.getClassName(), MOCK_FIELD, providerType.descriptorName()),
+ set.getThis(),
set.getMethodParam(0));
set.returnValue(null);
}
@@ -268,7 +270,8 @@ void implementDelegate(ClassCreator clientProxy, ProviderType providerType, Fiel
if (mockable) {
//if mockable and mocked just return the mock
ResultHandle mock = creator.readInstanceField(
- FieldDescriptor.of(clientProxy.getClassName(), MOCK_FIELD, Object.class.getName()), creator.getThis());
+ FieldDescriptor.of(clientProxy.getClassName(), MOCK_FIELD, providerType.descriptorName()),
+ creator.getThis());
BytecodeCreator falseBranch = creator.ifNull(mock).falseBranch();
falseBranch.returnValue(falseBranch.checkCast(mock, providerType.className()));
}
diff --git a/test-framework/junit5/src/main/java/io/quarkus/test/junit/MockSupport.java b/test-framework/junit5/src/main/java/io/quarkus/test/junit/MockSupport.java
index 2bbf9b6c1de..60107393d70 100644
--- a/test-framework/junit5/src/main/java/io/quarkus/test/junit/MockSupport.java
+++ b/test-framework/junit5/src/main/java/io/quarkus/test/junit/MockSupport.java
@@ -36,6 +36,10 @@ static <T> void installMock(T instance, T mock) {
if (inst == null) {
throw new IllegalStateException("No test in progress");
}
+ if (!(instance.getClass().getSuperclass().isAssignableFrom(mock.getClass()))) {
+ throw new RuntimeException(mock
+ + " is not assignable to type " + instance.getClass().getSuperclass());
+ }
try {
Method setMethod = instance.getClass().getDeclaredMethod("arc$setMock", Object.class);
setMethod.invoke(instance, mock); | ['independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ClientProxyGenerator.java', 'test-framework/junit5/src/main/java/io/quarkus/test/junit/MockSupport.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 14,688,056 | 2,862,937 | 381,308 | 4,041 | 1,343 | 231 | 15 | 1 | 2,203 | 207 | 605 | 38 | 0 | 2 | 2021-02-15T22:33:21 | 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,845 | quarkusio/quarkus/15067/15026 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15026 | https://github.com/quarkusio/quarkus/pull/15067 | https://github.com/quarkusio/quarkus/pull/15067 | 1 | fixes | @PreDestroy method seems to not be invocked when ExecutorManager is being used. | In the following project test-executor project
https://github.com/wmedvede/test-executor-issue.git
I have the silly component below.
All right, when I execute my application in dev mode, with mvn clean compile quarkus:dev
In can see that the created MyRunnable is executing, etc, as expected.
When I stop the application with "CTRL+C" the application stops gracefully, i.e. the @PreDestroy method is executed, the MyRunnable instance is stopped etc.
BUT, when I execute same application with
java -jar target/test-executor-1.0.0-SNAPSHOT-runner.jar (or with the generated native image)
There's no way to stop the application, i.e., the "CTRL+C" seems to simply do nothing in that particular scenario, and the @PreDestroy isn't invoked.
note: The @Observes ShutdownEvent works in all cases
`
@ApplicationScoped
@Startup
public class MyService {
class MyRunnable implements Runnable {
private AtomicBoolean exit = new AtomicBoolean(false);
public void exit() {
exit.set(true);
}
@Override
public void run() {
while (!exit.get()) {
try {
Thread.sleep(2000);
System.out.println("MyRunnable is working!");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
exit.set(true);
}
}
System.out.println("MyRunnable has finished it work!");
}
}
@Inject
ManagedExecutor managedExecutor;
MyRunnable myRunnableInstance;
@PostConstruct
void startService() {
myRunnableInstance = new MyRunnable();
managedExecutor.execute(myRunnableInstance);
}
/**
* When we stop the application with CTRL+C this method is only invoked when
* the application is started in dev mode. But not in native or if we execute the java runner.
*/
@PreDestroy
void destroyService() {
System.out.println("Destroying the service!");
if (myRunnableInstance != null) {
System.out.println("Destroying the runnable!");
myRunnableInstance.exit();
}
}
/*
This variant is always invocked
void onShutDownEvent(@Observes ShutdownEvent ev) {
System.out.println("SHUT DOWN EVENT is executed!!!!");
if (myRunnableInstance != null) {
System.out.println("Destroying the runnable!");
myRunnableInstance.exit();
}
}
*/
}
` | fa941e8c7b528b3d9847f9cd4dcbfde410c113ae | 3f78097884e1ed8c83e1c27b61edc412dce03bd1 | https://github.com/quarkusio/quarkus/compare/fa941e8c7b528b3d9847f9cd4dcbfde410c113ae...3f78097884e1ed8c83e1c27b61edc412dce03bd1 | diff --git a/core/runtime/src/main/java/io/quarkus/runtime/ExecutorRecorder.java b/core/runtime/src/main/java/io/quarkus/runtime/ExecutorRecorder.java
index d5b0f1618c0..372b4a0adbc 100644
--- a/core/runtime/src/main/java/io/quarkus/runtime/ExecutorRecorder.java
+++ b/core/runtime/src/main/java/io/quarkus/runtime/ExecutorRecorder.java
@@ -54,7 +54,7 @@ public void run() {
executor = devModeExecutor;
Runtime.getRuntime().addShutdownHook(new Thread(shutdownTask, "Executor shutdown thread"));
} else {
- shutdownContext.addShutdownTask(shutdownTask);
+ shutdownContext.addLastShutdownTask(shutdownTask);
executor = underlying;
}
if (threadPoolConfig.prefill) {
diff --git a/extensions/arc/runtime/src/main/java/io/quarkus/arc/runtime/context/ArcContextProvider.java b/extensions/arc/runtime/src/main/java/io/quarkus/arc/runtime/context/ArcContextProvider.java
index 5537feb0935..92941faaa61 100644
--- a/extensions/arc/runtime/src/main/java/io/quarkus/arc/runtime/context/ArcContextProvider.java
+++ b/extensions/arc/runtime/src/main/java/io/quarkus/arc/runtime/context/ArcContextProvider.java
@@ -66,12 +66,6 @@ public String getThreadContextType() {
return ThreadContext.CDI;
}
- // see ThreadContextController#endContext()
- private static void deactivateRequestContext() throws IllegalStateException {
- // Only deactivate the context
- Arc.container().requestContext().deactivate();
- }
-
private static final class ClearContextSnapshot implements ThreadContextSnapshot {
@Override
@@ -92,7 +86,7 @@ public ThreadContextController begin() {
} else {
// context not active, activate blank one, deactivate afterwards
requestContext.activate();
- return ArcContextProvider::deactivateRequestContext;
+ return requestContext::deactivate;
}
}
}
@@ -155,7 +149,7 @@ public ThreadContextController begin() {
} else {
// context not active, activate and pass it new instance, deactivate afterwards
requestContext.activate(state);
- return ArcContextProvider::deactivateRequestContext;
+ return requestContext::deactivate;
}
}
| ['core/runtime/src/main/java/io/quarkus/runtime/ExecutorRecorder.java', 'extensions/arc/runtime/src/main/java/io/quarkus/arc/runtime/context/ArcContextProvider.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 14,679,388 | 2,861,295 | 381,110 | 4,040 | 603 | 99 | 12 | 2 | 2,603 | 263 | 522 | 85 | 1 | 0 | 2021-02-15T05:23:48 | 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,846 | quarkusio/quarkus/15063/15062 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15062 | https://github.com/quarkusio/quarkus/pull/15063 | https://github.com/quarkusio/quarkus/pull/15063 | 1 | fixes | "Using Java versions older than 11 ... " complaint with Java 17 Early Access build | I see `[WARNING] [io.quarkus.deployment.QuarkusAugmentor] Using Java versions older than 11 to build Quarkus applications is deprecated and will be disallowed in a future release!` complaint when using Java 17 Early Access build
Code for version check probably doesn't handle `-ea` suffix in Early Access Java build version, e.g. `17-ea`. | d392404a6f00ce43d058dc8dc2f96c906a023849 | 05a31b65f8b8eadf09141c54e3d03bbcd7a8cdb8 | https://github.com/quarkusio/quarkus/compare/d392404a6f00ce43d058dc8dc2f96c906a023849...05a31b65f8b8eadf09141c54e3d03bbcd7a8cdb8 | diff --git a/core/runtime/src/main/java/io/quarkus/runtime/util/JavaVersionUtil.java b/core/runtime/src/main/java/io/quarkus/runtime/util/JavaVersionUtil.java
index 4236031c1d2..74d7d0c31ea 100644
--- a/core/runtime/src/main/java/io/quarkus/runtime/util/JavaVersionUtil.java
+++ b/core/runtime/src/main/java/io/quarkus/runtime/util/JavaVersionUtil.java
@@ -5,7 +5,7 @@
public class JavaVersionUtil {
- private static final Pattern PATTERN = Pattern.compile("(?:1\\\\.)?(\\\\d+)(?:\\\\..*)?");
+ private static final Pattern PATTERN = Pattern.compile("(?:1\\\\.)?(\\\\d+)");
private static boolean IS_JAVA_11_OR_NEWER;
private static boolean IS_JAVA_13_OR_NEWER;
@@ -16,7 +16,7 @@ public class JavaVersionUtil {
// visible for testing
static void performChecks() {
- Matcher matcher = PATTERN.matcher(System.getProperty("java.version", ""));
+ Matcher matcher = PATTERN.matcher(System.getProperty("java.specification.version", ""));
if (matcher.matches()) {
int first = Integer.parseInt(matcher.group(1));
IS_JAVA_11_OR_NEWER = (first >= 11);
diff --git a/core/runtime/src/test/java/io/quarkus/runtime/util/JavaVersionUtilTest.java b/core/runtime/src/test/java/io/quarkus/runtime/util/JavaVersionUtilTest.java
index 0e47d6b54a2..d2300aa1483 100644
--- a/core/runtime/src/test/java/io/quarkus/runtime/util/JavaVersionUtilTest.java
+++ b/core/runtime/src/test/java/io/quarkus/runtime/util/JavaVersionUtilTest.java
@@ -7,11 +7,11 @@
class JavaVersionUtilTest {
- private static final String JAVA_VERSION = "java.version";
+ private static final String JAVA_SPECIFICATION_VERSION = "java.specification.version";
@Test
void testJava8() {
- testWithVersion("1.8.0_242", () -> {
+ testWithVersion("1.8", () -> {
assertFalse(JavaVersionUtil.isJava11OrHigher());
assertFalse(JavaVersionUtil.isJava13OrHigher());
});
@@ -19,7 +19,7 @@ void testJava8() {
@Test
void testJava11() {
- testWithVersion("11.0.7", () -> {
+ testWithVersion("11", () -> {
assertTrue(JavaVersionUtil.isJava11OrHigher());
assertFalse(JavaVersionUtil.isJava13OrHigher());
});
@@ -27,20 +27,36 @@ void testJava11() {
@Test
void testJava14() {
- testWithVersion("14.0.1", () -> {
+ testWithVersion("14", () -> {
assertTrue(JavaVersionUtil.isJava11OrHigher());
assertTrue(JavaVersionUtil.isJava13OrHigher());
});
}
- private void testWithVersion(String javaVersion, Runnable test) {
- String previous = System.getProperty(JAVA_VERSION);
- System.setProperty(JAVA_VERSION, javaVersion);
+ @Test
+ void testJava17() {
+ testWithVersion("17", () -> {
+ assertTrue(JavaVersionUtil.isJava11OrHigher());
+ assertTrue(JavaVersionUtil.isJava13OrHigher());
+ });
+ }
+
+ @Test
+ void testJava21() {
+ testWithVersion("21", () -> {
+ assertTrue(JavaVersionUtil.isJava11OrHigher());
+ assertTrue(JavaVersionUtil.isJava13OrHigher());
+ });
+ }
+
+ private void testWithVersion(String javaSpecificationVersion, Runnable test) {
+ String previous = System.getProperty(JAVA_SPECIFICATION_VERSION);
+ System.setProperty(JAVA_SPECIFICATION_VERSION, javaSpecificationVersion);
JavaVersionUtil.performChecks();
try {
test.run();
} finally {
- System.setProperty(JAVA_VERSION, previous);
+ System.setProperty(JAVA_SPECIFICATION_VERSION, previous);
JavaVersionUtil.performChecks();
}
| ['core/runtime/src/test/java/io/quarkus/runtime/util/JavaVersionUtilTest.java', 'core/runtime/src/main/java/io/quarkus/runtime/util/JavaVersionUtil.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 14,670,012 | 2,859,631 | 380,858 | 4,038 | 351 | 77 | 4 | 1 | 341 | 49 | 81 | 3 | 0 | 0 | 2021-02-14T17:16:18 | 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,825 | quarkusio/quarkus/15589/15581 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15581 | https://github.com/quarkusio/quarkus/pull/15589 | https://github.com/quarkusio/quarkus/pull/15589 | 1 | close | Named Redis client injection not working when used in separate JAR | **Describe the bug**
We have an application scoped bean, defined in our common project and being used by other services, that utilizes `RedisClient`:
```
@ApplicationScoped
public class Service {
@Inject
@RedisClientName("second")
RedisClient redisClient;
...
}
```
This common project is packaged as JAR and then used as a Maven dependency from other services.
We keep getting this error when starting those other services:
```
javax.enterprise.inject.spi.DeploymentException:
javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type io.quarkus.redis.client.RedisClient and qualifiers [@RedisClientName(value = "second")]
```
We've defined an alternate Redis connection like this:
```
quarkus.redis.second.hosts=redis://localhost:6379
```
and made sure it's being used as expected by a Redis client defined in our service (not the common JAR!) like this:
```
@Inject
@RedisClientName("second")
RedisClient redisClient;
```
Should it be possible to have a bean class contained in a dependency JAR and make it use Redis connection defined in the project that uses that JAR?
**Expected behavior**
Bean defined in a dependency JAR, which uses a Redis client annotated by `@RedisClientName`, properly using Redis connection defined in containing service.
| eb98535ef9d17f08205586ee1fcfbf24990c8010 | ac273f991cda30ab6d5bb98ff0537c70efa40da3 | https://github.com/quarkusio/quarkus/compare/eb98535ef9d17f08205586ee1fcfbf24990c8010...ac273f991cda30ab6d5bb98ff0537c70efa40da3 | diff --git a/extensions/redis-client/deployment/src/main/java/io/quarkus/redis/client/deployment/RedisClientProcessor.java b/extensions/redis-client/deployment/src/main/java/io/quarkus/redis/client/deployment/RedisClientProcessor.java
index 8be65bfaef8..319d51f966a 100644
--- a/extensions/redis-client/deployment/src/main/java/io/quarkus/redis/client/deployment/RedisClientProcessor.java
+++ b/extensions/redis-client/deployment/src/main/java/io/quarkus/redis/client/deployment/RedisClientProcessor.java
@@ -16,13 +16,13 @@
import org.jboss.jandex.IndexView;
import io.quarkus.arc.deployment.AdditionalBeanBuildItem;
+import io.quarkus.arc.deployment.BeanArchiveIndexBuildItem;
import io.quarkus.arc.deployment.SyntheticBeanBuildItem;
import io.quarkus.deployment.Feature;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.ExecutionTime;
import io.quarkus.deployment.annotations.Record;
-import io.quarkus.deployment.builditem.ApplicationArchivesBuildItem;
import io.quarkus.deployment.builditem.ExtensionSslNativeSupportBuildItem;
import io.quarkus.deployment.builditem.FeatureBuildItem;
import io.quarkus.deployment.builditem.nativeimage.RuntimeInitializedClassBuildItem;
@@ -80,13 +80,13 @@ RuntimeInitializedClassBuildItem initializeBulkTypeDuringRuntime() {
@BuildStep
@Record(ExecutionTime.RUNTIME_INIT)
- public void produceRedisClient(RedisClientRecorder recorder, ApplicationArchivesBuildItem applicationArchives,
+ public void produceRedisClient(RedisClientRecorder recorder, BeanArchiveIndexBuildItem indexBuildItem,
BuildProducer<SyntheticBeanBuildItem> syntheticBeans,
VertxBuildItem vertxBuildItem) {
Set<String> clientNames = new HashSet<>();
clientNames.add(RedisClientUtil.DEFAULT_CLIENT);
- IndexView indexView = applicationArchives.getRootArchive().getIndex();
+ IndexView indexView = indexBuildItem.getIndex();
Collection<AnnotationInstance> clientAnnotations = indexView.getAnnotations(REDIS_CLIENT_ANNOTATION);
for (AnnotationInstance annotation : clientAnnotations) {
clientNames.add(annotation.value().asString()); | ['extensions/redis-client/deployment/src/main/java/io/quarkus/redis/client/deployment/RedisClientProcessor.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 15,189,560 | 2,959,275 | 393,566 | 4,179 | 492 | 96 | 6 | 1 | 1,352 | 168 | 284 | 36 | 0 | 4 | 2021-03-09T21:35:39 | 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,824 | quarkusio/quarkus/15610/15607 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15607 | https://github.com/quarkusio/quarkus/pull/15610 | https://github.com/quarkusio/quarkus/pull/15610 | 1 | fixes | Weird warn message with the OpenShift extension | Using the OpenShift extension, I now have this:
```
2021-03-10 17:12:56,920 WARN [io.qua.kub.dep.KubernetesProcessor] (build-56) exposition openshift=Optional.empty
```
I don't think that is normal. It looks like a debug message (and if not, the `Optional.empty` should go).
This is with master, no idea if it ended up in another branch so this needs to be checked. | 712fc3c7bbf5e77662b0e2611163bba8b2fc31d8 | 65226168d123782697f93c333a61b769b454f968 | https://github.com/quarkusio/quarkus/compare/712fc3c7bbf5e77662b0e2611163bba8b2fc31d8...65226168d123782697f93c333a61b769b454f968 | diff --git a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesProcessor.java b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesProcessor.java
index e1fe9b8fc5e..c1c3bbf1e90 100644
--- a/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesProcessor.java
+++ b/extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesProcessor.java
@@ -106,8 +106,6 @@ public void build(ApplicationInfoBuildItem applicationInfo,
throw new RuntimeException("Unable to setup environment for generating Kubernetes resources", e);
}
- log.warn("exposition openshift=" + openshiftConfig.route.host);
-
Map<String, Object> config = KubernetesConfigUtil.toMap(kubernetesConfig, openshiftConfig, knativeConfig);
Set<String> deploymentTargets = kubernetesDeploymentTargets.getEntriesSortedByPriority().stream()
.map(DeploymentTargetEntry::getName) | ['extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/KubernetesProcessor.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 15,202,589 | 2,961,804 | 393,880 | 4,180 | 74 | 16 | 2 | 1 | 375 | 55 | 103 | 8 | 0 | 1 | 2021-03-10T17:48:31 | 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,823 | quarkusio/quarkus/15619/15502 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15502 | https://github.com/quarkusio/quarkus/pull/15619 | https://github.com/quarkusio/quarkus/pull/15619 | 1 | fixes | Amazon LambdaRecorder Handler Discovery fails if handleRequest is in abstract class | **Describe the bug**
If the handleRequest method is implemented in abstract class, then AmazonLambdaRecorder.discoverHandlerMethod fails on [line 88](https://github.com/quarkusio/quarkus/blob/0a7518157ce3fa1ecaf39d62d7b9005ec54f5ff6/extensions/amazon-lambda/runtime/src/main/java/io/quarkus/amazon/lambda/runtime/AmazonLambdaRecorder.java#L88) with an ArrayIndexOutOfBoundsException.
**Expected behavior**
The handler discovery should include inherited methods or it should produce a better error message, e.g. "No handleRequest method found on class com.ExampleHandler. The handleRequest method should be implemented directly in the handler class. Inherited handler methods are not currently supported."
**Actual behavior**
```
2021-03-05 15:04:02,378 ERROR [io.qua.ama.lam.run.AbstractLambdaPollLoop] (Lambda Thread) Lambda init error: java.lang.IllegalStateException: Interrupted while waiting for another thread to start the application
at io.quarkus.runtime.Application.interruptedOnAwaitStart(Application.java:219)
at io.quarkus.runtime.Application.start(Application.java:75)
at io.quarkus.amazon.lambda.runtime.AbstractLambdaPollLoop.checkQuarkusBootstrapped(AbstractLambdaPollLoop.java:160)
at io.quarkus.amazon.lambda.runtime.AbstractLambdaPollLoop$1.run(AbstractLambdaPollLoop.java:46)
at java.lang.Thread.run(Thread.java:834)
at com.oracle.svm.core.thread.JavaThreads.threadStartRoutine(JavaThreads.java:519)
at com.oracle.svm.core.posix.thread.PosixJavaThreads.pthreadStartRoutine(PosixJavaThreads.java:192)
2021-03-05 15:04:02,383 ERROR [io.qua.run.Application] (main) Failed to start application (with profile prod): java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at io.quarkus.amazon.lambda.runtime.AmazonLambdaRecorder.discoverHandlerMethod(AmazonLambdaRecorder.java:88)
at io.quarkus.amazon.lambda.runtime.AmazonLambdaRecorder.setHandlerClass(AmazonLambdaRecorder.java:47)
at io.quarkus.amazon.lambda.runtime.AmazonLambdaRecorder.chooseHandlerClass(AmazonLambdaRecorder.java:140)
at io.quarkus.deployment.steps.AmazonLambdaProcessor$recordHandlerClass-1619263778.deploy_0(AmazonLambdaProcessor$recordHandlerClass-1619263778.zig:196)
at io.quarkus.deployment.steps.AmazonLambdaProcessor$recordHandlerClass-1619263778.deploy(AmazonLambdaProcessor$recordHandlerClass-1619263778.zig:40)
at io.quarkus.runtime.Application.start(Application.java:90)
at io.quarkus.runtime.ApplicationLifecycleManager.run(ApplicationLifecycleManager.java:100)
at io.quarkus.runtime.Quarkus.run(Quarkus.java:66)
```
**To Reproduce**
This was with a Graal Native custom Lambda runtime created following this guide: https://quarkus.io/guides/amazon-lambda
When the handleRequest method is implemented in an abstract class, and is not implemented in the concrete class, the lookup fails with the above error.
**Work around**
Don't use an abstract handler. Yet another reason to prefer composition, I guess. | 19e87cc2c715957b1eee3a61fc11ad7d5ad14507 | 0c67301e076524193f88331dfc3ebf98bcb49ac3 | https://github.com/quarkusio/quarkus/compare/19e87cc2c715957b1eee3a61fc11ad7d5ad14507...0c67301e076524193f88331dfc3ebf98bcb49ac3 | diff --git a/extensions/amazon-lambda/runtime/src/main/java/io/quarkus/amazon/lambda/runtime/AmazonLambdaRecorder.java b/extensions/amazon-lambda/runtime/src/main/java/io/quarkus/amazon/lambda/runtime/AmazonLambdaRecorder.java
index 959399a01ee..025873490e4 100644
--- a/extensions/amazon-lambda/runtime/src/main/java/io/quarkus/amazon/lambda/runtime/AmazonLambdaRecorder.java
+++ b/extensions/amazon-lambda/runtime/src/main/java/io/quarkus/amazon/lambda/runtime/AmazonLambdaRecorder.java
@@ -84,9 +84,12 @@ private Method discoverHandlerMethod(Class<? extends RequestHandler<?, ?>> handl
}
}
}
- if (method == null) {
+ if (method == null && methods.length > 0) {
method = methods[0];
}
+ if (method == null) {
+ throw new RuntimeException("Unable to find a method which handles request on handler class " + handlerClass);
+ }
return method;
}
| ['extensions/amazon-lambda/runtime/src/main/java/io/quarkus/amazon/lambda/runtime/AmazonLambdaRecorder.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 15,202,848 | 2,961,831 | 393,896 | 4,181 | 248 | 53 | 5 | 1 | 2,966 | 195 | 704 | 35 | 2 | 1 | 2021-03-11T04:11:17 | 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,804 | quarkusio/quarkus/15930/15837 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15837 | https://github.com/quarkusio/quarkus/pull/15930 | https://github.com/quarkusio/quarkus/pull/15930 | 1 | close | devmode - Not using JVM instrumentation, but always full restart | ## Describe the bug
I read from @maxandersen that in 1.11+ devmode new ability to detect wether a change can be applied using JVM instrumentation (what ides uses to update running jvms) or it requires a restart as devmode usually do.
### Expected behavior
Hot swap/reload applying JVM instrumentation, without a restart.
### Actual behavior
There´s always a restart, see logs below:
```
12:38:28: Executing task 'quarkusDev'...
> Task :quarkusGenerateCode
preparing quarkus application
> Task :compileJava
> Task :processResources UP-TO-DATE
> Task :classes
> Task :quarkusDev
Listening for transport dt_socket at address: 5005
2021-03-22 12:38:35,557 INFO [io.quarkus] (Quarkus Main Thread) my-artifactId my-version on JVM (powered by Quarkus 1.12.2.Final) started in 3.008s. Listening on: http://localhost:8080
2021-03-22 12:38:35,561 INFO [io.quarkus] (Quarkus Main Thread) Profile dev activated. Live Coding activated.
2021-03-22 12:38:35,562 INFO [io.quarkus] (Quarkus Main Thread) Installed features: [cdi, resteasy, resteasy-jackson]
2021-03-22 12:38:51,100 INFO [io.qua.dep.dev.RuntimeUpdatesProcessor] (vert.x-worker-thread-1) Changed source files detected, recompiling [/Users/admin/dev/others/my-artifactId/src/main/java/org/my/group/MyResource.java]
2021-03-22 12:38:51,597 WARN [io.qua.dep.dev.JavaCompilationProvider] (vert.x-worker-thread-1) system modules path not set in conjunction with -source 11, line -1 in [unknown source]
2021-03-22 12:38:51,663 INFO [io.quarkus] (Quarkus Main Thread) my-artifactId stopped in 0.065s
2021-03-22 12:38:52,370 INFO [io.quarkus] (Quarkus Main Thread) my-artifactId my-version on JVM (powered by Quarkus 1.12.2.Final) started in 0.701s. Listening on: http://localhost:8080
2021-03-22 12:38:52,371 INFO [io.quarkus] (Quarkus Main Thread) Profile dev activated. Live Coding activated.
2021-03-22 12:38:52,371 INFO [io.quarkus] (Quarkus Main Thread) Installed features: [cdi, resteasy, resteasy-jackson]
2021-03-22 12:38:52,371 INFO [io.qua.dep.dev.RuntimeUpdatesProcessor] (vert.x-worker-thread-1) Hot replace total time: 1.273s
```
## To Reproduce
- I´ve used directly the output of
```
mvn io.quarkus:quarkus-maven-plugin:1.12.2.Final:create \\
-DprojectGroupId=my-groupId \\
-DprojectArtifactId=my-artifactId \\
-DprojectVersion=my-version \\
-DclassName="org.my.group.MyResource" \\
-Dextensions="resteasy,resteasy-jackson" \\
-DbuildTool=gradle
```
## Environment (please complete the following information):
Intellij IDEA community 2020.3 build 203.5981.155 (also from console directly)
OS: Mac
Quarkus 1.12.2
### Output of `java -version`
>java -version
openjdk version "15" 2020-09-15
OpenJDK Runtime Environment (build 15+36-1562)
OpenJDK 64-Bit Server VM (build 15+36-1562, mixed mode, sharing)
### GraalVM version (if different from Java)
Not used
### Quarkus version or git rev
1.12.2
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
Gradle 6.8.3 | 04db442e87626fa58c08a51fe4dd4f56ca912dd2 | 2161d421e9bbb8e4e02c95e8299c9aa267ec8f59 | https://github.com/quarkusio/quarkus/compare/04db442e87626fa58c08a51fe4dd4f56ca912dd2...2161d421e9bbb8e4e02c95e8299c9aa267ec8f59 | diff --git a/devtools/gradle/src/main/java/io/quarkus/gradle/tasks/QuarkusDev.java b/devtools/gradle/src/main/java/io/quarkus/gradle/tasks/QuarkusDev.java
index d8c94a0a744..07fcf7de684 100644
--- a/devtools/gradle/src/main/java/io/quarkus/gradle/tasks/QuarkusDev.java
+++ b/devtools/gradle/src/main/java/io/quarkus/gradle/tasks/QuarkusDev.java
@@ -236,11 +236,21 @@ private QuarkusDevModeLauncher newLauncher() throws Exception {
for (AppDependency appDependency : appModel.getFullDeploymentDeps()) {
final AppArtifact appArtifact = appDependency.getArtifact();
+ //we only use the launcher for launching from the IDE, we need to exclude it
+ if (appArtifact.getGroupId().equals("io.quarkus") && appArtifact.getGroupId().equals("quarkus-ide-launcher")) {
+ continue;
+ }
if (!projectDependencies.contains(new AppArtifactKey(appArtifact.getGroupId(), appArtifact.getArtifactId()))) {
appArtifact.getPaths().forEach(p -> {
if (Files.exists(p)) {
- addToClassPaths(builder, p.toFile());
+ if (appArtifact.getGroupId().equals("io.quarkus")
+ && appArtifact.getArtifactId().equals("quarkus-class-change-agent")) {
+ builder.jvmArgs("-javaagent:" + p.toFile().getAbsolutePath());
+ } else {
+ addToClassPaths(builder, p.toFile());
+ }
}
+
});
}
} | ['devtools/gradle/src/main/java/io/quarkus/gradle/tasks/QuarkusDev.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 15,405,098 | 3,000,159 | 398,995 | 4,248 | 720 | 132 | 12 | 1 | 3,042 | 339 | 949 | 67 | 2 | 2 | 2021-03-22T15:05:21 | 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,805 | quarkusio/quarkus/15913/15442 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15442 | https://github.com/quarkusio/quarkus/pull/15913 | https://github.com/quarkusio/quarkus/pull/15913 | 1 | fixes | Narayana STM failing to build in Native | **Describe the bug**
When building a Quarkus application with the Narayana STM and also using any other extension that also brings the narayana JTA extension (hibernate orm, agroal, etc), the build fails in Native with:
```
[INFO] [io.quarkus.deployment.pkg.steps.NativeImageBuildStep] docker run -v /home/jcarvaja/Downloads/tmp/code-with-quarkus/target/code-with-quarkus-1.0.0-SNAPSHOT-native-image-source-jar:/project:z --env LANG=C --user 1000:1000 --rm quay.io/quarkus/ubi-quarkus-native-image:21.0.0-java11 -J-DCoordinatorEnvironmentBean.transactionStatusManagerEnable=false -J-Dsun.nio.ch.maxUpdateArraySize=100 -J-Djava.util.logging.manager=org.jboss.logmanager.LogManager -J-Dvertx.logger-delegate-factory-class-name=io.quarkus.vertx.core.runtime.VertxLogDelegateFactory -J-Dvertx.disableDnsResolver=true -J-Dio.netty.leakDetection.level=DISABLED -J-Dio.netty.allocator.maxOrder=1 -J-DCoordinatorEnvironmentBean.transactionStatusManagerEnable=false -J-Duser.language=es -J-Duser.country=ES -J-Dfile.encoding=UTF-8 --initialize-at-build-time= -H:InitialCollectionPolicy=com.oracle.svm.core.genscavenge.CollectionPolicy\\$BySpaceAndTime -H:+JNI -H:+AllowFoldMethods -jar code-with-quarkus-1.0.0-SNAPSHOT-runner.jar -H:FallbackThreshold=0 -H:+ReportExceptionStackTraces -J-Xmx4g -H:-AddAllCharsets -H:EnableURLProtocols=http --no-server -H:-UseServiceLoaderFeature -H:+StackTrace code-with-quarkus-1.0.0-SNAPSHOT-runner
[code-with-quarkus-1.0.0-SNAPSHOT-runner:24] classlist: 4.198,77 ms, 1,19 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:24] (cap): 815,95 ms, 1,19 GB
[code-with-quarkus-1.0.0-SNAPSHOT-runner:24] setup: 2.879,19 ms, 1,19 GB
15:13:59,636 INFO [org.jbo.threads] JBoss Threads version 3.2.0.Final
To see how the classes got initialized, use --trace-class-initialization=com.arjuna.ats.internal.arjuna.utils.SocketProcessId
[code-with-quarkus-1.0.0-SNAPSHOT-runner:24] analysis: 37.311,65 ms, 1,87 GB
Error: Classes that should be initialized at run time got initialized during image building:
com.arjuna.ats.internal.arjuna.utils.SocketProcessId the class was requested to be initialized at run time (from feature io.quarkus.runner.AutoFeature.beforeAnalysis). To see why com.arjuna.ats.internal.arjuna.utils.SocketProcessId got initialized use --trace-class-initialization=com.arjuna.ats.internal.arjuna.utils.SocketProcessId
com.oracle.svm.core.util.UserError$UserException: Classes that should be initialized at run time got initialized during image building:
com.arjuna.ats.internal.arjuna.utils.SocketProcessId the class was requested to be initialized at run time (from feature io.quarkus.runner.AutoFeature.beforeAnalysis). To see why com.arjuna.ats.internal.arjuna.utils.SocketProcessId got initialized use --trace-class-initialization=com.arjuna.ats.internal.arjuna.utils.SocketProcessId
at com.oracle.svm.core.util.UserError.abort(UserError.java:68)
at com.oracle.svm.hosted.classinitialization.ConfigurableClassInitialization.checkDelayedInitialization(ConfigurableClassInitialization.java:539)
at com.oracle.svm.hosted.classinitialization.ClassInitializationFeature.duringAnalysis(ClassInitializationFeature.java:226)
at com.oracle.svm.hosted.NativeImageGenerator.lambda$runPointsToAnalysis$8(NativeImageGenerator.java:740)
at com.oracle.svm.hosted.FeatureHandler.forEachFeature(FeatureHandler.java:70)
at com.oracle.svm.hosted.NativeImageGenerator.runPointsToAnalysis(NativeImageGenerator.java:740)
at com.oracle.svm.hosted.NativeImageGenerator.doRun(NativeImageGenerator.java:563)
at com.oracle.svm.hosted.NativeImageGenerator.lambda$run$0(NativeImageGenerator.java:476)
at java.base/java.util.concurrent.ForkJoinTask$AdaptedRunnableAction.exec(ForkJoinTask.java:1407)
at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183)
Error: Image build request failed with exit status 1
```
**Expected behavior**
It should work as in JVM.
**Actual behavior**
It fails when building, see exception above.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to code.quarkus.io
2. Select Narayana STM extension and Agroal (or directly Narayana JTA)
3. Download the ZIP and try to build the application using:
```
mvn clean install -Dnative -Dquarkus.native.container-build=true
```
**Environment (please complete the following information):**
- Quarkus version or git rev: 1.12.0.Final and 999-SNAPSHOT | 33062777080701f3d7c258f8585081357c12d56c | 78c56330ecb4355e948b55f78ecf13de57759dd6 | https://github.com/quarkusio/quarkus/compare/33062777080701f3d7c258f8585081357c12d56c...78c56330ecb4355e948b55f78ecf13de57759dd6 | diff --git a/extensions/narayana-stm/deployment/src/main/java/io/quarkus/narayana/stm/deployment/NarayanaSTMProcessor.java b/extensions/narayana-stm/deployment/src/main/java/io/quarkus/narayana/stm/deployment/NarayanaSTMProcessor.java
index b23e3d0b602..bb2082d8e3b 100644
--- a/extensions/narayana-stm/deployment/src/main/java/io/quarkus/narayana/stm/deployment/NarayanaSTMProcessor.java
+++ b/extensions/narayana-stm/deployment/src/main/java/io/quarkus/narayana/stm/deployment/NarayanaSTMProcessor.java
@@ -18,6 +18,7 @@
import com.arjuna.ats.internal.arjuna.coordinator.CheckedActionFactoryImple;
import com.arjuna.ats.internal.arjuna.objectstore.ShadowNoFileLockStore;
+import com.arjuna.ats.internal.arjuna.utils.SocketProcessId;
import com.arjuna.ats.txoj.Lock;
import io.quarkus.deployment.Feature;
@@ -30,6 +31,7 @@
import io.quarkus.deployment.builditem.nativeimage.NativeImageSystemPropertyBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveHierarchyBuildItem;
+import io.quarkus.deployment.builditem.nativeimage.RuntimeInitializedClassBuildItem;
import io.quarkus.narayana.stm.runtime.NarayanaSTMRecorder;
class NarayanaSTMProcessor {
@@ -60,8 +62,11 @@ public NativeImageSystemPropertyBuildItem substrateSystemPropertyBuildItem() {
// so disable it at runtime
@BuildStep()
@Record(RUNTIME_INIT)
- public void configureRuntimeProperties(NarayanaSTMRecorder recorder) {
+ public void configureRuntimeProperties(NarayanaSTMRecorder recorder,
+ BuildProducer<RuntimeInitializedClassBuildItem> runtimeInit) {
recorder.disableTransactionStatusManager();
+ runtimeInit.produce(new RuntimeInitializedClassBuildItem(SocketProcessId.class.getName()));
+ runtimeInit.produce(new RuntimeInitializedClassBuildItem(Lock.class.getName()));
}
// register STM dynamic proxies | ['extensions/narayana-stm/deployment/src/main/java/io/quarkus/narayana/stm/deployment/NarayanaSTMProcessor.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 15,396,863 | 2,998,612 | 398,841 | 4,248 | 564 | 109 | 7 | 1 | 4,801 | 296 | 1,258 | 52 | 0 | 2 | 2021-03-22T07:17:22 | 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,806 | quarkusio/quarkus/15910/15903 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15903 | https://github.com/quarkusio/quarkus/pull/15910 | https://github.com/quarkusio/quarkus/pull/15910 | 1 | fixes | MappedByteBufferReplacement substitutions is obsolete in JDK16 | ## Describe the bug
Trying to build a simple Quarkus Native Image application with a JDK16 based GraalVM results in
```
Error: Could not find target method: private void io.quarkus.runtime.graal.MappedByteBufferReplacement.force0(java.io.FileDescriptor,long,long)
com.oracle.svm.core.util.UserError$UserException: Could not find target method: private void io.quarkus.runtime.graal.MappedByteBufferReplacement.force0(java.io.FileDescriptor,long,long)
at com.oracle.svm.core.util.UserError.abort(UserError.java:68)
at com.oracle.svm.hosted.substitute.AnnotationSubstitutionProcessor.findOriginalMethod(AnnotationSubstitutionProcessor.java:734)
at com.oracle.svm.hosted.substitute.AnnotationSubstitutionProcessor.handleMethodInAliasClass(AnnotationSubstitutionProcessor.java:366)
at com.oracle.svm.hosted.substitute.AnnotationSubstitutionProcessor.handleAliasClass(AnnotationSubstitutionProcessor.java:338)
at com.oracle.svm.hosted.substitute.AnnotationSubstitutionProcessor.handleClass(AnnotationSubstitutionProcessor.java:310)
at com.oracle.svm.hosted.substitute.AnnotationSubstitutionProcessor.init(AnnotationSubstitutionProcessor.java:266)
at com.oracle.svm.hosted.NativeImageGenerator.createDeclarativeSubstitutionProcessor(NativeImageGenerator.java:952)
at com.oracle.svm.hosted.NativeImageGenerator.setupNativeImage(NativeImageGenerator.java:886)
at com.oracle.svm.hosted.NativeImageGenerator.doRun(NativeImageGenerator.java:578)
at com.oracle.svm.hosted.NativeImageGenerator.lambda$run$2(NativeImageGenerator.java:493)
at java.base/java.util.concurrent.ForkJoinTask$AdaptedRunnableAction.exec(ForkJoinTask.java:1414)
at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:295)
at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1016)
at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1665)
at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1598)
at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183)
```
The target method [`MappedByteBuffer.force0`](https://github.com/quarkusio/quarkus/blob/main/core/runtime/src/main/java/io/quarkus/runtime/graal/MappedByteBufferReplacement.java#L13) has been removed in JDK16.
Note: A JDK16 GraalVM is not widely available yet, it must be built from source. | 33062777080701f3d7c258f8585081357c12d56c | 7bf3040ea9e4d0c20322ff841ae9617de761081a | https://github.com/quarkusio/quarkus/compare/33062777080701f3d7c258f8585081357c12d56c...7bf3040ea9e4d0c20322ff841ae9617de761081a | diff --git a/core/runtime/src/main/java/io/quarkus/runtime/graal/MappedByteBufferReplacement.java b/core/runtime/src/main/java/io/quarkus/runtime/graal/MappedByteBufferReplacement.java
index f98382534aa..4b8967faffb 100644
--- a/core/runtime/src/main/java/io/quarkus/runtime/graal/MappedByteBufferReplacement.java
+++ b/core/runtime/src/main/java/io/quarkus/runtime/graal/MappedByteBufferReplacement.java
@@ -5,8 +5,9 @@
import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;
+import com.oracle.svm.core.jdk.JDK15OrEarlier;
-@TargetClass(MappedByteBuffer.class)
+@TargetClass(value = MappedByteBuffer.class, onlyWith = JDK15OrEarlier.class)
final class MappedByteBufferReplacement {
@Substitute | ['core/runtime/src/main/java/io/quarkus/runtime/graal/MappedByteBufferReplacement.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 15,396,863 | 2,998,612 | 398,841 | 4,248 | 164 | 41 | 3 | 1 | 2,377 | 96 | 535 | 25 | 1 | 1 | 2021-03-22T02:56:55 | 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,807 | quarkusio/quarkus/15898/15886 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15886 | https://github.com/quarkusio/quarkus/pull/15898 | https://github.com/quarkusio/quarkus/pull/15898 | 1 | resolves | CDI events qualifiers not working when abstract superclass is in a library | ## Describe the bug
CDI events qualifiers are not working well when abstract superclass is in a library since when implementing the class it will be registered as a general observer instead of one with a qualifier.
Check https://github.com/MarcoMartins86/event_qualifier_issue for more details.
### Expected behavior
If I trigger an important event `http://localhost:8080/Events/Important` should appear:
```text
Library AbstractObserverImportantEvent: Important event message 0 Event qualifiers[[@org.acme.ImportantEvent(), @javax.enterprise.inject.Any()]]
Runner ImportantEventImpl: Important event message 0
```
### Actual behavior
If I trigger an important event `http://localhost:8080/Events/Important` appears:
```text
Library AbstractObserverNormalEvent: Important event message 0 Event qualifiers[[@org.acme.ImportantEvent(), @javax.enterprise.inject.Any()]]
Runner NormalEventImpl: Important event message 0
Library AbstractObserverImportantEvent: Important event message 0 Event qualifiers[[@org.acme.ImportantEvent(), @javax.enterprise.inject.Any()]]
Runner ImportantEventImpl: Important event message 0
```
## To Reproduce
A project that reproduces this https://github.com/MarcoMartins86/event_qualifier_issue
Steps to reproduce the behavior:
1. make
2. Do GET to http://localhost:8080/Events/Important
3. Check the command line for the prints
## Environment (please complete the following information):
### Output of `uname -a` or `ver`
Darwin PT-320323-MBP16 20.2.0 Darwin Kernel Version 20.2.0: Wed Dec 2 20:39:59 PST 2020; root:xnu-7195.60.75~1/RELEASE_X86_64 x86_64
### Output of `java -version`
java version "11.0.9" 2020-10-20 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.9+7-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.9+7-LTS, mixed mode)
### GraalVM version (if different from Java)
### Quarkus version or git rev
1.12.2.Final
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
Maven home: /usr/local/Cellar/maven/3.6.3_1/libexec
Java version: 11.0.9, vendor: Oracle Corporation, runtime: /Library/Java/JavaVirtualMachines/jdk-11.0.9.jdk/Contents/Home
Default locale: en_PT, platform encoding: UTF-8
OS name: "mac os x", version: "10.16", arch: "x86_64", family: "mac"
## Additional context
| 69c1551a0fde22c007e1e6e19a87ac2d4421eb8e | 4f83ab734e829099bf5ce010eb07fb3035b89895 | https://github.com/quarkusio/quarkus/compare/69c1551a0fde22c007e1e6e19a87ac2d4421eb8e...4f83ab734e829099bf5ce010eb07fb3035b89895 | diff --git a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/DisposerInfo.java b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/DisposerInfo.java
index 9712660d828..175bae52a50 100644
--- a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/DisposerInfo.java
+++ b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/DisposerInfo.java
@@ -86,7 +86,7 @@ Type getDisposedParameterType() {
MethodParameterInfo initDisposedParam(MethodInfo disposerMethod) {
List<MethodParameterInfo> disposedParams = new ArrayList<>();
for (AnnotationInstance annotation : disposerMethod.annotations()) {
- if (Kind.METHOD_PARAMETER.equals(annotation.target().kind()) && annotation.name().equals(DotNames.DISPOSES)) {
+ if (Kind.METHOD_PARAMETER == annotation.target().kind() && annotation.name().equals(DotNames.DISPOSES)) {
disposedParams.add(annotation.target().asMethodParameter());
}
}
diff --git a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ObserverInfo.java b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ObserverInfo.java
index 298109e92db..b23b85a08b5 100644
--- a/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ObserverInfo.java
+++ b/independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ObserverInfo.java
@@ -1,5 +1,8 @@
package io.quarkus.arc.processor;
+import static io.quarkus.arc.processor.Annotations.find;
+import static io.quarkus.arc.processor.Annotations.getParameterAnnotations;
+
import io.quarkus.arc.processor.BuildExtension.BuildContext;
import io.quarkus.arc.processor.ObserverTransformer.ObserverTransformation;
import io.quarkus.arc.processor.ObserverTransformer.TransformationContext;
@@ -36,9 +39,11 @@ public class ObserverInfo implements InjectionTargetInfo {
static ObserverInfo create(BeanInfo declaringBean, MethodInfo observerMethod, Injection injection, boolean isAsync,
List<ObserverTransformer> transformers, BuildContext buildContext, boolean jtaCapabilities) {
MethodParameterInfo eventParameter = initEventParam(observerMethod, declaringBean.getDeployment());
- AnnotationInstance priorityAnnotation = observerMethod.annotation(DotNames.PRIORITY);
+ AnnotationInstance priorityAnnotation = find(
+ getParameterAnnotations(declaringBean.getDeployment(), observerMethod, eventParameter.position()),
+ DotNames.PRIORITY);
Integer priority;
- if (priorityAnnotation != null && priorityAnnotation.target().equals(eventParameter)) {
+ if (priorityAnnotation != null) {
priority = priorityAnnotation.value().asInt();
} else {
priority = ObserverMethod.DEFAULT_PRIORITY;
@@ -285,10 +290,9 @@ static TransactionPhase initTransactionPhase(boolean isAsync, BeanDeployment bea
static Set<AnnotationInstance> initQualifiers(BeanDeployment beanDeployment, MethodInfo observerMethod,
MethodParameterInfo eventParameter) {
Set<AnnotationInstance> qualifiers = new HashSet<>();
- for (AnnotationInstance annotation : beanDeployment.getAnnotations(observerMethod)) {
- if (annotation.target().equals(eventParameter)) {
- beanDeployment.extractQualifiers(annotation).forEach(qualifiers::add);
- }
+ for (AnnotationInstance annotation : getParameterAnnotations(beanDeployment, observerMethod,
+ eventParameter.position())) {
+ beanDeployment.extractQualifiers(annotation).forEach(qualifiers::add);
}
return qualifiers;
} | ['independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/ObserverInfo.java', 'independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/DisposerInfo.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 15,396,145 | 2,998,472 | 398,825 | 4,247 | 1,315 | 228 | 18 | 2 | 2,382 | 259 | 655 | 54 | 5 | 2 | 2021-03-19T20:40: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,808 | quarkusio/quarkus/15869/15859 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15859 | https://github.com/quarkusio/quarkus/pull/15869 | https://github.com/quarkusio/quarkus/pull/15869 | 1 | fixes | "quarkus.http.test-timeout" Was removed ? (using 1.12.1.Final) | I have this in my application.properties
# timeout for junit RestAssured / debug
%test.quarkus.http.test-timeout=600s
I'm using : <quarkus.platform.version>1.12.1.Final</quarkus.platform.version>
and now I obtain this in the logs
2021-03-18 12:47:35,512 WARN [io.qua.config] (main) Unrecognized configuration key "quarkus.http.test-timeout" was provided; it will be ignored; verify that the dependency extension for this configuration is set or you did not make a typo
In that guide : https://quarkus.io/guides/getting-started-testing
4.2. Controlling HTTP interaction timeout
When using REST Assured in your test, the connection and response timeouts are set to 30 seconds. You can override this setting with the quarkus.http.test-timeout property:
quarkus.http.test-timeout=10s
It should be a false warning:
| f54f17f1a899805fab6c7e1e05716fa94b51f592 | 521b939d089339b30e2f198ebed3e44592e9ce9d | https://github.com/quarkusio/quarkus/compare/f54f17f1a899805fab6c7e1e05716fa94b51f592...521b939d089339b30e2f198ebed3e44592e9ce9d | diff --git a/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/HttpBuildTimeConfig.java b/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/HttpBuildTimeConfig.java
index 172a24288d0..6bca11e7fe1 100644
--- a/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/HttpBuildTimeConfig.java
+++ b/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/HttpBuildTimeConfig.java
@@ -1,5 +1,7 @@
package io.quarkus.vertx.http.runtime;
+import java.time.Duration;
+
import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;
@@ -68,4 +70,10 @@ public class HttpBuildTimeConfig {
*/
@ConfigItem(defaultValue = "true")
public boolean redirectToNonApplicationRootPath;
+
+ /**
+ * The REST Assured client timeout for testing.
+ */
+ @ConfigItem(defaultValue = "30s")
+ public Duration testTimeout;
} | ['extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/HttpBuildTimeConfig.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 15,379,771 | 2,995,273 | 398,420 | 4,235 | 175 | 39 | 8 | 1 | 840 | 101 | 214 | 20 | 1 | 0 | 2021-03-18T22:06:13 | 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,810 | quarkusio/quarkus/15838/15825 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15825 | https://github.com/quarkusio/quarkus/pull/15838 | https://github.com/quarkusio/quarkus/pull/15838 | 1 | fixes | ElasticRestClient fails to load the provided custom configuration via @ElasticsearchClientConfig | ## Describe the bug
The ElasticRestClient fails to load the provided custom configuration via @ElasticsearchClientConfig.
I followed the documentation here https://quarkus.io/guides/elasticsearch#programmatically-configuring-elasticsearch to provide a custom configuration for elastic search.
In my case I am adding AWS signing interceptor to the httpClientBuilder.
Version 1.12.2.Final
### Expected behavior
The custom configuration (signing interceptor) should get loaded up
### Actual behavior
Fails to load the custom configuration.
## To Reproduce
Add a new custom configuration based on the docs.
```
@ApplicationScoped
@ElasticsearchClientConfig
public class MyCustomConfig implements RestClientBuilder.HttpClientConfigCallback {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
// log something here
}
}
```
Then inject the REST client.
```
@Inject
RestClient lowLevelClient;
```
No logged message above
From the MR here: https://github.com/quarkusio/quarkus/commit/08df613dd1f989a96b2414755ddd1dbc1c8ec02b#diff-3530ce31269994606ad048f4d42f2fa57425d1fa08c6cf4ffb37980ee8dcbd5dR86
```
Iterable<InstanceHandle<RestClientBuilder.HttpClientConfigCallback>> handles = Arc.container()
.select(RestClientBuilder.HttpClientConfigCallback.class, new ElasticsearchClientConfig.Literal())
.handles();
```
I copied the above code to my unit tests and the size of the `handles` variable always seem to be 0.
Arc.container() does not seem to find the custom config.
Or is there another class registration step missed in the documentation ?
Any feedback is really appreciated.
Thank you
Tagging original authors for help.
@eAybars @gsmet | 2ffff2ec818ca84fc4ed77768c4d453c57aae5b3 | ef38740d32498754972755acfbf58caa0889a8d2 | https://github.com/quarkusio/quarkus/compare/2ffff2ec818ca84fc4ed77768c4d453c57aae5b3...ef38740d32498754972755acfbf58caa0889a8d2 | diff --git a/extensions/elasticsearch-rest-client/deployment/src/main/java/io/quarkus/elasticsearch/restclient/lowlevel/deployment/ElasticsearchLowLevelClientProcessor.java b/extensions/elasticsearch-rest-client/deployment/src/main/java/io/quarkus/elasticsearch/restclient/lowlevel/deployment/ElasticsearchLowLevelClientProcessor.java
index 00187a72355..5f631fc2dc1 100644
--- a/extensions/elasticsearch-rest-client/deployment/src/main/java/io/quarkus/elasticsearch/restclient/lowlevel/deployment/ElasticsearchLowLevelClientProcessor.java
+++ b/extensions/elasticsearch-rest-client/deployment/src/main/java/io/quarkus/elasticsearch/restclient/lowlevel/deployment/ElasticsearchLowLevelClientProcessor.java
@@ -6,6 +6,7 @@
import io.quarkus.arc.deployment.BeanDefiningAnnotationBuildItem;
import io.quarkus.arc.processor.DotNames;
import io.quarkus.deployment.Feature;
+import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.FeatureBuildItem;
import io.quarkus.elasticsearch.restclient.lowlevel.ElasticsearchClientConfig;
@@ -27,8 +28,13 @@ AdditionalBeanBuildItem build() {
}
@BuildStep
- BeanDefiningAnnotationBuildItem elasticsearchClientConfigBeanDefiningAnnotation() {
- return new BeanDefiningAnnotationBuildItem(ELASTICSEARCH_CLIENT_CONFIG, DotNames.APPLICATION_SCOPED, false);
+ void elasticsearchClientConfigSupport(BuildProducer<AdditionalBeanBuildItem> additionalBeans,
+ BuildProducer<BeanDefiningAnnotationBuildItem> beanDefiningAnnotations) {
+ // add the @ElasticsearchClientConfig class otherwise it won't be registered as a qualifier
+ additionalBeans.produce(AdditionalBeanBuildItem.builder().addBeanClass(ElasticsearchClientConfig.class).build());
+
+ beanDefiningAnnotations
+ .produce(new BeanDefiningAnnotationBuildItem(ELASTICSEARCH_CLIENT_CONFIG, DotNames.APPLICATION_SCOPED, false));
}
@BuildStep
diff --git a/extensions/elasticsearch-rest-client/deployment/src/test/java/io/quarkus/elasticsearch/restclient/lowlevel/runtime/ElasticsearchClientConfigTest.java b/extensions/elasticsearch-rest-client/deployment/src/test/java/io/quarkus/elasticsearch/restclient/lowlevel/runtime/ElasticsearchClientConfigTest.java
index 06c308031e9..2f56c48eff7 100644
--- a/extensions/elasticsearch-rest-client/deployment/src/test/java/io/quarkus/elasticsearch/restclient/lowlevel/runtime/ElasticsearchClientConfigTest.java
+++ b/extensions/elasticsearch-rest-client/deployment/src/test/java/io/quarkus/elasticsearch/restclient/lowlevel/runtime/ElasticsearchClientConfigTest.java
@@ -26,30 +26,24 @@ public class ElasticsearchClientConfigTest {
@Inject
ElasticsearchConfig config;
- @Inject
- @ElasticsearchClientConfig
- TestConfigurator testConfigurator;
@Test
public void testRestClientBuilderHelperWithElasticsearchClientConfig() {
RestClientBuilderHelper.createRestClientBuilder(config).build();
- assertTrue(testConfigurator.isInvoked());
+ assertTrue(TestConfigurator.invoked);
}
@ElasticsearchClientConfig
@ApplicationScoped
public static class TestConfigurator implements RestClientBuilder.HttpClientConfigCallback {
- private boolean invoked = false;
+
+ private static boolean invoked = false;
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder builder) {
invoked = true;
return builder;
}
-
- public boolean isInvoked() {
- return invoked;
- }
}
} | ['extensions/elasticsearch-rest-client/deployment/src/main/java/io/quarkus/elasticsearch/restclient/lowlevel/deployment/ElasticsearchLowLevelClientProcessor.java', 'extensions/elasticsearch-rest-client/deployment/src/test/java/io/quarkus/elasticsearch/restclient/lowlevel/runtime/ElasticsearchClientConfigTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 15,335,851 | 2,987,176 | 397,263 | 4,231 | 837 | 168 | 10 | 1 | 1,840 | 183 | 412 | 59 | 2 | 3 | 2021-03-18T09:42: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,813 | quarkusio/quarkus/15798/10578 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/10578 | https://github.com/quarkusio/quarkus/pull/15798 | https://github.com/quarkusio/quarkus/pull/15798 | 1 | fixes | Named handler log files get logs duplicated when hot reload is performed | **Describe the bug**
In properties file I have configured 2 different named handlers, for very specific logging categories.
In dev mode the log in these categories are working fine and directed toward the right file handler.
When an hot-reload is performed I see the log lines duplicated, and each time a new hot-reload is performed there is one more copy of the log lines pushed to the files.
This might be related to the named log handler being registered multiple times on hot reload, I'm guessing, because console log and the general `quarkus.log.file.path` do not get duplicates traces after several hot reloads.
**Expected behavior**
Hot reload should reset logging configuration, and not duplicate log lines in named handler files
**Actual behavior**
After hot reload duplicate log lines are added to named handler log files, and the duplication factor is the number of live reloads performed.
**To Reproduce**
Steps to reproduce the behavior:
1. Configure named log handler
2. Append to the matching log topic/categories
3. See log lines appears one at a time
4. Perform hot reload, changing a blank line in source or something meaningless
5. See log lines appears duplicate
6. Perform another hot reload
7. See log lines appear 3 times each
**Configuration**
```properties
# Add your application.properties here, if applicable.
#Logging
quarkus.log.level=INFO
quarkus.log.category."com.darva.urlshortener".level=DEBUG
# Configure a named handler that logs to Activite file
quarkus.log.handler.file."ACTIVITE".enable=true
quarkus.log.handler.file."ACTIVITE".path=../logs/activite.log
quarkus.log.handler.file."ACTIVITE".format=%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX};%X{raisonsociale};%X{userroles};%X{sessionId};%X{posteId};%X{userId};%X{versionApp};%X{service};SERVICE-NAME;%X{numclient};%X{transactionId};%X{versionConfApp};%X{versionConfTech};%X{codePro};%X{codeAbo};%m%n
quarkus.log.category."com.company.log.ActivityTracer".level=INFO
quarkus.log.category."com.company.log.ActivityTracer".handlers=ACTIVITE
# Configure a named handler that logs to Exploitation file
quarkus.log.handler.file."EXPLOITATION".enable=true
quarkus.log.handler.file."EXPLOITATION".path=../logs/exploitation.log
quarkus.log.handler.file."EXPLOITATION".format=%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX};%X{raisonsociale};%X{userroles};%X{sessionId};%X{posteId};%X{userId};%X{versionApp};%X{service};SERVICE-NAME;%X{numclient};%X{transactionId};%X{versionConfApp};%X{versionConfTech};%X{codePro};%X{codeAbo};%p;%C;%m;%M%n
quarkus.log.category."com.company.log.ExploitationTracer".level=ERROR
quarkus.log.category."com.company.log.ExploitationTracer".handlers=EXPLOITATION
# General log goes to Application file
quarkus.log.file.enable=true
quarkus.log.file.path=../logs/application.log
quarkus.log.file.format=%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX};%X{raisonsociale};%X{userroles};%X{sessionId};%X{posteId};%X{userId};%X{versionApp};%X{service};SERVICE-NAME;%X{numclient};%X{transactionId};%X{versionConfApp};%X{versionConfTech};%X{codePro};%X{codeAbo};%p;%C;%m;%M%n
quarkus.log.file.level=DEBUG
quarkus.log.min-level=DEBUG
```
**Environment (please complete the following information):**
- Output of `uname -a` or `ver`: Darwin ***********.local 19.5.0 Darwin Kernel Version 19.5.0: Tue May 26 20:41:44 PDT 2020; root:xnu-6153.121.2~2/RELEASE_X86_64 x86_64
- 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):
- Quarkus version or git rev: 1.5.2.Final
- Build tool (ie. output of `mvnw --version` or `gradlew --version`): Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
**Additional context**
This all happened in dev mode, running the application using either `mvn quarkus:dev` or `./mvnw quarkus:dev`. Not very critical to me either, as hot reload is only useful for dev environment.
| ce244e1c13933a1862163fc70d0d5babcacdd41b | 5b69ffa9ded999138edfaaa6d9692bbf9697ee4a | https://github.com/quarkusio/quarkus/compare/ce244e1c13933a1862163fc70d0d5babcacdd41b...5b69ffa9ded999138edfaaa6d9692bbf9697ee4a | diff --git a/core/runtime/src/main/java/io/quarkus/runtime/logging/LoggingSetupRecorder.java b/core/runtime/src/main/java/io/quarkus/runtime/logging/LoggingSetupRecorder.java
index 3bd50a147ad..9715b77d878 100644
--- a/core/runtime/src/main/java/io/quarkus/runtime/logging/LoggingSetupRecorder.java
+++ b/core/runtime/src/main/java/io/quarkus/runtime/logging/LoggingSetupRecorder.java
@@ -289,14 +289,27 @@ private static void addToNamedHandlers(Map<String, Handler> namedHandlers, Handl
handlerName));
}
namedHandlers.put(handlerName, handler);
+ InitialConfigurator.DELAYED_HANDLER.addLoggingCloseTask(new Runnable() {
+ @Override
+ public void run() {
+ handler.close();
+ }
+ });
}
private static void addNamedHandlersToCategory(CategoryConfig categoryConfig, Map<String, Handler> namedHandlers,
Logger categoryLogger,
ErrorManager errorManager) {
for (String categoryNamedHandler : categoryConfig.handlers.get()) {
- if (namedHandlers.get(categoryNamedHandler) != null) {
- categoryLogger.addHandler(namedHandlers.get(categoryNamedHandler));
+ Handler handler = namedHandlers.get(categoryNamedHandler);
+ if (handler != null) {
+ categoryLogger.addHandler(handler);
+ InitialConfigurator.DELAYED_HANDLER.addLoggingCloseTask(new Runnable() {
+ @Override
+ public void run() {
+ categoryLogger.removeHandler(handler);
+ }
+ });
} else {
errorManager.error(String.format("Handler with name '%s' is linked to a category but not configured.",
categoryNamedHandler), null, ErrorManager.GENERIC_FAILURE);
diff --git a/independent-projects/bootstrap/runner/src/main/java/io/quarkus/bootstrap/logging/QuarkusDelayedHandler.java b/independent-projects/bootstrap/runner/src/main/java/io/quarkus/bootstrap/logging/QuarkusDelayedHandler.java
index ae28d6fc633..b39f29a5d57 100644
--- a/independent-projects/bootstrap/runner/src/main/java/io/quarkus/bootstrap/logging/QuarkusDelayedHandler.java
+++ b/independent-projects/bootstrap/runner/src/main/java/io/quarkus/bootstrap/logging/QuarkusDelayedHandler.java
@@ -17,7 +17,9 @@
package io.quarkus.bootstrap.logging;
import java.util.ArrayDeque;
+import java.util.ArrayList;
import java.util.Deque;
+import java.util.List;
import java.util.logging.ErrorManager;
import java.util.logging.Formatter;
import java.util.logging.Handler;
@@ -36,6 +38,7 @@
public class QuarkusDelayedHandler extends ExtHandler {
private final Deque<ExtLogRecord> logRecords = new ArrayDeque<>();
+ private final List<Runnable> logCloseTasks = new ArrayList<>();
private final int queueLimit;
private volatile boolean buildTimeLoggingActivated = false;
@@ -135,6 +138,10 @@ public Handler[] setHandlers(final Handler[] newHandlers) throws SecurityExcepti
return result;
}
+ public void addLoggingCloseTask(Runnable runnable) {
+ logCloseTasks.add(runnable);
+ }
+
public synchronized Handler[] setBuildTimeHandlers(final Handler[] newHandlers) throws SecurityException {
final Handler[] result = super.setHandlers(newHandlers);
buildTimeLoggingActivated = true;
@@ -177,6 +184,9 @@ public void removeHandler(final Handler handler) throws SecurityException {
@Override
public Handler[] clearHandlers() throws SecurityException {
activated = false;
+ for (Runnable i : logCloseTasks) {
+ i.run();
+ }
return super.clearHandlers();
}
| ['independent-projects/bootstrap/runner/src/main/java/io/quarkus/bootstrap/logging/QuarkusDelayedHandler.java', 'core/runtime/src/main/java/io/quarkus/runtime/logging/LoggingSetupRecorder.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 15,307,181 | 2,981,717 | 396,487 | 4,223 | 1,086 | 186 | 27 | 2 | 4,035 | 377 | 1,176 | 64 | 0 | 1 | 2021-03-17T06:42: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,814 | quarkusio/quarkus/15796/15195 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15195 | https://github.com/quarkusio/quarkus/pull/15796 | https://github.com/quarkusio/quarkus/pull/15796 | 1 | fixes | Subsequent @QuarkusTest's stuck when running with different @TestProfile for testing Lambdas | **Describe the bug**
The Gradle project consists of multiple `RequestHandler` which all need to be tested individually. We use one test profile for each handler test and one test class per handler.
The test profiles spawns test resources (WireMock, localstack) and sets the handler `quarkus.lambda.handler` accordingly with some other variables.
When running the tests we observe that the first `@QuarkusTest` class runs as expected but the subsequent class get stuck on the `LambdaClient.invoke(...)` call and blocks infinitely.
After some investigation it seems like the running `AbstractLambdaPollLoop` of the first QuarkusTest does not receive/check the interrupt of the Quarkus shutdown due to TestProfile switch.
Additionally the second QuarkusTest somehow does not wait until the old poll loop is destroyed and starts its poll loop and tests. The Lambda test call of the second QuarkusTest is queued into `LambdaClient.REQUEST_QUEUE`.
However, due to the fact that the first poll loop is still running, it requests another requestId in line `AbstractLambdaPollLoop.java:60` which is then dequeued of the REQUEST_QUEUE by `LambdaResourceManager`.
Since the loop has been stopped, it exits and does not propagate the response to the `CompletableFuture` inside `LambdaClient`. The test call however of the second QuarkusTest is still waiting for the response.
**Expected behavior**
All tests run with their assigned profile without being blocking.
**Actual behavior**
A subsequent QuarkusTest blocks due to a not returning call inside `AbstractLambdaPollLoop`.
**To Reproduce**
We were not able to reproduce it in a small example project. However we hope that contributors of the lambda extension
with more in-depth knowledge of the Quarkus testing lifecycle will understand the above. If not we can only provide an example
of the testing setup based on the aws-lambda archetype project which somehow does not run in the stated problem.
**Configuration**
```properties
quarkus.lambda.enable-polling-jvm-mode=true
```
**Screenshots**
(If applicable, add screenshots to help explain your problem.)
**Environment (please complete the following information):**
- Output of `java -version`:
openjdk 13.0.2 2020-01-14
OpenJDK Runtime Environment (build 13.0.2+8)
OpenJDK 64-Bit Server VM (build 13.0.2+8, mixed mode, sharing)
- Quarkus version or git rev:
1.11.3.Final
- Build tool (ie. output of `mvnw --version` or `gradlew --version`):
Gradle 6.5.1
**Additional context**
(Add any other context about the problem here.)
| ce244e1c13933a1862163fc70d0d5babcacdd41b | 7c6f45a4561e245638be998fe00b28d9b7f8f372 | https://github.com/quarkusio/quarkus/compare/ce244e1c13933a1862163fc70d0d5babcacdd41b...7c6f45a4561e245638be998fe00b28d9b7f8f372 | diff --git a/extensions/amazon-lambda/common-runtime/src/main/java/io/quarkus/amazon/lambda/runtime/AbstractLambdaPollLoop.java b/extensions/amazon-lambda/common-runtime/src/main/java/io/quarkus/amazon/lambda/runtime/AbstractLambdaPollLoop.java
index 720e8d4f452..0777ce720e8 100644
--- a/extensions/amazon-lambda/common-runtime/src/main/java/io/quarkus/amazon/lambda/runtime/AbstractLambdaPollLoop.java
+++ b/extensions/amazon-lambda/common-runtime/src/main/java/io/quarkus/amazon/lambda/runtime/AbstractLambdaPollLoop.java
@@ -36,7 +36,6 @@ public AbstractLambdaPollLoop(ObjectMapper objectMapper, ObjectReader cognitoIdR
public void startPollLoop(ShutdownContext context) {
final AtomicBoolean running = new AtomicBoolean(true);
-
final Thread pollingThread = new Thread(new Runnable() {
@SuppressWarnings("unchecked")
@Override
@@ -122,8 +121,11 @@ public void run() {
}
}
}, "Lambda Thread");
+ pollingThread.setDaemon(true);
context.addShutdownTask(() -> {
running.set(false);
+ //note that this does not seem to be 100% reliable in unblocking the thread
+ //which is why it is a daemon.
pollingThread.interrupt();
});
pollingThread.start();
diff --git a/test-framework/amazon-lambda/src/main/java/io/quarkus/amazon/lambda/test/LambdaResourceManager.java b/test-framework/amazon-lambda/src/main/java/io/quarkus/amazon/lambda/test/LambdaResourceManager.java
index 1ae03daefd9..73278d9e3bd 100644
--- a/test-framework/amazon-lambda/src/main/java/io/quarkus/amazon/lambda/test/LambdaResourceManager.java
+++ b/test-framework/amazon-lambda/src/main/java/io/quarkus/amazon/lambda/test/LambdaResourceManager.java
@@ -7,6 +7,7 @@
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -14,6 +15,7 @@
import io.quarkus.amazon.lambda.runtime.FunctionError;
import io.quarkus.test.common.QuarkusTestResourceLifecycleManager;
import io.undertow.Undertow;
+import io.undertow.httpcore.StatusCodes;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.RoutingHandler;
@@ -21,27 +23,38 @@
public class LambdaResourceManager implements QuarkusTestResourceLifecycleManager {
+ private volatile boolean started = false;
private volatile Undertow undertow;
+ private final AtomicInteger currentPollCount = new AtomicInteger();
public static final int PORT = Integer.getInteger("quarkus-internal.aws-lambda.test-port", 5387);
@Override
public Map<String, String> start() {
-
+ started = true;
RoutingHandler routingHandler = new RoutingHandler(true);
routingHandler.add("GET", AmazonLambdaApi.API_PATH_INVOCATION_NEXT, new HttpHandler() {
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
- LambdaStartedNotifier.started = true;
- Map.Entry<String, String> req = null;
- while (req == null) {
- req = LambdaClient.REQUEST_QUEUE.poll(100, TimeUnit.MILLISECONDS);
- if (undertow == null || undertow.getWorker() == null || undertow.getWorker().isShutdown()) {
- return;
+ currentPollCount.incrementAndGet();
+ try {
+ LambdaStartedNotifier.started = true;
+ Map.Entry<String, String> req = null;
+ while (req == null) {
+ req = LambdaClient.REQUEST_QUEUE.poll(100, TimeUnit.MILLISECONDS);
+ if (!started || undertow == null || undertow.getWorker() == null || undertow.getWorker().isShutdown()) {
+ exchange.setStatusCode(StatusCodes.SERVICE_UNAVAILABLE);
+ exchange.setPersistent(false);
+ exchange.getOutputStream().close();
+ return;
+ }
}
+ exchange.addResponseHeader(AmazonLambdaApi.LAMBDA_RUNTIME_AWS_REQUEST_ID, req.getKey());
+ exchange.getOutputStream().write(req.getValue().getBytes(StandardCharsets.UTF_8));
+ exchange.getOutputStream().close();
+ } finally {
+ currentPollCount.decrementAndGet();
}
- exchange.addResponseHeader(AmazonLambdaApi.LAMBDA_RUNTIME_AWS_REQUEST_ID, req.getKey());
- exchange.writeAsync(req.getValue());
}
});
routingHandler.add("POST", AmazonLambdaApi.API_PATH_INVOCATION + "{req}" + AmazonLambdaApi.API_PATH_RESPONSE,
@@ -117,6 +130,16 @@ public void handleRequest(HttpServerExchange exchange) throws Exception {
@Override
public void stop() {
+ started = false;
+ while (currentPollCount.get() > 0) {
+ try {
+ //wait for all the responses to be sent
+ //before we shutdown
+ Thread.sleep(10);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ }
if (undertow == null)
return;
undertow.stop(); | ['extensions/amazon-lambda/common-runtime/src/main/java/io/quarkus/amazon/lambda/runtime/AbstractLambdaPollLoop.java', 'test-framework/amazon-lambda/src/main/java/io/quarkus/amazon/lambda/test/LambdaResourceManager.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 15,307,181 | 2,981,717 | 396,487 | 4,223 | 174 | 38 | 4 | 1 | 2,598 | 360 | 585 | 49 | 0 | 1 | 2021-03-17T04:03:48 | 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,815 | quarkusio/quarkus/15795/15204 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15204 | https://github.com/quarkusio/quarkus/pull/15795 | https://github.com/quarkusio/quarkus/pull/15795 | 1 | fixes | NoClassDefFoundError for multi-module dependency in Vert.x reactive routes when using Maven quarkusDev | **Describe the bug**
A multi-module maven project contains two submodules _mod1_ and _mod2_, where _mod2_ depends on _mod1_.
When running _mod2_ in dev mode, `NoClassDefFoundError` occurs for a route class from _mod1_.
The error does not occur when the application is built with `mvn package` and run with `java -jar mod2/target/mod2-0.0.1-SNAPSHOT-runner.jar`.
**Expected behavior**
The application should work no matter if it is run in dev mode or not.
**Actual behavior**
If the application is started with `mvn compile quarkus:dev -pl mod2`, an internal server error is returned when a request is made to a route in _mod1_. Both the log and the HTTP response contain a stacktrace:
```
2021-02-20 02:39:39,613 ERROR [io.qua.ver.htt.run.QuarkusErrorHandler] (vert.x-eventloop-thread-3) HTTP Request to /mod1/ failed, error id: d2ed3e7e-337e-4fcf-9c6e-eddc7944cecc-1: java.lang.NoClassDefFoundError: sg/wjtan/mod1/IndexPage
at sg.wjtan.mod1.IndexPage_RouteHandler_index_279c3f7d45b3461bf7246354cb951cebf8120d77.invoke(IndexPage_RouteHandler_index_279c3f7d45b3461bf7246354cb951cebf8120d77.zig:104)
at io.quarkus.vertx.web.runtime.RouteHandler.handle(RouteHandler.java:97)
at io.quarkus.vertx.web.runtime.RouteHandler.handle(RouteHandler.java:22)
at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1038)
at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:101)
at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:132)
at io.quarkus.vertx.http.runtime.VertxHttpRecorder$17.handle(VertxHttpRecorder.java:1121)
at io.quarkus.vertx.http.runtime.VertxHttpRecorder$17.handle(VertxHttpRecorder.java:1092)
at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1038)
at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:137)
at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:132)
at io.quarkus.vertx.http.runtime.VertxHttpRecorder$4.handle(VertxHttpRecorder.java:333)
at io.quarkus.vertx.http.runtime.VertxHttpRecorder$4.handle(VertxHttpRecorder.java:311)
at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1038)
at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:137)
at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:132)
at io.quarkus.vertx.http.runtime.devmode.VertxHttpHotReplacementSetup$3.handle(VertxHttpHotReplacementSetup.java:86)
at io.quarkus.vertx.http.runtime.devmode.VertxHttpHotReplacementSetup$3.handle(VertxHttpHotReplacementSetup.java:75)
at io.vertx.core.impl.ContextImpl.lambda$null$0(ContextImpl.java:327)
at io.vertx.core.impl.ContextImpl.executeTask(ContextImpl.java:366)
at io.vertx.core.impl.EventLoopContext.lambda$executeAsync$0(EventLoopContext.java:38)
at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:500)
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
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:834)
Caused by: java.lang.ClassNotFoundException: sg.wjtan.mod1.IndexPage
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:428)
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:378)
... 28 more
```
**To Reproduce**
Steps to reproduce the behavior:
1. Fetch to sample project from https://github.com/wjtan/quarkus-multi-web
2. Compile the project `mvn install`
2. Start the application using `mvn compile quarkus:dev -pl mod2`
3. Open the URL http://localhost:8080/mod1
**Environment (please complete the following information):**
- Output of `uname -a` or `ver`: Windows 10 20H2
- Output of `java -version`: java 11.0.10 2021-01-19 LTS
- GraalVM version (if different from Java): n/a
- Quarkus version or git rev: 1.12.0.Final
- Build tool (ie. output of `mvnw --version` or `gradlew --version`): Maven 3.6.3
| ce244e1c13933a1862163fc70d0d5babcacdd41b | ae14fff9e70d6a77e532e40481cbbe843d2b92b8 | https://github.com/quarkusio/quarkus/compare/ce244e1c13933a1862163fc70d0d5babcacdd41b...ae14fff9e70d6a77e532e40481cbbe843d2b92b8 | diff --git a/extensions/vertx-web/deployment/src/main/java/io/quarkus/vertx/web/deployment/VertxWebProcessor.java b/extensions/vertx-web/deployment/src/main/java/io/quarkus/vertx/web/deployment/VertxWebProcessor.java
index 30889c74c92..add7a48d162 100644
--- a/extensions/vertx-web/deployment/src/main/java/io/quarkus/vertx/web/deployment/VertxWebProcessor.java
+++ b/extensions/vertx-web/deployment/src/main/java/io/quarkus/vertx/web/deployment/VertxWebProcessor.java
@@ -63,7 +63,7 @@
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.ExecutionTime;
import io.quarkus.deployment.annotations.Record;
-import io.quarkus.deployment.builditem.ApplicationIndexBuildItem;
+import io.quarkus.deployment.builditem.ApplicationClassPredicateBuildItem;
import io.quarkus.deployment.builditem.FeatureBuildItem;
import io.quarkus.deployment.builditem.GeneratedClassBuildItem;
import io.quarkus.deployment.builditem.LaunchModeBuildItem;
@@ -231,14 +231,19 @@ void addAdditionalRoutes(
BuildProducer<RouteDescriptionBuildItem> descriptions,
Capabilities capabilities,
Optional<BeanValidationAnnotationsBuildItem> beanValidationAnnotations,
- ApplicationIndexBuildItem applicationIndex) {
+ List<ApplicationClassPredicateBuildItem> predicates) {
Predicate<String> appClassPredicate = new Predicate<String>() {
@Override
public boolean test(String name) {
int idx = name.lastIndexOf(HANDLER_SUFFIX);
String className = idx != -1 ? name.substring(0, idx) : name;
- return applicationIndex.getIndex().getClassByName(DotName.createSimple(className.replace("/", "."))) != null;
+ for (ApplicationClassPredicateBuildItem i : predicates) {
+ if (i.test(className)) {
+ return true;
+ }
+ }
+ return false;
}
};
ClassOutput classOutput = new GeneratedClassGizmoAdaptor(generatedClass, appClassPredicate); | ['extensions/vertx-web/deployment/src/main/java/io/quarkus/vertx/web/deployment/VertxWebProcessor.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 15,307,181 | 2,981,717 | 396,487 | 4,223 | 628 | 103 | 11 | 1 | 4,849 | 285 | 1,253 | 65 | 2 | 1 | 2021-03-17T02:34: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,818 | quarkusio/quarkus/15748/15657 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15657 | https://github.com/quarkusio/quarkus/pull/15748 | https://github.com/quarkusio/quarkus/pull/15748 | 1 | fixes | Resteasy Reactive - NoClassDefFoundError: io/quarkus/generated/java/lang/Long$quarkusrestparamConverter$ | **Describe the bug**
I have a class "ListFilterImportData", which is used in all projects as BeanParam, in a common artefact. it looks something like this (getter/setter omitted for brevity):
```
@QueryParam("language")
String language;
@QueryParam("page")
@DefaultValue("1")
Integer page;
@QueryParam("sortAscending")
@DefaultValue("false")
Boolean sortAscending;
@QueryParam("anotherValue")
@DefaultValue("1")
Long anotherValue;
@QueryParam("anotherValue2")
@DefaultValue("1")
Short anotherValue2;
```
I now want to use this common artefact on a resource method like this:
```
@GET
public String hello(@BeanParam ListFilterImportData filterImportData)
```
This works without Problems in Resteasy Classic.
In Resteasy Reactive however, the ParamConverter for Long can not be found in dev mode, as indicated by the exception below. If I add this missing ParamConverter, another exception is throw but this time for Integer missing its ParamConverter.
**Expected behavior**
Classes defined in other artefacts should just work as BeanParams.
**Actual behavior**
I get this exception, indicating a missing ParamConverter for Long. I also get the same exception for String and Boolean.
```
Listening for transport dt_socket at address: 5005
2021-03-12 08:38:22,539 INFO [org.jbo.threads] (main) JBoss Threads version 3.2.0.Final
2021-03-12 08:38:24,439 INFO [io.qua.dep.dev.IsolatedDevModeMain] (main) Attempting to start hot replacement endpoint to recover from previous Quarkus startup failure
2021-03-12 08:38:24,440 ERROR [io.qua.run.boo.StartupActionImpl] (Quarkus Main Thread) Error running Quarkus: java.lang.reflect.InvocationTargetException
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$3.run(StartupActionImpl.java:134)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.ExceptionInInitializerError
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
at java.base/java.lang.Class.newInstance(Class.java:584)
at io.quarkus.runtime.Quarkus.run(Quarkus.java:65)
at io.quarkus.runtime.Quarkus.run(Quarkus.java:42)
at io.quarkus.runtime.Quarkus.run(Quarkus.java:119)
at io.quarkus.runner.GeneratedMain.main(GeneratedMain.zig:29)
... 6 more
Caused by: java.lang.RuntimeException: Failed to start quarkus
at io.quarkus.runner.ApplicationImpl.<clinit>(ApplicationImpl.zig:255)
... 15 more
Caused by: java.lang.NoClassDefFoundError: io/quarkus/generated/java/lang/Long$quarkusrestparamConverter$
at org.acme.common.ListFilterImportData.__quarkus_init_converter__anotherValue(ListFilterImportData.java)
at io.quarkus.rest.runtime.__QuarkusInit.init(__QuarkusInit.zig:31)
at io.quarkus.resteasy.reactive.server.runtime.ResteasyReactiveRecorder.createDeployment(ResteasyReactiveRecorder.java:113)
at io.quarkus.deployment.steps.ResteasyReactiveProcessor$setupEndpoints-1591811826.deploy_1(ResteasyReactiveProcessor$setupEndpoints-1591811826.zig:3522)
at io.quarkus.deployment.steps.ResteasyReactiveProcessor$setupEndpoints-1591811826.deploy(ResteasyReactiveProcessor$setupEndpoints-1591811826.zig:45)
at io.quarkus.runner.ApplicationImpl.<clinit>(ApplicationImpl.zig:224)
... 15 more
Caused by: java.lang.ClassNotFoundException: io.quarkus.generated.java.lang.Long$quarkusrestparamConverter$
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:428)
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:378)
... 21 more
```
**To Reproduce**
Steps to reproduce the behavior:
1. Download the reproducer:
[rr-missing-paramconverter.zip](https://github.com/quarkusio/quarkus/files/6128351/rr-missing-paramconverter.zip)
2. cd common, mvn clean install
3. cd ../web, mvn quarkus:dev
4. The exception from above happens
**Environment (please complete the following information):**
- Output of `uname -a` or `ver`:
MSYS_NT-10.0 NANB7NLNVP2 2.10.0(0.325/5/3) 2018-06-13 23:34 x86_64 Msys
- Quarkus version or git rev:
1.12.2.Final
- Build tool (ie. output of `mvnw --version` or `gradlew --version`):
Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
Maven home: C:\\eclipse\\tools\\apache-maven\\bin\\..
Java version: 11.0.7, vendor: Azul Systems, Inc., runtime: C:\\eclipse\\tools\\zulu11.39.15-ca-jdk11.0.7-win_x64
Default locale: de_DE, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"
| 40b3c2bc0536d1669268a7804adcd0bc5d7462d7 | 4ef6058a5f876208808c013818d5b66565812d82 | https://github.com/quarkusio/quarkus/compare/40b3c2bc0536d1669268a7804adcd0bc5d7462d7...4ef6058a5f876208808c013818d5b66565812d82 | diff --git a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/main/java/io/quarkus/resteasy/reactive/server/deployment/QuarkusServerEndpointIndexer.java b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/main/java/io/quarkus/resteasy/reactive/server/deployment/QuarkusServerEndpointIndexer.java
index 2e02d9759b5..72479621899 100644
--- a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/main/java/io/quarkus/resteasy/reactive/server/deployment/QuarkusServerEndpointIndexer.java
+++ b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/main/java/io/quarkus/resteasy/reactive/server/deployment/QuarkusServerEndpointIndexer.java
@@ -10,6 +10,7 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.function.Predicate;
import javax.ws.rs.core.MediaType;
@@ -53,6 +54,7 @@
private final DefaultProducesHandler defaultProducesHandler;
private final Map<String, String> multipartGeneratedPopulators = new HashMap<>();
+ private final Predicate<String> applicationClassPredicate;
private static final Set<DotName> CONTEXT_TYPES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
DotName.createSimple(HttpServerRequest.class.getName()),
@@ -66,6 +68,7 @@
this.bytecodeTransformerBuildProducer = builder.bytecodeTransformerBuildProducer;
this.reflectiveClassProducer = builder.reflectiveClassProducer;
this.defaultProducesHandler = builder.defaultProducesHandler;
+ this.applicationClassPredicate = builder.applicationClassPredicate;
}
protected boolean isContextType(ClassType klass) {
@@ -166,7 +169,9 @@ protected ParameterConverterSupplier extractConverter(String elementType, IndexV
}
baseName = effectivePrefix + "$quarkusrestparamConverter$";
try (ClassCreator classCreator = new ClassCreator(
- new GeneratedClassGizmoAdaptor(generatedClassBuildItemBuildProducer, true), baseName, null,
+ new GeneratedClassGizmoAdaptor(generatedClassBuildItemBuildProducer,
+ applicationClassPredicate.test(elementType)),
+ baseName, null,
Object.class.getName(), ParameterConverter.class.getName())) {
MethodCreator mc = classCreator.getMethodCreator("convert", Object.class, Object.class);
if (stringCtor != null) {
@@ -245,6 +250,7 @@ public static final class Builder extends AbstractBuilder<Builder> {
private BuildProducer<ReflectiveClassBuildItem> reflectiveClassProducer;
private MethodCreator initConverters;
private DefaultProducesHandler defaultProducesHandler = DefaultProducesHandler.Noop.INSTANCE;
+ public Predicate<String> applicationClassPredicate;
@Override
public QuarkusServerEndpointIndexer build() {
@@ -273,6 +279,11 @@ public Builder setReflectiveClassProducer(
return this;
}
+ public Builder setApplicationClassPredicate(Predicate<String> applicationClassPredicate) {
+ this.applicationClassPredicate = applicationClassPredicate;
+ return this;
+ }
+
public Builder setInitConverters(MethodCreator initConverters) {
this.initConverters = initConverters;
return this;
diff --git a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/main/java/io/quarkus/resteasy/reactive/server/deployment/ResteasyReactiveProcessor.java b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/main/java/io/quarkus/resteasy/reactive/server/deployment/ResteasyReactiveProcessor.java
index 307adbaee1a..738d8c310fd 100644
--- a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/main/java/io/quarkus/resteasy/reactive/server/deployment/ResteasyReactiveProcessor.java
+++ b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/main/java/io/quarkus/resteasy/reactive/server/deployment/ResteasyReactiveProcessor.java
@@ -77,6 +77,7 @@
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.annotations.ExecutionTime;
import io.quarkus.deployment.annotations.Record;
+import io.quarkus.deployment.builditem.ApplicationClassPredicateBuildItem;
import io.quarkus.deployment.builditem.BytecodeTransformerBuildItem;
import io.quarkus.deployment.builditem.CapabilityBuildItem;
import io.quarkus.deployment.builditem.FeatureBuildItem;
@@ -244,6 +245,7 @@ public void setupEndpoints(Capabilities capabilities, BeanArchiveIndexBuildItem
ExceptionMappersBuildItem exceptionMappersBuildItem,
ParamConverterProvidersBuildItem paramConverterProvidersBuildItem,
ContextResolversBuildItem contextResolversBuildItem,
+ List<ApplicationClassPredicateBuildItem> applicationClassPredicateBuildItems,
List<MethodScannerBuildItem> methodScanners, ResteasyReactiveServerConfig serverConfig)
throws NoSuchMethodException {
@@ -367,7 +369,15 @@ private boolean hasAnnotation(MethodInfo method, short paramPosition, DotName an
return false;
}
})
- .setInitConverters(initConverters);
+ .setInitConverters(initConverters)
+ .setApplicationClassPredicate(s -> {
+ for (ApplicationClassPredicateBuildItem i : applicationClassPredicateBuildItems) {
+ if (i.test(s)) {
+ return true;
+ }
+ }
+ return false;
+ });
if (!serverDefaultProducesHandlers.isEmpty()) {
List<DefaultProducesHandler> handlers = new ArrayList<>(serverDefaultProducesHandlers.size()); | ['extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/main/java/io/quarkus/resteasy/reactive/server/deployment/QuarkusServerEndpointIndexer.java', 'extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/main/java/io/quarkus/resteasy/reactive/server/deployment/ResteasyReactiveProcessor.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 15,282,422 | 2,976,981 | 395,852 | 4,216 | 1,425 | 221 | 25 | 2 | 5,721 | 384 | 1,457 | 104 | 1 | 3 | 2021-03-16T02:21:35 | 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,819 | quarkusio/quarkus/15730/15735 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15735 | https://github.com/quarkusio/quarkus/pull/15730 | https://github.com/quarkusio/quarkus/pull/15730 | 1 | fixes | QuarkusSecurityIdentity.builder(identity) loses isAnonymous flag | ## Describe the bug
If QuarkusSecurityIdentity.builder(identity) is called with an identity that is anonymous then the identity returned from the builder returns always `false` on `isAnonymous()`
This typcially happens in a `SecurityIdentityAugmentor` that doesn't check the identity for anonymous.
### Expected behavior
If QuarkusSecurityIdentity.builder(identity) is called with an anonymous identity (`isAnonymous()` returns true) the produced identity must be an anonymous identity too, if not specified otherwise. Or if that's not supported builder(identity) should throw an exception if the specified identity is anonymous.
Since `SecurityIdentity` is an interface, QuarkusSecurityIdentity.builder should not also work with other implementations of the interface.
### Actual behavior
(Describe the actual behavior clearly and concisely.)
## To Reproduce
See above
See also #15730 | a5657b67fb68a0234dcfa3533f70dc14f3810fcf | fdb63d34fbb3ee181473426d2f978ef571f5cc80 | https://github.com/quarkusio/quarkus/compare/a5657b67fb68a0234dcfa3533f70dc14f3810fcf...fdb63d34fbb3ee181473426d2f978ef571f5cc80 | diff --git a/extensions/security/runtime/src/main/java/io/quarkus/security/runtime/QuarkusSecurityIdentity.java b/extensions/security/runtime/src/main/java/io/quarkus/security/runtime/QuarkusSecurityIdentity.java
index 54638f3d978..50bd92790f5 100644
--- a/extensions/security/runtime/src/main/java/io/quarkus/security/runtime/QuarkusSecurityIdentity.java
+++ b/extensions/security/runtime/src/main/java/io/quarkus/security/runtime/QuarkusSecurityIdentity.java
@@ -22,6 +22,7 @@ public class QuarkusSecurityIdentity implements SecurityIdentity {
private final Set<Credential> credentials;
private final Map<String, Object> attributes;
private final List<Function<Permission, Uni<Boolean>>> permissionCheckers;
+ private final boolean anonymous;
private QuarkusSecurityIdentity(Builder builder) {
this.principal = builder.principal;
@@ -29,6 +30,7 @@ private QuarkusSecurityIdentity(Builder builder) {
this.credentials = Collections.unmodifiableSet(builder.credentials);
this.attributes = Collections.unmodifiableMap(builder.attributes);
this.permissionCheckers = Collections.unmodifiableList(builder.permissionCheckers);
+ this.anonymous = builder.anonymous;
}
@Override
@@ -38,7 +40,7 @@ public Principal getPrincipal() {
@Override
public boolean isAnonymous() {
- return false;
+ return anonymous;
}
@Override
@@ -121,11 +123,13 @@ public static Builder builder() {
}
public static Builder builder(SecurityIdentity identity) {
- return new Builder()
+ Builder builder = new Builder()
.addAttributes(identity.getAttributes())
.addCredentials(identity.getCredentials())
.addRoles(identity.getRoles())
- .setPrincipal(identity.getPrincipal());
+ .setPrincipal(identity.getPrincipal())
+ .setAnonymous(identity.isAnonymous());
+ return builder;
}
public static class Builder {
@@ -135,6 +139,7 @@ public static class Builder {
Set<Credential> credentials = new HashSet<>();
Map<String, Object> attributes = new HashMap<>();
List<Function<Permission, Uni<Boolean>>> permissionCheckers = new ArrayList<>();
+ private boolean anonymous;
boolean built = false;
public Builder setPrincipal(Principal principal) {
@@ -211,7 +216,25 @@ public Builder addPermissionChecker(Function<Permission, Uni<Boolean>> function)
return this;
}
+ /**
+ * Sets an anonymous identity status.
+ *
+ * @param anonymous the anonymous status
+ * @return This builder
+ */
+ public Builder setAnonymous(boolean anonymous) {
+ if (built) {
+ throw new IllegalStateException();
+ }
+ this.anonymous = anonymous;
+ return this;
+ }
+
public QuarkusSecurityIdentity build() {
+ if (principal == null && !anonymous) {
+ throw new IllegalStateException("Principal is null but anonymous status is false");
+ }
+
built = true;
return new QuarkusSecurityIdentity(this);
}
diff --git a/extensions/security/runtime/src/test/java/io/quarkus/security/runtime/QuarkusSecurityIdentityTest.java b/extensions/security/runtime/src/test/java/io/quarkus/security/runtime/QuarkusSecurityIdentityTest.java
index c1704c16b5e..7d9dc11e67b 100644
--- a/extensions/security/runtime/src/test/java/io/quarkus/security/runtime/QuarkusSecurityIdentityTest.java
+++ b/extensions/security/runtime/src/test/java/io/quarkus/security/runtime/QuarkusSecurityIdentityTest.java
@@ -1,11 +1,23 @@
package io.quarkus.security.runtime;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.security.Permission;
+import java.security.Principal;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
import org.junit.jupiter.api.Test;
+import io.quarkus.security.credential.Credential;
import io.quarkus.security.credential.PasswordCredential;
import io.quarkus.security.identity.SecurityIdentity;
+import io.smallrye.mutiny.Uni;
public class QuarkusSecurityIdentityTest {
@@ -18,11 +30,132 @@ public void testCopyIdentity() throws Exception {
.addAttribute("key", "value")
.build();
+ assertFalse(identity1.isAnonymous());
+
SecurityIdentity identity2 = QuarkusSecurityIdentity.builder(identity1).build();
+ assertFalse(identity1.isAnonymous());
assertEquals(identity1.getAttributes(), identity2.getAttributes());
assertEquals(identity1.getPrincipal(), identity2.getPrincipal());
assertEquals(identity1.getCredentials(), identity2.getCredentials());
assertEquals(identity1.getRoles(), identity2.getRoles());
}
+
+ @Test
+ public void testAnonymousPrincipalWithCustomIdentity() throws Exception {
+ SecurityIdentity identity1 = new TestSecurityIdentityAnonymousPrincipal();
+ assertTrue(identity1.isAnonymous());
+ assertEquals("anonymous-principal", identity1.getPrincipal().getName());
+
+ SecurityIdentity identity2 = QuarkusSecurityIdentity.builder(identity1).build();
+ assertTrue(identity2.isAnonymous());
+ assertEquals("anonymous-principal", identity2.getPrincipal().getName());
+ }
+
+ @Test
+ public void testPrincipalNullAnonymousFalseWithBuilder() throws Exception {
+ QuarkusSecurityIdentity.Builder builder = QuarkusSecurityIdentity.builder()
+ .addRole("admin")
+ .addCredential(new PasswordCredential("password".toCharArray()))
+ .addAttribute("key", "value");
+ ;
+
+ assertThrows(IllegalStateException.class, () -> builder.build());
+ }
+
+ @Test
+ public void testPrincipalNullAnonymousFalseWithCustomIdentity() throws Exception {
+ SecurityIdentity identity1 = new TestSecurityIdentityPrincipalNullAnonymousFalse();
+ assertFalse(identity1.isAnonymous());
+ assertNull(identity1.getPrincipal());
+
+ assertThrows(IllegalStateException.class, () -> QuarkusSecurityIdentity.builder(identity1).build());
+ }
+
+ @Test
+ public void testPrincipalNullAnonymousFalseWithCustomIdentityFixed() throws Exception {
+ SecurityIdentity identity1 = new TestSecurityIdentityPrincipalNullAnonymousFalse();
+ assertFalse(identity1.isAnonymous());
+ assertNull(identity1.getPrincipal());
+
+ SecurityIdentity identity2 = QuarkusSecurityIdentity.builder(identity1).setAnonymous(true).build();
+ assertTrue(identity2.isAnonymous());
+ assertNull(identity2.getPrincipal());
+ }
+
+ static class TestSecurityIdentityAnonymousPrincipal extends AbstractTestSecurityIdentity {
+
+ @Override
+ public Principal getPrincipal() {
+ return new Principal() {
+ @Override
+ public String getName() {
+ return "anonymous-principal";
+ }
+ };
+ }
+
+ @Override
+ public boolean isAnonymous() {
+ return true;
+ }
+
+ }
+
+ static class TestSecurityIdentityPrincipalNullAnonymousFalse extends AbstractTestSecurityIdentity {
+
+ @Override
+ public Principal getPrincipal() {
+ return null;
+ }
+
+ @Override
+ public boolean isAnonymous() {
+ return false;
+ }
+
+ }
+
+ static abstract class AbstractTestSecurityIdentity implements SecurityIdentity {
+
+ @Override
+ public Set<String> getRoles() {
+ return Collections.emptySet();
+ }
+
+ @Override
+ public boolean hasRole(String role) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public <T extends Credential> T getCredential(Class<T> credentialType) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Set<Credential> getCredentials() {
+ return Collections.emptySet();
+ }
+
+ @Override
+ public <T> T getAttribute(String name) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public Map<String, Object> getAttributes() {
+ return Collections.emptyMap();
+ }
+
+ @Override
+ public Uni<Boolean> checkPermission(Permission permission) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ }
} | ['extensions/security/runtime/src/main/java/io/quarkus/security/runtime/QuarkusSecurityIdentity.java', 'extensions/security/runtime/src/test/java/io/quarkus/security/runtime/QuarkusSecurityIdentityTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 15,404,588 | 3,000,022 | 398,983 | 4,248 | 1,003 | 162 | 29 | 1 | 908 | 116 | 178 | 17 | 0 | 0 | 2021-03-15T13:17:42 | 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,821 | quarkusio/quarkus/15645/15492 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15492 | https://github.com/quarkusio/quarkus/pull/15645 | https://github.com/quarkusio/quarkus/pull/15645 | 1 | fixes | Validation for REST endpoints does not return messages about the constraints violated | **Describe the bug**
After the changes in https://github.com/quarkusio/quarkus/pull/15447, now when using REST Panache or Spring Data REST quarkus extensions, we got 400 when there are constraint violations.
The problem now is that the response does not return the constraints that have been violated.
**Expected behavior**
After a REST violation, It's expected to receive something like:
```json
{
"classViolations": [],
"parameterViolations": [
{
"constraintType": "PARAMETER",
"message": "Title may not be blank",
"path": "addBook.book.title",
"value": ""
}
],
"propertyViolations": [],
"returnValueViolations": []
}
```
* If we're using JSON... *
**Actual behavior**
No message is returned.
**To Reproduce**
1- git clone https://github.com/Sgitario/beefy-scenarios
2- git checkout reproducer_15409
3- cd beefy-scenarios/602-spring-data-rest
4- mvn clean verify
There are some tests failing due to this issue.
**Environment (please complete the following information):**
- Quarkus version or git rev: 999-SNAPSHOT
| e86d7112630a6f630423f90d55eb134a7e0b10b9 | da3a42865d767d1800a91e72b2d462cda012d72d | https://github.com/quarkusio/quarkus/compare/e86d7112630a6f630423f90d55eb134a7e0b10b9...da3a42865d767d1800a91e72b2d462cda012d72d | diff --git a/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/JaxRsResourceImplementor.java b/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/JaxRsResourceImplementor.java
index 98d8c347b25..f5c6b67156f 100644
--- a/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/JaxRsResourceImplementor.java
+++ b/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/JaxRsResourceImplementor.java
@@ -33,16 +33,20 @@ class JaxRsResourceImplementor {
private static final Logger LOGGER = Logger.getLogger(JaxRsResourceImplementor.class);
- private final List<MethodImplementor> METHOD_IMPLEMENTORS = Arrays.asList(
- new GetMethodImplementor(),
- new GetHalMethodImplementor(),
- new ListMethodImplementor(),
- new ListHalMethodImplementor(),
- new AddMethodImplementor(),
- new AddHalMethodImplementor(),
- new UpdateMethodImplementor(),
- new UpdateHalMethodImplementor(),
- new DeleteMethodImplementor());
+ private final List<MethodImplementor> methodImplementors;
+
+ JaxRsResourceImplementor(boolean withValidation) {
+ this.methodImplementors = Arrays.asList(
+ new GetMethodImplementor(),
+ new GetHalMethodImplementor(),
+ new ListMethodImplementor(),
+ new ListHalMethodImplementor(),
+ new AddMethodImplementor(withValidation),
+ new AddHalMethodImplementor(withValidation),
+ new UpdateMethodImplementor(withValidation),
+ new UpdateHalMethodImplementor(withValidation),
+ new DeleteMethodImplementor());
+ }
/**
* Implement a JAX-RS resource with a following structure.
@@ -81,13 +85,14 @@ private void implementClassAnnotations(ClassCreator classCreator, ResourceProper
private FieldDescriptor implementResourceField(ClassCreator classCreator, ResourceMetadata resourceMetadata) {
FieldCreator resourceFieldCreator = classCreator.getFieldCreator("resource", resourceMetadata.getResourceClass());
- resourceFieldCreator.setModifiers(resourceFieldCreator.getModifiers() & ~Modifier.PRIVATE).addAnnotation(Inject.class);
+ resourceFieldCreator.setModifiers(resourceFieldCreator.getModifiers() & ~Modifier.PRIVATE)
+ .addAnnotation(Inject.class);
return resourceFieldCreator.getFieldDescriptor();
}
private void implementMethods(ClassCreator classCreator, ResourceMetadata resourceMetadata,
ResourceProperties resourceProperties, FieldDescriptor resourceField) {
- for (MethodImplementor methodImplementor : METHOD_IMPLEMENTORS) {
+ for (MethodImplementor methodImplementor : methodImplementors) {
methodImplementor.implement(classCreator, resourceMetadata, resourceProperties, resourceField);
}
}
diff --git a/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/RestDataProcessor.java b/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/RestDataProcessor.java
index 082c361d05b..0e3574c7b80 100644
--- a/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/RestDataProcessor.java
+++ b/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/RestDataProcessor.java
@@ -7,6 +7,8 @@
import io.quarkus.arc.deployment.GeneratedBeanBuildItem;
import io.quarkus.arc.deployment.GeneratedBeanGizmoAdaptor;
+import io.quarkus.deployment.Capabilities;
+import io.quarkus.deployment.Capability;
import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.CombinedIndexBuildItem;
@@ -31,10 +33,10 @@ public class RestDataProcessor {
@BuildStep
void implementResources(CombinedIndexBuildItem index, List<RestDataResourceBuildItem> resourceBuildItems,
- List<ResourcePropertiesBuildItem> resourcePropertiesBuildItems,
+ List<ResourcePropertiesBuildItem> resourcePropertiesBuildItems, Capabilities capabilities,
BuildProducer<GeneratedBeanBuildItem> implementationsProducer) {
ClassOutput classOutput = new GeneratedBeanGizmoAdaptor(implementationsProducer);
- JaxRsResourceImplementor jaxRsResourceImplementor = new JaxRsResourceImplementor();
+ JaxRsResourceImplementor jaxRsResourceImplementor = new JaxRsResourceImplementor(hasValidatorCapability(capabilities));
ResourcePropertiesProvider resourcePropertiesProvider = new ResourcePropertiesProvider(index.getIndex());
for (RestDataResourceBuildItem resourceBuildItem : resourceBuildItems) {
@@ -80,4 +82,8 @@ private ResourceProperties getResourceProperties(ResourcePropertiesProvider reso
}
return resourcePropertiesProvider.getForInterface(resourceMetadata.getResourceInterface());
}
+
+ private boolean hasValidatorCapability(Capabilities capabilities) {
+ return capabilities.isPresent(Capability.HIBERNATE_VALIDATOR);
+ }
}
diff --git a/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/AddMethodImplementor.java b/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/AddMethodImplementor.java
index e41d2e373f9..28b7be0ee95 100644
--- a/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/AddMethodImplementor.java
+++ b/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/AddMethodImplementor.java
@@ -2,6 +2,7 @@
import static io.quarkus.gizmo.MethodDescriptor.ofMethod;
+import javax.validation.Valid;
import javax.ws.rs.core.Response;
import io.quarkus.gizmo.ClassCreator;
@@ -22,6 +23,12 @@ public final class AddMethodImplementor extends StandardMethodImplementor {
private static final String REL = "add";
+ private final boolean withValidation;
+
+ public AddMethodImplementor(boolean withValidation) {
+ this.withValidation = withValidation;
+ }
+
/**
* Generate JAX-RS POST method that exposes {@link RestDataResource#add(Object)}.
* Generated code looks more or less like this:
@@ -67,6 +74,10 @@ protected void implementInternal(ClassCreator classCreator, ResourceMetadata res
addConsumesAnnotation(methodCreator, APPLICATION_JSON);
addProducesAnnotation(methodCreator, APPLICATION_JSON);
addLinksAnnotation(methodCreator, resourceMetadata.getEntityType(), REL);
+ // Add parameter annotations
+ if (withValidation) {
+ methodCreator.getParameterAnnotations(0).addAnnotation(Valid.class);
+ }
ResultHandle resource = methodCreator.readInstanceField(resourceField, methodCreator.getThis());
ResultHandle entityToSave = methodCreator.getMethodParam(0);
diff --git a/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/UpdateMethodImplementor.java b/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/UpdateMethodImplementor.java
index d5ffb4cd0c8..21335d65f46 100644
--- a/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/UpdateMethodImplementor.java
+++ b/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/UpdateMethodImplementor.java
@@ -2,6 +2,7 @@
import static io.quarkus.gizmo.MethodDescriptor.ofMethod;
+import javax.validation.Valid;
import javax.ws.rs.core.Response;
import io.quarkus.gizmo.BranchResult;
@@ -26,6 +27,12 @@ public final class UpdateMethodImplementor extends StandardMethodImplementor {
private static final String REL = "update";
+ private final boolean withValidation;
+
+ public UpdateMethodImplementor(boolean withValidation) {
+ this.withValidation = withValidation;
+ }
+
/**
* Generate JAX-RS UPDATE method that exposes {@link RestDataResource#update(Object, Object)}.
* Expose {@link RestDataResource#update(Object, Object)} via JAX-RS method.
@@ -79,6 +86,10 @@ protected void implementInternal(ClassCreator classCreator, ResourceMetadata res
addConsumesAnnotation(methodCreator, APPLICATION_JSON);
addProducesAnnotation(methodCreator, APPLICATION_JSON);
addLinksAnnotation(methodCreator, resourceMetadata.getEntityType(), REL);
+ // Add parameter annotations
+ if (withValidation) {
+ methodCreator.getParameterAnnotations(1).addAnnotation(Valid.class);
+ }
ResultHandle resource = methodCreator.readInstanceField(resourceField, methodCreator.getThis());
ResultHandle id = methodCreator.getMethodParam(0);
diff --git a/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/hal/AddHalMethodImplementor.java b/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/hal/AddHalMethodImplementor.java
index fce46c72078..4e12f49b9ac 100644
--- a/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/hal/AddHalMethodImplementor.java
+++ b/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/hal/AddHalMethodImplementor.java
@@ -2,6 +2,7 @@
import static io.quarkus.gizmo.MethodDescriptor.ofMethod;
+import javax.validation.Valid;
import javax.ws.rs.core.Response;
import io.quarkus.gizmo.ClassCreator;
@@ -20,6 +21,12 @@ public final class AddHalMethodImplementor extends HalMethodImplementor {
private static final String RESOURCE_METHOD_NAME = "add";
+ private final boolean withValidation;
+
+ public AddHalMethodImplementor(boolean withValidation) {
+ this.withValidation = withValidation;
+ }
+
/**
* Expose {@link RestDataResource#add(Object)} via HAL JAX-RS method.
* Generated code looks more or less like this:
@@ -61,6 +68,10 @@ protected void implementInternal(ClassCreator classCreator, ResourceMetadata res
addPostAnnotation(methodCreator);
addConsumesAnnotation(methodCreator, APPLICATION_JSON);
addProducesAnnotation(methodCreator, APPLICATION_HAL_JSON);
+ // Add parameter annotations
+ if (withValidation) {
+ methodCreator.getParameterAnnotations(0).addAnnotation(Valid.class);
+ }
ResultHandle resource = methodCreator.readInstanceField(resourceField, methodCreator.getThis());
ResultHandle entityToSave = methodCreator.getMethodParam(0);
diff --git a/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/hal/UpdateHalMethodImplementor.java b/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/hal/UpdateHalMethodImplementor.java
index ee55679932b..7c07580ce60 100644
--- a/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/hal/UpdateHalMethodImplementor.java
+++ b/extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/hal/UpdateHalMethodImplementor.java
@@ -2,6 +2,7 @@
import static io.quarkus.gizmo.MethodDescriptor.ofMethod;
+import javax.validation.Valid;
import javax.ws.rs.core.Response;
import io.quarkus.gizmo.BranchResult;
@@ -24,6 +25,12 @@ public final class UpdateHalMethodImplementor extends HalMethodImplementor {
private static final String RESOURCE_GET_METHOD_NAME = "get";
+ private final boolean withValidation;
+
+ public UpdateHalMethodImplementor(boolean withValidation) {
+ this.withValidation = withValidation;
+ }
+
/**
* Expose {@link RestDataResource#update(Object, Object)} via HAL JAX-RS method.
* Generated code looks more or less like this:
@@ -72,6 +79,10 @@ protected void implementInternal(ClassCreator classCreator, ResourceMetadata res
addPathParamAnnotation(methodCreator.getParameterAnnotations(0), "id");
addConsumesAnnotation(methodCreator, APPLICATION_JSON);
addProducesAnnotation(methodCreator, APPLICATION_HAL_JSON);
+ // Add parameter annotations
+ if (withValidation) {
+ methodCreator.getParameterAnnotations(1).addAnnotation(Valid.class);
+ }
ResultHandle resource = methodCreator.readInstanceField(resourceField, methodCreator.getThis());
ResultHandle id = methodCreator.getMethodParam(0);
diff --git a/integration-tests/hibernate-orm-rest-data-panache/src/test/java/io/quarkus/it/hibernate/orm/rest/data/panache/HibernateOrmRestDataPanacheTest.java b/integration-tests/hibernate-orm-rest-data-panache/src/test/java/io/quarkus/it/hibernate/orm/rest/data/panache/HibernateOrmRestDataPanacheTest.java
index df2f9f3db55..1e06b968175 100644
--- a/integration-tests/hibernate-orm-rest-data-panache/src/test/java/io/quarkus/it/hibernate/orm/rest/data/panache/HibernateOrmRestDataPanacheTest.java
+++ b/integration-tests/hibernate-orm-rest-data-panache/src/test/java/io/quarkus/it/hibernate/orm/rest/data/panache/HibernateOrmRestDataPanacheTest.java
@@ -178,7 +178,9 @@ void shouldNotCreateBookWithBlankTitle() {
.and().contentType("application/json")
.and().body(book.toString())
.when().post("/books")
- .then().statusCode(400);
+ .then().statusCode(400)
+ .and().body("parameterViolations[0].path", equalTo("add.arg0.title"))
+ .and().body("parameterViolations[0].message", equalTo("must not be blank"));
}
@Test
@@ -230,4 +232,24 @@ void shouldCreateUpdateAndDeleteBook() {
when().delete(location)
.then().statusCode(204);
}
+
+ @Test
+ void shouldNotUpdateBookWithBlankTitle() {
+ JsonObject author = Json.createObjectBuilder()
+ .add("id", DOSTOEVSKY_ID)
+ .add("name", DOSTOEVSKY_NAME)
+ .add("dob", DOSTOEVSKY_DOB)
+ .build();
+ JsonObject book = Json.createObjectBuilder()
+ .add("title", "")
+ .add("author", author)
+ .build();
+ given().accept("application/json")
+ .and().contentType("application/json")
+ .and().body(book.toString())
+ .when().put("/books/" + CRIME_AND_PUNISHMENT_ID)
+ .then().statusCode(400)
+ .and().body("parameterViolations[0].path", equalTo("update.arg1.title"))
+ .and().body("parameterViolations[0].message", equalTo("must not be blank"));
+ }
}
diff --git a/integration-tests/spring-data-rest/src/test/java/io/quarkus/it/spring/data/rest/SpringDataRestTest.java b/integration-tests/spring-data-rest/src/test/java/io/quarkus/it/spring/data/rest/SpringDataRestTest.java
index 7631cfe405b..0a5325c28e8 100644
--- a/integration-tests/spring-data-rest/src/test/java/io/quarkus/it/spring/data/rest/SpringDataRestTest.java
+++ b/integration-tests/spring-data-rest/src/test/java/io/quarkus/it/spring/data/rest/SpringDataRestTest.java
@@ -156,6 +156,26 @@ void shouldCreateAndDeleteBook() {
.then().statusCode(404);
}
+ @Test
+ void shouldNotCreateBookWithBlankTitle() {
+ JsonObject author = Json.createObjectBuilder()
+ .add("id", DOSTOEVSKY_ID)
+ .add("name", DOSTOEVSKY_NAME)
+ .add("dob", DOSTOEVSKY_DOB)
+ .build();
+ JsonObject book = Json.createObjectBuilder()
+ .add("title", "")
+ .add("author", author)
+ .build();
+ given().accept("application/json")
+ .and().contentType("application/json")
+ .and().body(book.toString())
+ .when().post("/books")
+ .then().statusCode(400)
+ .and().body("parameterViolations[0].path", equalTo("add.arg0.title"))
+ .and().body("parameterViolations[0].message", equalTo("must not be blank"));
+ }
+
@Test
void shouldNotUpdateAuthor() {
JsonObject author = Json.createObjectBuilder()
@@ -207,7 +227,7 @@ void shouldCreateUpdateAndDeleteBook() {
}
@Test
- void shouldNotCreateBookWithBlankTitle() {
+ void shouldNotUpdateBookWithBlankTitle() {
JsonObject author = Json.createObjectBuilder()
.add("id", DOSTOEVSKY_ID)
.add("name", DOSTOEVSKY_NAME)
@@ -220,7 +240,9 @@ void shouldNotCreateBookWithBlankTitle() {
given().accept("application/json")
.and().contentType("application/json")
.and().body(book.toString())
- .when().put("/books/100")
- .then().statusCode(400);
+ .when().put("/books/" + CRIME_AND_PUNISHMENT_ID)
+ .then().statusCode(400)
+ .and().body("parameterViolations[0].path", equalTo("update.arg1.title"))
+ .and().body("parameterViolations[0].message", equalTo("must not be blank"));
}
} | ['extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/UpdateMethodImplementor.java', 'extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/hal/AddHalMethodImplementor.java', 'extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/AddMethodImplementor.java', 'extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/methods/hal/UpdateHalMethodImplementor.java', 'extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/RestDataProcessor.java', 'integration-tests/hibernate-orm-rest-data-panache/src/test/java/io/quarkus/it/hibernate/orm/rest/data/panache/HibernateOrmRestDataPanacheTest.java', 'integration-tests/spring-data-rest/src/test/java/io/quarkus/it/spring/data/rest/SpringDataRestTest.java', 'extensions/panache/rest-data-panache/deployment/src/main/java/io/quarkus/rest/data/panache/deployment/JaxRsResourceImplementor.java'] | {'.java': 8} | 8 | 8 | 0 | 0 | 8 | 15,259,653 | 2,972,891 | 395,315 | 4,200 | 3,626 | 650 | 83 | 6 | 1,149 | 133 | 269 | 39 | 2 | 1 | 2021-03-11T17:05:10 | 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,822 | quarkusio/quarkus/15636/15220 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/15220 | https://github.com/quarkusio/quarkus/pull/15636 | https://github.com/quarkusio/quarkus/pull/15636 | 1 | fixes | Memory leak in non-quarkus main() in quarkus-using module (due to quarkus dependencies) | To reproduce, take any quarkus quickstart and add this class in `src/test/java` (or `src/main/java`):
```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoggingMemoryLeakMain {
protected static final Logger logger = LoggerFactory.getLogger(LoggingMemoryLeakMain.class);
public static void main(String[] args) {
for (int i = 0; i < 1_000_000_000; i++) {
System.out.println("Sout iteration " + i);
if (i % 1_000_000 == 0) {
logger.info("Iteration {}", i);
} else if (i % 1_000 == 0) {
logger.debug("Iteration {}", i);
} else {
logger.trace("Iteration {}", i);
}
}
}
}
```
With JDK 11, I get this:
```
Sout iteration 21071313
Sout iteration 21071314
Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "main"
```
That takes a few minutes. Use `-Xmx64m` to get it in a few seconds.
Its caused by jboss logging that by default remembers all logging statements in memory, see https://quarkusio.zulipchat.com/#narrow/stream/187030-users/topic/Memory.20leak.2C.20logging.20and.20psvm
**This memory leak might also affects unit tests that don't use quarkus integration.**
Why is this a problem?
It's often useful to add plain old mains in a quarkus module too, without having to create yet another module for them. These do not replace the Quarkus main that is the actually application. Examples include:
- to run a benchmark
- to experiment with a new library before mixing Quarkus in the complexity mix
- to run a tool such as converting adoc into html that goes in META-INF/resources, etc.
- ...
All of these have alternative ways of accomplishing that goal, which are better but more work intensive: it's easier to temporary just add a plain-java main and it's very _surprising_ that quarkus crippled that with a memory leak. It doesn't abide by the principle of least surprise. | 258d74ebf0cc7f07781cba186de5638eaf1fb529 | 1748cd3135c64aa737d08bf55b2194f1d88e4976 | https://github.com/quarkusio/quarkus/compare/258d74ebf0cc7f07781cba186de5638eaf1fb529...1748cd3135c64aa737d08bf55b2194f1d88e4976 | diff --git a/independent-projects/bootstrap/runner/src/main/java/io/quarkus/bootstrap/logging/QuarkusDelayedHandler.java b/independent-projects/bootstrap/runner/src/main/java/io/quarkus/bootstrap/logging/QuarkusDelayedHandler.java
index 6fe4b7ed492..ae28d6fc633 100644
--- a/independent-projects/bootstrap/runner/src/main/java/io/quarkus/bootstrap/logging/QuarkusDelayedHandler.java
+++ b/independent-projects/bootstrap/runner/src/main/java/io/quarkus/bootstrap/logging/QuarkusDelayedHandler.java
@@ -18,6 +18,7 @@
import java.util.ArrayDeque;
import java.util.Deque;
+import java.util.logging.ErrorManager;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Logger;
@@ -36,10 +37,19 @@ public class QuarkusDelayedHandler extends ExtHandler {
private final Deque<ExtLogRecord> logRecords = new ArrayDeque<>();
+ private final int queueLimit;
private volatile boolean buildTimeLoggingActivated = false;
private volatile boolean activated = false;
private volatile boolean callerCalculationRequired = false;
+ public QuarkusDelayedHandler() {
+ this(4000);
+ }
+
+ public QuarkusDelayedHandler(final int queueLimit) {
+ this.queueLimit = queueLimit;
+ }
+
@Override
protected void doPublish(final ExtLogRecord record) {
// If activated just delegate
@@ -53,6 +63,13 @@ protected void doPublish(final ExtLogRecord record) {
publishToNestedHandlers(record);
super.doPublish(record);
} else {
+ // Determine whether the queue was overrun
+ if (logRecords.size() >= queueLimit) {
+ reportError(
+ "The delayed handler's queue was overrun and log record(s) were lost. Did you forget to configure logging?",
+ null, ErrorManager.WRITE_FAILURE);
+ return;
+ }
// Determine if we need to calculate the caller information before we queue the record
if (isCallerCalculationRequired()) {
// prepare record to move to another thread | ['independent-projects/bootstrap/runner/src/main/java/io/quarkus/bootstrap/logging/QuarkusDelayedHandler.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 15,211,808 | 2,963,486 | 394,067 | 4,182 | 676 | 117 | 17 | 1 | 2,026 | 275 | 488 | 47 | 1 | 2 | 2021-03-11T14:49: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,151 | quarkusio/quarkus/34144/34141 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/34141 | https://github.com/quarkusio/quarkus/pull/34144 | https://github.com/quarkusio/quarkus/pull/34144 | 1 | closes | Remove usage of @AlwaysInline as it's not GraalVM API | ### Describe the bug
There are some usages of `@AlwaysInline` that prevent a switch-over of the GraalVM dependency from `org.graalvm.nativeimage:svm` (which isn't supposed to be API) to `org.graalvm.sdk:graal-sdk`. These are currently:
```
grep -rn @AlwaysInline
core/runtime/src/main/java/io/quarkus/runtime/graal/ConfigurationSubstitutions.java:26: @AlwaysInline("trivial")
extensions/jdbc/jdbc-mssql/runtime/src/main/java/io/quarkus/jdbc/mssql/runtime/graal/com/microsoft/sqlserver/jdbc/SQLServerJDBCSubstitutions.java:90: @AlwaysInline("We need this to be constant folded")
```
### Expected behavior
No more use of `@AlwaysInline` and `graal-sdk` is being used as a dep only.
### Actual behavior
Some modules fail to compile with the `graal-sdk` dependency. For example:
```
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /home/sgehwolf/Documents/openjdk/quarkus/quarkus-source/extensions/jdbc/jdbc-mssql/runtime/src/main/java/io/quarkus/jdbc/mssql/runtime/graal/com/microsoft/sqlserver/jdbc/SQLServerJDBCSubstitutions.java:[12,27] cannot find symbol
symbol: class AlwaysInline
location: package com.oracle.svm.core
[ERROR] /home/sgehwolf/Documents/openjdk/quarkus/quarkus-source/extensions/jdbc/jdbc-mssql/runtime/src/main/java/io/quarkus/jdbc/mssql/runtime/graal/com/microsoft/sqlserver/jdbc/SQLServerJDBCSubstitutions.java:[90,6] cannot find symbol
symbol: class AlwaysInline
location: class io.quarkus.jdbc.mssql.runtime.graal.com.microsoft.sqlserver.jdbc.DisableFMTRemove
```
### How to Reproduce?
Change the deps to `graal-sdk` over `svm` artifact. Compile quarkus.
### Output of `uname -a` or `ver`
_No response_
### Output of `java -version`
17
### GraalVM version (if different from Java)
22.3.2
### Quarkus version or git rev
main
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
_No response_
### Additional information
See https://github.com/oracle/graal/pull/4683 which moved supported annotations to the `graal-sdk`. | 297c0ca19015608487eb603b7432bf6f9375737f | 0c5d2988f51ea4ac54cadd9f25cd14a0eeeb2184 | https://github.com/quarkusio/quarkus/compare/297c0ca19015608487eb603b7432bf6f9375737f...0c5d2988f51ea4ac54cadd9f25cd14a0eeeb2184 | diff --git a/core/runtime/src/main/java/io/quarkus/runtime/graal/ConfigurationSubstitutions.java b/core/runtime/src/main/java/io/quarkus/runtime/graal/ConfigurationSubstitutions.java
index c65c8bbad71..deda93e99ee 100644
--- a/core/runtime/src/main/java/io/quarkus/runtime/graal/ConfigurationSubstitutions.java
+++ b/core/runtime/src/main/java/io/quarkus/runtime/graal/ConfigurationSubstitutions.java
@@ -2,7 +2,6 @@
import org.eclipse.microprofile.config.Config;
-import com.oracle.svm.core.AlwaysInline;
import com.oracle.svm.core.annotate.Alias;
import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;
@@ -23,7 +22,6 @@ public Config getConfig() {
}
@Substitute
- @AlwaysInline("trivial")
public Config getConfig(ClassLoader classLoader) {
return getConfig();
}
diff --git a/extensions/jdbc/jdbc-mssql/runtime/src/main/java/io/quarkus/jdbc/mssql/runtime/graal/com/microsoft/sqlserver/jdbc/SQLServerJDBCSubstitutions.java b/extensions/jdbc/jdbc-mssql/runtime/src/main/java/io/quarkus/jdbc/mssql/runtime/graal/com/microsoft/sqlserver/jdbc/SQLServerJDBCSubstitutions.java
index b5e861f1b2c..02fbe8d1fa4 100644
--- a/extensions/jdbc/jdbc-mssql/runtime/src/main/java/io/quarkus/jdbc/mssql/runtime/graal/com/microsoft/sqlserver/jdbc/SQLServerJDBCSubstitutions.java
+++ b/extensions/jdbc/jdbc-mssql/runtime/src/main/java/io/quarkus/jdbc/mssql/runtime/graal/com/microsoft/sqlserver/jdbc/SQLServerJDBCSubstitutions.java
@@ -9,7 +9,6 @@
import com.microsoft.sqlserver.jdbc.SQLServerException;
import com.microsoft.sqlserver.jdbc.SQLServerStatement;
import com.microsoft.sqlserver.jdbc.SqlAuthenticationToken;
-import com.oracle.svm.core.AlwaysInline;
import com.oracle.svm.core.annotate.Delete;
import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;
@@ -87,7 +86,6 @@ final class SQLServerFMTQuery {
final class DisableFMTRemove {
@Substitute
- @AlwaysInline("We need this to be constant folded")
public final boolean getUseFmtOnly() throws SQLServerException {
return false;//Important for this to be disabled via a constant
} | ['extensions/jdbc/jdbc-mssql/runtime/src/main/java/io/quarkus/jdbc/mssql/runtime/graal/com/microsoft/sqlserver/jdbc/SQLServerJDBCSubstitutions.java', 'core/runtime/src/main/java/io/quarkus/runtime/graal/ConfigurationSubstitutions.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 26,903,778 | 5,306,525 | 682,982 | 6,292 | 169 | 41 | 4 | 2 | 2,071 | 176 | 542 | 56 | 1 | 2 | 2023-06-19T18:27:17 | 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,149 | quarkusio/quarkus/34246/34089 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/34089 | https://github.com/quarkusio/quarkus/pull/34246 | https://github.com/quarkusio/quarkus/pull/34246 | 1 | fixes | Quarkus extension created with 2.13 stream and Quarkus CLI 3 contains Jakarta imports | ### Describe the bug
I create extension with Quarkus CLI 3 for my application that uses Quarkus 2.13 and module `integration tests` of generated projects contain Jakarta imports.
### Expected behavior
Generated tests should be working for Quarkus 2.13.
### Actual behavior
```
[ERROR] /home/mvavrik/Downloads/tmp/ex2/quarkus-extension-abc/integration-tests/src/main/java/io/quarkiverse/extension/abc/it/ExtensionAbcResource.java:[19,34] package jakarta.enterprise.context does not exist
[ERROR] /home/mvavrik/Downloads/tmp/ex2/quarkus-extension-abc/integration-tests/src/main/java/io/quarkiverse/extension/abc/it/ExtensionAbcResource.java:[20,21] package jakarta.ws.rs does not exist
[ERROR] /home/mvavrik/Downloads/tmp/ex2/quarkus-extension-abc/integration-tests/src/main/java/io/quarkiverse/extension/abc/it/ExtensionAbcResource.java:[21,21] package jakarta.ws.rs does not exist
[ERROR] /home/mvavrik/Downloads/tmp/ex2/quarkus-extension-abc/integration-tests/src/main/java/io/quarkiverse/extension/abc/it/ExtensionAbcResource.java:[23,2] cannot find symbol
[ERROR] symbol: class Path
[ERROR] /home/mvavrik/Downloads/tmp/ex2/quarkus-extension-abc/integration-tests/src/main/java/io/quarkiverse/extension/abc/it/ExtensionAbcResource.java:[24,2] cannot find symbol
[ERROR] symbol: class ApplicationScoped
[ERROR] /home/mvavrik/Downloads/tmp/ex2/quarkus-extension-abc/integration-tests/src/main/java/io/quarkiverse/extension/abc/it/ExtensionAbcResource.java:[28,6] cannot find symbol
```
### How to Reproduce?
Steps to reproduce the behavior:
1. `quarkus create extension extension-abc --stream=2.13`
2. `cd quarkus-extension-abc/`
3. `quarkus build`
### Output of `uname -a` or `ver`
Linux apc-ap8641-3a-d11d.mgmt.pnr.lab.eng.rdu2.redhat.com 6.3.6-200.fc38.x86_64 #1 SMP PREEMPT_DYNAMIC Mon Jun 5 15:45:04 UTC 2023 x86_64 GNU/Linux
### Output of `java -version`
openjdk version "17.0.7" 2023-04-18
### GraalVM version (if different from Java)
22.3
### Quarkus version or git rev
2.13.8.Final
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
Apache Maven 3.9.2 and 3.8.6
### Additional information
_No response_ | eedd893f21a045ce7b9a943cc36103189dfecdae | 8a96b2747ddc8e57ab70aa1fdec3b3dc447de239 | https://github.com/quarkusio/quarkus/compare/eedd893f21a045ce7b9a943cc36103189dfecdae...8a96b2747ddc8e57ab70aa1fdec3b3dc447de239 | diff --git a/devtools/project-core-extension-codestarts/src/main/resources/codestarts/quarkus/extension-codestarts/resteasy-codestart/java/src/main/java/org/acme/{resource.class-name}.tpl.qute.java b/devtools/project-core-extension-codestarts/src/main/resources/codestarts/quarkus/extension-codestarts/resteasy-codestart/java/src/main/java/org/acme/{resource.class-name}.tpl.qute.java
index 720033d91c9..076f775b79b 100644
--- a/devtools/project-core-extension-codestarts/src/main/resources/codestarts/quarkus/extension-codestarts/resteasy-codestart/java/src/main/java/org/acme/{resource.class-name}.tpl.qute.java
+++ b/devtools/project-core-extension-codestarts/src/main/resources/codestarts/quarkus/extension-codestarts/resteasy-codestart/java/src/main/java/org/acme/{resource.class-name}.tpl.qute.java
@@ -1,9 +1,16 @@
package org.acme;
+{#if quarkus.bom.version.startsWith("2.") or quarkus.bom.version.startsWith("1.")}
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+{#else}
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
+{/if}
@Path("{resource.path}")
public class {resource.class-name} {
diff --git a/independent-projects/tools/base-codestarts/src/main/resources/codestarts/quarkus-extension/code/integration-tests/java/integration-tests/src/main/java/{package-name.dir}/it/{class-name-base}Resource.tpl.qute.java b/independent-projects/tools/base-codestarts/src/main/resources/codestarts/quarkus-extension/code/integration-tests/java/integration-tests/src/main/java/{package-name.dir}/it/{class-name-base}Resource.tpl.qute.java
index 99eb1068ffd..ed38c752d39 100644
--- a/independent-projects/tools/base-codestarts/src/main/resources/codestarts/quarkus-extension/code/integration-tests/java/integration-tests/src/main/java/{package-name.dir}/it/{class-name-base}Resource.tpl.qute.java
+++ b/independent-projects/tools/base-codestarts/src/main/resources/codestarts/quarkus-extension/code/integration-tests/java/integration-tests/src/main/java/{package-name.dir}/it/{class-name-base}Resource.tpl.qute.java
@@ -16,9 +16,15 @@
*/
package {package-name}.it;
+{#if quarkus.bom.version.startsWith("2.") or quarkus.bom.version.startsWith("1.")}
+import javax.enterprise.context.ApplicationScoped;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+{#else}
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
+{/if}
@Path("/{extension.id}")
@ApplicationScoped | ['devtools/project-core-extension-codestarts/src/main/resources/codestarts/quarkus/extension-codestarts/resteasy-codestart/java/src/main/java/org/acme/{resource.class-name}.tpl.qute.java', 'independent-projects/tools/base-codestarts/src/main/resources/codestarts/quarkus-extension/code/integration-tests/java/integration-tests/src/main/java/{package-name.dir}/it/{class-name-base}Resource.tpl.qute.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 26,998,477 | 5,324,938 | 685,604 | 6,322 | 216 | 58 | 7 | 1 | 2,170 | 175 | 638 | 52 | 0 | 1 | 2023-06-22T11:23:04 | 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,125 | quarkusio/quarkus/35174/34576 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/34576 | https://github.com/quarkusio/quarkus/pull/35174 | https://github.com/quarkusio/quarkus/pull/35174 | 1 | fixes | Live reload stopped working on 3.2 when using XA transactions | ### Describe the bug
When upgrading from 3.1 to 3.2, using quarkus:dev mode, the application will no longer reload on code changes, but fail with an exception, if an XA transaction manager is used (`quarkus.datasource.jdbc.transactions=xa`).
### Expected behavior
Application reloads as before
### Actual behavior
```
023-07-06 14:42:10,384 ERROR [io.qua.run.Application] (Quarkus Main Thread) Failed to start application (with profile [dev]) [Error Occurred After Shutdown]: java.lang.RuntimeException: Failed to start quarkus
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:111)
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)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
at java.base/java.lang.reflect.Method.invoke(Method.java:580)
at io.quarkus.runner.bootstrap.StartupActionImpl$1.run(StartupActionImpl.java:104)
at java.base/java.lang.Thread.run(Thread.java:1583)
Caused by: java.lang.IllegalStateException: ARJUNA012400: Cannot terminate the recovery manager as the implementation is not known. Could be the recovery manager was not started yet?
at com.arjuna.ats.arjuna.recovery.RecoveryManager.checkState(RecoveryManager.java:489)
at com.arjuna.ats.arjuna.recovery.RecoveryManager.getModules(RecoveryManager.java:355)
at com.arjuna.ats.jbossatx.jta.RecoveryManagerService.addXAResourceRecovery(RecoveryManagerService.java:97)
at io.quarkus.narayana.jta.runtime.QuarkusRecoveryService.addXAResourceRecovery(QuarkusRecoveryService.java:30)
at io.agroal.narayana.NarayanaTransactionIntegration.addResourceRecoveryFactory(NarayanaTransactionIntegration.java:132)
at io.agroal.pool.ConnectionPool.init(ConnectionPool.java:133)
at io.agroal.pool.DataSource.<init>(DataSource.java:42)
at io.quarkus.agroal.runtime.DataSources.doCreateDataSource(DataSources.java:246)
at io.quarkus.agroal.runtime.DataSources$1.apply(DataSources.java:129)
at io.quarkus.agroal.runtime.DataSources$1.apply(DataSources.java:126)
at java.base/java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1708)
at io.quarkus.agroal.runtime.DataSources.getDataSource(DataSources.java:126)
at io.quarkus.agroal.runtime.DataSources.fromName(DataSources.java:122)
at io.quarkus.agroal.runtime.AgroalRecorder.agroalDataSourceSupplier(AgroalRecorder.java:23)
at io.quarkus.deployment.steps.AgroalProcessor$generateDataSourceBeans109901991.deploy_0(Unknown Source)
at io.quarkus.deployment.steps.AgroalProcessor$generateDataSourceBeans109901991.deploy(Unknown Source)
... 11 more
```
### How to Reproduce?
```
modules: agroal, narayana-jta, postgres jdbc driver
quarkus.datasource.db-kind=postgresql
quarkus.datasource.username=postgres
quarkus.datasource.password=postgres
quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/postgres
quarkus.datasource.jdbc.transactions=xa
quarkus.transaction-manager.enable-recovery=true
@Inject
DataSource ds;
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() throws Exception{
QuarkusTransaction.requiringNew()
.run(()->{
try(var c = ds.getConnection()) {
} catch (Exception e) {
throw new RuntimeException(e);
}
});
return "blah"; // <-- change output to test live reload
}
```
### Output of `uname -a` or `ver`
_No response_
### Output of `java -version`
20
### GraalVM version (if different from Java)
20
### Quarkus version or git rev
3.2.0.Final
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
maven
### Additional information
_No response_ | 6e65c470dd80761951d144a816f85a413c7cef06 | d99f0b52d202bc36a4731652052b706e096a412f | https://github.com/quarkusio/quarkus/compare/6e65c470dd80761951d144a816f85a413c7cef06...d99f0b52d202bc36a4731652052b706e096a412f | diff --git a/extensions/narayana-jta/runtime/src/main/java/io/quarkus/narayana/jta/runtime/NarayanaJtaRecorder.java b/extensions/narayana-jta/runtime/src/main/java/io/quarkus/narayana/jta/runtime/NarayanaJtaRecorder.java
index 38b1b1293ae..c73a1cddb39 100644
--- a/extensions/narayana-jta/runtime/src/main/java/io/quarkus/narayana/jta/runtime/NarayanaJtaRecorder.java
+++ b/extensions/narayana-jta/runtime/src/main/java/io/quarkus/narayana/jta/runtime/NarayanaJtaRecorder.java
@@ -16,7 +16,6 @@
import com.arjuna.ats.arjuna.common.arjPropertyManager;
import com.arjuna.ats.arjuna.coordinator.TransactionReaper;
import com.arjuna.ats.arjuna.coordinator.TxControl;
-import com.arjuna.ats.arjuna.recovery.RecoveryManager;
import com.arjuna.ats.internal.arjuna.objectstore.jdbc.JDBCStore;
import com.arjuna.ats.jta.common.JTAEnvironmentBean;
import com.arjuna.ats.jta.common.jtaPropertyManager;
@@ -158,7 +157,14 @@ public void startRecoveryService(final TransactionManagerConfiguration transacti
public void handleShutdown(ShutdownContext context, TransactionManagerConfiguration transactions) {
context.addLastShutdownTask(() -> {
if (transactions.enableRecovery) {
- RecoveryManager.manager().terminate(true);
+ try {
+ QuarkusRecoveryService.getInstance().stop();
+ } catch (Exception e) {
+ // the recovery manager throws IllegalStateException if it has already been shutdown
+ log.warn("The recovery manager has already been shutdown", e);
+ } finally {
+ QuarkusRecoveryService.getInstance().destroy();
+ }
}
TransactionReaper.terminate(false);
});
diff --git a/extensions/narayana-jta/runtime/src/main/java/io/quarkus/narayana/jta/runtime/QuarkusRecoveryService.java b/extensions/narayana-jta/runtime/src/main/java/io/quarkus/narayana/jta/runtime/QuarkusRecoveryService.java
index 55ff7ae05fe..923bcfe4625 100644
--- a/extensions/narayana-jta/runtime/src/main/java/io/quarkus/narayana/jta/runtime/QuarkusRecoveryService.java
+++ b/extensions/narayana-jta/runtime/src/main/java/io/quarkus/narayana/jta/runtime/QuarkusRecoveryService.java
@@ -51,4 +51,11 @@ public void create() {
}
xaResources.clear();
}
+
+ @Override
+ public void destroy() {
+ super.destroy();
+ isCreated = false;
+ recoveryManagerService = null;
+ }
} | ['extensions/narayana-jta/runtime/src/main/java/io/quarkus/narayana/jta/runtime/QuarkusRecoveryService.java', 'extensions/narayana-jta/runtime/src/main/java/io/quarkus/narayana/jta/runtime/NarayanaJtaRecorder.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 27,373,658 | 5,400,412 | 694,393 | 6,376 | 698 | 121 | 17 | 2 | 4,102 | 258 | 992 | 96 | 0 | 2 | 2023-08-02T16:42:17 | 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,124 | quarkusio/quarkus/35188/34908 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/34908 | https://github.com/quarkusio/quarkus/pull/35188 | https://github.com/quarkusio/quarkus/pull/35188 | 1 | fixes | @RouteFilter stopped working with WebSocket requests Quarkus 3.2.0.Final | ### Describe the bug
We were migrating from 2.16.7 to 3.2.0.Final
And we have WebSocket interceptor implemented with @RouteFilter
It looks like this:
```java
@RouteFilter
void authFilter(RoutingContext rc) {
/// logic to search for websocket header etc
}
```
We use it to intercept GQL Subscriptions and its initial websocket request.
After migration to 3.2.0.Final it stopped intercepting WebSocket for some reason.
### Expected behavior
Intercept all requests as it was in 2.16.7
### Actual behavior
Not intercepting websocket initial request
### How to Reproduce?
_No response_
### Output of `uname -a` or `ver`
_No response_
### Output of `java -version`
17
### GraalVM version (if different from Java)
_No response_
### Quarkus version or git rev
3.2.0.Final
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
gradle 8.1.1
### Additional information
_No response_ | 6e65c470dd80761951d144a816f85a413c7cef06 | 2be7e958493f2a947be72120d03ccfa9b3e55e52 | https://github.com/quarkusio/quarkus/compare/6e65c470dd80761951d144a816f85a413c7cef06...2be7e958493f2a947be72120d03ccfa9b3e55e52 | diff --git a/extensions/smallrye-graphql/deployment/src/main/java/io/quarkus/smallrye/graphql/deployment/SmallRyeGraphQLProcessor.java b/extensions/smallrye-graphql/deployment/src/main/java/io/quarkus/smallrye/graphql/deployment/SmallRyeGraphQLProcessor.java
index d5857405ca9..9a494fdb4df 100644
--- a/extensions/smallrye-graphql/deployment/src/main/java/io/quarkus/smallrye/graphql/deployment/SmallRyeGraphQLProcessor.java
+++ b/extensions/smallrye-graphql/deployment/src/main/java/io/quarkus/smallrye/graphql/deployment/SmallRyeGraphQLProcessor.java
@@ -146,6 +146,8 @@ public class SmallRyeGraphQLProcessor {
private static final List<String> SUPPORTED_WEBSOCKET_SUBPROTOCOLS = List.of(SUBPROTOCOL_GRAPHQL_WS,
SUBPROTOCOL_GRAPHQL_TRANSPORT_WS);
+ private static final int GRAPHQL_WEBSOCKET_HANDLER_ORDER = -10000;
+
@BuildStep
void feature(BuildProducer<FeatureBuildItem> featureProducer) {
featureProducer.produce(new FeatureBuildItem(Feature.SMALLRYE_GRAPHQL));
@@ -370,7 +372,7 @@ void buildExecutionEndpoint(
runBlocking);
HttpRootPathBuildItem.Builder subscriptionsBuilder = httpRootPathBuildItem.routeBuilder()
- .orderedRoute(graphQLConfig.rootPath, Integer.MIN_VALUE)
+ .orderedRoute(graphQLConfig.rootPath, GRAPHQL_WEBSOCKET_HANDLER_ORDER)
.handler(graphqlOverWebsocketHandler);
routeProducer.produce(subscriptionsBuilder.build());
| ['extensions/smallrye-graphql/deployment/src/main/java/io/quarkus/smallrye/graphql/deployment/SmallRyeGraphQLProcessor.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 27,373,658 | 5,400,412 | 694,393 | 6,376 | 235 | 49 | 4 | 1 | 966 | 136 | 241 | 52 | 0 | 1 | 2023-08-03T13:47: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,123 | quarkusio/quarkus/35203/34875 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/34875 | https://github.com/quarkusio/quarkus/pull/35203 | https://github.com/quarkusio/quarkus/pull/35203 | 1 | fix | Quarkus build does not work since 3.2.0 with teamcity/plexus launcher | ### Describe the bug
We have some custom extensions which use dependencies from a private repository. Since quarkus 3.2.0 the build fails while generating the test code. Up to 3.1.3 it worked fine.
```
[INFO] --- quarkus:3.2.1.Final:generate-code-tests (default) @ database-extension-base ---
[INFO] Artifact de.mobilexag.serviceplatform:service-parent-kotlin:pom:1.8.1 is present in the local repository, but cached from a remote repository ID that is unavailable in current build context, verifying that is downloadable from [central (https://repo.maven.apache.org/maven2, default, releases)]
Downloading from central: https://repo.maven.apache.org/maven2/de/mobilexag/serviceplatform/service-parent-kotlin/1.8.1/service-parent-kotlin-1.8.1.pom
[INFO] No previous run data found, generating javadoc.
Failed to execute goal io.quarkus:quarkus-maven-plugin:3.2.1.Final:generate-code-tests (default) on project database-extension-base: Quarkus code generation phase has failed
```
I first thought this might be the problem, but it fails still with 3.2.1 https://github.com/quarkusio/quarkus/issues/34448
We encountered the problem on our build system teamcity. It starts maven builds via the plexus launcher. https://codehaus-plexus.github.io/plexus-classworlds/launcher.html
The quarkus maven plugin seems to ignore the settings file set via plexus. The call looks something like this:
```
java -Dmaven.repo.local=local-repo \\
-Dclassworlds.conf=teamcity.m2.conf \\
-Dmaven.multiModuleProjectDirectory=../code-with-quarkus \\
--add-opens \\
java.base/java.lang=ALL-UNNAMED \\
-classpath \\
"$MAVEN_HOME/boot/*:" \\
org.codehaus.plexus.classworlds.launcher.Launcher \\
-f \\
pom.xml \\
-B \\
-s \\
custom-settings.xml \\
-fae \\
-Plicense \\
-X \\
clean \\
package
```
The settings file is set via -s command on maven start.
In the reproducer, there are some scripts to start the build.
### Expected behavior
Build should work.
### Actual behavior
Build fails.
### How to Reproduce?
https://github.com/robp94/quarkus-3.2.x-maven-problem
### Output of `uname -a` or `ver`
ubuntu
### Output of `java -version`
17
### GraalVM version (if different from Java)
_No response_
### Quarkus version or git rev
3.2.2
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
maven 3.9.3
### Additional information
_No response_ | 0d3cb3545c838b7232a32b4a0b7e993c8bd5a496 | 3306eb930024c8726c53e02e4532805b33e9b369 | https://github.com/quarkusio/quarkus/compare/0d3cb3545c838b7232a32b4a0b7e993c8bd5a496...3306eb930024c8726c53e02e4532805b33e9b369 | diff --git a/devtools/maven/src/main/java/io/quarkus/maven/DependencyTreeMojo.java b/devtools/maven/src/main/java/io/quarkus/maven/DependencyTreeMojo.java
index a990e5d8ccd..22891e8f44d 100644
--- a/devtools/maven/src/main/java/io/quarkus/maven/DependencyTreeMojo.java
+++ b/devtools/maven/src/main/java/io/quarkus/maven/DependencyTreeMojo.java
@@ -8,6 +8,7 @@
import java.util.List;
import java.util.function.Consumer;
+import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
@@ -37,6 +38,9 @@ public class DependencyTreeMojo extends AbstractMojo {
@Parameter(defaultValue = "${project}", readonly = true, required = true)
protected MavenProject project;
+ @Parameter(defaultValue = "${session}", readonly = true)
+ protected MavenSession session;
+
@Parameter(defaultValue = "${project.remoteProjectRepositories}", readonly = true, required = true)
private List<RemoteRepository> repos;
@@ -130,6 +134,7 @@ private void logTree(final Consumer<String> log) throws MojoExecutionException {
protected MavenArtifactResolver resolver() {
return resolver == null
? resolver = workspaceProvider.createArtifactResolver(BootstrapMavenContext.config()
+ .setUserSettings(session.getRequest().getUserSettingsFile())
// The system needs to be initialized with the bootstrap model builder to properly interpolate system properties set on the command line
// e.g. -Dquarkus.platform.version=xxx
//.setRepositorySystem(repoSystem)
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 b06e1b16173..34d04f14e98 100644
--- a/devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java
+++ b/devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java
@@ -1137,6 +1137,7 @@ private QuarkusDevModeLauncher newLauncher(Boolean debugPortOk, String bootstrap
bootstrapProvider.close();
} else {
final BootstrapMavenContextConfig<?> mvnConfig = BootstrapMavenContext.config()
+ .setUserSettings(session.getRequest().getUserSettingsFile())
.setRemoteRepositories(repos)
.setWorkspaceDiscovery(true)
.setPreferPomsFromWorkspace(true)
diff --git a/devtools/maven/src/main/java/io/quarkus/maven/GoOfflineMojo.java b/devtools/maven/src/main/java/io/quarkus/maven/GoOfflineMojo.java
index 4502351c87d..d76dee2638e 100644
--- a/devtools/maven/src/main/java/io/quarkus/maven/GoOfflineMojo.java
+++ b/devtools/maven/src/main/java/io/quarkus/maven/GoOfflineMojo.java
@@ -7,6 +7,7 @@
import java.util.List;
import java.util.Set;
+import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
@@ -43,6 +44,9 @@ public class GoOfflineMojo extends AbstractMojo {
@Parameter(defaultValue = "${project}", readonly = true, required = true)
MavenProject project;
+ @Parameter(defaultValue = "${session}", readonly = true)
+ MavenSession session;
+
@Component
RepositorySystem repoSystem;
@@ -118,6 +122,7 @@ public void execute() throws MojoExecutionException, MojoFailureException {
private MavenArtifactResolver getResolver() throws MojoExecutionException {
return workspaceProvider.createArtifactResolver(BootstrapMavenContext.config()
+ .setUserSettings(session.getRequest().getUserSettingsFile())
.setCurrentProject(project.getBasedir().toString())
.setRemoteRepositoryManager(remoteRepositoryManager)
.setRemoteRepositories(repos)
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 36bcdf8908c..2ae61b88271 100644
--- a/devtools/maven/src/main/java/io/quarkus/maven/QuarkusBootstrapProvider.java
+++ b/devtools/maven/src/main/java/io/quarkus/maven/QuarkusBootstrapProvider.java
@@ -180,6 +180,9 @@ private MavenArtifactResolver artifactResolver(QuarkusBootstrapMojo mojo, Launch
if (mode == LaunchMode.DEVELOPMENT || mode == LaunchMode.TEST || isWorkspaceDiscovery(mojo)) {
return workspaceProvider.createArtifactResolver(
BootstrapMavenContext.config()
+ // it's important to pass user settings in case the process was not launched using the original mvn script
+ // for example using org.codehaus.plexus.classworlds.launcher.Launcher
+ .setUserSettings(mojo.mavenSession().getRequest().getUserSettingsFile())
.setCurrentProject(mojo.mavenProject().getFile().toString())
.setPreferPomsFromWorkspace(true)
.setProjectModelProvider(getProjectMap(mojo.mavenSession())::get));
diff --git a/devtools/maven/src/main/java/io/quarkus/maven/QuarkusProjectMojoBase.java b/devtools/maven/src/main/java/io/quarkus/maven/QuarkusProjectMojoBase.java
index 16043a4d5aa..62a7e1437ac 100644
--- a/devtools/maven/src/main/java/io/quarkus/maven/QuarkusProjectMojoBase.java
+++ b/devtools/maven/src/main/java/io/quarkus/maven/QuarkusProjectMojoBase.java
@@ -11,6 +11,7 @@
import java.util.Collections;
import java.util.List;
+import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
@@ -52,6 +53,9 @@ public abstract class QuarkusProjectMojoBase extends AbstractMojo {
@Parameter(defaultValue = "${project}")
protected MavenProject project;
+ @Parameter(defaultValue = "${session}", readonly = true)
+ MavenSession session;
+
@Component
protected RepositorySystem repoSystem;
diff --git a/devtools/maven/src/main/java/io/quarkus/maven/QuarkusProjectStateMojoBase.java b/devtools/maven/src/main/java/io/quarkus/maven/QuarkusProjectStateMojoBase.java
index 9007e7315bb..62a346128a0 100644
--- a/devtools/maven/src/main/java/io/quarkus/maven/QuarkusProjectStateMojoBase.java
+++ b/devtools/maven/src/main/java/io/quarkus/maven/QuarkusProjectStateMojoBase.java
@@ -140,6 +140,7 @@ protected MavenArtifactResolver catalogArtifactResolver() throws MojoExecutionEx
@Override
protected MavenArtifactResolver initArtifactResolver() throws MojoExecutionException {
return workspaceProvider.createArtifactResolver(BootstrapMavenContext.config()
+ .setUserSettings(session.getRequest().getUserSettingsFile())
.setRemoteRepositoryManager(remoteRepositoryManager)
// The system needs to be initialized with the bootstrap model builder to properly interpolate system properties set on the command line
// e.g. -Dquarkus.platform.version=xxx | ['devtools/maven/src/main/java/io/quarkus/maven/DependencyTreeMojo.java', 'devtools/maven/src/main/java/io/quarkus/maven/QuarkusProjectMojoBase.java', 'devtools/maven/src/main/java/io/quarkus/maven/QuarkusProjectStateMojoBase.java', 'devtools/maven/src/main/java/io/quarkus/maven/GoOfflineMojo.java', 'devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java', 'devtools/maven/src/main/java/io/quarkus/maven/QuarkusBootstrapProvider.java'] | {'.java': 6} | 6 | 6 | 0 | 0 | 6 | 27,361,897 | 5,398,293 | 694,128 | 6,375 | 1,110 | 189 | 19 | 6 | 2,437 | 277 | 638 | 76 | 5 | 2 | 2023-08-04T12:40:15 | 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,122 | quarkusio/quarkus/35301/35285 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/35285 | https://github.com/quarkusio/quarkus/pull/35301 | https://github.com/quarkusio/quarkus/pull/35301 | 1 | fixes | NullPointerException during http post request when quarkus-csrf-reactive extension is added to a project | ### Describe the bug
Adding the quarkus-csrf-reactive extension to a project leads to a NPE during a post request when CsrfRequestResponseReactiveFilter is checking the media type.
```
2023-08-09 13:47:44,725 ERROR [io.qua.ver.htt.run.QuarkusErrorHandler] (vert.x-eventloop-thread-1) HTTP Request to /hello failed, error id: c34caf8f-fc59-48c7-9cdd-cb2b1041ef1c-13: java.lang.NullPointerException: Cannot invoke "jakarta.ws.rs.core.MediaType.getType()" because "contentType" is null
at io.quarkus.csrf.reactive.runtime.CsrfRequestResponseReactiveFilter.isMatchingMediaType(CsrfRequestResponseReactiveFilter.java:152)
at io.quarkus.csrf.reactive.runtime.CsrfRequestResponseReactiveFilter.filter(CsrfRequestResponseReactiveFilter.java:100)
at io.quarkus.csrf.reactive.runtime.CsrfRequestResponseReactiveFilter$GeneratedServerRequestFilter$filter.filter(Unknown Source)
at io.quarkus.csrf.reactive.runtime.CsrfRequestResponseReactiveFilter$GeneratedServerRequestFilter$filter_ClientProxy.filter(Unknown Source)
at org.jboss.resteasy.reactive.server.handlers.ResourceRequestFilterHandler.handle(ResourceRequestFilterHandler.java:48)
at io.quarkus.resteasy.reactive.server.runtime.QuarkusResteasyReactiveRequestContext.invokeHandler(QuarkusResteasyReactiveRequestContext.java:131)
at org.jboss.resteasy.reactive.common.core.AbstractResteasyReactiveContext.run(AbstractResteasyReactiveContext.java:145)
at org.jboss.resteasy.reactive.server.handlers.RestInitialHandler.beginProcessing(RestInitialHandler.java:48)
at org.jboss.resteasy.reactive.server.vertx.ResteasyReactiveVertxHandler.handle(ResteasyReactiveVertxHandler.java:23)
at org.jboss.resteasy.reactive.server.vertx.ResteasyReactiveVertxHandler.handle(ResteasyReactiveVertxHandler.java:10)
at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1284)
at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:177)
at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:141)
at io.quarkus.vertx.http.runtime.options.HttpServerCommonHandlers$1.handle(HttpServerCommonHandlers.java:58)
at io.quarkus.vertx.http.runtime.options.HttpServerCommonHandlers$1.handle(HttpServerCommonHandlers.java:36)
at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1284)
at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:177)
at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:141)
at io.quarkus.resteasy.reactive.server.runtime.ResteasyReactiveRecorder$13.handle(ResteasyReactiveRecorder.java:382)
at io.quarkus.resteasy.reactive.server.runtime.ResteasyReactiveRecorder$13.handle(ResteasyReactiveRecorder.java:375)
at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1284)
at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:177)
at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:141)
at io.quarkus.vertx.http.runtime.devmode.VertxHttpHotReplacementSetup.handleHotReplacementRequest(VertxHttpHotReplacementSetup.java:135)
at io.quarkus.vertx.http.runtime.VertxHttpRecorder$5.handle(VertxHttpRecorder.java:434)
at io.quarkus.vertx.http.runtime.VertxHttpRecorder$5.handle(VertxHttpRecorder.java:430)
at io.vertx.ext.web.impl.RouteState.handleContext(RouteState.java:1284)
at io.vertx.ext.web.impl.RoutingContextImplBase.iterateNext(RoutingContextImplBase.java:177)
at io.vertx.ext.web.impl.RoutingContextImpl.next(RoutingContextImpl.java:141)
at io.vertx.ext.web.impl.RouterImpl.handle(RouterImpl.java:68)
at io.vertx.ext.web.impl.RouterImpl.handle(RouterImpl.java:37)
at io.quarkus.vertx.http.runtime.options.HttpServerCommonHandlers$2.handle(HttpServerCommonHandlers.java:82)
at io.quarkus.vertx.http.runtime.options.HttpServerCommonHandlers$2.handle(HttpServerCommonHandlers.java:65)
at io.quarkus.vertx.http.runtime.VertxHttpRecorder$1.handle(VertxHttpRecorder.java:177)
at io.quarkus.vertx.http.runtime.VertxHttpRecorder$1.handle(VertxHttpRecorder.java:153)
at io.quarkus.vertx.http.runtime.devmode.VertxHttpHotReplacementSetup$5.handle(VertxHttpHotReplacementSetup.java:194)
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.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:833)
```
### Expected behavior
Adding the extension doesn't lead to a NPEs during HTTP POST Requests.
### How to Reproduce?
Reproducer: https://github.com/tamaro-skaljic/quarkus-csrf-np-bug/
Steps to reproduce behaviour:
1. Start Quarkus in Dev Mode
2. Visit http://localhost:8080/q/dev-ui/io.quarkus.quarkus-smallrye-openapi/swagger-ui
3. Do a post request to /hello through it
### Additional information
If further configuration is required so that the extension does not produce errors, the build should fail. | a34ab2742b2133ffabb4b547c7a2485f98287036 | 3c6944364aa3936e6353327da3947367e04de850 | https://github.com/quarkusio/quarkus/compare/a34ab2742b2133ffabb4b547c7a2485f98287036...3c6944364aa3936e6353327da3947367e04de850 | diff --git a/extensions/csrf-reactive/runtime/src/main/java/io/quarkus/csrf/reactive/runtime/CsrfRequestResponseReactiveFilter.java b/extensions/csrf-reactive/runtime/src/main/java/io/quarkus/csrf/reactive/runtime/CsrfRequestResponseReactiveFilter.java
index 8fcba71e714..4c5eaa15177 100644
--- a/extensions/csrf-reactive/runtime/src/main/java/io/quarkus/csrf/reactive/runtime/CsrfRequestResponseReactiveFilter.java
+++ b/extensions/csrf-reactive/runtime/src/main/java/io/quarkus/csrf/reactive/runtime/CsrfRequestResponseReactiveFilter.java
@@ -97,15 +97,16 @@ public void filter(ResteasyReactiveContainerRequestContext requestContext, Routi
} else if (config.verifyToken) {
// unsafe HTTP method, token is required
- if (!isMatchingMediaType(requestContext.getMediaType(), MediaType.APPLICATION_FORM_URLENCODED_TYPE)
- && !isMatchingMediaType(requestContext.getMediaType(), MediaType.MULTIPART_FORM_DATA_TYPE)) {
+ MediaType mediaType = requestContext.getMediaType();
+ if (!isMatchingMediaType(mediaType, MediaType.APPLICATION_FORM_URLENCODED_TYPE)
+ && !isMatchingMediaType(mediaType, MediaType.MULTIPART_FORM_DATA_TYPE)) {
if (config.requireFormUrlEncoded) {
- LOG.debugf("Request has the wrong media type: %s", requestContext.getMediaType().toString());
+ LOG.debugf("Request has the wrong media type: %s", mediaType);
requestContext.abortWith(badClientRequest());
return;
} else {
- LOG.debugf("Request has the media type: %s, skipping the token verification",
- requestContext.getMediaType().toString());
+ LOG.debugf("Request has the media type: %s, skipping the token verification",
+ mediaType);
return;
}
}
@@ -148,7 +149,16 @@ public void filter(ResteasyReactiveContainerRequestContext requestContext, Routi
}
}
+ /**
+ * Compares if {@link MediaType} matches the expected type.
+ * <p>
+ * Note: isCompatible is taking wildcards, which is why we individually compare types and subtypes,
+ * so if someone sends a <code>Content-Type: *</code> it will be marked as compatible which is a problem
+ */
private static boolean isMatchingMediaType(MediaType contentType, MediaType expectedType) {
+ if (contentType == null) {
+ return (expectedType == null);
+ }
return contentType.getType().equals(expectedType.getType())
&& contentType.getSubtype().equals(expectedType.getSubtype());
} | ['extensions/csrf-reactive/runtime/src/main/java/io/quarkus/csrf/reactive/runtime/CsrfRequestResponseReactiveFilter.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 27,445,232 | 5,414,987 | 696,121 | 6,390 | 1,393 | 272 | 20 | 1 | 5,686 | 208 | 1,361 | 71 | 2 | 1 | 2023-08-10T02:19:41 | 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,121 | quarkusio/quarkus/35308/11903 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/11903 | https://github.com/quarkusio/quarkus/pull/35308 | https://github.com/quarkusio/quarkus/pull/35308 | 1 | fix | Gradle multimodule project + quarkus-container-image-jib: OverlappingFileLockException | **Describe the bug**
I have a gradle + Kotlin multi-module project and try to build container images with the quarkus-container-image-jib extension. When I run `./gradlew assemble -Dquarkus.container-image.build=true`, I get an `OverlappingFileLockException` (on Windows 10 as well as on the `gradle:6.6-jdk11` docker image).
Apart from the issues I described in #11900, I can build both images by manually running `./gradlew :serviceA:assemble -Dquarkus.container-image.build=true` and then `./gradlew :serviceB:assemble -Dquarkus.container-image.build=true`.
Detailed exception:
```
17:28:34: Executing task 'assemble -Dquarkus.container-image.build=true'...
> Task :serviceA:quarkusGenerateCode
preparing quarkus application
kotlin scripting plugin: project ':serviceA'.compileQuarkus-generated-sourcesKotlin - configuration not found: quarkus-generated-sourcesKotlinScriptDef, the plugin is probably applied by a mistake
> Task :serviceB:quarkusGenerateCode
preparing quarkus application
kotlin scripting plugin: project ':serviceB'.compileQuarkus-generated-sourcesKotlin - configuration not found: quarkus-generated-sourcesKotlinScriptDef, the plugin is probably applied by a mistake
> Task :serviceA:quarkusGenerateCodeTests
preparing quarkus application
kotlin scripting plugin: project ':serviceA'.compileQuarkus-test-generated-sourcesKotlin - configuration not found: quarkus-test-generated-sourcesKotlinScriptDef, the plugin is probably applied by a mistake
> Task :serviceB:quarkusGenerateCodeTests
preparing quarkus application
kotlin scripting plugin: project ':serviceB'.compileQuarkus-test-generated-sourcesKotlin - configuration not found: quarkus-test-generated-sourcesKotlinScriptDef, the plugin is probably applied by a mistake
> Task :serviceB:compileKotlin
> Task :serviceA:compileKotlin
> Task :serviceA:compileJava NO-SOURCE
> Task :serviceB:compileJava NO-SOURCE
> Task :serviceA:processResources
> Task :serviceB:processResources
> Task :serviceA:classes
> Task :serviceB:classes
> Task :serviceA:inspectClassesForKotlinIC
> Task :serviceB:inspectClassesForKotlinIC
> Task :serviceA:jar
> Task :serviceB:jar
> Task :serviceA:quarkusBuild
building quarkus jar
Base image 'fabric8/java-alpine-openjdk11-jre' does not use a specific image digest - build may not be reproducible
Base image 'fabric8/java-alpine-openjdk11-jre' does not use a specific image digest - build may not be reproducible
> Task :serviceB:quarkusBuild
building quarkus jar
> Task :serviceB:quarkusBuild FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':serviceB:quarkusBuild'.
> io.quarkus.builder.BuildException: Build failure: Build failed due to errors
[error]: Build step io.quarkus.container.image.jib.deployment.JibProcessor#buildFromJar threw an exception: java.lang.RuntimeException: Unable to create container image
at io.quarkus.container.image.jib.deployment.JibProcessor.containerize(JibProcessor.java:153)
at io.quarkus.container.image.jib.deployment.JibProcessor.buildFromJar(JibProcessor.java:102)
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:567)
at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:932)
at io.quarkus.builder.BuildContext.run(BuildContext.java:277)
at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:2046)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1578)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1452)
at java.base/java.lang.Thread.run(Thread.java:830)
at org.jboss.threads.JBossThread.run(JBossThread.java:479)
Caused by: java.util.concurrent.ExecutionException: java.nio.channels.OverlappingFileLockException
at com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:552)
at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:533)
at com.google.common.util.concurrent.FluentFuture$TrustedFuture.get(FluentFuture.java:82)
at com.google.cloud.tools.jib.builder.steps.StepsRunner.lambda$buildImage$8(StepsRunner.java:344)
at com.google.common.util.concurrent.TrustedListenableFutureTask$TrustedFutureInterruptibleTask.runInterruptibly(TrustedListenableFutureTask.java:125)
at com.google.common.util.concurrent.InterruptibleTask.run(InterruptibleTask.java:57)
at com.google.common.util.concurrent.TrustedListenableFutureTask.run(TrustedListenableFutureTask.java:78)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.nio.channels.OverlappingFileLockException
at java.base/sun.nio.ch.FileLockTable.checkList(FileLockTable.java:229)
at java.base/sun.nio.ch.FileLockTable.add(FileLockTable.java:123)
at java.base/sun.nio.ch.FileChannelImpl.lock(FileChannelImpl.java:1110)
at java.base/java.nio.channels.FileChannel.lock(FileChannel.java:1076)
at com.google.cloud.tools.jib.filesystem.LockFile.lock(LockFile.java:67)
at com.google.cloud.tools.jib.cache.CacheStorageWriter.writeMetadata(CacheStorageWriter.java:315)
at com.google.cloud.tools.jib.cache.Cache.writeMetadata(Cache.java:81)
at com.google.cloud.tools.jib.builder.steps.PullBaseImageStep.pullBaseImage(PullBaseImageStep.java:249)
at com.google.cloud.tools.jib.builder.steps.PullBaseImageStep.call(PullBaseImageStep.java:160)
at com.google.cloud.tools.jib.builder.steps.PullBaseImageStep.call(PullBaseImageStep.java:56)
... 6 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 26s
14 actionable tasks: 14 executed
17:29:00: Task execution finished 'assemble -Dquarkus.container-image.build=true'.
```
**To Reproduce**
Steps to reproduce the behavior:
1. Dowload reproducer project and unzip it [2020-09-04_jib-multimodule-problems.zip](https://github.com/quarkusio/quarkus/files/5175735/2020-09-04_jib-multimodule-problems.zip)
2. Run `./gradlew assemble -Dquarkus.container-image.build=true`
3. See the error shown above.
**Environment (please complete the following information):**
- Windows 10 (also happens on `gradle:6.6-jdk11` docker image in my CI builds)
- Gradle
- Kotlin
| 14763e32610b587091cc017ab092bbebf3b258e4 | 1eb8b2d80673abe76b9cced7a1cf491872d22748 | https://github.com/quarkusio/quarkus/compare/14763e32610b587091cc017ab092bbebf3b258e4...1eb8b2d80673abe76b9cced7a1cf491872d22748 | 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 e406fed36f2..2d79781a403 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
@@ -6,7 +6,6 @@
import static io.quarkus.container.image.deployment.util.EnablementUtil.buildContainerImageNeeded;
import static io.quarkus.container.image.deployment.util.EnablementUtil.pushContainerImageNeeded;
import static io.quarkus.container.util.PathsUtil.findMainSourcesRoot;
-import static io.quarkus.deployment.pkg.PackageConfig.MUTABLE_JAR;
import java.io.IOException;
import java.io.UncheckedIOException;
@@ -26,6 +25,7 @@
import java.util.Map;
import java.util.Optional;
import java.util.Set;
+import java.util.concurrent.ExecutionException;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -33,6 +33,7 @@
import org.eclipse.microprofile.config.ConfigProvider;
import org.jboss.logging.Logger;
+import com.google.cloud.tools.jib.api.CacheDirectoryCreationException;
import com.google.cloud.tools.jib.api.Containerizer;
import com.google.cloud.tools.jib.api.DockerDaemonImage;
import com.google.cloud.tools.jib.api.ImageReference;
@@ -42,6 +43,7 @@
import com.google.cloud.tools.jib.api.JibContainer;
import com.google.cloud.tools.jib.api.JibContainerBuilder;
import com.google.cloud.tools.jib.api.LogEvent;
+import com.google.cloud.tools.jib.api.RegistryException;
import com.google.cloud.tools.jib.api.RegistryImage;
import com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath;
import com.google.cloud.tools.jib.api.buildplan.FileEntriesLayer;
@@ -249,7 +251,7 @@ private JibContainer containerize(ContainerImageConfig containerImageConfig,
previousContextStorageSysProp = System.setProperty(OPENTELEMETRY_CONTEXT_CONTEXT_STORAGE_PROVIDER_SYS_PROP,
"default");
- JibContainer container = jibContainerBuilder.containerize(containerizer);
+ JibContainer container = containerizeUnderLock(jibContainerBuilder, containerizer);
log.infof("%s container image %s (%s)\\n",
containerImageConfig.isPushExplicitlyEnabled() ? "Pushed" : "Created",
container.getTargetImage(),
@@ -300,7 +302,7 @@ private Containerizer createContainerizer(ContainerImageConfig containerImageCon
}
containerizer.setToolName("Quarkus");
containerizer.setToolVersion(Version.getVersion());
- containerizer.addEventHandler(LogEvent.class, (e) -> {
+ containerizer.addEventHandler(LogEvent.class, e -> {
if (!e.getMessage().isEmpty()) {
log.log(toJBossLoggingLevel(e.getLevel()), e.getMessage());
}
@@ -311,6 +313,29 @@ private Containerizer createContainerizer(ContainerImageConfig containerImageCon
return containerizer;
}
+ /**
+ * Wraps the containerize invocation in a synchronized block to avoid OverlappingFileLockException when running parallel jib
+ * builds (e.g. mvn -T2 ...).
+ * Each build thread uses its own augmentation CL (which is why the OverlappingFileLockException prevention in jib doesn't
+ * work here), so the lock object
+ * has to be loaded via the parent classloader so that all build threads lock the same object.
+ * QuarkusAugmentor was chosen semi-randomly (note: quarkus-core-deployment is visible to that parent CL, this jib extension
+ * is not!).
+ */
+ private JibContainer containerizeUnderLock(JibContainerBuilder jibContainerBuilder, Containerizer containerizer)
+ throws InterruptedException, RegistryException, IOException, CacheDirectoryCreationException, ExecutionException {
+ Class<?> lockObj = getClass();
+ ClassLoader parentCL = getClass().getClassLoader().getParent();
+ try {
+ lockObj = parentCL.loadClass("io.quarkus.deployment.QuarkusAugmentor");
+ } catch (ClassNotFoundException e) {
+ log.warnf("Could not load io.quarkus.deployment.QuarkusAugmentor with parent classloader: %s", parentCL);
+ }
+ synchronized (lockObj) {
+ return jibContainerBuilder.containerize(containerizer);
+ }
+ }
+
private void writeOutputFiles(JibContainer jibContainer, ContainerImageJibConfig jibConfig,
OutputTargetBuildItem outputTarget) {
doWriteOutputFile(outputTarget, Paths.get(jibConfig.imageDigestFile), jibContainer.getDigest().toString()); | ['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 | 27,437,191 | 5,413,364 | 695,938 | 6,389 | 1,912 | 394 | 31 | 1 | 7,028 | 472 | 1,724 | 120 | 2 | 1 | 2023-08-10T12:51:25 | 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,120 | quarkusio/quarkus/35315/35314 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/35314 | https://github.com/quarkusio/quarkus/pull/35315 | https://github.com/quarkusio/quarkus/pull/35315 | 1 | fixes | Regression in 3.3.0.CR1: Synthetic bean instance for io.opentelemetry.api.OpenTelemetry not initialized yet | ### Describe the bug
Though I'm still waiting for a fix in Hibernate (hopefully 6.2.8), I gave 3.3.0.CR1 a try in my pending Quarkus 3 upgrade branch for my app.
QuarkusTests that have been working in 3.2.3.Final are now failing with:
```
java.lang.RuntimeException: java.lang.RuntimeException: Failed to start quarkus
[...]
Caused by: jakarta.enterprise.inject.CreationException: Error creating synthetic bean [2deeb341bce4a230183bf3a228841625fe2519ae]: jakarta.enterprise.inject.CreationException: Synthetic bean instance for io.opentelemetry.api.OpenTelemetry not initialized yet: io_opentelemetry_api_OpenTelemetry_4087e2c748253198bc7b05f31387f3f4492f0131
- a synthetic bean initialized during RUNTIME_INIT must not be accessed during STATIC_INIT
- RUNTIME_INIT build steps that require access to synthetic beans initialized during RUNTIME_INIT should consume the SyntheticBeansRuntimeInitBuildItem
at io.opentelemetry.api.OpenTelemetry_2deeb341bce4a230183bf3a228841625fe2519ae_Synthetic_Bean.doCreate(Unknown Source)
at io.opentelemetry.api.OpenTelemetry_2deeb341bce4a230183bf3a228841625fe2519ae_Synthetic_Bean.create(Unknown Source)
at io.opentelemetry.api.OpenTelemetry_2deeb341bce4a230183bf3a228841625fe2519ae_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:32)
at io.quarkus.arc.impl.ComputingCache.computeIfAbsent(ComputingCache.java:69)
at io.quarkus.arc.impl.AbstractSharedContext.get(AbstractSharedContext.java:34)
at io.opentelemetry.api.OpenTelemetry_2deeb341bce4a230183bf3a228841625fe2519ae_Synthetic_Bean.get(Unknown Source)
at io.opentelemetry.api.OpenTelemetry_2deeb341bce4a230183bf3a228841625fe2519ae_Synthetic_Bean.get(Unknown Source)
at io.quarkus.arc.impl.ArcContainerImpl.beanInstanceHandle(ArcContainerImpl.java:557)
at io.quarkus.arc.impl.ArcContainerImpl.beanInstanceHandle(ArcContainerImpl.java:537)
at io.quarkus.arc.impl.ArcContainerImpl.beanInstanceHandle(ArcContainerImpl.java:570)
at io.quarkus.arc.impl.ArcContainerImpl.instanceHandle(ArcContainerImpl.java:532)
at io.quarkus.arc.impl.ArcContainerImpl.instance(ArcContainerImpl.java:279)
at io.quarkus.agroal.runtime.OpenTelemetryAgroalDataSource.<init>(OpenTelemetryAgroalDataSource.java:24)
at io.quarkus.agroal.runtime.AgroalOpenTelemetryWrapper.apply(AgroalOpenTelemetryWrapper.java:11)
at io.quarkus.agroal.runtime.DataSources.doCreateDataSource(DataSources.java:263)
at io.quarkus.agroal.runtime.DataSources$1.apply(DataSources.java:126)
at io.quarkus.agroal.runtime.DataSources$1.apply(DataSources.java:123)
at java.base/java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1708)
at io.quarkus.agroal.runtime.DataSources.getDataSource(DataSources.java:123)
at io.quarkus.agroal.runtime.DataSources.fromName(DataSources.java:119)
at io.quarkus.liquibase.runtime.LiquibaseRecorder.liquibaseFunction(LiquibaseRecorder.java:32)
at io.quarkus.deployment.steps.LiquibaseProcessor$createBeans1097260187.deploy_0(Unknown Source)
at io.quarkus.deployment.steps.LiquibaseProcessor$createBeans1097260187.deploy(Unknown Source)
... 53 more
```
PS: OTEL is active for tests, but OTLP export is off.
### Expected behavior
Boot error
### Actual behavior
Test should still be running ok
### How to Reproduce?
[q_otel-jdbc.zip](https://github.com/quarkusio/quarkus/files/12315665/q_otel-jdbc.zip)
### 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
3.3.0.CR1
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
_No response_
### Additional information
Maybe related to #34545 @geoand? | 9c73946d31063f5ffdf59b41d7fe0a432f36a798 | ec04931ef0f298f1f5e24491c3940d63879ba0e5 | https://github.com/quarkusio/quarkus/compare/9c73946d31063f5ffdf59b41d7fe0a432f36a798...ec04931ef0f298f1f5e24491c3940d63879ba0e5 | diff --git a/extensions/agroal/runtime/src/main/java/io/quarkus/agroal/runtime/DataSources.java b/extensions/agroal/runtime/src/main/java/io/quarkus/agroal/runtime/DataSources.java
index bff38eee02e..341e2cca199 100644
--- a/extensions/agroal/runtime/src/main/java/io/quarkus/agroal/runtime/DataSources.java
+++ b/extensions/agroal/runtime/src/main/java/io/quarkus/agroal/runtime/DataSources.java
@@ -113,7 +113,10 @@ public DataSources(DataSourcesBuildTimeConfig dataSourcesBuildTimeConfig,
* (which makes sense because {@code DataSource} is a {@code Singleton} bean).
* <p>
* This method is thread-safe
+ *
+ * @deprecated This method should not be used as it can very easily lead to timing issues during bean creation
*/
+ @Deprecated
public static AgroalDataSource fromName(String dataSourceName) {
return Arc.container().instance(DataSources.class).get()
.getDataSource(dataSourceName);
diff --git a/extensions/flyway/deployment/src/main/java/io/quarkus/flyway/FlywayProcessor.java b/extensions/flyway/deployment/src/main/java/io/quarkus/flyway/FlywayProcessor.java
index 412b185a89f..1fb06fce2b9 100644
--- a/extensions/flyway/deployment/src/main/java/io/quarkus/flyway/FlywayProcessor.java
+++ b/extensions/flyway/deployment/src/main/java/io/quarkus/flyway/FlywayProcessor.java
@@ -18,18 +18,21 @@
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import jakarta.enterprise.context.Dependent;
import jakarta.enterprise.inject.Default;
+import jakarta.inject.Singleton;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.Location;
import org.flywaydb.core.api.callback.Callback;
import org.flywaydb.core.api.migration.JavaMigration;
import org.flywaydb.core.extensibility.Plugin;
+import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
+import org.jboss.jandex.ClassType;
import org.jboss.jandex.DotName;
import org.jboss.logging.Logger;
+import io.quarkus.agroal.runtime.DataSources;
import io.quarkus.agroal.spi.JdbcDataSourceBuildItem;
import io.quarkus.agroal.spi.JdbcDataSourceSchemaReadyBuildItem;
import io.quarkus.agroal.spi.JdbcInitialSQLGeneratorBuildItem;
@@ -62,6 +65,7 @@
import io.quarkus.deployment.logging.LoggingSetupBuildItem;
import io.quarkus.deployment.recording.RecorderContext;
import io.quarkus.flyway.runtime.FlywayBuildTimeConfig;
+import io.quarkus.flyway.runtime.FlywayContainer;
import io.quarkus.flyway.runtime.FlywayContainerProducer;
import io.quarkus.flyway.runtime.FlywayRecorder;
import io.quarkus.flyway.runtime.FlywayRuntimeConfig;
@@ -71,6 +75,7 @@ class FlywayProcessor {
private static final String CLASSPATH_APPLICATION_MIGRATIONS_PROTOCOL = "classpath";
+ private static final String FLYWAY_CONTAINER_BEAN_NAME_PREFIX = "flyway_container_";
private static final String FLYWAY_BEAN_NAME_PREFIX = "flyway_";
private static final DotName JAVA_MIGRATION = DotName.createSimple(JavaMigration.class.getName());
@@ -172,8 +177,6 @@ void createBeans(FlywayRecorder recorder,
// add the @FlywayDataSource class otherwise it won't be registered as a qualifier
additionalBeans.produce(AdditionalBeanBuildItem.builder().addBeanClass(FlywayDataSource.class).build());
- recorder.resetFlywayContainers();
-
Collection<String> dataSourceNames = getDataSourceNames(jdbcDataSourceBuildItems);
for (String dataSourceName : dataSourceNames) {
@@ -182,25 +185,62 @@ void createBeans(FlywayRecorder recorder,
if (!hasMigrations) {
createPossible = sqlGeneratorBuildItems.stream().anyMatch(s -> s.getDatabaseName().equals(dataSourceName));
}
- SyntheticBeanBuildItem.ExtendedBeanConfigurator configurator = SyntheticBeanBuildItem
+
+ SyntheticBeanBuildItem.ExtendedBeanConfigurator flywayContainerConfigurator = SyntheticBeanBuildItem
+ .configure(FlywayContainer.class)
+ .scope(Singleton.class)
+ .setRuntimeInit()
+ .unremovable()
+ .addInjectionPoint(ClassType.create(DotName.createSimple(FlywayContainerProducer.class)))
+ .addInjectionPoint(ClassType.create(DotName.createSimple(DataSources.class)))
+ .createWith(recorder.flywayContainerFunction(dataSourceName, hasMigrations, createPossible));
+
+ AnnotationInstance flywayContainerQualifier;
+
+ if (DataSourceUtil.isDefault(dataSourceName)) {
+ flywayContainerConfigurator.addQualifier(Default.class);
+
+ // Flyway containers used to be ordered with the default database coming first.
+ // Some multitenant tests are relying on this order.
+ flywayContainerConfigurator.priority(10);
+
+ flywayContainerQualifier = AnnotationInstance.builder(Default.class).build();
+ } else {
+ String beanName = FLYWAY_CONTAINER_BEAN_NAME_PREFIX + dataSourceName;
+ flywayContainerConfigurator.name(beanName);
+
+ flywayContainerConfigurator.addQualifier().annotation(DotNames.NAMED).addValue("value", beanName).done();
+ flywayContainerConfigurator.addQualifier().annotation(FlywayDataSource.class).addValue("value", dataSourceName)
+ .done();
+ flywayContainerConfigurator.priority(5);
+
+ flywayContainerQualifier = AnnotationInstance.builder(FlywayDataSource.class).add("value", dataSourceName)
+ .build();
+ }
+
+ syntheticBeanBuildItemBuildProducer.produce(flywayContainerConfigurator.done());
+
+ SyntheticBeanBuildItem.ExtendedBeanConfigurator flywayConfigurator = SyntheticBeanBuildItem
.configure(Flyway.class)
- .scope(Dependent.class) // this is what the existing code does, but it doesn't seem reasonable
+ .scope(Singleton.class)
.setRuntimeInit()
.unremovable()
- .supplier(recorder.flywaySupplier(dataSourceName,
- hasMigrations, createPossible));
+ .addInjectionPoint(ClassType.create(DotName.createSimple(FlywayContainer.class)), flywayContainerQualifier)
+ .createWith(recorder.flywayFunction(dataSourceName));
if (DataSourceUtil.isDefault(dataSourceName)) {
- configurator.addQualifier(Default.class);
+ flywayConfigurator.addQualifier(Default.class);
+ flywayConfigurator.priority(10);
} else {
String beanName = FLYWAY_BEAN_NAME_PREFIX + dataSourceName;
- configurator.name(beanName);
+ flywayConfigurator.name(beanName);
+ flywayConfigurator.priority(5);
- configurator.addQualifier().annotation(DotNames.NAMED).addValue("value", beanName).done();
- configurator.addQualifier().annotation(FlywayDataSource.class).addValue("value", dataSourceName).done();
+ flywayConfigurator.addQualifier().annotation(DotNames.NAMED).addValue("value", beanName).done();
+ flywayConfigurator.addQualifier().annotation(FlywayDataSource.class).addValue("value", dataSourceName).done();
}
- syntheticBeanBuildItemBuildProducer.produce(configurator.done());
+ syntheticBeanBuildItemBuildProducer.produce(flywayConfigurator.done());
}
}
diff --git a/extensions/flyway/runtime/src/main/java/io/quarkus/flyway/runtime/FlywayContainersSupplier.java b/extensions/flyway/runtime/src/main/java/io/quarkus/flyway/runtime/FlywayContainersSupplier.java
index 47537af91e9..11261c88c30 100644
--- a/extensions/flyway/runtime/src/main/java/io/quarkus/flyway/runtime/FlywayContainersSupplier.java
+++ b/extensions/flyway/runtime/src/main/java/io/quarkus/flyway/runtime/FlywayContainersSupplier.java
@@ -1,24 +1,30 @@
package io.quarkus.flyway.runtime;
import java.util.Collection;
-import java.util.Collections;
import java.util.Comparator;
+import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Supplier;
+import io.quarkus.arc.Arc;
+import io.quarkus.arc.InstanceHandle;
import io.quarkus.datasource.common.runtime.DataSourceUtil;
public class FlywayContainersSupplier implements Supplier<Collection<FlywayContainer>> {
@Override
public Collection<FlywayContainer> get() {
- if (FlywayRecorder.FLYWAY_CONTAINERS.isEmpty()) {
- return Collections.emptySet();
+ List<InstanceHandle<FlywayContainer>> flywayContainerHandles = Arc.container().listAll(FlywayContainer.class);
+
+ if (flywayContainerHandles.isEmpty()) {
+ return Set.of();
}
Set<FlywayContainer> containers = new TreeSet<>(FlywayContainerComparator.INSTANCE);
- containers.addAll(FlywayRecorder.FLYWAY_CONTAINERS);
+ for (InstanceHandle<FlywayContainer> flywayContainerHandle : flywayContainerHandles) {
+ containers.add(flywayContainerHandle.get());
+ }
return containers;
}
diff --git a/extensions/flyway/runtime/src/main/java/io/quarkus/flyway/runtime/FlywayRecorder.java b/extensions/flyway/runtime/src/main/java/io/quarkus/flyway/runtime/FlywayRecorder.java
index 94c7919fe46..2b0f724a9a1 100644
--- a/extensions/flyway/runtime/src/main/java/io/quarkus/flyway/runtime/FlywayRecorder.java
+++ b/extensions/flyway/runtime/src/main/java/io/quarkus/flyway/runtime/FlywayRecorder.java
@@ -1,13 +1,13 @@
package io.quarkus.flyway.runtime;
-import java.util.ArrayList;
+import java.lang.annotation.Annotation;
import java.util.Collection;
-import java.util.List;
import java.util.Map;
-import java.util.function.Supplier;
+import java.util.function.Function;
import javax.sql.DataSource;
+import jakarta.enterprise.inject.Default;
import jakarta.enterprise.inject.UnsatisfiedResolutionException;
import org.flywaydb.core.Flyway;
@@ -18,6 +18,10 @@
import io.quarkus.agroal.runtime.DataSources;
import io.quarkus.agroal.runtime.UnconfiguredDataSource;
import io.quarkus.arc.Arc;
+import io.quarkus.arc.InstanceHandle;
+import io.quarkus.arc.SyntheticCreationalContext;
+import io.quarkus.datasource.common.runtime.DataSourceUtil;
+import io.quarkus.flyway.FlywayDataSource.FlywayDataSourceLiteral;
import io.quarkus.runtime.RuntimeValue;
import io.quarkus.runtime.annotations.Recorder;
@@ -26,8 +30,6 @@ public class FlywayRecorder {
private static final Logger log = Logger.getLogger(FlywayRecorder.class);
- static final List<FlywayContainer> FLYWAY_CONTAINERS = new ArrayList<>(2);
-
private final RuntimeValue<FlywayRuntimeConfig> config;
public FlywayRecorder(RuntimeValue<FlywayRuntimeConfig> config) {
@@ -49,27 +51,37 @@ public void setApplicationCallbackClasses(Map<String, Collection<Callback>> call
QuarkusPathLocationScanner.setApplicationCallbackClasses(callbackClasses);
}
- public void resetFlywayContainers() {
- FLYWAY_CONTAINERS.clear();
- }
-
- public Supplier<Flyway> flywaySupplier(String dataSourceName, boolean hasMigrations, boolean createPossible) {
- DataSource dataSource = DataSources.fromName(dataSourceName);
- if (dataSource instanceof UnconfiguredDataSource) {
- return new Supplier<Flyway>() {
- @Override
- public Flyway get() {
+ public Function<SyntheticCreationalContext<FlywayContainer>, FlywayContainer> flywayContainerFunction(String dataSourceName,
+ boolean hasMigrations,
+ boolean createPossible) {
+ return new Function<>() {
+ @Override
+ public FlywayContainer apply(SyntheticCreationalContext<FlywayContainer> context) {
+ DataSource dataSource = context.getInjectedReference(DataSources.class).getDataSource(dataSourceName);
+ if (dataSource instanceof UnconfiguredDataSource) {
throw new UnsatisfiedResolutionException("No datasource present");
}
- };
- }
- FlywayContainerProducer flywayProducer = Arc.container().instance(FlywayContainerProducer.class).get();
- FlywayContainer flywayContainer = flywayProducer.createFlyway(dataSource, dataSourceName, hasMigrations,
- createPossible);
- FLYWAY_CONTAINERS.add(flywayContainer);
- return new Supplier<Flyway>() {
+
+ FlywayContainerProducer flywayProducer = context.getInjectedReference(FlywayContainerProducer.class);
+ FlywayContainer flywayContainer = flywayProducer.createFlyway(dataSource, dataSourceName, hasMigrations,
+ createPossible);
+ return flywayContainer;
+ }
+ };
+ }
+
+ public Function<SyntheticCreationalContext<Flyway>, Flyway> flywayFunction(String dataSourceName) {
+ return new Function<>() {
@Override
- public Flyway get() {
+ public Flyway apply(SyntheticCreationalContext<Flyway> context) {
+ Annotation flywayContainerQualifier;
+ if (DataSourceUtil.isDefault(dataSourceName)) {
+ flywayContainerQualifier = Default.Literal.INSTANCE;
+ } else {
+ flywayContainerQualifier = FlywayDataSourceLiteral.of(dataSourceName);
+ }
+
+ FlywayContainer flywayContainer = context.getInjectedReference(FlywayContainer.class, flywayContainerQualifier);
return flywayContainer.getFlyway();
}
};
@@ -79,7 +91,10 @@ public void doStartActions() {
if (!config.getValue().enabled) {
return;
}
- for (FlywayContainer flywayContainer : FLYWAY_CONTAINERS) {
+
+ for (InstanceHandle<FlywayContainer> flywayContainerHandle : Arc.container().listAll(FlywayContainer.class)) {
+ FlywayContainer flywayContainer = flywayContainerHandle.get();
+
if (flywayContainer.isCleanAtStart()) {
flywayContainer.getFlyway().clean();
}
diff --git a/extensions/flyway/runtime/src/main/java/io/quarkus/flyway/runtime/FlywaySchemaProvider.java b/extensions/flyway/runtime/src/main/java/io/quarkus/flyway/runtime/FlywaySchemaProvider.java
index b5026a133c9..57dab412c16 100644
--- a/extensions/flyway/runtime/src/main/java/io/quarkus/flyway/runtime/FlywaySchemaProvider.java
+++ b/extensions/flyway/runtime/src/main/java/io/quarkus/flyway/runtime/FlywaySchemaProvider.java
@@ -1,23 +1,25 @@
package io.quarkus.flyway.runtime;
+import io.quarkus.arc.Arc;
import io.quarkus.datasource.runtime.DatabaseSchemaProvider;
public class FlywaySchemaProvider implements DatabaseSchemaProvider {
+
@Override
public void resetDatabase(String dbName) {
- for (FlywayContainer i : FlywayRecorder.FLYWAY_CONTAINERS) {
- if (i.getDataSourceName().equals(dbName)) {
- i.getFlyway().clean();
- i.getFlyway().migrate();
+ for (FlywayContainer flywayContainer : Arc.container().select(FlywayContainer.class)) {
+ if (flywayContainer.getDataSourceName().equals(dbName)) {
+ flywayContainer.getFlyway().clean();
+ flywayContainer.getFlyway().migrate();
}
}
}
@Override
public void resetAllDatabases() {
- for (FlywayContainer i : FlywayRecorder.FLYWAY_CONTAINERS) {
- i.getFlyway().clean();
- i.getFlyway().migrate();
+ for (FlywayContainer flywayContainer : Arc.container().select(FlywayContainer.class)) {
+ flywayContainer.getFlyway().clean();
+ flywayContainer.getFlyway().migrate();
}
}
}
diff --git a/extensions/liquibase/deployment/src/main/java/io/quarkus/liquibase/deployment/LiquibaseProcessor.java b/extensions/liquibase/deployment/src/main/java/io/quarkus/liquibase/deployment/LiquibaseProcessor.java
index 33188df5e78..4d6c65e2b30 100644
--- a/extensions/liquibase/deployment/src/main/java/io/quarkus/liquibase/deployment/LiquibaseProcessor.java
+++ b/extensions/liquibase/deployment/src/main/java/io/quarkus/liquibase/deployment/LiquibaseProcessor.java
@@ -28,6 +28,7 @@
import org.jboss.jandex.DotName;
import org.jboss.logging.Logger;
+import io.quarkus.agroal.runtime.DataSources;
import io.quarkus.agroal.spi.JdbcDataSourceBuildItem;
import io.quarkus.agroal.spi.JdbcDataSourceSchemaReadyBuildItem;
import io.quarkus.arc.deployment.AdditionalBeanBuildItem;
@@ -285,6 +286,7 @@ void createBeans(LiquibaseRecorder recorder,
.setRuntimeInit()
.unremovable()
.addInjectionPoint(ClassType.create(DotName.createSimple(LiquibaseFactoryProducer.class)))
+ .addInjectionPoint(ClassType.create(DotName.createSimple(DataSources.class)))
.createWith(recorder.liquibaseFunction(dataSourceName));
if (DataSourceUtil.isDefault(dataSourceName)) {
diff --git a/extensions/liquibase/runtime/src/main/java/io/quarkus/liquibase/runtime/LiquibaseRecorder.java b/extensions/liquibase/runtime/src/main/java/io/quarkus/liquibase/runtime/LiquibaseRecorder.java
index 2b9429b73d5..d85785d61e3 100644
--- a/extensions/liquibase/runtime/src/main/java/io/quarkus/liquibase/runtime/LiquibaseRecorder.java
+++ b/extensions/liquibase/runtime/src/main/java/io/quarkus/liquibase/runtime/LiquibaseRecorder.java
@@ -29,21 +29,16 @@ public LiquibaseRecorder(RuntimeValue<LiquibaseRuntimeConfig> config) {
}
public Function<SyntheticCreationalContext<LiquibaseFactory>, LiquibaseFactory> liquibaseFunction(String dataSourceName) {
- DataSource dataSource = DataSources.fromName(dataSourceName);
- if (dataSource instanceof UnconfiguredDataSource) {
- return new Function<SyntheticCreationalContext<LiquibaseFactory>, LiquibaseFactory>() {
- @Override
- public LiquibaseFactory apply(SyntheticCreationalContext<LiquibaseFactory> context) {
- throw new UnsatisfiedResolutionException("No datasource has been configured");
- }
- };
- }
return new Function<SyntheticCreationalContext<LiquibaseFactory>, LiquibaseFactory>() {
@Override
public LiquibaseFactory apply(SyntheticCreationalContext<LiquibaseFactory> context) {
+ DataSource dataSource = context.getInjectedReference(DataSources.class).getDataSource(dataSourceName);
+ if (dataSource instanceof UnconfiguredDataSource) {
+ throw new UnsatisfiedResolutionException("No datasource has been configured");
+ }
+
LiquibaseFactoryProducer liquibaseProducer = context.getInjectedReference(LiquibaseFactoryProducer.class);
- LiquibaseFactory liquibaseFactory = liquibaseProducer.createLiquibaseFactory(dataSource, dataSourceName);
- return liquibaseFactory;
+ return liquibaseProducer.createLiquibaseFactory(dataSource, dataSourceName);
}
};
} | ['extensions/flyway/runtime/src/main/java/io/quarkus/flyway/runtime/FlywayRecorder.java', 'extensions/liquibase/runtime/src/main/java/io/quarkus/liquibase/runtime/LiquibaseRecorder.java', 'extensions/liquibase/deployment/src/main/java/io/quarkus/liquibase/deployment/LiquibaseProcessor.java', 'extensions/flyway/runtime/src/main/java/io/quarkus/flyway/runtime/FlywaySchemaProvider.java', 'extensions/agroal/runtime/src/main/java/io/quarkus/agroal/runtime/DataSources.java', 'extensions/flyway/deployment/src/main/java/io/quarkus/flyway/FlywayProcessor.java', 'extensions/flyway/runtime/src/main/java/io/quarkus/flyway/runtime/FlywayContainersSupplier.java'] | {'.java': 7} | 7 | 7 | 0 | 0 | 7 | 27,413,587 | 5,408,613 | 695,453 | 6,387 | 10,085 | 1,887 | 179 | 7 | 4,058 | 245 | 1,081 | 75 | 1 | 1 | 2023-08-10T18:38:14 | 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,119 | quarkusio/quarkus/35350/35348 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/35348 | https://github.com/quarkusio/quarkus/pull/35350 | https://github.com/quarkusio/quarkus/pull/35350 | 1 | fix | quarkus-maven-plugin runs native building even if the profile is commented out | ### Describe the bug
It comes across
- https://github.com/apache/camel-quarkus/issues/5180
The `native` profile is commented out but quarkus build is still running the graal native build. After investigating, it seems related to https://github.com/quarkusio/quarkus/blob/3747c0d85b68ca33b58871d9cf3b2d4b3bb304a4/devtools/maven/src/main/java/io/quarkus/maven/BuildMojo.java#L121-L123
I think it should check `setPackageTypeSystemPropertyIfNativeProfileEnabled` is **true**.
### Expected behavior
No running the native build.
### Actual behavior
The native build is still running.
### 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
3.2.4.Final
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
_No response_
### Additional information
_No response_ | 42cd3eac552ee5102033f7f7de7acc3ec90a75d3 | 690244bdf81355dbe88820311837e3f5ee26512c | https://github.com/quarkusio/quarkus/compare/42cd3eac552ee5102033f7f7de7acc3ec90a75d3...690244bdf81355dbe88820311837e3f5ee26512c | diff --git a/devtools/maven/src/main/java/io/quarkus/maven/BuildMojo.java b/devtools/maven/src/main/java/io/quarkus/maven/BuildMojo.java
index 0c7146ddb16..fefb7457970 100644
--- a/devtools/maven/src/main/java/io/quarkus/maven/BuildMojo.java
+++ b/devtools/maven/src/main/java/io/quarkus/maven/BuildMojo.java
@@ -118,7 +118,7 @@ protected void doExecute() throws MojoExecutionException {
// Essentially what this does is to enable the native package type even if a different package type is set
// in application properties. This is done to preserve what users expect to happen when
// they execute "mvn package -Dnative" even if quarkus.package.type has been set in application.properties
- if (!setPackageTypeSystemPropertyIfNativeProfileEnabled()) {
+ if (setPackageTypeSystemPropertyIfNativeProfileEnabled()) {
propertiesToClear.add(PACKAGE_TYPE_PROP);
}
diff --git a/devtools/maven/src/main/java/io/quarkus/maven/TrackConfigChangesMojo.java b/devtools/maven/src/main/java/io/quarkus/maven/TrackConfigChangesMojo.java
index e721cf89e80..b8b43e94db0 100644
--- a/devtools/maven/src/main/java/io/quarkus/maven/TrackConfigChangesMojo.java
+++ b/devtools/maven/src/main/java/io/quarkus/maven/TrackConfigChangesMojo.java
@@ -132,7 +132,9 @@ protected void doExecute() throws MojoExecutionException, MojoFailureException {
} catch (Exception any) {
throw new MojoExecutionException("Failed to bootstrap Quarkus application", any);
} finally {
- System.clearProperty(PACKAGE_TYPE_PROP);
+ if (clearPackageTypeSystemProperty) {
+ System.clearProperty(PACKAGE_TYPE_PROP);
+ }
Thread.currentThread().setContextClassLoader(originalCl);
if (deploymentClassLoader != null) {
deploymentClassLoader.close(); | ['devtools/maven/src/main/java/io/quarkus/maven/BuildMojo.java', 'devtools/maven/src/main/java/io/quarkus/maven/TrackConfigChangesMojo.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 27,441,087 | 5,414,176 | 696,009 | 6,389 | 323 | 60 | 6 | 2 | 962 | 113 | 259 | 44 | 2 | 0 | 2023-08-15T06:50:40 | 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,118 | quarkusio/quarkus/35396/35344 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/35344 | https://github.com/quarkusio/quarkus/pull/35396 | https://github.com/quarkusio/quarkus/pull/35396 | 1 | fix | ResteasyReactiveRuntimeRecorder throws ClassCastException when deployed on Openshift | ### Describe the bug
Related to PR #35246
When deploying RestEasy Reactive application to Openshift, it will fail on ResteasyReactiveRuntimeRecorder's ClassCastException (see stack trace below).
```
15:47:36,238 INFO [app] 13:47:35,438 Failed to start application (with profile [OpenShiftCompressionHandlerIT]): java.lang.RuntimeException: Failed to start quarkus
15:47:36,238 INFO [app] at io.quarkus.runner.ApplicationImpl.doStart(Unknown Source)
15:47:36,238 INFO [app] at io.quarkus.runtime.Application.start(Application.java:101)
15:47:36,238 INFO [app] at io.quarkus.runtime.ApplicationLifecycleManager.run(ApplicationLifecycleManager.java:111)
15:47:36,238 INFO [app] at io.quarkus.runtime.Quarkus.run(Quarkus.java:71)
15:47:36,238 INFO [app] at io.quarkus.runtime.Quarkus.run(Quarkus.java:44)
15:47:36,238 INFO [app] at io.quarkus.runtime.Quarkus.run(Quarkus.java:124)
15:47:36,239 INFO [app] at io.quarkus.runner.GeneratedMain.main(Unknown Source)
15:47:36,239 INFO [app] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
15:47:36,239 INFO [app] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
15:47:36,239 INFO [app] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
15:47:36,239 INFO [app] at java.base/java.lang.reflect.Method.invoke(Method.java:568)
15:47:36,239 INFO [app] at io.quarkus.bootstrap.runner.QuarkusEntryPoint.doRun(QuarkusEntryPoint.java:61)
15:47:36,239 INFO [app] at io.quarkus.bootstrap.runner.QuarkusEntryPoint.main(QuarkusEntryPoint.java:32)
15:47:36,239 INFO [app] Caused by: java.lang.ClassCastException: class java.lang.String cannot be cast to class java.util.List (java.lang.String and java.util.List are in module java.base of loader 'bootstrap')
15:47:36,239 INFO [app] at io.quarkus.resteasy.reactive.server.runtime.ResteasyReactiveRuntimeRecorder.runtimeConfiguration(ResteasyReactiveRuntimeRecorder.java:38)
15:47:36,240 INFO [app] at io.quarkus.deployment.steps.ResteasyReactiveProcessor$runtimeConfiguration1462480334.deploy_0(Unknown Source)
15:47:36,240 INFO [app] at io.quarkus.deployment.steps.ResteasyReactiveProcessor$runtimeConfiguration1462480334.deploy(Unknown Source)
15:47:36,240 INFO [app] ... 13 more
```
Seems like issue is on [this line](https://github.com/quarkusio/quarkus/blob/42cd3eac552ee5102033f7f7de7acc3ec90a75d3/extensions/resteasy-reactive/quarkus-resteasy-reactive/runtime/src/main/java/io/quarkus/resteasy/reactive/server/runtime/ResteasyReactiveRuntimeRecorder.java#L38). Somehow produces `String` ,while expected is `List<String>`.
Reverting #35246 fixes this issue.
### Expected behavior
RestEasy Reactive application will deploy
### Actual behavior
RestEasy Reactive application fails to deploy, with above-mention exception.
### 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_ | 31d78a602f772abe53a79eb3bdd65208196a9e3c | 857abbe148b023590a95fd4ed257c6148a81773b | https://github.com/quarkusio/quarkus/compare/31d78a602f772abe53a79eb3bdd65208196a9e3c...857abbe148b023590a95fd4ed257c6148a81773b | diff --git a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/multipart/MultipartInputWithAllUploadsTest.java b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/multipart/MultipartInputWithAllUploadsTest.java
index c9529c094e8..43ff48cba36 100644
--- a/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/multipart/MultipartInputWithAllUploadsTest.java
+++ b/extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/multipart/MultipartInputWithAllUploadsTest.java
@@ -35,8 +35,11 @@ public JavaArchive get() {
Status.class, MultipartResourceWithAllUploads.class)
.addAsResource(new StringAsset(
// keep the files around so we can assert the outcome
- "quarkus.http.body.delete-uploaded-files-on-end=false\\nquarkus.http.body.uploads-directory="
- + uploadDir.toString() + "\\n"),
+ "quarkus.http.body.delete-uploaded-files-on-end=false\\n"
+ + "quarkus.http.body.uploads-directory=" + uploadDir.toString() + "\\n"
+ // to reproduce https://github.com/quarkusio/quarkus/issues/35344:
+ + "quarkus.http.body.multipart.file-content-types=text/xml,custom/content-type"
+ + "\\n"),
"application.properties");
}
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 588b2cf7407..dc6981d8d7a 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
@@ -19,6 +19,5 @@ public interface MultiPartConfig {
*
* For now, this setting only works when using RESTEasy Reactive.
*/
- @WithConverter(TrimmedStringConverter.class)
- Optional<List<String>> fileContentTypes();
+ Optional<List<@WithConverter(TrimmedStringConverter.class) String>> fileContentTypes();
} | ['extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/MultiPartConfig.java', 'extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/multipart/MultipartInputWithAllUploadsTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 27,447,781 | 5,415,682 | 696,253 | 6,390 | 190 | 40 | 3 | 1 | 3,285 | 254 | 914 | 65 | 1 | 1 | 2023-08-17T10:57: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,117 | quarkusio/quarkus/6129/6091 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/6091 | https://github.com/quarkusio/quarkus/pull/6129 | https://github.com/quarkusio/quarkus/pull/6129#issuecomment-564812529 | 1 | fixes | mvn quarkus:dev freezes in a project with bidirectional JPA relationships | **Describe the bug**
Having the following entities in a Quarkus app makes `mvn compile quarkus:dev` freeze:
```java
@Entity
@Table(name = "owners")
public class Owner {
@OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
private Set<Pet> pets;
public Set<Pet> getPets() {
return pets;
}
public void setPets(Set<Pet> pets) {
this.pets = pets;
}
}
```
And
```java
@Entity
@Table(name = "pets")
public class Pet {
@ManyToOne
@JoinColumn(name = "owner_id")
private Owner owner;
public Owner getOwner() {
return owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
}
```
**Expected behavior**
Application should run
**Actual behavior**
Application is frozen. This is the output of jstack:
```java
"main" #1 prio=5 os_prio=0 tid=0x00007f65d400d800 nid=0x24228 waiting on condition [0x00007f65db60a000]
java.lang.Thread.State: WAITING (parking)
at sun.misc.Unsafe.park(Native Method)
- parking to wait for <0x0000000726b33bc0> (a java.util.concurrent.CompletableFuture$Signaller)
at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
at java.util.concurrent.CompletableFuture$Signaller.block(CompletableFuture.java:1707)
at java.util.concurrent.ForkJoinPool.managedBlock(ForkJoinPool.java:3323)
at java.util.concurrent.CompletableFuture.waitingGet(CompletableFuture.java:1742)
at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1908)
at io.quarkus.runner.RuntimeClassLoader.findClass(RuntimeClassLoader.java:214)
at io.quarkus.runner.RuntimeClassLoader.loadClass(RuntimeClassLoader.java:179)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.objectweb.asm.ClassWriter.getCommonSuperClass(ClassWriter.java:935)
at org.objectweb.asm.SymbolTable.addMergedType(SymbolTable.java:1200)
at org.objectweb.asm.Frame.merge(Frame.java:1299)
at org.objectweb.asm.Frame.merge(Frame.java:1197)
at org.objectweb.asm.MethodWriter.computeAllFrames(MethodWriter.java:1607)
at org.objectweb.asm.MethodWriter.visitMaxs(MethodWriter.java:1543)
at org.objectweb.asm.ClassReader.readCode(ClassReader.java:2431)
at org.objectweb.asm.ClassReader.readThis is causeMethod(ClassReader.java:1283)
at org.objectweb.asm.ClassReader.accept(ClassReader.java:688)
at org.objectweb.asm.ClassReader.accept(ClassReader.java:400)
at io.quarkus.hibernate.orm.deployment.HibernateEntityEnhancer$HibernateEnhancingClassVisitor.visitEnd(HibernateEntityEnhancer.java:67)
at org.objectweb.asm.ClassReader.accept(ClassReader.java:692)
at org.objectweb.asm.ClassReader.accept(ClassReader.java:400)
at io.quarkus.runner.RuntimeClassLoader.handleTransform(RuntimeClassLoader.java:430)
at io.quarkus.runner.RuntimeClassLoader.findClass(RuntimeClassLoader.java:225)
at io.quarkus.runner.RuntimeClassLoader.loadClass(RuntimeClassLoader.java:179)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at io.quarkus.hibernate.orm.runtime.service.FlatClassLoaderService.classForName(FlatClassLoaderService.java:36)
at org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl.<init>(AnnotationMetadataSourceProcessorImpl.java:109)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess$1.<init>(MetadataBuildingProcess.java:155)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:149)
at io.quarkus.hibernate.orm.runtime.boot.FastBootMetadataBuilder.build(FastBootMetadataBuilder.java:342)
at io.quarkus.hibernate.orm.runtime.PersistenceUnitsHolder.createMetadata(PersistenceUnitsHolder.java:111)
at io.quarkus.hibernate.orm.runtime.PersistenceUnitsHolder.constructMetadataAdvance(PersistenceUnitsHolder.java:84)
at io.quarkus.hibernate.orm.runtime.PersistenceUnitsHolder.initializeJpa(PersistenceUnitsHolder.java:47)
at io.quarkus.hibernate.orm.runtime.HibernateOrmRecorder$4.created(HibernateOrmRecorder.java:75)
at io.quarkus.arc.runtime.ArcRecorder.initBeanContainer(ArcRecorder.java:101)
at io.quarkus.deployment.steps.ArcProcessor$generateResources25.deploy_0(ArcProcessor$generateResources25.zig:406)
at io.quarkus.deployment.steps.ArcProcessor$generateResources25.deploy(ArcProcessor$generateResources25.zig:36)
at io.quarkus.runner.ApplicationImpl.<clinit>(ApplicationImpl.zig:378)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at io.quarkus.runner.RuntimeRunner.run(RuntimeRunner.java:152)
at io.quarkus.dev.DevModeMain.doStart(DevModeMain.java:178)
- locked <0x00000005d3e2ea78> (a io.quarkus.dev.DevModeMain)
at io.quarkus.dev.DevModeMain.start(DevModeMain.java:96)
at io.quarkus.dev.DevModeMain.main(DevModeMain.java:67)
```
**To Reproduce**
Steps to reproduce the behavior:
1. Unzip the project in [jpa-example.zip](https://github.com/quarkusio/quarkus/files/3948053/jpa-example.zip)
2. run `mvn compile quarkus:dev`
3. Output should freeze after the following output is displayed:
```
[INFO] Launching JVM with command line: /home/ggastald/.sdkman/candidates/java/8.0.232-open/jre/bin/java -XX:TieredStopAtLevel=1 -Xverify:none -Xdebug -Xrunjdwp:transport=dt_socket,address=5005,server=y,suspend=n -Djava.util.logging.manager=org.jboss.logmanager.LogManager -jar /tmp/jpa-example/target/jpa-example-dev.jar
```
**Environment (please complete the following information):**
- Output of `uname -a` or `ver`: `Linux ggastald-laptop 5.3.14-300.fc31.x86_64 #1 SMP Mon Dec 2 15:41:35 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux`
- Output of `java -version`:
```
openjdk version "1.8.0_232"
OpenJDK Runtime Environment (build 1.8.0_232-b09)
OpenJDK 64-Bit Server VM (build 25.232-b09, mixed mode)
```
- GraalVM version (if different from Java): Not used
- Quarkus version or git rev: 1.1.0.CR1
**Additional context**
Look at the jstack output to find where the problem is. HINT: recursion in RuntimeClassloader
| e6ae706a6a53f13e3fd41c99af4076100c3ef456 | c17aa16649bbe930994456a8098e8b40374a338d | https://github.com/quarkusio/quarkus/compare/e6ae706a6a53f13e3fd41c99af4076100c3ef456...c17aa16649bbe930994456a8098e8b40374a338d | diff --git a/core/deployment/src/main/java/io/quarkus/runner/RuntimeClassLoader.java b/core/deployment/src/main/java/io/quarkus/runner/RuntimeClassLoader.java
index c323f8ba4de..cc07cb92f26 100644
--- a/core/deployment/src/main/java/io/quarkus/runner/RuntimeClassLoader.java
+++ b/core/deployment/src/main/java/io/quarkus/runner/RuntimeClassLoader.java
@@ -32,7 +32,6 @@
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiFunction;
import java.util.function.Consumer;
@@ -44,7 +43,6 @@
import org.objectweb.asm.ClassWriter;
import io.quarkus.deployment.ClassOutput;
-import io.quarkus.deployment.QuarkusClassWriter;
public class RuntimeClassLoader extends ClassLoader implements ClassOutput, TransformerTarget {
@@ -56,6 +54,7 @@ public class RuntimeClassLoader extends ClassLoader implements ClassOutput, Tran
private final Map<String, byte[]> resources = new ConcurrentHashMap<>();
private volatile Map<String, List<BiFunction<String, ClassVisitor, ClassVisitor>>> bytecodeTransformers = null;
+ private volatile ClassLoader transformerSafeClassLoader;
private final List<Path> applicationClassDirectories;
@@ -68,7 +67,7 @@ public class RuntimeClassLoader extends ClassLoader implements ClassOutput, Tran
private static final String DEBUG_CLASSES_DIR = System.getProperty("quarkus.debug.generated-classes-dir");
- private final ConcurrentHashMap<String, Future<Class<?>>> loadingClasses = new ConcurrentHashMap<>();
+ private final ConcurrentHashMap<String, LoadingClass> loadingClasses = new ConcurrentHashMap<>();
static {
registerAsParallelCapable();
@@ -207,11 +206,15 @@ protected Class<?> findClass(String name) throws ClassNotFoundException {
Path classLoc = getClassInApplicationClassPaths(name);
if (classLoc != null) {
- CompletableFuture<Class<?>> res = new CompletableFuture<>();
- Future<Class<?>> loadingClass = loadingClasses.putIfAbsent(name, res);
+ LoadingClass res = new LoadingClass(new CompletableFuture<>(), Thread.currentThread());
+ LoadingClass loadingClass = loadingClasses.putIfAbsent(name, res);
if (loadingClass != null) {
+ if (loadingClass.initiator == Thread.currentThread()) {
+ throw new LinkageError(
+ "Load caused recursion in RuntimeClassLoader, this is a Quarkus bug loading class: " + name);
+ }
try {
- return loadingClass.get();
+ return loadingClass.value.get();
} catch (Exception e) {
throw new ClassNotFoundException("Failed to load " + name, e);
}
@@ -225,13 +228,13 @@ protected Class<?> findClass(String name) throws ClassNotFoundException {
bytes = handleTransform(name, bytes);
definePackage(name);
Class<?> clazz = defineClass(name, bytes, 0, bytes.length, defaultProtectionDomain);
- res.complete(clazz);
+ res.value.complete(clazz);
return clazz;
} catch (RuntimeException e) {
- res.completeExceptionally(e);
+ res.value.completeExceptionally(e);
throw e;
} catch (Throwable e) {
- res.completeExceptionally(e);
+ res.value.completeExceptionally(e);
throw e;
}
}
@@ -301,6 +304,7 @@ public Writer writeSource(final String className) {
@Override
public void setTransformers(Map<String, List<BiFunction<String, ClassVisitor, ClassVisitor>>> functions) {
this.bytecodeTransformers = functions;
+ this.transformerSafeClassLoader = Thread.currentThread().getContextClassLoader();
}
public void setApplicationArchives(List<Path> archives) {
@@ -422,7 +426,12 @@ private byte[] handleTransform(String name, byte[] bytes) {
}
ClassReader cr = new ClassReader(bytes);
- ClassWriter writer = new QuarkusClassWriter(cr, ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
+ ClassWriter writer = new ClassWriter(cr, ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS) {
+ @Override
+ protected ClassLoader getClassLoader() {
+ return transformerSafeClassLoader;
+ }
+ };
ClassVisitor visitor = writer;
for (BiFunction<String, ClassVisitor, ClassVisitor> i : transformers) {
visitor = i.apply(name, visitor);
@@ -537,4 +546,13 @@ private ProtectionDomain createDefaultProtectionDomain(Path applicationClasspath
return protectionDomain;
}
+ static final class LoadingClass {
+ final CompletableFuture<Class<?>> value;
+ final Thread initiator;
+
+ LoadingClass(CompletableFuture<Class<?>> value, Thread initiator) {
+ this.value = value;
+ this.initiator = initiator;
+ }
+ }
} | ['core/deployment/src/main/java/io/quarkus/runner/RuntimeClassLoader.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 6,518,742 | 1,259,819 | 168,793 | 1,777 | 2,101 | 349 | 38 | 1 | 6,224 | 363 | 1,542 | 129 | 1 | 5 | 2019-12-12T01:37: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,116 | quarkusio/quarkus/5451/5443 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/5443 | https://github.com/quarkusio/quarkus/pull/5451 | https://github.com/quarkusio/quarkus/issues/5443#issuecomment-554224543 | 2 | fixes | Thread locked after stress test | **Describe the bug**
(Describe the problem clearly and concisely.)
I did a simple stress test,then the program keeps giving alarm log.
```log
21:59:37 WARNING [io.ve.co.im.BlockedThreadChecker] (vertx-blocked-thread-checker) Thread Thread[vert.x-worker-thread-9,5,main]=Thread[vert.x-worker-thread-9,5,main] has been blocked for 3382564 ms, time limit is 60000 ms: io.vertx.core.VertxException: Thread blocked
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
at io.quarkus.resteasy.runtime.standalone.VertxBlockingOutput.awaitWriteable(VertxBlockingOutput.java:111)
at io.quarkus.resteasy.runtime.standalone.VertxBlockingOutput.write(VertxBlockingOutput.java:71)
at io.quarkus.resteasy.runtime.standalone.VertxHttpResponse.writeBlocking(VertxHttpResponse.java:179)
at io.quarkus.resteasy.runtime.standalone.VertxOutputStream.write(VertxOutputStream.java:69)
at io.quarkus.resteasy.runtime.standalone.VertxOutputStream.write(VertxOutputStream.java:42)
at org.jboss.resteasy.util.CommitHeaderOutputStream.write(CommitHeaderOutputStream.java:64)
at org.jboss.resteasy.util.DelegatingOutputStream.write(DelegatingOutputStream.java:42)
at org.jboss.resteasy.plugins.providers.jsonb.JsonBindingProvider.writeTo(JsonBindingProvider.java:137)
at org.jboss.resteasy.core.interception.jaxrs.AbstractWriterInterceptorContext.writeTo(AbstractWriterInterceptorContext.java:193)
at org.jboss.resteasy.core.interception.jaxrs.ServerWriterInterceptorContext.writeTo(ServerWriterInterceptorContext.java:64)
at org.jboss.resteasy.core.interception.jaxrs.AbstractWriterInterceptorContext.proceed(AbstractWriterInterceptorContext.java:155)
at org.jboss.resteasy.core.ServerResponseWriter.lambda$writeNomapResponse$2(ServerResponseWriter.java:156)
at org.jboss.resteasy.core.ServerResponseWriter$$Lambda$417/1780592217.run(Unknown Source)
at org.jboss.resteasy.core.interception.jaxrs.ContainerResponseContextImpl.filter(ContainerResponseContextImpl.java:404)
at org.jboss.resteasy.core.ServerResponseWriter.executeFilters(ServerResponseWriter.java:232)
at org.jboss.resteasy.core.ServerResponseWriter.writeNomapResponse(ServerResponseWriter.java:97)
at org.jboss.resteasy.core.ServerResponseWriter.writeNomapResponse(ServerResponseWriter.java:70)
at org.jboss.resteasy.core.SynchronousDispatcher.writeResponse(SynchronousDispatcher.java:578)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:508)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:252)
at org.jboss.resteasy.core.SynchronousDispatcher$$Lambda$332/1061176646.run(Unknown Source)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:153)
at org.jboss.resteasy.core.SynchronousDispatcher$$Lambda$338/1804746610.get(Unknown Source)
at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:363)
at org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:156)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:238)
at io.quarkus.resteasy.runtime.standalone.RequestDispatcher.service(RequestDispatcher.java:73)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.dispatch(VertxRequestHandler.java:109)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.dispatchRequestContext(VertxRequestHandler.java:84)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.lambda$handle$0(VertxRequestHandler.java:71)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler$$Lambda$313/2064123549.handle(Unknown Source)
at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$2(ContextImpl.java:316)
at io.vertx.core.impl.ContextImpl$$Lambda$327/865803395.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:748)
```
After the test ,All requests are unresponsive .
jstack log:
```
"mysql-cj-abandoned-connection-cleanup" #54 daemon prio=5 os_prio=0 tid=0x00007ff55c042800 nid=0xfaa in Object.wait() [0x00007ff60e3e8000]
java.lang.Thread.State: TIMED_WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:144)
- locked <0x00000006ca58bd08> (a java.lang.ref.ReferenceQueue$Lock)
at com.mysql.cj.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:85)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Locked ownable synchronizers:
- <0x00000006ca58b8f8> (a java.util.concurrent.ThreadPoolExecutor$Worker)
"vert.x-worker-thread-12" #53 prio=5 os_prio=0 tid=0x00007ff58c007000 nid=0xfa9 in Object.wait() [0x00007ff60e8e8000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
at io.quarkus.resteasy.runtime.standalone.VertxBlockingOutput.awaitWriteable(VertxBlockingOutput.java:111)
at io.quarkus.resteasy.runtime.standalone.VertxBlockingOutput.write(VertxBlockingOutput.java:71)
- locked <0x00000006c8739c58> (a io.vertx.core.http.impl.Http1xServerConnection)
at io.quarkus.resteasy.runtime.standalone.VertxHttpResponse.writeBlocking(VertxHttpResponse.java:179)
at io.quarkus.resteasy.runtime.standalone.VertxOutputStream.write(VertxOutputStream.java:69)
at io.quarkus.resteasy.runtime.standalone.VertxOutputStream.write(VertxOutputStream.java:42)
at org.jboss.resteasy.util.CommitHeaderOutputStream.write(CommitHeaderOutputStream.java:64)
at org.jboss.resteasy.util.DelegatingOutputStream.write(DelegatingOutputStream.java:42)
at org.jboss.resteasy.plugins.providers.jsonb.JsonBindingProvider.writeTo(JsonBindingProvider.java:137)
at org.jboss.resteasy.core.interception.jaxrs.AbstractWriterInterceptorContext.writeTo(AbstractWriterInterceptorContext.java:193)
at org.jboss.resteasy.core.interception.jaxrs.ServerWriterInterceptorContext.writeTo(ServerWriterInterceptorContext.java:64)
at org.jboss.resteasy.core.interception.jaxrs.AbstractWriterInterceptorContext.proceed(AbstractWriterInterceptorContext.java:155)
at org.jboss.resteasy.core.ServerResponseWriter.lambda$writeNomapResponse$2(ServerResponseWriter.java:156)
at org.jboss.resteasy.core.ServerResponseWriter$$Lambda$417/1780592217.run(Unknown Source)
at org.jboss.resteasy.core.interception.jaxrs.ContainerResponseContextImpl.filter(ContainerResponseContextImpl.java:404)
- locked <0x00000007bea82098> (a org.jboss.resteasy.core.interception.jaxrs.ContainerResponseContextImpl)
at org.jboss.resteasy.core.ServerResponseWriter.executeFilters(ServerResponseWriter.java:232)
at org.jboss.resteasy.core.ServerResponseWriter.writeNomapResponse(ServerResponseWriter.java:97)
at org.jboss.resteasy.core.ServerResponseWriter.writeNomapResponse(ServerResponseWriter.java:70)
at org.jboss.resteasy.core.SynchronousDispatcher.writeResponse(SynchronousDispatcher.java:578)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:508)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:252)
at org.jboss.resteasy.core.SynchronousDispatcher$$Lambda$332/1061176646.run(Unknown Source)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:153)
at org.jboss.resteasy.core.SynchronousDispatcher$$Lambda$338/1804746610.get(Unknown Source)
at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:363)
- locked <0x00000007bea82130> (a org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext)
at org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:156)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:238)
at io.quarkus.resteasy.runtime.standalone.RequestDispatcher.service(RequestDispatcher.java:73)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.dispatch(VertxRequestHandler.java:109)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.dispatchRequestContext(VertxRequestHandler.java:84)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.lambda$handle$0(VertxRequestHandler.java:71)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler$$Lambda$313/2064123549.handle(Unknown Source)
at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$2(ContextImpl.java:316)
at io.vertx.core.impl.ContextImpl$$Lambda$327/865803395.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:748)
Locked ownable synchronizers:
- <0x00000006c8863b08> (a java.util.concurrent.ThreadPoolExecutor$Worker)
```
**Expected behavior**
(Describe the expected behavior clearly and concisely.)
**Actual behavior**
(Describe the actual behavior clearly and concisely.)
**To Reproduce**
Steps to reproduce the behavior:
1. My program was modified from hibernate-orm-panache-resteasy in quickstart. I add a restful service returns all records of the table,there are 800 records in the table.
```java
@GET
public List<Student> findAll() {
List<Student> list = Student.findAll().list();
if (list == null) {
throw new WebApplicationException("Fruit does not exist.", 404);
}
return list;
}
```
2. Then run in JVM mode.
3. Did a simple stress test .
```shell
wrk -t12 -c2000 -d30s http://10.32.1.***:8888/rest/students/
```
**Configuration**
```properties
# Add your application.properties here, if applicable.
quarkus.datasource.url=jdbc:mysql://10.32.1.***:3306/xyz
quarkus.datasource.driver=com.mysql.cj.jdbc.Driver
```
```xml
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jdbc-mysql</artifactId>
</dependency>
```
**Screenshots**
(If applicable, add screenshots to help explain your problem.)
**Environment (please complete the following information):**
- Output of `uname -a` or `ver`:
Linux ***** 3.10.0-862.3.3.el7.x86_64 #1 SMP Fri Jun 15 04:15:27 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
- Output of `java -version`:
java version "1.8.0_201"
Java(TM) SE Runtime Environment (build 1.8.0_201-b09)
Java HotSpot(TM) 64-Bit Server VM (build 25.201-b09, mixed mode)
- GraalVM version (if different from Java):
- Quarkus version or git rev: 1.0.0.CR1
**Additional context**
**The full jstack dump info**
[jstack-l.txt](https://github.com/quarkusio/quarkus/files/3841662/jstack-l.txt)
| 8be0f981ba69e645bdd83bf985037f6d1944736b | c4e86939ba7f291c0e1456f36cd0db68a12487e6 | https://github.com/quarkusio/quarkus/compare/8be0f981ba69e645bdd83bf985037f6d1944736b...c4e86939ba7f291c0e1456f36cd0db68a12487e6 | diff --git a/extensions/resteasy/runtime/src/main/java/io/quarkus/resteasy/runtime/standalone/VertxBlockingOutput.java b/extensions/resteasy/runtime/src/main/java/io/quarkus/resteasy/runtime/standalone/VertxBlockingOutput.java
index bbb7e882f7b..fafae708f2f 100644
--- a/extensions/resteasy/runtime/src/main/java/io/quarkus/resteasy/runtime/standalone/VertxBlockingOutput.java
+++ b/extensions/resteasy/runtime/src/main/java/io/quarkus/resteasy/runtime/standalone/VertxBlockingOutput.java
@@ -68,11 +68,18 @@ public void write(ByteBuf data, boolean last) throws IOException {
try {
//do all this in the same lock
synchronized (request.connection()) {
- awaitWriteable();
- if (last) {
- request.response().end(createBuffer(data));
- } else {
- request.response().write(createBuffer(data));
+ try {
+ awaitWriteable();
+ if (last) {
+ request.response().end(createBuffer(data));
+ } else {
+ request.response().write(createBuffer(data));
+ }
+ } catch (Exception e) {
+ if (data != null && data.refCnt() > 0) {
+ data.release();
+ }
+ throw new IOException("Failed to write", e);
}
}
} finally {
@@ -95,16 +102,21 @@ private void awaitWriteable() throws IOException {
if (Context.isOnEventLoopThread()) {
throw new IOException("Attempting a blocking write on io thread");
}
+ if (request.response().closed()) {
+ throw new IOException("Connection has been closed");
+ }
if (!drainHandlerRegistered) {
drainHandlerRegistered = true;
- request.response().drainHandler(new Handler<Void>() {
+ Handler<Void> handler = new Handler<Void>() {
@Override
public void handle(Void event) {
if (waitingForDrain) {
request.connection().notifyAll();
}
}
- });
+ };
+ request.response().drainHandler(handler);
+ request.response().closeHandler(handler);
}
try {
waitingForDrain = true;
diff --git a/extensions/resteasy/runtime/src/main/java/io/quarkus/resteasy/runtime/standalone/VertxOutputStream.java b/extensions/resteasy/runtime/src/main/java/io/quarkus/resteasy/runtime/standalone/VertxOutputStream.java
index a4ca581b378..8e626aceb26 100644
--- a/extensions/resteasy/runtime/src/main/java/io/quarkus/resteasy/runtime/standalone/VertxOutputStream.java
+++ b/extensions/resteasy/runtime/src/main/java/io/quarkus/resteasy/runtime/standalone/VertxOutputStream.java
@@ -66,12 +66,13 @@ public void write(final byte[] b, final int off, final int len) throws IOExcepti
rem -= toWrite;
idx += toWrite;
if (!buffer.isWritable()) {
- response.writeBlocking(buffer, false);
+ ByteBuf tmpBuf = buffer;
this.pooledBuffer = buffer = allocator.allocateBuffer();
+ response.writeBlocking(tmpBuf, false);
}
}
} catch (Exception e) {
- if (buffer != null) {
+ if (buffer != null && buffer.refCnt() > 0) {
buffer.release();
}
throw new IOException(e); | ['extensions/resteasy/runtime/src/main/java/io/quarkus/resteasy/runtime/standalone/VertxBlockingOutput.java', 'extensions/resteasy/runtime/src/main/java/io/quarkus/resteasy/runtime/standalone/VertxOutputStream.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 5,922,746 | 1,148,164 | 152,831 | 1,582 | 1,426 | 226 | 31 | 2 | 11,559 | 498 | 2,776 | 168 | 2 | 6 | 2019-11-13T19:54:25 | 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,115 | quarkusio/quarkus/5336/5335 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/5335 | https://github.com/quarkusio/quarkus/pull/5336 | https://github.com/quarkusio/quarkus/pull/5336#issuecomment-552184240 | 1 | fixes | URLClassPath substitutions not working with Java 11 | ```
Error: substitution target for io.quarkus.vertx.core.runtime.graal.Target_sun_misc_URLClassPath 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.vertx.core.runtime.graal.Target_sun_misc_URLClassPath is not loaded. Use field `onlyWith` in the `TargetClass` annotation to make substitution only active when needed.
at com.oracle.svm.core.util.UserError.abort(UserError.java:65)
at com.oracle.svm.hosted.substitute.AnnotationSubstitutionProcessor.findTargetClass(AnnotationSubstitutionProcessor.java:823)
at com.oracle.svm.hosted.substitute.AnnotationSubstitutionProcessor.handleClass(AnnotationSubstitutionProcessor.java:252)
at com.oracle.svm.hosted.substitute.AnnotationSubstitutionProcessor.init(AnnotationSubstitutionProcessor.java:230)
at com.oracle.svm.hosted.NativeImageGenerator.createDeclarativeSubstitutionProcessor(NativeImageGenerator.java:874)
at com.oracle.svm.hosted.NativeImageGenerator.setupNativeImage(NativeImageGenerator.java:823)
at com.oracle.svm.hosted.NativeImageGenerator.doRun(NativeImageGenerator.java:528)
at com.oracle.svm.hosted.NativeImageGenerator.lambda$run$0(NativeImageGenerator.java:445)
at java.base/java.util.concurrent.ForkJoinTask$AdaptedRunnableAction.exec(ForkJoinTask.java:1407)
at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:177)
```
PR on its way | 971217113cc71abebd7e50635e936fbd70a41fb1 | 784bce9f7869c0ac5000e190a9f816739c40f66d | https://github.com/quarkusio/quarkus/compare/971217113cc71abebd7e50635e936fbd70a41fb1...784bce9f7869c0ac5000e190a9f816739c40f66d | diff --git a/extensions/vertx-core/runtime/src/main/java/io/quarkus/vertx/core/runtime/graal/JdkSubstitutions.java b/extensions/vertx-core/runtime/src/main/java/io/quarkus/vertx/core/runtime/graal/JdkSubstitutions.java
index 14afde0c967..a6413dbfde9 100644
--- a/extensions/vertx-core/runtime/src/main/java/io/quarkus/vertx/core/runtime/graal/JdkSubstitutions.java
+++ b/extensions/vertx-core/runtime/src/main/java/io/quarkus/vertx/core/runtime/graal/JdkSubstitutions.java
@@ -4,43 +4,46 @@
import java.io.IOException;
import java.net.URL;
import java.util.function.BooleanSupplier;
+import java.util.function.Function;
import com.oracle.svm.core.annotate.Alias;
import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;
+import com.oracle.svm.core.jdk.JDK11OrLater;
+import com.oracle.svm.core.jdk.JDK8OrEarlier;
-@TargetClass(className = "sun.misc.URLClassPath$Loader")
-final class Target_sun_misc_URLClassPath$Loader {
+@TargetClass(className = "URLClassPath$Loader", classNameProvider = Package_jdk_internal_loader.class)
+final class Target_URLClassPath$Loader {
@Alias
- public Target_sun_misc_URLClassPath$Loader(URL url) {
+ public Target_URLClassPath$Loader(URL url) {
}
}
-@TargetClass(className = "sun.misc.URLClassPath$FileLoader")
-final class Target_sun_misc_URLClassPath$FileLoader {
+@TargetClass(className = "URLClassPath$FileLoader", classNameProvider = Package_jdk_internal_loader.class)
+final class Target_URLClassPath$FileLoader {
@Alias
- public Target_sun_misc_URLClassPath$FileLoader(URL url) throws IOException {
+ public Target_URLClassPath$FileLoader(URL url) throws IOException {
}
}
-@TargetClass(className = "sun.misc.URLClassPath")
+@TargetClass(className = "sun.misc.URLClassPath", onlyWith = JDK8OrEarlier.class)
final class Target_sun_misc_URLClassPath {
@Substitute
- private Target_sun_misc_URLClassPath$Loader getLoader(final URL url) throws IOException {
+ private Target_URLClassPath$Loader getLoader(final URL url) throws IOException {
String file = url.getFile();
if (file != null && file.endsWith("/")) {
if ("file".equals(url.getProtocol())) {
- return (Target_sun_misc_URLClassPath$Loader) (Object) new Target_sun_misc_URLClassPath$FileLoader(
+ return (Target_URLClassPath$Loader) (Object) new Target_URLClassPath$FileLoader(
url);
} else {
- return new Target_sun_misc_URLClassPath$Loader(url);
+ return new Target_URLClassPath$Loader(url);
}
} else {
// that must be wrong, but JarLoader is deleted by SVM
- return (Target_sun_misc_URLClassPath$Loader) (Object) new Target_sun_misc_URLClassPath$FileLoader(
+ return (Target_URLClassPath$Loader) (Object) new Target_URLClassPath$FileLoader(
url);
}
}
@@ -51,6 +54,28 @@ private int[] getLookupCache(String name) {
}
}
+@TargetClass(className = "jdk.internal.loader.URLClassPath", onlyWith = JDK11OrLater.class)
+final class Target_jdk_internal_loader_URLClassPath {
+
+ @Substitute
+ private Target_URLClassPath$Loader getLoader(final URL url) throws IOException {
+ String file = url.getFile();
+ if (file != null && file.endsWith("/")) {
+ if ("file".equals(url.getProtocol())) {
+ return (Target_URLClassPath$Loader) (Object) new Target_URLClassPath$FileLoader(
+ url);
+ } else {
+ return new Target_URLClassPath$Loader(url);
+ }
+ } else {
+ // that must be wrong, but JarLoader is deleted by SVM
+ return (Target_URLClassPath$Loader) (Object) new Target_URLClassPath$FileLoader(
+ url);
+ }
+ }
+
+}
+
@TargetClass(className = "sun.nio.ch.DatagramChannelImpl", onlyWith = GraalVersion19_0.class)
final class Target_sun_nio_ch_DatagramChannelImpl {
@@ -68,6 +93,20 @@ public boolean getAsBoolean() {
}
}
+final class Package_jdk_internal_loader implements Function<TargetClass, String> {
+
+ private static final JDK8OrEarlier JDK_8_OR_EARLIER = new JDK8OrEarlier();
+
+ @Override
+ public String apply(TargetClass annotation) {
+ if (JDK_8_OR_EARLIER.getAsBoolean()) {
+ return "sun.misc." + annotation.className();
+ }
+
+ return "jdk.internal.loader." + annotation.className();
+ }
+}
+
class JdkSubstitutions {
} | ['extensions/vertx-core/runtime/src/main/java/io/quarkus/vertx/core/runtime/graal/JdkSubstitutions.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 5,909,992 | 1,145,754 | 152,532 | 1,574 | 3,069 | 667 | 61 | 1 | 1,843 | 78 | 418 | 20 | 0 | 1 | 2019-11-08T15:30:20 | 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,112 | quarkusio/quarkus/3547/3202 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/3202 | https://github.com/quarkusio/quarkus/pull/3547 | https://github.com/quarkusio/quarkus/pull/3547#issuecomment-528452806 | 2 | fixes | Kafka Streams Extension can't find Serdes.StringSerde | **Describe the bug**
Native image generated cannot find the StringSerde. This causes the app to fail on startup.
**Expected behavior**
The app should start up and run without issues.
**Actual behavior**
I have a Java Kafka Streams app. I configure the Serdes.StringSerde as the default Serdes in the Kafka properties.
I then build a native image (either on OSX or docker).
When I run the native image, it fails with:
```
Caused by: org.apache.kafka.common.config.ConfigException: Invalid value org.apache.kafka.common.serialization.Serdes$StringSerde for configuration default.key.serde: Class org.apache.kafka.common.serialization.Serdes$StringSerde could not be found.
at org.apache.kafka.common.config.ConfigDef.parseType(ConfigDef.java:718)
at org.apache.kafka.common.config.ConfigDef.parseValue(ConfigDef.java:471)
at org.apache.kafka.common.config.ConfigDef.parse(ConfigDef.java:464)
at org.apache.kafka.common.config.AbstractConfig.<init>(AbstractConfig.java:62)
at org.apache.kafka.streams.StreamsConfig.<init>(StreamsConfig.java:849)
at org.apache.kafka.streams.StreamsConfig.<init>(StreamsConfig.java:844)
at org.apache.kafka.streams.KafkaStreams.<init>(KafkaStreams.java:544)
at com.aimyourtechnology.quarkus.kafka.streams.ConverterStream.runTopology(ConverterStream.java:52)
at com.aimyourtechnology.quarkus.kafka.streams.StreamingApp.onStart(StreamingApp.java:54)
at com.aimyourtechnology.quarkus.kafka.streams.StreamingApp_Observer_onStart_fd71b5e0b207b7d1ef838b94eaeff75e52b8f463.notify(StreamingApp_Observer_onStart_fd71b5e0b207b7d1ef838b94eaeff75e52b8f463.zig:63)
at io.quarkus.arc.EventImpl$Notifier.notify(EventImpl.java:228)
at io.quarkus.arc.EventImpl.fire(EventImpl.java:69)
at io.quarkus.arc.runtime.LifecycleEventRunner.fireStartupEvent(LifecycleEventRunner.java:23)
at io.quarkus.arc.runtime.ArcDeploymentTemplate.handleLifecycleEvents(ArcDeploymentTemplate.java:99)
at io.quarkus.deployment.steps.LifecycleEventsBuildStep$startupEvent17.deploy_0(LifecycleEventsBuildStep$startupEvent17.zig:58)
at io.quarkus.deployment.steps.LifecycleEventsBuildStep$startupEvent17.deploy(LifecycleEventsBuildStep$startupEvent17.zig:77)
at io.quarkus.runner.ApplicationImpl1.doStart(ApplicationImpl1.zig:90)
... 3 more
```
**To Reproduce**
Steps to reproduce the behavior:
You can show it through docker:
```
1. git clone https://github.com/muirandy/quarkus-kafka-streams-xml-json-converter.git
2. cd quarkus-kafka-streams-xml-json-converter
3. mvn package -Pnative -Dnative-image.docker-build=true
4. docker build -f src/main/docker/Dockerfile.native -t quarkus/quarkus-kafka-streams-xml-json-converter .
```
You can now run acceptance.converter.ConvertToJsonShould from an IDE. This will demonstrate the failure.
**Environment (please complete the following information):**
- Output of `uname -a` or `ver`:
```
Darwin andymuir-3.local 18.6.0 Darwin Kernel Version 18.6.0: Thu Apr 25 23:16:27 PDT 2019; root:xnu-4903.261.4~2/RELEASE_X86_64 x86_64
```
- Output of `java -version`:
```
java version "1.8.0_212"
Java(TM) SE Runtime Environment (build 1.8.0_212-b31)
Java HotSpot(TM) 64-Bit GraalVM EE 19.1.0 (build 25.212-b31-jvmci-20-b04, mixed mode)
```
- GraalVM version (if different from Java): 19.1.0
- Quarkus version or git rev: 0.18.0
**Additional context**
The quickstart example uses a StringSerde defined for the Stream:
```
builder.stream(
TEMPERATURE_VALUES_TOPIC,
Consumed.with(Serdes.Integer(), Serdes.String())
)
```
My code defines:
```
streamingConfig.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
streamingConfig.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
```
as part of the Kafka Properties used when creating the KafkaStreams within com.aimyourtechnology.quarkus.kafka.streams.ConverterStream:
```
streams = new KafkaStreams(topology, streamingConfig);
```
| a7892346634d9aa8a2bb4bbdc4b0f2fc2f8cd59e | 3f96d8724306428c9da9a780f48e31580603f291 | https://github.com/quarkusio/quarkus/compare/a7892346634d9aa8a2bb4bbdc4b0f2fc2f8cd59e...3f96d8724306428c9da9a780f48e31580603f291 | diff --git a/extensions/kafka-streams/deployment/src/main/java/io/quarkus/kafka/streams/deployment/KafkaStreamsProcessor.java b/extensions/kafka-streams/deployment/src/main/java/io/quarkus/kafka/streams/deployment/KafkaStreamsProcessor.java
index 9b8cf410880..c46fd119b9b 100644
--- a/extensions/kafka-streams/deployment/src/main/java/io/quarkus/kafka/streams/deployment/KafkaStreamsProcessor.java
+++ b/extensions/kafka-streams/deployment/src/main/java/io/quarkus/kafka/streams/deployment/KafkaStreamsProcessor.java
@@ -4,6 +4,7 @@
import java.util.Properties;
import org.apache.kafka.common.serialization.Serdes.ByteArraySerde;
+import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.errors.DefaultProductionExceptionHandler;
import org.apache.kafka.streams.errors.LogAndFailExceptionHandler;
import org.apache.kafka.streams.processor.DefaultPartitionGrouper;
@@ -44,13 +45,62 @@ void build(RecorderContext recorder,
feature.produce(new FeatureBuildItem(FeatureBuildItem.KAFKA_STREAMS));
+ registerClassesThatAreLoadedThroughReflection(reflectiveClasses);
+ addSupportForRocksDbLib(nativeLibs);
+ enableLoadOfNativeLibs(reinitialized);
+ enableJniForNativeBuild(jni);
+ }
+
+ private void registerClassesThatAreLoadedThroughReflection(BuildProducer<ReflectiveClassBuildItem> reflectiveClasses) {
+ registerCompulsoryClasses(reflectiveClasses);
+ registerClassesThatClientMaySpecify(reflectiveClasses);
+ }
+
+ private void registerCompulsoryClasses(BuildProducer<ReflectiveClassBuildItem> reflectiveClasses) {
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, false, false, StreamsPartitionAssignor.class));
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, false, false, DefaultPartitionGrouper.class));
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, false, false, DefaultProductionExceptionHandler.class));
- reflectiveClasses.produce(new ReflectiveClassBuildItem(true, false, false, LogAndFailExceptionHandler.class));
- reflectiveClasses.produce(new ReflectiveClassBuildItem(true, false, false, ByteArraySerde.class));
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, false, false, FailOnInvalidTimestamp.class));
+ }
+
+ private void registerClassesThatClientMaySpecify(BuildProducer<ReflectiveClassBuildItem> reflectiveClasses) {
+ registerExceptionHandler(reflectiveClasses);
+ registerDefaultSerdes(reflectiveClasses);
+ }
+
+ private void registerExceptionHandler(BuildProducer<ReflectiveClassBuildItem> reflectiveClasses) {
+ Properties properties = buildKafkaStreamsProperties();
+ String exceptionHandlerClassName = properties
+ .getProperty(StreamsConfig.DEFAULT_DESERIALIZATION_EXCEPTION_HANDLER_CLASS_CONFIG);
+ if (exceptionHandlerClassName == null) {
+ registerDefaultExceptionHandler(reflectiveClasses);
+ } else {
+ registerClassName(reflectiveClasses, exceptionHandlerClassName);
+ }
+ }
+
+ private void registerDefaultExceptionHandler(BuildProducer<ReflectiveClassBuildItem> reflectiveClasses) {
+ reflectiveClasses.produce(new ReflectiveClassBuildItem(true, false, false, LogAndFailExceptionHandler.class));
+ }
+
+ private void registerDefaultSerdes(BuildProducer<ReflectiveClassBuildItem> reflectiveClasses) {
+ Properties properties = buildKafkaStreamsProperties();
+ String defaultKeySerdeClass = properties.getProperty(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG);
+ String defaultValueSerdeClass = properties.getProperty(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG);
+
+ if (defaultKeySerdeClass != null) {
+ registerClassName(reflectiveClasses, defaultKeySerdeClass);
+ }
+ if (defaultValueSerdeClass != null) {
+ registerClassName(reflectiveClasses, defaultValueSerdeClass);
+ }
+ if (!allDefaultSerdesAreDefinedInProperties(defaultKeySerdeClass, defaultValueSerdeClass)) {
+ registerDefaultSerde(reflectiveClasses);
+ }
+ }
+
+ private void addSupportForRocksDbLib(BuildProducer<SubstrateResourceBuildItem> nativeLibs) {
// for RocksDB, either add linux64 native lib when targeting containers
if (isContainerBuild()) {
nativeLibs.produce(new SubstrateResourceBuildItem("librocksdbjni-linux64.so"));
@@ -59,27 +109,53 @@ void build(RecorderContext recorder,
else {
nativeLibs.produce(new SubstrateResourceBuildItem(Environment.getJniLibraryFileName("rocksdb")));
}
+ }
- // re-initializing RocksDB to enable load of native libs
+ private void enableLoadOfNativeLibs(BuildProducer<RuntimeReinitializedClassBuildItem> reinitialized) {
reinitialized.produce(new RuntimeReinitializedClassBuildItem("org.rocksdb.RocksDB"));
+ }
+ private void enableJniForNativeBuild(BuildProducer<JniBuildItem> jni) {
jni.produce(new JniBuildItem());
}
+ private void registerClassName(BuildProducer<ReflectiveClassBuildItem> reflectiveClasses, String defaultKeySerdeClass) {
+ reflectiveClasses.produce(new ReflectiveClassBuildItem(true, false, false, defaultKeySerdeClass));
+ }
+
+ private boolean allDefaultSerdesAreDefinedInProperties(String defaultKeySerdeClass, String defaultValueSerdeClass) {
+ return defaultKeySerdeClass != null && defaultValueSerdeClass != null;
+ }
+
+ private void registerDefaultSerde(BuildProducer<ReflectiveClassBuildItem> reflectiveClasses) {
+ reflectiveClasses.produce(new ReflectiveClassBuildItem(true, false, false, ByteArraySerde.class));
+ }
+
@BuildStep
@Record(ExecutionTime.STATIC_INIT)
BeanContainerListenerBuildItem processBuildTimeConfig(KafkaStreamsRecorder recorder) {
- Config config = ConfigProvider.getConfig();
+ Properties kafkaStreamsProperties = buildKafkaStreamsProperties();
+ return new BeanContainerListenerBuildItem(recorder.configure(kafkaStreamsProperties));
+ }
- Properties properties = new Properties();
+ private Properties buildKafkaStreamsProperties() {
+ Config config = ConfigProvider.getConfig();
+ Properties kafkaStreamsProperties = new Properties();
for (String property : config.getPropertyNames()) {
- if (property.startsWith(STREAMS_OPTION_PREFIX)) {
- properties.setProperty(property.substring(STREAMS_OPTION_PREFIX.length()),
- config.getValue(property, String.class));
+ if (isKafkaStreamsProperty(property)) {
+ includeKafkaStreamsProperty(config, kafkaStreamsProperties, property);
}
}
+ return kafkaStreamsProperties;
+ }
+
+ private boolean isKafkaStreamsProperty(String property) {
+ return property.startsWith(STREAMS_OPTION_PREFIX);
+ }
- return new BeanContainerListenerBuildItem(recorder.configure(properties));
+ private void includeKafkaStreamsProperty(Config config, Properties kafkaStreamsProperties, String property) {
+ kafkaStreamsProperties.setProperty(property.substring(STREAMS_OPTION_PREFIX.length()),
+ config.getValue(property, String.class));
}
@BuildStep | ['extensions/kafka-streams/deployment/src/main/java/io/quarkus/kafka/streams/deployment/KafkaStreamsProcessor.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 4,343,964 | 840,734 | 112,306 | 1,137 | 5,096 | 952 | 94 | 1 | 4,121 | 291 | 1,043 | 78 | 1 | 7 | 2019-08-16T18:14:33 | 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,109 | quarkusio/quarkus/2554/2549 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/2549 | https://github.com/quarkusio/quarkus/pull/2554 | https://github.com/quarkusio/quarkus/pull/2554#issuecomment-494814527 | 1 | fixes | NullPointerException in DevMojo when running mvn compile quarkus:dev | **Describe the bug**
Running `mvn compile quarkus:dev -rf web` in the root of https://github.com/fabric8-launcher/launcher-backend gives the following error when using the 999-SNAPSHOT version
```
Caused by: java.lang.NullPointerException
at io.quarkus.maven.DevMojo.execute (DevMojo.java:248)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192)
at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105)
at org.apache.maven.cli.MavenCli.execute (MavenCli.java:956)
at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:288)
at org.apache.maven.cli.MavenCli.main (MavenCli.java:192)
at sun.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:498)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
```
**Expected behavior**
Quarkus should start appropriately. It works in 0.15.0
```
[INFO] --- quarkus-maven-plugin:0.15.0:dev (default-cli) @ launcher-app ---
Listening for transport dt_socket at address: 5005
2019-05-22 00:17:22,061 INFO [io.qua.dep.QuarkusAugmentor] (main) Beginning quarkus augmentation
2019-05-22 00:17:24,021 INFO [io.qua.dep.QuarkusAugmentor] (main) Quarkus augmentation completed in 1960ms
2019-05-22 00:17:25,505 WARN [io.und.web.jsr] (main) UT026010: Buffer pool was not set on WebSocketDeploymentInfo, the default pool will be used
2019-05-22 00:17:25,509 INFO [io.und.web.jsr] (main) UT026003: Adding annotated server endpoint class io.fabric8.launcher.web.endpoints.websocket.MissionControlStatusEndpoint for path /status/{uuid}
2019-05-22 00:17:26,022 INFO [io.fab.lau.boo.cat.AbstractBoosterCatalogService] (main) Using io.fabric8.launcher.booster.catalog.spi.NativeGitBoosterCatalogPathProvider
2019-05-22 00:17:26,023 INFO [io.fab.lau.boo.cat.spi.NativeGitBoosterCatalogPathProvider] (pool-5-thread-1) Indexing contents from https://github.com/fabric8-launcher/launcher-booster-catalog.git using master ref
2019-05-22 00:17:26,025 INFO [io.fab.lau.cor.imp.doc.BoosterDocumentationStoreImpl] (pool-5-thread-2) Indexing contents from https://github.com/fabric8-launcher/launcher-documentation.git using master ref
2019-05-22 00:17:26,026 INFO [io.quarkus] (main) Quarkus 0.15.0 started in 4.199s. Listening on: http://[::]:8080
```
**Actual behavior**
Fails with NPE.
**To Reproduce**
Steps to reproduce the behavior:
1. `git clone https://github.com/fabric8-launcher/launcher-backend`
2. `mvn clean install -DskipTests`
3. `mvn compile quarkus:dev -rf web`
**Environment (please complete the following information):**
- Output of `uname -a` or `ver`: `Linux ggastald-laptop 5.0.13-300.fc30.x86_64 #1 SMP Mon May 6 00:39:45 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux`
- Output of `java -version`: openjdk version "1.8.0_202"
- GraalVM version (if different from Java): not using it
- Quarkus version or git rev: 999-SNAPSHOT (built from master)
| 48e18181885c6ae3e5caa2bee9dcef4fecbe426a | c8bf8c32a62fcd47b4f3e2183ad3adaa4fa9f55c | https://github.com/quarkusio/quarkus/compare/48e18181885c6ae3e5caa2bee9dcef4fecbe426a...c8bf8c32a62fcd47b4f3e2183ad3adaa4fa9f55c | 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 46f6aaccdc3..99f65ff4900 100644
--- a/devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java
+++ b/devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java
@@ -34,6 +34,7 @@
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.jar.Attributes;
@@ -241,15 +242,25 @@ public void execute() throws MojoFailureException, MojoExecutionException {
AppArtifact appArtifact = project.getAppArtifact();
MavenProject mavenProject = projectMap.get(String.format("%s:%s:%s",
appArtifact.getGroupId(), appArtifact.getArtifactId(), appArtifact.getVersion()));
- String sourcePath = null;
+ // no information about this project from Maven. Skip.
+
+ String projectDirectory = null;
+ List<String> sourcePaths = null;
String classesPath = null;
String resourcePath = null;
- List<String> sourcePaths = mavenProject.getCompileSourceRoots().stream()
- .map(Paths::get)
- .filter(Files::isDirectory)
- .map(src -> src.toAbsolutePath().toString())
- .collect(Collectors.toList());
+ if (mavenProject == null) {
+ projectDirectory = localProject.getDir().toAbsolutePath().toString();
+ sourcePaths = Collections.singletonList(
+ localProject.getSourcesSourcesDir().toAbsolutePath().toString());
+ } else {
+ projectDirectory = mavenProject.getBasedir().getPath();
+ sourcePaths = mavenProject.getCompileSourceRoots().stream()
+ .map(Paths::get)
+ .filter(Files::isDirectory)
+ .map(src -> src.toAbsolutePath().toString())
+ .collect(Collectors.toList());
+ }
Path classesDir = project.getClassesDir();
if (Files.isDirectory(classesDir)) {
@@ -261,7 +272,7 @@ public void execute() throws MojoFailureException, MojoExecutionException {
}
DevModeContext.ModuleInfo moduleInfo = new DevModeContext.ModuleInfo(
project.getArtifactId(),
- mavenProject.getBasedir().getPath(),
+ projectDirectory,
sourcePaths,
classesPath,
resourcePath); | ['devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,781,328 | 739,544 | 98,289 | 965 | 1,487 | 218 | 25 | 1 | 4,327 | 303 | 1,197 | 60 | 5 | 2 | 2019-05-22T08:02:17 | 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,108 | quarkusio/quarkus/2301/2270 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/2270 | https://github.com/quarkusio/quarkus/pull/2301 | https://github.com/quarkusio/quarkus/pull/2301#issuecomment-487976482 | 2 | solves | The datasources are not ready to be consumed when injecting a DS to CamelLifecycle | Injecting a `DataSource` into a `CamelLifecycle` fails with the exception below. I am injecting the datasource to be able to bind it to a name in the Camel registry https://github.com/ppalaga/quarkus/blob/e8253198085073559bf35bfc9a0002ab2d83faec/integration-tests/camel-jdbc/src/main/java/io/quarkus/it/camel/jdbc/CamelLifecycle.java#L38
I assume that should work, @gnodet @lburgazzoli ?
```
[INFO] Running io.quarkus.it.camel.jdbc.CamelJdbcTest
[INFO] H2 database started in TCP server mode
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 2.916 s <<< FAILURE! - in io.quarkus.it.camel.jdbc.CamelJdbcTest
[ERROR] select Time elapsed: 0.009 s <<< ERROR!
org.junit.jupiter.api.extension.TestInstantiationException: TestInstanceFactory [io.quarkus.test.junit.QuarkusTestExtension] failed to instantiate test class [io.quarkus.it.camel.jdbc.CamelJdbcTest]
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.invokeTestInstanceFactory(ClassTestDescriptor.java:314)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateTestClass(ClassTestDescriptor.java:289)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateTestClass(ClassTestDescriptor.java:281)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateAndPostProcessTestInstance(ClassTestDescriptor.java:269)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstancesProvider$2(ClassTestDescriptor.java:259)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstancesProvider$3(ClassTestDescriptor.java:263)
at java.util.Optional.orElseGet(Optional.java:267)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$testInstancesProvider$4(ClassTestDescriptor.java:262)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:98)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:97)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:68)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$1(NodeTestTask.java:107)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:107)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:75)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
at org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.invokeAllTests(JUnitPlatformProvider.java:142)
at org.apache.maven.surefire.junitplatform.JUnitPlatformProvider.invoke(JUnitPlatformProvider.java:117)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:383)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:344)
at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:125)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:417)
Caused by: java.lang.ExceptionInInitializerError
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)
at io.quarkus.runner.RuntimeRunner.run(RuntimeRunner.java:121)
at io.quarkus.test.junit.QuarkusTestExtension.doJavaStart(QuarkusTestExtension.java:236)
at io.quarkus.test.junit.QuarkusTestExtension.createTestInstance(QuarkusTestExtension.java:302)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.invokeTestInstanceFactory(ClassTestDescriptor.java:299)
... 47 more
Caused by: java.lang.RuntimeException: Failed to start quarkus
at io.quarkus.runner.ApplicationImpl1.<clinit>(Unknown Source)
... 56 more
Caused by: org.apache.camel.RuntimeCamelException: java.lang.IllegalStateException: The datasources are not ready to be consumed: the runtime configuration has not been injected yet
at org.apache.camel.RuntimeCamelException.wrapRuntimeCamelException(RuntimeCamelException.java:52)
at io.quarkus.camel.core.runtime.support.FastCamelRuntime.doInit(FastCamelRuntime.java:104)
at io.quarkus.camel.core.runtime.support.FastCamelRuntime.init(FastCamelRuntime.java:51)
at io.quarkus.camel.core.runtime.CamelTemplate.init(CamelTemplate.java:43)
at io.quarkus.deployment.steps.CamelInitProcessor$createInitTask17.deploy(Unknown Source)
... 57 more
Caused by: java.lang.IllegalStateException: The datasources are not ready to be consumed: the runtime configuration has not been injected yet
at io.quarkus.agroal.runtime.AbstractDataSourceProducer.checkRuntimeConfig(AbstractDataSourceProducer.java:195)
at io.quarkus.agroal.runtime.AbstractDataSourceProducer.getDefaultRuntimeConfig(AbstractDataSourceProducer.java:63)
at io.quarkus.agroal.runtime.DataSourceProducer.createDefaultDataSource(Unknown Source)
at io.quarkus.agroal.runtime.DataSourceProducer_ProducerMethod_createDefaultDataSource_7c487e3ef869f878aa871e917c94f4d26d5d5c56_Bean.create(Unknown Source)
at io.quarkus.agroal.runtime.DataSourceProducer_ProducerMethod_createDefaultDataSource_7c487e3ef869f878aa871e917c94f4d26d5d5c56_Bean.create(Unknown Source)
at io.quarkus.arc.AbstractSharedContext.createInstanceHandle(AbstractSharedContext.java:86)
at io.quarkus.arc.AbstractSharedContext.lambda$new$0(AbstractSharedContext.java:33)
at io.quarkus.arc.ComputingCache$CacheFunction.lambda$apply$0(ComputingCache.java:115)
at io.quarkus.arc.LazyValue.get(LazyValue.java:42)
at io.quarkus.arc.ComputingCache.getValue(ComputingCache.java:57)
at io.quarkus.arc.AbstractSharedContext.get(AbstractSharedContext.java:39)
at io.quarkus.agroal.runtime.DataSourceProducer_ProducerMethod_createDefaultDataSource_7c487e3ef869f878aa871e917c94f4d26d5d5c56_Bean.get(Unknown Source)
at io.quarkus.agroal.runtime.DataSourceProducer_ProducerMethod_createDefaultDataSource_7c487e3ef869f878aa871e917c94f4d26d5d5c56_Bean.get(Unknown Source)
at io.quarkus.it.camel.jdbc.CamelLifecycle_Bean.create(Unknown Source)
at io.quarkus.it.camel.jdbc.CamelLifecycle_Bean.create(Unknown Source)
at io.quarkus.arc.AbstractSharedContext.createInstanceHandle(AbstractSharedContext.java:86)
at io.quarkus.arc.AbstractSharedContext.lambda$new$0(AbstractSharedContext.java:33)
at io.quarkus.arc.ComputingCache$CacheFunction.lambda$apply$0(ComputingCache.java:115)
at io.quarkus.arc.LazyValue.get(LazyValue.java:42)
at io.quarkus.arc.ComputingCache.getValue(ComputingCache.java:57)
at io.quarkus.arc.AbstractSharedContext.get(AbstractSharedContext.java:39)
at io.quarkus.it.camel.jdbc.CamelLifecycle_ClientProxy.delegate(Unknown Source)
at io.quarkus.it.camel.jdbc.CamelLifecycle_ClientProxy.getContextualInstance(Unknown Source)
at io.quarkus.it.camel.jdbc.CamelLifecycle_Observer_initializing_efc0f046e9729a2e45b64b01b6ae7f050d5bccd4.notify(Unknown Source)
at io.quarkus.arc.EventImpl$Notifier.notify(EventImpl.java:244)
at io.quarkus.arc.EventImpl.fire(EventImpl.java:85)
at io.quarkus.camel.core.runtime.support.FastCamelRuntime.fireEvent(FastCamelRuntime.java:161)
at io.quarkus.camel.core.runtime.support.FastCamelRuntime.doInit(FastCamelRuntime.java:85)
... 60 more
```
Here is the reproducer ( `cd integration-tests/camel-jdbc && mvn clean verify` ):
https://github.com/ppalaga/quarkus/commits/190429-camel-jdbc
| ff5dda2e7ea6b20b6cc0675772c1df3489089f7f | 9ac94cc10e34c86220f2c1b168f24c73360349d2 | https://github.com/quarkusio/quarkus/compare/ff5dda2e7ea6b20b6cc0675772c1df3489089f7f...9ac94cc10e34c86220f2c1b168f24c73360349d2 | diff --git a/extensions/agroal/deployment/src/main/java/io/quarkus/agroal/deployment/AgroalProcessor.java b/extensions/agroal/deployment/src/main/java/io/quarkus/agroal/deployment/AgroalProcessor.java
index b7043e57fb3..4b91fedeb81 100644
--- a/extensions/agroal/deployment/src/main/java/io/quarkus/agroal/deployment/AgroalProcessor.java
+++ b/extensions/agroal/deployment/src/main/java/io/quarkus/agroal/deployment/AgroalProcessor.java
@@ -27,7 +27,6 @@
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Default;
import javax.enterprise.inject.Produces;
-import javax.inject.Singleton;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationValue;
@@ -195,7 +194,7 @@ public void write(String name, byte[] data) {
if (agroalBuildTimeConfig.defaultDataSource.driver.isPresent()) {
MethodCreator defaultDataSourceMethodCreator = classCreator.getMethodCreator("createDefaultDataSource",
AgroalDataSource.class);
- defaultDataSourceMethodCreator.addAnnotation(Singleton.class);
+ defaultDataSourceMethodCreator.addAnnotation(ApplicationScoped.class);
defaultDataSourceMethodCreator.addAnnotation(Produces.class);
defaultDataSourceMethodCreator.addAnnotation(Default.class);
| ['extensions/agroal/deployment/src/main/java/io/quarkus/agroal/deployment/AgroalProcessor.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,658,157 | 715,844 | 95,325 | 930 | 191 | 27 | 3 | 1 | 11,203 | 356 | 2,496 | 114 | 2 | 1 | 2019-04-30T13:49:46 | 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,107 | quarkusio/quarkus/1810/1636 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/1636 | https://github.com/quarkusio/quarkus/pull/1810 | https://github.com/quarkusio/quarkus/issues/1636#issuecomment-480983579 | 1 | fixes | Native image build in docker writes files as root to target dir | If you build a native image inside a docker container with `mvn clean package -Pnative -Dnative-image.docker-build=true` the artefacts are written by root.
As a result, subsequent commands like `mvn clean` fail, and artifacts can only be removed with `sudo rm`.
It is possible to run processes in Docker with a different user with the `--user` command line argument, but we will need to find a portable way of running the docker build with the current user id | 90f5d56b8df14fbcbc6895a5695c5f814865b1bb | a37451ccb53eaaff036c1d700b6f2f8e1a2e88c7 | https://github.com/quarkusio/quarkus/compare/90f5d56b8df14fbcbc6895a5695c5f814865b1bb...a37451ccb53eaaff036c1d700b6f2f8e1a2e88c7 | diff --git a/core/creator/src/main/java/io/quarkus/creator/phase/nativeimage/NativeImagePhase.java b/core/creator/src/main/java/io/quarkus/creator/phase/nativeimage/NativeImagePhase.java
index 88ea58d798a..305391f5306 100644
--- a/core/creator/src/main/java/io/quarkus/creator/phase/nativeimage/NativeImagePhase.java
+++ b/core/creator/src/main/java/io/quarkus/creator/phase/nativeimage/NativeImagePhase.java
@@ -20,7 +20,8 @@
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
-import java.io.PrintStream;
+import java.io.InputStream;
+import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -313,6 +314,14 @@ public void provideOutcome(AppCreator ctx) throws AppCreatorException {
// E.g. "/usr/bin/docker run -v {{PROJECT_DIR}}:/project --rm quarkus/graalvm-native-image"
nativeImage = new ArrayList<>();
Collections.addAll(nativeImage, containerRuntime, "run", "-v", outputDir.toAbsolutePath() + ":/project:z", "--rm");
+
+ if (IS_LINUX & "docker".equals(containerRuntime)) {
+ String uid = getLinuxID("-ur");
+ String gid = getLinuxID("-gr");
+ if (uid != null & gid != null & !"".equals(uid) & !"".equals(gid)) {
+ Collections.addAll(nativeImage, "--user", uid.concat(":").concat(gid));
+ }
+ }
nativeImage.addAll(containerRuntimeOptions);
nativeImage.add(this.builderImage);
} else {
@@ -506,6 +515,52 @@ private boolean isThisGraalVMRCObsolete() {
return false;
}
+ private static String getLinuxID(String option) {
+ Process process;
+
+ try {
+ StringBuilder responseBuilder = new StringBuilder();
+ String line;
+
+ ProcessBuilder idPB = new ProcessBuilder().command("id", option);
+ idPB.redirectError(new File("/dev/null"));
+ idPB.redirectOutput(new File("/dev/null"));
+
+ process = idPB.start();
+ try (InputStream inputStream = process.getInputStream()) {
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
+ while ((line = reader.readLine()) != null) {
+ responseBuilder.append(line);
+ }
+ safeWaitFor(process);
+ return responseBuilder.toString();
+ }
+ } catch (Throwable t) {
+ safeWaitFor(process);
+ throw t;
+ }
+ } catch (IOException e) { //from process.start()
+ //swallow and return null id
+ return null;
+ }
+ }
+
+ static void safeWaitFor(Process process) {
+ boolean intr = false;
+ try {
+ for (;;)
+ try {
+ process.waitFor();
+ return;
+ } catch (InterruptedException ex) {
+ intr = true;
+ }
+ } finally {
+ if (intr)
+ Thread.currentThread().interrupt();
+ }
+ }
+
private static String detectNoPIE() {
String argument = testGCCArgument("-no-pie");
| ['core/creator/src/main/java/io/quarkus/creator/phase/nativeimage/NativeImagePhase.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,524,947 | 690,538 | 92,045 | 907 | 2,025 | 347 | 57 | 1 | 468 | 77 | 104 | 5 | 0 | 0 | 2019-04-02T08:45: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,126 | quarkusio/quarkus/35172/35171 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/35171 | https://github.com/quarkusio/quarkus/pull/35172 | https://github.com/quarkusio/quarkus/pull/35172 | 1 | fixes | kafka-streams: feature not listed on startup | ### Describe the bug
Develop a microservice based on the quarkus kafka-streams extension.
Run quarkus:dev and look at the start logs of Quarkus.
kafka-streams does not appear in the list.
### Expected behavior
kafka-streams should be listed in the activated extensions
### Actual behavior
kafka-streams does not appear, probably since this commit https://github.com/quarkusio/quarkus/commit/4bd0553402aa0b6009d7b36e84fc70df385db572, i.e. whenever the microservice is launched in JVM mode
### How to Reproduce?
[reproducer-kafka-streams-not-listed.zip](https://github.com/quarkusio/quarkus/files/12242048/reproducer-kafka-streams-not-listed.zip)
1. unzip above code.quarkus.io generated project
2. run mvn quarkus:dev
3. the following log line: `Installed features: [cdi, kafka-client]` does not contain kafka-streams
### Output of `uname -a` or `ver`
Linux 5.19.0-50-generic #50-Ubuntu SMP PREEMPT_DYNAMIC x86_64 x86_64 x86_64 GNU/Linux
### Output of `java -version`
openjdk version "17.0.8" 2023-07-18
### GraalVM version (if different from Java)
OpenJDK Runtime Environment GraalVM CE 17.0.8+7.1 (build 17.0.8+7-jvmci-23.0-b15)
### Quarkus version or git rev
3.2.2.Final
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
Apache Maven 3.9.3
### Additional information
_No response_ | 9aa28e347ff1441e35b9a82f47a930182b8860a7 | b884a10acdd51740ab2e1aed015e3b9e3d3d9ef5 | https://github.com/quarkusio/quarkus/compare/9aa28e347ff1441e35b9a82f47a930182b8860a7...b884a10acdd51740ab2e1aed015e3b9e3d3d9ef5 | diff --git a/extensions/kafka-streams/deployment/src/main/java/io/quarkus/kafka/streams/deployment/KafkaStreamsProcessor.java b/extensions/kafka-streams/deployment/src/main/java/io/quarkus/kafka/streams/deployment/KafkaStreamsProcessor.java
index 915ab5d7158..112d70f3467 100644
--- a/extensions/kafka-streams/deployment/src/main/java/io/quarkus/kafka/streams/deployment/KafkaStreamsProcessor.java
+++ b/extensions/kafka-streams/deployment/src/main/java/io/quarkus/kafka/streams/deployment/KafkaStreamsProcessor.java
@@ -44,17 +44,18 @@ class KafkaStreamsProcessor {
public static final String DEFAULT_PARTITION_GROUPER = "org.apache.kafka.streams.processor.DefaultPartitionGrouper";
+ @BuildStep
+ FeatureBuildItem feature() {
+ return new FeatureBuildItem(Feature.KAFKA_STREAMS);
+ }
+
@BuildStep(onlyIf = NativeOrNativeSourcesBuild.class)
- void build(BuildProducer<FeatureBuildItem> feature,
- BuildProducer<ReflectiveClassBuildItem> reflectiveClasses,
+ void build(BuildProducer<ReflectiveClassBuildItem> reflectiveClasses,
BuildProducer<JniRuntimeAccessBuildItem> jniRuntimeAccessibleClasses,
BuildProducer<RuntimeReinitializedClassBuildItem> reinitialized,
BuildProducer<NativeImageResourceBuildItem> nativeLibs,
LaunchModeBuildItem launchMode,
NativeImageRunnerBuildItem nativeImageRunner) throws IOException {
-
- feature.produce(new FeatureBuildItem(Feature.KAFKA_STREAMS));
-
registerClassesThatAreLoadedThroughReflection(reflectiveClasses, launchMode);
registerClassesThatAreAccessedViaJni(jniRuntimeAccessibleClasses);
addSupportForRocksDbLib(nativeLibs, nativeImageRunner); | ['extensions/kafka-streams/deployment/src/main/java/io/quarkus/kafka/streams/deployment/KafkaStreamsProcessor.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 27,377,066 | 5,400,980 | 694,525 | 6,370 | 398 | 84 | 11 | 1 | 1,329 | 156 | 402 | 45 | 2 | 0 | 2023-08-02T15:53:22 | 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,110 | quarkusio/quarkus/3161/2991 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/2991 | https://github.com/quarkusio/quarkus/pull/3161 | https://github.com/quarkusio/quarkus/pull/3161#issuecomment-509922559 | 1 | fix | OpenAPI: RESTEASY003210 issue with @ApplicationPath("") | I am not a JAX-RS expert, but I think that `@ApplicationPath("")` and `@ApplicationPath("/")` are the same.
Javadoc for `String value();` in `@ApplicationPath`:
> Defines the base URI for all resource URIs. A trailing '/' character will be automatically appended if one is not present.
If this is correct you can continue to read this issue.
---
**Describe the bug**
When using `@ApplicationPath("")` the OpenAPI specification is not served.
**Expected behavior**
```
GET http://localhost:8080/openapi
```
Returns a Yaml OpenAPI.
**Actual behavior**
```
GET http://localhost:8080/openapi
```
Returns:
```
RESTEASY003210: Could not find resource for full path: http://localhost:8080/openapi
```
**To Reproduce**
Steps to reproduce the behavior:
1. Create a simple project with `[cdi, resteasy, resteasy-jsonb, smallrye-openapi, swagger-ui]`
2. Create 2 simple classes:
```java
package com.example.openapi;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("")
public class RestApplication extends Application {
}
```
```java
package com.example.openapi;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.io.InputStream;
import java.util.Map;
import java.util.List;
import javax.validation.constraints.*;
import javax.validation.Valid;
@Path("/ping")
public class PingApi {
@GET
public Response pingGet() {
return Response.ok().entity("magic!").build();
}
}
```
3. Open http://localhost:8080/openapi
**Environment (please complete the following information):**
- Output of `uname -a` or `ver`:
```
Darwin MacBook-Pro.local 18.5.0 Darwin Kernel Version 18.5.0: Mon Mar 11 20:40:32 PDT 2019; root:xnu-4903.251.3~3/RELEASE_X86_64 x86_64
```
- Output of `java -version`:
```
java version "1.8.0_161"
Java(TM) SE Runtime Environment (build 1.8.0_161-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.161-b12, mixed mode)
```
- GraalVM version (if different from Java): not used
- Quarkus version or git rev: 0.17.0
| 1cb51f9c10f5ebf7be5ff134467e6c6fdafec367 | fdfc0bcb2680f7c7d10d6566e70bfefac102903c | https://github.com/quarkusio/quarkus/compare/1cb51f9c10f5ebf7be5ff134467e6c6fdafec367...fdfc0bcb2680f7c7d10d6566e70bfefac102903c | diff --git a/extensions/resteasy/deployment/src/main/java/io/quarkus/resteasy/deployment/ResteasyProcessor.java b/extensions/resteasy/deployment/src/main/java/io/quarkus/resteasy/deployment/ResteasyProcessor.java
index 3c02dd1bbb6..009ab2761f2 100755
--- a/extensions/resteasy/deployment/src/main/java/io/quarkus/resteasy/deployment/ResteasyProcessor.java
+++ b/extensions/resteasy/deployment/src/main/java/io/quarkus/resteasy/deployment/ResteasyProcessor.java
@@ -59,7 +59,7 @@ public void build(
String path = resteasyServerConfig.get().getPath();
//if JAX-RS is installed at the root location we use a filter, otherwise we use a Servlet and take over the whole mapped path
- if (resteasyServerConfig.get().getPath().equals("/")) {
+ if (path.equals("/") || path.isEmpty()) {
filter.produce(FilterBuildItem.builder(JAX_RS_FILTER_NAME, ResteasyFilter.class.getName()).setLoadOnStartup(1)
.addFilterServletNameMapping("default", DispatcherType.REQUEST).setAsyncSupported(true)
.build()); | ['extensions/resteasy/deployment/src/main/java/io/quarkus/resteasy/deployment/ResteasyProcessor.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 3,876,306 | 747,233 | 100,584 | 1,074 | 123 | 26 | 2 | 1 | 2,094 | 241 | 539 | 84 | 4 | 7 | 2019-07-10T05:40: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,139 | quarkusio/quarkus/34655/34628 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/34628 | https://github.com/quarkusio/quarkus/pull/34655 | https://github.com/quarkusio/quarkus/pull/34655 | 1 | fixes | Quarkus 3.2: Hibernate ORM configuration problem | ### Describe the bug
I'm upgrading to Quarkus 3.2 from 2.x (lates) and I need to add one new config property:
quarkus.hibernate-orm.mydatasource.mapping.timezone.default-storage=normalize
When I try to build the app with Maven package goal I'm gettting this error:
SRCFG00014: The config property quarkus.hibernate-orm.mydatasource.mapping.query.query-plan-cache-max-size is required but it could not be found in any config source
### Expected behavior
The reported configuration property is both bad (there is no "mapping" prefix") and not mandatory, so it shouldn't complain about it.
### Actual behavior
Halts the build with the mentioned error message.
### How to Reproduce?
_No response_
### Output of `uname -a` or `ver`
_No response_
### Output of `java -version`
17
### GraalVM version (if different from Java)
_No response_
### Quarkus version or git rev
3.2.0
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
Maven 3.8
### Additional information
_No response_ | b71789b459d308bcd06e6bb90982709d62618d09 | ad94afbdc9951f7c0dcd31aa7756be49223f3df8 | https://github.com/quarkusio/quarkus/compare/b71789b459d308bcd06e6bb90982709d62618d09...ad94afbdc9951f7c0dcd31aa7756be49223f3df8 | diff --git a/extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/HibernateOrmConfigPersistenceUnit.java b/extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/HibernateOrmConfigPersistenceUnit.java
index 3959bb5f707..7462c4b1308 100644
--- a/extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/HibernateOrmConfigPersistenceUnit.java
+++ b/extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/HibernateOrmConfigPersistenceUnit.java
@@ -341,71 +341,98 @@ public boolean isAnyPropertySet() {
@ConfigGroup
public static class HibernateOrmConfigPersistenceUnitMapping {
/**
- * How to store timezones in the database by default
- * for properties of type `OffsetDateTime` and `ZonedDateTime`.
- *
- * This default may be overridden on a per-property basis using `@TimeZoneStorage`.
- *
- * NOTE: Properties of type `OffsetTime` are https://hibernate.atlassian.net/browse/HHH-16287[not affected by this
- * setting].
- *
- * `default`::
- * Equivalent to `native` if supported, `normalize-utc` otherwise.
- * `auto`::
- * Equivalent to `native` if supported, `column` otherwise.
- * `native`::
- * Stores the timestamp and timezone in a column of type `timestamp with time zone`.
- * +
- * Only available on some databases/dialects;
- * if not supported, an exception will be thrown during static initialization.
- * `column`::
- * Stores the timezone in a separate column next to the timestamp column.
- * +
- * Use `@TimeZoneColumn` on the relevant entity property to customize the timezone column.
- * `normalize-utc`::
- * Does not store the timezone, and loses timezone information upon persisting.
- * +
- * Instead, normalizes the value to a timestamp in the UTC timezone.
- * `normalize`::
- * Does not store the timezone, and loses timezone information upon persisting.
- * +
- * Instead, normalizes the value:
- * * upon persisting to the database, to a timestamp in the JDBC timezone
- * set through `quarkus.hibernate-orm.jdbc.timezone`,
- * or the JVM default timezone if not set.
- * * upon reading back from the database, to the JVM default timezone.
- * +
- * Use this to get the legacy behavior of Quarkus 2 / Hibernate ORM 5 or older.
- *
- * @asciidoclet
+ * Timezone configuration.
*/
- @ConfigItem(name = "timezone.default-storage", defaultValueDocumentation = "default")
- public Optional<TimeZoneStorageType> timeZoneDefaultStorage;
+ @ConfigItem
+ public Timezone timezone;
/**
- * The optimizer to apply to identifier generators
- * whose optimizer is not configured explicitly.
- *
- * Only relevant for table- and sequence-based identifier generators.
- * Other generators, such as UUID-based generators, will ignore this setting.
- *
- * The optimizer is responsible for pooling new identifier values,
- * in order to reduce the frequency of database calls to retrieve those values
- * and thereby improve performance.
- *
- * @asciidoclet
+ * Optimizer configuration.
*/
- @ConfigItem(name = "id.optimizer.default", defaultValueDocumentation = "pooled-lo")
- // Note this needs to be a build-time property due to
- // org.hibernate.boot.internal.InFlightMetadataCollectorImpl.handleIdentifierValueBinding
- // which may call (indirectly) org.hibernate.id.enhanced.SequenceStructure.buildSequence
- // whose output depends on org.hibernate.id.enhanced.SequenceStructure.applyIncrementSizeToSourceValues
- // which is determined by the optimizer.
- public Optional<IdOptimizerType> idOptimizerDefault;
+ @ConfigItem
+ public Id id;
+
+ @ConfigGroup
+ public static class Timezone {
+ /**
+ * How to store timezones in the database by default
+ * for properties of type `OffsetDateTime` and `ZonedDateTime`.
+ *
+ * This default may be overridden on a per-property basis using `@TimeZoneStorage`.
+ *
+ * NOTE: Properties of type `OffsetTime` are https://hibernate.atlassian.net/browse/HHH-16287[not affected by this
+ * setting].
+ *
+ * `default`::
+ * Equivalent to `native` if supported, `normalize-utc` otherwise.
+ * `auto`::
+ * Equivalent to `native` if supported, `column` otherwise.
+ * `native`::
+ * Stores the timestamp and timezone in a column of type `timestamp with time zone`.
+ * +
+ * Only available on some databases/dialects;
+ * if not supported, an exception will be thrown during static initialization.
+ * `column`::
+ * Stores the timezone in a separate column next to the timestamp column.
+ * +
+ * Use `@TimeZoneColumn` on the relevant entity property to customize the timezone column.
+ * `normalize-utc`::
+ * Does not store the timezone, and loses timezone information upon persisting.
+ * +
+ * Instead, normalizes the value to a timestamp in the UTC timezone.
+ * `normalize`::
+ * Does not store the timezone, and loses timezone information upon persisting.
+ * +
+ * Instead, normalizes the value:
+ * * upon persisting to the database, to a timestamp in the JDBC timezone
+ * set through `quarkus.hibernate-orm.jdbc.timezone`,
+ * or the JVM default timezone if not set.
+ * * upon reading back from the database, to the JVM default timezone.
+ * +
+ * Use this to get the legacy behavior of Quarkus 2 / Hibernate ORM 5 or older.
+ *
+ * @asciidoclet
+ */
+ @ConfigItem(name = "default-storage", defaultValueDocumentation = "default")
+ public Optional<TimeZoneStorageType> timeZoneDefaultStorage;
+ }
+
+ @ConfigGroup
+ public static class Id {
+ /**
+ * Optimizer configuration.
+ */
+ @ConfigItem
+ public Optimizer optimizer;
+
+ @ConfigGroup
+ public static class Optimizer {
+ /**
+ * The optimizer to apply to identifier generators
+ * whose optimizer is not configured explicitly.
+ *
+ * Only relevant for table- and sequence-based identifier generators.
+ * Other generators, such as UUID-based generators, will ignore this setting.
+ *
+ * The optimizer is responsible for pooling new identifier values,
+ * in order to reduce the frequency of database calls to retrieve those values
+ * and thereby improve performance.
+ *
+ * @asciidoclet
+ */
+ @ConfigItem(name = "default", defaultValueDocumentation = "pooled-lo")
+ // Note this needs to be a build-time property due to
+ // org.hibernate.boot.internal.InFlightMetadataCollectorImpl.handleIdentifierValueBinding
+ // which may call (indirectly) org.hibernate.id.enhanced.SequenceStructure.buildSequence
+ // whose output depends on org.hibernate.id.enhanced.SequenceStructure.applyIncrementSizeToSourceValues
+ // which is determined by the optimizer.
+ public Optional<IdOptimizerType> idOptimizerDefault;
+ }
+ }
public boolean isAnyPropertySet() {
- return timeZoneDefaultStorage.isPresent()
- || idOptimizerDefault.isPresent();
+ return timezone.timeZoneDefaultStorage.isPresent()
+ || id.optimizer.idOptimizerDefault.isPresent();
}
}
diff --git a/extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/HibernateOrmProcessor.java b/extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/HibernateOrmProcessor.java
index 953370f0512..ed82729ff90 100644
--- a/extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/HibernateOrmProcessor.java
+++ b/extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/HibernateOrmProcessor.java
@@ -953,12 +953,12 @@ private static void producePersistenceUnitDescriptorFromConfig(
.setProperty(EntityManagerFactoryBuilderImpl.METADATA_BUILDER_CONTRIBUTOR, className));
// Mapping
- if (persistenceUnitConfig.mapping.timeZoneDefaultStorage.isPresent()) {
+ if (persistenceUnitConfig.mapping.timezone.timeZoneDefaultStorage.isPresent()) {
descriptor.getProperties().setProperty(AvailableSettings.TIMEZONE_DEFAULT_STORAGE,
- persistenceUnitConfig.mapping.timeZoneDefaultStorage.get().name());
+ persistenceUnitConfig.mapping.timezone.timeZoneDefaultStorage.get().name());
}
descriptor.getProperties().setProperty(AvailableSettings.PREFERRED_POOLED_OPTIMIZER,
- persistenceUnitConfig.mapping.idOptimizerDefault
+ persistenceUnitConfig.mapping.id.optimizer.idOptimizerDefault
.orElse(HibernateOrmConfigPersistenceUnit.IdOptimizerType.POOLED_LO).configName);
//charset
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 a9270d50321..72f7ce71a52 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
@@ -286,12 +286,12 @@ private static ParsedPersistenceXmlDescriptor generateReactivePersistenceUnit(
.setProperty(AvailableSettings.IMPLICIT_NAMING_STRATEGY, namingStrategy));
// Mapping
- if (persistenceUnitConfig.mapping.timeZoneDefaultStorage.isPresent()) {
+ if (persistenceUnitConfig.mapping.timezone.timeZoneDefaultStorage.isPresent()) {
desc.getProperties().setProperty(AvailableSettings.TIMEZONE_DEFAULT_STORAGE,
- persistenceUnitConfig.mapping.timeZoneDefaultStorage.get().name());
+ persistenceUnitConfig.mapping.timezone.timeZoneDefaultStorage.get().name());
}
desc.getProperties().setProperty(AvailableSettings.PREFERRED_POOLED_OPTIMIZER,
- persistenceUnitConfig.mapping.idOptimizerDefault
+ persistenceUnitConfig.mapping.id.optimizer.idOptimizerDefault
.orElse(HibernateOrmConfigPersistenceUnit.IdOptimizerType.POOLED_LO).configName);
//charset | ['extensions/hibernate-reactive/deployment/src/main/java/io/quarkus/hibernate/reactive/deployment/HibernateReactiveProcessor.java', 'extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/HibernateOrmConfigPersistenceUnit.java', 'extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/HibernateOrmProcessor.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 27,246,603 | 5,374,796 | 691,429 | 6,369 | 8,531 | 1,571 | 157 | 3 | 1,019 | 144 | 250 | 45 | 0 | 0 | 2023-07-10T15:42:41 | 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,129 | quarkusio/quarkus/34994/34993 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/34993 | https://github.com/quarkusio/quarkus/pull/34994 | https://github.com/quarkusio/quarkus/pull/34994 | 1 | fixes | OIDC UserInfo endpoint is called even if the token verification fails | ### Describe the bug
OIDC UserInfo endpoint is called even if the token verification fails which is a redundant, unnecessary call.
I already did some work related to this issue: https://github.com/quarkusio/quarkus/commit/1677a8f997209c2cb134669c9c943d1d90f3cb48, but the fix was incomplete, the test there just focuses on confirming there is only one UserInfo call in case of the successful verification - but no negative test scenario.
The problem is, `OidcIdentityProvider` keeps checking UserInfo first and then starts verifying the token. OIDC certification tests I'm trying, https://www.certification.openid.net/login.html, have flagged it
### 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_ | d2ed11f077987ec84acd881cc6dc1fa0789053e5 | dac533fef045802b96ce09d817df74af8fa40725 | https://github.com/quarkusio/quarkus/compare/d2ed11f077987ec84acd881cc6dc1fa0789053e5...dac533fef045802b96ce09d817df74af8fa40725 | diff --git a/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/OidcIdentityProvider.java b/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/OidcIdentityProvider.java
index 5d61792865d..92b31d90728 100644
--- a/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/OidcIdentityProvider.java
+++ b/extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/OidcIdentityProvider.java
@@ -45,7 +45,6 @@ public class OidcIdentityProvider implements IdentityProvider<TokenAuthenticatio
static final String NEW_AUTHENTICATION = "new_authentication";
private static final Uni<TokenVerificationResult> NULL_CODE_ACCESS_TOKEN_UNI = Uni.createFrom().nullItem();
- private static final Uni<UserInfo> NULL_USER_INFO_UNI = Uni.createFrom().nullItem();
private static final String CODE_ACCESS_TOKEN_RESULT = "code_flow_access_token_result";
@Inject
@@ -107,21 +106,21 @@ && isOpaqueAccessToken(vertxContext, request, resolvedContext)) {
// Typically it will be done for bearer access tokens therefore even if the access token has expired
// the client will be able to refresh if needed, no refresh token is available to Quarkus during the
// bearer access token verification
-
- Uni<UserInfo> userInfo = resolvedContext.oidcConfig.authentication.isUserInfoRequired().orElse(false)
- ? getUserInfoUni(vertxContext, request, resolvedContext)
- : NULL_USER_INFO_UNI;
-
- return userInfo.onItemOrFailure().transformToUni(
- new BiFunction<UserInfo, Throwable, Uni<? extends SecurityIdentity>>() {
- @Override
- public Uni<SecurityIdentity> apply(UserInfo userInfo, Throwable t) {
- if (t != null) {
- return Uni.createFrom().failure(new AuthenticationFailedException(t));
+ if (resolvedContext.oidcConfig.authentication.isUserInfoRequired().orElse(false)) {
+ return getUserInfoUni(vertxContext, request, resolvedContext).onItemOrFailure().transformToUni(
+ new BiFunction<UserInfo, Throwable, Uni<? extends SecurityIdentity>>() {
+ @Override
+ public Uni<SecurityIdentity> apply(UserInfo userInfo, Throwable t) {
+ if (t != null) {
+ return Uni.createFrom().failure(new AuthenticationFailedException(t));
+ }
+ return validateTokenWithUserInfoAndCreateIdentity(vertxContext, request, resolvedContext,
+ userInfo);
}
- return validateTokenWithUserInfoAndCreateIdentity(vertxContext, request, resolvedContext, userInfo);
- }
- });
+ });
+ } else {
+ return validateTokenWithUserInfoAndCreateIdentity(vertxContext, request, resolvedContext, null);
+ }
} else {
final Uni<TokenVerificationResult> primaryTokenUni;
if (isInternalIdToken(request)) {
@@ -184,7 +183,20 @@ public Uni<SecurityIdentity> apply(TokenVerificationResult codeAccessToken, Thro
Uni<TokenVerificationResult> tokenUni = verifyTokenUni(resolvedContext, request.getToken().getToken(),
false, userInfo);
- return createSecurityIdentityWithOidcServer(tokenUni, vertxContext, request, resolvedContext, userInfo);
+ return tokenUni.onItemOrFailure()
+ .transformToUni(
+ new BiFunction<TokenVerificationResult, Throwable, Uni<? extends SecurityIdentity>>() {
+ @Override
+ public Uni<SecurityIdentity> apply(TokenVerificationResult result, Throwable t) {
+ if (t != null) {
+ return Uni.createFrom().failure(new AuthenticationFailedException(t));
+ }
+
+ return createSecurityIdentityWithOidcServer(result, vertxContext, request,
+ resolvedContext, userInfo);
+ }
+ });
+
}
});
}
@@ -193,20 +205,32 @@ private Uni<SecurityIdentity> getUserInfoAndCreateIdentity(Uni<TokenVerification
RoutingContext vertxContext, TokenAuthenticationRequest request,
TenantConfigContext resolvedContext) {
- Uni<UserInfo> userInfo = resolvedContext.oidcConfig.authentication.isUserInfoRequired().orElse(false)
- ? getUserInfoUni(vertxContext, request, resolvedContext)
- : NULL_USER_INFO_UNI;
-
- return userInfo.onItemOrFailure().transformToUni(
- new BiFunction<UserInfo, Throwable, Uni<? extends SecurityIdentity>>() {
+ return tokenUni.onItemOrFailure()
+ .transformToUni(new BiFunction<TokenVerificationResult, Throwable, Uni<? extends SecurityIdentity>>() {
@Override
- public Uni<SecurityIdentity> apply(UserInfo userInfo, Throwable t) {
+ public Uni<SecurityIdentity> apply(TokenVerificationResult result, Throwable t) {
if (t != null) {
return Uni.createFrom().failure(new AuthenticationFailedException(t));
}
- return createSecurityIdentityWithOidcServer(tokenUni, vertxContext, request, resolvedContext, userInfo);
+ if (resolvedContext.oidcConfig.authentication.isUserInfoRequired().orElse(false)) {
+ return getUserInfoUni(vertxContext, request, resolvedContext).onItemOrFailure().transformToUni(
+ new BiFunction<UserInfo, Throwable, Uni<? extends SecurityIdentity>>() {
+ @Override
+ public Uni<SecurityIdentity> apply(UserInfo userInfo, Throwable t) {
+ if (t != null) {
+ return Uni.createFrom().failure(new AuthenticationFailedException(t));
+ }
+ return createSecurityIdentityWithOidcServer(result, vertxContext, request,
+ resolvedContext, userInfo);
+ }
+ });
+ } else {
+ return createSecurityIdentityWithOidcServer(result, vertxContext, request, resolvedContext, null);
+ }
+
}
});
+
}
private boolean isOpaqueAccessToken(RoutingContext vertxContext, TokenAuthenticationRequest request,
@@ -222,108 +246,100 @@ private boolean isOpaqueAccessToken(RoutingContext vertxContext, TokenAuthentica
return false;
}
- private Uni<SecurityIdentity> createSecurityIdentityWithOidcServer(Uni<TokenVerificationResult> tokenUni,
+ private Uni<SecurityIdentity> createSecurityIdentityWithOidcServer(TokenVerificationResult result,
RoutingContext vertxContext, TokenAuthenticationRequest request, TenantConfigContext resolvedContext,
final UserInfo userInfo) {
- return tokenUni.onItemOrFailure()
- .transformToUni(new BiFunction<TokenVerificationResult, Throwable, Uni<? extends SecurityIdentity>>() {
- @Override
- public Uni<SecurityIdentity> apply(TokenVerificationResult result, Throwable t) {
- if (t != null) {
- return Uni.createFrom().failure(new AuthenticationFailedException(t));
- }
- // Token has been verified, as a JWT or an opaque token, possibly involving
- // an introspection request.
- final TokenCredential tokenCred = request.getToken();
-
- JsonObject tokenJson = result.localVerificationResult;
- if (tokenJson == null) {
- // JSON token representation may be null not only if it is an opaque access token
- // but also if it is JWT and no JWK with a matching kid is available, asynchronous
- // JWK refresh has not finished yet, but the fallback introspection request has succeeded.
- tokenJson = OidcUtils.decodeJwtContent(tokenCred.getToken());
- }
- if (tokenJson != null) {
- try {
- OidcUtils.validatePrimaryJwtTokenType(resolvedContext.oidcConfig.token, tokenJson);
- JsonObject rolesJson = getRolesJson(vertxContext, resolvedContext, tokenCred, tokenJson,
- userInfo);
- SecurityIdentity securityIdentity = validateAndCreateIdentity(vertxContext, tokenCred,
- resolvedContext, tokenJson, rolesJson, userInfo, result.introspectionResult);
- // If the primary token is a bearer access token then there's no point of checking if
- // it should be refreshed as RT is only available for the code flow tokens
- if (isIdToken(request)
- && tokenAutoRefreshPrepared(result, vertxContext, resolvedContext.oidcConfig)) {
- return Uni.createFrom().failure(new TokenAutoRefreshException(securityIdentity));
- } else {
- return Uni.createFrom().item(securityIdentity);
- }
- } catch (Throwable ex) {
- return Uni.createFrom().failure(new AuthenticationFailedException(ex));
- }
- } else if (isIdToken(request)
- || tokenCred instanceof AccessTokenCredential
- && !((AccessTokenCredential) tokenCred).isOpaque()) {
- return Uni.createFrom()
- .failure(new AuthenticationFailedException("JWT token can not be converted to JSON"));
- } else {
- // ID Token or Bearer access token has been introspected or verified via Userinfo acquisition
- QuarkusSecurityIdentity.Builder builder = QuarkusSecurityIdentity.builder();
- builder.addCredential(tokenCred);
- OidcUtils.setSecurityIdentityUserInfo(builder, userInfo);
- OidcUtils.setSecurityIdentityConfigMetadata(builder, resolvedContext);
- final String userName;
- if (result.introspectionResult == null) {
- if (resolvedContext.oidcConfig.token.allowOpaqueTokenIntrospection &&
- resolvedContext.oidcConfig.token.verifyAccessTokenWithUserInfo.orElse(false)) {
- if (resolvedContext.oidcConfig.token.principalClaim.isPresent() && userInfo != null) {
- userName = userInfo.getString(resolvedContext.oidcConfig.token.principalClaim.get());
- } else {
- userName = "";
- }
- } else {
- // we don't expect this to ever happen
- LOG.debug("Illegal state - token introspection result is not available.");
- return Uni.createFrom().failure(new AuthenticationFailedException());
- }
- } else {
- OidcUtils.setSecurityIdentityIntrospection(builder, result.introspectionResult);
- String principalName = result.introspectionResult.getUsername();
- if (principalName == null) {
- principalName = result.introspectionResult.getSubject();
- }
- userName = principalName != null ? principalName : "";
+ // Token has been verified, as a JWT or an opaque token, possibly involving
+ // an introspection request.
+ final TokenCredential tokenCred = request.getToken();
- Set<String> scopes = result.introspectionResult.getScopes();
- if (scopes != null) {
- builder.addRoles(scopes);
- }
- }
- builder.setPrincipal(new Principal() {
- @Override
- public String getName() {
- return userName != null ? userName : "";
- }
- });
- if (userInfo != null) {
- OidcUtils.setSecurityIdentityRoles(builder, resolvedContext.oidcConfig,
- new JsonObject(userInfo.getJsonObject().toString()));
- }
- OidcUtils.setBlockingApiAttribute(builder, vertxContext);
- OidcUtils.setTenantIdAttribute(builder, resolvedContext.oidcConfig);
- OidcUtils.setRoutingContextAttribute(builder, vertxContext);
- SecurityIdentity identity = builder.build();
- // If the primary token is a bearer access token then there's no point of checking if
- // it should be refreshed as RT is only available for the code flow tokens
- if (isIdToken(request)
- && tokenAutoRefreshPrepared(result, vertxContext, resolvedContext.oidcConfig)) {
- return Uni.createFrom().failure(new TokenAutoRefreshException(identity));
- }
- return Uni.createFrom().item(identity);
- }
+ JsonObject tokenJson = result.localVerificationResult;
+ if (tokenJson == null) {
+ // JSON token representation may be null not only if it is an opaque access token
+ // but also if it is JWT and no JWK with a matching kid is available, asynchronous
+ // JWK refresh has not finished yet, but the fallback introspection request has succeeded.
+ tokenJson = OidcUtils.decodeJwtContent(tokenCred.getToken());
+ }
+ if (tokenJson != null) {
+ try {
+ OidcUtils.validatePrimaryJwtTokenType(resolvedContext.oidcConfig.token, tokenJson);
+ JsonObject rolesJson = getRolesJson(vertxContext, resolvedContext, tokenCred, tokenJson,
+ userInfo);
+ SecurityIdentity securityIdentity = validateAndCreateIdentity(vertxContext, tokenCred,
+ resolvedContext, tokenJson, rolesJson, userInfo, result.introspectionResult);
+ // If the primary token is a bearer access token then there's no point of checking if
+ // it should be refreshed as RT is only available for the code flow tokens
+ if (isIdToken(request)
+ && tokenAutoRefreshPrepared(result, vertxContext, resolvedContext.oidcConfig)) {
+ return Uni.createFrom().failure(new TokenAutoRefreshException(securityIdentity));
+ } else {
+ return Uni.createFrom().item(securityIdentity);
+ }
+ } catch (Throwable ex) {
+ return Uni.createFrom().failure(new AuthenticationFailedException(ex));
+ }
+ } else if (isIdToken(request)
+ || tokenCred instanceof AccessTokenCredential
+ && !((AccessTokenCredential) tokenCred).isOpaque()) {
+ return Uni.createFrom()
+ .failure(new AuthenticationFailedException("JWT token can not be converted to JSON"));
+ } else {
+ // ID Token or Bearer access token has been introspected or verified via Userinfo acquisition
+ QuarkusSecurityIdentity.Builder builder = QuarkusSecurityIdentity.builder();
+ builder.addCredential(tokenCred);
+ OidcUtils.setSecurityIdentityUserInfo(builder, userInfo);
+ OidcUtils.setSecurityIdentityConfigMetadata(builder, resolvedContext);
+ final String userName;
+ if (result.introspectionResult == null) {
+ if (resolvedContext.oidcConfig.token.allowOpaqueTokenIntrospection &&
+ resolvedContext.oidcConfig.token.verifyAccessTokenWithUserInfo.orElse(false)) {
+ if (resolvedContext.oidcConfig.token.principalClaim.isPresent() && userInfo != null) {
+ userName = userInfo.getString(resolvedContext.oidcConfig.token.principalClaim.get());
+ } else {
+ userName = "";
}
- });
+ } else {
+ // we don't expect this to ever happen
+ LOG.debug("Illegal state - token introspection result is not available.");
+ return Uni.createFrom().failure(new AuthenticationFailedException());
+ }
+ } else {
+ OidcUtils.setSecurityIdentityIntrospection(builder, result.introspectionResult);
+ String principalName = result.introspectionResult.getUsername();
+ if (principalName == null) {
+ principalName = result.introspectionResult.getSubject();
+ }
+ userName = principalName != null ? principalName : "";
+
+ Set<String> scopes = result.introspectionResult.getScopes();
+ if (scopes != null) {
+ builder.addRoles(scopes);
+ }
+ }
+ builder.setPrincipal(new Principal() {
+ @Override
+ public String getName() {
+ return userName != null ? userName : "";
+ }
+ });
+ if (userInfo != null) {
+ OidcUtils.setSecurityIdentityRoles(builder, resolvedContext.oidcConfig,
+ new JsonObject(userInfo.getJsonObject().toString()));
+ }
+ OidcUtils.setBlockingApiAttribute(builder, vertxContext);
+ OidcUtils.setTenantIdAttribute(builder, resolvedContext.oidcConfig);
+ OidcUtils.setRoutingContextAttribute(builder, vertxContext);
+ SecurityIdentity identity = builder.build();
+ // If the primary token is a bearer access token then there's no point of checking if
+ // it should be refreshed as RT is only available for the code flow tokens
+ if (isIdToken(request)
+ && tokenAutoRefreshPrepared(result, vertxContext, resolvedContext.oidcConfig)) {
+ return Uni.createFrom().failure(new TokenAutoRefreshException(identity));
+ }
+ return Uni.createFrom().item(identity);
+ }
+
}
private static boolean isInternalIdToken(TokenAuthenticationRequest request) {
diff --git a/integration-tests/oidc-tenancy/src/main/java/io/quarkus/it/keycloak/OidcResource.java b/integration-tests/oidc-tenancy/src/main/java/io/quarkus/it/keycloak/OidcResource.java
index 4dd17153b0e..bc3e34a53b3 100644
--- a/integration-tests/oidc-tenancy/src/main/java/io/quarkus/it/keycloak/OidcResource.java
+++ b/integration-tests/oidc-tenancy/src/main/java/io/quarkus/it/keycloak/OidcResource.java
@@ -115,9 +115,11 @@ public int resetIntrospectionEndpointCallCount() {
@Produces("application/json")
@Path("introspect")
public String introspect(@FormParam("client_id") String clientId, @FormParam("client_secret") String clientSecret,
- @HeaderParam("Authorization") String authorization) throws Exception {
+ @HeaderParam("Authorization") String authorization, @FormParam("token") String token) throws Exception {
introspectionEndpointCallCount++;
+ boolean activeStatus = introspection && !token.endsWith("-invalid");
+
String introspectionClientId = "none";
String introspectionClientSecret = "none";
if (clientSecret != null) {
@@ -139,7 +141,7 @@ public String introspect(@FormParam("client_id") String clientId, @FormParam("cl
}
return "{" +
- " \\"active\\": " + introspection + "," +
+ " \\"active\\": " + activeStatus + "," +
" \\"scope\\": \\"user\\"," +
" \\"email\\": \\"[email protected]\\"," +
" \\"username\\": \\"alice\\"," +
diff --git a/integration-tests/oidc-tenancy/src/main/java/io/quarkus/it/keycloak/TenantResource.java b/integration-tests/oidc-tenancy/src/main/java/io/quarkus/it/keycloak/TenantResource.java
index 81160469166..5c59e4bb2b6 100644
--- a/integration-tests/oidc-tenancy/src/main/java/io/quarkus/it/keycloak/TenantResource.java
+++ b/integration-tests/oidc-tenancy/src/main/java/io/quarkus/it/keycloak/TenantResource.java
@@ -74,6 +74,7 @@ public String userNameService(@PathParam("tenant") String tenant, @QueryParam("r
response += (",introspection_client_id:" + introspection.getString("introspection_client_id"));
response += (",introspection_client_secret:" + introspection.getString("introspection_client_secret"));
response += (",active:" + introspection.getBoolean("active"));
+ response += (",userinfo:" + getUserInfo().getPreferredUserName());
response += (",cache-size:" + tokenCache.getCacheSize());
}
diff --git a/integration-tests/oidc-tenancy/src/test/java/io/quarkus/it/keycloak/BearerTokenAuthorizationTest.java b/integration-tests/oidc-tenancy/src/test/java/io/quarkus/it/keycloak/BearerTokenAuthorizationTest.java
index ada7f136074..7926bdd89ce 100644
--- a/integration-tests/oidc-tenancy/src/test/java/io/quarkus/it/keycloak/BearerTokenAuthorizationTest.java
+++ b/integration-tests/oidc-tenancy/src/test/java/io/quarkus/it/keycloak/BearerTokenAuthorizationTest.java
@@ -491,7 +491,7 @@ public void testJwtTokenIntrospectionOnlyAndUserInfo() {
.statusCode(200)
.body(equalTo(
"tenant-oidc-introspection-only:alice,client_id:client-introspection-only,"
- + "introspection_client_id:none,introspection_client_secret:none,active:true,cache-size:0"));
+ + "introspection_client_id:none,introspection_client_secret:none,active:true,userinfo:alice,cache-size:0"));
}
RestAssured.when().get("/oidc/jwk-endpoint-call-count").then().body(equalTo("0"));
@@ -501,6 +501,26 @@ public void testJwtTokenIntrospectionOnlyAndUserInfo() {
RestAssured.when().get("/cache/size").then().body(equalTo("0"));
}
+ @Test
+ public void testNoUserInfoCallIfTokenIsInvalid() {
+ RestAssured.when().post("/oidc/userinfo-endpoint-call-count").then().body(equalTo("0"));
+ RestAssured.when().post("/oidc/enable-introspection").then().body(equalTo("true"));
+ RestAssured.when().post("/cache/clear").then().body(equalTo("0"));
+
+ String jwt = getAccessTokenFromSimpleOidc("2");
+ // Modify the signature
+ jwt += "-invalid";
+ RestAssured.given().auth().oauth2(jwt)
+ .when().get("/tenant/tenant-oidc-introspection-only/api/user")
+ .then()
+ .statusCode(401);
+
+ RestAssured.when().get("/oidc/introspection-endpoint-call-count").then().body(equalTo("1"));
+ RestAssured.when().post("/oidc/disable-introspection").then().body(equalTo("false"));
+ RestAssured.when().get("/oidc/userinfo-endpoint-call-count").then().body(equalTo("0"));
+ RestAssured.when().get("/cache/size").then().body(equalTo("0"));
+ }
+
@Test
public void testJwtTokenIntrospectionOnlyAndUserInfoCache() {
RestAssured.when().post("/oidc/jwk-endpoint-call-count").then().body(equalTo("0"));
@@ -537,7 +557,7 @@ private void verifyTokenIntrospectionAndUserInfoAreCached(String token1, int exp
.statusCode(200)
.body(equalTo(
"tenant-oidc-introspection-only-cache:alice,client_id:client-introspection-only-cache,"
- + "introspection_client_id:bob,introspection_client_secret:bob_secret,active:true,cache-size:"
+ + "introspection_client_id:bob,introspection_client_secret:bob_secret,active:true,userinfo:alice,cache-size:"
+ expectedCacheSize));
}
RestAssured.when().get("/oidc/introspection-endpoint-call-count").then().body(equalTo("1")); | ['integration-tests/oidc-tenancy/src/main/java/io/quarkus/it/keycloak/TenantResource.java', 'extensions/oidc/runtime/src/main/java/io/quarkus/oidc/runtime/OidcIdentityProvider.java', 'integration-tests/oidc-tenancy/src/test/java/io/quarkus/it/keycloak/BearerTokenAuthorizationTest.java', 'integration-tests/oidc-tenancy/src/main/java/io/quarkus/it/keycloak/OidcResource.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 27,401,653 | 5,404,711 | 694,875 | 6,373 | 17,854 | 2,751 | 258 | 1 | 1,099 | 151 | 259 | 43 | 2 | 0 | 2023-07-25T11:14:54 | 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,147 | quarkusio/quarkus/34307/34305 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/34305 | https://github.com/quarkusio/quarkus/pull/34307 | https://github.com/quarkusio/quarkus/pull/34307 | 1 | fixes | NPE at io.quarkus.opentelemetry.runtime.tracing.intrumentation.vertx.OpenTelemetryVertxTracingFactory$VertxDelegator.receiveResponse(OpenTelemetryVertxTracingFactory.java:102) | ### Describe the bug
While executing unit test on CI there are some errors that happens sometimes.
I feel it is related to https://github.com/quarkusio/quarkus/issues/33285 and https://github.com/quarkusio/quarkus/issues/33669.
```
INFO: HHH000406: Using bytecode reflection optimizer
Jun 26, 2023 8:34:51 AM io.quarkus.opentelemetry.runtime.tracing.intrumentation.vertx.OpenTelemetryVertxTracingFactory$VertxDelegator
WARN: VertxTracer delegate not set. Will not submit this trace. SpanKind: {}; Object: {}; Operation:{}.
Jun 26, 2023 8:34:51 AM io.vertx.core.net.impl.ConnectionBase
ERROR: Cannot invoke "java.lang.Throwable.getMessage()" because "failure" is null
java.lang.NullPointerException: Cannot invoke "java.lang.Throwable.getMessage()" because "failure" is null
at io.quarkus.opentelemetry.runtime.tracing.intrumentation.vertx.OpenTelemetryVertxTracingFactory$VertxDelegator.receiveResponse(OpenTelemetryVertxTracingFactory.java:102)
at io.vertx.core.http.impl.Http1xClientConnection.handleResponseEnd(Http1xClientConnection.java:935)
at io.vertx.core.http.impl.Http1xClientConnection.handleHttpMessage(Http1xClientConnection.java:814)
at io.vertx.core.http.impl.Http1xClientConnection.handleMessage(Http1xClientConnection.java:778)
at io.vertx.core.net.impl.ConnectionBase.read(ConnectionBase.java:158)
at io.vertx.core.net.impl.VertxHandler.channelRead(VertxHandler.java:153)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:442)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412)
at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireChannelRead(CombinedChannelDuplexHandler.java:436)
at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:346)
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:318)
at io.netty.channel.CombinedChannelDuplexHandler.channelRead(CombinedChannelDuplexHandler.java:251)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:442)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412)
at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1383)
at io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1246)
at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1295)
at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:529)
at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:468)
at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:290)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:444)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:412)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:440)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:420)
at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:166)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:788)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:724)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:650)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:562)
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:833)
```
In the code of `OpenTelemetryVertxTracingFactory`, `failure` is null here:
```
log.warnv("VertxTracer delegate not set. Will not submit this trace. " +
"response: {}; failure: {}.", response.toString(), failure.getMessage());
```
### Expected behavior
The tests should pass
### Actual behavior
The tests fail sometimes.
### How to Reproduce?
This reproducer: https://github.com/Adelrisk/quarkus-reproducer-33285 was mentioned here: https://github.com/quarkusio/quarkus/issues/33285 but i am not sure it can reproduce the issue.
### Output of `uname -a` or `ver`
_No response_
### Output of `java -version`
openjdk version "17.0.6" 2023-01-17 OpenJDK Runtime Environment GraalVM CE 22.3.1 (build 17.0.6+10-jvmci-22.3-b13) OpenJDK 64-Bit Server VM GraalVM CE 22.3.1 (build 17.0.6+10-jvmci-22.3-b13, mixed mode, sharing)
### GraalVM version (if different from Java)
_No response_
### Quarkus version or git rev
3.1.2.Final
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
Maven 3.8.6
### Additional information
| 5676d078c4b748a3cb56f724aeaab7c4ed79fdd2 | 508994ca6bbea7ae706a8431bfe42da21828f408 | https://github.com/quarkusio/quarkus/compare/5676d078c4b748a3cb56f724aeaab7c4ed79fdd2...508994ca6bbea7ae706a8431bfe42da21828f408 | diff --git a/extensions/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/tracing/intrumentation/vertx/OpenTelemetryVertxTracingFactory.java b/extensions/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/tracing/intrumentation/vertx/OpenTelemetryVertxTracingFactory.java
index 1d3b11390ca..56060eaa5d1 100644
--- a/extensions/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/tracing/intrumentation/vertx/OpenTelemetryVertxTracingFactory.java
+++ b/extensions/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/tracing/intrumentation/vertx/OpenTelemetryVertxTracingFactory.java
@@ -52,7 +52,10 @@ public Object receiveRequest(
final TagExtractor tagExtractor) {
if (delegate == null) {
log.warnv("VertxTracer delegate not set. Will not submit this trace. " +
- "SpanKind: {}; Object: {}; Operation:{}.", kind, request.toString(), operation);
+ "SpanKind: {}; Request: {}; Operation:{}.",
+ kind,
+ request == null ? "null" : request.toString(),
+ operation);
return null;
}
return delegate.receiveRequest(context, kind, policy, request, operation, headers, tagExtractor);
@@ -67,7 +70,9 @@ public void sendResponse(
final TagExtractor tagExtractor) {
if (delegate == null) {
log.warnv("VertxTracer delegate not set. Will not submit this trace. " +
- "response: {}; failure: {}.", response.toString(), failure.getMessage());
+ "Response: {}; Failure: {}.",
+ response == null ? "null" : response.toString(),
+ failure == null ? "null" : failure.getMessage());
return;
}
delegate.sendResponse(context, response, payload, failure, tagExtractor);
@@ -84,7 +89,10 @@ public Object sendRequest(
final TagExtractor tagExtractor) {
if (delegate == null) {
log.warnv("VertxTracer delegate not set. Will not submit this trace. " +
- "SpanKind: {}; Object: {}; Operation:{}.", kind, request.toString(), operation);
+ "SpanKind: {}; Request: {}; Operation:{}.",
+ kind,
+ request == null ? "null" : request.toString(),
+ operation);
return null;
}
return delegate.sendRequest(context, kind, policy, request, operation, headers, tagExtractor);
@@ -99,7 +107,9 @@ public void receiveResponse(
final TagExtractor tagExtractor) {
if (delegate == null) {
log.warnv("VertxTracer delegate not set. Will not submit this trace. " +
- "response: {}; failure: {}.", response.toString(), failure.getMessage());
+ "Response: {}; Failure: {}.",
+ response == null ? "null" : response.toString(),
+ failure == null ? "null" : failure.getMessage());
return;
}
delegate.receiveResponse(context, response, payload, failure, tagExtractor);
diff --git a/extensions/opentelemetry/runtime/src/test/java/io/quarkus/opentelemetry/runtime/tracing/intrumentation/vertx/OpenTelemetryVertxTracingFactoryTest.java b/extensions/opentelemetry/runtime/src/test/java/io/quarkus/opentelemetry/runtime/tracing/intrumentation/vertx/OpenTelemetryVertxTracingFactoryTest.java
index c4b43c0d4ed..ed1aadb63a5 100644
--- a/extensions/opentelemetry/runtime/src/test/java/io/quarkus/opentelemetry/runtime/tracing/intrumentation/vertx/OpenTelemetryVertxTracingFactoryTest.java
+++ b/extensions/opentelemetry/runtime/src/test/java/io/quarkus/opentelemetry/runtime/tracing/intrumentation/vertx/OpenTelemetryVertxTracingFactoryTest.java
@@ -50,6 +50,19 @@ void testSendRequest() {
assertNull(openTelemetryVertxTracingFactory.getVertxTracerDelegator().getDelegate());
}
+ @Test
+ void testSendNullRequest() {
+ assertNull(openTelemetryVertxTracingFactory.getVertxTracerDelegator().sendRequest(
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null));
+ assertNull(openTelemetryVertxTracingFactory.getVertxTracerDelegator().getDelegate());
+ }
+
@Test
void testReceiveRequest() {
assertNull(openTelemetryVertxTracingFactory.getVertxTracerDelegator().receiveRequest(
@@ -63,6 +76,19 @@ void testReceiveRequest() {
assertNull(openTelemetryVertxTracingFactory.getVertxTracerDelegator().getDelegate());
}
+ @Test
+ void testReceiveNullRequest() {
+ assertNull(openTelemetryVertxTracingFactory.getVertxTracerDelegator().receiveRequest(
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null));
+ assertNull(openTelemetryVertxTracingFactory.getVertxTracerDelegator().getDelegate());
+ }
+
@Test
void testSendResponse() {
assertDoesNotThrow(() -> openTelemetryVertxTracingFactory.getVertxTracerDelegator().sendResponse(
@@ -74,6 +100,17 @@ void testSendResponse() {
assertNull(openTelemetryVertxTracingFactory.getVertxTracerDelegator().getDelegate());
}
+ @Test
+ void testSendNullResponse() {
+ assertDoesNotThrow(() -> openTelemetryVertxTracingFactory.getVertxTracerDelegator().sendResponse(
+ null,
+ null,
+ null,
+ null,
+ null));
+ assertNull(openTelemetryVertxTracingFactory.getVertxTracerDelegator().getDelegate());
+ }
+
@Test
void testReceiveResponse() {
assertDoesNotThrow(() -> openTelemetryVertxTracingFactory.getVertxTracerDelegator().receiveResponse(
@@ -85,6 +122,17 @@ void testReceiveResponse() {
assertNull(openTelemetryVertxTracingFactory.getVertxTracerDelegator().getDelegate());
}
+ @Test
+ void testReceiveNullResponse() {
+ assertDoesNotThrow(() -> openTelemetryVertxTracingFactory.getVertxTracerDelegator().receiveResponse(
+ null,
+ null,
+ null,
+ null,
+ null));
+ assertNull(openTelemetryVertxTracingFactory.getVertxTracerDelegator().getDelegate());
+ }
+
private static Response createResponse() {
return new Response() {
@Override | ['extensions/opentelemetry/runtime/src/test/java/io/quarkus/opentelemetry/runtime/tracing/intrumentation/vertx/OpenTelemetryVertxTracingFactoryTest.java', 'extensions/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/tracing/intrumentation/vertx/OpenTelemetryVertxTracingFactory.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 27,016,514 | 5,328,393 | 685,992 | 6,323 | 1,235 | 198 | 18 | 1 | 5,636 | 286 | 1,285 | 96 | 4 | 2 | 2023-06-26T10:11: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,146 | quarkusio/quarkus/34374/34276 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/34276 | https://github.com/quarkusio/quarkus/pull/34374 | https://github.com/quarkusio/quarkus/pull/34374 | 1 | fix | Openshift extension fails to deploy when on RHEL | ### Describe the bug
I have an application(resteasy, two endpoints) which I wan to deploy to Openshift via quarkus-openshift extension. After an update to 3.2.0.CR2, the deployment process succeeds on Fedora and fails on RHEL 8 with "Connection was closed" error. This happens robustly.
### Expected behavior
Successful deployment as for 3.1.0.Final and on Fedora
### Actual behavior
```
[ERROR] [error]: Build step io.quarkus.container.image.openshift.deployment.OpenshiftProcessor#openshiftBuildFromJar threw an exception: io.fabric8.kubernetes.client.KubernetesClientException: Connection was closed
[ERROR] at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.waitForResult(OperationSupport.java:520)
[ERROR] at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.handleResponse(OperationSupport.java:535)
[ERROR] at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.handleGet(OperationSupport.java:478)
[ERROR] at io.fabric8.kubernetes.client.dsl.internal.BaseOperation.handleGet(BaseOperation.java:741)
[ERROR] at io.fabric8.kubernetes.client.dsl.internal.BaseOperation.requireFromServer(BaseOperation.java:185)
[ERROR] at io.fabric8.kubernetes.client.dsl.internal.BaseOperation.get(BaseOperation.java:141)
[ERROR] at io.fabric8.kubernetes.client.dsl.internal.BaseOperation.get(BaseOperation.java:92)
[ERROR] at io.quarkus.container.image.openshift.deployment.OpenshiftProcessor.openshiftBuild(OpenshiftProcessor.java:462)
[ERROR] at io.quarkus.container.image.openshift.deployment.OpenshiftProcessor.lambda$openshiftBuild$10(OpenshiftProcessor.java:429)
[ERROR] at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
[ERROR] at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
[ERROR] at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
[ERROR] at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655)
[ERROR] at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
[ERROR] at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
[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:497)
[ERROR] at io.quarkus.container.image.openshift.deployment.OpenshiftProcessor.openshiftBuild(OpenshiftProcessor.java:429)
[ERROR] at io.quarkus.container.image.openshift.deployment.OpenshiftProcessor.createContainerImage(OpenshiftProcessor.java:388)
[ERROR] at io.quarkus.container.image.openshift.deployment.OpenshiftProcessor.openshiftBuildFromJar(OpenshiftProcessor.java:285)
[ERROR] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[ERROR] at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[ERROR] at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[ERROR] at java.base/java.lang.reflect.Method.invoke(Method.java:566)
[ERROR] at io.quarkus.deployment.ExtensionLoader$3.execute(ExtensionLoader.java:909)
[ERROR] at io.quarkus.builder.BuildContext.run(BuildContext.java:282)
[ERROR] at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18)
[ERROR] at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2513)
[ERROR] at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1538)
[ERROR] at java.base/java.lang.Thread.run(Thread.java:829)
[ERROR] at org.jboss.threads.JBossThread.run(JBossThread.java:501)
[ERROR] Caused by: io.vertx.core.http.HttpClosedException: Connection was closed
```
### How to Reproduce?
1. `git clone https://github.com/fedinskiy/reproducer -b opeshift-extension-rhel-disconnect`
2. `oc new-project rhel-disconnect && cd reproducer`
3. `mvn package -Dquarkus.kubernetes.deploy=true -Dquarkus.openshift.expose=true -Dquarkus.openshift.route.expose=true -Dquarkus.application.name=app -Dquarkus.kubernetes-client.trust-certs=true -Dquarkus.kubernetes.deployment-target=openshift` fails
4. `mvn package -Dquarkus.kubernetes.deploy=true -Dquarkus.openshift.expose=true -Dquarkus.openshift.route.expose=true -Dquarkus.application.name=app -Dquarkus.kubernetes-client.trust-certs=true -Dquarkus.kubernetes.deployment-target=openshift -Dquarkus.platform.version=3.1.0.Final` succeeds (in another project)
### Output of `uname -a` or `ver`
4.18.0-477.13.1.el8_8.x86_64
### Output of `java -version`
11.0.13, vendor: Red Hat, Inc
### GraalVM version (if different from Java)
_No response_
### Quarkus version or git rev
3.2.0.CR2
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
Apache Maven 3.8.6 (84538c9988a25aec085021c365c560670ad80f63)
### Additional information
oc version(same on both Fedora and RHEL):
```
Client Version: 4.13.0-202305312300.p0.g05d83ef.assembly.stream-05d83ef
Kustomize Version: v4.5.7
Kubernetes Version: v1.26.5+7a891f0
``` | d3e70c85b0973706242c717aa46b43b6fccbf20a | 4b48895380fa777abeb2038c0e773c0a556a2d2a | https://github.com/quarkusio/quarkus/compare/d3e70c85b0973706242c717aa46b43b6fccbf20a...4b48895380fa777abeb2038c0e773c0a556a2d2a | 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 1839dc50436..35d2ce3c248 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
@@ -26,7 +26,6 @@
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.stream.Collectors;
-import java.util.stream.Stream;
import org.jboss.logging.Logger;
@@ -385,7 +384,7 @@ public static void createContainerImage(KubernetesClientBuilder kubernetesClient
.collect(Collectors.toList());
applyOpenshiftResources(openShiftClient, buildResources);
- openshiftBuild(openShiftClient, buildResources, tar, openshiftConfig);
+ openshiftBuild(buildResources, tar, openshiftConfig, kubernetesClientBuilder);
}
}
@@ -423,73 +422,85 @@ private static void applyOpenshiftResources(OpenShiftClient client, List<HasMeta
}
}
- private static void openshiftBuild(OpenShiftClient client, List<HasMetadata> buildResources, File binaryFile,
- OpenshiftConfig openshiftConfig) {
+ private static void openshiftBuild(List<HasMetadata> buildResources, File binaryFile,
+ OpenshiftConfig openshiftConfig, KubernetesClientBuilder kubernetesClientBuilder) {
distinct(buildResources).stream().filter(i -> i instanceof BuildConfig).map(i -> (BuildConfig) i)
- .forEach(bc -> openshiftBuild(client, bc, binaryFile, openshiftConfig));
+ .forEach(bc -> {
+ Build build = startOpenshiftBuild(bc, binaryFile, openshiftConfig, kubernetesClientBuilder);
+ waitForOpenshiftBuild(build, openshiftConfig, kubernetesClientBuilder);
+ });
}
/**
* Performs the binary build of the specified {@link BuildConfig} with the given
* binary input.
*
- * @param client The openshift client instance
* @param buildConfig The build config
* @param binaryFile The binary file
* @param openshiftConfig The openshift configuration
+ * @param kubernetesClientBuilder The kubernetes client builder
*/
- private static void openshiftBuild(OpenShiftClient client, BuildConfig buildConfig, File binaryFile,
- OpenshiftConfig openshiftConfig) {
- Build build;
- try {
- build = client.buildConfigs().withName(buildConfig.getMetadata().getName())
- .instantiateBinary()
- .withTimeoutInMillis(openshiftConfig.buildTimeout.toMillis())
- .fromFile(binaryFile);
- } catch (Exception e) {
- Optional<Build> running = runningBuildsOf(client, buildConfig).findFirst();
- if (running.isPresent()) {
- LOG.warn("An exception: '" + e.getMessage()
- + " ' occurred while instantiating the build, however the build has been started.");
- build = running.get();
- } else {
- throw openshiftException(e);
+ private static Build startOpenshiftBuild(BuildConfig buildConfig, File binaryFile,
+ OpenshiftConfig openshiftConfig, KubernetesClientBuilder kubernetesClientBuilder) {
+ try (KubernetesClient kubernetesClient = kubernetesClientBuilder.build()) {
+ OpenShiftClient client = toOpenshiftClient(kubernetesClient);
+ try {
+ return client.buildConfigs().withName(buildConfig.getMetadata().getName())
+ .instantiateBinary()
+ .withTimeoutInMillis(openshiftConfig.buildTimeout.toMillis())
+ .fromFile(binaryFile);
+ } catch (Exception e) {
+ Optional<Build> running = buildsOf(client, buildConfig).stream().findFirst();
+ if (running.isPresent()) {
+ LOG.warn("An exception: '" + e.getMessage()
+ + " ' occurred while instantiating the build, however the build has been started.");
+ return running.get();
+ } else {
+ throw openshiftException(e);
+ }
}
}
+ }
+
+ private static void waitForOpenshiftBuild(Build build, OpenshiftConfig openshiftConfig,
+ KubernetesClientBuilder kubernetesClientBuilder) {
while (isNew(build) || isPending(build) || isRunning(build)) {
final String buildName = build.getMetadata().getName();
- Build updated = client.builds().withName(buildName).get();
- if (updated == null) {
- throw new IllegalStateException("Build:" + build.getMetadata().getName() + " is no longer present!");
- } else if (updated.getStatus() == null) {
- throw new IllegalStateException("Build:" + build.getMetadata().getName() + " has no status!");
- } else if (isNew(updated) || isPending(updated) || isRunning(updated)) {
- build = updated;
- try (LogWatch w = client.builds().withName(buildName).withPrettyOutput().watchLog();
- Reader reader = new InputStreamReader(w.getOutput())) {
- display(reader, openshiftConfig.buildLogLevel);
- } catch (IOException e) {
- // This may happen if the LogWatch is closed while we are still reading.
- // We shouldn't let the build fail, so let's log a warning and display last few lines of the log
- LOG.warn("Log stream closed, redisplaying last " + LOG_TAIL_SIZE + " entries:");
- try {
- display(client.builds().withName(buildName).tailingLines(LOG_TAIL_SIZE).getLogReader(),
- Logger.Level.WARN);
- } catch (IOException ex) {
- // Let's ignore this.
+ try (KubernetesClient kubernetesClient = kubernetesClientBuilder.build()) {
+ OpenShiftClient client = toOpenshiftClient(kubernetesClient);
+ Build updated = client.builds().withName(buildName).get();
+ if (updated == null) {
+ throw new IllegalStateException("Build:" + build.getMetadata().getName() + " is no longer present!");
+ } else if (updated.getStatus() == null) {
+ throw new IllegalStateException("Build:" + build.getMetadata().getName() + " has no status!");
+ } else if (isNew(updated) || isPending(updated) || isRunning(updated)) {
+ build = updated;
+ try (LogWatch w = client.builds().withName(buildName).withPrettyOutput().watchLog();
+ Reader reader = new InputStreamReader(w.getOutput())) {
+ display(reader, openshiftConfig.buildLogLevel);
+ } catch (IOException | KubernetesClientException ex) {
+ // This may happen if the LogWatch is closed while we are still reading.
+ // We shouldn't let the build fail, so let's log a warning and display last few lines of the log
+ LOG.warn("Log stream closed, redisplaying last " + LOG_TAIL_SIZE + " entries:");
+ try {
+ display(client.builds().withName(buildName).tailingLines(LOG_TAIL_SIZE).getLogReader(),
+ Logger.Level.WARN);
+ } catch (IOException | KubernetesClientException ignored) {
+ // Let's ignore this.
+ }
}
+ } else if (isComplete(updated)) {
+ return;
+ } else if (isCancelled(updated)) {
+ throw new IllegalStateException("Build:" + buildName + " cancelled!");
+ } else if (isFailed(updated)) {
+ throw new IllegalStateException(
+ "Build:" + buildName + " failed! " + updated.getStatus().getMessage());
+ } else if (isError(updated)) {
+ throw new IllegalStateException(
+ "Build:" + buildName + " encountered error! " + updated.getStatus().getMessage());
}
- } else if (isComplete(updated)) {
- return;
- } else if (isCancelled(updated)) {
- throw new IllegalStateException("Build:" + buildName + " cancelled!");
- } else if (isFailed(updated)) {
- throw new IllegalStateException(
- "Build:" + buildName + " failed! " + updated.getStatus().getMessage());
- } else if (isError(updated)) {
- throw new IllegalStateException(
- "Build:" + buildName + " encountered error! " + updated.getStatus().getMessage());
}
}
}
@@ -508,10 +519,6 @@ private static List<Build> buildsOf(OpenShiftClient client, BuildConfig config)
return client.builds().withLabel(BUILD_CONFIG_NAME, config.getMetadata().getName()).list().getItems();
}
- private static Stream<Build> runningBuildsOf(OpenShiftClient client, BuildConfig config) {
- return buildsOf(client, config).stream().filter(b -> RUNNING.equalsIgnoreCase(b.getStatus().getPhase()));
- }
-
private static RuntimeException openshiftException(Throwable t) {
if (t instanceof KubernetesClientException) {
KubernetesClientErrorHandler.handle((KubernetesClientException) t); | ['extensions/container-image/container-image-openshift/deployment/src/main/java/io/quarkus/container/image/openshift/deployment/OpenshiftProcessor.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 27,038,580 | 5,332,638 | 686,551 | 6,327 | 7,837 | 1,403 | 117 | 1 | 5,342 | 290 | 1,392 | 83 | 1 | 2 | 2023-06-28T12:36:22 | 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,144 | quarkusio/quarkus/34471/31010 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/31010 | https://github.com/quarkusio/quarkus/pull/34471 | https://github.com/quarkusio/quarkus/pull/34471 | 1 | fix | HTTP access log %t missing enclosing brackets | ### Describe the bug
According to the [Common Log Format (CLF)](https://en.wikipedia.org/wiki/Common_Log_Format) the datetime specified as `%t` in http access logs should be enclosed in brackets as in `[10/Oct/2000:13:55:36 -0700]`, however this is not what you get when configuring your own pattern.
The problem lies in the following code ([see link here](https://github.com/quarkusio/quarkus/blob/2cbd177416f92b9f45abb34b6f01acb8cb0f4eb5/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/attribute/DateTimeAttribute.java#L16)):
```
private static final String COMMON_LOG_PATTERN = "[dd/MMM/yyyy:HH:mm:ss Z]";
```
This pattern is fed to `DateTimeFormatter.ofPattern()` which, [according to the docs](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html), treats the brackets as special characters denoting the start and end of an optional datetime part.
The trivial fix involves single-quoting the brackets in the pattern string as follows:
```
private static final String COMMON_LOG_PATTERN = "'['dd/MMM/yyyy:HH:mm:ss Z']'";
```
### Expected behavior
The `%t` modifier in http access logs should print common log format datetime enclosed in brackets as in `[10/Oct/2000:13:55:36 -0700]`
### Actual behavior
The `%t` modifier in http access logs prints datetime without brackets as in `10/Oct/2000:13:55:36 -0700`
### How to Reproduce?
Either check access logs in a simple web app or contrast the output of the following expressions' evaluation:
1. `DateTimeFormatter.ofPattern("'['dd/MMM/yyyy:HH:mm:ss Z']'", Locale.US).format(ZonedDateTime.now())`
2. `DateTimeFormatter.ofPattern("[dd/MMM/yyyy:HH:mm:ss Z]", Locale.US).format(ZonedDateTime.now())`
### Output of `uname -a` or `ver`
Darwin Users-MacBook-Pro.local 22.3.0 Darwin Kernel Version 22.3.0: Thu Jan 5 20:53:49 PST 2023; root:xnu-8792.81.2~2/RELEASE_X86_64 x86_64
### Output of `java -version`
1.8.0_351
### GraalVM version (if different from Java)
_No response_
### Quarkus version or git rev
2.14.1
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
Apache Maven 3.8.1
### Additional information
_No response_ | 9bcc5baa67ff0d54ab1e2af45ed414165e9552be | 9cc6ffc073622fb381ebef2b86d2532ab1798142 | https://github.com/quarkusio/quarkus/compare/9bcc5baa67ff0d54ab1e2af45ed414165e9552be...9cc6ffc073622fb381ebef2b86d2532ab1798142 | diff --git a/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/attribute/DateTimeAttribute.java b/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/attribute/DateTimeAttribute.java
index ade164d92f8..de5c3aae57b 100644
--- a/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/attribute/DateTimeAttribute.java
+++ b/extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/attribute/DateTimeAttribute.java
@@ -13,7 +13,7 @@
*/
public class DateTimeAttribute implements ExchangeAttribute {
- private static final String COMMON_LOG_PATTERN = "[dd/MMM/yyyy:HH:mm:ss Z]";
+ private static final String COMMON_LOG_PATTERN = "'['dd/MMM/yyyy:HH:mm:ss Z']'";
public static final String DATE_TIME_SHORT = "%t";
public static final String DATE_TIME = "%{DATE_TIME}";
diff --git a/integration-tests/vertx-http/src/test/java/io/quarkus/it/vertx/AccessLogTestCase.java b/integration-tests/vertx-http/src/test/java/io/quarkus/it/vertx/AccessLogTestCase.java
index da7b395710d..5d0051a1b75 100644
--- a/integration-tests/vertx-http/src/test/java/io/quarkus/it/vertx/AccessLogTestCase.java
+++ b/integration-tests/vertx-http/src/test/java/io/quarkus/it/vertx/AccessLogTestCase.java
@@ -2,7 +2,6 @@
import static org.hamcrest.Matchers.containsString;
-import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@@ -23,12 +22,11 @@ public class AccessLogTestCase {
/**
* Fires a HTTP request, to an application which has access log enabled and then checks
* the access-log contents to verify that the request was logged
- *
- * @throws Exception
*/
@Test
- public void testAccessLogContent() throws Exception {
+ public void testAccessLogContent() {
final Path logDirectory = Paths.get(".", "target");
+ final Path accessLogFilePath = logDirectory.resolve("quarkus-access-log.log");
final String queryParamVal = UUID.randomUUID().toString();
final String targetUri = "/simple/access-log-test-endpoint?foo=" + queryParamVal;
RestAssured.when().get(targetUri).then().body(containsString("passed"));
@@ -37,15 +35,18 @@ public void testAccessLogContent() throws Exception {
.untilAsserted(new ThrowingRunnable() {
@Override
public void run() throws Throwable {
- final Path accessLogFilePath = logDirectory.resolve("quarkus-access-log.log");
Assertions.assertTrue(Files.exists(accessLogFilePath),
"access log file " + accessLogFilePath + " is missing");
- String data = new String(Files.readAllBytes(accessLogFilePath), StandardCharsets.UTF_8);
- Assertions.assertTrue(data.contains(targetUri),
+ String line = Files.readString(accessLogFilePath);
+ Assertions.assertTrue(line.startsWith("127.0.0.1 - - ["),
+ "access log doesn't contain request IP or does not wrap the date with []: " + line);
+ Assertions.assertTrue(line.contains("] \\"GET"),
+ "access log doesn't contain the HTTP method or does not wrap the date with []: " + line);
+ Assertions.assertTrue(line.contains(targetUri),
"access log doesn't contain an entry for " + targetUri);
- Assertions.assertTrue(data.contains("?foo=" + queryParamVal),
+ Assertions.assertTrue(line.contains("?foo=" + queryParamVal),
"access log is missing query params");
- Assertions.assertFalse(data.contains("?foo=" + queryParamVal + "?foo=" + queryParamVal),
+ Assertions.assertFalse(line.contains("?foo=" + queryParamVal + "?foo=" + queryParamVal),
"access log contains duplicated query params");
}
}); | ['integration-tests/vertx-http/src/test/java/io/quarkus/it/vertx/AccessLogTestCase.java', 'extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/attribute/DateTimeAttribute.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 27,164,018 | 5,357,961 | 689,439 | 6,351 | 167 | 43 | 2 | 1 | 2,200 | 245 | 596 | 58 | 3 | 2 | 2023-07-03T08:54: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,143 | quarkusio/quarkus/34490/34448 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/34448 | https://github.com/quarkusio/quarkus/pull/34490 | https://github.com/quarkusio/quarkus/pull/34490 | 1 | fix | Failure to pull non-cached deps during test launch with proxy private repository | ### Describe the bug
Quarkus (3.x) fails to pull dependencies from a private repository during tests, with this error:
```
Caused by: org.apache.http.client.HttpResponseException: status code: 401, reason phrase: Unauthorized (401)
at org.eclipse.aether.transport.http.HttpTransporter.handleStatus(HttpTransporter.java:527)
at org.eclipse.aether.transport.http.HttpTransporter.execute(HttpTransporter.java:396)
at org.eclipse.aether.transport.http.HttpTransporter.implGet(HttpTransporter.java:343)
at org.eclipse.aether.spi.connector.transport.AbstractTransporter.get(AbstractTransporter.java:64)
at org.eclipse.aether.connector.basic.BasicRepositoryConnector$GetTaskRunner.runTask(BasicRepositoryConnector.java:482)
at org.eclipse.aether.connector.basic.BasicRepositoryConnector$TaskRunner.run(BasicRepositoryConnector.java:414)
... 67 more
```
This happens if during the test launch, quarkus needs some extra dependency that maven couldn't resolve and cache (typically the `*-deployment` libraries).
The problem is because it tries to pull dependencies from repository defined in the settings.xml; but somehow misses the settings-security.xml setup. If explicitly providing such setup to maven, it works (similar problem can also be replicated in the IDEs)
The error is pretty obscure, because success or failure depends on having the dependency locally cached or not by just mere chance. So upgrading to a newer Quarkus version might make it fail (because of transitive dependency changes). This tipically hits pipelines quite hard and make usage of maven args or parameters mandatory in CI/CD and cumbersome for local dev. In CI/CD this can be overcome with workarounds such as `MAVEN_ARGS = "-Dsettings.security=~/.m2/settings-security.xml"` (if using maven >= 3.9).
Using pom.xml-> surefire config -> systemPropertyVariables -> `<settings.security>${settings.security}</settings.security>` doesn't work (looks like no system property used there works but /shrug)
Link to reproducer that's just a copy of the `quarkus-quickstarts/getting-started:3.1.3.Final` [project ](https://github.com/quarkusio/quarkus-quickstarts/tree/main/getting-started).
https://github.com/agseijas/maven-security-quarkus/blob/master/README.md
### Expected behavior
The `GreetingResourceTest` test passes and the build ends successfully with maven
### Actual behavior
Error pulling dependencies during test launch:
```text
Caused by: org.apache.http.client.HttpResponseException: status code: 401, reason phrase: Unauthorized (401)
at org.eclipse.aether.transport.http.HttpTransporter.handleStatus(HttpTransporter.java:527)
at org.eclipse.aether.transport.http.HttpTransporter.execute(HttpTransporter.java:396)
at org.eclipse.aether.transport.http.HttpTransporter.implGet(HttpTransporter.java:343)
at org.eclipse.aether.spi.connector.transport.AbstractTransporter.get(AbstractTransporter.java:64)
at org.eclipse.aether.connector.basic.BasicRepositoryConnector$GetTaskRunner.runTask(BasicRepositoryConnector.java:482)
at org.eclipse.aether.connector.basic.BasicRepositoryConnector$TaskRunner.run(BasicRepositoryConnector.java:414)
... 67 more
```
### How to Reproduce?
Check the README file that explains the steps and tools setup needed to reproduce the issue:
https://github.com/agseijas/maven-security-quarkus/blob/master/README.md
### Output of `uname -a` or `ver`
_No response_
### Output of `java -version`
openjdk version "20.0.1" 2023-04-18
### GraalVM version (if different from Java)
_No response_
### Quarkus version or git rev
3.1.3.Final
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
Apache Maven 3.9.3 (21122926829f1ead511c958d89bd2f672198ae9f)
### Additional information
_No response_ | 5382a3de02facc6f1be2f55d8fdb7d5c1fce8dc2 | dd1f1d69d9c23776fe634bdbba9c0c3f344a749d | https://github.com/quarkusio/quarkus/compare/5382a3de02facc6f1be2f55d8fdb7d5c1fce8dc2...dd1f1d69d9c23776fe634bdbba9c0c3f344a749d | 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 a6e7f45eb3a..712de094100 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
@@ -95,6 +95,7 @@ public class BootstrapMavenContext {
private static final String MAVEN_SETTINGS = "maven.settings";
private static final String MAVEN_TOP_LEVEL_PROJECT_BASEDIR = "maven.top-level-basedir";
private static final String SETTINGS_XML = "settings.xml";
+ private static final String SETTINGS_SECURITY = "settings.security";
private static final String EFFECTIVE_MODEL_BUILDER_PROP = "quarkus.bootstrap.effective-model-builder";
@@ -271,11 +272,17 @@ public boolean isOffline() throws BootstrapMavenException {
}
public RepositorySystem getRepositorySystem() throws BootstrapMavenException {
- return repoSystem == null ? repoSystem = newRepositorySystem() : repoSystem;
+ if (repoSystem == null) {
+ initRepoSystemAndManager();
+ }
+ return repoSystem;
}
public RemoteRepositoryManager getRemoteRepositoryManager() {
- return remoteRepoManager == null ? remoteRepoManager = newRemoteRepositoryManager() : remoteRepoManager;
+ if (remoteRepoManager == null) {
+ initRepoSystemAndManager();
+ }
+ return remoteRepoManager;
}
public RepositorySystemSession getRepositorySystemSession() throws BootstrapMavenException {
@@ -291,7 +298,10 @@ public List<RemoteRepository> getRemotePluginRepositories() throws BootstrapMave
}
private SettingsDecrypter getSettingsDecrypter() {
- return settingsDecrypter == null ? settingsDecrypter = newSettingsDecrypter() : settingsDecrypter;
+ if (settingsDecrypter == null) {
+ initRepoSystemAndManager();
+ }
+ return settingsDecrypter;
}
public Settings getEffectiveSettings() throws BootstrapMavenException {
@@ -463,7 +473,17 @@ private DefaultRepositorySystemSession newRepositorySystemSession() throws Boots
final SettingsDecryptionRequest decrypt = new DefaultSettingsDecryptionRequest();
decrypt.setProxies(settings.getProxies());
decrypt.setServers(settings.getServers());
+ // set settings.security property to ~/.m2/settings-security.xml unless it's already set to some other value
+ File settingsSecurityXml = null;
+ final boolean setSettingsSecurity = !System.getProperties().contains(SETTINGS_SECURITY)
+ && ((settingsSecurityXml = new File(getUserMavenConfigurationHome(), "settings-security.xml")).exists());
+ if (setSettingsSecurity) {
+ System.setProperty(SETTINGS_SECURITY, settingsSecurityXml.toString());
+ }
final SettingsDecryptionResult decrypted = getSettingsDecrypter().decrypt(decrypt);
+ if (setSettingsSecurity) {
+ System.clearProperty(SETTINGS_SECURITY);
+ }
if (!decrypted.getProblems().isEmpty() && log.isDebugEnabled()) {
// this is how maven handles these
for (SettingsProblem p : decrypted.getProblems()) {
@@ -842,21 +862,6 @@ private static Proxy toAetherProxy(org.apache.maven.settings.Proxy proxy) {
return new Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), auth);
}
- private RepositorySystem newRepositorySystem() throws BootstrapMavenException {
- initRepoSystemAndManager();
- return repoSystem;
- }
-
- public RemoteRepositoryManager newRemoteRepositoryManager() {
- initRepoSystemAndManager();
- return remoteRepoManager;
- }
-
- private SettingsDecrypter newSettingsDecrypter() {
- initRepoSystemAndManager();
- return settingsDecrypter;
- }
-
private void initRepoSystemAndManager() {
final MavenFactory factory = configureMavenFactory();
if (repoSystem == null) {
@@ -871,7 +876,7 @@ private void initRepoSystemAndManager() {
}
protected MavenFactory configureMavenFactory() {
- final MavenFactory factory = MavenFactory.create(RepositorySystem.class.getClassLoader(), builder -> {
+ return MavenFactory.create(RepositorySystem.class.getClassLoader(), builder -> {
builder.addBean(ModelBuilder.class).setSupplier(new BeanSupplier<ModelBuilder>() {
@Override
public ModelBuilder get(Scope scope) {
@@ -879,7 +884,6 @@ public ModelBuilder get(Scope scope) {
}
}).setPriority(100).build();
});
- return factory;
}
private static String getUserAgent() { | ['independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/BootstrapMavenContext.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 27,164,244 | 5,358,005 | 689,449 | 6,351 | 2,037 | 375 | 44 | 1 | 3,922 | 343 | 875 | 77 | 3 | 2 | 2023-07-03T15:06:25 | 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,142 | quarkusio/quarkus/34583/33567 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/33567 | https://github.com/quarkusio/quarkus/pull/34583 | https://github.com/quarkusio/quarkus/pull/34583 | 1 | fixes | Custom ConfigSource not working with extensions that implement CodeGenProvider | ### Describe the bug
Any extension that implements CodeGenProvider results in a broken build when used in conjunction with a custom ConfigSource. This is currently impacting quarkus-cxf, quarkus-grpc, and any other extensions that implement CodeGenProvider.
Error below shows up with `mvn clean verify`:
[ERROR] Failed to execute goal io.quarkus.platform:quarkus-maven-plugin:3.0.3.Final:generate-code (default) on project code-with-quarkus: Quarkus code generation phase has failed: InvocationTargetException: org.eclipse.microprofile.config.spi.ConfigSource: Provider org.acme.config.InMemoryConfigSource not found -> [Help 1]
### Expected behavior
_No response_
### Actual behavior
_No response_
### How to Reproduce?
Reproducer is attached: [code-with-quarkus.zip](https://github.com/quarkusio/quarkus/files/11549332/code-with-quarkus.zip), it was created as follows:
1. Generate project using https://code.quarkus.io/
2. Add custom ConfigSource as per https://quarkus.io/guides/config-extending-support (running `mvn clean verify` executes successfully at this stage).
3. Add `quarkus-cxf` or `quarkus-grpc` dependency (or any extension that uses CodeGenProvider) to project (running `mvn clean verify` fails at this point).
### Output of `uname -a` or `ver`
_No response_
### Output of `java -version`
openjdk version "17.0.4" 2022-07-19 OpenJDK Runtime Environment GraalVM CE 22.2.0 (build 17.0.4+8-jvmci-22.2-b06) OpenJDK 64-Bit Server VM GraalVM CE 22.2.0 (build 17.0.4+8-jvmci-22.2-b06, 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`)
_No response_
### Additional information
_No response_ | e7e1a8a6efd81081e9df73ae61b15bfc4e97d977 | 0cf2e58cb509aa73ba107098b67dc9734253a3a1 | https://github.com/quarkusio/quarkus/compare/e7e1a8a6efd81081e9df73ae61b15bfc4e97d977...0cf2e58cb509aa73ba107098b67dc9734253a3a1 | diff --git a/core/deployment/src/main/java/io/quarkus/deployment/CodeGenerator.java b/core/deployment/src/main/java/io/quarkus/deployment/CodeGenerator.java
index 45e54c68bb9..7e8f81b410f 100644
--- a/core/deployment/src/main/java/io/quarkus/deployment/CodeGenerator.java
+++ b/core/deployment/src/main/java/io/quarkus/deployment/CodeGenerator.java
@@ -39,9 +39,16 @@ public class CodeGenerator {
private static final Logger log = Logger.getLogger(CodeGenerator.class);
- private static final List<String> CONFIG_SOURCE_FACTORY_INTERFACES = List.of(
+ private static final List<String> CONFIG_SERVICES = List.of(
+ "META-INF/services/org.eclipse.microprofile.config.spi.Converter",
+ "META-INF/services/org.eclipse.microprofile.config.spi.ConfigSource",
+ "META-INF/services/org.eclipse.microprofile.config.spi.ConfigSourceProvider",
+ "META-INF/services/io.smallrye.config.ConfigSourceInterceptor",
+ "META-INF/services/io.smallrye.config.ConfigSourceInterceptorFactory",
"META-INF/services/io.smallrye.config.ConfigSourceFactory",
- "META-INF/services/org.eclipse.microprofile.config.spi.ConfigSourceProvider");
+ "META-INF/services/io.smallrye.config.SecretKeysHandler",
+ "META-INF/services/io.smallrye.config.SecretKeysHandlerFactory",
+ "META-INF/services/io.smallrye.config.ConfigValidator");
// used by Gradle and Maven
public static void initAndRun(QuarkusClassLoader classLoader,
@@ -179,17 +186,17 @@ public static boolean trigger(ClassLoader deploymentClassLoader,
public static Config getConfig(ApplicationModel appModel, LaunchMode launchMode, Properties buildSystemProps,
QuarkusClassLoader deploymentClassLoader) throws CodeGenException {
// Config instance that is returned by this method should be as close to the one built in the ExtensionLoader as possible
- final Map<String, List<String>> appModuleConfigFactories = getConfigSourceFactoryImpl(appModel.getAppArtifact());
- if (!appModuleConfigFactories.isEmpty()) {
- final Map<String, List<String>> allConfigFactories = new HashMap<>(appModuleConfigFactories.size());
- final Map<String, byte[]> allowedConfigFactories = new HashMap<>(appModuleConfigFactories.size());
- final Map<String, byte[]> bannedConfigFactories = new HashMap<>(appModuleConfigFactories.size());
- for (Map.Entry<String, List<String>> appModuleFactories : appModuleConfigFactories.entrySet()) {
- final String factoryImpl = appModuleFactories.getKey();
+ final Map<String, List<String>> appModuleConfigServices = getConfigServices(appModel.getAppArtifact());
+ if (!appModuleConfigServices.isEmpty()) {
+ final Map<String, List<String>> allConfigServices = new HashMap<>(appModuleConfigServices.size());
+ final Map<String, byte[]> allowedConfigServices = new HashMap<>(appModuleConfigServices.size());
+ final Map<String, byte[]> bannedConfigServices = new HashMap<>(appModuleConfigServices.size());
+ for (Map.Entry<String, List<String>> appModuleServices : appModuleConfigServices.entrySet()) {
+ final String service = appModuleServices.getKey();
try {
- ClassPathUtils.consumeAsPaths(deploymentClassLoader, factoryImpl, p -> {
+ ClassPathUtils.consumeAsPaths(deploymentClassLoader, service, p -> {
try {
- allConfigFactories.computeIfAbsent(factoryImpl, k -> new ArrayList<>())
+ allConfigServices.computeIfAbsent(service, k -> new ArrayList<>())
.addAll(Files.readAllLines(p));
} catch (IOException e) {
throw new UncheckedIOException("Failed to read " + p, e);
@@ -198,25 +205,25 @@ public static Config getConfig(ApplicationModel appModel, LaunchMode launchMode,
} catch (IOException e) {
throw new CodeGenException("Failed to read resources from classpath", e);
}
- final List<String> allFactories = allConfigFactories.getOrDefault(factoryImpl, List.of());
- allFactories.removeAll(appModuleFactories.getValue());
- if (allFactories.isEmpty()) {
- bannedConfigFactories.put(factoryImpl, new byte[0]);
+ final List<String> allServices = allConfigServices.getOrDefault(service, List.of());
+ allServices.removeAll(appModuleServices.getValue());
+ if (allServices.isEmpty()) {
+ bannedConfigServices.put(service, new byte[0]);
} else {
final StringJoiner joiner = new StringJoiner(System.lineSeparator());
- allFactories.forEach(joiner::add);
- allowedConfigFactories.put(factoryImpl, joiner.toString().getBytes());
+ allServices.forEach(joiner::add);
+ allowedConfigServices.put(service, joiner.toString().getBytes());
}
}
- // we don't want to load config source factories/providers from the current module because they haven't been compiled yet
+ // we don't want to load config services from the current module because they haven't been compiled yet
final QuarkusClassLoader.Builder configClBuilder = QuarkusClassLoader.builder("CodeGenerator Config ClassLoader",
deploymentClassLoader, false);
- if (!allowedConfigFactories.isEmpty()) {
- configClBuilder.addElement(new MemoryClassPathElement(allowedConfigFactories, true));
+ if (!allowedConfigServices.isEmpty()) {
+ configClBuilder.addElement(new MemoryClassPathElement(allowedConfigServices, true));
}
- if (!bannedConfigFactories.isEmpty()) {
- configClBuilder.addBannedElement(new MemoryClassPathElement(bannedConfigFactories, true));
+ if (!bannedConfigServices.isEmpty()) {
+ configClBuilder.addBannedElement(new MemoryClassPathElement(bannedConfigServices, true));
}
deploymentClassLoader = configClBuilder.build();
}
@@ -226,22 +233,22 @@ public static Config getConfig(ApplicationModel appModel, LaunchMode launchMode,
} catch (Exception e) {
throw new CodeGenException("Failed to initialize application configuration", e);
} finally {
- if (!appModuleConfigFactories.isEmpty()) {
+ if (!appModuleConfigServices.isEmpty()) {
deploymentClassLoader.close();
}
}
}
- private static Map<String, List<String>> getConfigSourceFactoryImpl(ResolvedDependency dep) throws CodeGenException {
- final Map<String, List<String>> configFactoryImpl = new HashMap<>(CONFIG_SOURCE_FACTORY_INTERFACES.size());
+ private static Map<String, List<String>> getConfigServices(ResolvedDependency dep) throws CodeGenException {
+ final Map<String, List<String>> configServices = new HashMap<>(CONFIG_SERVICES.size());
try (OpenPathTree openTree = dep.getContentTree().open()) {
- for (String s : CONFIG_SOURCE_FACTORY_INTERFACES) {
+ for (String s : CONFIG_SERVICES) {
openTree.accept(s, v -> {
if (v == null) {
return;
}
try {
- configFactoryImpl.put(s, Files.readAllLines(v.getPath()));
+ configServices.put(s, Files.readAllLines(v.getPath()));
} catch (IOException e) {
throw new UncheckedIOException("Failed to read " + v.getPath(), e);
}
@@ -250,7 +257,7 @@ private static Map<String, List<String>> getConfigSourceFactoryImpl(ResolvedDepe
} catch (IOException e) {
throw new CodeGenException("Failed to read " + dep.getResolvedPaths(), e);
}
- return configFactoryImpl;
+ return configServices;
}
private static Path codeGenOutDir(Path generatedSourcesDir, | ['core/deployment/src/main/java/io/quarkus/deployment/CodeGenerator.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 27,199,213 | 5,364,723 | 690,222 | 6,360 | 5,290 | 964 | 63 | 1 | 1,780 | 207 | 478 | 48 | 3 | 0 | 2023-07-06T18:44:30 | 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,137 | quarkusio/quarkus/34789/34632 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/34632 | https://github.com/quarkusio/quarkus/pull/34789 | https://github.com/quarkusio/quarkus/pull/34789 | 1 | fixes | Resteasy Reactive: Server becomes unresponsive due to race condition on ContainerResponseContext.getEntityStream() | ### Describe the bug
We have had unexplained intermittent timeouts occurring on various Rest services and eventually managed to reproduce it under load and isolate the cause.
I've added a reproducer which shows that under high throughput you can create a race condition where a call to getEntityStream in a JAX-RS Container response filter for a response with no body (returns a 204) will eventually cause all current TCP connections to the server to become unresponsive. Clients need to terminate and reconnect in order to send requests. All in-progress requests or new requests on the open TCP connections will result in no HTTP response from the server. Instead clients will just receive an ACK to the request.
### Expected behavior
The entity stream call should return an empty stream all the time and not cause the server to stop responding.
### Actual behavior
In my reproducer, after a minute or two one will see the server stops processing requests.
### How to Reproduce?
git clone https://github.com/bcluap/quarkus-examples.git
cd quarkus-examples/resteasy-reactive
mvn clean install
java -jar ./target/quarkus-app/quarkus-run.jar
Then run a load test like this:
wrk --timeout=10s -d600 -t1 -c1 'http://localhost:8000/test'
The server will log "HERE" over and over and eventually stop. The load test client experiences timeouts for all future requests. Only fresh TCP connections get any response from the server.
### Output of `uname -a` or `ver`
Linux paul-xps 5.19.0-45-generic #46~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Wed Jun 7 15:06:04 UTC 20 x86_64 x86_64 x86_64 GNU/Linux
### Output of `java -version`
openjdk version "20.0.1" 2023-04-18 OpenJDK Runtime Environment Temurin-20.0.1+9 (build 20.0.1+9) OpenJDK 64-Bit Server VM Temurin-20.0.1+9 (build 20.0.1+9, mixed mode, sharing)
### GraalVM version (if different from Java)
NA
### Quarkus version or git rev
3.1.3.Final
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
mvn 3.9.3
### Additional information
Can reproduce on my laptop and AWS ECS. The lock up occurs normally within a minute of the load test kicking off. Commenting out the responseContext.getEntityStream(); in the filter prevents the issue.
Note this only happens when there is no response. A thread dump during the lock up shows that the server is not doing anything and not locking on anything. Its as though the event loop has lost all knowledge of the TCP connections.
If the jax-rs method returns void or returns a null String then the same behaviour is seen. It does not happen if data is returned in the body. | 7ed4b980138dc05aae55da288cee35927c385f95 | 890a36afacf577b1077ffb77e0ce815c692d9c31 | https://github.com/quarkusio/quarkus/compare/7ed4b980138dc05aae55da288cee35927c385f95...890a36afacf577b1077ffb77e0ce815c692d9c31 | diff --git a/independent-projects/resteasy-reactive/server/vertx/src/main/java/org/jboss/resteasy/reactive/server/vertx/ResteasyReactiveOutputStream.java b/independent-projects/resteasy-reactive/server/vertx/src/main/java/org/jboss/resteasy/reactive/server/vertx/ResteasyReactiveOutputStream.java
index 701d6458625..6a2fcf0a3ea 100644
--- a/independent-projects/resteasy-reactive/server/vertx/src/main/java/org/jboss/resteasy/reactive/server/vertx/ResteasyReactiveOutputStream.java
+++ b/independent-projects/resteasy-reactive/server/vertx/src/main/java/org/jboss/resteasy/reactive/server/vertx/ResteasyReactiveOutputStream.java
@@ -226,10 +226,12 @@ private void prepareWrite(ByteBuf buffer, boolean finished) throws IOException {
if (!committed) {
committed = true;
if (finished) {
- if (buffer == null) {
- context.serverResponse().setResponseHeader(HttpHeaderNames.CONTENT_LENGTH, "0");
- } else {
- context.serverResponse().setResponseHeader(HttpHeaderNames.CONTENT_LENGTH, "" + buffer.readableBytes());
+ if (!context.serverResponse().headWritten()) {
+ if (buffer == null) {
+ context.serverResponse().setResponseHeader(HttpHeaderNames.CONTENT_LENGTH, "0");
+ } else {
+ context.serverResponse().setResponseHeader(HttpHeaderNames.CONTENT_LENGTH, "" + buffer.readableBytes());
+ }
}
} else {
var contentLengthSet = contentLengthSet(); | ['independent-projects/resteasy-reactive/server/vertx/src/main/java/org/jboss/resteasy/reactive/server/vertx/ResteasyReactiveOutputStream.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 27,290,955 | 5,382,920 | 692,480 | 6,372 | 688 | 113 | 10 | 1 | 2,647 | 400 | 652 | 53 | 2 | 0 | 2023-07-17T11:17:46 | 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,131 | quarkusio/quarkus/34925/13453 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/13453 | https://github.com/quarkusio/quarkus/pull/34925 | https://github.com/quarkusio/quarkus/pull/34925 | 1 | fixes | RestEasy Jaxb not registered properly anymore | **Describe the bug**
After Upgrading our Application from 1.9.2.Final to 1.10.0.Final which uses Jax-b, REST calls fail because there is no MessageBodyReader present anymore
```
RESTEASY003145: Unable to find a MessageBodyReader of content-type application/xml and type class xxx.xxx.xxx
```
The dependecies include
```
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-jaxb</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy-jaxb</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-rest-client-jaxb</artifactId>
</dependency>
```
Funny Note:
In Tests that are run without Quarkus, the Jaxb-Providers are still registered and working
**Expected behavior**
XML should be read with jaxb as before
**Actual behavior**
(Describe the actual behavior clearly and concisely.)
```
**Environment (please complete the following information):**
- Output of `uname -a` or `ver`: Linux 3.10.0-1160.6.1.el7.x86_64 #1 SMP Tue Nov 17 13:59:11 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
- Output of `java -version`: openjdk 11.0.9 2020-10-20 LTS
- Quarkus version or git rev: 1.10.0.Final
| a4172d43754cfedf8da2db889790e49e274bf8d7 | 55a771d85375b1891df01ab793e8a69c70b57c5b | https://github.com/quarkusio/quarkus/compare/a4172d43754cfedf8da2db889790e49e274bf8d7...55a771d85375b1891df01ab793e8a69c70b57c5b | diff --git a/extensions/resteasy-classic/resteasy-jaxb/deployment/src/main/java/io/quarkus/resteasy/jaxb/deployment/ResteasyJaxbProcessor.java b/extensions/resteasy-classic/resteasy-jaxb/deployment/src/main/java/io/quarkus/resteasy/jaxb/deployment/ResteasyJaxbProcessor.java
index e6d430d099d..e4ce30d18ac 100644
--- a/extensions/resteasy-classic/resteasy-jaxb/deployment/src/main/java/io/quarkus/resteasy/jaxb/deployment/ResteasyJaxbProcessor.java
+++ b/extensions/resteasy-classic/resteasy-jaxb/deployment/src/main/java/io/quarkus/resteasy/jaxb/deployment/ResteasyJaxbProcessor.java
@@ -4,6 +4,7 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import java.util.Set;
import org.jboss.jandex.DotName;
import org.jboss.jandex.IndexView;
@@ -20,6 +21,7 @@
import io.quarkus.deployment.builditem.FeatureBuildItem;
import io.quarkus.deployment.builditem.nativeimage.ReflectiveClassBuildItem;
import io.quarkus.jaxb.deployment.JaxbClassesToBeBoundBuildItem;
+import io.quarkus.resteasy.common.spi.ResteasyJaxrsProviderBuildItem;
public class ResteasyJaxbProcessor {
@@ -61,6 +63,23 @@ void build(BuildProducer<FeatureBuildItem> feature) {
feature.produce(new FeatureBuildItem(Feature.RESTEASY_JAXB));
}
+ @BuildStep
+ void registerProviders(BuildProducer<ResteasyJaxrsProviderBuildItem> jaxrsProviders) {
+ Set<String> providers = Set.of(
+ "org.jboss.resteasy.plugins.providers.SourceProvider",
+ "org.jboss.resteasy.plugins.providers.jaxb.JAXBXmlSeeAlsoProvider",
+ "org.jboss.resteasy.plugins.providers.jaxb.JAXBXmlRootElementProvider",
+ "org.jboss.resteasy.plugins.providers.jaxb.JAXBElementProvider",
+ "org.jboss.resteasy.plugins.providers.jaxb.JAXBXmlTypeProvider",
+ "org.jboss.resteasy.plugins.providers.jaxb.CollectionProvider",
+ "org.jboss.resteasy.plugins.providers.jaxb.MapProvider",
+ "org.jboss.resteasy.plugins.providers.jaxb.XmlJAXBContextFinder");
+
+ for (String provider : providers) {
+ jaxrsProviders.produce(new ResteasyJaxrsProviderBuildItem(provider));
+ }
+ }
+
private void addReflectiveClass(BuildProducer<ReflectiveClassBuildItem> reflectiveClass, boolean methods, boolean fields,
String... className) {
reflectiveClass.produce(new ReflectiveClassBuildItem(methods, fields, className)); | ['extensions/resteasy-classic/resteasy-jaxb/deployment/src/main/java/io/quarkus/resteasy/jaxb/deployment/ResteasyJaxbProcessor.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 27,406,272 | 5,405,384 | 695,091 | 6,382 | 1,041 | 225 | 19 | 1 | 1,342 | 135 | 367 | 42 | 0 | 2 | 2023-07-21T16:55: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,132 | quarkusio/quarkus/34885/34880 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/34880 | https://github.com/quarkusio/quarkus/pull/34885 | https://github.com/quarkusio/quarkus/pull/34885 | 1 | fixes | ConcurrentModificationException in Quarkus 3.2.x Dev Mode | ### Describe the bug
Currently, we are using Quarkus 3.1.3.Final without any issues. However, when we attempt to switch to version 3.2.0 or 3.2.1, we encounter a ConcurrentModificationException in quarkus-maven-plugin.
Here's the error output we received:
`[ERROR] Failed to execute goal io.quarkus:quarkus-maven-plugin:3.2.1.Final:dev (default-cli) on project my-project-quarkus: Failed to run: ConcurrentModificationException`
The full stack trace can be found in Additional Information.
Upon investigating the issue, I traced the problematic code to the DevMojo class in the Quarkus repository, specifically in the following method:
[GitHub DevMojo.java](https://github.com/quarkusio/quarkus/blob/e23f4345951f680915559f42c7d263f4e6b77db9/devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java#L1063C7-L1077C10).
In this code snippet, the effectiveProperties HashMap is modified while being iterated over, causing the ConcurrentModificationException.
Here's the specific part of the code causing the issue:
```
for (String value : effectiveProperties.values()) {
for (String reference : Expression.compile(value, LENIENT_SYNTAX, NO_TRIM).getReferencedStrings()) {
String referenceValue = session.getUserProperties().getProperty(reference);
if (referenceValue != null) {
effectiveProperties.put(reference, referenceValue); // This line causes the ConcurrentModificationException
continue;
}
referenceValue = projectProperties.getProperty(reference);
if (referenceValue != null) {
effectiveProperties.put(reference, referenceValue); // This line also causes the ConcurrentModificationException
}
}
}
```
I haven't found anything about why it started in this version yet. However, I can confirm that this issue can be resolved by using a different approach to updating the effectiveProperties HashMap during iteration.
Please let me know if you need any additional information or if there is anything else I can do to help in resolving this bug.
### Expected behavior
_No response_
### Actual behavior
_No response_
### How to Reproduce?
_No response_
### Output of `uname -a` or `ver`
Darwin Kernel Version 22.5.0: Thu Jun 8 22:22:22 PDT 2023; root:xnu-8796.121.3~7/RELEASE_X86_64 x86_64
### Output of `java -version`
java version "17.0.4.1" 2022-08-18 LTS Java(TM) SE Runtime Environment (build 17.0.4.1+1-LTS-2) Java HotSpot(TM) 64-Bit Server VM (build 17.0.4.1+1-LTS-2, mixed mode, sharing)
### GraalVM version (if different from Java)
_No response_
### Quarkus version or git rev
3.2.x
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
Apache Maven 3.9.3
### Additional information
```
[ERROR] Failed to execute goal io.quarkus:quarkus-maven-plugin:3.2.1.Final:dev (default-cli) on project my-project-quarkus: Failed to run: ConcurrentModificationException -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal io.quarkus:quarkus-maven-plugin:3.2.1.Final:dev (default-cli) on project my-project-quarkus: Failed to run
at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute2 (MojoExecutor.java:333)
at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute (MojoExecutor.java:316)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:212)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:174)
at org.apache.maven.lifecycle.internal.MojoExecutor.access$000 (MojoExecutor.java:75)
at org.apache.maven.lifecycle.internal.MojoExecutor$1.run (MojoExecutor.java:162)
at org.apache.maven.plugin.DefaultMojosExecutionStrategy.execute (DefaultMojosExecutionStrategy.java:39)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:159)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:105)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:73)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:53)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:118)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:261)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:173)
at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:101)
at org.apache.maven.cli.MavenCli.execute (MavenCli.java:906)
at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:283)
at org.apache.maven.cli.MavenCli.main (MavenCli.java:206)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:568)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:283)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:226)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:407)
at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:348)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:568)
at org.apache.maven.wrapper.BootstrapMainStarter.start (BootstrapMainStarter.java:39)
at org.apache.maven.wrapper.WrapperExecutor.execute (WrapperExecutor.java:122)
at org.apache.maven.wrapper.MavenWrapperMain.main (MavenWrapperMain.java:61)
Caused by: org.apache.maven.plugin.MojoFailureException: Failed to run
at io.quarkus.maven.DevMojo.execute (DevMojo.java:482)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:126)
at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute2 (MojoExecutor.java:328)
at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute (MojoExecutor.java:316)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:212)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:174)
at org.apache.maven.lifecycle.internal.MojoExecutor.access$000 (MojoExecutor.java:75)
at org.apache.maven.lifecycle.internal.MojoExecutor$1.run (MojoExecutor.java:162)
at org.apache.maven.plugin.DefaultMojosExecutionStrategy.execute (DefaultMojosExecutionStrategy.java:39)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:159)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:105)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:73)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:53)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:118)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:261)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:173)
at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:101)
at org.apache.maven.cli.MavenCli.execute (MavenCli.java:906)
at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:283)
at org.apache.maven.cli.MavenCli.main (MavenCli.java:206)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:568)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:283)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:226)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:407)
at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:348)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:568)
at org.apache.maven.wrapper.BootstrapMainStarter.start (BootstrapMainStarter.java:39)
at org.apache.maven.wrapper.WrapperExecutor.execute (WrapperExecutor.java:122)
at org.apache.maven.wrapper.MavenWrapperMain.main (MavenWrapperMain.java:61)
Caused by: java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode (HashMap.java:1597)
at java.util.HashMap$ValueIterator.next (HashMap.java:1625)
at io.quarkus.maven.DevMojo.newLauncher (DevMojo.java:1064)
at io.quarkus.maven.DevMojo$DevModeRunner.<init> (DevMojo.java:957)
at io.quarkus.maven.DevMojo.execute (DevMojo.java:439)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:126)
at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute2 (MojoExecutor.java:328)
at org.apache.maven.lifecycle.internal.MojoExecutor.doExecute (MojoExecutor.java:316)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:212)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:174)
at org.apache.maven.lifecycle.internal.MojoExecutor.access$000 (MojoExecutor.java:75)
at org.apache.maven.lifecycle.internal.MojoExecutor$1.run (MojoExecutor.java:162)
at org.apache.maven.plugin.DefaultMojosExecutionStrategy.execute (DefaultMojosExecutionStrategy.java:39)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:159)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:105)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:73)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:53)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:118)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:261)
at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:173)
at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:101)
at org.apache.maven.cli.MavenCli.execute (MavenCli.java:906)
at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:283)
at org.apache.maven.cli.MavenCli.main (MavenCli.java:206)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:568)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:283)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:226)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:407)
at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:348)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:77)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:568)
at org.apache.maven.wrapper.BootstrapMainStarter.start (BootstrapMainStarter.java:39)
at org.apache.maven.wrapper.WrapperExecutor.execute (WrapperExecutor.java:122)
at org.apache.maven.wrapper.MavenWrapperMain.main (MavenWrapperMain.java:61)
[ERROR]
[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/MojoFailureException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR] mvn <args> -rf :my-project-quarkus
``` | 35c1ca2cf25e017d3096a3006012205a6f212dca | 57049246823286d84f3b7713d8c1961948586d3d | https://github.com/quarkusio/quarkus/compare/35c1ca2cf25e017d3096a3006012205a6f212dca...57049246823286d84f3b7713d8c1961948586d3d | 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 848cd78bedc..b06e1b16173 100644
--- a/devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java
+++ b/devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java
@@ -1061,7 +1061,8 @@ private QuarkusDevModeLauncher newLauncher(Boolean debugPortOk, String bootstrap
}
// Add other properties that may be required for expansion
- for (String value : effectiveProperties.values()) {
+ List<String> effectivePropertyValues = new ArrayList<>(effectiveProperties.values());
+ for (String value : effectivePropertyValues) {
for (String reference : Expression.compile(value, LENIENT_SYNTAX, NO_TRIM).getReferencedStrings()) {
String referenceValue = session.getUserProperties().getProperty(reference);
if (referenceValue != null) { | ['devtools/maven/src/main/java/io/quarkus/maven/DevMojo.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 27,363,876 | 5,397,742 | 694,156 | 6,375 | 211 | 37 | 3 | 1 | 12,954 | 738 | 3,085 | 196 | 2 | 2 | 2023-07-20T10:55:07 | 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,134 | quarkusio/quarkus/34856/34825 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/34825 | https://github.com/quarkusio/quarkus/pull/34856 | https://github.com/quarkusio/quarkus/pull/34856 | 1 | fixes | quarkus.analytics.uri.base unrecognized by build time analytics | ### Describe the bug
`quarkus-maven-plugin` reports a warning
```
[WARNING] [io.quarkus.config] Unrecognized configuration key "quarkus.analytics.uri.base" was provided; it will be ignored; verify that the dependency extension for this configuration is set or that you did not make a typo
```
when the `quarkus.analytics.uri.base` is provided.
The warning is issued regardless of whether the analytics are active or not.
The other analytics-related properties are fine:
```
quarkus.analytics.disabled
quarkus.analytics.timeout
```
### Expected behavior
No warning in build/app log.
### Actual behavior
_No response_
### How to Reproduce?
```
quarkus create app bta-reproducer --no-code
cd bta-reproducer
quarkus build -Dquarkus.analytics.uri.base="http://fake.url"
```
### Output of `uname -a` or `ver`
Linux 6.2.15-200.fc37.x86_64
### Output of `java -version`
openjdk 17.0.7 2023-04-18
### GraalVM version (if different from Java)
_No response_
### Quarkus version or git rev
3.2.0.Final, 999-SNAPSHOT
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
3.8.8
### Additional information
_No response_ | 9e0ebaf2876eb64e1947e0b073772cae07b6a049 | d84973523d813201dbbe7bdbc42f99bf71d3ed0e | https://github.com/quarkusio/quarkus/compare/9e0ebaf2876eb64e1947e0b073772cae07b6a049...d84973523d813201dbbe7bdbc42f99bf71d3ed0e | diff --git a/core/runtime/src/main/java/io/quarkus/runtime/BuildAnalyticsConfig.java b/core/runtime/src/main/java/io/quarkus/runtime/BuildAnalyticsConfig.java
index e34b1a0e1af..73929157752 100644
--- a/core/runtime/src/main/java/io/quarkus/runtime/BuildAnalyticsConfig.java
+++ b/core/runtime/src/main/java/io/quarkus/runtime/BuildAnalyticsConfig.java
@@ -23,7 +23,7 @@ public class BuildAnalyticsConfig {
/**
* The Segment base URI.
*/
- @ConfigItem
+ @ConfigItem(name = "uri.base")
public Optional<String> uriBase;
/** | ['core/runtime/src/main/java/io/quarkus/runtime/BuildAnalyticsConfig.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 27,322,830 | 5,388,064 | 693,151 | 6,374 | 52 | 15 | 2 | 1 | 1,158 | 148 | 310 | 55 | 1 | 3 | 2023-07-19T13:57:17 | 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,136 | quarkusio/quarkus/34792/34759 | quarkusio | quarkus | https://github.com/quarkusio/quarkus/issues/34759 | https://github.com/quarkusio/quarkus/pull/34792 | https://github.com/quarkusio/quarkus/pull/34792 | 1 | fixes | Application throws "Configuration validation failed" exception for service-binded properties | ### Describe the bug
I have an application, which uses service binding and requires postgress, deployed by crunchydata operator. When I deploy the app on the Openshift via extension, it fails to start with "Configuration validation failed" exception, but only if use 999-SNAPOSHOT Quarkus build
### Expected behavior
The application should start successfully, same as for 3.1.0.Final and 3.2.0.Final
### Actual behavior
The pod crash-loops and logs contain this exception:
```
java.lang.RuntimeException: Failed to start quarkus
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:111)
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)
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.bootstrap.runner.QuarkusEntryPoint.doRun(QuarkusEntryPoint.java:61)
at io.quarkus.bootstrap.runner.QuarkusEntryPoint.main(QuarkusEntryPoint.java:32)
Caused by: io.smallrye.config.ConfigValidationException: Configuration validation failed:
SRCFG00050: quarkus.kubernetes-service-binding.services.postgresql.name in io.smallrye.config.ConfigSourceContext$ConfigSourceContextConfigSource does not map to any root
SRCFG00050: quarkus.kubernetes-service-binding.services.postgresql.api-version in io.smallrye.config.ConfigSourceContext$ConfigSourceContextConfigSource does not map to any root
SRCFG00050: quarkus.kubernetes-service-binding.services.postgresql.kind in io.smallrye.config.ConfigSourceContext$ConfigSourceContextConfigSource does not map to any root
at io.smallrye.config.ConfigMappingProvider.mapConfigurationInternal(ConfigMappingProvider.java:1001)
at io.smallrye.config.ConfigMappingProvider.lambda$mapConfiguration$3(ConfigMappingProvider.java:957)
at io.smallrye.config.SecretKeys.doUnlocked(SecretKeys.java:28)
at io.smallrye.config.ConfigMappingProvider.mapConfiguration(ConfigMappingProvider.java:957)
at io.smallrye.config.ConfigMappings.mapConfiguration(ConfigMappings.java:91)
at io.smallrye.config.SmallRyeConfigBuilder.build(SmallRyeConfigBuilder.java:630)
at io.smallrye.config.ConfigSourceFactory$ConfigurableConfigSourceFactory.getConfigSources(ConfigSourceFactory.java:54)
at io.smallrye.config.ConfigurableConfigSource.getConfigSources(ConfigurableConfigSource.java:50)
at io.smallrye.config.SmallRyeConfig$ConfigSources.mapLateSources(SmallRyeConfig.java:669)
at io.smallrye.config.SmallRyeConfig$ConfigSources.<init>(SmallRyeConfig.java:553)
at io.smallrye.config.SmallRyeConfig.<init>(SmallRyeConfig.java:69)
at io.smallrye.config.SmallRyeConfigBuilder.build(SmallRyeConfigBuilder.java:629)
at io.quarkus.runtime.generated.Config.readConfig(Unknown Source)
at io.quarkus.deployment.steps.RuntimeConfigSetup.deploy(Unknown Source)
... 13 more
```
### How to Reproduce?
1. Clone the reproducer `git clone https://github.com/fedinskiy/reproducer -b postgres-cluster-properties`
2. Create new project on kubernetes: `oc new-project fd-postgres`
3. Verify, that Crunchy operator is installed:
```
$ oc get csv
NAME DISPLAY VERSION REPLACES PHASE
datagrid-operator.v8.4.6 Data Grid 8.4.6 datagrid-operator.v8.4.5 Succeeded
postgresoperator.v5.4.0 Crunchy Postgres for Kubernetes 5.4.0 postgresoperator.v5.3.0 Succeeded
serverless-operator.v1.29.0 Red Hat OpenShift Serverless 1.29.0 serverless-operator.v1.28.0 Succeeded
service-binding-operator.v1.3.3 Service Binding Operator 1.3.3 service-binding-operator.v1.3.1 Succeeded
```
4. Create postgres cluster: `oc apply -f pg-cluster.yml`
5. Wait for cluster to start: `oc wait --for condition=Ready --timeout=300s pods --all`
6. Deploy the app: `mvn package -Dquarkus.kubernetes.deploy=true -Dquarkus.openshift.expose=true -Dquarkus.openshift.route.expose=true -Dquarkus.kubernetes-client.trust-certs=true -Dquarkus.openshift.build-strategy=docker -Dquarkus.openshift.base-jvm-image=registry.access.redhat.com/ubi8/openjdk-17:latest -Dquarkus.platform.version=999-SNAPSHOT -Dquarkus.platform.group-id=io.quarkus`
7. Check deployments:
```
$ oc get pods
NAME READY STATUS RESTARTS AGE
hippo-backup-b8f9-mmmhq 0/1 Completed 0 3m5s
hippo-instance1-4nbf-0 4/4 Running 0 3m22s
hippo-repo-host-0 2/2 Running 0 3m22s
theapp-1-build 0/1 Completed 0 2m5s
theapp-1-deploy 0/1 Completed 0 48s
theapp-1-zq2q6 0/1 CrashLoopBackOff 2 (22s ago) 45s
```
8. Check logs: `oc logs theapp-1-zq2q6` (results above)
9. If started using command `mvn package -Dquarkus.kubernetes.deploy=true -Dquarkus.openshift.expose=true -Dquarkus.openshift.route.expose=true -Dquarkus.kubernetes-client.trust-certs=true -Dquarkus.openshift.build-strategy=docker -Dquarkus.openshift.base-jvm-image=registry.access.redhat.com/ubi8/openjdk-17:latest -Dquarkus.platform.version=3.2.0.Final` the application starts successfully.
### Output of `uname -a` or `ver`
6.3.8-200.fc38.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
1a9a20dc8f5964b8361f7785b4a173a98530ec29
### Build tool (ie. output of `mvnw --version` or `gradlew --version`)
Apache Maven 3.8.7 (b89d5959fcde851dcb1c8946a785a163f14e1e29)
### Additional information
```
$ oc version
Client Version: 4.13.0-202305312300.p0.g05d83ef.assembly.stream-05d83ef
Kustomize Version: v4.5.7
Kubernetes Version: v1.26.5+7d22122
``` | d903356bdf5b6b591dd5a66be6608252163642c9 | bec7a737c40b41816ad8c11bca9a0a2626a89020 | https://github.com/quarkusio/quarkus/compare/d903356bdf5b6b591dd5a66be6608252163642c9...bec7a737c40b41816ad8c11bca9a0a2626a89020 | diff --git a/extensions/kubernetes-service-binding/runtime/src/main/java/io/quarkus/kubernetes/service/binding/runtime/KubernetesServiceBindingConfigSourceFactory.java b/extensions/kubernetes-service-binding/runtime/src/main/java/io/quarkus/kubernetes/service/binding/runtime/KubernetesServiceBindingConfigSourceFactory.java
index 44f675d4349..df605dc3633 100644
--- a/extensions/kubernetes-service-binding/runtime/src/main/java/io/quarkus/kubernetes/service/binding/runtime/KubernetesServiceBindingConfigSourceFactory.java
+++ b/extensions/kubernetes-service-binding/runtime/src/main/java/io/quarkus/kubernetes/service/binding/runtime/KubernetesServiceBindingConfigSourceFactory.java
@@ -18,28 +18,37 @@
import org.jboss.logging.Logger;
import io.smallrye.config.ConfigSourceContext;
-import io.smallrye.config.ConfigSourceFactory.ConfigurableConfigSourceFactory;
+import io.smallrye.config.ConfigSourceFactory;
+import io.smallrye.config.SmallRyeConfig;
+import io.smallrye.config.SmallRyeConfigBuilder;
-public class KubernetesServiceBindingConfigSourceFactory
- implements ConfigurableConfigSourceFactory<KubernetesServiceBindingConfig> {
+public class KubernetesServiceBindingConfigSourceFactory implements ConfigSourceFactory {
private static final Logger log = Logger.getLogger(KubernetesServiceBindingConfigSourceFactory.class);
@Override
- public Iterable<ConfigSource> getConfigSources(final ConfigSourceContext context,
- final KubernetesServiceBindingConfig config) {
- if (!config.enabled()) {
+ public Iterable<ConfigSource> getConfigSources(final ConfigSourceContext context) {
+ SmallRyeConfig config = new SmallRyeConfigBuilder()
+ .withSources(new ConfigSourceContext.ConfigSourceContextConfigSource(context))
+ .withMapping(KubernetesServiceBindingConfig.class)
+ .withMappingIgnore("quarkus.**")
+ .build();
+
+ KubernetesServiceBindingConfig kubernetesServiceBindingConfig = config
+ .getConfigMapping(KubernetesServiceBindingConfig.class);
+
+ if (!kubernetesServiceBindingConfig.enabled()) {
log.debug(
"No attempt will be made to bind configuration based on Kubernetes ServiceBinding because the feature was not enabled.");
return emptyList();
}
- if (config.root().isEmpty()) {
+ if (kubernetesServiceBindingConfig.root().isEmpty()) {
log.debug(
"No attempt will be made to bind configuration based on Kubernetes Service Binding because the binding root was not specified.");
return emptyList();
}
- List<ServiceBinding> serviceBindings = getServiceBindings(config.root().get());
+ List<ServiceBinding> serviceBindings = getServiceBindings(kubernetesServiceBindingConfig.root().get());
if (serviceBindings.isEmpty()) {
return emptyList();
} | ['extensions/kubernetes-service-binding/runtime/src/main/java/io/quarkus/kubernetes/service/binding/runtime/KubernetesServiceBindingConfigSourceFactory.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 27,290,683 | 5,382,868 | 692,477 | 6,372 | 1,549 | 278 | 25 | 1 | 6,381 | 416 | 1,689 | 106 | 1 | 4 | 2023-07-17T13:04:10 | 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 |
531 | codecentric/spring-boot-admin/1589/1586 | codecentric | spring-boot-admin | https://github.com/codecentric/spring-boot-admin/issues/1586 | https://github.com/codecentric/spring-boot-admin/pull/1589 | https://github.com/codecentric/spring-boot-admin/pull/1589#issuecomment-765189411 | 1 | closes | Unable to override spring.security.user.name and spring.security.user.password credentials in spring-boot-admin-sample-servlet sample | I was unable to override `spring.security.user.name` and `spring.security.user.password` credentials in spring-boot-admin-sample-servlet sample when I migrate from 2.1.6 to 2.3.1.
I think the problem may be related to this code [here](https://github.com/codecentric/spring-boot-admin/blob/10022c67a0fcbd6d6dadaf969a423824cc68ce5b/spring-boot-admin-samples/spring-boot-admin-sample-servlet/src/main/java/de/codecentric/boot/admin/SecuritySecureConfig.java#L71). It forces fixed credentials.
I look forward to your answer. | 8beb98664de476546c8f2df4627051764610a3e1 | dac53444fbc6eaa29225292486fea43e5e9d6ed5 | https://github.com/codecentric/spring-boot-admin/compare/8beb98664de476546c8f2df4627051764610a3e1...dac53444fbc6eaa29225292486fea43e5e9d6ed5 | diff --git a/spring-boot-admin-samples/spring-boot-admin-sample-servlet/src/main/java/de/codecentric/boot/admin/SecuritySecureConfig.java b/spring-boot-admin-samples/spring-boot-admin-sample-servlet/src/main/java/de/codecentric/boot/admin/SecuritySecureConfig.java
index 314539e7..794cc43c 100644
--- a/spring-boot-admin-samples/spring-boot-admin-sample-servlet/src/main/java/de/codecentric/boot/admin/SecuritySecureConfig.java
+++ b/spring-boot-admin-samples/spring-boot-admin-sample-servlet/src/main/java/de/codecentric/boot/admin/SecuritySecureConfig.java
@@ -18,6 +18,7 @@ package de.codecentric.boot.admin;
import java.util.UUID;
+import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpMethod;
@@ -38,8 +39,11 @@ public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
private final AdminServerProperties adminServer;
- public SecuritySecureConfig(AdminServerProperties adminServer) {
+ private final SecurityProperties security;
+
+ public SecuritySecureConfig(AdminServerProperties adminServer, SecurityProperties security) {
this.adminServer = adminServer;
+ this.security = security;
}
@Override
@@ -70,7 +74,8 @@ public class SecuritySecureConfig extends WebSecurityConfigurerAdapter {
// Required to provide UserDetailsService for "remember functionality"
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.inMemoryAuthentication().withUser("user").password("{noop}password").roles("USER");
+ auth.inMemoryAuthentication().withUser(security.getUser().getName())
+ .password("{noop}" + security.getUser().getPassword()).roles("USER");
}
} | ['spring-boot-admin-samples/spring-boot-admin-sample-servlet/src/main/java/de/codecentric/boot/admin/SecuritySecureConfig.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 545,695 | 113,488 | 15,941 | 196 | 553 | 101 | 9 | 1 | 526 | 40 | 136 | 5 | 1 | 0 | 2021-01-14T16:29:26 | 11,832 | Java | {'Java': 1222285, 'Vue': 485886, 'TypeScript': 421999, 'JavaScript': 28953, 'HTML': 9736, 'CSS': 7226, 'SCSS': 4803, 'MDX': 582, 'Dockerfile': 159} | Apache License 2.0 |
616 | zaproxy/zaproxy/7194/6001 | zaproxy | zaproxy | https://github.com/zaproxy/zaproxy/issues/6001 | https://github.com/zaproxy/zaproxy/pull/7194 | https://github.com/zaproxy/zaproxy/pull/7194 | 1 | fixes | Context endpoint on API does not output included and excluded technologies | **Describe the bug**
When browsing the context through the API, it does not output what technologies are included or excluded. The API correctly allows a user to include or exclude technologies programmatically, however the view Context endpoint is missing data from its output.
**To Reproduce**
Steps to reproduce the behavior:
1. Open ZAP api in your browser, http://localhost:8080/UI/context/view/context/
2. Enter in a valid context name and the api key.
3. The results will not show you the included or excluded technologies
**Expected behavior**
A list of the included or excluded technologies.
** To fix **
This method is missing the output of the included and excluded technologies
https://github.com/zaproxy/zaproxy/blob/master/zap/src/main/java/org/zaproxy/zap/extension/api/ContextAPI.java#L385
| d7c1dea21ba409a602b123b5ae91300f525ecd12 | fd9b27c46f6fe7dda4d011564b2058a52b989e06 | https://github.com/zaproxy/zaproxy/compare/d7c1dea21ba409a602b123b5ae91300f525ecd12...fd9b27c46f6fe7dda4d011564b2058a52b989e06 | diff --git a/zap/src/main/java/org/zaproxy/zap/extension/api/ContextAPI.java b/zap/src/main/java/org/zaproxy/zap/extension/api/ContextAPI.java
index 08fa4b7f7..3c03ad5a2 100644
--- a/zap/src/main/java/org/zaproxy/zap/extension/api/ContextAPI.java
+++ b/zap/src/main/java/org/zaproxy/zap/extension/api/ContextAPI.java
@@ -28,6 +28,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
+import java.util.stream.Collectors;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
@@ -37,6 +38,9 @@ import org.apache.logging.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.model.Model;
import org.parosproxy.paros.model.SiteNode;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Text;
import org.zaproxy.zap.authentication.AuthenticationMethod;
import org.zaproxy.zap.authentication.AuthenticationMethod.AuthCheckingStrategy;
import org.zaproxy.zap.authentication.AuthenticationMethod.AuthPollFrequencyUnits;
@@ -49,6 +53,7 @@ import org.zaproxy.zap.model.Tech;
import org.zaproxy.zap.model.TechSet;
import org.zaproxy.zap.utils.ApiUtils;
import org.zaproxy.zap.utils.JsonUtil;
+import org.zaproxy.zap.utils.XMLStringUtil;
public class ContextAPI extends ApiImplementor {
@@ -458,13 +463,23 @@ public class ContextAPI extends ApiImplementor {
* @return the api response
*/
private ApiResponse buildResponseFromContext(Context c) {
- Map<String, String> fields = new HashMap<>();
+ Map<String, Object> fields = new HashMap<>();
fields.put("name", c.getName());
fields.put("id", Integer.toString(c.getId()));
fields.put("description", c.getDescription());
fields.put("inScope", Boolean.toString(c.isInScope()));
fields.put("excludeRegexs", jsonEncodeList(c.getExcludeFromContextRegexs()));
fields.put("includeRegexs", jsonEncodeList(c.getIncludeInContextRegexs()));
+ fields.put(
+ "includedTechnologies",
+ c.getTechSet().getIncludeTech().stream()
+ .map(Tech::toString)
+ .collect(Collectors.toList()));
+ fields.put(
+ "excludedTechnologies",
+ c.getTechSet().getExcludeTech().stream()
+ .map(Tech::toString)
+ .collect(Collectors.toList()));
AuthenticationMethod authenticationMethod = c.getAuthenticationMethod();
if (authenticationMethod != null) {
@@ -502,7 +517,40 @@ public class ContextAPI extends ApiImplementor {
"postParameterParserClass", c.getPostParamParser().getClass().getCanonicalName());
fields.put("postParameterParserConfig", c.getPostParamParser().getConfig());
- return new ApiResponseSet<>("context", fields);
+ return new ContextApiResponseSet<>("context", fields);
+ }
+
+ private static class ContextApiResponseSet<T> extends ApiResponseSet<T> {
+
+ ContextApiResponseSet(String name, Map<String, T> values) {
+ super(name, values);
+ }
+
+ @Override
+ public void toXML(Document doc, Element parent) {
+ parent.setAttribute("type", "set");
+ for (Map.Entry<String, T> val : getValues().entrySet()) {
+ Element el = doc.createElement(val.getKey());
+ if ("includedTechnologies".equals(val.getKey())
+ || "excludedTechnologies".equals(val.getKey())) {
+ el.setAttribute("type", "list");
+ @SuppressWarnings("unchecked")
+ List<String> techs = (List<String>) val.getValue();
+ for (String tech : techs) {
+ Element elTech = doc.createElement("tech");
+ elTech.appendChild(
+ doc.createTextNode(XMLStringUtil.escapeControlChrs(tech)));
+
+ el.appendChild(elTech);
+ }
+ } else {
+ String textValue = val.getValue() == null ? "" : val.getValue().toString();
+ Text text = doc.createTextNode(XMLStringUtil.escapeControlChrs(textValue));
+ el.appendChild(text);
+ }
+ parent.appendChild(el);
+ }
+ }
}
private String jsonEncodeList(List<String> list) { | ['zap/src/main/java/org/zaproxy/zap/extension/api/ContextAPI.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,909,983 | 1,974,408 | 270,522 | 1,159 | 2,308 | 401 | 52 | 1 | 827 | 108 | 177 | 16 | 2 | 0 | 2022-04-08T01:40:03 | 11,102 | Java | {'Java': 12002133, 'HTML': 3977629, 'Python': 158050, 'Kotlin': 54286, 'JavaScript': 9640, 'Shell': 8430, 'Lex': 5179, 'Perl': 3832, 'XSLT': 3054} | Apache License 2.0 |
615 | zaproxy/zaproxy/7222/7221 | zaproxy | zaproxy | https://github.com/zaproxy/zaproxy/issues/7221 | https://github.com/zaproxy/zaproxy/pull/7222 | https://github.com/zaproxy/zaproxy/pull/7222 | 1 | fix | Default policy on start up not using edited policy rules | ### Describe the bug
modified rules of the auto selected scan policy are not used. 'Default' is shown and used for the active scans.
### Steps to reproduce the behavior
Change the rules of the default policy, then close zap and restart.
Attempt an active scan, the default policy is used however the edited rules that I changed are not shown. It states 'Default' for all rules.
If reselect default policy from drop down in active scan pop up then modified rules show.
From then on the default policy has the correct modified rules for all active scans.
### Expected behavior
Show and use modified rules
### Software versions
2.11.1
### Screenshots
_No response_
### Errors from the zap.log file
_No response_
### Additional context
_No response_
### Would you like to help fix this issue?
- [ ] Yes | d2d0b7155b5bd6a55851c2edd5e13b6e26a930dc | ae2797e0c4fea78bbe32cc971f86e16c4edadb42 | https://github.com/zaproxy/zaproxy/compare/d2d0b7155b5bd6a55851c2edd5e13b6e26a930dc...ae2797e0c4fea78bbe32cc971f86e16c4edadb42 | diff --git a/zap/src/main/java/org/zaproxy/zap/extension/ascan/CustomScanDialog.java b/zap/src/main/java/org/zaproxy/zap/extension/ascan/CustomScanDialog.java
index 2420ce43c..0fc5fd738 100644
--- a/zap/src/main/java/org/zaproxy/zap/extension/ascan/CustomScanDialog.java
+++ b/zap/src/main/java/org/zaproxy/zap/extension/ascan/CustomScanDialog.java
@@ -146,10 +146,7 @@ public class CustomScanDialog extends StandardFieldsDialog {
this.customPanels = customPanels;
this.policyPanel =
new ScanPolicyPanel(
- this,
- extension,
- Constant.messages.getString("ascan.custom.tab.policy"),
- new ScanPolicy());
+ this, extension, Constant.messages.getString("ascan.custom.tab.policy"));
this.filterPanel = new FilterPanel();
addWindowListener(
new WindowAdapter() {
@@ -259,6 +256,7 @@ public class CustomScanDialog extends StandardFieldsDialog {
getTechTree().refresh();
setTechSet(techTreeState);
+ policyPanel.initScanPolicy(scanPolicy);
this.setCustomTabPanel(4, policyPanel);
// Filter panel
@@ -982,14 +980,10 @@ public class CustomScanDialog extends StandardFieldsDialog {
private List<PolicyCategoryPanel> categoryPanels = Collections.emptyList();
private ScanPolicy scanPolicy;
- public ScanPolicyPanel(
- Window parent,
- ExtensionActiveScan extension,
- String rootName,
- ScanPolicy scanPolicy) {
+ ScanPolicyPanel(Window parent, ExtensionActiveScan extension, String rootName) {
super(rootName);
- this.scanPolicy = scanPolicy;
+ this.scanPolicy = new ScanPolicy();
String[] ROOT = {};
policyAllCategoryPanel =
@@ -1021,6 +1015,26 @@ public class CustomScanDialog extends StandardFieldsDialog {
this.categoryPanels.add(panel);
}
showDialog(true);
+
+ scanPolicy = null;
+ }
+
+ /**
+ * Initialises the panel with the given policy.
+ *
+ * <p>Successive calls have no effect.
+ *
+ * @param scanPolicy the scan policy.
+ * @see #setScanPolicy(ScanPolicy)
+ * @see #resetAndSetPolicy(String)
+ */
+ void initScanPolicy(ScanPolicy scanPolicy) {
+ if (this.scanPolicy != null || scanPolicy == null) {
+ return;
+ }
+
+ this.scanPolicy = scanPolicy;
+ setScanPolicy(scanPolicy);
}
public void resetAndSetPolicy(String scanPolicyName) { | ['zap/src/main/java/org/zaproxy/zap/extension/ascan/CustomScanDialog.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,912,020 | 1,974,766 | 270,570 | 1,159 | 1,292 | 228 | 34 | 1 | 824 | 140 | 175 | 37 | 0 | 0 | 2022-04-20T10:09:13 | 11,102 | Java | {'Java': 12002133, 'HTML': 3977629, 'Python': 158050, 'Kotlin': 54286, 'JavaScript': 9640, 'Shell': 8430, 'Lex': 5179, 'Perl': 3832, 'XSLT': 3054} | Apache License 2.0 |
614 | zaproxy/zaproxy/7325/541 | zaproxy | zaproxy | https://github.com/zaproxy/zaproxy/issues/541 | https://github.com/zaproxy/zaproxy/pull/7325 | https://github.com/zaproxy/zaproxy/pull/7325 | 1 | fixes | Break panel icons do not resize | ```
I'd rather open it up for comment to see if anyone else agrees first.
One: If you're continually using them, you'd want something big you can easily click.
There's a bit of precision clicking going or a little extra care which is required
if you're clicking constantly at a high rate.
As a bonus, i've seen quite a few people starting off with zap miss them completely
because of their size and not know how to intercept. While yes, rtfm, ui that allows
you to easily infer how to use it is a good thing.
I do think burp got the right scale + having names on this one. What do people think
comparing the two?
```
Original issue reported on code.google.com by `[email protected]` on 2013-02-27 09:59:47
| 2d90058e7e5c411ca19f180fd30279ed60d6e753 | fde4617596e711c5cd1db2fe4e5fcebe5a947159 | https://github.com/zaproxy/zaproxy/compare/2d90058e7e5c411ca19f180fd30279ed60d6e753...fde4617596e711c5cd1db2fe4e5fcebe5a947159 | diff --git a/zap/src/main/java/org/parosproxy/paros/extension/manualrequest/ManualRequestEditorDialog.java b/zap/src/main/java/org/parosproxy/paros/extension/manualrequest/ManualRequestEditorDialog.java
index 5e12593de..b391b8632 100644
--- a/zap/src/main/java/org/parosproxy/paros/extension/manualrequest/ManualRequestEditorDialog.java
+++ b/zap/src/main/java/org/parosproxy/paros/extension/manualrequest/ManualRequestEditorDialog.java
@@ -41,11 +41,11 @@
// ZAP: 2020/11/20 Support Send button in response panel in tab mode
// ZAP: 2020/11/26 Use Log4j 2 classes for logging.
// ZAP: 2021/02/12 Add shortcut key to Send button (Issue 6448).
+// ZAP: 2022/06/08 Fix resizing issues.
package org.parosproxy.paros.extension.manualrequest;
import java.awt.BorderLayout;
import java.awt.Component;
-import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.HeadlessException;
import java.awt.event.KeyEvent;
@@ -68,6 +68,7 @@ import org.zaproxy.zap.extension.httppanel.HttpPanelRequest;
import org.zaproxy.zap.extension.httppanel.InvalidMessageDataException;
import org.zaproxy.zap.extension.httppanel.Message;
import org.zaproxy.zap.extension.tab.Tab;
+import org.zaproxy.zap.utils.DisplayUtils;
import org.zaproxy.zap.view.ZapMenuItem;
/** Send custom crafted messages via HTTP or other TCP based protocols. */
@@ -100,7 +101,7 @@ public abstract class ManualRequestEditorDialog extends AbstractFrame implements
this.isSendEnabled = isSendEnabled;
this.configurationKey = OptionsParamView.BASE_VIEW_KEY + "." + configurationKey + ".";
- this.setPreferredSize(new Dimension(700, 800));
+ this.setPreferredSize(DisplayUtils.getScaledDimension(700, 800));
}
protected void initialize() {
diff --git a/zap/src/main/java/org/parosproxy/paros/view/AbstractParamContainerPanel.java b/zap/src/main/java/org/parosproxy/paros/view/AbstractParamContainerPanel.java
index 57b9c36a4..3a573b359 100644
--- a/zap/src/main/java/org/parosproxy/paros/view/AbstractParamContainerPanel.java
+++ b/zap/src/main/java/org/parosproxy/paros/view/AbstractParamContainerPanel.java
@@ -39,6 +39,7 @@
// ZAP: 2021/11/19 Remove empty parent nodes.
// ZAP: 2022/02/12 Show child panel if parent has none.
// ZAP: 2022/05/11 Use a unique ID to identify the panels instead of their name (Issue 5637).
+// ZAP: 2022/06/08 Fix resizing issues.
package org.parosproxy.paros.view;
import java.awt.BorderLayout;
@@ -156,8 +157,8 @@ public class AbstractParamContainerPanel extends JSplitPane {
this.setContinuousLayout(true);
this.setRightComponent(getJPanel1());
// ZAP: added more space for readability (was 175)
- this.setDividerLocation(200);
- this.setDividerSize(3);
+ this.setDividerLocation(DisplayUtils.getScaledSize(200));
+ this.setDividerSize(DisplayUtils.getScaledSize(3));
this.setResizeWeight(0.3D);
this.setBorder(
javax.swing.BorderFactory.createEtchedBorder(
diff --git a/zap/src/main/java/org/parosproxy/paros/view/OptionsDialog.java b/zap/src/main/java/org/parosproxy/paros/view/OptionsDialog.java
index f3b1b2705..5104260ab 100644
--- a/zap/src/main/java/org/parosproxy/paros/view/OptionsDialog.java
+++ b/zap/src/main/java/org/parosproxy/paros/view/OptionsDialog.java
@@ -23,6 +23,7 @@
// ZAP: 2019/06/01 Normalise line endings.
// ZAP: 2019/06/05 Normalise format/style.
// ZAP: 2020/11/26 Use Log4j 2 classes for logging.
+// ZAP: 2022/06/08 Fix resizing issues.
package org.parosproxy.paros.view;
import java.awt.Frame;
@@ -37,6 +38,7 @@ import org.apache.logging.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.model.Model;
import org.parosproxy.paros.model.OptionsParam;
+import org.zaproxy.zap.utils.DisplayUtils;
public class OptionsDialog extends AbstractParamDialog {
@@ -61,10 +63,7 @@ public class OptionsDialog extends AbstractParamDialog {
/** This method initializes this */
private void initialize() {
- // ZAP: Increase width and height of options dialog
- // if (Model.getSingleton().getOptionsParam().getViewParam().getWmUiHandlingOption() == 0) {
- this.setSize(750, 584);
- // }
+ this.setSize(DisplayUtils.getScaledDimension(750, 584));
}
@Override
diff --git a/zap/src/main/java/org/zaproxy/zap/extension/ascan/PolicyDialog.java b/zap/src/main/java/org/zaproxy/zap/extension/ascan/PolicyDialog.java
index 768cb8ccf..489e106d7 100644
--- a/zap/src/main/java/org/zaproxy/zap/extension/ascan/PolicyDialog.java
+++ b/zap/src/main/java/org/zaproxy/zap/extension/ascan/PolicyDialog.java
@@ -32,6 +32,7 @@ import org.parosproxy.paros.Constant;
import org.parosproxy.paros.core.scanner.Category;
import org.parosproxy.paros.view.AbstractParamDialog;
import org.parosproxy.paros.view.AbstractParamPanel;
+import org.zaproxy.zap.utils.DisplayUtils;
public class PolicyDialog extends AbstractParamDialog {
@@ -58,7 +59,7 @@ public class PolicyDialog extends AbstractParamDialog {
private void initialize() {
this.setTitle(POLICY);
- this.setSize(750, 420);
+ this.setSize(DisplayUtils.getScaledDimension(750, 420));
addParamPanel(null, getPolicyAllCategoryPanel(), false);
for (int i = 0; i < Category.getAllNames().length; i++) {
diff --git a/zap/src/main/java/org/zaproxy/zap/extension/ascan/PolicyManagerDialog.java b/zap/src/main/java/org/zaproxy/zap/extension/ascan/PolicyManagerDialog.java
index 9b9670967..ca54b1ca1 100644
--- a/zap/src/main/java/org/zaproxy/zap/extension/ascan/PolicyManagerDialog.java
+++ b/zap/src/main/java/org/zaproxy/zap/extension/ascan/PolicyManagerDialog.java
@@ -19,7 +19,6 @@
*/
package org.zaproxy.zap.extension.ascan;
-import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
@@ -41,6 +40,7 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.view.View;
+import org.zaproxy.zap.utils.DisplayUtils;
import org.zaproxy.zap.view.SingleColumnTableModel;
import org.zaproxy.zap.view.StandardFieldsDialog;
import org.zaproxy.zap.view.widgets.WritableFileChooser;
@@ -63,7 +63,7 @@ public class PolicyManagerDialog extends StandardFieldsDialog {
private static final Logger logger = LogManager.getLogger(PolicyManagerDialog.class);
public PolicyManagerDialog(Frame owner) {
- super(owner, "ascan.policymgr.title", new Dimension(512, 400));
+ super(owner, "ascan.policymgr.title", DisplayUtils.getScaledDimension(512, 400));
}
public void init(ExtensionActiveScan extension) {
diff --git a/zap/src/main/java/org/zaproxy/zap/extension/brk/BreakPanelToolbarFactory.java b/zap/src/main/java/org/zaproxy/zap/extension/brk/BreakPanelToolbarFactory.java
index 32694a4c7..bd22e25e3 100644
--- a/zap/src/main/java/org/zaproxy/zap/extension/brk/BreakPanelToolbarFactory.java
+++ b/zap/src/main/java/org/zaproxy/zap/extension/brk/BreakPanelToolbarFactory.java
@@ -35,6 +35,7 @@ import org.parosproxy.paros.control.Control;
import org.parosproxy.paros.view.TabbedPanel;
import org.parosproxy.paros.view.View;
import org.zaproxy.zap.extension.brk.impl.http.HttpBreakpointMessage;
+import org.zaproxy.zap.utils.DisplayUtils;
import org.zaproxy.zap.utils.Stats;
import org.zaproxy.zap.view.TabbedPanel2;
import org.zaproxy.zap.view.ZapToggleButton;
@@ -51,6 +52,8 @@ import org.zaproxy.zap.view.ZapToggleButton;
public class BreakPanelToolbarFactory {
+ private static final String ICON_RESOURCE_PATH = "/resource/icon/";
+
private ContinueButtonAction continueButtonAction;
private StepButtonAction stepButtonAction;
private DropButtonAction dropButtonAction;
@@ -165,6 +168,12 @@ public class BreakPanelToolbarFactory {
return ignoreRulesEnable;
}
+ private static ImageIcon getScaledIcon(String path) {
+ return DisplayUtils.getScaledIcon(
+ new ImageIcon(
+ BreakPanelToolbarFactory.class.getResource(ICON_RESOURCE_PATH + path)));
+ }
+
private void setActiveIcon(boolean active) {
if (active) {
// Have to do this before the getParent() call
@@ -174,16 +183,11 @@ public class BreakPanelToolbarFactory {
TabbedPanel parent = (TabbedPanel) breakPanel.getParent();
if (active) {
parent.setIconAt(
- parent.indexOfComponent(breakPanel),
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource(
- "/resource/icon/16/101.png"))); // Red X
+ parent.indexOfComponent(breakPanel), getScaledIcon("16/101.png")); // Red X
} else {
parent.setIconAt(
parent.indexOfComponent(breakPanel),
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource(
- "/resource/icon/16/101grey.png"))); // Grey X
+ getScaledIcon("16/101grey.png")); // Grey X
}
if (parent instanceof TabbedPanel2) {
// If possible lock the tab while it is active so it cant be closed
@@ -263,9 +267,8 @@ public class BreakPanelToolbarFactory {
ZapToggleButton btnBreakRequest;
btnBreakRequest = new ZapToggleButton(breakRequestsButtonAction);
- btnBreakRequest.setSelectedIcon(
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource("/resource/icon/16/105r.png")));
+ btnBreakRequest.setSelectedIcon(getScaledIcon("16/105r.png"));
+
btnBreakRequest.setSelectedToolTipText(
Constant.messages.getString("brk.toolbar.button.request.unset"));
@@ -276,9 +279,8 @@ public class BreakPanelToolbarFactory {
ZapToggleButton btnBreakResponse;
btnBreakResponse = new ZapToggleButton(breakResponsesButtonAction);
- btnBreakResponse.setSelectedIcon(
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource("/resource/icon/16/106r.png")));
+ btnBreakResponse.setSelectedIcon(getScaledIcon("16/106r.png"));
+
btnBreakResponse.setSelectedToolTipText(
Constant.messages.getString("brk.toolbar.button.response.unset"));
@@ -289,9 +291,8 @@ public class BreakPanelToolbarFactory {
ZapToggleButton btnBreakAll;
btnBreakAll = new ZapToggleButton(breakAllButtonAction);
- btnBreakAll.setSelectedIcon(
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource("/resource/icon/16/151.png")));
+ btnBreakAll.setSelectedIcon(getScaledIcon("16/151.png"));
+
btnBreakAll.setSelectedToolTipText(
Constant.messages.getString("brk.toolbar.button.all.unset"));
@@ -302,10 +303,7 @@ public class BreakPanelToolbarFactory {
ZapToggleButton btnBreakOnJavaScript;
btnBreakOnJavaScript = new ZapToggleButton(setBreakOnJavaScriptAction);
- btnBreakOnJavaScript.setSelectedIcon(
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource(
- "/resource/icon/breakTypes/javascriptNotBreaking.png")));
+ btnBreakOnJavaScript.setSelectedIcon(getScaledIcon("breakTypes/javascriptNotBreaking.png"));
btnBreakOnJavaScript.setSelectedToolTipText(
Constant.messages.getString("brk.toolbar.button.brkjavascript.set"));
@@ -317,9 +315,7 @@ public class BreakPanelToolbarFactory {
btnBreakOnCssAndFonts = new ZapToggleButton(setBreakOnCssAndFontsAction);
btnBreakOnCssAndFonts.setSelectedIcon(
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource(
- "/resource/icon/breakTypes/cssAndFontsNotBreaking.png")));
+ getScaledIcon("breakTypes/cssAndFontsNotBreaking.png"));
btnBreakOnCssAndFonts.setSelectedToolTipText(
Constant.messages.getString("brk.toolbar.button.brkcssfonts.set"));
@@ -330,10 +326,7 @@ public class BreakPanelToolbarFactory {
ZapToggleButton btnBreakOnMultimedia;
btnBreakOnMultimedia = new ZapToggleButton(setBreakOnMultimediaAction);
- btnBreakOnMultimedia.setSelectedIcon(
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource(
- "/resource/icon/breakTypes/multimediaNotBreaking.png")));
+ btnBreakOnMultimedia.setSelectedIcon(getScaledIcon("breakTypes/multimediaNotBreaking.png"));
btnBreakOnMultimedia.setSelectedToolTipText(
Constant.messages.getString("brk.toolbar.button.brkmultimedia.set"));
@@ -344,10 +337,8 @@ public class BreakPanelToolbarFactory {
ZapToggleButton btnOnlyBreakOnScope;
btnOnlyBreakOnScope = new ZapToggleButton(setOnlyBreakOnScopeAction);
- btnOnlyBreakOnScope.setSelectedIcon(
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource(
- "/resource/icon/fugue/target.png")));
+ btnOnlyBreakOnScope.setSelectedIcon(getScaledIcon("fugue/target.png"));
+
btnOnlyBreakOnScope.setSelectedToolTipText(
Constant.messages.getString("brk.toolbar.button.brkOnlyOnScope.unset"));
@@ -630,11 +621,8 @@ public class BreakPanelToolbarFactory {
private static final long serialVersionUID = 1L;
public ContinueButtonAction() {
- super(
- null,
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource(
- "/resource/icon/16/131.png")));
+ super(null, getScaledIcon("16/131.png"));
+
putValue(
Action.SHORT_DESCRIPTION,
Constant.messages.getString("brk.toolbar.button.cont"));
@@ -660,11 +648,8 @@ public class BreakPanelToolbarFactory {
private static final long serialVersionUID = 1L;
public StepButtonAction() {
- super(
- null,
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource(
- "/resource/icon/16/143.png")));
+ super(null, getScaledIcon("16/143.png"));
+
putValue(
Action.SHORT_DESCRIPTION,
Constant.messages.getString("brk.toolbar.button.step"));
@@ -694,11 +679,8 @@ public class BreakPanelToolbarFactory {
private static final long serialVersionUID = 1L;
public DropButtonAction() {
- super(
- null,
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource(
- "/resource/icon/16/150.png")));
+ super(null, getScaledIcon("16/150.png"));
+
putValue(
Action.SHORT_DESCRIPTION,
Constant.messages.getString("brk.toolbar.button.bin"));
@@ -717,11 +699,8 @@ public class BreakPanelToolbarFactory {
private static final long serialVersionUID = 1L;
public AddBreakpointButtonAction() {
- super(
- null,
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource(
- "/resource/icon/16/break_add.png")));
+ super(null, getScaledIcon("16/break_add.png"));
+
putValue(
Action.SHORT_DESCRIPTION,
Constant.messages.getString("brk.toolbar.button.brkpoint"));
@@ -738,11 +717,8 @@ public class BreakPanelToolbarFactory {
private static final long serialVersionUID = 1L;
public BreakRequestsButtonAction() {
- super(
- null,
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource(
- "/resource/icon/16/105.png")));
+ super(null, getScaledIcon("16/105.png"));
+
putValue(
Action.SHORT_DESCRIPTION,
Constant.messages.getString("brk.toolbar.button.request.set"));
@@ -759,11 +735,8 @@ public class BreakPanelToolbarFactory {
private static final long serialVersionUID = 1L;
public BreakResponsesButtonAction() {
- super(
- null,
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource(
- "/resource/icon/16/106.png")));
+ super(null, getScaledIcon("16/106.png"));
+
putValue(
Action.SHORT_DESCRIPTION,
Constant.messages.getString("brk.toolbar.button.response.set"));
@@ -780,11 +753,8 @@ public class BreakPanelToolbarFactory {
private static final long serialVersionUID = 1L;
public BreakAllButtonAction() {
- super(
- null,
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource(
- "/resource/icon/16/152.png")));
+ super(null, getScaledIcon("16/152.png"));
+
putValue(
Action.SHORT_DESCRIPTION,
Constant.messages.getString("brk.toolbar.button.all.set"));
@@ -801,11 +771,8 @@ public class BreakPanelToolbarFactory {
private static final long serialVersionUID = 1L;
public SetBreakOnJavaScriptAction() {
- super(
- null,
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource(
- "/resource/icon/breakTypes/javascript.png")));
+ super(null, getScaledIcon("breakTypes/javascript.png"));
+
putValue(
Action.SHORT_DESCRIPTION,
Constant.messages.getString("brk.toolbar.button.brkjavascript.unset"));
@@ -822,11 +789,8 @@ public class BreakPanelToolbarFactory {
private static final long serialVersionUID = 1L;
public SetBreakOnCssAndFontsAction() {
- super(
- null,
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource(
- "/resource/icon/breakTypes/cssAndFonts.png")));
+ super(null, getScaledIcon("breakTypes/cssAndFonts.png"));
+
putValue(
Action.SHORT_DESCRIPTION,
Constant.messages.getString("brk.toolbar.button.brkcssfonts.unset"));
@@ -843,11 +807,8 @@ public class BreakPanelToolbarFactory {
private static final long serialVersionUID = 1L;
public SetBreakOnMultimediaAction() {
- super(
- null,
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource(
- "/resource/icon/breakTypes/multimedia.png")));
+ super(null, getScaledIcon("breakTypes/multimedia.png"));
+
putValue(
Action.SHORT_DESCRIPTION,
Constant.messages.getString("brk.toolbar.button.brkmultimedia.unset"));
@@ -864,11 +825,8 @@ public class BreakPanelToolbarFactory {
private static final long serialVersionUID = 1L;
public SetBreakOnlyOnScopeAction() {
- super(
- null,
- new ImageIcon(
- BreakPanelToolbarFactory.class.getResource(
- "/resource/icon/fugue/target-grey.png")));
+ super(null, getScaledIcon("fugue/target-grey.png"));
+
putValue(
Action.SHORT_DESCRIPTION,
Constant.messages.getString("brk.toolbar.button.brkOnlyOnScope.set"));
diff --git a/zap/src/main/java/org/zaproxy/zap/view/AboutPanel.java b/zap/src/main/java/org/zaproxy/zap/view/AboutPanel.java
index 6909ae6f4..a10e80fd7 100644
--- a/zap/src/main/java/org/zaproxy/zap/view/AboutPanel.java
+++ b/zap/src/main/java/org/zaproxy/zap/view/AboutPanel.java
@@ -20,7 +20,6 @@
package org.zaproxy.zap.view;
import java.awt.Color;
-import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
@@ -31,6 +30,7 @@ import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import org.parosproxy.paros.Constant;
+import org.zaproxy.zap.utils.DisplayUtils;
import org.zaproxy.zap.utils.FontUtils;
public class AboutPanel extends JPanel {
@@ -80,7 +80,7 @@ public class AboutPanel extends JPanel {
GridBagConstraints gbcLogo = new GridBagConstraints();
Color backgroundColor = new Color(UIManager.getColor("TextField.background").getRGB());
- this.setPreferredSize(new Dimension(420, 460));
+ this.setPreferredSize(DisplayUtils.getScaledDimension(420, 460));
this.setBackground(backgroundColor);
this.setBorder(BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));
| ['zap/src/main/java/org/parosproxy/paros/view/AbstractParamContainerPanel.java', 'zap/src/main/java/org/parosproxy/paros/view/OptionsDialog.java', 'zap/src/main/java/org/zaproxy/zap/extension/brk/BreakPanelToolbarFactory.java', 'zap/src/main/java/org/parosproxy/paros/extension/manualrequest/ManualRequestEditorDialog.java', 'zap/src/main/java/org/zaproxy/zap/extension/ascan/PolicyDialog.java', 'zap/src/main/java/org/zaproxy/zap/extension/ascan/PolicyManagerDialog.java', 'zap/src/main/java/org/zaproxy/zap/view/AboutPanel.java'] | {'.java': 7} | 7 | 7 | 0 | 0 | 7 | 9,934,259 | 1,981,372 | 271,448 | 1,167 | 7,636 | 1,306 | 158 | 7 | 719 | 128 | 179 | 17 | 0 | 1 | 2022-06-08T14:24:00 | 11,102 | Java | {'Java': 12002133, 'HTML': 3977629, 'Python': 158050, 'Kotlin': 54286, 'JavaScript': 9640, 'Shell': 8430, 'Lex': 5179, 'Perl': 3832, 'XSLT': 3054} | Apache License 2.0 |
617 | zaproxy/zaproxy/7172/7171 | zaproxy | zaproxy | https://github.com/zaproxy/zaproxy/issues/7171 | https://github.com/zaproxy/zaproxy/pull/7172 | https://github.com/zaproxy/zaproxy/pull/7172 | 1 | closes | Loss of new line chars for GZIP HTTP responses returned by the API | ### Describe the bug
When the content encoding of a message response is gzip the method `httpMessageToSet` of `ApiResponseConversionUtils.java` reads the unzipped content line by line and forgets to add the new line chars to the string is going to add to the ApiResponseConversionUtils. The code where this happen is:
```java
if (HttpHeader.GZIP.equals(
msg.getResponseHeader().getHeader(HttpHeader.CONTENT_ENCODING))) {
// Uncompress gziped content
try (ByteArrayInputStream bais =
new ByteArrayInputStream(msg.getResponseBody().getBytes());
GZIPInputStream gis = new GZIPInputStream(bais);
InputStreamReader isr = new InputStreamReader(gis);
BufferedReader br = new BufferedReader(isr); ) {
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
map.put("responseBody", sb.toString());
} catch (IOException e) {
LOGGER.error("Unable to uncompress gzip content: " + e.getMessage(), e);
map.put("responseBody", msg.getResponseBody().toString());
}
} else {
map.put("responseBody", msg.getResponseBody().toString());
}
```
### Steps to reproduce the behavior
1. Make a request to a server that responds with gzip encoding using the ZAP API ( `/JSON/core/action/accessUrl/`)
2. On the API request result check if the response has new line chars.
### Expected behavior
The response should have new line characters.
### Software versions
The main branch
### Screenshots
_No response_
### Errors from the zap.log file
_No response_
### Additional context
_No response_
### Would you like to help fix this issue?
- [X] Yes | b7ffac8758ace6fa20405166acce9c6ff278823a | 7d4fea927446505cd572abf087461863dc6012ae | https://github.com/zaproxy/zaproxy/compare/b7ffac8758ace6fa20405166acce9c6ff278823a...7d4fea927446505cd572abf087461863dc6012ae | diff --git a/zap/src/main/java/org/zaproxy/zap/extension/api/ApiResponseConversionUtils.java b/zap/src/main/java/org/zaproxy/zap/extension/api/ApiResponseConversionUtils.java
index 8a92d3441..1d22fde75 100644
--- a/zap/src/main/java/org/zaproxy/zap/extension/api/ApiResponseConversionUtils.java
+++ b/zap/src/main/java/org/zaproxy/zap/extension/api/ApiResponseConversionUtils.java
@@ -19,16 +19,11 @@
*/
package org.zaproxy.zap.extension.api;
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-import java.util.zip.GZIPInputStream;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@@ -37,7 +32,6 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.parosproxy.paros.db.DatabaseException;
import org.parosproxy.paros.model.HistoryReference;
-import org.parosproxy.paros.network.HttpHeader;
import org.parosproxy.paros.network.HttpMessage;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
@@ -89,28 +83,7 @@ public final class ApiResponseConversionUtils {
map.put("requestHeader", msg.getRequestHeader().toString());
map.put("requestBody", msg.getRequestBody().toString());
map.put("responseHeader", msg.getResponseHeader().toString());
-
- if (HttpHeader.GZIP.equals(
- msg.getResponseHeader().getHeader(HttpHeader.CONTENT_ENCODING))) {
- // Uncompress gziped content
- try (ByteArrayInputStream bais =
- new ByteArrayInputStream(msg.getResponseBody().getBytes());
- GZIPInputStream gis = new GZIPInputStream(bais);
- InputStreamReader isr = new InputStreamReader(gis);
- BufferedReader br = new BufferedReader(isr); ) {
- StringBuilder sb = new StringBuilder();
- String line = null;
- while ((line = br.readLine()) != null) {
- sb.append(line);
- }
- map.put("responseBody", sb.toString());
- } catch (IOException e) {
- LOGGER.error("Unable to uncompress gzip content: " + e.getMessage(), e);
- map.put("responseBody", msg.getResponseBody().toString());
- }
- } else {
- map.put("responseBody", msg.getResponseBody().toString());
- }
+ map.put("responseBody", msg.getResponseBody().toString());
List<String> tags = Collections.emptyList();
try {
diff --git a/zap/src/test/java/org/zaproxy/zap/extension/api/ApiResponseConversionUtilsUnitTest.java b/zap/src/test/java/org/zaproxy/zap/extension/api/ApiResponseConversionUtilsUnitTest.java
index 15720ad90..d194ecfc1 100644
--- a/zap/src/test/java/org/zaproxy/zap/extension/api/ApiResponseConversionUtilsUnitTest.java
+++ b/zap/src/test/java/org/zaproxy/zap/extension/api/ApiResponseConversionUtilsUnitTest.java
@@ -24,14 +24,11 @@ import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
import static org.mockito.BDDMockito.given;
-import java.io.ByteArrayOutputStream;
-import java.util.zip.GZIPOutputStream;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
-import org.parosproxy.paros.network.HttpHeader;
import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.network.HttpRequestHeader;
import org.parosproxy.paros.network.HttpResponseHeader;
@@ -112,32 +109,4 @@ class ApiResponseConversionUtilsUnitTest {
assertThat(response.getValues(), hasEntry("timestamp", "1010101010101"));
assertThat(response.getValues(), hasEntry("rtt", "200"));
}
-
- @Test
- void compressedResponseBodyShouldBeDeflatedIntoApiResponse() throws Exception {
- given(responseHeader.getHeader(HttpHeader.CONTENT_ENCODING)).willReturn(HttpHeader.GZIP);
- given(responseBody.getBytes()).willReturn(gzip(new byte[] {97, 98, 99}));
-
- ApiResponseSet<String> response = ApiResponseConversionUtils.httpMessageToSet(0, message);
-
- assertThat(response.getValues(), hasEntry("responseBody", "abc"));
- }
-
- @Test
- void brokenCompressedResponseBodyShouldBeStoredAsStringRepresentationInApiResponse() {
- given(responseHeader.getHeader(HttpHeader.CONTENT_ENCODING)).willReturn(HttpHeader.GZIP);
- given(responseBody.getBytes()).willReturn(new byte[] {0, 0, 0});
-
- ApiResponseSet<String> response = ApiResponseConversionUtils.httpMessageToSet(0, message);
-
- assertThat(response.getValues(), hasEntry("responseBody", responseBody.toString()));
- }
-
- private static byte[] gzip(byte[] raw) throws Exception {
- ByteArrayOutputStream bytes = new ByteArrayOutputStream(raw.length);
- try (GZIPOutputStream zip = new GZIPOutputStream(bytes)) {
- zip.write(raw);
- }
- return bytes.toByteArray();
- }
} | ['zap/src/main/java/org/zaproxy/zap/extension/api/ApiResponseConversionUtils.java', 'zap/src/test/java/org/zaproxy/zap/extension/api/ApiResponseConversionUtilsUnitTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 9,909,785 | 1,974,179 | 270,521 | 1,159 | 1,389 | 235 | 29 | 1 | 1,934 | 209 | 366 | 56 | 0 | 1 | 2022-03-28T13:20:38 | 11,102 | Java | {'Java': 12002133, 'HTML': 3977629, 'Python': 158050, 'Kotlin': 54286, 'JavaScript': 9640, 'Shell': 8430, 'Lex': 5179, 'Perl': 3832, 'XSLT': 3054} | Apache License 2.0 |
613 | zaproxy/zaproxy/7402/7400 | zaproxy | zaproxy | https://github.com/zaproxy/zaproxy/issues/7400 | https://github.com/zaproxy/zaproxy/pull/7402 | https://github.com/zaproxy/zaproxy/pull/7402 | 1 | fix | ascan disableAllScanners API endpoint no longer disabled all scanners | ### Describe the bug
As of ZAP `w2022-03-07`, using the API endpoint `ascan/action/disableAllScanners/` with a policy file no longer disabled scanners that are identified in that policy file as enabled.
### Steps to reproduce the behavior
The issue is best demonstrated using the following scripts.
Create a file named `test.py`
```py
import time
from subprocess import Popen
from zapv2 import ZAPv2 as ZAP
def print_totals(json):
totals = {
'enabled': 0,
'disabled': 0,
}
for scanner in json['scanners']:
if scanner['enabled'] == 'true':
totals['enabled'] = totals['enabled'] + 1
else:
totals['disabled'] = totals['disabled'] + 1
print(totals)
port = '42248'
settings = [
'/zap/zap.sh', '-daemon',
'-config', 'network.localServers.mainProxy.address=0.0.0.0',
'-config', f'network.localServers.mainProxy.port={port}',
'-dir', '/home/zap',
'-config', 'api.disablekey=true',
'-config', 'api.addrs.addr.name=.*',
'-config', 'api.addrs.addr.regex=true',
'-silent'
]
connection_details = {'http': f'http://127.0.0.1:{port}', 'https': f'http://127.0.0.1:{port}'}
p = Popen(settings)
print('sleeping...')
time.sleep(10)
print('done')
print('ZAP should be running')
zap = ZAP(proxies=connection_details)
policy_name = 'API-Minimal'
url = zap.base + 'ascan/view/scanners'
before_response = zap._request(url, {'scanPolicyName': policy_name, 'apikey': ''})
print_totals(before_response)
zap.ascan.disable_all_scanners(policy_name)
after_response = zap._request(url, {'scanPolicyName': policy_name, 'apikey': ''})
print_totals(after_response)
```
create a bash script `run.sh` with the contents
```sh
#!/bin/bash
docker run -d -it --name zap-test owasp/zap2docker-weekly:w2022-07-25
docker cp test.py zap-test:/zap
docker exec -it zap-test mkdir /home/zap/policies
docker exec -it zap-test cp /home/zap/.ZAP_D/policies/API-Minimal.policy /home/zap/policies
docker exec -it zap-test python /zap/test.py
docker kill zap-test
```
Make the script executable, `chmod 755 run.sh`
Run the script.
The script will
- start the ZAP docker container
- copy the test python script to it
- move the API policy to the expected policy location
- run the python script (which will...)
- start ZAP
- query the API to get all the scanners for the API policy, then count the number of enabled and disabled scanner
- call ascan `disabledAllScanners` with the API policy
- query the API to get all the scanners for the API policy, then count the number of enabled and disabled scanner
- kill the container
The output I've experienced is:
```
{'enabled': 25, 'disabled': 36}
{'enabled': 16, 'disabled': 45}
```
### Expected behavior
All the scanners for the policy should be disabled. On versions of ZAP before `w2022-03-07`, the output of the above script is:
```
{'enabled': 25, 'disabled': 36}
{'enabled': 0, 'disabled': 61}
```
### Software versions
since w2022-03-07
### Screenshots
_No response_
### Errors from the zap.log file
_No response_
### Additional context
_No response_
### Would you like to help fix this issue?
- [ ] Yes | a207070b8de1a83d8e6877032a31554656ce832b | 221e88ca440b140487e30b438b7eefe99ea3efe1 | https://github.com/zaproxy/zaproxy/compare/a207070b8de1a83d8e6877032a31554656ce832b...221e88ca440b140487e30b438b7eefe99ea3efe1 | diff --git a/zap/src/main/java/org/parosproxy/paros/core/scanner/AbstractPlugin.java b/zap/src/main/java/org/parosproxy/paros/core/scanner/AbstractPlugin.java
index 0e0741764..919c11653 100644
--- a/zap/src/main/java/org/parosproxy/paros/core/scanner/AbstractPlugin.java
+++ b/zap/src/main/java/org/parosproxy/paros/core/scanner/AbstractPlugin.java
@@ -71,6 +71,7 @@
// ZAP: 2020/11/26 Use Log4j2 getLogger() and deprecate Log4j1.x.
// ZAP: 2021/07/20 Correct message updated with the scan rule ID header (Issue 6689).
// ZAP: 2022/06/05 Remove usage of HttpException.
+// ZAP: 2022/08/03 Keep enabled state when setting default alert threshold (Issue 7400).
package org.parosproxy.paros.core.scanner;
import java.io.IOException;
@@ -831,8 +832,13 @@ public abstract class AbstractPlugin implements Plugin, Comparable<Object> {
@Override
public void setDefaultAlertThreshold(AlertThreshold level) {
+ AlertThreshold oldDefaultAlertThreshold = defaultAttackThreshold;
this.defaultAttackThreshold = level;
- setEnabledFromLevel();
+ if ((defaultAttackThreshold == AlertThreshold.OFF
+ || oldDefaultAlertThreshold == AlertThreshold.OFF)
+ && getAlertThreshold(true) == AlertThreshold.DEFAULT) {
+ setEnabled(defaultAttackThreshold != AlertThreshold.OFF);
+ }
}
private void setEnabledFromLevel() {
diff --git a/zap/src/test/java/org/parosproxy/paros/core/scanner/AbstractPluginUnitTest.java b/zap/src/test/java/org/parosproxy/paros/core/scanner/AbstractPluginUnitTest.java
index cfe2992ef..9668845ad 100644
--- a/zap/src/test/java/org/parosproxy/paros/core/scanner/AbstractPluginUnitTest.java
+++ b/zap/src/test/java/org/parosproxy/paros/core/scanner/AbstractPluginUnitTest.java
@@ -26,6 +26,7 @@ import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.params.provider.Arguments.arguments;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
@@ -35,12 +36,15 @@ import static org.mockito.Mockito.when;
import java.io.IOException;
import java.security.InvalidParameterException;
+import java.util.stream.Stream;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.httpclient.URI;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import org.parosproxy.paros.Constant;
@@ -214,6 +218,25 @@ class AbstractPluginUnitTest extends PluginTestUtils {
assertThat(plugin.isEnabled(), is(equalTo(Boolean.FALSE)));
}
+ private static Stream<Arguments> alertThresholdsAndEnabledState() {
+ return Stream.of(AlertThreshold.values())
+ .flatMap(e -> Stream.of(arguments(e, true), arguments(e, false)));
+ }
+
+ @ParameterizedTest
+ @MethodSource("alertThresholdsAndEnabledState")
+ void shouldNotChangeEnabledStateIfNotUsingDefaultThresholdWhenDefaultSet(
+ AlertThreshold defaultThreshold, boolean enabled) {
+ // Given
+ AbstractPlugin plugin = createAbstractPluginWithConfig();
+ plugin.setAlertThreshold(AlertThreshold.MEDIUM);
+ plugin.setEnabled(enabled);
+ // When
+ plugin.setDefaultAlertThreshold(defaultThreshold);
+ // Then
+ assertThat(plugin.isEnabled(), is(equalTo(enabled)));
+ }
+
@Test
void shouldBeDisabledWhenOffAndDefaultOffThresholdSet() {
// Given
@@ -239,6 +262,21 @@ class AbstractPluginUnitTest extends PluginTestUtils {
assertThat(plugin.isEnabled(), is(equalTo(Boolean.TRUE)));
}
+ @ParameterizedTest
+ @EnumSource(
+ value = AlertThreshold.class,
+ names = {"LOW", "MEDIUM", "HIGH"})
+ void shouldBeReEnabledWhenDefaultThresholdSetFromOff(AlertThreshold threshold) {
+ // Given
+ AbstractPlugin plugin = createAbstractPluginWithConfig();
+ plugin.setAlertThreshold(AlertThreshold.DEFAULT);
+ plugin.setDefaultAlertThreshold(AlertThreshold.OFF);
+ // When
+ plugin.setDefaultAlertThreshold(threshold);
+ // Then
+ assertThat(plugin.isEnabled(), is(equalTo(Boolean.TRUE)));
+ }
+
@Test
void shouldFailWhenSettingEnabledStateWithoutConfig() {
// Given | ['zap/src/test/java/org/parosproxy/paros/core/scanner/AbstractPluginUnitTest.java', 'zap/src/main/java/org/parosproxy/paros/core/scanner/AbstractPlugin.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 9,945,402 | 1,983,625 | 271,711 | 1,167 | 486 | 94 | 8 | 1 | 3,227 | 392 | 852 | 125 | 2 | 4 | 2022-08-03T13:53:24 | 11,102 | Java | {'Java': 12002133, 'HTML': 3977629, 'Python': 158050, 'Kotlin': 54286, 'JavaScript': 9640, 'Shell': 8430, 'Lex': 5179, 'Perl': 3832, 'XSLT': 3054} | Apache License 2.0 |
612 | zaproxy/zaproxy/7494/7484 | zaproxy | zaproxy | https://github.com/zaproxy/zaproxy/issues/7484 | https://github.com/zaproxy/zaproxy/pull/7494 | https://github.com/zaproxy/zaproxy/pull/7494 | 1 | fix | Using the Active Scan for GET targets sends a 'Content-Length' header | When using the Active Scan for a GET target Zap sends the header 'Content-Length: 0' in the requests.
This should not happen and can prevent scanning some servers which do reject the 'Content-Length: 0' header in GET requests.
Reproduction:
Install Python
Start Python http server: `python -m http.server 7777`
Start Zap GUI, proxy at 8080, turn off HUD
Make a request using curl: `curl --proxy http://localhost:8080 http://localhost:7777`
See the request in Zap history
Right click the request in Zap history, select "Open/Resend in request editor"
See that no "content-length" header is present
Right click the request again, select "Attack->Active Scan"
Check the requests in the Active Scan tab
See that all the request have the header `Content-Length: 0`
The requests in the attack should not have the "Content-Length" header as some systems reject GET requests with it.
Zap version used: 2.11.1 | 680d0024afbef18339c7acfe3b64b9861e73de51 | 3ba3cc92f6a127349eecf54f4e8928a3bf9efbc4 | https://github.com/zaproxy/zaproxy/compare/680d0024afbef18339c7acfe3b64b9861e73de51...3ba3cc92f6a127349eecf54f4e8928a3bf9efbc4 | diff --git a/zap/src/main/java/org/parosproxy/paros/core/scanner/AbstractPlugin.java b/zap/src/main/java/org/parosproxy/paros/core/scanner/AbstractPlugin.java
index 963f38c27..57e306581 100644
--- a/zap/src/main/java/org/parosproxy/paros/core/scanner/AbstractPlugin.java
+++ b/zap/src/main/java/org/parosproxy/paros/core/scanner/AbstractPlugin.java
@@ -74,6 +74,7 @@
// ZAP: 2022/06/05 Remove usage of HttpException.
// ZAP: 2022/08/03 Keep enabled state when setting default alert threshold (Issue 7400).
// ZAP: 2022/09/08 Use format specifiers instead of concatenation when logging.
+// ZAP: 2022/09/28 Do not set the Content-Length header when the method does not require one.
package org.parosproxy.paros.core.scanner;
import java.io.IOException;
@@ -95,6 +96,7 @@ import org.parosproxy.paros.core.scanner.Alert.Source;
import org.parosproxy.paros.model.HistoryReference;
import org.parosproxy.paros.network.HttpHeader;
import org.parosproxy.paros.network.HttpMessage;
+import org.parosproxy.paros.network.HttpRequestHeader;
import org.parosproxy.paros.network.HttpStatusCode;
import org.zaproxy.zap.control.AddOn;
import org.zaproxy.zap.extension.anticsrf.ExtensionAntiCSRF;
@@ -297,7 +299,8 @@ public abstract class AbstractPlugin implements Plugin, Comparable<Object> {
// always get the fresh copy
message.getRequestHeader().setHeader(HttpHeader.IF_MODIFIED_SINCE, null);
message.getRequestHeader().setHeader(HttpHeader.IF_NONE_MATCH, null);
- message.getRequestHeader().setContentLength(message.getRequestBody().length());
+
+ updateRequestContentLength(message);
if (this.getDelayInMs() > 0) {
try {
@@ -323,6 +326,30 @@ public abstract class AbstractPlugin implements Plugin, Comparable<Object> {
parent.performScannerHookAfterScan(message, this);
}
+ /**
+ * Updates the Content-Length header of the request.
+ *
+ * <p>For methods with absent or unanticipated enclosed content, the header is removed otherwise
+ * in all other cases the header is updated to match the length of the content.
+ *
+ * @param message the message to update.
+ * @since 2.12.0
+ */
+ protected void updateRequestContentLength(HttpMessage message) {
+ int bodyLength = message.getRequestBody().length();
+ String method = message.getRequestHeader().getMethod();
+ if (bodyLength == 0
+ && (HttpRequestHeader.GET.equalsIgnoreCase(method)
+ || HttpRequestHeader.CONNECT.equalsIgnoreCase(method)
+ || HttpRequestHeader.DELETE.equalsIgnoreCase(method)
+ || HttpRequestHeader.HEAD.equalsIgnoreCase(method)
+ || HttpRequestHeader.TRACE.equalsIgnoreCase(method))) {
+ message.getRequestHeader().setHeader(HttpHeader.CONTENT_LENGTH, null);
+ return;
+ }
+ message.getRequestHeader().setContentLength(bodyLength);
+ }
+
@Override
public void run() {
// ZAP : set skipped to false otherwise the plugin should stop continuously
diff --git a/zap/src/test/java/org/parosproxy/paros/core/scanner/AbstractPluginUnitTest.java b/zap/src/test/java/org/parosproxy/paros/core/scanner/AbstractPluginUnitTest.java
index c5b3a6fa2..c108385c0 100644
--- a/zap/src/test/java/org/parosproxy/paros/core/scanner/AbstractPluginUnitTest.java
+++ b/zap/src/test/java/org/parosproxy/paros/core/scanner/AbstractPluginUnitTest.java
@@ -36,6 +36,8 @@ import static org.mockito.Mockito.when;
import java.io.IOException;
import java.security.InvalidParameterException;
+import java.util.Arrays;
+import java.util.List;
import java.util.stream.Stream;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.httpclient.URI;
@@ -50,6 +52,7 @@ import org.mockito.ArgumentCaptor;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.core.scanner.Plugin.AlertThreshold;
import org.parosproxy.paros.network.HttpHeader;
+import org.parosproxy.paros.network.HttpMalformedHeaderException;
import org.parosproxy.paros.network.HttpMessage;
import org.parosproxy.paros.network.HttpRequestHeader;
import org.parosproxy.paros.network.HttpSender;
@@ -63,6 +66,19 @@ import org.zaproxy.zap.utils.ZapXmlConfiguration;
/** Unit test for {@link AbstractPlugin}. */
class AbstractPluginUnitTest extends PluginTestUtils {
+ private static final List<String> METHODS_NO_ENCLOSED_CONTENT =
+ Arrays.asList(
+ HttpRequestHeader.CONNECT,
+ "connect",
+ HttpRequestHeader.DELETE,
+ "delete",
+ HttpRequestHeader.GET,
+ "get",
+ HttpRequestHeader.HEAD,
+ "head",
+ HttpRequestHeader.TRACE,
+ "trace");
+
HostProcess parent;
HttpMessage message;
Analyser analyser;
@@ -2073,6 +2089,95 @@ class AbstractPluginUnitTest extends PluginTestUtils {
assertThat(message.getRequestHeader().getHeader(HttpHeader.X_ZAP_SCAN_ID), is(nullValue()));
}
+ @ParameterizedTest
+ @MethodSource("methodsNoEnclosedContent")
+ void shouldNotAddContentLenthHeaderWhenNotExpected(String method) {
+ // Given
+ HttpMessage message = messageWithMethod(method);
+ // When
+ plugin.updateRequestContentLength(message);
+ // Then
+ assertContentLength(message.getRequestHeader(), null);
+ }
+
+ @ParameterizedTest
+ @MethodSource("methodsNoEnclosedContent")
+ void shouldRemoveExistingContentLengthHeaderWhenNotExpectedNorNeeded(String method) {
+ // Given
+ HttpMessage message = messageWithMethod(method);
+ message.getRequestHeader().setContentLength(1234);
+ // When
+ plugin.updateRequestContentLength(message);
+ // Then
+ assertContentLength(message.getRequestHeader(), null);
+ }
+
+ @ParameterizedTest
+ @MethodSource("allMethods")
+ void shouldAddContentLengthHeaderWhenNeeded(String method) {
+ // Given
+ HttpMessage message = messageWithMethod(method);
+ message.setRequestBody("1234");
+ // When
+ plugin.updateRequestContentLength(message);
+ // Then
+ assertContentLength(message.getRequestHeader(), "4");
+ }
+
+ @ParameterizedTest
+ @MethodSource("allMethodsExceptNoEnclosedContent")
+ void shouldAddZeroContentLengthHeaderWhenNeeded(String method) {
+ // Given
+ HttpMessage message = messageWithMethod(method);
+ // When
+ plugin.updateRequestContentLength(message);
+ // Then
+ assertContentLength(message.getRequestHeader(), "0");
+ }
+
+ @ParameterizedTest
+ @MethodSource("allMethods")
+ void shouldUpdateExistingContentLengthHeaderWhenNeeded(String method) {
+ // Given
+ HttpMessage message = messageWithMethod(method);
+ message.setRequestBody("1234");
+ message.getRequestHeader().setContentLength(42);
+ // When
+ plugin.updateRequestContentLength(message);
+ // Then
+ assertContentLength(message.getRequestHeader(), "4");
+ }
+
+ private static void assertContentLength(HttpHeader header, String value) {
+ assertThat(header.getHeader(HttpHeader.CONTENT_LENGTH), is(equalTo(value)));
+ }
+
+ private static HttpMessage messageWithMethod(String method) {
+ try {
+ String header =
+ method
+ + (HttpRequestHeader.CONNECT.equalsIgnoreCase(method)
+ ? " example.com "
+ : " / ")
+ + "HTTP/1.1";
+ return new HttpMessage(new HttpRequestHeader(header));
+ } catch (HttpMalformedHeaderException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private static Stream<String> allMethods() {
+ return Stream.of(HttpRequestHeader.METHODS);
+ }
+
+ private static Stream<String> methodsNoEnclosedContent() {
+ return METHODS_NO_ENCLOSED_CONTENT.stream();
+ }
+
+ private static Stream<String> allMethodsExceptNoEnclosedContent() {
+ return allMethods().filter(e -> !METHODS_NO_ENCLOSED_CONTENT.contains(e));
+ }
+
private static HttpMessage createAlertMessage() {
return createAlertMessage(null);
} | ['zap/src/test/java/org/parosproxy/paros/core/scanner/AbstractPluginUnitTest.java', 'zap/src/main/java/org/parosproxy/paros/core/scanner/AbstractPlugin.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 9,989,471 | 1,993,309 | 272,919 | 1,169 | 1,432 | 256 | 29 | 1 | 922 | 141 | 216 | 19 | 2 | 0 | 2022-09-28T20:39:04 | 11,102 | Java | {'Java': 12002133, 'HTML': 3977629, 'Python': 158050, 'Kotlin': 54286, 'JavaScript': 9640, 'Shell': 8430, 'Lex': 5179, 'Perl': 3832, 'XSLT': 3054} | Apache License 2.0 |
628 | zaproxy/zaproxy/6414/6381 | zaproxy | zaproxy | https://github.com/zaproxy/zaproxy/issues/6381 | https://github.com/zaproxy/zaproxy/pull/6414 | https://github.com/zaproxy/zaproxy/pull/6414 | 1 | fix | Proxy script return value misinterpreted in 2.10.0 | **Describe the bug**
Hi,
Not sure if it's related to the version, but since the update to 2.10.0, I have this issue.
If I enable a proxy script, I have the error "Secure Connection Failed" in the browser when I try to connect to any url.
- it was working fine before the update (not 100% sure when it start to fail)
- I'm using dynamic SSL certificates, and SSL is working fine if I use proxy without any script enabled
- I tested with Jython and Zest script, even with basic provided templates (so it's not related to the script himself)
- I tried to regenerate SSL certs, but doesn't help.
- no error in logs
From the browser side, it looks like the SSL is not validated when script is enabled.
Any advice to solve this issue ?
Thanks
**To Reproduce**
Steps to reproduce the behavior:
1. Setup dynamic SSL certificates and browser proxy to connect through zap
2. Create new proxy script (jython or zest) and choose any default template
3. Enable the script
4. Connect to any url from browser
**Expected behavior**
Connection should be done and the script should be executed.
**Software versions**
- ZAP: 2.10.0
- Browser: Tried with Firefox & Chrome
- OS : Kali linux
**Errors from the zap.log file**
No error in zap log.
**Would you like to help fix this issue?**
sure | d2f71edb5b5333cfb0058cfaf06cfdab65598fb4 | 6b31da4c3ebdeee08c496c5ea95ee857d2300e82 | https://github.com/zaproxy/zaproxy/compare/d2f71edb5b5333cfb0058cfaf06cfdab65598fb4...6b31da4c3ebdeee08c496c5ea95ee857d2300e82 | diff --git a/zap/src/main/java/org/zaproxy/zap/extension/script/ProxyListenerScript.java b/zap/src/main/java/org/zaproxy/zap/extension/script/ProxyListenerScript.java
index 2d5bb8e1c..1a66066ed 100644
--- a/zap/src/main/java/org/zaproxy/zap/extension/script/ProxyListenerScript.java
+++ b/zap/src/main/java/org/zaproxy/zap/extension/script/ProxyListenerScript.java
@@ -65,9 +65,9 @@ public class ProxyListenerScript implements ProxyListener {
for (CachedScript<ProxyScript> cachedScript : scripts.getCachedScripts()) {
ProxyScript script = cachedScript.getScript();
try {
- boolean dropMessage =
+ boolean forwardMessage =
request ? script.proxyRequest(msg) : script.proxyResponse(msg);
- if (dropMessage) {
+ if (!forwardMessage) {
return false;
}
} catch (Exception e) {
diff --git a/zap/src/test/java/org/zaproxy/zap/extension/script/ProxyListenerScriptUnitTest.java b/zap/src/test/java/org/zaproxy/zap/extension/script/ProxyListenerScriptUnitTest.java
index c1c8b0930..0ecbc285c 100644
--- a/zap/src/test/java/org/zaproxy/zap/extension/script/ProxyListenerScriptUnitTest.java
+++ b/zap/src/test/java/org/zaproxy/zap/extension/script/ProxyListenerScriptUnitTest.java
@@ -99,7 +99,7 @@ class ProxyListenerScriptUnitTest extends WithConfigsTest {
@SuppressWarnings("unchecked")
void shouldRefreshScriptsAndCallOnHttpRequestSend() throws Exception {
// Given
- ProxyScript script = mock(TARGET_INTERFACE);
+ ProxyScript script = mockProxyScript();
CachedScript<ProxyScript> cachedScript = createCachedScript(script);
ScriptsCache<ProxyScript> scriptsCache = createScriptsCache(cachedScript);
given(extensionScript.<ProxyScript>createScriptsCache(any())).willReturn(scriptsCache);
@@ -117,7 +117,7 @@ class ProxyListenerScriptUnitTest extends WithConfigsTest {
@SuppressWarnings("unchecked")
void shouldHandleExceptionsThrownByScriptsOnHttpRequestSend() throws Exception {
// Given
- ProxyScript script = mock(TARGET_INTERFACE);
+ ProxyScript script = mockProxyScript();
Exception exception = mock(ScriptException.class);
given(script.proxyRequest(any())).willThrow(exception);
ScriptWrapper scriptWrapper = mock(ScriptWrapper.class);
@@ -136,10 +136,10 @@ class ProxyListenerScriptUnitTest extends WithConfigsTest {
@SuppressWarnings("unchecked")
void shouldDropMessageOnHttpRequestSend() throws Exception {
// Given
- ProxyScript script1 = mock(TARGET_INTERFACE);
- given(script1.proxyRequest(any())).willReturn(true);
+ ProxyScript script1 = mockProxyScript();
+ given(script1.proxyRequest(any())).willReturn(false);
CachedScript<ProxyScript> cachedScript1 = createCachedScript(script1);
- ProxyScript script2 = mock(TARGET_INTERFACE);
+ ProxyScript script2 = mockProxyScript();
CachedScript<ProxyScript> cachedScript2 = createCachedScript(script2);
ScriptsCache<ProxyScript> scriptsCache = createScriptsCache(cachedScript1, cachedScript2);
given(extensionScript.<ProxyScript>createScriptsCache(any())).willReturn(scriptsCache);
@@ -156,7 +156,7 @@ class ProxyListenerScriptUnitTest extends WithConfigsTest {
@SuppressWarnings("unchecked")
void shouldCallOnHttpResponseReceive() throws Exception {
// Given
- ProxyScript script = mock(TARGET_INTERFACE);
+ ProxyScript script = mockProxyScript();
CachedScript<ProxyScript> cachedScript = createCachedScript(script);
ScriptsCache<ProxyScript> scriptsCache = createScriptsCache(cachedScript);
given(extensionScript.<ProxyScript>createScriptsCache(any())).willReturn(scriptsCache);
@@ -174,7 +174,7 @@ class ProxyListenerScriptUnitTest extends WithConfigsTest {
@SuppressWarnings("unchecked")
void shouldHandleExceptionsThrownByScriptsOnHttpResponseReceive() throws Exception {
// Given
- ProxyScript script = mock(TARGET_INTERFACE);
+ ProxyScript script = mockProxyScript();
Exception exception = mock(ScriptException.class);
given(script.proxyResponse(any())).willThrow(exception);
ScriptWrapper scriptWrapper = mock(ScriptWrapper.class);
@@ -193,10 +193,10 @@ class ProxyListenerScriptUnitTest extends WithConfigsTest {
@SuppressWarnings("unchecked")
void shouldDropMessageOnHttpResponseReceive() throws Exception {
// Given
- ProxyScript script1 = mock(TARGET_INTERFACE);
- given(script1.proxyResponse(any())).willReturn(true);
+ ProxyScript script1 = mockProxyScript();
+ given(script1.proxyResponse(any())).willReturn(false);
CachedScript<ProxyScript> cachedScript1 = createCachedScript(script1);
- ProxyScript script2 = mock(TARGET_INTERFACE);
+ ProxyScript script2 = mockProxyScript();
CachedScript<ProxyScript> cachedScript2 = createCachedScript(script2);
ScriptsCache<ProxyScript> scriptsCache = createScriptsCache(cachedScript1, cachedScript2);
given(extensionScript.<ProxyScript>createScriptsCache(any())).willReturn(scriptsCache);
@@ -209,6 +209,13 @@ class ProxyListenerScriptUnitTest extends WithConfigsTest {
verify(script2, times(0)).proxyResponse(message);
}
+ private static ProxyScript mockProxyScript() throws ScriptException {
+ ProxyScript script = mock(TARGET_INTERFACE, withSettings().lenient());
+ given(script.proxyRequest(any())).willReturn(true);
+ given(script.proxyResponse(any())).willReturn(true);
+ return script;
+ }
+
private static <T> CachedScript<T> createCachedScript(T script) {
return createCachedScript(script, null);
} | ['zap/src/test/java/org/zaproxy/zap/extension/script/ProxyListenerScriptUnitTest.java', 'zap/src/main/java/org/zaproxy/zap/extension/script/ProxyListenerScript.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 10,102,330 | 2,020,210 | 275,718 | 1,175 | 156 | 24 | 4 | 1 | 1,321 | 232 | 309 | 37 | 0 | 0 | 2021-01-21T17:28:21 | 11,102 | Java | {'Java': 12002133, 'HTML': 3977629, 'Python': 158050, 'Kotlin': 54286, 'JavaScript': 9640, 'Shell': 8430, 'Lex': 5179, 'Perl': 3832, 'XSLT': 3054} | Apache License 2.0 |
630 | zaproxy/zaproxy/6009/6008 | zaproxy | zaproxy | https://github.com/zaproxy/zaproxy/issues/6008 | https://github.com/zaproxy/zaproxy/pull/6009 | https://github.com/zaproxy/zaproxy/pull/6009 | 1 | fix | Initialization of scripts via ZAP API | **Describe the bug**
When trying to enable scripts(httpsender, selenium...) via the REST API , the target script does not get enabled. Testing via a local desktop client using the API produces the same result as it does when using a Docker image with your custom ZAP scripts + config.xml imported. When using a local desktop instance API I see the same activity there with selenium or httpsender scripts not being enabled UNLESS i click on the + to show the scripts tab next to the "Sites" tab. Then i can enable it via the REST API.
**To Reproduce**
Steps to reproduce the behavior:
1. Spin up a local desktop instance of ZAP
2. Config the REST API to allow access and control
3. Be sure to have a Selenium, Httpsender, ... script available within ZAP gui
3. Use a API client to GET http://zap/JSON/script/action/enable/?scriptName=targetScript
4. You should receive a `Result: "OK"`
5. Now navigate back to ZAP Gui and click the "+" Tab next to the "Sites" tab and select "Scripts"
6. You should now be able to confirm the targetScript was not enabled.
7. Now that we have the scripts tab showing, Send the request again to enable the script. You will get the same `Result: "OK"` response but this time the **script will indeed be enabled.**
8. **The "Scripts" tab must be enabled for control of the script via REST API. This creates issues when trying to drive your scan from the REST API alone.**
**Expected behavior**
Script is enabled without any actions within the GUI
**Software versions**
- ZAP: 2.9.0
- OS: Windows 10, Windows server 2016, Docker images FROM Focal Fossa (Ubuntu 20.04 LTS)
| edd1f3371a361e7f56ad6242fc7a9b995270d0cc | 42bfe40f3b1177631542dfff016628bdd77821ce | https://github.com/zaproxy/zaproxy/compare/edd1f3371a361e7f56ad6242fc7a9b995270d0cc...42bfe40f3b1177631542dfff016628bdd77821ce | diff --git a/zap/src/main/java/org/zaproxy/zap/extension/script/ExtensionScript.java b/zap/src/main/java/org/zaproxy/zap/extension/script/ExtensionScript.java
index 03f7cb44e..24c6b7874 100644
--- a/zap/src/main/java/org/zaproxy/zap/extension/script/ExtensionScript.java
+++ b/zap/src/main/java/org/zaproxy/zap/extension/script/ExtensionScript.java
@@ -464,6 +464,20 @@ public class ExtensionScript extends ExtensionAdaptor implements CommandLineList
}
public ScriptEngineWrapper getEngineWrapper(String name) {
+ ScriptEngineWrapper sew = getEngineWrapperImpl(name);
+ if (sew == null) {
+ throw new InvalidParameterException("No such engine: " + name);
+ }
+ return sew;
+ }
+
+ /**
+ * Gets the script engine with the given name.
+ *
+ * @param name the name of the script engine.
+ * @return the engine, or {@code null} if not available.
+ */
+ private ScriptEngineWrapper getEngineWrapperImpl(String name) {
for (ScriptEngineWrapper sew : this.engineWrappers) {
if (isSameScriptEngine(name, sew.getEngineName(), sew.getLanguageName())) {
return sew;
@@ -484,7 +498,7 @@ public class ExtensionScript extends ExtensionAdaptor implements CommandLineList
this.registerScriptEngineWrapper(dew);
return dew;
}
- throw new InvalidParameterException("No such engine: " + name);
+ return null;
}
public String getEngineNameForExtension(String ext) {
@@ -684,6 +698,7 @@ public class ExtensionScript extends ExtensionAdaptor implements CommandLineList
if (script == null) {
return null;
}
+ setEngine(script);
ScriptNode node = this.getTreeModel().addScript(script);
for (ScriptEventListener listener : this.listeners) {
@@ -1328,9 +1343,30 @@ public class ExtensionScript extends ExtensionAdaptor implements CommandLineList
// may well not have been registered at that stage
script.setType(this.getScriptType(script.getTypeName()));
}
+ setEngine(script);
return script;
}
+ /**
+ * Sets the engine script to the given script, if not already set.
+ *
+ * <p>Scripts loaded from the configuration file might not have the engine set when used.
+ *
+ * <p>Does nothing if the engine script is not available.
+ *
+ * @param script the script to set the engine.
+ */
+ private void setEngine(ScriptWrapper script) {
+ if (script.getEngine() != null) {
+ return;
+ }
+ ScriptEngineWrapper sew = getEngineWrapperImpl(script.getEngineName());
+ if (sew == null) {
+ return;
+ }
+ script.setEngine(sew);
+ }
+
public List<ScriptWrapper> getScripts(String type) {
return this.getScripts(this.getScriptType(type));
}
@@ -1416,10 +1452,7 @@ public class ExtensionScript extends ExtensionAdaptor implements CommandLineList
* @see ScriptEventListener#preInvoke(ScriptWrapper)
*/
private void preInvokeScript(ScriptWrapper script) throws ScriptException {
- if (script.getEngine() == null) {
- // Scripts loaded from the configs my have loaded before all of the engines
- script.setEngine(this.getEngineWrapper(script.getEngineName()));
- }
+ setEngine(script);
if (script.getEngine() == null) {
throw new ScriptException("Failed to find script engine: " + script.getEngineName());
diff --git a/zap/src/main/java/org/zaproxy/zap/extension/script/ScriptAPI.java b/zap/src/main/java/org/zaproxy/zap/extension/script/ScriptAPI.java
index 9db403640..0fe8a2719 100644
--- a/zap/src/main/java/org/zaproxy/zap/extension/script/ScriptAPI.java
+++ b/zap/src/main/java/org/zaproxy/zap/extension/script/ScriptAPI.java
@@ -291,6 +291,12 @@ public class ScriptAPI extends ApiImplementor {
throw new ApiException(
ApiException.Type.ILLEGAL_PARAMETER, ACTION_PARAM_SCRIPT_NAME);
}
+ if (script.getEngine() == null) {
+ throw new ApiException(
+ ApiException.Type.BAD_STATE,
+ "Unable to enable the script, script engine not available: "
+ + script.getEngineName());
+ }
extension.setEnabled(script, true);
return ApiResponseElement.OK;
| ['zap/src/main/java/org/zaproxy/zap/extension/script/ScriptAPI.java', 'zap/src/main/java/org/zaproxy/zap/extension/script/ExtensionScript.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 9,816,276 | 1,965,046 | 268,391 | 1,152 | 1,803 | 363 | 49 | 2 | 1,633 | 278 | 385 | 25 | 1 | 0 | 2020-05-26T15:39:45 | 11,102 | Java | {'Java': 12002133, 'HTML': 3977629, 'Python': 158050, 'Kotlin': 54286, 'JavaScript': 9640, 'Shell': 8430, 'Lex': 5179, 'Perl': 3832, 'XSLT': 3054} | Apache License 2.0 |
629 | zaproxy/zaproxy/6268/6267 | zaproxy | zaproxy | https://github.com/zaproxy/zaproxy/issues/6267 | https://github.com/zaproxy/zaproxy/pull/6268 | https://github.com/zaproxy/zaproxy/pull/6268 | 1 | fixes | HTML / Markdown Report Generation Fails When Path Contains '#' | **Describe the bug**
HTML / Markdown Report Generation fails when the file name or path contains a '#'. XML and JSON reports are generated as expected.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to 'Report'
2. Click on 'Generate HTML Report' or 'Generate Markdown Report'
3. Save the file with a '#' in it's name or path.
4. See error
**Expected behavior**
The report is generated without a problem.
**Software versions**
- ZAP: 2.9.0
- OS: Windows 10, Linux
- Java: openjdk version "11.0.8 2020-07-14"
**Additional context**
Discussed on IRC.
**Would you like to help fix this issue?**
Yes. | c7372d2d432fb3484fa5210ffcd67f08942c3974 | 4c2dc4c392041de7760ac9c17dee290a6ba47db1 | https://github.com/zaproxy/zaproxy/compare/c7372d2d432fb3484fa5210ffcd67f08942c3974...4c2dc4c392041de7760ac9c17dee290a6ba47db1 | diff --git a/zap/src/main/java/org/parosproxy/paros/extension/report/ReportGenerator.java b/zap/src/main/java/org/parosproxy/paros/extension/report/ReportGenerator.java
index 4665605ff..55d433280 100644
--- a/zap/src/main/java/org/parosproxy/paros/extension/report/ReportGenerator.java
+++ b/zap/src/main/java/org/parosproxy/paros/extension/report/ReportGenerator.java
@@ -31,6 +31,7 @@ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// ZAP: 2019/06/01 Normalise line endings.
// ZAP: 2019/06/05 Normalise format/style.
// ZAP: 2020/08/06 Issue 6084: Added date time to html report.
+// ZAP: 2020/10/29 Issue 6267: Fix bug to allow writing reports with file path containing '#'.
package org.parosproxy.paros.extension.report;
import java.io.BufferedReader;
@@ -92,7 +93,7 @@ public class ReportGenerator {
Transformer transformer = tFactory.newTransformer(stylesource);
// Make the transformation and write to the output file
- StreamResult result = new StreamResult(outFile);
+ StreamResult result = new StreamResult(outFile.getPath());
transformer.transform(source, result);
} catch (TransformerException e) {
@@ -132,7 +133,7 @@ public class ReportGenerator {
transformer.setParameter("datetime", getCurrentDateTimeString());
DOMSource source = new DOMSource(doc);
- StreamResult result = new StreamResult(outfile);
+ StreamResult result = new StreamResult(outfile.getPath());
transformer.transform(source, result);
} catch (TransformerException
@@ -311,7 +312,7 @@ public class ReportGenerator {
transformer.setParameter("datetime", getCurrentDateTimeString());
DOMSource source = new DOMSource(doc);
- StreamResult result = new StreamResult(outfile);
+ StreamResult result = new StreamResult(outfile.getPath());
transformer.transform(source, result);
} catch (TransformerException
diff --git a/zap/src/test/java/org/parosproxy/paros/extension/report/ReportGeneratorUnitTest.java b/zap/src/test/java/org/parosproxy/paros/extension/report/ReportGeneratorUnitTest.java
index 82da211b8..3a59b4cea 100644
--- a/zap/src/test/java/org/parosproxy/paros/extension/report/ReportGeneratorUnitTest.java
+++ b/zap/src/test/java/org/parosproxy/paros/extension/report/ReportGeneratorUnitTest.java
@@ -71,6 +71,18 @@ public class ReportGeneratorUnitTest extends TestUtils {
assertThat(contents(report), is(equalTo("")));
}
+ @Test
+ public void shouldWriteReportWhenPathContainsHashSymbol(@TempDir Path tempDir)
+ throws Exception {
+ // Given
+ String data = "<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?><data>ZAP</data>" + NEWLINE;
+ Path report = Files.createTempFile(tempDir, "#", "");
+ // When
+ ReportGenerator.stringToHtml(data, identityXsl(), report.toString());
+ // Then
+ assertThat(contents(report), is(equalTo(data)));
+ }
+
@Test
public void shouldUseEmptyArrayForSitesInJsonReportIfNoSitePresent() {
// Given | ['zap/src/test/java/org/parosproxy/paros/extension/report/ReportGeneratorUnitTest.java', 'zap/src/main/java/org/parosproxy/paros/extension/report/ReportGenerator.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 9,945,230 | 1,990,846 | 271,922 | 1,165 | 505 | 93 | 7 | 1 | 634 | 101 | 161 | 23 | 0 | 0 | 2020-10-29T12:19:42 | 11,102 | Java | {'Java': 12002133, 'HTML': 3977629, 'Python': 158050, 'Kotlin': 54286, 'JavaScript': 9640, 'Shell': 8430, 'Lex': 5179, 'Perl': 3832, 'XSLT': 3054} | Apache License 2.0 |
626 | zaproxy/zaproxy/6438/6437 | zaproxy | zaproxy | https://github.com/zaproxy/zaproxy/issues/6437 | https://github.com/zaproxy/zaproxy/pull/6438 | https://github.com/zaproxy/zaproxy/pull/6438 | 1 | fix | Unable to set only breaks on message in scope | Welcome. While "mark" set only breaks on message in scope box click OK and back to settings, this is unmark again (while trying few others, looks like works fine). No error in zap, but in log file
```
2021-02-03 14:17:00,393 [AWT-EventQueue-0] INFO SSLConnector - ClientCert disabled
2021-02-03 14:17:00,709 [AWT-EventQueue-0] ERROR ExtensionQuickStartHud - object is not an instance of declaring class
java.lang.IllegalArgumentException: object is not an instance of declaring class
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:?]
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:?]
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:?]
at java.lang.reflect.Method.invoke(Method.java:566) ~[?:?]
at org.zaproxy.zap.extension.quickstart.hud.ExtensionQuickStartHud.isInScopeOnly(ExtensionQuickStartHud.java:98) [quickstart-release-29.zap:?]
at org.zaproxy.zap.extension.quickstart.launch.LaunchPanel.setHudIsInScopeOnlyText(LaunchPanel.java:228) [quickstart-release-29.zap:?]
at org.zaproxy.zap.extension.quickstart.launch.LaunchPanel.optionsChanged(LaunchPanel.java:396) [quickstart-release-29.zap:?]
at org.zaproxy.zap.extension.quickstart.launch.ExtensionQuickStartLaunch.optionsChanged(ExtensionQuickStartLaunch.java:158) [quickstart-release-29.zap:?]
at org.parosproxy.paros.extension.ExtensionLoader.optionsChangedAllPlugin(ExtensionLoader.java:535) [zap-2.10.0.jar:2.10.0]
at org.parosproxy.paros.control.MenuToolsControl.options(MenuToolsControl.java:84) [zap-2.10.0.jar:2.10.0]
at org.parosproxy.paros.control.MenuToolsControl.options(MenuToolsControl.java:64) [zap-2.10.0.jar:2.10.0]
at org.parosproxy.paros.view.MainMenuBar$3.actionPerformed(MainMenuBar.java:240) [zap-2.10.0.jar:2.10.0]
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967) [?:?]
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308) [?:?]
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405) [?:?]
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262) [?:?]
at javax.swing.AbstractButton.doClick(AbstractButton.java:369) [?:?]
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1020) [?:?]
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1064) [?:?]
at java.awt.Component.processMouseEvent(Component.java:6635) [?:?]
at javax.swing.JComponent.processMouseEvent(JComponent.java:3342) [?:?]
at java.awt.Component.processEvent(Component.java:6400) [?:?]
at java.awt.Container.processEvent(Container.java:2263) [?:?]
at java.awt.Component.dispatchEventImpl(Component.java:5011) [?:?]
at java.awt.Container.dispatchEventImpl(Container.java:2321) [?:?]
at java.awt.Component.dispatchEvent(Component.java:4843) [?:?]
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4918) [?:?]
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4547) [?:?]
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4488) [?:?]
at java.awt.Container.dispatchEventImpl(Container.java:2307) [?:?]
at java.awt.Window.dispatchEventImpl(Window.java:2772) [?:?]
at java.awt.Component.dispatchEvent(Component.java:4843) [?:?]
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772) [?:?]
at java.awt.EventQueue$4.run(EventQueue.java:721) [?:?]
at java.awt.EventQueue$4.run(EventQueue.java:715) [?:?]
at java.security.AccessController.doPrivileged(Native Method) ~[?:?]
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85) [?:?]
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95) [?:?]
at java.awt.EventQueue$5.run(EventQueue.java:745) [?:?]
at java.awt.EventQueue$5.run(EventQueue.java:743) [?:?]
at java.security.AccessController.doPrivileged(Native Method) ~[?:?]
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85) [?:?]
at java.awt.EventQueue.dispatchEvent(EventQueue.java:742) [?:?]
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203) [?:?]
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124) [?:?]
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113) [?:?]
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109) [?:?]
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) [?:?]
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90) [?:?]
```
while run zap fron console i get `org.parosproxy.paros.network.SSLConnector - ClientCert disabled`
Im also trying to set it true in config file, but zap back it to false. Before in zap 2.9 it works correct, but that version don work for me anymore
Im using latest Linux mint and have java is:
```
openjdk version "11.0.9.1" 2020-11-04
OpenJDK Runtime Environment (build 11.0.9.1+1-Ubuntu-0ubuntu1.20.04)
OpenJDK 64-Bit Server VM (build 11.0.9.1+1-Ubuntu-0ubuntu1.20.04, mixed mode)
``` | 82aa3940b1b1cc6a2b65c1a2f9f3701afa01d593 | 0fa18d3b73913408e8167b942c6eb6a11c733f84 | https://github.com/zaproxy/zaproxy/compare/82aa3940b1b1cc6a2b65c1a2f9f3701afa01d593...0fa18d3b73913408e8167b942c6eb6a11c733f84 | diff --git a/zap/src/main/java/org/zaproxy/zap/extension/brk/BreakPanelToolbarFactory.java b/zap/src/main/java/org/zaproxy/zap/extension/brk/BreakPanelToolbarFactory.java
index 5a5628aeb..f518f8ce9 100644
--- a/zap/src/main/java/org/zaproxy/zap/extension/brk/BreakPanelToolbarFactory.java
+++ b/zap/src/main/java/org/zaproxy/zap/extension/brk/BreakPanelToolbarFactory.java
@@ -536,10 +536,7 @@ public class BreakPanelToolbarFactory {
isBreakRequest = false;
isBreakResponse = false;
isBreakAll = false;
- setBreakOnJavaScript(true);
- setBreakOnCssAndFonts(true);
- setBreakOnMultimedia(true);
- setOnlyBreakOnScope(breakpointsParams.isInScopeOnly());
+ setShowIgnoreFilesButtons(false);
countCaughtMessages = 0;
}
@@ -604,7 +601,7 @@ public class BreakPanelToolbarFactory {
setBreakOnJavaScript(true);
setBreakOnCssAndFonts(true);
setBreakOnMultimedia(true);
- setOnlyBreakOnScope(false);
+ setOnlyBreakOnScope(breakpointsParams.isInScopeOnly());
}
}
| ['zap/src/main/java/org/zaproxy/zap/extension/brk/BreakPanelToolbarFactory.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,969,694 | 1,988,686 | 272,318 | 1,168 | 329 | 69 | 7 | 1 | 5,237 | 290 | 1,372 | 66 | 0 | 2 | 2021-02-04T15:53:45 | 11,102 | Java | {'Java': 12002133, 'HTML': 3977629, 'Python': 158050, 'Kotlin': 54286, 'JavaScript': 9640, 'Shell': 8430, 'Lex': 5179, 'Perl': 3832, 'XSLT': 3054} | Apache License 2.0 |
623 | zaproxy/zaproxy/6564/6520 | zaproxy | zaproxy | https://github.com/zaproxy/zaproxy/issues/6520 | https://github.com/zaproxy/zaproxy/pull/6564 | https://github.com/zaproxy/zaproxy/pull/6564 | 1 | fix | Can not scroll past 'contexts' in 'sites' tab with FlatLaf L&F | **Describe the bug**
Can not use mouse wheel to scroll past 'Context' in 'Sites' tab.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to 'Sites'
2. Browse around a bunch with the proxy on so the Sites populate
3. Scroll to the top of the list with both sites and contexts expanded
4. Use mouse wheel to scroll down
**Expected behavior**
The list scrolls normally to the bottom.
**Observed behavior**
The scrolling stops at the end of Contexts. Neither can you use arrow keys to go down from the bottom most entry in contexts.
However dragging the scrollbar manually with the mouse past that point allows normal scrolling. Just not when any context is in view.
**Screenshots**
N/A
**Software versions**
- ZAP: 2.10
- Add-on: N/A
- OS: Ubuntu 20.04 (5.4.0-70-generic, amd64)
- Java: openjdk 11.0.10 2021-01-19
- Browser: N/A
**Errors from the zap.log file**
None
**Additional context**
None
**Would you like to help fix this issue?**
I don't do java. | ee2cae59b583003617cfcede524fd7044e6fcecb | 55cbb9b38b6c8b90b40a4b9b5690ac15669a4b60 | https://github.com/zaproxy/zaproxy/compare/ee2cae59b583003617cfcede524fd7044e6fcecb...55cbb9b38b6c8b90b40a4b9b5690ac15669a4b60 | diff --git a/zap/src/main/java/org/zaproxy/zap/view/ContextsSitesPanel.java b/zap/src/main/java/org/zaproxy/zap/view/ContextsSitesPanel.java
index 228d29780..3d901a09f 100644
--- a/zap/src/main/java/org/zaproxy/zap/view/ContextsSitesPanel.java
+++ b/zap/src/main/java/org/zaproxy/zap/view/ContextsSitesPanel.java
@@ -110,7 +110,12 @@ public class ContextsSitesPanel extends JPanel {
public int getScrollableUnitIncrement(
Rectangle visibleRect, int orientation, int direction) {
if (visibleRect.getY() < sitesTree.getBounds().getY()) {
- return contextsTree.getScrollableUnitIncrement(visibleRect, orientation, direction);
+ int unitIncrement =
+ contextsTree.getScrollableUnitIncrement(
+ visibleRect, orientation, direction);
+ if (unitIncrement != 0) {
+ return unitIncrement;
+ }
}
return sitesTree.getScrollableUnitIncrement(visibleRect, orientation, direction);
} | ['zap/src/main/java/org/zaproxy/zap/view/ContextsSitesPanel.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,972,864 | 1,989,177 | 272,315 | 1,168 | 380 | 55 | 7 | 1 | 1,003 | 162 | 254 | 35 | 0 | 0 | 2021-04-24T18:28:55 | 11,102 | Java | {'Java': 12002133, 'HTML': 3977629, 'Python': 158050, 'Kotlin': 54286, 'JavaScript': 9640, 'Shell': 8430, 'Lex': 5179, 'Perl': 3832, 'XSLT': 3054} | Apache License 2.0 |
625 | zaproxy/zaproxy/6464/6427 | zaproxy | zaproxy | https://github.com/zaproxy/zaproxy/issues/6427 | https://github.com/zaproxy/zaproxy/pull/6464 | https://github.com/zaproxy/zaproxy/pull/6464 | 1 | fixes | Manual Request Editor CONNECT Http Method Broken | I'm not sure what CONNECT is even for, but when you switch a request that works to CONNECT, it eats all of the URL except for the protocol like so:
CONNECT https HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0
Pragma: no-cache
Cache-Control: no-cache
Content-Length: 78
Accept: text/html
Content-Type: application/x-www-form-urlencoded
Host: localhost:8443
And then when you hit SEND, you get this error:
1186267 [Thread-15] ERROR org.parosproxy.paros.extension.manualrequest.http.impl.HttpPanelSender - host parameter is null
java.lang.IllegalArgumentException: host parameter is null
at org.apache.commons.httpclient.HttpConnection.<init>(HttpConnection.java:220) ~[zap-D-2021-01-20.jar:?]
at org.apache.commons.httpclient.HttpConnection.<init>(HttpConnection.java:168) ~[zap-D-2021-01-20.jar:?]
at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionWithReference.<init>(MultiThreadedHttpConnectionManager.java:1145) ~[commons-httpclient-3.1.jar:?]
at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$ConnectionPool.createConnection(MultiThreadedHttpConnectionManager.java:762) ~[commons-httpclient-3.1.jar:?]
at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.doGetConnection(MultiThreadedHttpConnectionManager.java:476) ~[commons-httpclient-3.1.jar:?]
at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager.getConnectionWithTimeout(MultiThreadedHttpConnectionManager.java:416) ~[commons-httpclient-3.1.jar:?]
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:189) ~[zap-D-2021-01-20.jar:?]
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) ~[commons-httpclient-3.1.jar:?]
at org.parosproxy.paros.network.HttpSender.executeMethod(HttpSender.java:429) ~[zap-D-2021-01-20.jar:D-2021-01-20]
at org.parosproxy.paros.network.HttpSender.runMethod(HttpSender.java:671) ~[zap-D-2021-01-20.jar:D-2021-01-20]
at org.parosproxy.paros.network.HttpSender.send(HttpSender.java:626) ~[zap-D-2021-01-20.jar:D-2021-01-20]
at org.parosproxy.paros.network.HttpSender.sendAuthenticated(HttpSender.java:601) ~[zap-D-2021-01-20.jar:D-2021-01-20]
at org.parosproxy.paros.network.HttpSender.sendAndReceiveImpl(HttpSender.java:1033) ~[zap-D-2021-01-20.jar:D-2021-01-20]
at org.parosproxy.paros.network.HttpSender.sendAndReceive(HttpSender.java:993) ~[zap-D-2021-01-20.jar:D-2021-01-20]
at org.parosproxy.paros.extension.manualrequest.http.impl.HttpPanelSender.handleSendMessage(HttpPanelSender.java:120) [zap-D-2021-01-20.jar:D-2021-01-20]
at org.parosproxy.paros.extension.manualrequest.ManualRequestEditorDialog$2.run(ManualRequestEditorDialog.java:239) [zap-D-2021-01-20.jar:D-2021-01-20]
at java.lang.Thread.run(Thread.java:834) [?:?]
(And I also notice the Response pane doesn't change when there was an error.) Seems like if you hit SEND, it should first clear out the response pane, then try to SEND, and if successful, show the response, and if not, maybe display some kind of error message?
And if you 'accidentally' select CONNECT, and then switch to another HTTP Method, the rest of the URL is still lost, so the manual request is now broken until you close it, find the original request in the history, and reopen it from that request, which is annoying. (Maybe you should have a 'restore original request' button? Although I realize we are somewhat out of room for new buttons.)
So, please fix CONNECT, or drop it if it's not a useful HTTP method to test.
| 4763d82951023685f06f79df80299806e4aad6b2 | d5f32d6ff5ba9f7cf61161f602367d4fdaa11696 | https://github.com/zaproxy/zaproxy/compare/4763d82951023685f06f79df80299806e4aad6b2...d5f32d6ff5ba9f7cf61161f602367d4fdaa11696 | diff --git a/zap/src/main/java/org/parosproxy/paros/network/HttpMessage.java b/zap/src/main/java/org/parosproxy/paros/network/HttpMessage.java
index 771bec347..0f5e49d60 100644
--- a/zap/src/main/java/org/parosproxy/paros/network/HttpMessage.java
+++ b/zap/src/main/java/org/parosproxy/paros/network/HttpMessage.java
@@ -58,6 +58,7 @@
// ZAP: 2020/11/26 Use Log4j 2 classes for logging.
// ZAP: 2020/12/09 Handle content encodings in request/response bodies.
// ZAP: 2021/04/01 Detect WebSocket upgrade messages having multiple Connection directives
+// ZAP: 2021/05/11 Fixed conversion of Request Method to/from CONNECT
package org.parosproxy.paros.network;
import java.net.HttpCookie;
@@ -980,15 +981,11 @@ public class HttpMessage implements Message {
}
public void mutateHttpMethod(String method) {
- // String header = reqPanel.getTxtHeader().getText();
- String header = getRequestHeader().toString();
try {
- HttpRequestHeader hrh = new HttpRequestHeader(header);
-
- URI uri = hrh.getURI();
- // String body = reqPanel.getTxtBody().getText();
+ URI uri = getRequestHeader().getURI();
String body = getRequestBody().toString();
- String prevMethod = hrh.getMethod();
+ String prevMethod = getRequestHeader().getMethod();
+
if (prevMethod.equalsIgnoreCase(method)) {
return;
}
@@ -1016,7 +1013,6 @@ public class HttpMessage implements Message {
}
uri.setQuery(sb.toString());
}
- hrh.setURI(uri);
// Clear the body
body = "";
@@ -1040,12 +1036,28 @@ public class HttpMessage implements Message {
}
body = sb.toString();
uri.setQuery(null);
- hrh.setURI(uri);
}
}
- hrh.setMethod(method);
-
- getRequestHeader().setMessage(hrh.toString());
+ if (prevMethod.equalsIgnoreCase(HttpRequestHeader.CONNECT)) {
+ String scheme;
+ if (getRequestHeader().getHostPort() == 443) {
+ scheme = "https://";
+ } else {
+ scheme = "http://";
+ }
+ uri = new URI(scheme + uri, true);
+ } else if (method.equals(HttpRequestHeader.CONNECT)) {
+ uri = URI.fromAuthority(uri.getAuthority());
+ }
+ getRequestHeader()
+ .setMessage(
+ method
+ + " "
+ + uri
+ + " "
+ + getRequestHeader().getVersion()
+ + "\\r\\n"
+ + getRequestHeader().getHeadersAsString());
getRequestBody().setBody(body);
} catch (HttpMalformedHeaderException e) {
// Ignore?
diff --git a/zap/src/test/java/org/parosproxy/paros/network/HttpMessageUnitTest.java b/zap/src/test/java/org/parosproxy/paros/network/HttpMessageUnitTest.java
index acf998bee..1c7fd5f17 100644
--- a/zap/src/test/java/org/parosproxy/paros/network/HttpMessageUnitTest.java
+++ b/zap/src/test/java/org/parosproxy/paros/network/HttpMessageUnitTest.java
@@ -200,6 +200,62 @@ public class HttpMessageUnitTest {
assertThat(copy.isResponseFromTargetHost(), is(equalTo(false)));
}
+ @Test
+ public void shouldCorrectlyMutateFromConnectHttpMethodWhenGenericPort() throws Exception {
+ // Given
+ HttpMessage message =
+ new HttpMessage(
+ new HttpRequestHeader(
+ "CONNECT "
+ + "www.example.com:9000 HTTP/1.1\\r\\nHost: www.example.com:9000"));
+ // When
+ message.mutateHttpMethod(HttpRequestHeader.GET);
+ // Then
+ assertThat(message.getRequestHeader().getMethod(), is(HttpRequestHeader.GET));
+ assertThat(
+ message.getRequestHeader().getURI().toString(), is("http://www.example.com:9000"));
+ assertThat(
+ message.getRequestHeader().getHeader(HttpRequestHeader.HOST),
+ is("www.example.com:9000"));
+ }
+
+ @Test
+ public void shouldCorrectlyMutateFromConnectHttpMethodWhenHttpsPort() throws Exception {
+ // Given
+ HttpMessage message =
+ new HttpMessage(
+ new HttpRequestHeader(
+ "CONNECT "
+ + "www.example.com:443 HTTP/1.1\\r\\nHost: www.example.com:443"));
+ // When
+ message.mutateHttpMethod(HttpRequestHeader.GET);
+ // Then
+ assertThat(message.getRequestHeader().getMethod(), is(HttpRequestHeader.GET));
+ assertThat(
+ message.getRequestHeader().getURI().toString(), is("https://www.example.com:443"));
+ assertThat(
+ message.getRequestHeader().getHeader(HttpRequestHeader.HOST),
+ is("www.example.com:443"));
+ }
+
+ @Test
+ public void shouldCorrectlyMutateToConnectHttpMethod() throws Exception {
+ // Given
+ HttpMessage message =
+ new HttpMessage(
+ new HttpRequestHeader(
+ "GET "
+ + "http://www.example.com:9000/path HTTP/1.1\\r\\nHost: www.example.com:9000"));
+ // When
+ message.mutateHttpMethod(HttpRequestHeader.CONNECT);
+ // Then
+ assertThat(message.getRequestHeader().getMethod(), is(HttpRequestHeader.CONNECT));
+ assertThat(message.getRequestHeader().getURI().toString(), is("www.example.com:9000"));
+ assertThat(
+ message.getRequestHeader().getHeader(HttpRequestHeader.HOST),
+ is("www.example.com:9000"));
+ }
+
@Test
void shouldNotSetContentEncodingsWhenSettingHttpRequestBody() {
// Given | ['zap/src/main/java/org/parosproxy/paros/network/HttpMessage.java', 'zap/src/test/java/org/parosproxy/paros/network/HttpMessageUnitTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 9,984,803 | 1,991,652 | 272,693 | 1,172 | 1,623 | 268 | 36 | 1 | 3,596 | 262 | 955 | 38 | 0 | 0 | 2021-02-24T08:12:09 | 11,102 | Java | {'Java': 12002133, 'HTML': 3977629, 'Python': 158050, 'Kotlin': 54286, 'JavaScript': 9640, 'Shell': 8430, 'Lex': 5179, 'Perl': 3832, 'XSLT': 3054} | Apache License 2.0 |
624 | zaproxy/zaproxy/6492/4671 | zaproxy | zaproxy | https://github.com/zaproxy/zaproxy/issues/4671 | https://github.com/zaproxy/zaproxy/pull/6492 | https://github.com/zaproxy/zaproxy/pull/6492 | 1 | fix | Tag changes in Search tab not reflected in History tab | **Describe the bug**
Managing message tags with the "Manage Tags..." dialog in Search view does not affect message tags in History view. This might not be a bug, but actually just a missing feature, not sure though.
**To Reproduce**
1. find message in "Search" tab
2. got to "Manage Tags"
3. add a new tag and finish the dialogue
4. there is no new tag in the tag column of search view. This will appear if the search is repeated. The tag does not appear in the history view at all
**Expected behavior**
It is expected for a tag added in Search to affect the History view and be persisted in history and the ZAP session.
**Software versions**
- ZAP: w2018-05-14
- Add-on: Search is part of the core, right?
- OS: OSX 10.13.4
- Java: 1.8.0_152
| 08327c9b3f359949841efba3e6d0174df30b5176 | 284ba91af7b600a75146445d83cb0040b55a10cc | https://github.com/zaproxy/zaproxy/compare/08327c9b3f359949841efba3e6d0174df30b5176...284ba91af7b600a75146445d83cb0040b55a10cc | diff --git a/zap/src/main/java/org/zaproxy/zap/extension/search/SearchResultsTableModel.java b/zap/src/main/java/org/zaproxy/zap/extension/search/SearchResultsTableModel.java
index b1c4b00c0..f6fdd8832 100644
--- a/zap/src/main/java/org/zaproxy/zap/extension/search/SearchResultsTableModel.java
+++ b/zap/src/main/java/org/zaproxy/zap/extension/search/SearchResultsTableModel.java
@@ -74,7 +74,10 @@ public class SearchResultsTableModel
.registerConsumer(
this,
HistoryReferenceEventPublisher.getPublisher().getPublisherName(),
- HistoryReferenceEventPublisher.EVENT_REMOVED);
+ HistoryReferenceEventPublisher.EVENT_REMOVED,
+ HistoryReferenceEventPublisher.EVENT_TAG_ADDED,
+ HistoryReferenceEventPublisher.EVENT_TAG_REMOVED,
+ HistoryReferenceEventPublisher.EVENT_TAGS_SET);
}
public void addSearchResult(SearchResult sr) {
@@ -294,6 +297,27 @@ public class SearchResultsTableModel
String idStr =
event.getParameters()
.get(HistoryReferenceEventPublisher.FIELD_HISTORY_REFERENCE_ID);
- this.removeEntry(Integer.parseInt(idStr));
+ int historyId = Integer.parseInt(idStr);
+ switch (event.getEventType()) {
+ case HistoryReferenceEventPublisher.EVENT_REMOVED:
+ this.removeEntry(historyId);
+ break;
+ case HistoryReferenceEventPublisher.EVENT_TAG_ADDED:
+ case HistoryReferenceEventPublisher.EVENT_TAG_REMOVED:
+ case HistoryReferenceEventPublisher.EVENT_TAGS_SET:
+ boolean rowsUpdated = false;
+ for (int i = 0; i < results.size(); i++) {
+ SearchResultTableEntry entry = results.get(i);
+ if (entry.getHistoryId() == historyId) {
+ entry.refreshCachedValues();
+ rowsUpdated = true;
+ }
+ }
+
+ if (rowsUpdated) {
+ fireTableRowsUpdated(0, results.size() - 1);
+ }
+ break;
+ }
}
}
diff --git a/zap/src/main/java/org/zaproxy/zap/extension/search/SearchThread.java b/zap/src/main/java/org/zaproxy/zap/extension/search/SearchThread.java
index 0ecf4277f..f6e9833f1 100644
--- a/zap/src/main/java/org/zaproxy/zap/extension/search/SearchThread.java
+++ b/zap/src/main/java/org/zaproxy/zap/extension/search/SearchThread.java
@@ -25,7 +25,9 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
+import org.parosproxy.paros.control.Control;
import org.parosproxy.paros.db.DatabaseException;
+import org.parosproxy.paros.extension.history.ExtensionHistory;
import org.parosproxy.paros.model.HistoryReference;
import org.parosproxy.paros.model.Model;
import org.parosproxy.paros.model.Session;
@@ -191,6 +193,11 @@ public class SearchThread extends Thread {
return;
}
+ ExtensionHistory extensionHistory =
+ Control.getSingleton()
+ .getExtensionLoader()
+ .getExtension(ExtensionHistory.class);
+
List<Integer> list =
Model.getSingleton()
.getDb()
@@ -211,7 +218,13 @@ public class SearchThread extends Thread {
try {
currentRecordId = index;
// Create the href to ensure the msg is set up correctly
- HistoryReference href = new HistoryReference(historyId);
+ HistoryReference href = null;
+ if (extensionHistory != null) {
+ href = extensionHistory.getHistoryReference(historyId);
+ }
+ if (href == null) {
+ href = new HistoryReference(historyId);
+ }
HttpMessage message = href.getHttpMessage();
if (searchJustInScope
&& !session.isInScope(message.getRequestHeader().getURI().toString())) { | ['zap/src/main/java/org/zaproxy/zap/extension/search/SearchThread.java', 'zap/src/main/java/org/zaproxy/zap/extension/search/SearchResultsTableModel.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 9,970,251 | 1,988,799 | 272,328 | 1,168 | 2,113 | 323 | 43 | 2 | 767 | 137 | 196 | 18 | 0 | 0 | 2021-03-23T17:38:17 | 11,102 | Java | {'Java': 12002133, 'HTML': 3977629, 'Python': 158050, 'Kotlin': 54286, 'JavaScript': 9640, 'Shell': 8430, 'Lex': 5179, 'Perl': 3832, 'XSLT': 3054} | Apache License 2.0 |
610 | zaproxy/zaproxy/7616/7590 | zaproxy | zaproxy | https://github.com/zaproxy/zaproxy/issues/7590 | https://github.com/zaproxy/zaproxy/pull/7616 | https://github.com/zaproxy/zaproxy/pull/7616 | 1 | fix | Add-ons being updated might be marked as blocked | ### Describe the bug
When I start the zap proxy from the command line for the first time after installing, it will start fine. If I shut it down, then try to start it up again, it fails to start, citing that the mandatory "network" plugin is missing. This plugin is shown as being installed during the first run:
`43232 [ZAP-daemon] INFO org.parosproxy.paros.CommandLine - Add-on downloaded to: /home/gary/.ZAP/plugin/network-beta-0.4.0.zap`
NOTE: this apparently doesn't happen when I run as the root user. Only as non-root.
### Steps to reproduce the behavior
1. Start the ZAP proxy:
`/usr/share/owasp-zap/zap.sh -version -daemon -host 127.0.0.1 -port 52090 -config api.key=dynamic-scan`
2. Shut down the proxy via the API:
`curl -H "X-ZAP-API-KEY: dynamic-scan" http://127.0.0.1:52090/JSON/core/action/shutdown/`
3. Try to start the proxy again in the same way, with the same command
### Expected behavior
The proxy should start up and enter the ready state, same as before.
### Software versions
ZAP 2.12.0
Installed from: https://download.opensuse.org/repositories/home:/cabelo/xUbuntu_20.04/amd64/owasp-zap_2.12.0-1_amd64.deb
### Screenshots
_No response_
### Errors from the zap.log file
Found Java version 11.0.16
Available memory: 7851 MB
Using JVM args: -Xmx1962m
4841 [main] INFO org.zaproxy.zap.DaemonBootstrap - OWASP ZAP 2.12.0 started 08/11/2022, 21:03:40 with home /home/gary/.ZAP/
5025 [main] INFO org.parosproxy.paros.common.AbstractParam - Setting config api.key = dynamic-scan was dynamic-scan
9797 [ZAP-daemon] INFO org.zaproxy.zap.control.ExtensionFactory - Installed add-ons: [[id=alertFilters, version=14.0.0], [id=automation, version=0.19.0], [id=bruteforce, version=12.0.0], [id=callhome, version=0.5.0], [id=commonlib, version=1.11.0], [id=database, version=0.1.0], [id=diff, version=12.0.0], [id=directorylistv1, version=5.0.0], [id=encoder, version=0.7.0], [id=exim, version=0.3.0], [id=formhandler, version=6.1.0], [id=fuzz, version=13.8.0], [id=gettingStarted, version=14.0.0], [id=graaljs, version=0.3.0], [id=graphql, version=0.11.0], [id=help, version=15.0.0], [id=invoke, version=12.0.0], [id=onlineMenu, version=10.0.0], [id=openapi, version=29.0.0], [id=pscanrules, version=44.0.0], [id=replacer, version=11.0.0], [id=reports, version=0.16.0], [id=requester, version=7.0.0], [id=retest, version=0.4.0], [id=retire, version=0.16.0], [id=reveal, version=5.0.0], [id=scripts, version=33.0.0], [id=soap, version=15.0.0], [id=tips, version=10.0.0], [id=webdriverlinux, version=46.0.0], [id=websocket, version=27.0.0]]
9809 [ZAP-daemon] ERROR org.parosproxy.paros.control.Control - The mandatory add-on was not found: network
Refer to https://www.zaproxy.org/docs/developer/ if you are building ZAP from source.
Failed to start ZAP. The mandatory add-on was not found: network
Refer to https://www.zaproxy.org/docs/developer/ if you are building ZAP from source.
### Additional context
For the test I am running in the official ubuntu container: `ubuntu:latest` (Currently 22.04)
Here is the dockerfile I am using, in case it's relevant:
```
FROM ubuntu:latest
ADD https://download.opensuse.org/repositories/home:/cabelo/xUbuntu_20.04/amd64/owasp-zap_2.12.0-1_amd64.deb /tmp/owasp.deb
RUN apt-get -y update
RUN apt-get -y install curl openjdk-11-jre
RUN dpkg -i /tmp/owasp.deb
RUN useradd -ms /bin/bash gary
USER gary
WORKDIR /home/gary
CMD ["/bin/bash"]
```
### Would you like to help fix this issue?
- [ ] Yes | 7a8326bef732b7ffa04500a3ca49b23800ecd73f | 8854d6ccec907645921d57c441b7d8c111f1cfd4 | https://github.com/zaproxy/zaproxy/compare/7a8326bef732b7ffa04500a3ca49b23800ecd73f...8854d6ccec907645921d57c441b7d8c111f1cfd4 | diff --git a/zap/src/main/java/org/zaproxy/zap/extension/autoupdate/ExtensionAutoUpdate.java b/zap/src/main/java/org/zaproxy/zap/extension/autoupdate/ExtensionAutoUpdate.java
index 5292b1b3a..263be0ee4 100644
--- a/zap/src/main/java/org/zaproxy/zap/extension/autoupdate/ExtensionAutoUpdate.java
+++ b/zap/src/main/java/org/zaproxy/zap/extension/autoupdate/ExtensionAutoUpdate.java
@@ -1629,7 +1629,7 @@ public class ExtensionAutoUpdate extends ExtensionAdaptor
final Set<AddOn> failedUninstallations = new HashSet<>();
for (AddOn addOn : addOns) {
- if (!uninstall(addOn, false, null)) {
+ if (!uninstall(addOn, updates, null)) {
failedUninstallations.add(addOn);
}
} | ['zap/src/main/java/org/zaproxy/zap/extension/autoupdate/ExtensionAutoUpdate.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,999,635 | 1,997,186 | 273,375 | 1,176 | 103 | 26 | 2 | 1 | 3,531 | 388 | 1,164 | 65 | 5 | 1 | 2022-11-24T20:07:48 | 11,102 | Java | {'Java': 12002133, 'HTML': 3977629, 'Python': 158050, 'Kotlin': 54286, 'JavaScript': 9640, 'Shell': 8430, 'Lex': 5179, 'Perl': 3832, 'XSLT': 3054} | Apache License 2.0 |
611 | zaproxy/zaproxy/7599/7598 | zaproxy | zaproxy | https://github.com/zaproxy/zaproxy/issues/7598 | https://github.com/zaproxy/zaproxy/pull/7599 | https://github.com/zaproxy/zaproxy/pull/7599 | 1 | fix | Misspelling in `config.xml` `scanner.antiCSFR` should be `scanner.antiCSRF` | ### Describe the bug
Minor typo.
### Steps to reproduce the behavior
`grep CSFR ~/.ZAP/config.xml`
### Expected behavior
Just a spelling correction but may have larger ramifications since it's in the config file.
### Software versions
2.12.0
### Screenshots
_No response_
### Errors from the zap.log file
_No response_
### Additional context
_No response_
### Would you like to help fix this issue?
- [ ] Yes | 45180ea383ec85317d3f342f2c86763b337a8172 | ae4c362ff154efced38c4493bc8eb09ba2501071 | https://github.com/zaproxy/zaproxy/compare/45180ea383ec85317d3f342f2c86763b337a8172...ae4c362ff154efced38c4493bc8eb09ba2501071 | diff --git a/zap/src/main/java/org/parosproxy/paros/core/scanner/ScannerParam.java b/zap/src/main/java/org/parosproxy/paros/core/scanner/ScannerParam.java
index 0a2685f04..fe571edea 100644
--- a/zap/src/main/java/org/parosproxy/paros/core/scanner/ScannerParam.java
+++ b/zap/src/main/java/org/parosproxy/paros/core/scanner/ScannerParam.java
@@ -77,7 +77,7 @@ public class ScannerParam extends AbstractParam {
// ZAP: Added support for delayInMs
private static final String DELAY_IN_MS = ACTIVE_SCAN_BASE_KEY + ".delayInMs";
private static final String INJECT_PLUGIN_ID_IN_HEADER = ACTIVE_SCAN_BASE_KEY + ".pluginHeader";
- private static final String HANDLE_ANTI_CSRF_TOKENS = ACTIVE_SCAN_BASE_KEY + ".antiCSFR";
+ private static final String HANDLE_ANTI_CSRF_TOKENS = ACTIVE_SCAN_BASE_KEY + ".antiCSRF";
private static final String PROMPT_IN_ATTACK_MODE = ACTIVE_SCAN_BASE_KEY + ".attackPrompt";
private static final String RESCAN_IN_ATTACK_MODE = ACTIVE_SCAN_BASE_KEY + ".attackRescan";
private static final String PROMPT_TO_CLEAR_FINISHED = ACTIVE_SCAN_BASE_KEY + ".clearFinished";
@@ -219,7 +219,7 @@ public class ScannerParam extends AbstractParam {
@Override
protected void parse() {
- removeOldOptions();
+ migrateOldOptions();
this.threadPerHost = Math.max(1, getInt(THREAD_PER_HOST, 2));
@@ -311,8 +311,14 @@ public class ScannerParam extends AbstractParam {
}
}
- private void removeOldOptions() {
- final String oldKey = "scanner.deleteOnShutdown";
+ private void migrateOldOptions() {
+ String oldKey = "scanner.antiCSFR";
+ if (getConfig().containsKey(oldKey)) {
+ getConfig().setProperty(HANDLE_ANTI_CSRF_TOKENS, getConfig().getProperty(oldKey));
+ getConfig().clearProperty(oldKey);
+ }
+
+ oldKey = "scanner.deleteOnShutdown";
if (getConfig().containsKey(oldKey)) {
getConfig().clearProperty(oldKey);
}
diff --git a/zap/src/test/java/org/parosproxy/paros/core/scanner/ScannerParamUnitTest.java b/zap/src/test/java/org/parosproxy/paros/core/scanner/ScannerParamUnitTest.java
index 1fb294b8f..91e4c504c 100644
--- a/zap/src/test/java/org/parosproxy/paros/core/scanner/ScannerParamUnitTest.java
+++ b/zap/src/test/java/org/parosproxy/paros/core/scanner/ScannerParamUnitTest.java
@@ -22,6 +22,7 @@ package org.parosproxy.paros.core.scanner;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import org.junit.jupiter.api.AfterAll;
@@ -185,4 +186,18 @@ class ScannerParamUnitTest {
assertThat(
configuration.getBoolean(ScannerParam.SCAN_NULL_JSON_VALUES), is(equalTo(value)));
}
+
+ @Test
+ void shouldMigrateOldOptions() {
+ // Given
+ configuration.setProperty("scanner.deleteOnShutdown", true);
+ configuration.setProperty("scanner.antiCSRF", true);
+ // When
+ param.load(configuration);
+ // Then
+ assertThat(configuration.getProperty("scanner.antiCSRF"), is(equalTo(true)));
+ assertThat(param.getHandleAntiCSRFTokens(), is(equalTo(true)));
+ assertNull(configuration.getProperty("scanner.antiCSFR"));
+ assertNull(configuration.getProperty("scanner.deleteOnShutdown"));
+ }
} | ['zap/src/main/java/org/parosproxy/paros/core/scanner/ScannerParam.java', 'zap/src/test/java/org/parosproxy/paros/core/scanner/ScannerParamUnitTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 9,998,952 | 1,997,026 | 273,361 | 1,176 | 682 | 146 | 14 | 1 | 423 | 67 | 95 | 31 | 0 | 0 | 2022-11-11T06:15:32 | 11,102 | Java | {'Java': 12002133, 'HTML': 3977629, 'Python': 158050, 'Kotlin': 54286, 'JavaScript': 9640, 'Shell': 8430, 'Lex': 5179, 'Perl': 3832, 'XSLT': 3054} | Apache License 2.0 |
621 | zaproxy/zaproxy/6817/3988 | zaproxy | zaproxy | https://github.com/zaproxy/zaproxy/issues/3988 | https://github.com/zaproxy/zaproxy/pull/6817 | https://github.com/zaproxy/zaproxy/pull/6817 | 1 | fix | Selected checkbox tree nodes not correctly highlighted in macOS | Issue reported in OWASP ZAP User Group: https://groups.google.com/d/msg/zaproxy-users/8xw8VDLbO5U/PbOXDbOaAwAJ
The selected nodes in the checkbox tree are not correctly highlighted (like the Sites tree in #3351).
ZAP version:
Version 2.6.0 (older versions are also affected). | 2910aa12c8e422a4efc4824ba14fdbbc13d54d0a | e00be5616e3d96a70870de9baad4ec369c3510ac | https://github.com/zaproxy/zaproxy/compare/2910aa12c8e422a4efc4824ba14fdbbc13d54d0a...e00be5616e3d96a70870de9baad4ec369c3510ac | diff --git a/zap/src/main/java/org/zaproxy/zap/view/JCheckBoxTree.java b/zap/src/main/java/org/zaproxy/zap/view/JCheckBoxTree.java
index 5d5feaebd..fd0134868 100644
--- a/zap/src/main/java/org/zaproxy/zap/view/JCheckBoxTree.java
+++ b/zap/src/main/java/org/zaproxy/zap/view/JCheckBoxTree.java
@@ -167,6 +167,7 @@ public class JCheckBoxTree extends JTree {
this.setLayout(new BorderLayout());
checkBox = new JCheckBox();
altLabel = new JLabel("");
+ altLabel.setOpaque(true);
add(checkBox, BorderLayout.CENTER);
add(altLabel, BorderLayout.EAST);
setOpaque(false);
@@ -188,6 +189,9 @@ public class JCheckBoxTree extends JTree {
altLabel.setForeground(
UIManager.getColor(
selected ? "Tree.selectionForeground" : "Tree.textForeground"));
+ altLabel.setBackground(
+ UIManager.getColor(
+ selected ? "Tree.selectionBackground" : "Tree.textBackground"));
CheckedNode cn = nodesCheckingState.get(tp);
if (cn == null) {
checkBox.setVisible(false); | ['zap/src/main/java/org/zaproxy/zap/view/JCheckBoxTree.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 9,997,414 | 1,992,807 | 273,243 | 1,180 | 210 | 30 | 4 | 1 | 282 | 34 | 81 | 6 | 1 | 0 | 2021-09-20T17:22:07 | 11,102 | Java | {'Java': 12002133, 'HTML': 3977629, 'Python': 158050, 'Kotlin': 54286, 'JavaScript': 9640, 'Shell': 8430, 'Lex': 5179, 'Perl': 3832, 'XSLT': 3054} | Apache License 2.0 |
609 | zaproxy/zaproxy/7748/7716 | zaproxy | zaproxy | https://github.com/zaproxy/zaproxy/issues/7716 | https://github.com/zaproxy/zaproxy/pull/7748 | https://github.com/zaproxy/zaproxy/pull/7748 | 1 | fix | Ascan Category summaries not updated | ### Describe the bug
The Active scan dialog Category Threshold and Stength columns are not updated when the "Go" buttons are used.
The underlying rules are however set correctly.
https://groups.google.com/g/zaproxy-users/c/AfVXJpiPPYw/m/m4Jg2KmvAQAJ
### Steps to reproduce the behavior
As per https://groups.google.com/g/zaproxy-users/c/AfVXJpiPPYw/m/m4Jg2KmvAQAJ
### Expected behavior
The Threshold and Strength columns should be updated to reflect the new states.
### Software versions
2.12.0
### Screenshots
See https://groups.google.com/g/zaproxy-users/c/AfVXJpiPPYw/m/m4Jg2KmvAQAJ
### Errors from the zap.log file
_No response_
### Additional context
_No response_
### Would you like to help fix this issue?
- [ ] Yes | 03115da6816df2a5ebe5962fae3a5f676940c70e | c40a2cf72407460ab84aac109c860032a4f2b683 | https://github.com/zaproxy/zaproxy/compare/03115da6816df2a5ebe5962fae3a5f676940c70e...c40a2cf72407460ab84aac109c860032a4f2b683 | diff --git a/zap/src/main/java/org/zaproxy/zap/extension/ascan/PolicyAllCategoryPanel.java b/zap/src/main/java/org/zaproxy/zap/extension/ascan/PolicyAllCategoryPanel.java
index 747d707d0..ab0cfd4b1 100644
--- a/zap/src/main/java/org/zaproxy/zap/extension/ascan/PolicyAllCategoryPanel.java
+++ b/zap/src/main/java/org/zaproxy/zap/extension/ascan/PolicyAllCategoryPanel.java
@@ -279,7 +279,6 @@ public class PolicyAllCategoryPanel extends AbstractParamPanel {
policy = extension.getPolicyManager().getPolicy(policyName);
if (policy != null) {
setScanPolicy(policy);
- fireScanPolicyChanged(policy);
}
} catch (ConfigurationException e1) {
LOGGER.error(e1.getMessage(), e1);
@@ -511,11 +510,12 @@ public class PolicyAllCategoryPanel extends AbstractParamPanel {
throw new InvalidParameterException(
"Cannot change policy if the panel has not been defined as switchable");
}
- this.policy = scanPolicy;
this.getPolicySelector().setSelectedItem(scanPolicy.getName());
+ this.policy = scanPolicy;
this.setThreshold(scanPolicy.getDefaultThreshold());
this.setStrength(scanPolicy.getDefaultStrength());
this.getAllCategoryTableModel().setPluginFactory(scanPolicy.getPluginFactory());
+ fireScanPolicyChanged(policy);
}
@Override | ['zap/src/main/java/org/zaproxy/zap/extension/ascan/PolicyAllCategoryPanel.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 10,057,750 | 2,008,947 | 274,951 | 1,185 | 177 | 28 | 4 | 1 | 739 | 89 | 202 | 33 | 3 | 0 | 2023-02-22T17:56:23 | 11,102 | Java | {'Java': 12002133, 'HTML': 3977629, 'Python': 158050, 'Kotlin': 54286, 'JavaScript': 9640, 'Shell': 8430, 'Lex': 5179, 'Perl': 3832, 'XSLT': 3054} | Apache License 2.0 |
607 | zaproxy/zaproxy/7813/7703 | zaproxy | zaproxy | https://github.com/zaproxy/zaproxy/issues/7703 | https://github.com/zaproxy/zaproxy/pull/7813 | https://github.com/zaproxy/zaproxy/pull/7813 | 1 | fix | Do not remove add-ons from the install dir | ### Describe the bug
We document the `-dir` option as a way to start ZAP with a clean config: https://www.zaproxy.org/docs/desktop/cmdline/
However on some platforms add-ons are deleted from the install dir when they are updated.
If the user updates one of the mandatory add-ons then it breaks this option - ZAP will not start.
### Steps to reproduce the behavior
1. Install ZAP
2. Update ZAP (making sure at least one mandatory option is updated)
3. Run ZAP using the `-d` option
### Expected behavior
ZAP will start with all of the orignal add-ons
### Software versions
2.12.0
### Screenshots
_No response_
### Errors from the zap.log file
_No response_
### Additional context
_No response_
### Would you like to help fix this issue?
- [ ] Yes | 6af51729fede1c37b173b8e3aee83e72ef460d51 | a307f6e8c877c1dce6c2e20806fb19680b28c9b4 | https://github.com/zaproxy/zaproxy/compare/6af51729fede1c37b173b8e3aee83e72ef460d51...a307f6e8c877c1dce6c2e20806fb19680b28c9b4 | diff --git a/zap/src/main/java/org/zaproxy/zap/control/AddOnLoader.java b/zap/src/main/java/org/zaproxy/zap/control/AddOnLoader.java
index 9c1d18361..24a3453ea 100644
--- a/zap/src/main/java/org/zaproxy/zap/control/AddOnLoader.java
+++ b/zap/src/main/java/org/zaproxy/zap/control/AddOnLoader.java
@@ -23,6 +23,7 @@ import java.awt.EventQueue;
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
+import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.net.MalformedURLException;
@@ -30,6 +31,9 @@ import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -713,15 +717,56 @@ public class AddOnLoader extends URLClassLoader {
private void deleteAddOn(AddOn addOn, boolean upgrading) {
AddOnInstaller.uninstallAddOnLibs(addOn);
+ File addOnFile = addOn.getFile();
+ if (addOnFile == null || !addOnFile.exists()) {
+ return;
+ }
+
+ if (isInstallationAddOn(addOnFile.toPath())) {
+ LOGGER.debug(
+ "Not removing add-on in the installation directory: {}",
+ addOnFile.getAbsolutePath());
+ if (!upgrading) {
+ saveBlockedAddOn(addOn);
+ }
+ return;
+ }
+
if (addOn.getFile() != null && addOn.getFile().exists()) {
if (!addOn.getFile().delete() && !upgrading) {
LOGGER.debug("Can't delete {}", addOn.getFile().getAbsolutePath());
- this.blockList.add(addOn.getId());
- this.saveBlockList();
+ saveBlockedAddOn(addOn);
}
}
}
+ private void saveBlockedAddOn(AddOn addOn) {
+ if (addOn.isMandatory()) {
+ return;
+ }
+
+ blockList.add(addOn.getId());
+ saveBlockList();
+ }
+
+ List<String> getBlockList() {
+ return blockList;
+ }
+
+ private static boolean isInstallationAddOn(Path file) {
+ Path installDir = Paths.get(Constant.getZapInstall()).resolve(Constant.FOLDER_PLUGIN);
+ if (Files.notExists(installDir)) {
+ return false;
+ }
+
+ try {
+ return Files.isSameFile(installDir, file.getParent());
+ } catch (IOException e) {
+ LOGGER.warn("An error occurred while checking the add-on's dir:", e);
+ return false;
+ }
+ }
+
private void removeAddOnClassLoader(AddOn addOn) {
if (this.addOnLoaders.containsKey(addOn.getId())) {
try (AddOnClassLoader addOnClassLoader = this.addOnLoaders.remove(addOn.getId())) {
diff --git a/zap/src/test/java/org/zaproxy/zap/control/AddOnLoaderUnitTest.java b/zap/src/test/java/org/zaproxy/zap/control/AddOnLoaderUnitTest.java
index 367c63e63..8f48533e7 100644
--- a/zap/src/test/java/org/zaproxy/zap/control/AddOnLoaderUnitTest.java
+++ b/zap/src/test/java/org/zaproxy/zap/control/AddOnLoaderUnitTest.java
@@ -25,12 +25,15 @@ import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.mockito.Mockito.verify;
import java.io.File;
import java.io.IOException;
+import java.nio.file.Files;
import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -56,6 +59,7 @@ class AddOnLoaderUnitTest extends AddOnTestUtils {
@BeforeEach
void createZapHome() throws Exception {
Constant.setZapHome(newTempDir("home").toAbsolutePath().toString());
+ Constant.setZapInstall(newTempDir("install").toAbsolutePath().toString());
}
@ParameterizedTest
@@ -323,6 +327,52 @@ class AddOnLoaderUnitTest extends AddOnTestUtils {
is(equalTo(InstallationStatus.INSTALLED)));
}
+ @Test
+ void shouldRemoveAddOnWhenNotInInstallationPluginDir() throws Exception {
+ // Given
+ Path dir = newTempDir();
+ String addOnId = "id";
+ createAddOnFile(dir, addOnId + ".zap");
+ AddOnLoader addOnLoader = new AddOnLoader(new File[] {dir.toFile()});
+ AddOn addOn = getAddOn(addOnLoader, addOnId);
+ // When
+ addOnLoader.removeAddOn(addOn, false, AddOnLoader.NULL_CALLBACK);
+ // Then
+ assertThat(Files.exists(addOn.getFile().toPath()), is(equalTo(false)));
+ assertThat(addOnLoader.getBlockList(), not(contains("id")));
+ }
+
+ @Test
+ void shouldKeepAndBlockAddOnInInstallationPluginDir() throws Exception {
+ // Given
+ Path dir = Paths.get(Constant.getZapInstall(), Constant.FOLDER_PLUGIN);
+ String addOnId = "id";
+ createAddOnFile(dir, addOnId + ".zap");
+ AddOnLoader addOnLoader = new AddOnLoader(new File[] {dir.toFile()});
+ AddOn addOn = getAddOn(addOnLoader, addOnId);
+ // When
+ addOnLoader.removeAddOn(addOn, false, AddOnLoader.NULL_CALLBACK);
+ // Then
+ assertThat(Files.exists(addOn.getFile().toPath()), is(equalTo(true)));
+ assertThat(addOnLoader.getBlockList(), contains("id"));
+ }
+
+ @Test
+ void shouldKeepButNotBlockMandatoryAddOnInInstallationPluginDir() throws Exception {
+ // Given
+ Path dir = Paths.get(Constant.getZapInstall(), Constant.FOLDER_PLUGIN);
+ String addOnId = "id";
+ createAddOnFile(dir, addOnId + ".zap");
+ AddOnLoader addOnLoader = new AddOnLoader(new File[] {dir.toFile()});
+ AddOn addOn = getAddOn(addOnLoader, addOnId);
+ addOn.setMandatory(true);
+ // When
+ addOnLoader.removeAddOn(addOn, false, AddOnLoader.NULL_CALLBACK);
+ // Then
+ assertThat(Files.exists(addOn.getFile().toPath()), is(equalTo(true)));
+ assertThat(addOnLoader.getBlockList(), not(contains("id")));
+ }
+
private void assertExtensionRemoved(Extension extension) {
verify(extensionLoader).removeExtension(extension);
}
diff --git a/zap/src/test/java/org/zaproxy/zap/control/AddOnTestUtils.java b/zap/src/test/java/org/zaproxy/zap/control/AddOnTestUtils.java
index 9d6d80804..125aa29ae 100644
--- a/zap/src/test/java/org/zaproxy/zap/control/AddOnTestUtils.java
+++ b/zap/src/test/java/org/zaproxy/zap/control/AddOnTestUtils.java
@@ -152,6 +152,7 @@ class AddOnTestUtils extends WithConfigsTest {
Consumer<StringBuilder> manifestConsumer,
Consumer<ZipOutputStream> addOnConsumer) {
try {
+ Files.createDirectories(dir);
Path file = dir.resolve(fileName);
try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(file))) {
ZipEntry manifest = new ZipEntry(AddOn.MANIFEST_FILE_NAME); | ['zap/src/main/java/org/zaproxy/zap/control/AddOnLoader.java', 'zap/src/test/java/org/zaproxy/zap/control/AddOnLoaderUnitTest.java', 'zap/src/test/java/org/zaproxy/zap/control/AddOnTestUtils.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 10,032,646 | 2,003,653 | 274,243 | 1,179 | 1,469 | 289 | 49 | 1 | 794 | 128 | 183 | 35 | 1 | 0 | 2023-04-06T19:31:26 | 11,102 | Java | {'Java': 12002133, 'HTML': 3977629, 'Python': 158050, 'Kotlin': 54286, 'JavaScript': 9640, 'Shell': 8430, 'Lex': 5179, 'Perl': 3832, 'XSLT': 3054} | Apache License 2.0 |
606 | zaproxy/zaproxy/7845/6957 | zaproxy | zaproxy | https://github.com/zaproxy/zaproxy/issues/6957 | https://github.com/zaproxy/zaproxy/pull/7845 | https://github.com/zaproxy/zaproxy/pull/7845 | 1 | fixes | Use of commas within regex for contexts renders them unloadable | ## Summary
When regular expressions are created using braces, the GUI will save the user input during the current working session and behave as expected. However, if the user restarts OWASP Zap and attempts to import the context into a new session, the resulting action creates an exception. This is based upon how the rendered context file is created where braces and commas are involved.
## System Information
* OWASP ZAP version 2.11.0
* Tested on both Ubuntu and OSX
## Steps to Reproduce
1. Launch OWASP Zap.
2. Double-click on the Default Context to launch the Session Properties modal. Select "Include In Context".
3. Click the "Add..." button and enter the following regular expression: `http[s]{0,1}:\\/\\/[a-zA-Z0-9.-]{1,}(google.com)\\/{0,1}(.*)`. Click the "Add" button when done.
4. Click the "OK" button to close the Session Properties modal.
5. Right-click on the Default Context and select "Export Context..".
6. Save the context somewhere on your local drive.
7. Locate the context file on your local drive and view the contents. For the example above, here is the first few nodes of the XML content:
```<configuration>
<context>
<name>Default Context</name>
<desc/>
<inscope>true</inscope>
<incregexes>http[s]{0</incregexes>
<incregexes>1}:\\/\\/[a-zA-Z0-9.-]{1</incregexes>
<incregexes>}(google.com)\\/{0</incregexes>
<incregexes>1}(.*)</incregexes>
8. Exit OWASP Zap and re-open the application.
9. Click the "Import Context..." icon and select the context you just created.
10. _*NOTICE:* You now see a "Failed to import Context" error suggesting that the issue is the first node containing some portion of the regular expression (i.e. `http[s]{0`).
11. Repeat the same process as above, exept this time use the following regular expression: `http[s]?:\\/\\/[a-zA-Z0-9.-]+(google.com)\\/?(.*)`. Note that the difference is that quantifiers used have the same meaning but use different symbols (i.e. https://docs.microsoft.com/en-us/dotnet/standard/base-types/quantifiers-in-regular-expressions). The resulting XML now looks like this when viewing the contents of the new context file:
```<configuration>
<context>
<name>New Context</name>
<desc/>
<inscope>true</inscope>
<incregexes>http[s]?:\\/\\/[a-zA-Z0-9.-]+(google.com)\\/?(.*)</incregexes>
## Log Output (from zap.log)
```
java.util.regex.PatternSyntaxException: Unclosed counted closure near index 9
http[s]{0
at java.util.regex.Pattern.error(Pattern.java:2027) ~[?:?]
at java.util.regex.Pattern.closure(Pattern.java:3304) ~[?:?]
at java.util.regex.Pattern.sequence(Pattern.java:2213) ~[?:?]
at java.util.regex.Pattern.expr(Pattern.java:2068) ~[?:?]
at java.util.regex.Pattern.compile(Pattern.java:1782) ~[?:?]
at java.util.regex.Pattern.<init>(Pattern.java:1428) ~[?:?]
at java.util.regex.Pattern.compile(Pattern.java:1094) ~[?:?]
at org.zaproxy.zap.model.Context.validateRegex(Context.java:364) ~[zap-2.11.0.jar:2.11.0]
at org.zaproxy.zap.model.Context.addIncludeInContextRegex(Context.java:402) ~[zap-2.11.0.jar:2.11.0]
at org.parosproxy.paros.model.Session.importContext(Session.java:1542) ~[zap-2.11.0.jar:2.11.0]
at org.parosproxy.paros.control.MenuFileControl.importContext(MenuFileControl.java:594) [zap-2.11.0.jar:2.11.0]
at org.parosproxy.paros.view.SiteMapPanel$3.actionPerformed(SiteMapPanel.java:283) [zap-2.11.0.jar:2.11.0]
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1967) [?:?]
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2308) [?:?]
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:405) [?:?]
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:262) [?:?]
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:279) [?:?]
at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:297) [?:?]
at java.awt.Component.processMouseEvent(Component.java:6635) [?:?]
at javax.swing.JComponent.processMouseEvent(JComponent.java:3342) [?:?]
at java.awt.Component.processEvent(Component.java:6400) [?:?]
at java.awt.Container.processEvent(Container.java:2263) [?:?]
at java.awt.Component.dispatchEventImpl(Component.java:5011) [?:?]
at java.awt.Container.dispatchEventImpl(Container.java:2321) [?:?]
at java.awt.Component.dispatchEvent(Component.java:4843) [?:?]
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4918) [?:?]
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4547) [?:?]
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4488) [?:?]
at java.awt.Container.dispatchEventImpl(Container.java:2307) [?:?]
at java.awt.Window.dispatchEventImpl(Window.java:2772) [?:?]
at java.awt.Component.dispatchEvent(Component.java:4843) [?:?]
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772) [?:?]
at java.awt.EventQueue$4.run(EventQueue.java:721) [?:?]
at java.awt.EventQueue$4.run(EventQueue.java:715) [?:?]
at java.security.AccessController.doPrivileged(Native Method) ~[?:?]
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85) [?:?]
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95) [?:?]
at java.awt.EventQueue$5.run(EventQueue.java:745) [?:?]
at java.awt.EventQueue$5.run(EventQueue.java:743) [?:?]
at java.security.AccessController.doPrivileged(Native Method) ~[?:?]
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85) [?:?]
at java.awt.EventQueue.dispatchEvent(EventQueue.java:742) [?:?]
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203) [?:?]
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124) [?:?]
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113) [?:?]
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109) [?:?]
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) [?:?]
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90) [?:?]
```
## Bug Fix Suggestion
Both syntax structures should be honored. Serialization of the regular expression might help resolve characters being accidentally interpreted by the underlying code.
## Success
Regular expressions which utilize braces can now be accepted as input for the development of contexts. | f537976b486310cd422fe85969634aebff0901d1 | b0dc3c5a49bed6e8335e2785dd4a4b30aa86f03a | https://github.com/zaproxy/zaproxy/compare/f537976b486310cd422fe85969634aebff0901d1...b0dc3c5a49bed6e8335e2785dd4a4b30aa86f03a | diff --git a/zap/src/main/java/org/zaproxy/zap/utils/ZapXmlConfiguration.java b/zap/src/main/java/org/zaproxy/zap/utils/ZapXmlConfiguration.java
index 17cdedb6b..0dd34945f 100644
--- a/zap/src/main/java/org/zaproxy/zap/utils/ZapXmlConfiguration.java
+++ b/zap/src/main/java/org/zaproxy/zap/utils/ZapXmlConfiguration.java
@@ -55,6 +55,7 @@ public class ZapXmlConfiguration extends XMLConfiguration {
super.setEncoding("UTF-8");
super.setDelimiterParsingDisabled(true);
+ super.setListDelimiter('\\0');
}
/**
@@ -83,6 +84,19 @@ public class ZapXmlConfiguration extends XMLConfiguration {
load();
}
+ /**
+ * Creates a new instance of {@code ZapXmlConfiguration}. The configuration is loaded from the
+ * specified {@code url}.
+ *
+ * @param url the URL
+ * @throws ConfigurationException if loading the configuration fails
+ */
+ public ZapXmlConfiguration(URL url) throws ConfigurationException {
+ this();
+ setURL(url);
+ load();
+ }
+
/**
* Creates a new instance of {@code ZapXmlConfiguration}. The configuration is loaded from the
* specified {@code file}.
@@ -134,19 +148,6 @@ public class ZapXmlConfiguration extends XMLConfiguration {
return transformer;
}
- /**
- * Creates a new instance of {@code ZapXmlConfiguration}. The configuration is loaded from the
- * specified {@code url}.
- *
- * @param url the URL
- * @throws ConfigurationException if loading the configuration fails
- */
- public ZapXmlConfiguration(URL url) throws ConfigurationException {
- this();
- setURL(url);
- load();
- }
-
/**
* Calling this method has <strong>no</strong> effect. The character encoding used is always the
* same, UTF-8.
diff --git a/zap/src/test/java/org/zaproxy/zap/utils/ZapXmlConfigurationUnitTest.java b/zap/src/test/java/org/zaproxy/zap/utils/ZapXmlConfigurationUnitTest.java
index e8494b698..94cd6d09a 100644
--- a/zap/src/test/java/org/zaproxy/zap/utils/ZapXmlConfigurationUnitTest.java
+++ b/zap/src/test/java/org/zaproxy/zap/utils/ZapXmlConfigurationUnitTest.java
@@ -25,8 +25,11 @@ import static org.hamcrest.Matchers.is;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
+import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
+import java.util.List;
+import org.apache.commons.configuration.ConfigurationException;
import org.junit.jupiter.api.Test;
/** Unit test for {@link ZapXmlConfiguration}. */
@@ -43,6 +46,92 @@ class ZapXmlConfigurationUnitTest {
+ " </d>\\n"
+ "</a>\\n";
+ @Test
+ void shouldBeInstantiatedWithDelimeterParsingDisabledAndSetNullChar() {
+ // Given
+ ZapXmlConfiguration config = new ZapXmlConfiguration();
+ // When
+ boolean isParsingDisabled = config.isDelimiterParsingDisabled();
+ char delimChar = config.getListDelimiter();
+ // Then
+ assertThat(isParsingDisabled, is(equalTo(true)));
+ assertThat(delimChar, is(equalTo('\\0')));
+ }
+
+ @Test
+ void shouldSetVariousPropertiesAsExpected()
+ throws ConfigurationException, UnsupportedEncodingException {
+ // Given
+ ZapXmlConfiguration config = new ZapXmlConfiguration();
+ String aString = "Some string 🙂.";
+ String bString = "";
+ String cString = null;
+ int aInt = 120;
+ boolean aBoolean = true;
+ // When
+ config.setProperty("aString", aString);
+ config.setProperty("bString", bString);
+ config.setProperty("cString", cString);
+ config.setProperty("aInt", aInt);
+ config.setProperty("aBoolean", aBoolean);
+ // Then
+ List<Object> aStringList = config.getList("aString");
+ assertThat(aStringList.size(), is(equalTo(1)));
+ assertThat(aStringList.get(0), is(equalTo(aString)));
+
+ List<Object> bStringList = config.getList("bString");
+ assertThat(bStringList.size(), is(equalTo(1)));
+ assertThat(bStringList.get(0), is(equalTo(bString)));
+
+ List<Object> cStringList = config.getList("cString");
+ assertThat(cStringList.size(), is(equalTo(0)));
+
+ List<Object> aIntList = config.getList("aInt");
+ int aActualInt = config.getInt("aInt");
+ assertThat(aIntList.size(), is(equalTo(1)));
+ // Int is string when handled via list
+ assertThat(aIntList.get(0), is(equalTo("120")));
+ assertThat(aActualInt, is(equalTo(120)));
+
+ List<Object> aBooleanList = config.getList("aBoolean");
+ boolean aActualBoolean = config.getBoolean("aBoolean");
+ assertThat(aBooleanList.size(), is(equalTo(1)));
+ // Boolean is string when handled via list
+ assertThat(aBooleanList.get(0), is(equalTo("true")));
+ assertThat(aActualBoolean, is(equalTo(true)));
+ }
+
+ @Test
+ void shouldSetListOfPropertiesAsExpected() {
+ // Given
+ ZapXmlConfiguration config = new ZapXmlConfiguration();
+ String aString = "Some string 🙂.{2,2}";
+ String bString = "Some other string";
+ List<String> aList = List.of(aString, bString);
+ // When
+ config.setProperty("aList", aList);
+ // Then
+ List<Object> readList = config.getList("aList");
+ assertThat(readList.size(), is(equalTo(2)));
+ assertThat(readList.get(0), is(equalTo(aString)));
+ }
+
+ @Test
+ void shouldSetListOfNonPrimitivesAsExpected() throws IOException, ConfigurationException {
+ // Given
+ ZapXmlConfiguration config = new ZapXmlConfiguration();
+ CustomObject coOne = new CustomObject("coOne");
+ String stringTwo = "foo,bar";
+ CustomObject coTwo = new CustomObject(stringTwo);
+ List<CustomObject> customObjects = List.of(coOne, coTwo);
+ // When
+ config.setProperty("customObjects", customObjects);
+ // Then
+ List<Object> readList = config.getList("customObjects");
+ assertThat(readList.size(), is(equalTo(2)));
+ assertThat(((CustomObject) readList.get(1)).getValue(), is(equalTo(stringTwo)));
+ }
+
@Test
void shouldSaveNewConfigurationIndented() throws Exception {
// Given
@@ -78,4 +167,21 @@ class ZapXmlConfigurationUnitTest {
.toString(StandardCharsets.UTF_8.name())
.replaceAll(System.lineSeparator(), "\\n");
}
+
+ private static class CustomObject {
+ private final String value;
+
+ CustomObject(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ @Override
+ public String toString() {
+ return value;
+ }
+ }
} | ['zap/src/main/java/org/zaproxy/zap/utils/ZapXmlConfiguration.java', 'zap/src/test/java/org/zaproxy/zap/utils/ZapXmlConfigurationUnitTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 10,035,573 | 2,004,435 | 274,324 | 1,179 | 830 | 168 | 27 | 1 | 6,656 | 500 | 1,680 | 94 | 1 | 2 | 2023-04-30T10:26:13 | 11,102 | Java | {'Java': 12002133, 'HTML': 3977629, 'Python': 158050, 'Kotlin': 54286, 'JavaScript': 9640, 'Shell': 8430, 'Lex': 5179, 'Perl': 3832, 'XSLT': 3054} | Apache License 2.0 |
294 | code4craft/webmagic/370/301 | code4craft | webmagic | https://github.com/code4craft/webmagic/issues/301 | https://github.com/code4craft/webmagic/pull/370 | https://github.com/code4craft/webmagic/pull/370 | 1 | fixed | 在使用annotation时,解析json出问题 | 我在使用annotation解析json时,因为代码中只获取page.getHtml()而不是获取page.getJson(),所以不能正常解析json内容。问题代码出现在PageModelExtractor的processSingle方法中
我是在这里遇到问题,第346行-357行
`String value;`
`switch(PageModelExtractor.SyntheticClass_1.$SwitchMap$us$codecraft$webmagic$model$Extractor$Source[fieldExtractor.getSource().ordinal()]) {`
`case 1:`
`value = page.getHtml().selectDocument(fieldExtractor.getSelector());`
`break;`
`case 2:`
`if(isRaw) {`
`value = page.getHtml().selectDocument(fieldExtractor.getSelector());`
`} else {`
`value = fieldExtractor.getSelector().select(html);`
`}`
`break;`
| e22d6426fc5d7aa523945b1bcabf8ad8c4a46054 | 700898fe8acc7a32c1bdf339bc13beb2625819f1 | https://github.com/code4craft/webmagic/compare/e22d6426fc5d7aa523945b1bcabf8ad8c4a46054...700898fe8acc7a32c1bdf339bc13beb2625819f1 | diff --git a/webmagic-extension/src/main/java/us/codecraft/webmagic/example/GithubRepoApi.java b/webmagic-extension/src/main/java/us/codecraft/webmagic/example/GithubRepoApi.java
index 34608fd9..4181bb9e 100644
--- a/webmagic-extension/src/main/java/us/codecraft/webmagic/example/GithubRepoApi.java
+++ b/webmagic-extension/src/main/java/us/codecraft/webmagic/example/GithubRepoApi.java
@@ -15,19 +15,19 @@ import java.util.List;
*/
public class GithubRepoApi implements HasKey {
- @ExtractBy(type = ExtractBy.Type.JsonPath, value = "$.name")
+ @ExtractBy(type = ExtractBy.Type.JsonPath, value = "$.name", source = ExtractBy.Source.RawText)
private String name;
- @ExtractBy(type = ExtractBy.Type.JsonPath, value = "$..owner.login")
+ @ExtractBy(type = ExtractBy.Type.JsonPath, value = "$..owner.login", source = ExtractBy.Source.RawText)
private String author;
- @ExtractBy(type = ExtractBy.Type.JsonPath, value = "$.language",multi = true)
+ @ExtractBy(type = ExtractBy.Type.JsonPath, value = "$.language",multi = true, source = ExtractBy.Source.RawText)
private List<String> language;
- @ExtractBy(type = ExtractBy.Type.JsonPath, value = "$.stargazers_count")
+ @ExtractBy(type = ExtractBy.Type.JsonPath, value = "$.stargazers_count", source = ExtractBy.Source.RawText)
private int star;
- @ExtractBy(type = ExtractBy.Type.JsonPath, value = "$.homepage")
+ @ExtractBy(type = ExtractBy.Type.JsonPath, value = "$.forks_count", source = ExtractBy.Source.RawText)
private int fork;
@ExtractByUrl
diff --git a/webmagic-extension/src/main/java/us/codecraft/webmagic/model/Extractor.java b/webmagic-extension/src/main/java/us/codecraft/webmagic/model/Extractor.java
index 32f561e2..f1d2f84d 100644
--- a/webmagic-extension/src/main/java/us/codecraft/webmagic/model/Extractor.java
+++ b/webmagic-extension/src/main/java/us/codecraft/webmagic/model/Extractor.java
@@ -17,7 +17,7 @@ class Extractor {
protected final boolean multi;
- static enum Source {Html, Url, RawHtml}
+ static enum Source {Html, Url, RawHtml, RawText}
public Extractor(Selector selector, Source source, boolean notNull, boolean multi) {
this.selector = selector;
diff --git a/webmagic-extension/src/main/java/us/codecraft/webmagic/model/PageModelExtractor.java b/webmagic-extension/src/main/java/us/codecraft/webmagic/model/PageModelExtractor.java
index 9816c714..a1da94bd 100644
--- a/webmagic-extension/src/main/java/us/codecraft/webmagic/model/PageModelExtractor.java
+++ b/webmagic-extension/src/main/java/us/codecraft/webmagic/model/PageModelExtractor.java
@@ -179,7 +179,24 @@ class PageModelExtractor {
ExtractBy extractBy = field.getAnnotation(ExtractBy.class);
if (extractBy != null) {
Selector selector = ExtractorUtils.getSelector(extractBy);
- fieldExtractor = new FieldExtractor(field, selector, extractBy.source() == ExtractBy.Source.RawHtml ? FieldExtractor.Source.RawHtml : FieldExtractor.Source.Html,
+
+ FieldExtractor.Source source = null;
+ switch (extractBy.source()){
+ case RawText:
+ source = FieldExtractor.Source.RawText;
+ break;
+ case RawHtml:
+ source = FieldExtractor.Source.RawHtml;
+ break;
+ case SelectedHtml:
+ source =FieldExtractor.Source.Html;
+ break;
+ default:
+ source =FieldExtractor.Source.Html;
+
+ }
+
+ fieldExtractor = new FieldExtractor(field, selector, source,
extractBy.notNull(), extractBy.multi() || List.class.isAssignableFrom(field.getType()));
Method setterMethod = getSetterMethod(clazz, field);
if (setterMethod != null) {
@@ -284,6 +301,9 @@ class PageModelExtractor {
case Url:
value = fieldExtractor.getSelector().selectList(page.getUrl().toString());
break;
+ case RawText:
+ value = fieldExtractor.getSelector().selectList(page.getRawText());
+ break;
default:
value = fieldExtractor.getSelector().selectList(html);
}
@@ -312,6 +332,9 @@ class PageModelExtractor {
case Url:
value = fieldExtractor.getSelector().select(page.getUrl().toString());
break;
+ case RawText:
+ value = fieldExtractor.getSelector().select(page.getRawText());
+ break;
default:
value = fieldExtractor.getSelector().select(html);
}
diff --git a/webmagic-extension/src/main/java/us/codecraft/webmagic/model/annotation/ExtractBy.java b/webmagic-extension/src/main/java/us/codecraft/webmagic/model/annotation/ExtractBy.java
index 2e23aa00..8e02895a 100644
--- a/webmagic-extension/src/main/java/us/codecraft/webmagic/model/annotation/ExtractBy.java
+++ b/webmagic-extension/src/main/java/us/codecraft/webmagic/model/annotation/ExtractBy.java
@@ -52,7 +52,8 @@ public @interface ExtractBy {
/**
* extract from the raw html
*/
- RawHtml
+ RawHtml,
+ RawText
}
/** | ['webmagic-extension/src/main/java/us/codecraft/webmagic/model/annotation/ExtractBy.java', 'webmagic-extension/src/main/java/us/codecraft/webmagic/model/Extractor.java', 'webmagic-extension/src/main/java/us/codecraft/webmagic/example/GithubRepoApi.java', 'webmagic-extension/src/main/java/us/codecraft/webmagic/model/PageModelExtractor.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 381,299 | 82,028 | 12,966 | 192 | 2,214 | 446 | 40 | 4 | 565 | 27 | 185 | 17 | 0 | 0 | 2016-08-29T09:08:36 | 10,893 | Java | {'Java': 765774, 'HTML': 231706, 'JavaScript': 1777, 'Kotlin': 1371, 'Ruby': 832, 'Groovy': 545, 'Python': 393, 'Shell': 193} | Apache License 2.0 |
8,861 | apache/dolphinscheduler/1445/1441 | apache | dolphinscheduler | https://github.com/apache/dolphinscheduler/issues/1441 | https://github.com/apache/dolphinscheduler/pull/1445 | https://github.com/apache/dolphinscheduler/pull/1445 | 1 | fix | [Feature] add user error when user name contains '.' | **Is your feature request related to a problem? Please describe.**
add a user when user name contains '.'
i think maybe the username regex string is error.
| 5cecc0e6181e3d3c2c971411cf69b73acd8f68c7 | ab9caec50eca3d51bdeecbd517f84a89a1c0d48c | https://github.com/apache/dolphinscheduler/compare/5cecc0e6181e3d3c2c971411cf69b73acd8f68c7...ab9caec50eca3d51bdeecbd517f84a89a1c0d48c | diff --git a/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/Constants.java b/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/Constants.java
index 440446e56..791c0bb55 100644
--- a/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/Constants.java
+++ b/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/Constants.java
@@ -315,7 +315,7 @@ public final class Constants {
/**
* user name regex
*/
- public static final Pattern REGEX_USER_NAME = Pattern.compile("^[a-zA-Z0-9_-]{3,20}$");
+ public static final Pattern REGEX_USER_NAME = Pattern.compile("^[a-zA-Z0-9._-]{3,20}$");
/**
* email regex | ['dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/Constants.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,912,241 | 391,396 | 56,447 | 310 | 186 | 55 | 2 | 1 | 162 | 27 | 34 | 5 | 0 | 0 | 2019-12-11T10:05:11 | 10,886 | Java | {'Java': 10141828, 'TypeScript': 2049856, 'Vue': 1360734, 'PLpgSQL': 62410, 'HCL': 54673, 'SCSS': 52091, 'Shell': 42925, 'Python': 19071, 'Smarty': 13851, 'Dockerfile': 6454, 'Batchfile': 1677, 'Makefile': 1496} | Apache License 2.0 |
8,857 | apache/dolphinscheduler/3957/3956 | apache | dolphinscheduler | https://github.com/apache/dolphinscheduler/issues/3956 | https://github.com/apache/dolphinscheduler/pull/3957 | https://github.com/apache/dolphinscheduler/pull/3957 | 1 | close | [Bug][Master] When running a task, the resource file is lost, which results in an error | When running a shell task, the resource file is lost, which results in an error
TaskParams
Taskparams does not have a resourcelist. When converting, the content of resourcelist will be lost
Not only shell tasks, param parameters in other task types may be overridden
The code is as follows:
VarPoolUtils#setTaskNodeLocalParams
```
/**
* setTaskNodeLocalParams
* @param taskNode taskNode
* @param prop LocalParamName
* @param value LocalParamValue
*/
public static void setTaskNodeLocalParams(TaskNode taskNode, String prop, Object value) {
String taskParamsJson = taskNode.getParams();
TaskParams taskParams = JSONUtils.parseObject(taskParamsJson, TaskParams.class);
if (taskParams == null) {
return;
}
taskParams.setLocalParamValue(prop, value);
taskNode.setParams(JSONUtils.toJsonString(taskParams));
}
```
| 44259688bab684923776b70e04c09f535d01848b | 7dd717af16f374c217f956b7c55d19161580dbd3 | https://github.com/apache/dolphinscheduler/compare/44259688bab684923776b70e04c09f535d01848b...7dd717af16f374c217f956b7c55d19161580dbd3 | diff --git a/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/task/TaskParams.java b/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/task/TaskParams.java
deleted file mode 100644
index abea2d95b..000000000
--- a/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/task/TaskParams.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.dolphinscheduler.common.task;
-
-import java.util.Map;
-
-public class TaskParams {
-
- private String rawScript;
- private Map<String, String>[] localParams;
-
- public void setRawScript(String rawScript) {
- this.rawScript = rawScript;
- }
-
- public void setLocalParams(Map<String, String>[] localParams) {
- this.localParams = localParams;
- }
-
- public String getRawScript() {
- return rawScript;
- }
-
- public void setLocalParamValue(String prop, Object value) {
- if (localParams == null || value == null) {
- return;
- }
- for (int i = 0; i < localParams.length; i++) {
- if (localParams[i].get("prop").equals(prop)) {
- localParams[i].put("value", (String)value);
- }
- }
- }
-
- public void setLocalParamValue(Map<String, Object> propToValue) {
- if (localParams == null || propToValue == null) {
- return;
- }
- for (int i = 0; i < localParams.length; i++) {
- String prop = localParams[i].get("prop");
- if (propToValue.containsKey(prop)) {
- localParams[i].put("value",(String)propToValue.get(prop));
- }
- }
- }
-
- public String getLocalParamValue(String prop) {
- if (localParams == null) {
- return null;
- }
- for (int i = 0; i < localParams.length; i++) {
- String tmpProp = localParams[i].get("prop");
- if (tmpProp.equals(prop)) {
- return localParams[i].get("value");
- }
- }
- return null;
- }
-
- public Map<String, String>[] getLocalParams() {
- return localParams;
- }
-}
\\ No newline at end of file
diff --git a/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/VarPoolUtils.java b/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/VarPoolUtils.java
index 837e96f55..89a8605a9 100644
--- a/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/VarPoolUtils.java
+++ b/dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/VarPoolUtils.java
@@ -18,42 +18,19 @@
package org.apache.dolphinscheduler.common.utils;
import org.apache.dolphinscheduler.common.model.TaskNode;
-import org.apache.dolphinscheduler.common.task.TaskParams;
import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.HashMap;
import java.util.Map;
public class VarPoolUtils {
- /**
- * getTaskNodeLocalParam
- * @param taskNode taskNode
- * @param prop prop
- * @return localParamForProp
- */
- public static Object getTaskNodeLocalParam(TaskNode taskNode, String prop) {
- String taskParamsJson = taskNode.getParams();
- TaskParams taskParams = JSONUtils.parseObject(taskParamsJson, TaskParams.class);
- if (taskParams == null) {
- return null;
- }
- return taskParams.getLocalParamValue(prop);
- }
-
- /**
- * setTaskNodeLocalParams
- * @param taskNode taskNode
- * @param prop LocalParamName
- * @param value LocalParamValue
- */
- public static void setTaskNodeLocalParams(TaskNode taskNode, String prop, Object value) {
- String taskParamsJson = taskNode.getParams();
- TaskParams taskParams = JSONUtils.parseObject(taskParamsJson, TaskParams.class);
- if (taskParams == null) {
- return;
- }
- taskParams.setLocalParamValue(prop, value);
- taskNode.setParams(JSONUtils.toJsonString(taskParams));
- }
+
+ private static final String LOCALPARAMS = "localParams";
+
+ private static final String PROP = "prop";
+
+ private static final String VALUE = "value";
/**
* setTaskNodeLocalParams
@@ -62,11 +39,20 @@ public class VarPoolUtils {
*/
public static void setTaskNodeLocalParams(TaskNode taskNode, Map<String, Object> propToValue) {
String taskParamsJson = taskNode.getParams();
- TaskParams taskParams = JSONUtils.parseObject(taskParamsJson, TaskParams.class);
- if (taskParams == null) {
- return;
+ Map<String,Object> taskParams = JSONUtils.parseObject(taskParamsJson, HashMap.class);
+
+ Object localParamsObject = taskParams.get(LOCALPARAMS);
+ if (null != localParamsObject && null != propToValue && propToValue.size() > 0) {
+ ArrayList<Object> localParams = (ArrayList)localParamsObject;
+ for (int i = 0; i < localParams.size(); i++) {
+ Map<String,String> map = (Map)localParams.get(i);
+ String prop = map.get(PROP);
+ if (StringUtils.isNotEmpty(prop) && propToValue.containsKey(prop)) {
+ map.put(VALUE,(String)propToValue.get(prop));
+ }
+ }
+ taskParams.put(LOCALPARAMS,localParams);
}
- taskParams.setLocalParamValue(propToValue);
taskNode.setParams(JSONUtils.toJsonString(taskParams));
}
diff --git a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/VarPoolUtilsTest.java b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/VarPoolUtilsTest.java
index e47203c22..6713b221b 100644
--- a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/VarPoolUtilsTest.java
+++ b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/VarPoolUtilsTest.java
@@ -19,6 +19,8 @@ package org.apache.dolphinscheduler.common.utils;
import org.apache.dolphinscheduler.common.model.TaskNode;
+import java.util.HashMap;
+import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.junit.Assert;
@@ -29,28 +31,7 @@ import org.slf4j.LoggerFactory;
public class VarPoolUtilsTest {
private static final Logger logger = LoggerFactory.getLogger(VarPoolUtilsTest.class);
-
- @Test
- public void testSetTaskNodeLocalParams() {
- String taskJson = "{\\"conditionResult\\":\\"{\\\\\\"successNode\\\\\\":[\\\\\\"\\\\\\"],\\\\\\"failedNode\\\\\\":[\\\\\\"\\\\\\"]}\\","
- + "\\"conditionsTask\\":false,\\"depList\\":[],\\"dependence\\":\\"{}\\",\\"forbidden\\":false,\\"id\\":\\"tasks-75298\\",\\"maxRetryTimes\\":0,\\"name\\":\\"a1\\","
- + "\\"params\\":\\"{\\\\\\"rawScript\\\\\\":\\\\\\"print(\\\\\\\\\\\\\\"this is python task \\\\\\\\\\\\\\",${p0})\\\\\\","
- + "\\\\\\"localParams\\\\\\":[{\\\\\\"prop\\\\\\":\\\\\\"p1\\\\\\",\\\\\\"direct\\\\\\":\\\\\\"IN\\\\\\",\\\\\\"type\\\\\\":\\\\\\"VARCHAR\\\\\\",\\\\\\"value\\\\\\":\\\\\\"1\\\\\\"}],"
- + "\\\\\\"resourceList\\\\\\":[]}\\",\\"preTasks\\":\\"[]\\",\\"retryInterval\\":1,\\"runFlag\\":\\"NORMAL\\",\\"taskInstancePriority\\":\\"MEDIUM\\","
- + "\\"taskTimeoutParameter\\":{\\"enable\\":false,\\"interval\\":0},\\"timeout\\":\\"{\\\\\\"enable\\\\\\":false,\\\\\\"strategy\\\\\\":\\\\\\"\\\\\\"}\\","
- + "\\"type\\":\\"PYTHON\\",\\"workerGroup\\":\\"default\\"}";
- TaskNode taskNode = JSONUtils.parseObject(taskJson, TaskNode.class);
-
- VarPoolUtils.setTaskNodeLocalParams(taskNode, "p1", "test1");
- Assert.assertEquals(VarPoolUtils.getTaskNodeLocalParam(taskNode, "p1"), "test1");
-
- ConcurrentHashMap<String, Object> propToValue = new ConcurrentHashMap<String, Object>();
- propToValue.put("p1", "test2");
-
- VarPoolUtils.setTaskNodeLocalParams(taskNode, propToValue);
- Assert.assertEquals(VarPoolUtils.getTaskNodeLocalParam(taskNode, "p1"), "test2");
- }
-
+
@Test
public void testConvertVarPoolToMap() throws Exception {
String varPool = "p1,66$VarPool$p2,69$VarPool$";
@@ -70,4 +51,40 @@ public class VarPoolUtilsTest {
+ "print(\\"${{setValue({},{})}}\\".format(\\"p2\\",4));");
logger.info(rawScript);
}
+
+ @Test
+ public void testSetTaskNodeLocalParams() throws Exception {
+ String taskJson = "{\\"id\\":\\"tasks-66199\\",\\"name\\":\\"file-shell\\",\\"desc\\":null,\\"type\\":\\"SHELL\\","
+ + "\\"runFlag\\":\\"NORMAL\\",\\"loc\\":null,\\"maxRetryTimes\\":0,\\"retryInterval\\":1,\\""
+ + "params\\":{\\"rawScript\\":\\"sh n-1/n-1-1/run.sh\\",\\""
+ + "localParams\\":[{\\"prop\\":\\"k1\\",\\"direct\\":\\"IN\\",\\"type\\":\\"VARCHAR\\",\\"value\\":\\"v1\\"},{\\"prop\\":\\"k2\\",\\"direct\\":\\"IN\\",\\"type\\":\\"VARCHAR\\",\\"value\\":\\"v2\\"},"
+ + "{\\"prop\\":\\"k3\\",\\"direct\\":\\"IN\\",\\"type\\":\\"VARCHAR\\",\\"value\\":\\"v3\\"}],\\""
+ + "resourceList\\":[{\\"id\\":\\"dolphinschedule-code\\",\\"res\\":\\"n-1/n-1-1/dolphinscheduler-api-server.log\\"},"
+ + "{\\"id\\":\\"mr-code\\",\\"res\\":\\"n-1/n-1-1/hadoop-mapreduce-examples-2.7.4.jar\\"},"
+ + "{\\"id\\":\\"run\\",\\"res\\":\\"n-1/n-1-1/run.sh\\"}]},\\"preTasks\\":[],\\"extras\\":null,\\"depList\\":[],\\""
+ + "dependence\\":{},\\"conditionResult\\":{\\"successNode\\":[\\"\\"],\\"failedNode\\":[\\"\\"]},\\"taskInstancePriority\\":\\"MEDIUM\\",\\""
+ + "workerGroup\\":\\"default\\",\\"workerGroupId\\":null,\\"timeout\\":{\\"strategy\\":\\"\\",\\"interval\\":null,\\"enable\\":false},\\"delayTime\\":0}";
+ String changeTaskJson = "{\\"id\\":\\"tasks-66199\\",\\"name\\":\\"file-shell\\",\\"desc\\":null,\\"type\\":\\"SHELL\\","
+ + "\\"runFlag\\":\\"NORMAL\\",\\"loc\\":null,\\"maxRetryTimes\\":0,\\"retryInterval\\":1,\\""
+ + "params\\":{\\"rawScript\\":\\"sh n-1/n-1-1/run.sh\\",\\""
+ + "localParams\\":[{\\"prop\\":\\"k1\\",\\"direct\\":\\"IN\\",\\"type\\":\\"VARCHAR\\",\\"value\\":\\"k1-value-change\\"},"
+ + "{\\"prop\\":\\"k2\\",\\"direct\\":\\"IN\\",\\"type\\":\\"VARCHAR\\",\\"value\\":\\"k2-value-change\\"},"
+ + "{\\"prop\\":\\"k3\\",\\"direct\\":\\"IN\\",\\"type\\":\\"VARCHAR\\",\\"value\\":\\"v3\\"}],\\""
+ + "resourceList\\":[{\\"id\\":\\"dolphinschedule-code\\",\\"res\\":\\"n-1/n-1-1/dolphinscheduler-api-server.log\\"},"
+ + "{\\"id\\":\\"mr-code\\",\\"res\\":\\"n-1/n-1-1/hadoop-mapreduce-examples-2.7.4.jar\\"},"
+ + "{\\"id\\":\\"run\\",\\"res\\":\\"n-1/n-1-1/run.sh\\"}]},\\"preTasks\\":[],\\"extras\\":null,\\"depList\\":[],\\""
+ + "dependence\\":{},\\"conditionResult\\":{\\"successNode\\":[\\"\\"],\\"failedNode\\":[\\"\\"]},\\"taskInstancePriority\\":\\"MEDIUM\\",\\""
+ + "workerGroup\\":\\"default\\",\\"workerGroupId\\":null,\\"timeout\\":{\\"strategy\\":\\"\\",\\"interval\\":null,\\"enable\\":false},\\"delayTime\\":0}";
+ Map<String, Object> propToValue = new HashMap<String, Object>();
+ propToValue.put("k1","k1-value-change");
+ propToValue.put("k2","k2-value-change");
+
+ TaskNode taskNode = JSONUtils.parseObject(taskJson,TaskNode.class);
+
+ VarPoolUtils.setTaskNodeLocalParams(taskNode,propToValue);
+
+ Assert.assertEquals(changeTaskJson,JSONUtils.toJsonString(taskNode));
+
+ }
+
} | ['dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/VarPoolUtilsTest.java', 'dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/utils/VarPoolUtils.java', 'dolphinscheduler-common/src/main/java/org/apache/dolphinscheduler/common/task/TaskParams.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 2,839,790 | 576,131 | 82,878 | 522 | 4,892 | 1,057 | 134 | 2 | 935 | 98 | 209 | 28 | 0 | 1 | 2020-10-20T11:27:54 | 10,886 | Java | {'Java': 10141828, 'TypeScript': 2049856, 'Vue': 1360734, 'PLpgSQL': 62410, 'HCL': 54673, 'SCSS': 52091, 'Shell': 42925, 'Python': 19071, 'Smarty': 13851, 'Dockerfile': 6454, 'Batchfile': 1677, 'Makefile': 1496} | Apache License 2.0 |
8,859 | apache/dolphinscheduler/1523/1522 | apache | dolphinscheduler | https://github.com/apache/dolphinscheduler/issues/1522 | https://github.com/apache/dolphinscheduler/pull/1523 | https://github.com/apache/dolphinscheduler/pull/1523 | 2 | fix | MasterSchedulerThread bug | MasterSchedulerThread should not be sleep after handle command
```
if(OSUtils.checkResource(masterConfig.getMasterMaxCpuloadAvg(), masterConfig.getMasterReservedMemory())){
if (zkMasterClient.getZkClient().getState() == CuratorFrameworkState.STARTED) {
// create distributed lock with the root node path of the lock space as /dolphinscheduler/lock/masters
String znodeLock = zkMasterClient.getMasterLockPath();
mutex = new InterProcessMutex(zkMasterClient.getZkClient(), znodeLock);
mutex.acquire();
ThreadPoolExecutor poolExecutor = (ThreadPoolExecutor) masterExecService;
int activeCount = poolExecutor.getActiveCount();
// make sure to scan and delete command table in one transaction
Command command = processDao.findOneCommand();
if (command != null) {
logger.info(String.format("find one command: id: %d, type: %s", command.getId(),command.getCommandType().toString()));
try{
processInstance = processDao.handleCommand(logger, OSUtils.getHost(), this.masterExecThreadNum - activeCount, command);
if (processInstance != null) {
logger.info("start master exec thread , split DAG ...");
masterExecService.execute(new MasterExecThread(processInstance,processDao));
}
}catch (Exception e){
logger.error("scan command error ", e);
processDao.moveToErrorCommand(command, e.toString());
}
}
}
}
// should not sleep here
Thread.sleep(Constants.SLEEP_TIME_MILLIS);
``` | 0567b5829c9ce13d64a13480403ccf6d46cc783a | 1868c56764a380a7dca80429c90b8faf58e2b51f | https://github.com/apache/dolphinscheduler/compare/0567b5829c9ce13d64a13480403ccf6d46cc783a...1868c56764a380a7dca80429c90b8faf58e2b51f | diff --git a/dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/runner/MasterSchedulerThread.java b/dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/runner/MasterSchedulerThread.java
index 69c2304cd..8d7d5a0ad 100644
--- a/dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/runner/MasterSchedulerThread.java
+++ b/dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/runner/MasterSchedulerThread.java
@@ -98,39 +98,41 @@ public class MasterSchedulerThread implements Runnable {
InterProcessMutex mutex = null;
try {
- if(OSUtils.checkResource(masterConfig.getMasterMaxCpuloadAvg(), masterConfig.getMasterReservedMemory())){
- if (zkMasterClient.getZkClient().getState() == CuratorFrameworkState.STARTED) {
-
- // create distributed lock with the root node path of the lock space as /dolphinscheduler/lock/masters
- String znodeLock = zkMasterClient.getMasterLockPath();
-
- mutex = new InterProcessMutex(zkMasterClient.getZkClient(), znodeLock);
- mutex.acquire();
-
- ThreadPoolExecutor poolExecutor = (ThreadPoolExecutor) masterExecService;
- int activeCount = poolExecutor.getActiveCount();
- // make sure to scan and delete command table in one transaction
- Command command = processDao.findOneCommand();
- if (command != null) {
- logger.info(String.format("find one command: id: %d, type: %s", command.getId(),command.getCommandType().toString()));
-
- try{
- processInstance = processDao.handleCommand(logger, OSUtils.getHost(), this.masterExecThreadNum - activeCount, command);
- if (processInstance != null) {
- logger.info("start master exec thread , split DAG ...");
- masterExecService.execute(new MasterExecThread(processInstance,processDao));
- }
- }catch (Exception e){
- logger.error("scan command error ", e);
- processDao.moveToErrorCommand(command, e.toString());
+ boolean runCheckFlag = OSUtils.checkResource(masterConfig.getMasterMaxCpuloadAvg(), masterConfig.getMasterReservedMemory());
+ if(!runCheckFlag) {
+ Thread.sleep(Constants.SLEEP_TIME_MILLIS);
+ continue;
+ }
+ if (zkMasterClient.getZkClient().getState() == CuratorFrameworkState.STARTED) {
+
+ // create distributed lock with the root node path of the lock space as /dolphinscheduler/lock/masters
+ String znodeLock = zkMasterClient.getMasterLockPath();
+
+ mutex = new InterProcessMutex(zkMasterClient.getZkClient(), znodeLock);
+ mutex.acquire();
+
+ ThreadPoolExecutor poolExecutor = (ThreadPoolExecutor) masterExecService;
+ int activeCount = poolExecutor.getActiveCount();
+ // make sure to scan and delete command table in one transaction
+ Command command = processDao.findOneCommand();
+ if (command != null) {
+ logger.info(String.format("find one command: id: %d, type: %s", command.getId(),command.getCommandType().toString()));
+
+ try{
+ processInstance = processDao.handleCommand(logger, OSUtils.getHost(), this.masterExecThreadNum - activeCount, command);
+ if (processInstance != null) {
+ logger.info("start master exec thread , split DAG ...");
+ masterExecService.execute(new MasterExecThread(processInstance,processDao));
}
+ }catch (Exception e){
+ logger.error("scan command error ", e);
+ processDao.moveToErrorCommand(command, e.toString());
}
+ } else{
+ //indicate that no command ,sleep for 1s
+ Thread.sleep(Constants.SLEEP_TIME_MILLIS);
}
}
-
- // accessing the command table every SLEEP_TIME_MILLIS milliseconds
- Thread.sleep(Constants.SLEEP_TIME_MILLIS);
-
}catch (Exception e){
logger.error("master scheduler thread exception : " + e.getMessage(),e);
}finally{ | ['dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/master/runner/MasterSchedulerThread.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,918,542 | 392,870 | 56,658 | 311 | 4,002 | 660 | 60 | 1 | 2,078 | 125 | 329 | 36 | 0 | 1 | 2019-12-19T07:02:30 | 10,886 | Java | {'Java': 10141828, 'TypeScript': 2049856, 'Vue': 1360734, 'PLpgSQL': 62410, 'HCL': 54673, 'SCSS': 52091, 'Shell': 42925, 'Python': 19071, 'Smarty': 13851, 'Dockerfile': 6454, 'Batchfile': 1677, 'Makefile': 1496} | Apache License 2.0 |
8,860 | apache/dolphinscheduler/1516/1515 | apache | dolphinscheduler | https://github.com/apache/dolphinscheduler/issues/1515 | https://github.com/apache/dolphinscheduler/pull/1516 | https://github.com/apache/dolphinscheduler/pull/1516 | 2 | fix | FetchTaskThread minor bug | should not sleep there.
```
boolean runCheckFlag = OSUtils.checkResource(workerConfig.getWorkerMaxCpuloadAvg(), workerConfig.getWorkerReservedMemory()) && checkThreadCount(poolExecutor);
Thread.sleep(Constants.SLEEP_TIME_MILLIS);
if(!runCheckFlag) {
continue;
}
```
i think the right way is :
```
boolean runCheckFlag = OSUtils.checkResource(workerConfig.getWorkerMaxCpuloadAvg(), workerConfig.getWorkerReservedMemory()) && checkThreadCount(poolExecutor);
if(!runCheckFlag) {
Thread.sleep(Constants.SLEEP_TIME_MILLIS);
continue;
}
```
| 38b0765ddfc4ab273352a615604acfc349b316b5 | 947d8044d7101ace1f95f08b511088737eb4ba1e | https://github.com/apache/dolphinscheduler/compare/38b0765ddfc4ab273352a615604acfc349b316b5...947d8044d7101ace1f95f08b511088737eb4ba1e | diff --git a/dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/worker/runner/FetchTaskThread.java b/dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/worker/runner/FetchTaskThread.java
index ae4ee792c..68f27d76d 100644
--- a/dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/worker/runner/FetchTaskThread.java
+++ b/dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/worker/runner/FetchTaskThread.java
@@ -147,9 +147,8 @@ public class FetchTaskThread implements Runnable{
//check memory and cpu usage and threads
boolean runCheckFlag = OSUtils.checkResource(workerConfig.getWorkerMaxCpuloadAvg(), workerConfig.getWorkerReservedMemory()) && checkThreadCount(poolExecutor);
- Thread.sleep(Constants.SLEEP_TIME_MILLIS);
-
if(!runCheckFlag) {
+ Thread.sleep(Constants.SLEEP_TIME_MILLIS);
continue;
}
| ['dolphinscheduler-server/src/main/java/org/apache/dolphinscheduler/server/worker/runner/FetchTaskThread.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,917,047 | 392,512 | 56,612 | 311 | 125 | 22 | 3 | 1 | 686 | 39 | 137 | 21 | 0 | 2 | 2019-12-18T13:01:38 | 10,886 | Java | {'Java': 10141828, 'TypeScript': 2049856, 'Vue': 1360734, 'PLpgSQL': 62410, 'HCL': 54673, 'SCSS': 52091, 'Shell': 42925, 'Python': 19071, 'Smarty': 13851, 'Dockerfile': 6454, 'Batchfile': 1677, 'Makefile': 1496} | Apache License 2.0 |
8,855 | apache/dolphinscheduler/595/594 | apache | dolphinscheduler | https://github.com/apache/dolphinscheduler/issues/594 | https://github.com/apache/dolphinscheduler/pull/595 | https://github.com/apache/dolphinscheduler/issues/594#issuecomment-512710312 | 2 | fix | After the soft kill task, the process still exists (parent process child process)(soft kill task 后 进程依旧存在(父进程 子进程)) |
In the shell script, the task is executed in a multi-threaded manner. The timeout of the task is set to fail. After the timeout, the process of starting the task is executed, but the parent process is not yet killed.
Worker LOG:
[INFO] 2019-07-18 02:03:01.513 cn.escheduler.server.worker.log.TaskLogger:[178] - [taskAppId=TASK_33_552_739] task run command:
Sudo sudo -u rundeck sh /tmp/escheduler/exec/process/5/33/552/739/33_552_739.command
[INFO] 2019-07-18 02:03:01.516 cn.escheduler.server.worker.log.TaskLogger:[178] - [taskAppId=TASK_33_552_739] process start, process id is: 185464
[INFO] 2019-07-18 02:04:18.082 cn.escheduler.server.worker.log.TaskLogger:[188] - [taskAppId=TASK_33_552_739] process has exited, work dir:/tmp/escheduler/exec/process/ 5/33/552/739, pid:185464, exitStatusCode: 0
[INFO] 2019-07-18 02:04:18.083 cn.escheduler.server.worker.runner.TaskScheduleThread:[198] - task : 33_552_739 exit status code : 0
[INFO] 2019-07-18 02:17:15.531 cn.escheduler.server.worker.log.TaskLogger:[178] - [taskAppId=TASK_24_548_737] -> ============== ==========
[INFO] 2019-07-18 02:17:15.531 cn.escheduler.server.worker.log.TaskLogger:[178] - [taskAppId=TASK_24_548_737] cancel process: 170216
[INFO] 2019-07-18 02:17:15.531 cn.escheduler.server.worker.log.TaskLogger:[188] - [taskAppId=TASK_24_548_737] soft kill task:24_548_737, process id:170216, cmd:sudo kill 170216
[WARN] 2019-07-18 02:17:15.533 cn.escheduler.server.worker.log.TaskLogger:[243] - [taskAppId=TASK_24_548_737] process timeout, work dir:/tmp/escheduler/exec/process/3 /24/548/737, pid:170216
[INFO] 2019-07-18 02:17:15.533 cn.escheduler.server.worker.runner.TaskScheduleThread:[198] - task : 24_548_737 exit status code : -1
[INFO] 2019-07-18 02:18:18.758 cn.escheduler.common.queue.TaskQueueZkImpl:[181] - consume task /escheduler/tasks_queue/0_548_2_740
[INFO] 2019-07-18 02:18:18.758 cn.escheduler.common.queue.TaskQueueZkImpl:[188] - consume task: 740,there still have 0 tasks need to be executed
---
shell脚本中使用多线程的方式执行任务, 对任务设定超时失败, 超时后启动任务的进程被执行 kill, 但父进程 并没有被killed 子进程也依旧存在.
Worker LOG:
[INFO] 2019-07-18 02:03:01.513 cn.escheduler.server.worker.log.TaskLogger:[178] - [taskAppId=TASK_33_552_739] task run command:
sudo sudo -u rundeck sh /tmp/escheduler/exec/process/5/33/552/739/33_552_739.command
[INFO] 2019-07-18 02:03:01.516 cn.escheduler.server.worker.log.TaskLogger:[178] - [taskAppId=TASK_33_552_739] process start, process id is: 185464
[INFO] 2019-07-18 02:04:18.082 cn.escheduler.server.worker.log.TaskLogger:[188] - [taskAppId=TASK_33_552_739] process has exited, work dir:/tmp/escheduler/exec/process/5/33/552/739, pid:185464 ,exitStatusCode:0
[INFO] 2019-07-18 02:04:18.083 cn.escheduler.server.worker.runner.TaskScheduleThread:[198] - task : 33_552_739 exit status code : 0
[INFO] 2019-07-18 02:17:15.531 cn.escheduler.server.worker.log.TaskLogger:[178] - [taskAppId=TASK_24_548_737] -> ========================
[INFO] 2019-07-18 02:17:15.531 cn.escheduler.server.worker.log.TaskLogger:[178] - [taskAppId=TASK_24_548_737] cancel process: 170216
[INFO] 2019-07-18 02:17:15.531 cn.escheduler.server.worker.log.TaskLogger:[188] - [taskAppId=TASK_24_548_737] soft kill task:24_548_737, process id:170216, cmd:sudo kill 170216
[WARN] 2019-07-18 02:17:15.533 cn.escheduler.server.worker.log.TaskLogger:[243] - [taskAppId=TASK_24_548_737] process timeout, work dir:/tmp/escheduler/exec/process/3/24/548/737, pid:170216
[INFO] 2019-07-18 02:17:15.533 cn.escheduler.server.worker.runner.TaskScheduleThread:[198] - task : 24_548_737 exit status code : -1
[INFO] 2019-07-18 02:18:18.758 cn.escheduler.common.queue.TaskQueueZkImpl:[181] - consume task /escheduler/tasks_queue/0_548_2_740
[INFO] 2019-07-18 02:18:18.758 cn.escheduler.common.queue.TaskQueueZkImpl:[188] - consume task: 740,there still have 0 tasks need to be executed | cf149c1b7643e4091b3957366664c5a91340742e | c8662bd83606854cdd25e54ac199f156f00fd9fb | https://github.com/apache/dolphinscheduler/compare/cf149c1b7643e4091b3957366664c5a91340742e...c8662bd83606854cdd25e54ac199f156f00fd9fb | diff --git a/escheduler-server/src/main/java/cn/escheduler/server/worker/task/AbstractCommandExecutor.java b/escheduler-server/src/main/java/cn/escheduler/server/worker/task/AbstractCommandExecutor.java
index e3bd40139..82c9be9f0 100644
--- a/escheduler-server/src/main/java/cn/escheduler/server/worker/task/AbstractCommandExecutor.java
+++ b/escheduler-server/src/main/java/cn/escheduler/server/worker/task/AbstractCommandExecutor.java
@@ -162,7 +162,12 @@ public abstract class AbstractCommandExecutor {
exitStatusCode = updateState(processDao, exitStatusCode, pid, taskInstId);
} else {
- cancelApplication();
+ TaskInstance taskInstance = processDao.findTaskInstanceById(taskInstId);
+ if (taskInstance == null) {
+ logger.error("task instance id:{} not exist", taskInstId);
+ } else {
+ ProcessUtils.kill(taskInstance);
+ }
exitStatusCode = -1;
logger.warn("process timeout, work dir:{}, pid:{}", taskDir, pid);
} | ['escheduler-server/src/main/java/cn/escheduler/server/worker/task/AbstractCommandExecutor.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 1,993,988 | 417,189 | 58,378 | 321 | 351 | 57 | 7 | 1 | 3,864 | 320 | 1,375 | 33 | 0 | 0 | 2019-07-18T05:55:00 | 10,886 | Java | {'Java': 10141828, 'TypeScript': 2049856, 'Vue': 1360734, 'PLpgSQL': 62410, 'HCL': 54673, 'SCSS': 52091, 'Shell': 42925, 'Python': 19071, 'Smarty': 13851, 'Dockerfile': 6454, 'Batchfile': 1677, 'Makefile': 1496} | Apache License 2.0 |
8,858 | apache/dolphinscheduler/3402/3680 | apache | dolphinscheduler | https://github.com/apache/dolphinscheduler/issues/3680 | https://github.com/apache/dolphinscheduler/pull/3402 | https://github.com/apache/dolphinscheduler/pull/3402 | 1 | fix | [Bug][API] Zookeeper does not start, printed logs have no error messages, Api services can start but cannot be accessed. | Zookeeper does not start, printed logs have no error messages, Api services can start but cannot be accessed.
Zookeeper没有启动,打印的日志没有错误信息,Api服务能启动但是不能访问。 | 60bf3f851102f1e259a6fa65ee642a0e669b188b | 787845578b6bfdbb7b753f0b517a2e725b945fe4 | https://github.com/apache/dolphinscheduler/compare/60bf3f851102f1e259a6fa65ee642a0e669b188b...787845578b6bfdbb7b753f0b517a2e725b945fe4 | diff --git a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/threadutils/ThreadUtilsTest.java b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/threadutils/ThreadUtilsTest.java
deleted file mode 100644
index 2c76f40c0..000000000
--- a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/threadutils/ThreadUtilsTest.java
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.dolphinscheduler.common.threadutils;
-
-import org.apache.dolphinscheduler.common.thread.Stopper;
-import org.apache.dolphinscheduler.common.thread.ThreadPoolExecutors;
-import org.apache.dolphinscheduler.common.thread.ThreadUtils;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Calendar;
-import java.util.concurrent.*;
-
-import static org.junit.Assert.*;
-
-
-public class ThreadUtilsTest {
- private static final Logger logger = LoggerFactory.getLogger(ThreadUtilsTest.class);
- /**
- * create a naming thread
- */
- @Test
- public void testNewDaemonFixedThreadExecutor() {
- // create core size and max size are all 3
- ExecutorService testExec = ThreadUtils.newDaemonFixedThreadExecutor("test-exec-thread",10);
-
- for (int i = 0; i < 19; i++) {
- final int index = i;
- testExec.submit(() -> {
- System.out.println("do some work index " + index);
- });
- }
- assertFalse(testExec.isShutdown());
- testExec.shutdownNow();
- assertTrue(testExec.isShutdown());
-
- }
-
- /**
- * test schedulerThreadExecutor as for print time in scheduler
- * default check thread is 1
- */
- @Test
- public void testNewDaemonScheduleThreadExecutor() {
-
- ScheduledExecutorService scheduleService = ThreadUtils.newDaemonThreadScheduledExecutor("scheduler-thread", 1);
- Calendar start = Calendar.getInstance();
- Calendar globalTimer = Calendar.getInstance();
- globalTimer.set(2019, Calendar.DECEMBER, 1, 0, 0, 0);
- // current
- Calendar end = Calendar.getInstance();
- end.set(2019, Calendar.DECEMBER, 1, 0, 0, 3);
- Runnable schedulerTask = new Runnable() {
- @Override
- public void run() {
- start.set(2019, Calendar.DECEMBER, 1, 0, 0, 0);
- int index = 0;
- // send heart beat work
- while (start.getTime().getTime() <= end.getTime().getTime()) {
- System.out.println("worker here");
- System.out.println(index ++);
- start.add(Calendar.SECOND, 1);
- globalTimer.add(Calendar.SECOND, 1);
- }
- System.out.println("time is " + System.currentTimeMillis());
- }
- };
- scheduleService.scheduleAtFixedRate(schedulerTask, 2, 10, TimeUnit.SECONDS);
- assertFalse(scheduleService.isShutdown());
- try {
- Thread.sleep(60000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- scheduleService.shutdownNow();
- assertTrue(scheduleService.isShutdown());
- }
-
- /**
- * test stopper is working normal
- */
- @Test
- public void testStopper() {
- assertTrue(Stopper.isRunning());
- Stopper.stop();
- assertTrue(Stopper.isStopped());
- }
-
- /**
- * test threadPoolExecutors with 3 workers and current each 5 tasks
- * @throws InterruptedException
- */
- @Test
- public void testThreadInfo() throws InterruptedException {
- ThreadPoolExecutors workers = ThreadPoolExecutors.getInstance("worker", 3);
- for (int i = 0; i < 5; ++i ) {
- int index = i;
- workers.execute(() -> {
- for (int j = 0; j < 10; ++j) {
- try {
- Thread.sleep(1000);
- System.out.printf("worker %d is doing the task", index);
- System.out.println();
- workers.printStatus();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- });
- workers.submit(() -> {
- for (int j = 0; j < 10; ++j) {
- try {
- Thread.sleep(1000);
- System.out.printf("worker_2 %d is doing the task", index);
- System.out.println();
- workers.printStatus();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- });
- }
- Thread.sleep(50001);
- workers.shutdown();
- }
-
- /**
- * test a single daemon thread pool
- */
- @Test
- public void testNewDaemonSingleThreadExecutor() {
- ExecutorService threadTest = ThreadUtils.newDaemonSingleThreadExecutor("thread_test");
- threadTest.execute(() -> {
- for (int i = 0; i < 100; ++i) {
- System.out.println("daemon working ");
- }
-
- });
- assertFalse(threadTest.isShutdown());
- threadTest.shutdownNow();
- assertTrue(threadTest.isShutdown());
- }
-
- @Test
- public void testNewDaemonCachedThreadPool() {
-
- ThreadPoolExecutor threadPoolExecutor = ThreadUtils.newDaemonCachedThreadPool("threadTest-");
- Thread thread1 = threadPoolExecutor.getThreadFactory().newThread(() -> {
- for (int i = 0; i < 10; ++i) {
- System.out.println("this task is with index " + i );
- }
- });
- assertTrue(thread1.getName().startsWith("threadTest-"));
- assertFalse(threadPoolExecutor.isShutdown());
- threadPoolExecutor.shutdown();
- assertTrue(threadPoolExecutor.isShutdown());
- }
-
- @Test
- public void testNewDaemonCachedThreadPoolWithThreadNumber() {
- ThreadPoolExecutor threadPoolExecutor = ThreadUtils.newDaemonCachedThreadPool("threadTest--", 3, 10);
- for (int i = 0; i < 10; ++ i) {
- threadPoolExecutor.getThreadFactory().newThread(() -> {
- assertEquals(3, threadPoolExecutor.getActiveCount());
- System.out.println("this task is first work to do");
- });
- }
- assertFalse(threadPoolExecutor.isShutdown());
- threadPoolExecutor.shutdown();
- assertTrue(threadPoolExecutor.isShutdown());
- }
-
-
-
-}
diff --git a/dolphinscheduler-service/src/main/java/org/apache/dolphinscheduler/service/zk/CuratorZookeeperClient.java b/dolphinscheduler-service/src/main/java/org/apache/dolphinscheduler/service/zk/CuratorZookeeperClient.java
index c08da0ef7..5a04c5a23 100644
--- a/dolphinscheduler-service/src/main/java/org/apache/dolphinscheduler/service/zk/CuratorZookeeperClient.java
+++ b/dolphinscheduler-service/src/main/java/org/apache/dolphinscheduler/service/zk/CuratorZookeeperClient.java
@@ -24,6 +24,7 @@ import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
+
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
@@ -32,6 +33,7 @@ import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
import java.util.List;
+import java.util.concurrent.TimeUnit;
import static org.apache.dolphinscheduler.common.utils.Preconditions.checkNotNull;
@@ -55,9 +57,10 @@ public class CuratorZookeeperClient implements InitializingBean {
}
private CuratorFramework buildClient() {
- logger.info("zookeeper registry center init, server lists is: {}.", zookeeperConfig.getServerList());
+ logger.info("zookeeper registry center init, server lists is: [{}]", zookeeperConfig.getServerList());
- CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder().ensembleProvider(new DefaultEnsembleProvider(checkNotNull(zookeeperConfig.getServerList(),"zookeeper quorum can't be null")))
+ CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
+ .ensembleProvider(new DefaultEnsembleProvider(checkNotNull(zookeeperConfig.getServerList(), "zookeeper quorum can't be null")))
.retryPolicy(new ExponentialBackoffRetry(zookeeperConfig.getBaseSleepTimeMs(), zookeeperConfig.getMaxRetries(), zookeeperConfig.getMaxSleepMs()));
//these has default value
@@ -84,7 +87,9 @@ public class CuratorZookeeperClient implements InitializingBean {
zkClient = builder.build();
zkClient.start();
try {
- zkClient.blockUntilConnected();
+ logger.info("trying to connect zookeeper server list:{}", zookeeperConfig.getServerList());
+ zkClient.blockUntilConnected(30, TimeUnit.SECONDS);
+
} catch (final Exception ex) {
throw new RuntimeException(ex);
}
@@ -95,12 +100,14 @@ public class CuratorZookeeperClient implements InitializingBean {
checkNotNull(zkClient);
zkClient.getConnectionStateListenable().addListener((client, newState) -> {
- if(newState == ConnectionState.LOST){
+ if (newState == ConnectionState.LOST) {
logger.error("connection lost from zookeeper");
- } else if(newState == ConnectionState.RECONNECTED){
+ } else if (newState == ConnectionState.RECONNECTED) {
logger.info("reconnected to zookeeper");
- } else if(newState == ConnectionState.SUSPENDED){
+ } else if (newState == ConnectionState.SUSPENDED) {
logger.warn("connection SUSPENDED to zookeeper");
+ } else if (newState == ConnectionState.CONNECTED) {
+ logger.info("connected to zookeeper server list:[{}]", zookeeperConfig.getServerList());
}
});
}
diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/zk/CuratorZookeeperClientTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/zk/CuratorZookeeperClientTest.java
index c0297799e..b1c2ec5e2 100644
--- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/zk/CuratorZookeeperClientTest.java
+++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/zk/CuratorZookeeperClientTest.java
@@ -59,9 +59,8 @@ public class CuratorZookeeperClientTest {
zookeeperConfig.setDsRoot("/dolphinscheduler");
zookeeperConfig.setMaxWaitTime(30000);
zookeeperClient.setZookeeperConfig(zookeeperConfig);
- System.out.println("start");
zookeeperClient.afterPropertiesSet();
- System.out.println("end");
+
Assert.assertNotNull(zookeeperClient.getZkClient());
}
}
\\ No newline at end of file | ['dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/zk/CuratorZookeeperClientTest.java', 'dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/threadutils/ThreadUtilsTest.java', 'dolphinscheduler-service/src/main/java/org/apache/dolphinscheduler/service/zk/CuratorZookeeperClient.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 2,839,441 | 576,079 | 82,876 | 522 | 1,456 | 274 | 19 | 1 | 152 | 19 | 50 | 2 | 0 | 0 | 2020-08-04T10:04:56 | 10,886 | Java | {'Java': 10141828, 'TypeScript': 2049856, 'Vue': 1360734, 'PLpgSQL': 62410, 'HCL': 54673, 'SCSS': 52091, 'Shell': 42925, 'Python': 19071, 'Smarty': 13851, 'Dockerfile': 6454, 'Batchfile': 1677, 'Makefile': 1496} | Apache License 2.0 |
1,404 | grpc/grpc-java/1356/1343 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/1343 | https://github.com/grpc/grpc-java/pull/1356 | https://github.com/grpc/grpc-java/pull/1356 | 1 | fixes | Deadline can fire before stream started | In [ClientCallImpl](https://github.com/grpc/grpc-java/blob/master/core/src/main/java/io/grpc/internal/ClientCallImpl.java#L249) the deadline is scheduled before `stream.start()`. However, if the deadline has already elapsed the runnable will be executed immediately and race with the `start`. I've only looked into how OkHttp may be impacted.
I believe [a NullPointerException](https://github.com/grpc/grpc-java/blob/master/core/src/main/java/io/grpc/internal/AbstractClientStream.java#L284) would be thrown when trying to notify the stream listener [due to the cancellation](https://github.com/grpc/grpc-java/blob/master/okhttp/src/main/java/io/grpc/okhttp/OkHttpClientStream.java#L259). However, due to #1237 the exception won't be logged. Thus, this will result in a hung stream that never completes with no logging as to what went wrong.
This was discovered due to timeout_on_sleeping_server on android being flaky, because it uses a very small timeout. The test would fail at [awaitCompletion](https://github.com/grpc/grpc-java/blob/master/android-interop-testing/app/src/main/java/io/grpc/android/integrationtest/InteropTester.java#L735).
@carl-mastrangelo, FYI
| 15d86d9c4238659e2b23a42d7c25fcf8e8a4d7c6 | fe5e624153a7aae4d0295bc318b92daa1c91977d | https://github.com/grpc/grpc-java/compare/15d86d9c4238659e2b23a42d7c25fcf8e8a4d7c6...fe5e624153a7aae4d0295bc318b92daa1c91977d | diff --git a/core/src/main/java/io/grpc/internal/ClientCallImpl.java b/core/src/main/java/io/grpc/internal/ClientCallImpl.java
index cf6acb344..2698476cc 100644
--- a/core/src/main/java/io/grpc/internal/ClientCallImpl.java
+++ b/core/src/main/java/io/grpc/internal/ClientCallImpl.java
@@ -85,6 +85,7 @@ final class ClientCallImpl<ReqT, RespT> extends ClientCall<ReqT, RespT>
private final CallOptions callOptions;
private ClientStream stream;
private volatile ScheduledFuture<?> deadlineCancellationFuture;
+ private volatile boolean deadlineCancellationFutureShouldBeCancelled;
private boolean cancelCalled;
private boolean halfCloseCalled;
private final ClientTransportProvider clientTransportProvider;
@@ -243,14 +244,23 @@ final class ClientCallImpl<ReqT, RespT> extends ClientCall<ReqT, RespT>
stream.setMessageCompression(true);
}
+ stream.start(new ClientStreamListenerImpl(observer, transportFuture));
+ // Delay any sources of cancellation after start(), because most of the transports are broken if
+ // they receive cancel before start. Issue #1343 has more details
+
// Start the deadline timer after stream creation because it will close the stream
Long timeoutNanos = getRemainingTimeoutNanos(callOptions.getDeadlineNanoTime());
if (timeoutNanos != null) {
deadlineCancellationFuture = startDeadlineTimer(timeoutNanos);
+ if (deadlineCancellationFutureShouldBeCancelled) {
+ // Race detected! ClientStreamListener.closed may have been called before
+ // deadlineCancellationFuture was set, thereby preventing the future from being cancelled.
+ // Go ahead and cancel again, just to be sure it was cancelled.
+ deadlineCancellationFuture.cancel(false);
+ }
}
// Propagate later Context cancellation to the remote side.
this.context.addListener(this, MoreExecutors.directExecutor());
- stream.start(new ClientStreamListenerImpl(observer, transportFuture));
}
/**
@@ -445,6 +455,7 @@ final class ClientCallImpl<ReqT, RespT> extends ClientCall<ReqT, RespT>
public final void runInContext() {
try {
closed = true;
+ deadlineCancellationFutureShouldBeCancelled = true;
// manually optimize the volatile read
ScheduledFuture<?> future = deadlineCancellationFuture;
if (future != null) {
diff --git a/interop-testing/src/main/java/io/grpc/testing/integration/AbstractTransportTest.java b/interop-testing/src/main/java/io/grpc/testing/integration/AbstractTransportTest.java
index 43d08c57a..14d914f06 100644
--- a/interop-testing/src/main/java/io/grpc/testing/integration/AbstractTransportTest.java
+++ b/interop-testing/src/main/java/io/grpc/testing/integration/AbstractTransportTest.java
@@ -658,6 +658,28 @@ public abstract class AbstractTransportTest {
assertEquals(Status.DEADLINE_EXCEEDED, Status.fromThrowable(recorder.getError()));
}
+ @Test(timeout = 10000)
+ public void deadlineInPast() throws Exception {
+ // Test once with idle channel and once with active channel
+ try {
+ TestServiceGrpc.newBlockingStub(channel)
+ .withDeadlineAfter(-10, TimeUnit.SECONDS)
+ .emptyCall(Empty.getDefaultInstance());
+ } catch (StatusRuntimeException ex) {
+ assertEquals(Status.Code.DEADLINE_EXCEEDED, ex.getStatus().getCode());
+ }
+
+ // warm up the channel
+ blockingStub.emptyCall(Empty.getDefaultInstance());
+ try {
+ TestServiceGrpc.newBlockingStub(channel)
+ .withDeadlineAfter(-10, TimeUnit.SECONDS)
+ .emptyCall(Empty.getDefaultInstance());
+ } catch (StatusRuntimeException ex) {
+ assertEquals(Status.Code.DEADLINE_EXCEEDED, ex.getStatus().getCode());
+ }
+ }
+
protected int unaryPayloadLength() {
// 10MiB.
return 10485760; | ['core/src/main/java/io/grpc/internal/ClientCallImpl.java', 'interop-testing/src/main/java/io/grpc/testing/integration/AbstractTransportTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 2,434,049 | 526,447 | 68,849 | 299 | 1,655 | 318 | 35 | 2 | 1,171 | 106 | 259 | 8 | 4 | 0 | 2016-01-25T19:14:46 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,398 | grpc/grpc-java/1671/1657 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/1657 | https://github.com/grpc/grpc-java/pull/1671 | https://github.com/grpc/grpc-java/pull/1671 | 1 | resolves | OutOfBounds exception with NameResolvers and TransportSet | Long story short, it appears there's an explicit array.get(0) that happens on the first outbound call, but if the NameResolver hasn't found any servers yet, this causes an exception. Stack trace can be found below(SpectatorInterceptor is a proprietary metrics component, and the EurekaNameResolver simply uses Eureka to resolve a set of IP + port that can then be used to load balance). In the case below, the list of servers the EurekaNameResolver passes to onUpdate is empty.
```
SEVERE: Exception while executing runnable io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$2@7d8bd17e
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at java.util.Collections$UnmodifiableList.get(Collections.java:1309)
at io.grpc.internal.TransportSet.scheduleConnection(TransportSet.java:197)
at io.grpc.internal.TransportSet.obtainActiveTransport(TransportSet.java:169)
at io.grpc.internal.ManagedChannelImpl$3.getTransport(ManagedChannelImpl.java:381)
at io.grpc.SimpleLoadBalancerFactory$SimpleLoadBalancer$1.get(SimpleLoadBalancerFactory.java:121)
at io.grpc.SimpleLoadBalancerFactory$SimpleLoadBalancer$1.get(SimpleLoadBalancerFactory.java:119)
at io.grpc.internal.BlankFutureProvider$FulfillmentBatch.link(BlankFutureProvider.java:128)
at io.grpc.SimpleLoadBalancerFactory$SimpleLoadBalancer.handleResolvedAddresses(SimpleLoadBalancerFactory.java:119)
at io.grpc.internal.ManagedChannelImpl$2.onUpdate(ManagedChannelImpl.java:165)
at com.netflix.grpc.nameresolver.eureka.EurekaNameResolver$1.onNext(EurekaNameResolver.java:64)
at com.netflix.grpc.nameresolver.eureka.EurekaNameResolver$1.onNext(EurekaNameResolver.java:61)
at io.grpc.stub.ClientCalls$StreamObserverToCallListenerAdapter.onMessage(ClientCalls.java:305)
at io.grpc.ForwardingClientCallListener.onMessage(ForwardingClientCallListener.java:51)
at io.grpc.ForwardingClientCallListener.onMessage(ForwardingClientCallListener.java:51)
at com.netflix.grpc.interceptor.spectator.SpectatorMetricsClientInterceptor$1$1.onMessage(SpectatorMetricsClientInterceptor.java:44)
at io.grpc.internal.ClientCallImpl$ClientStreamListenerImpl$2.runInContext(ClientCallImpl.java:423)
at io.grpc.internal.ContextRunnable.run(ContextRunnable.java:54)
at io.grpc.internal.SerializingExecutor$TaskRunner.run(SerializingExecutor.java:154)
at java.util.concurrent.ThreadPoolExecutorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
```
| 51fd870cfd4b30f65477d51016a1781139f21c04 | 7659f6ed689ad7b18071925dbea796989e591125 | https://github.com/grpc/grpc-java/compare/51fd870cfd4b30f65477d51016a1781139f21c04...7659f6ed689ad7b18071925dbea796989e591125 | diff --git a/core/src/main/java/io/grpc/EquivalentAddressGroup.java b/core/src/main/java/io/grpc/EquivalentAddressGroup.java
index ef64a90be..49efbbf6a 100644
--- a/core/src/main/java/io/grpc/EquivalentAddressGroup.java
+++ b/core/src/main/java/io/grpc/EquivalentAddressGroup.java
@@ -31,6 +31,8 @@
package io.grpc;
+import com.google.common.base.Preconditions;
+
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Collections;
@@ -49,6 +51,7 @@ public final class EquivalentAddressGroup {
private final List<SocketAddress> addrs;
public EquivalentAddressGroup(List<SocketAddress> addrs) {
+ Preconditions.checkArgument(!addrs.isEmpty(), "addrs is empty");
this.addrs = Collections.unmodifiableList(new ArrayList<SocketAddress>(addrs));
}
diff --git a/core/src/main/java/io/grpc/LoadBalancer.java b/core/src/main/java/io/grpc/LoadBalancer.java
index fbc2f7991..fec3ae222 100644
--- a/core/src/main/java/io/grpc/LoadBalancer.java
+++ b/core/src/main/java/io/grpc/LoadBalancer.java
@@ -68,6 +68,9 @@ public abstract class LoadBalancer<T> {
* Handles newly resolved addresses and service config from name resolution system.
*
* <p>Implementations should not modify the given {@code servers}.
+ *
+ * @param servers the resolved server addresses. Never empty.
+ * @param config extra configuration data from naming system.
*/
public void handleResolvedAddresses(List<ResolvedServerInfo> servers, Attributes config) { }
diff --git a/core/src/main/java/io/grpc/NameResolver.java b/core/src/main/java/io/grpc/NameResolver.java
index b6c8e4d12..3e5210743 100644
--- a/core/src/main/java/io/grpc/NameResolver.java
+++ b/core/src/main/java/io/grpc/NameResolver.java
@@ -119,6 +119,9 @@ public abstract class NameResolver {
* Handles updates on resolved addresses and config.
*
* <p>Implementations will not modify the given {@code servers}.
+ *
+ * @param servers the resolved server addresses. An empty list will trigger {@link #onError}
+ * @param config extra configuration data from naming system
*/
void onUpdate(List<ResolvedServerInfo> servers, Attributes config);
diff --git a/core/src/main/java/io/grpc/internal/ManagedChannelImpl.java b/core/src/main/java/io/grpc/internal/ManagedChannelImpl.java
index 82f903a85..284cba4b1 100644
--- a/core/src/main/java/io/grpc/internal/ManagedChannelImpl.java
+++ b/core/src/main/java/io/grpc/internal/ManagedChannelImpl.java
@@ -168,7 +168,11 @@ public final class ManagedChannelImpl extends ManagedChannel implements WithLogI
this.nameResolver.start(new NameResolver.Listener() {
@Override
public void onUpdate(List<ResolvedServerInfo> servers, Attributes config) {
- loadBalancer.handleResolvedAddresses(servers, config);
+ if (servers.isEmpty()) {
+ onError(Status.UNAVAILABLE.withDescription("NameResolver returned an empty list"));
+ } else {
+ loadBalancer.handleResolvedAddresses(servers, config);
+ }
}
@Override
diff --git a/core/src/test/java/io/grpc/internal/ManagedChannelImplTest.java b/core/src/test/java/io/grpc/internal/ManagedChannelImplTest.java
index ed49239d7..ad75482e1 100644
--- a/core/src/test/java/io/grpc/internal/ManagedChannelImplTest.java
+++ b/core/src/test/java/io/grpc/internal/ManagedChannelImplTest.java
@@ -362,6 +362,27 @@ public class ManagedChannelImplTest {
Status status = statusCaptor.getValue();
assertSame(error.getCode(), status.getCode());
assertSame(error.getCause(), status.getCause());
+ assertEquals(1, loadBalancerFactory.balancers.size());
+ verify(loadBalancerFactory.balancers.get(0)).handleNameResolutionError(same(error));
+ }
+
+ @Test
+ public void nameResolverReturnsEmptyList() {
+ String errorDescription = "NameResolver returned an empty list";
+ ManagedChannel channel = createChannel(
+ new FakeNameResolverFactory(new ArrayList<ResolvedServerInfo>()), NO_INTERCEPTOR);
+ ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT);
+ call.start(mockCallListener, new Metadata());
+ ArgumentCaptor<Status> statusCaptor = ArgumentCaptor.forClass(Status.class);
+ verify(mockCallListener, timeout(1000)).onClose(statusCaptor.capture(), any(Metadata.class));
+ Status status = statusCaptor.getValue();
+ assertSame(Status.Code.UNAVAILABLE, status.getCode());
+ assertTrue(status.getDescription(), status.getDescription().contains(errorDescription));
+ assertEquals(1, loadBalancerFactory.balancers.size());
+ verify(loadBalancerFactory.balancers.get(0)).handleNameResolutionError(statusCaptor.capture());
+ status = statusCaptor.getValue();
+ assertSame(Status.Code.UNAVAILABLE, status.getCode());
+ assertEquals(errorDescription, status.getDescription());
}
@Test | ['core/src/main/java/io/grpc/NameResolver.java', 'core/src/test/java/io/grpc/internal/ManagedChannelImplTest.java', 'core/src/main/java/io/grpc/EquivalentAddressGroup.java', 'core/src/main/java/io/grpc/internal/ManagedChannelImpl.java', 'core/src/main/java/io/grpc/LoadBalancer.java'] | {'.java': 5} | 5 | 5 | 0 | 0 | 5 | 3,219,946 | 687,505 | 89,543 | 292 | 710 | 135 | 15 | 4 | 2,683 | 136 | 619 | 30 | 0 | 1 | 2016-04-14T18:21:38 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,403 | grpc/grpc-java/1379/1225 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/1225 | https://github.com/grpc/grpc-java/pull/1379 | https://github.com/grpc/grpc-java/pull/1379 | 1 | fixes | NPE in ProtoInputStream.drainTo | ```
java.lang.NullPointerException: null
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:210)
at com.google.common.io.ByteStreams.copy(ByteStreams.java:65)
at io.grpc.protobuf.ProtoInputStream.drainTo(ProtoInputStream.java:74)
at io.grpc.internal.MessageFramer.writeToOutputStream(MessageFramer.java:224)
at io.grpc.internal.MessageFramer.writeKnownLength(MessageFramer.java:185)
at io.grpc.internal.MessageFramer.writeUncompressed(MessageFramer.java:135)
at io.grpc.internal.MessageFramer.writePayload(MessageFramer.java:125)
at io.grpc.internal.AbstractStream.writeMessage(AbstractStream.java:165)
at io.grpc.internal.ClientCallImpl.sendMessage(ClientCallImpl.java:204)
at com.google.cloud.bigtable.grpc.io.ReconnectingChannel$DelayingCall.sendMessage(ReconnectingChannel.java:122)
at io.grpc.ForwardingClientCall.sendMessage(ForwardingClientCall.java:65)
```
It looks like if you call `drainTo()` twice then it will NPE. Calling `drainTo()` twice is sort of strange, so I wouldn't expect this to be critical, but we should still not NPE.
| e475d388b929b6bf3b48d83d5a8bfb442fb5e5e4 | 4573836df97a5d66b78bcfe0523dac729881f78e | https://github.com/grpc/grpc-java/compare/e475d388b929b6bf3b48d83d5a8bfb442fb5e5e4...4573836df97a5d66b78bcfe0523dac729881f78e | diff --git a/protobuf/src/main/java/io/grpc/protobuf/ProtoInputStream.java b/protobuf/src/main/java/io/grpc/protobuf/ProtoInputStream.java
index d5ebae188..186e3c12e 100644
--- a/protobuf/src/main/java/io/grpc/protobuf/ProtoInputStream.java
+++ b/protobuf/src/main/java/io/grpc/protobuf/ProtoInputStream.java
@@ -70,9 +70,11 @@ class ProtoInputStream extends InputStream implements Drainable, KnownLength {
written = message.getSerializedSize();
message.writeTo(target);
message = null;
- } else {
+ } else if (partial != null) {
written = (int) ByteStreams.copy(partial, target);
partial = null;
+ } else {
+ written = 0;
}
return written;
}
diff --git a/protobuf/src/test/java/io/grpc/protobuf/ProtoUtilsTest.java b/protobuf/src/test/java/io/grpc/protobuf/ProtoUtilsTest.java
index 7fc93e023..7858568c5 100644
--- a/protobuf/src/test/java/io/grpc/protobuf/ProtoUtilsTest.java
+++ b/protobuf/src/test/java/io/grpc/protobuf/ProtoUtilsTest.java
@@ -41,6 +41,7 @@ import com.google.protobuf.Empty;
import com.google.protobuf.Enum;
import com.google.protobuf.Type;
+import io.grpc.Drainable;
import io.grpc.MethodDescriptor.Marshaller;
import org.junit.Test;
@@ -48,6 +49,7 @@ import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
@@ -115,4 +117,46 @@ public class ProtoUtilsTest {
assertEquals(-1, is.read());
assertEquals(0, is.available());
}
+
+ @Test
+ public void testDrainTo_all() throws Exception {
+ byte[] golden = ByteStreams.toByteArray(marshaller.stream(proto));
+ InputStream is = marshaller.stream(proto);
+ Drainable d = (Drainable) is;
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ int drained = d.drainTo(baos);
+ assertEquals(baos.size(), drained);
+ assertArrayEquals(golden, baos.toByteArray());
+ assertEquals(0, is.available());
+ }
+
+ @Test
+ public void testDrainTo_partial() throws Exception {
+ final byte[] golden;
+ {
+ InputStream is = marshaller.stream(proto);
+ is.read();
+ golden = ByteStreams.toByteArray(is);
+ }
+ InputStream is = marshaller.stream(proto);
+ is.read();
+ Drainable d = (Drainable) is;
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ int drained = d.drainTo(baos);
+ assertEquals(baos.size(), drained);
+ assertArrayEquals(golden, baos.toByteArray());
+ assertEquals(0, is.available());
+ }
+
+ @Test
+ public void testDrainTo_none() throws Exception {
+ byte[] golden = ByteStreams.toByteArray(marshaller.stream(proto));
+ InputStream is = marshaller.stream(proto);
+ ByteStreams.toByteArray(is);
+ Drainable d = (Drainable) is;
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ assertEquals(0, d.drainTo(baos));
+ assertArrayEquals(new byte[0], baos.toByteArray());
+ assertEquals(0, is.available());
+ }
} | ['protobuf/src/main/java/io/grpc/protobuf/ProtoInputStream.java', 'protobuf/src/test/java/io/grpc/protobuf/ProtoUtilsTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 2,433,678 | 526,633 | 68,911 | 299 | 82 | 24 | 4 | 1 | 1,154 | 59 | 254 | 17 | 0 | 1 | 2016-02-01T23:17:24 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |
1,402 | grpc/grpc-java/1402/1401 | grpc | grpc-java | https://github.com/grpc/grpc-java/issues/1401 | https://github.com/grpc/grpc-java/pull/1402 | https://github.com/grpc/grpc-java/pull/1402 | 1 | fixes | ProtocolNegotiators leaks ByteBufs on failure | As reported by @trask in #1277 with repro repo at https://github.com/trask/grpc-netty-leak-repro. The key distinguishing feature is `BufferUntilChannelActiveHandler` in the log here:
```
SEVERE: LEAK: ByteBuf.release() was not called before it's garbage-collected. See http://netty.io/wiki/reference-counted-objects.html for more information.
Recent access records: 2
#2:
Hint: 'ProtocolNegotiators$BufferUntilChannelActiveHandler#0' will handle the message from this point.
```
When looking at the code, it is obvious it doesn't release when it fails the promise. This leak only happens when failing to establish a connection to the server.
| 52bd63f88e281162cddc1f4ecd4b66e4e5e36460 | 5b9726ea7dade0952d64796178dc0bdfd134d16d | https://github.com/grpc/grpc-java/compare/52bd63f88e281162cddc1f4ecd4b66e4e5e36460...5b9726ea7dade0952d64796178dc0bdfd134d16d | diff --git a/netty/src/main/java/io/grpc/netty/ProtocolNegotiators.java b/netty/src/main/java/io/grpc/netty/ProtocolNegotiators.java
index d4b96c946..6414f1dba 100644
--- a/netty/src/main/java/io/grpc/netty/ProtocolNegotiators.java
+++ b/netty/src/main/java/io/grpc/netty/ProtocolNegotiators.java
@@ -60,6 +60,7 @@ import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.ssl.SslHandshakeCompletionEvent;
import io.netty.util.AsciiString;
+import io.netty.util.ReferenceCountUtil;
import java.net.URI;
import java.util.ArrayDeque;
@@ -388,6 +389,7 @@ public final class ProtocolNegotiators {
*/
if (failCause != null) {
promise.setFailure(failCause);
+ ReferenceCountUtil.release(msg);
} else if (bufferedWrites == null) {
super.write(ctx, msg, promise);
} else {
@@ -424,6 +426,7 @@ public final class ProtocolNegotiators {
while (!bufferedWrites.isEmpty()) {
ChannelWrite write = bufferedWrites.poll();
write.promise.setFailure(cause);
+ ReferenceCountUtil.release(write.msg);
}
bufferedWrites = null;
} | ['netty/src/main/java/io/grpc/netty/ProtocolNegotiators.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 2,433,539 | 526,690 | 68,912 | 299 | 133 | 23 | 3 | 1 | 652 | 80 | 155 | 11 | 2 | 1 | 2016-02-10T00:35:46 | 10,705 | Java | {'Java': 11734252, 'Shell': 64137, 'C++': 50003, 'Starlark': 45373, 'Batchfile': 6230, 'Dockerfile': 3878, 'Python': 1961} | Apache License 2.0 |