Skip to content

Commit

Permalink
WFLY-2176 Add the CDI-enabled ValidatorFactory to the servlet context…
Browse files Browse the repository at this point in the history
… so it can be used by JSF when bootstrapping bean validation.
  • Loading branch information
fjuma authored and jaikiran committed Oct 5, 2013
1 parent 72bd4e9 commit 68a98b0
Show file tree
Hide file tree
Showing 11 changed files with 459 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/

package org.jboss.as.jsf.deployment;

import static javax.faces.validator.BeanValidator.VALIDATOR_FACTORY_KEY;

import javax.validation.ValidatorFactory;

import org.jboss.as.ee.beanvalidation.BeanValidationAttachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.web.common.ServletContextAttribute;

/**
* Deployment processor that adds the CDI-enabled ValidatorFactory to the servlet context.
*
* @author Farah Juma
*/
public class JSFBeanValidationFactoryProcessor implements DeploymentUnitProcessor {

@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();

// Get the CDI-enabled ValidatorFactory and add it to the servlet context
ValidatorFactory validatorFactory = deploymentUnit.getAttachment(BeanValidationAttachments.VALIDATOR_FACTORY);

deploymentUnit.addToAttachmentList(ServletContextAttribute.ATTACHMENT_KEY,
new ServletContextAttribute(VALIDATOR_FACTORY_KEY, validatorFactory));
}

@Override
public void undeploy(DeploymentUnit context) {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ public class JSFDependencyProcessor implements DeploymentUnitProcessor {
public static final String IS_CDI_PARAM = "org.jboss.jbossfaces.IS_CDI";

private static final ModuleIdentifier JSF_SUBSYSTEM = ModuleIdentifier.create("org.jboss.as.jsf");
private static final ModuleIdentifier BEAN_VALIDATION = ModuleIdentifier.create("org.hibernate.validator");
private static final ModuleIdentifier JSTL = ModuleIdentifier.create("javax.servlet.jstl.api");

private JSFModuleIdFactory moduleIdFactory = JSFModuleIdFactory.getInstance();
Expand Down Expand Up @@ -96,7 +95,6 @@ public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitPro
}

moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, JSTL, false, false, false, false));
moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, BEAN_VALIDATION, false, false, true, false));
moduleSpecification.addSystemDependency(new ModuleDependency(moduleLoader, JSF_SUBSYSTEM, false, false, true, false));

