Fix issue with optional CDI in BV module (#4574)

Fixes #4542

Signed-off-by: jansupol <jan.supol@oracle.com>
diff --git a/ext/bean-validation/src/main/java/org/glassfish/jersey/server/validation/internal/ValidationBinder.java b/ext/bean-validation/src/main/java/org/glassfish/jersey/server/validation/internal/ValidationBinder.java
index 4369f2a..445ab53 100644
--- a/ext/bean-validation/src/main/java/org/glassfish/jersey/server/validation/internal/ValidationBinder.java
+++ b/ext/bean-validation/src/main/java/org/glassfish/jersey/server/validation/internal/ValidationBinder.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2018 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2020 Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2018, 2019 Payara Foundation and/or its affiliates. All rights reserved.
  *
  * This program and the accompanying materials are made available under the
@@ -18,7 +18,6 @@
 package org.glassfish.jersey.server.validation.internal;
 
 import java.security.AccessController;
-import java.security.PrivilegedAction;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.WeakHashMap;
@@ -259,9 +258,8 @@
         private ValidatorContext getDefaultValidatorContext(final ValidateOnExecutionHandler handler) {
             final ValidatorContext context = factory.usingContext();
 
-            // if CDI is available use composite factiry
-            if (AccessController.doPrivileged(
-                    ReflectionHelper.classForNamePA("javax.enterprise.inject.spi.BeanManager")) != null) {
+            // if CDI is available use composite factory
+            if (isCDIAvailable()) {
                 // Composite Configuration - due to PAYARA-2491
                 // https://github.com/payara/Payara/issues/2245
                 context.constraintValidatorFactory(resourceContext.getResource(
@@ -277,6 +275,15 @@
             return context;
         }
 
+        private boolean isCDIAvailable() {
+            // Both CDI & Jersey CDI modules must be available
+            return AccessController.doPrivileged(
+                        ReflectionHelper.classForNamePA("javax.enterprise.inject.spi.BeanManager")) != null
+                   &&
+                   AccessController.doPrivileged(
+                        ReflectionHelper.classForNamePA("org.glassfish.jersey.ext.cdi1x.internal.CdiUtil")) != null;
+        }
+
         /**
          * Create traversable resolver able to process {@link javax.validation.executable.ValidateOnExecution} annotation on
          * beans.
diff --git a/tests/integration/jersey-4542/pom.xml b/tests/integration/jersey-4542/pom.xml
new file mode 100644
index 0000000..d031098
--- /dev/null
+++ b/tests/integration/jersey-4542/pom.xml
@@ -0,0 +1,59 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Public License v. 2.0, which is available at
+    http://www.eclipse.org/legal/epl-2.0.
+
+    This Source Code may also be made available under the following Secondary
+    Licenses when the conditions for such availability set forth in the
+    Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
+    version 2 with the GNU Classpath Exception, which is available at
+    https://www.gnu.org/software/classpath/license.html.
+
+    SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
+
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <parent>
+        <artifactId>project</artifactId>
+        <groupId>org.glassfish.jersey.tests.integration</groupId>
+        <version>2.32.0-SNAPSHOT</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+
+    <artifactId>jersey-4542</artifactId>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.glassfish.jersey.ext</groupId>
+            <artifactId>jersey-bean-validation</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.glassfish.jersey.test-framework.providers</groupId>
+            <artifactId>jersey-test-framework-provider-grizzly2</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.glassfish.jersey.test-framework.providers</groupId>
+            <artifactId>jersey-test-framework-provider-external</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.glassfish.jersey.test-framework</groupId>
+            <artifactId>jersey-test-framework-core</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.jboss.weld.se</groupId>
+            <artifactId>weld-se-core</artifactId>
+            <scope>test</scope>
+        </dependency>
+    </dependencies>
+
+</project>
\ No newline at end of file
diff --git a/tests/integration/jersey-4542/src/main/java/org.glassfish.jersey.tests.integration.jersey4542/ValidationInflector.java b/tests/integration/jersey-4542/src/main/java/org.glassfish.jersey.tests.integration.jersey4542/ValidationInflector.java
new file mode 100644
index 0000000..61934e0
--- /dev/null
+++ b/tests/integration/jersey-4542/src/main/java/org.glassfish.jersey.tests.integration.jersey4542/ValidationInflector.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v. 2.0, which is available at
+ * http://www.eclipse.org/legal/epl-2.0.
+ *
+ * This Source Code may also be made available under the following Secondary
+ * Licenses when the conditions for such availability set forth in the
+ * Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
+ * version 2 with the GNU Classpath Exception, which is available at
+ * https://www.gnu.org/software/classpath/license.html.
+ *
+ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
+ */
+
+package org.glassfish.jersey.tests.integration.jersey4542;
+
+import java.io.IOException;
+
+import javax.ws.rs.container.ContainerRequestContext;
+
+import javax.validation.constraints.NotNull;
+
+import org.glassfish.jersey.message.internal.ReaderWriter;
+import org.glassfish.jersey.process.Inflector;
+
+/**
+ * @author Michal Gajdos
+ */
+public class ValidationInflector implements Inflector<ContainerRequestContext, String> {
+
+    @NotNull
+    @Override
+    public String apply(final ContainerRequestContext requestContext) {
+        return get(requestContext);
+    }
+
+    @NotNull
+    public String get(@NotNull final ContainerRequestContext requestContext) {
+        try {
+            final String entity = ReaderWriter.readFromAsString(
+                    requestContext.getEntityStream(),
+                    requestContext.getMediaType());
+
+            return entity.isEmpty() ? null : entity;
+        } catch (IOException e) {
+            return "error";
+        }
+    }
+}
diff --git a/tests/integration/jersey-4542/src/test/java/org.glassfish.jersey.tests.integration.jersey4542/ProgrammaticValidationTest.java b/tests/integration/jersey-4542/src/test/java/org.glassfish.jersey.tests.integration.jersey4542/ProgrammaticValidationTest.java
new file mode 100644
index 0000000..ba34e63
--- /dev/null
+++ b/tests/integration/jersey-4542/src/test/java/org.glassfish.jersey.tests.integration.jersey4542/ProgrammaticValidationTest.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v. 2.0, which is available at
+ * http://www.eclipse.org/legal/epl-2.0.
+ *
+ * This Source Code may also be made available under the following Secondary
+ * Licenses when the conditions for such availability set forth in the
+ * Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
+ * version 2 with the GNU Classpath Exception, which is available at
+ * https://www.gnu.org/software/classpath/license.html.
+ *
+ * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
+ */
+
+package org.glassfish.jersey.tests.integration.jersey4542;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.Application;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.glassfish.jersey.inject.hk2.Hk2InjectionManagerFactory;
+import org.glassfish.jersey.logging.LoggingFeature;
+import org.glassfish.jersey.server.ResourceConfig;
+import org.glassfish.jersey.server.model.Resource;
+import org.glassfish.jersey.test.JerseyTest;
+
+import static org.junit.Assert.assertEquals;
+
+import org.glassfish.jersey.test.external.ExternalTestContainerFactory;
+import org.jboss.weld.environment.se.Weld;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Bean Validation tests for programmatically created resources.
+ *
+ * @author Michal Gajdos
+ */
+public class ProgrammaticValidationTest extends JerseyTest {
+
+    Weld weld;
+
+    @Before
+    public void setup() {
+        Assume.assumeTrue(Hk2InjectionManagerFactory.isImmediateStrategy());
+    }
+
+    @Override
+    public void setUp() throws Exception {
+        if (Hk2InjectionManagerFactory.isImmediateStrategy()) {
+            if (!ExternalTestContainerFactory.class.isAssignableFrom(getTestContainerFactory().getClass())) {
+                weld = new Weld();
+                weld.initialize();
+            }
+            super.setUp();
+        }
+    }
+
+    @Override
+    public void tearDown() throws Exception {
+        if (Hk2InjectionManagerFactory.isImmediateStrategy()) {
+            if (!ExternalTestContainerFactory.class.isAssignableFrom(getTestContainerFactory().getClass())) {
+                weld.shutdown();
+            }
+            super.tearDown();
+        }
+    }
+
+    @Override
+    protected Application configure() {
+        final Set<Resource> resources = new HashSet<>();
+
+        Resource.Builder resourceBuilder = Resource.builder("class");
+        resourceBuilder
+                .addMethod("POST")
+                .handledBy(ValidationInflector.class);
+        resources.add(resourceBuilder.build());
+
+        return new ResourceConfig().register(LoggingFeature.class).registerResources(resources);
+    }
+
+    @Test
+    public void testInflectorClass() throws Exception {
+        final Response response = target("class").request().post(Entity.entity("value", MediaType.TEXT_PLAIN_TYPE));
+
+        assertEquals(200, response.getStatus());
+        assertEquals("value", response.readEntity(String.class));
+    }
+
+    @Test
+    public void testInflectorClassNegative() throws Exception {
+        final Response response = target("class").request().post(Entity.entity(null, MediaType.TEXT_PLAIN_TYPE));
+
+        assertEquals(500, response.getStatus());
+    }
+}
diff --git a/tests/integration/jersey-4542/src/test/resources/META-INF/beans.xml b/tests/integration/jersey-4542/src/test/resources/META-INF/beans.xml
new file mode 100644
index 0000000..d773c46
--- /dev/null
+++ b/tests/integration/jersey-4542/src/test/resources/META-INF/beans.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+    Copyright (c) 2020 Oracle and/or its affiliates. All rights reserved.
+
+    This program and the accompanying materials are made available under the
+    terms of the Eclipse Public License v. 2.0, which is available at
+    http://www.eclipse.org/legal/epl-2.0.
+
+    This Source Code may also be made available under the following Secondary
+    Licenses when the conditions for such availability set forth in the
+    Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
+    version 2 with the GNU Classpath Exception, which is available at
+    https://www.gnu.org/software/classpath/license.html.
+
+    SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
+
+-->
+
+<beans/>
\ No newline at end of file
diff --git a/tests/integration/pom.xml b/tests/integration/pom.xml
index 31714df..0b722a7 100644
--- a/tests/integration/pom.xml
+++ b/tests/integration/pom.xml
@@ -86,6 +86,7 @@
         <module>jersey-4099</module>
         <module>jersey-4321</module>
         <module>jersey-4507</module>
+        <module>jersey-4542</module>
         <module>jetty-response-close</module>
         <module>microprofile</module>
         <module>portability-jersey-1</module>