Commit 3594c092ea647f92742ef9ba9b4b0af8d575333f
1 parent
eb82cbf7
Exists in
master
-Removida validação customizada do projeto Core e movida para componente
Demoiselle Validation. -Inserida dependência para teste do Demoiselle Validation -Criação de testes usando validação de beans.
Showing
7 changed files
with
120 additions
and
196 deletions
Show diff stats
impl/core/pom.xml
... | ... | @@ -77,15 +77,6 @@ |
77 | 77 | <scope>import</scope> |
78 | 78 | <type>pom</type> |
79 | 79 | </dependency> |
80 | - <!-- | |
81 | - <dependency> | |
82 | - <groupId>org.jboss.arquillian</groupId> | |
83 | - <artifactId>arquillian-bom</artifactId> | |
84 | - <version>${arquillian.version}</version> | |
85 | - <scope>import</scope> | |
86 | - <type>pom</type> | |
87 | - </dependency> | |
88 | - --> | |
89 | 80 | </dependencies> |
90 | 81 | </dependencyManagement> |
91 | 82 | |
... | ... | @@ -248,6 +239,13 @@ |
248 | 239 | <artifactId>slf4j-log4j12</artifactId> |
249 | 240 | <scope>test</scope> |
250 | 241 | </dependency> |
242 | + | |
243 | + <dependency> | |
244 | + <groupId>br.gov.frameworkdemoiselle.component</groupId> | |
245 | + <artifactId>demoiselle-validation</artifactId> | |
246 | + <scope>test</scope> | |
247 | + <version>${demoiselle.validation.version}</version> | |
248 | + </dependency> | |
251 | 249 | </dependencies> |
252 | 250 | |
253 | 251 | <repositories> |
... | ... | @@ -279,5 +277,6 @@ |
279 | 277 | <!-- |
280 | 278 | <jacoco.version>0.6.0.201210061924</jacoco.version> |
281 | 279 | --> |
280 | + <demoiselle.validation.version>2.4.0-BETA2-SNAPSHOT</demoiselle.validation.version> | |
282 | 281 | </properties> |
283 | 282 | </project> | ... | ... |
impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/management/Management.java
... | ... | @@ -40,11 +40,16 @@ import java.lang.reflect.Method; |
40 | 40 | import java.util.ArrayList; |
41 | 41 | import java.util.Collection; |
42 | 42 | import java.util.List; |
43 | +import java.util.Set; | |
43 | 44 | |
44 | 45 | import javax.enterprise.context.ApplicationScoped; |
45 | 46 | import javax.enterprise.context.RequestScoped; |
46 | 47 | import javax.inject.Inject; |
47 | 48 | import javax.management.ReflectionException; |
49 | +import javax.validation.ConstraintViolation; | |
50 | +import javax.validation.Validation; | |
51 | +import javax.validation.ValidationException; | |
52 | +import javax.validation.Validator; | |
48 | 53 | |
49 | 54 | import org.slf4j.Logger; |
50 | 55 | |
... | ... | @@ -78,6 +83,8 @@ public class Management { |
78 | 83 | private ResourceBundle bundle; |
79 | 84 | |
80 | 85 | private final List<ManagedType> managedTypes = new ArrayList<ManagedType>(); |
86 | + | |
87 | + private Validator validator; | |
81 | 88 | |
82 | 89 | public void addManagedType(ManagedType managedType) { |
83 | 90 | managedTypes.add(managedType); |
... | ... | @@ -215,12 +222,31 @@ public class Management { |
215 | 222 | "management-debug-setting-property", method.getName(), |
216 | 223 | managedType.getType().getCanonicalName())); |
217 | 224 | |
218 | - // Obtém uma instância da classe gerenciada, lembrando que | |
219 | - // classes | |
220 | - // anotadas com @ManagementController são sempre singletons. | |
221 | 225 | activateContexts(managedType.getType()); |
222 | 226 | try { |
227 | + // Obtém uma instância da classe gerenciada, lembrando que | |
228 | + // classes | |
229 | + // anotadas com @ManagementController são sempre singletons. | |
223 | 230 | Object delegate = Beans.getReference(managedType.getType()); |
231 | + | |
232 | + //Se houver um validador anexado à propriedade alterada, executa o validador sobre | |
233 | + //o novo valor. | |
234 | + Validator validator = getDefaultValidator(); | |
235 | + if (validator!=null){ | |
236 | + Set<?> violations = validator.validateValue(managedType.getType(), propertyName, newValue); | |
237 | + if (violations.size()>0){ | |
238 | + StringBuffer errorBuffer = new StringBuffer(); | |
239 | + for (Object objectViolation : violations){ | |
240 | + ConstraintViolation<?> violation = (ConstraintViolation<?>) objectViolation; | |
241 | + errorBuffer.append(violation.getMessage()).append('\r').append('\n'); | |
242 | + } | |
243 | + | |
244 | + throw new DemoiselleException(bundle.getString("validation-constraint-violation",managedType.getType().getCanonicalName(),errorBuffer.toString())); | |
245 | + } | |
246 | + } | |
247 | + else{ | |
248 | + logger.warn(bundle.getString("validation-validator-not-found")); | |
249 | + } | |
224 | 250 | |
225 | 251 | Method getterMethod = managedType.getFields().get(propertyName).getGetterMethod(); |
226 | 252 | Object oldValue; |
... | ... | @@ -244,6 +270,8 @@ public class Management { |
244 | 270 | , newValue); |
245 | 271 | notificationManager.sendNotification(notification); |
246 | 272 | |
273 | + } catch (DemoiselleException de){ | |
274 | + throw de; | |
247 | 275 | } catch (Exception e) { |
248 | 276 | throw new DemoiselleException(bundle.getString( |
249 | 277 | "management-invoke-error", method.getName()), e); |
... | ... | @@ -306,5 +334,18 @@ public class Management { |
306 | 334 | } |
307 | 335 | |
308 | 336 | } |
337 | + | |
338 | + private Validator getDefaultValidator(){ | |
339 | + if (validator == null){ | |
340 | + try{ | |
341 | + this.validator = Validation.buildDefaultValidatorFactory().getValidator(); | |
342 | + } | |
343 | + catch(ValidationException e){ | |
344 | + this.validator = null; | |
345 | + } | |
346 | + } | |
347 | + | |
348 | + return this.validator; | |
349 | + } | |
309 | 350 | |
310 | 351 | } | ... | ... |
impl/core/src/main/java/br/gov/frameworkdemoiselle/internal/validation/AllowedValuesValidator.java
... | ... | @@ -1,104 +0,0 @@ |
1 | -/* | |
2 | - * Demoiselle Framework | |
3 | - * Copyright (C) 2010 SERPRO | |
4 | - * ---------------------------------------------------------------------------- | |
5 | - * This file is part of Demoiselle Framework. | |
6 | - * | |
7 | - * Demoiselle Framework is free software; you can redistribute it and/or | |
8 | - * modify it under the terms of the GNU Lesser General Public License version 3 | |
9 | - * as published by the Free Software Foundation. | |
10 | - * | |
11 | - * This program is distributed in the hope that it will be useful, | |
12 | - * but WITHOUT ANY WARRANTY; without even the implied warranty of | |
13 | - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
14 | - * GNU General Public License for more details. | |
15 | - * | |
16 | - * You should have received a copy of the GNU Lesser General Public License version 3 | |
17 | - * along with this program; if not, see <http://www.gnu.org/licenses/> | |
18 | - * or write to the Free Software Foundation, Inc., 51 Franklin Street, | |
19 | - * Fifth Floor, Boston, MA 02110-1301, USA. | |
20 | - * ---------------------------------------------------------------------------- | |
21 | - * Este arquivo é parte do Framework Demoiselle. | |
22 | - * | |
23 | - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou | |
24 | - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação | |
25 | - * do Software Livre (FSF). | |
26 | - * | |
27 | - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA | |
28 | - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou | |
29 | - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português | |
30 | - * para maiores detalhes. | |
31 | - * | |
32 | - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título | |
33 | - * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> | |
34 | - * ou escreva para a Fundação do Software Livre (FSF) Inc., | |
35 | - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. | |
36 | - */ | |
37 | -package br.gov.frameworkdemoiselle.internal.validation; | |
38 | - | |
39 | -import java.math.BigDecimal; | |
40 | - | |
41 | -import javax.validation.ConstraintValidator; | |
42 | -import javax.validation.ConstraintValidatorContext; | |
43 | - | |
44 | -import br.gov.frameworkdemoiselle.validation.AllowedValues; | |
45 | - | |
46 | - | |
47 | -public class AllowedValuesValidator implements ConstraintValidator<AllowedValues, Object> { | |
48 | - | |
49 | - private br.gov.frameworkdemoiselle.validation.AllowedValues.ValueType valueType; | |
50 | - private String[] allowedValues; | |
51 | - | |
52 | - @Override | |
53 | - public void initialize(AllowedValues constraintAnnotation) { | |
54 | - valueType = constraintAnnotation.valueType(); | |
55 | - allowedValues = constraintAnnotation.allows(); | |
56 | - } | |
57 | - | |
58 | - @Override | |
59 | - public boolean isValid(Object value, ConstraintValidatorContext context) { | |
60 | - | |
61 | - if (value==null){ | |
62 | - return false; | |
63 | - } | |
64 | - | |
65 | - switch(valueType){ | |
66 | - case STRING: | |
67 | - for (String str : allowedValues){ | |
68 | - if (str.equals(value)) return true; | |
69 | - } | |
70 | - return false; | |
71 | - | |
72 | - case INTEGER: | |
73 | - try{ | |
74 | - Integer number = Integer.valueOf(value.toString()); | |
75 | - String strNumber = number.toString(); | |
76 | - for (String str : allowedValues){ | |
77 | - if (str.equals(strNumber)) return true; | |
78 | - } | |
79 | - | |
80 | - return false; | |
81 | - } | |
82 | - catch(NumberFormatException ne){ | |
83 | - return false; | |
84 | - } | |
85 | - | |
86 | - case DECIMAL: | |
87 | - try{ | |
88 | - BigDecimal number = new BigDecimal(value.toString()); | |
89 | - String strNumber = number.toString(); | |
90 | - for (String str : allowedValues){ | |
91 | - if (str.equals(strNumber)) return true; | |
92 | - } | |
93 | - } | |
94 | - catch(NumberFormatException ne){ | |
95 | - return false; | |
96 | - } | |
97 | - | |
98 | - return false; | |
99 | - } | |
100 | - | |
101 | - return false; | |
102 | - } | |
103 | - | |
104 | -} |
impl/core/src/main/java/br/gov/frameworkdemoiselle/validation/AllowedValues.java
... | ... | @@ -1,76 +0,0 @@ |
1 | -/* | |
2 | - * Demoiselle Framework | |
3 | - * Copyright (C) 2010 SERPRO | |
4 | - * ---------------------------------------------------------------------------- | |
5 | - * This file is part of Demoiselle Framework. | |
6 | - * | |
7 | - * Demoiselle Framework is free software; you can redistribute it and/or | |
8 | - * modify it under the terms of the GNU Lesser General Public License version 3 | |
9 | - * as published by the Free Software Foundation. | |
10 | - * | |
11 | - * This program is distributed in the hope that it will be useful, | |
12 | - * but WITHOUT ANY WARRANTY; without even the implied warranty of | |
13 | - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
14 | - * GNU General Public License for more details. | |
15 | - * | |
16 | - * You should have received a copy of the GNU Lesser General Public License version 3 | |
17 | - * along with this program; if not, see <http://www.gnu.org/licenses/> | |
18 | - * or write to the Free Software Foundation, Inc., 51 Franklin Street, | |
19 | - * Fifth Floor, Boston, MA 02110-1301, USA. | |
20 | - * ---------------------------------------------------------------------------- | |
21 | - * Este arquivo é parte do Framework Demoiselle. | |
22 | - * | |
23 | - * O Framework Demoiselle é um software livre; você pode redistribuí-lo e/ou | |
24 | - * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação | |
25 | - * do Software Livre (FSF). | |
26 | - * | |
27 | - * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA | |
28 | - * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou | |
29 | - * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português | |
30 | - * para maiores detalhes. | |
31 | - * | |
32 | - * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título | |
33 | - * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/> | |
34 | - * ou escreva para a Fundação do Software Livre (FSF) Inc., | |
35 | - * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA. | |
36 | - */ | |
37 | -package br.gov.frameworkdemoiselle.validation; | |
38 | - | |
39 | -import static java.lang.annotation.ElementType.FIELD; | |
40 | -import static java.lang.annotation.RetentionPolicy.RUNTIME; | |
41 | - | |
42 | -import java.lang.annotation.Documented; | |
43 | -import java.lang.annotation.Retention; | |
44 | -import java.lang.annotation.Target; | |
45 | - | |
46 | -import javax.validation.Constraint; | |
47 | - | |
48 | -import br.gov.frameworkdemoiselle.internal.validation.AllowedValuesValidator; | |
49 | - | |
50 | -@Documented | |
51 | -@Target({ FIELD}) | |
52 | -@Retention(RUNTIME) | |
53 | -@Constraint(validatedBy = AllowedValuesValidator.class) | |
54 | -/** | |
55 | - * Validate a value against a list of allowed values. | |
56 | - * | |
57 | - * @author serpro | |
58 | - * | |
59 | - */ | |
60 | -public @interface AllowedValues { | |
61 | - | |
62 | - /** | |
63 | - * List of accepted values | |
64 | - */ | |
65 | - String[] allows(); | |
66 | - | |
67 | - /** | |
68 | - * Type of allowed values. Defaults to {@link ValueType#STRING}. | |
69 | - */ | |
70 | - ValueType valueType() default ValueType.STRING; | |
71 | - | |
72 | - enum ValueType { | |
73 | - STRING,INTEGER,DECIMAL; | |
74 | - } | |
75 | - | |
76 | -} |
impl/core/src/main/resources/demoiselle-core-bundle.properties
... | ... | @@ -113,4 +113,6 @@ management-debug-starting-custom-context=Levantando contexto {0} para executar c |
113 | 113 | management-debug-stoping-custom-context=Desligando contexto {0} para classe gerenciada {1} |
114 | 114 | management-debug-registering-managed-type=Registrando classe gerenciada [{0}] |
115 | 115 | management-debug-processing-management-extension=Processando extens\u00E3o de gerenciamento [{0}] |
116 | -management-debug-removing-management-extension=Desativando extens\u00E3o de gerenciamento [{0}] | |
117 | 116 | \ No newline at end of file |
117 | +management-debug-removing-management-extension=Desativando extens\u00E3o de gerenciamento [{0}] | |
118 | + | |
119 | +validation-validator-not-found=Nenhum provedor de valida\u00E7\u00E3o de beans encontrado, as anota\u00E7\u00F5es de valida\u00E7\u00E3o n\u00E3o ser\u00E3o processadas | ... | ... |
impl/core/src/test/java/management/ValidationTestCase.java
0 → 100644
... | ... | @@ -0,0 +1,62 @@ |
1 | +package management; | |
2 | + | |
3 | +import java.io.File; | |
4 | + | |
5 | +import management.testclasses.DummyManagedClass; | |
6 | +import management.testclasses.DummyManagementExtension; | |
7 | +import management.testclasses.ManagedClassStore; | |
8 | + | |
9 | +import org.jboss.arquillian.container.test.api.Deployment; | |
10 | +import org.jboss.arquillian.junit.Arquillian; | |
11 | +import org.jboss.shrinkwrap.api.ShrinkWrap; | |
12 | +import org.jboss.shrinkwrap.api.asset.FileAsset; | |
13 | +import org.jboss.shrinkwrap.api.spec.JavaArchive; | |
14 | +import org.junit.Assert; | |
15 | +import org.junit.Test; | |
16 | +import org.junit.runner.RunWith; | |
17 | + | |
18 | +import test.LocaleProducer; | |
19 | +import br.gov.frameworkdemoiselle.DemoiselleException; | |
20 | +import br.gov.frameworkdemoiselle.util.Beans; | |
21 | + | |
22 | +@RunWith(Arquillian.class) | |
23 | +public class ValidationTestCase { | |
24 | + | |
25 | + @Deployment | |
26 | + public static JavaArchive createDeployment() { | |
27 | + return ShrinkWrap | |
28 | + .create(JavaArchive.class) | |
29 | + .addClass(LocaleProducer.class) | |
30 | + .addPackages(true, "br") | |
31 | + .addAsResource(new FileAsset(new File("src/test/resources/test/beans.xml")), "beans.xml") | |
32 | + .addAsManifestResource( | |
33 | + new File("src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension"), | |
34 | + "services/javax.enterprise.inject.spi.Extension") | |
35 | + .addPackages(false, NotificationTestCase.class.getPackage()) | |
36 | + .addClasses(DummyManagementExtension.class,ManagedClassStore.class,DummyManagedClass.class); | |
37 | + } | |
38 | + | |
39 | + /** | |
40 | + * Test if changing properties of a management controller passes through | |
41 | + * validation phase. | |
42 | + */ | |
43 | + @Test | |
44 | + public void testManagedClassValidation(){ | |
45 | + | |
46 | + //Testa se é possível definir um valor válido para uma propriedade. | |
47 | + ManagedClassStore store = Beans.getReference(ManagedClassStore.class); | |
48 | + store.setProperty(DummyManagedClass.class, "id", new Integer(1)); | |
49 | + Assert.assertEquals(new Integer(1), store.getProperty(DummyManagedClass.class, "id")); | |
50 | + | |
51 | + //Testa se definir um valor inválido dispara o erro adequado | |
52 | + try{ | |
53 | + store.setProperty(DummyManagedClass.class, "id", new Integer(5)); | |
54 | + Assert.fail(); | |
55 | + } | |
56 | + catch(DemoiselleException e){ | |
57 | + //SUCCESS | |
58 | + } | |
59 | + | |
60 | + } | |
61 | + | |
62 | +} | ... | ... |
impl/core/src/test/java/management/testclasses/DummyManagedClass.java
... | ... | @@ -41,8 +41,8 @@ import java.util.UUID; |
41 | 41 | import br.gov.frameworkdemoiselle.annotation.ManagedOperation; |
42 | 42 | import br.gov.frameworkdemoiselle.annotation.ManagedProperty; |
43 | 43 | import br.gov.frameworkdemoiselle.stereotype.ManagementController; |
44 | -import br.gov.frameworkdemoiselle.validation.AllowedValues; | |
45 | -import br.gov.frameworkdemoiselle.validation.AllowedValues.ValueType; | |
44 | +import br.gov.frameworkdemoiselle.validation.annotation.AllowedValues; | |
45 | +import br.gov.frameworkdemoiselle.validation.annotation.AllowedValues.ValueType; | |
46 | 46 | |
47 | 47 | @ManagementController |
48 | 48 | public class DummyManagedClass { |
... | ... | @@ -51,7 +51,7 @@ public class DummyManagedClass { |
51 | 51 | private String name; |
52 | 52 | |
53 | 53 | @ManagedProperty |
54 | - @AllowedValues(allows={"f","m","F","M"},valueType=ValueType.INTEGER) | |
54 | + @AllowedValues(allows={"1","2","3","4"},valueType=ValueType.INTEGER) | |
55 | 55 | private Integer id; |
56 | 56 | |
57 | 57 | @ManagedProperty | ... | ... |