addJSFInjection(jsfVersion, moduleSpecification, moduleLoader);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.ServiceVerificationHandler;
import org.jboss.as.jsf.deployment.JSFAnnotationProcessor;
import org.jboss.as.jsf.deployment.JSFBeanValidationFactoryProcessor;
import org.jboss.as.jsf.deployment.JSFDependencyProcessor;
import org.jboss.as.jsf.deployment.JSFManagedBeanProcessor;
import org.jboss.as.jsf.deployment.JSFSharedTldsProcessor;
Expand Down Expand Up @@ -63,6 +64,7 @@ protected void execute(DeploymentProcessorTarget processorTarget) {
processorTarget.addDeploymentProcessor(JSFExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_JSF, new JSFDependencyProcessor());
processorTarget.addDeploymentProcessor(JSFExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_JSF_MANAGED_BEANS, new JSFManagedBeanProcessor());
processorTarget.addDeploymentProcessor(JSFExtension.SUBSYSTEM_NAME, Phase.INSTALL, Phase.INSTALL_JSF_ANNOTATIONS, new JSFAnnotationProcessor());
processorTarget.addDeploymentProcessor(JSFExtension.SUBSYSTEM_NAME, Phase.INSTALL, Phase.INSTALL_JSF_VALIDATOR_FACTORY, new JSFBeanValidationFactoryProcessor());
}
}, OperationContext.Stage.RUNTIME);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,7 @@ public AttachmentKey<?> getPhaseKey() {
public static final int INSTALL_SERVLET_INIT_DEPLOYMENT = 0x1300;
public static final int INSTALL_JAXRS_DEPLOYMENT = 0x1500;
public static final int INSTALL_JSF_ANNOTATIONS = 0x1600;
public static final int INSTALL_JSF_VALIDATOR_FACTORY = 0x1700;
public static final int INSTALL_JDBC_DRIVER = 0x1800;
public static final int INSTALL_TRANSACTION_BINDINGS = 0x1900;
public static final int INSTALL_WELD_DEPLOYMENT = 0x1B00;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.beanvalidation.cdi;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
* Tests for the integration of JSF, CDI, and Bean Validation.
*
* @author Farah Juma
*/
@RunWith(Arquillian.class)
@RunAsClient
public class BeanValidationCdiIntegrationTestCase {
@ArquillianResource
private URL url;

private final Pattern viewStatePattern = Pattern.compile("id=\".*javax.faces.ViewState.*\" value=\"([^\"]*)\"");
private final Pattern nameErrorPattern = Pattern.compile("<div id=\"nameError\">([^<]+)</div>");
private final Pattern numberErrorPattern = Pattern.compile("<div id=\"numberError\">([^<]+)</div>");

@Deployment(testable = false)
public static Archive<?> deploy() {
WebArchive war = ShrinkWrap.create(WebArchive.class, "registration-jsf.war");
war.addPackage(BeanValidationCdiIntegrationTestCase.class.getPackage());
war.addAsWebResource(BeanValidationCdiIntegrationTestCase.class.getPackage(), "register.xhtml", "register.xhtml");
war.addAsWebResource(BeanValidationCdiIntegrationTestCase.class.getPackage(), "confirmation.xhtml", "confirmation.xhtml");
war.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
return war;
}

@Test
public void testSuccessfulBeanValidation() throws Exception {
String responseString = registerTeam("Team1", 6);

Matcher errorMatcher = nameErrorPattern.matcher(responseString);
assertTrue(!errorMatcher.find());

errorMatcher = numberErrorPattern.matcher(responseString);
assertTrue(!errorMatcher.find());
}

@Test
public void testFailingBeanValidation() throws Exception {
String nameError = null;
String numberError = null;
String responseString = registerTeam("", 1);

Matcher errorMatcher = nameErrorPattern.matcher(responseString);
if (errorMatcher.find()) {
nameError = errorMatcher.group(1).trim();
}

errorMatcher = numberErrorPattern.matcher(responseString);
if (errorMatcher.find()) {
numberError = errorMatcher.group(1).trim();
}

assertEquals("Team name must be at least 3 characters.", nameError);
assertEquals("Not enough people for a team.", numberError);
}

private String registerTeam(String name, int numberOfPeople) throws Exception {
DefaultHttpClient client = new DefaultHttpClient();

try {
// Create and execute a GET request
String jsfViewState = null;
String requestUrl = url.toString() + "register.jsf";
HttpGet getRequest = new HttpGet(requestUrl);
HttpResponse response = client.execute(getRequest);
try {
String responseString = IOUtils.toString(response.getEntity().getContent(), "UTF-8");

// Get the JSF view state
Matcher jsfViewMatcher = viewStatePattern.matcher(responseString);
if (jsfViewMatcher.find()) {
jsfViewState = jsfViewMatcher.group(1);
}
} finally {
HttpClientUtils.closeQuietly(response);
}

// Create and execute a POST request with the given team name and
// the given number of people
HttpPost post = new HttpPost(requestUrl);

List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("javax.faces.ViewState", jsfViewState));
list.add(new BasicNameValuePair("register", "register"));
list.add(new BasicNameValuePair("register:inputName", name));
list.add(new BasicNameValuePair("register:inputNumber", Integer.toString(numberOfPeople)));
list.add(new BasicNameValuePair("register:registerButton", "Register"));

post.setEntity(new StringEntity(URLEncodedUtils.format(list, "UTF-8"), ContentType.APPLICATION_FORM_URLENCODED));
response = client.execute(post);

try {
return IOUtils.toString(response.getEntity().getContent(), "UTF-8");
} finally {
HttpClientUtils.closeQuietly(response);
}
} finally {
HttpClientUtils.closeQuietly(client);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.beanvalidation.cdi;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

/**
* A custom constraint that uses CDI in its validator class.
*
* @author Farah Juma
*/
@Constraint(validatedBy = CustomMinValidator.class)
@Documented
@Target({ METHOD, FIELD, TYPE, PARAMETER })
@Retention(RUNTIME)
public @interface CustomMin {
String message() default "Not enough people for a team.";

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.beanvalidation.cdi;

import javax.inject.Inject;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
* A validator that uses constructor injection.
*
* @author Farah Juma
*/
public class CustomMinValidator implements ConstraintValidator<CustomMin, Integer> {

private final MinimumValueProvider minimumValueProvider;

@Inject
public CustomMinValidator(MinimumValueProvider minimumValueProvider) {
this.minimumValueProvider = minimumValueProvider;
}

@Override
public void initialize(CustomMin constraintAnnotation) {
}

@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
return value >= minimumValueProvider.getMin();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.test.integration.jsf.beanvalidation.cdi;

/**
* Provides a minimum value for the number of people for a Team instance.
*
* @author Farah Juma
*/
public class MinimumValueProvider {

public int getMin() {
return 3;
}
}
Loading

0 comments on commit 68a98b0

Please sign in to comment.