Nuiton-utils-commits
Threads by month
- ----- 2026 -----
- June
- May
- April
- March
- February
- January
- ----- 2025 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2011 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2010 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2009 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2008 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2007 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2006 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2005 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2004 -----
- December
- November
- October
- September
- August
January 2011
- 5 participants
- 66 discussions
r2021 - in trunk/nuiton-utils/src: main/java/org/nuiton/util/rmi test/java/org/nuiton/util test/java/org/nuiton/util/rmi
by athimel@users.nuiton.org 19 Jan '11
by athimel@users.nuiton.org 19 Jan '11
19 Jan '11
Author: athimel
Date: 2011-01-19 17:45:00 +0100 (Wed, 19 Jan 2011)
New Revision: 2021
Url: http://nuiton.org/repositories/revision/nuiton-utils/2021
Log:
Evolution #1209 : Add a method to unregister a service ; Implement tests
Added:
trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/
trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/AnyException.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/RmiExporterAndProxyTest.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/TestBean.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/TestService.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/TestServiceImpl.java
Modified:
trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteProxyFactory.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/ServiceExporter.java
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteProxyFactory.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteProxyFactory.java 2011-01-18 07:06:31 UTC (rev 2020)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteProxyFactory.java 2011-01-19 16:45:00 UTC (rev 2021)
@@ -1,23 +1,23 @@
/*
* #%L
* Nuiton Utils
- * *
+ *
* $Id$
* $HeadURL$
* %%
* Copyright (C) 2004 - 2010 CodeLutin
* %%
* This program 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 3 of the
+ * it under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
- *
+ *
* This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
+ *
+ * You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
@@ -47,7 +47,7 @@
// TODO AThimel 12/01/2011 This settings has to be externalized
protected final static int PORT = 12345;
- protected final static String REGISTRY_IP = "10.1.1.85";
+ protected final static String REGISTRY_IP = "127.0.0.1";
/**
* Create a RMI proxy on the wanted service interface. The default RMI name
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/ServiceExporter.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/ServiceExporter.java 2011-01-18 07:06:31 UTC (rev 2020)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/ServiceExporter.java 2011-01-19 16:45:00 UTC (rev 2021)
@@ -1,23 +1,23 @@
/*
* #%L
* Nuiton Utils
- * *
+ *
* $Id$
* $HeadURL$
* %%
* Copyright (C) 2004 - 2010 CodeLutin
* %%
* This program 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 3 of the
+ * it under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
- *
+ *
* This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
+ *
+ * You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
@@ -28,6 +28,7 @@
import org.apache.commons.logging.LogFactory;
import java.rmi.ConnectException;
+import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
@@ -41,7 +42,7 @@
*
* @author Arnaud Thimel <thimel(a)codelutin.com>
*/
-public class ServiceExporter {
+public final class ServiceExporter {
private final static Log log = LogFactory.getLog(ServiceExporter.class);
@@ -51,7 +52,7 @@
/**
* Does some checks on RMI configuration
*/
- protected void testRmiConfig() {
+ protected static void testRmiConfig() {
String rmiHost = System.getProperty("java.rmi.server.hostname");
if ((rmiHost == null || "".equals(rmiHost.trim()))
&& log.isWarnEnabled()) {
@@ -67,7 +68,7 @@
* @return the registry found or created
* @throws RemoteException in case it is not possible to get the registry
*/
- protected Registry getRegistry() throws RemoteException {
+ protected static Registry getRegistry() throws RemoteException {
Registry result;
try {
result = LocateRegistry.getRegistry(PORT);
@@ -92,7 +93,7 @@
* @param <E> some interface class
* @throws RemoteException in case the registry is not reachable
*/
- public <E> void registerService(Class<E> serviceInterface, E instance)
+ public static <E> void registerService(Class<E> serviceInterface, E instance)
throws RemoteException {
String rmiName = serviceInterface.getName();
registerService(rmiName, instance);
@@ -106,7 +107,7 @@
* @param <E> some interface class
* @throws RemoteException in case the registry is not reachable
*/
- public <E> void registerService(String rmiName, E instance)
+ public static <E> void registerService(String rmiName, E instance)
throws RemoteException {
testRmiConfig();
@@ -121,4 +122,33 @@
registry.rebind(rmiName, stub);
}
+ /**
+ * Will unregister a service using the default name.
+ *
+ * @param serviceInterface the interface used to unbind the service. The RMI
+ * name will be generated from this class name
+ * @throws RemoteException in case the registry is not reachable
+ * @throws NotBoundException in case the given name is not bound
+ */
+ public static void unregisterService(Class<?> serviceInterface)
+ throws RemoteException, NotBoundException {
+ String rmiName = serviceInterface.getName();
+ unregisterService(rmiName);
+ }
+
+ /**
+ * Will unregister a service using the given RMI name.
+ *
+ * @param rmiName the RMI name used to unbind the service in the registry
+ * @throws RemoteException in case the registry is not reachable
+ * @throws NotBoundException in case the given name is not bound
+ */
+ public static void unregisterService(String rmiName)
+ throws RemoteException, NotBoundException {
+
+ // Bind into the registry
+ Registry registry = getRegistry();
+ registry.unbind(rmiName);
+ }
+
}
Added: trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/AnyException.java
===================================================================
--- trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/AnyException.java (rev 0)
+++ trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/AnyException.java 2011-01-19 16:45:00 UTC (rev 2021)
@@ -0,0 +1,36 @@
+/*
+ * #%L
+ * Nuiton Utils
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2004 - 2010 CodeLutin
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.util.rmi;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public class AnyException extends Exception {
+
+ public AnyException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/AnyException.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/RmiExporterAndProxyTest.java
===================================================================
--- trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/RmiExporterAndProxyTest.java (rev 0)
+++ trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/RmiExporterAndProxyTest.java 2011-01-19 16:45:00 UTC (rev 2021)
@@ -0,0 +1,118 @@
+package org.nuiton.util.rmi;
+
+import junit.framework.TestCase;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.rmi.NotBoundException;
+import java.security.InvalidParameterException;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public class RmiExporterAndProxyTest {
+
+ /** to use log facility, just put in your code: log.info(\"...\"); */
+ static private Log log = LogFactory.getLog(RmiExporterAndProxyTest.class);
+
+ @Test(expected = NullPointerException.class)
+ public void testExportNullService() throws Exception {
+
+ // It is mandatory to provide a service instance
+ ServiceExporter.registerService(TestService.class, null);
+ }
+
+ @Test(expected = NotBoundException.class)
+ public void testProxyWithoutService() throws Exception {
+
+ // Register and unregister (to make sure RMI registry is created)
+ TestServiceImpl impl = new TestServiceImpl();
+ ServiceExporter.registerService(TestService.class, impl);
+ ServiceExporter.unregisterService(TestService.class);
+
+ // This will throw an exception because service is not registered
+ RemoteProxyFactory.createProxy(TestService.class);
+ }
+
+ @Test
+ public void testObjectIdentity() throws Exception {
+
+ // Create and bind the service
+ TestServiceImpl impl = new TestServiceImpl();
+ int realServiceIdentity = System.identityHashCode(impl);
+ ServiceExporter.registerService(TestService.class, impl);
+
+ // Get a proxy on this service and make sure this is not the same object
+ TestService clientSide = RemoteProxyFactory.createProxy(TestService.class);
+ int proxyIdentity = System.identityHashCode(clientSide);
+ Assert.assertNotSame(proxyIdentity, realServiceIdentity);
+
+ // Get the remote identifier and compare
+ int serviceIdentityFromProxy = clientSide.getInstanceId();
+ Assert.assertEquals(realServiceIdentity, serviceIdentityFromProxy);
+
+ ServiceExporter.unregisterService(TestService.class);
+ }
+
+ @Test
+ public void testComplexType() throws Exception {
+
+ // Create and bind the service
+ TestServiceImpl impl = new TestServiceImpl();
+ int realServiceIdentity = System.identityHashCode(impl);
+ ServiceExporter.registerService(TestService.class, impl);
+
+ // Get a proxy on this service and do the call to createComplexTypeObject
+ TestService clientSide = RemoteProxyFactory.createProxy(TestService.class);
+ TestBean bean = clientSide.createComplexTypeObject();
+
+ // Now check that the bean is exactly as expected
+ TestBean father = bean.getFather();
+ Assert.assertNotNull(father);
+ Assert.assertEquals("I'm your father !", father.getMessage());
+ Assert.assertEquals(realServiceIdentity, father.getCreatedBy());
+ Assert.assertNull(father.getFather());
+ Assert.assertNull(father.getCreatedOn()); // transient value
+ Assert.assertEquals(0L, father.getNumber()); // transient value
+
+ Assert.assertEquals("Son", bean.getMessage());
+ Assert.assertEquals(realServiceIdentity, bean.getCreatedBy());
+ Assert.assertNull(bean.getCreatedOn()); // transient value
+ Assert.assertEquals(0L, bean.getNumber()); // transient value
+
+ ServiceExporter.unregisterService(TestService.class);
+ }
+
+ @Test
+ public void testExceptionPropagation() throws Exception {
+
+ // Create and bind the service
+ TestServiceImpl impl = new TestServiceImpl();
+ ServiceExporter.registerService(TestService.class, impl);
+
+ // Get a proxy on this service and do the call to createComplexTypeObject
+ TestService clientSide = RemoteProxyFactory.createProxy(TestService.class);
+
+ // Does not fail
+ clientSide.throwAnExceptionIfFalse(true);
+
+ try {
+ clientSide.throwAnExceptionIfFalse(false);
+ Assert.fail("An axeption should have been thrown");
+ } catch (AnyException ae) {
+
+ Assert.assertEquals("Please provide 'true'", ae.getMessage());
+
+ // Exception is the good one. Now check its cause
+ InvalidParameterException cause = (InvalidParameterException)ae.getCause();
+ Assert.assertEquals("Wrong parameter !", cause.getMessage());
+ }
+
+ ServiceExporter.unregisterService(TestService.class);
+ }
+
+}
Added: trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/TestBean.java
===================================================================
--- trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/TestBean.java (rev 0)
+++ trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/TestBean.java 2011-01-19 16:45:00 UTC (rev 2021)
@@ -0,0 +1,88 @@
+/*
+ * #%L
+ * Nuiton Utils
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2004 - 2010 CodeLutin
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.util.rmi;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public class TestBean implements Serializable {
+
+ protected TestBean father;
+ protected String message;
+ protected int createdBy;
+ protected transient Date createdOn;
+ protected transient long number;
+
+ public TestBean(String message, Object creator, long number) {
+ this.message = message;
+ this.createdBy = System.identityHashCode(creator);
+ this.createdOn = new Date();
+ this.number = number;
+ }
+
+ public TestBean getFather() {
+ return father;
+ }
+
+ public void setFather(TestBean father) {
+ this.father = father;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public int getCreatedBy() {
+ return createdBy;
+ }
+
+ public void setCreatedBy(int createdBy) {
+ this.createdBy = createdBy;
+ }
+
+ public Date getCreatedOn() {
+ return createdOn;
+ }
+
+ public void setCreatedOn(Date createdOn) {
+ this.createdOn = createdOn;
+ }
+
+ public long getNumber() {
+ return number;
+ }
+
+ public void setNumber(long number) {
+ this.number = number;
+ }
+
+}
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/TestBean.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/TestService.java
===================================================================
--- trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/TestService.java (rev 0)
+++ trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/TestService.java 2011-01-19 16:45:00 UTC (rev 2021)
@@ -0,0 +1,57 @@
+/*
+ * #%L
+ * Nuiton Utils
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2004 - 2010 CodeLutin
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.util.rmi;
+
+/**
+ * Any service interface which will be used to test the RMI proxy.
+ *
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public interface TestService {
+
+ /**
+ * This method will return a String that can only be known by itself
+ *
+ * @return an instance identifier
+ */
+ int getInstanceId();
+
+ /**
+ * This method will return a complex object to validate that this is not
+ * working only with primitive types
+ *
+ * @return a newly created TestBean
+ */
+ TestBean createComplexTypeObject();
+
+ /**
+ * Will throw an AnyException to test exception propagation
+ *
+ * @param bool true : will not fail, false will fail
+ * @throws AnyException if the given boolean is false
+ */
+ void throwAnExceptionIfFalse(Boolean bool) throws AnyException;
+
+}
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/TestService.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/TestServiceImpl.java
===================================================================
--- trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/TestServiceImpl.java (rev 0)
+++ trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/TestServiceImpl.java 2011-01-19 16:45:00 UTC (rev 2021)
@@ -0,0 +1,57 @@
+/*
+ * #%L
+ * Nuiton Utils
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2004 - 2010 CodeLutin
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.util.rmi;
+
+import com.sun.javaws.exceptions.InvalidArgumentException;
+
+import java.security.InvalidParameterException;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public class TestServiceImpl implements TestService{
+
+ @Override
+ public int getInstanceId() {
+ return System.identityHashCode(this);
+ }
+
+ @Override
+ public TestBean createComplexTypeObject() {
+ TestBean father = new TestBean("I'm your father !", this, 123);
+ TestBean result = new TestBean("Son", this, 456);
+ result.setFather(father);
+ return result;
+ }
+
+ @Override
+ public void throwAnExceptionIfFalse(Boolean bool) throws AnyException {
+ if (!bool) {
+ InvalidParameterException ipe = new InvalidParameterException("Wrong parameter !");
+ throw new AnyException("Please provide 'true'", ipe);
+ }
+ }
+
+}
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/TestServiceImpl.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
1
0
18 Jan '11
Author: tchemit
Date: 2011-01-18 08:06:31 +0100 (Tue, 18 Jan 2011)
New Revision: 2020
Url: http://nuiton.org/repositories/revision/nuiton-utils/2020
Log:
improve ApplicationConfig code
Modified:
trunk/nuiton-utils/src/main/java/org/nuiton/util/ApplicationConfig.java
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/ApplicationConfig.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/ApplicationConfig.java 2011-01-18 06:51:43 UTC (rev 2019)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/ApplicationConfig.java 2011-01-18 07:06:31 UTC (rev 2020)
@@ -587,14 +587,17 @@
this.value = value;
}
+ protected <T> List<T> convertListOption(Class<T> type) {
+ List<T> result= (List<T>) config.convertOption(type, key, value, true);
+ return result;
+ }
/**
* Get option value as {@link String}.
*
* @return value as String
*/
public List<String> getOption() {
- List<String> result = (List<String>)config.convertOption(
- String.class, key, value, true);
+ List<String> result = convertListOption(String.class);
return result;
}
@@ -604,8 +607,7 @@
* @return value as file
*/
public List<File> getOptionAsFile() {
- List<File> tmp = (List<File>)config.convertOption(
- File.class, key, value, true);
+ List<File> tmp = convertListOption(File.class);
List<File> result = new ArrayList<File>(tmp.size());
for (File file : tmp) {
result.add(file.getAbsoluteFile());
@@ -619,8 +621,7 @@
* @return value as URL
*/
public List<URL> getOptionAsURL() {
- List<URL> result = (List<URL>)config.convertOption(
- URL.class, key, value, true);
+ List<URL> result = convertListOption(URL.class);
return result;
}
@@ -630,8 +631,7 @@
* @return value as Class
*/
public List<Class> getOptionAsClass() {
- List<Class> result = (List<Class>)config.convertOption(
- Class.class, key, value, true);
+ List<Class> result = convertListOption(Class.class);
return result;
}
@@ -641,8 +641,7 @@
* @return value as Date
*/
public List<Date> getOptionAsDate() {
- List<Date> result = (List<Date>)config.convertOption(
- Date.class, key, value, true);
+ List<Date> result = convertListOption(Date.class);
return result;
}
@@ -652,8 +651,7 @@
* @return value as Time
*/
public List<Time> getOptionAsTime() {
- List<Time> result = (List<Time>)config.convertOption(
- Time.class, key, value, true);
+ List<Time> result = convertListOption(Time.class);
return result;
}
@@ -663,8 +661,7 @@
* @return value as Timestamp
*/
public List<Timestamp> getOptionAsTimestamp() {
- List<Timestamp> result = (List<Timestamp>)config.convertOption(
- Timestamp.class, key, value, true);
+ List<Timestamp> result = convertListOption(Timestamp.class);
return result;
}
@@ -674,8 +671,7 @@
* @return value as {@code int}
*/
public List<Integer> getOptionAsInt() {
- List<Integer> result = (List<Integer>)config.convertOption(
- Integer.class, key, value, true);
+ List<Integer> result = convertListOption(Integer.class);
return result;
}
@@ -685,8 +681,7 @@
* @return value as {@code double}
*/
public List<Double> getOptionAsDouble() {
- List<Double> result = (List<Double>)config.convertOption(
- Double.class, key, value, true);
+ List<Double> result = convertListOption(Double.class);
return result;
}
@@ -696,8 +691,7 @@
* @return value as {@code boolean}.
*/
public List<Boolean> getOptionAsBoolean() {
- List<Boolean> result = (List<Boolean>)config.convertOption(
- Boolean.class, key, value, true);
+ List<Boolean> result = convertListOption(Boolean.class);
return result;
}
}
@@ -723,11 +717,11 @@
* method is automaticaly called
*
* @param configFilename name of wikitty config file
+ * @throws ArgumentsParserException
*/
public ApplicationConfig(String configFilename) throws ArgumentsParserException {
this();
- parse(new String[]{
- "--option", ApplicationConfig.CONFIG_FILE_NAME, configFilename});
+ parse("--option", CONFIG_FILE_NAME, configFilename);
}
/**
@@ -751,7 +745,7 @@
* Get user home directory (system property {@code user.home}).
* @return user home directory
*/
- static public String getUserHome() {
+ public static String getUserHome() {
String result = System.getProperty("user.home");
return result;
}
@@ -895,7 +889,7 @@
}
/**
- * Add action to list of action to do
+ * Add action to list of action to do.
*
* @param action action to add, can be null.
*/
@@ -955,7 +949,7 @@
/**
* Add alias for action. This method put just -- front the actionMethod and
- * call {@link #addAlias(String, String...)}
+ * call {@link #addAlias(String, String...)}.
*
* @param alias the alias to add for the given method action
* @param actionMethod must be fully qualified method path:
@@ -967,7 +961,7 @@
/**
* Set name of file where options are read (in /etc, $HOME, $CURDIR)
- * This set used {@link #setDefaultOption(String, String)}
+ * This set used {@link #setDefaultOption(String, String)}.
*
* @param name file name
*/
@@ -978,6 +972,7 @@
/**
* Get name of file where options are read (in /etc, $HOME, $CURDIR).
+ *
* @return name of file
*/
public String getConfigFileName() {
@@ -1293,9 +1288,12 @@
* @param key option key
* @param value value to convert
* @param asList value is string that represente a list
- * @return
+ * @return the converted option in the required type
*/
- protected <T> Object convertOption(Class<T> clazz, String key, String value, boolean asList) {
+ protected <T> Object convertOption(Class<T> clazz,
+ String key,
+ String value,
+ boolean asList) {
String cacheKey = key + "-" + asList + "-" + clazz.getName();
int hash = 0;
1
0
18 Jan '11
Author: tchemit
Date: 2011-01-18 07:51:43 +0100 (Tue, 18 Jan 2011)
New Revision: 2019
Url: http://nuiton.org/repositories/revision/nuiton-utils/2019
Log:
fix javadoc + Evolution #852: [ApplicationConfig] change parse signature from parse(String[]) to parse(String...)
Modified:
trunk/nuiton-utils/src/main/java/org/nuiton/util/ApplicationConfig.java
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/ApplicationConfig.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/ApplicationConfig.java 2011-01-18 06:43:11 UTC (rev 2018)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/ApplicationConfig.java 2011-01-18 06:51:43 UTC (rev 2019)
@@ -590,7 +590,6 @@
/**
* Get option value as {@link String}.
*
- * @param key the option's key
* @return value as String
*/
public List<String> getOption() {
@@ -602,7 +601,6 @@
/**
* Get option value as {@link File}.
*
- * @param key the option's key
* @return value as file
*/
public List<File> getOptionAsFile() {
@@ -618,7 +616,6 @@
/**
* Get option value as {@link URL}.
*
- * @param key the option's key
* @return value as URL
*/
public List<URL> getOptionAsURL() {
@@ -630,7 +627,6 @@
/**
* Get option value as {@link Class}.
*
- * @param key the option's key
* @return value as Class
*/
public List<Class> getOptionAsClass() {
@@ -642,7 +638,6 @@
/**
* Get option value as {@link Date}.
*
- * @param key the option's key
* @return value as Date
*/
public List<Date> getOptionAsDate() {
@@ -654,7 +649,6 @@
/**
* Get option value as {@link Time}.
*
- * @param key the option's key
* @return value as Time
*/
public List<Time> getOptionAsTime() {
@@ -666,7 +660,6 @@
/**
* Get option value as {@link Timestamp}.
*
- * @param key the option's key
* @return value as Timestamp
*/
public List<Timestamp> getOptionAsTimestamp() {
@@ -678,7 +671,6 @@
/**
* Get option value as {@code int}.
*
- * @param key the option's key
* @return value as {@code int}
*/
public List<Integer> getOptionAsInt() {
@@ -690,7 +682,6 @@
/**
* Get option value as {@code double}.
*
- * @param key the option's key
* @return value as {@code double}
*/
public List<Double> getOptionAsDouble() {
@@ -702,7 +693,6 @@
/**
* Get option value as {@code boolean}.
*
- * @param key the option's key
* @return value as {@code boolean}.
*/
public List<Boolean> getOptionAsBoolean() {
@@ -1685,7 +1675,7 @@
* @param args argument as main(String[] args)
* @throws ArgumentsParserException if parsing failed
*/
- public void parse(String[] args) throws ArgumentsParserException {
+ public void parse(String... args) throws ArgumentsParserException {
if (args == null) {
args = ArrayUtil.EMPTY_STRING_ARRAY;
}
1
0
r2018 - in trunk/nuiton-validator/src: main/java/org/nuiton/validator main/java/org/nuiton/validator/xwork2 test/java/org/nuiton/validator/xwork2
by tchemit@users.nuiton.org 18 Jan '11
by tchemit@users.nuiton.org 18 Jan '11
18 Jan '11
Author: tchemit
Date: 2011-01-18 07:43:11 +0100 (Tue, 18 Jan 2011)
New Revision: 2018
Url: http://nuiton.org/repositories/revision/nuiton-utils/2018
Log:
suppression de la methode getModel du contrat de NuitonValidator
Modified:
trunk/nuiton-validator/src/main/java/org/nuiton/validator/NuitonValidator.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/XWork2NuitonValidator.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/XWork2NuitonValidatorProviderTest.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/XWork2NuitonValidatorTest.java
Modified: trunk/nuiton-validator/src/main/java/org/nuiton/validator/NuitonValidator.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/NuitonValidator.java 2011-01-17 18:50:24 UTC (rev 2017)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/NuitonValidator.java 2011-01-18 06:43:11 UTC (rev 2018)
@@ -33,14 +33,6 @@
public interface NuitonValidator<O> {
/**
- * Obtain the model of a validator.
- *
- * @return the model of this validator
- * @see NuitonValidatorModel
- */
- NuitonValidatorModel<O> getModel();
-
- /**
* Validates the given object and returns the result of validation.
*
* @param object the object to validate
Modified: trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/XWork2NuitonValidator.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/XWork2NuitonValidator.java 2011-01-17 18:50:24 UTC (rev 2017)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/XWork2NuitonValidator.java 2011-01-18 06:43:11 UTC (rev 2018)
@@ -37,7 +37,7 @@
import java.util.Set;
/**
- * Implementation of {@link NuitonValidator} using {@code XWorks2} validators.
+ * Implementation of {@link NuitonValidator} using {@code XWork2} validators.
*
* @author tchemit <chemit(a)codelutin.com>
* @since 2.0
@@ -86,17 +86,12 @@
}
@Override
- public NuitonValidatorModel<O> getModel() {
- return model;
- }
-
- @Override
public NuitonValidatorResult validate(O object) throws NullPointerException {
if (object == null) {
throw new NullPointerException("object parameter can not be null.");
}
-
+
NuitonValidatorResult result = new NuitonValidatorResult();
for (NuitonValidatorScope scope : validators.keySet()) {
@@ -109,4 +104,8 @@
}
return result;
}
+
+ protected NuitonValidatorModel<O> getModel() {
+ return model;
+ }
}
Modified: trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/XWork2NuitonValidatorProviderTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/XWork2NuitonValidatorProviderTest.java 2011-01-17 18:50:24 UTC (rev 2017)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/XWork2NuitonValidatorProviderTest.java 2011-01-18 06:43:11 UTC (rev 2018)
@@ -75,9 +75,6 @@
NuitonValidator<Person> validator = provider.newValidator(model);
Assert.assertNotNull(validator);
- Assert.assertNotNull(validator.getModel());
- Assert.assertEquals(model, validator.getModel());
-
}
}
Modified: trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/XWork2NuitonValidatorTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/XWork2NuitonValidatorTest.java 2011-01-17 18:50:24 UTC (rev 2017)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/XWork2NuitonValidatorTest.java 2011-01-18 06:43:11 UTC (rev 2018)
@@ -52,8 +52,6 @@
NuitonValidator<Person> validator = provider.newValidator(model);
Assert.assertNotNull(validator);
- Assert.assertNotNull(validator.getModel());
- Assert.assertEquals(model, validator.getModel());
ValidatorTestHelper.testPerson(validator);
1
0
r2017 - in trunk: . nuiton-utils/src/main/java/org/nuiton/util/beans nuiton-utils/src/main/java/org/nuiton/util/rmi nuiton-utils/src/test/java/org/nuiton/util/beans
by tchemit@users.nuiton.org 17 Jan '11
by tchemit@users.nuiton.org 17 Jan '11
17 Jan '11
Author: tchemit
Date: 2011-01-17 19:50:24 +0100 (Mon, 17 Jan 2011)
New Revision: 2017
Url: http://nuiton.org/repositories/revision/nuiton-utils/2017
Log:
remove deprecated binder api + fix docs
Removed:
trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/BinderBuilder.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/BinderProvider.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/beans/BinderBuilderTest.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/beans/BinderProviderTest.java
Modified:
trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/package-info.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteMethodExecutor.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteMethodExecutorImpl.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteProxyFactory.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/ServiceExporter.java
trunk/pom.xml
Deleted: trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/BinderBuilder.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/BinderBuilder.java 2011-01-17 18:49:58 UTC (rev 2016)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/BinderBuilder.java 2011-01-17 18:50:24 UTC (rev 2017)
@@ -1,459 +0,0 @@
-/*
- * #%L
- * Nuiton Utils
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2004 - 2010 CodeLutin
- * %%
- * This program 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 3 of the
- * License, or (at your option) any later version.
- *
- * This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/lgpl-3.0.html>.
- * #L%
- */
-
-package org.nuiton.util.beans;
-
-import java.beans.BeanInfo;
-import java.beans.IntrospectionException;
-import java.beans.Introspector;
-import java.beans.PropertyDescriptor;
-import java.lang.reflect.Method;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Map;
-import java.util.TreeMap;
-
-/**
- * A builder of {@link Binder.BinderModel} and {@link Binder}.
- * <p/>
- * A {@code binder} permits to copy some properties from a bean to another one.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @see Binder.BinderModel
- * @see Binder
- * @since 1.1.5
- * @deprecated since 1.5.3, prefer use the {@link BinderModelBuilder} instead, will be removed in version 2.0
- */
-@Deprecated
-public class BinderBuilder {
-
- /** current model used to build the binder */
- protected Binder.BinderModel<?, ?> model;
-
- /** source properties descriptors */
- protected Map<String, PropertyDescriptor> sourceDescriptors;
-
- /** target properties descriptors */
- protected Map<String, PropertyDescriptor> targetDescriptors;
-
- public BinderBuilder() {
- }
-
- /**
- * Creates a mirrored binder for the given {@code type} and add the given
- * simple properties.
- *
- * @param type the type of mirrored binder
- * @param properties simple properties to add
- */
- public BinderBuilder(Class<?> type, String... properties) {
- createBinderModel(type);
- addSimpleProperties(properties);
- }
-
- /**
- * Creates a binder for the given types and add the given simple properties.
- *
- * @param sourceType type of the source of the binder
- * @param targetType type of the target of the binder
- * @param properties simple properties to add
- */
- public BinderBuilder(Class<?> sourceType,
- Class<?> targetType,
- String... properties) {
- createBinderModel(sourceType, targetType);
- addSimpleProperties(properties);
- }
-
- /**
- * Creates a new binder model for a mirrored binder (source type = target
- * type).
- * <p/>
- * <b>Note:</b> If a previous model was created, but not released via the
- * method {@link #createBinder(Class)}, the method will failed.
- *
- * @param type the type of source and target
- * @return the instance of the builder
- * @throws IllegalStateException if a previous builder model was created
- * without been released
- * @throws NullPointerException if a parameter is null
- */
- public BinderBuilder createBinderModel(Class<?> type)
- throws IllegalStateException, NullPointerException {
- createBinderModel(type, type);
- return this;
- }
-
- /**
- * Creates a new binder model.
- * <p/>
- * <b>Note:</b> If a previous model was created, but not released via the
- * method {@link #createBinder(Class)}, the method will failed.
- *
- * @param sourceType the type of the source
- * @param targetType the type of the target
- * @return the instance of the builder
- * @throws IllegalStateException if a previous builder model was created
- * without been released
- * @throws NullPointerException if a parameter is null
- */
- public BinderBuilder createBinderModel(Class<?> sourceType,
- Class<?> targetType)
- throws IllegalStateException, NullPointerException {
- if (sourceType == null) {
- throw new NullPointerException("sourceType can not be null");
- }
- if (targetType == null) {
- throw new NullPointerException("targetType can not be null");
- }
-
- if (model != null) {
- throw new IllegalStateException(
- "there is already a binderModel in construction, release " +
- "it with the method createBinder before using this method."
- );
- }
-
- // init model
- model = new Binder.BinderModel(sourceType, targetType);
-
- // obtain source descriptors
- sourceDescriptors = new TreeMap<String, PropertyDescriptor>();
- loadDescriptors(model.getSourceType(), sourceDescriptors);
-
- // obtain target descriptors
- targetDescriptors = new TreeMap<String, PropertyDescriptor>();
- loadDescriptors(model.getTargetType(), targetDescriptors);
-
- return this;
- }
-
- /**
- * Creates a new binder given using the {@link Binder} type of binder
- * from the internal binder model
- * previously created via the method {@code createBinderModel<XXX>} and
- * then filled with methods {@code addXXX(XXX)}.
- * <p/>
- * <b>Note:</b> If no model is present, the method will fail.
- *
- * @return the instance of the new buinder.
- * @throws IllegalStateException if no model was previously created.
- * @throws NullPointerException if the parameter is {@code null}
- */
- public Binder<?, ?> createBinder()
- throws NullPointerException, IllegalStateException {
-
- Binder<?, ?> binder = createBinder(Binder.class);
- return binder;
- }
-
- /**
- * Creates a new binder given his type from the internal binder model
- * previously created via the method {@code createBinderModel<XXX>} and
- * then filled with methods {@code addXXX(XXX)}.
- * <p/>
- * <b>Note:</b> If no model is present, the method will fail.
- *
- * @param binderType the type of binder to instanciate
- * @param <B> the type of binder to instanciate
- * @return the instance of the new buinder.
- * @throws IllegalStateException if no model was previously created.
- * @throws NullPointerException if the parameter is {@code null}
- */
- public <B extends Binder<?, ?>> B createBinder(Class<B> binderType)
- throws NullPointerException, IllegalStateException {
- checkModelExists();
- if (binderType == null) {
- throw new NullPointerException("binderType can not be null");
- }
- try {
- Binder binder = binderType.newInstance();
- binder.setModel(model);
- return (B)binder;
- } catch (Exception e) {
- throw new IllegalStateException(
- "could not instanciate binder " + binderType, e);
- } finally {
- // release resources of the model
- model = null;
- sourceDescriptors.clear();
- sourceDescriptors = null;
- targetDescriptors.clear();
- targetDescriptors = null;
- }
- }
-
- /**
- * Add to the binder model some simple properties (says source property name
- * = target property name).
- * <p/>
- * <b>Note:</b> If no model is present, the method will fail.
- *
- * @param properties the name of mirrored property
- * @return the instance of the builder
- * @throws IllegalStateException if no model was previously created
- * @throws NullPointerException if a property is {@code null}
- */
- public BinderBuilder addSimpleProperties(String... properties)
- throws IllegalStateException, NullPointerException {
- checkModelExists();
- for (String property : properties) {
- if (property == null) {
- throw new NullPointerException(
- "parameter 'properties' can not contains a null value");
- }
- addProperty0(property, property);
- }
- return this;
- }
-
- /**
- * Add to the binder model some simple properties (says source property name
- * = target property name).
- * <p/>
- * <b>Note:</b> If no model is present, the method will fail.
- *
- * @param sourceProperty the name of the source property to bind
- * @param targetProperty the name of the target property to bind
- * @return the instance of the builder
- * @throws IllegalStateException if no model was previously created
- * @throws NullPointerException if a parameter is {@code null}
- */
-
- public BinderBuilder addProperty(String sourceProperty,
- String targetProperty)
- throws IllegalStateException, NullPointerException {
- if (sourceProperty == null) {
- throw new NullPointerException(
- "parameter 'sourceProperty' can not be null");
- }
- if (targetProperty == null) {
- throw new NullPointerException(
- "parameter 'targetProperty' can not be null");
- }
- checkModelExists();
- addProperty0(sourceProperty, targetProperty);
- return this;
- }
-
- /**
- * Add to the binder model some properties.
- * <p/>
- * Parameter {@code sourceAndTargetProperties} must be a array of couple
- * of {@code sourceProperty}, {@code targetProperty}.
- * <p/>
- * Example :
- * <pre>
- * builder.addProperties("name","name2","text","text");
- * </pre>
- * <p/>
- * <b>Note:</b> If no model is present, the method will fail.
- *
- * @param sourceAndTargetProperties the couple of (sourceProperty -
- * targetProperty) to bind
- * @return the instance of the builder
- * @throws IllegalStateException if no model was previously created
- * @throws IllegalArgumentException if there is not the same number of
- * source and target properties
- * @throws NullPointerException if a parameter is {@code null}
- */
- public BinderBuilder addProperties(String... sourceAndTargetProperties)
- throws IllegalStateException, IllegalArgumentException,
- NullPointerException {
- checkModelExists();
- if (sourceAndTargetProperties.length % 2 != 0) {
- throw new IllegalArgumentException(
- "must have couple(s) of sourceProperty,targetProperty) " +
- "but had " + Arrays.toString(sourceAndTargetProperties));
- }
- for (int i = 0, max = sourceAndTargetProperties.length / 2;
- i < max; i++) {
- String sourceProperty = sourceAndTargetProperties[2 * i];
- String targetProperty = sourceAndTargetProperties[2 * i + 1];
- if (sourceProperty == null) {
- throw new NullPointerException(
- "parameter 'sourceAndTargetProperties' can not " +
- "contains a null value");
- }
- if (targetProperty == null) {
- throw new NullPointerException(
- "parameter 'sourceAndTargetProperties' can not " +
- "contains a null value");
- }
- addProperty0(sourceProperty, targetProperty);
- }
- return this;
- }
-
- public BinderBuilder addCollectionStrategy(Binder.CollectionStrategy strategy,
- String... propertyNames) {
-
- for (String propertyName : propertyNames) {
-
- // check property is registred
- if (!model.containsSourceProperty(propertyName)) {
- throw new IllegalArgumentException(
- "source property '" + propertyName + "' " +
- " is NOT registred.");
- }
-
- // check property is collection type
- PropertyDescriptor descriptor = sourceDescriptors.get(propertyName);
- Class<?> type = descriptor.getPropertyType();
- if (!Collection.class.isAssignableFrom(type)) {
- throw new IllegalStateException(
- "source property '" + propertyName +
- "' is not a collection type [" + type + "]");
- }
-
- // can safely add the strategy
- model.addCollectionStrategy(propertyName, strategy);
- }
- return this;
- }
-
- public BinderBuilder addBinder(String propertyName, Binder<?, ?> binder) {
-
- // check property is registred
- if (!model.containsSourceProperty(propertyName)) {
- throw new IllegalArgumentException(
- "source property '" + propertyName + "' " +
- " is NOT registred.");
- }
-
- // check property is the same type of given binder
- PropertyDescriptor descriptor = sourceDescriptors.get(propertyName);
- Class<?> type = descriptor.getPropertyType();
-
- if (!Collection.class.isAssignableFrom(type) &&
- !binder.model.getSourceType().isAssignableFrom(type)) {
- throw new IllegalStateException(
- "source property '" + propertyName +
- "' has not the same type [" + type +
- "] of the binder [" + binder.model.getSourceType() + "].");
- }
-
- // can safely add the strategy
- model.addBinder(propertyName, binder);
-
- return this;
- }
-
- protected void addProperty0(String sourceProperty,
- String targetProperty) {
- // check srcProperty does not exist
- if (model.containsSourceProperty(sourceProperty)) {
- throw new IllegalArgumentException("source property '" +
- sourceProperty + "' " + " was already registred.");
- }
- // check dstProperty does not exist
- if (model.containsTargetProperty(targetProperty)) {
- throw new IllegalArgumentException("destination property '" +
- targetProperty + "' " + " was already registred.");
- }
-
- // obtain source descriptor
- PropertyDescriptor sourceDescriptor =
- sourceDescriptors.get(sourceProperty);
- if (sourceDescriptor == null) {
- throw new IllegalArgumentException("no property '" +
- sourceProperty + "' " + "found on type " +
- model.getSourceType());
- }
- // check srcProperty is readable
- Method readMethod = sourceDescriptor.getReadMethod();
- if (readMethod == null) {
- throw new IllegalArgumentException("property '" + sourceProperty +
- "' " + "is not readable on type " + model.getSourceType());
- }
-
- // obtain dst descriptor
- PropertyDescriptor targetDescriptor =
- targetDescriptors.get(targetProperty);
- if (targetDescriptor == null) {
- throw new IllegalArgumentException("no property '" +
- targetProperty + "' " + "found on type " +
- model.getTargetType());
- }
- // check dstProperty is writable
- Method writeMethod = sourceDescriptor.getWriteMethod();
- if (writeMethod == null) {
- throw new IllegalArgumentException("property '" + targetProperty +
- "' " + "is not writable on type " + model.getTargetType());
- }
-
- // check types are ok
- Class<?> sourceType = sourceDescriptor.getPropertyType();
- Class<?> targetType = targetDescriptor.getPropertyType();
- //TODO-TC20100221 : should check if primitive and boxed it in such case
- if (!sourceType.equals(targetType)) {
- throw new IllegalArgumentException("source property '" +
- sourceProperty + "' and target property '" +
- targetProperty + "' are not compatible ( sourceType : " +
- sourceType + " vs targetType :" + targetType + ')');
- }
-
- // safe to add the binding
- model.addBinding(sourceDescriptor, targetDescriptor);
- }
-
-
- protected void checkModelExists() throws IllegalStateException {
- if (model == null) {
- throw new IllegalStateException("there is not model, must " +
- "create one with createBinderModel method");
- }
- }
-
- protected Binder.BinderModel<?, ?> getModel() {
- return model;
- }
-
- protected static void loadDescriptors(
- Class<?> type,
- Map<String, PropertyDescriptor> descriptors) {
- try {
-
- BeanInfo beanInfo = Introspector.getBeanInfo(type);
- for (PropertyDescriptor descriptor :
- beanInfo.getPropertyDescriptors()) {
- if (!descriptors.containsKey(descriptor.getName())) {
- descriptors.put(descriptor.getName(), descriptor);
- }
- }
- } catch (IntrospectionException e) {
- throw new RuntimeException("Could not obtain bean properties " +
- "descriptors for source type " + type, e);
- }
- Class<?>[] interfaces = type.getInterfaces();
- for (Class<?> i : interfaces) {
- loadDescriptors(i, descriptors);
- }
- Class<?> superClass = type.getSuperclass();
- if (superClass != null && !Object.class.equals(superClass)) {
- loadDescriptors(superClass, descriptors);
- }
- }
-}
Deleted: trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/BinderProvider.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/BinderProvider.java 2011-01-17 18:49:58 UTC (rev 2016)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/BinderProvider.java 2011-01-17 18:50:24 UTC (rev 2017)
@@ -1,337 +0,0 @@
-/*
- * #%L
- * Nuiton Utils
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2004 - 2010 CodeLutin
- * %%
- * This program 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 3 of the
- * License, or (at your option) any later version.
- *
- * This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/lgpl-3.0.html>.
- * #L%
- */
-
-package org.nuiton.util.beans;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Manage a cache of {@link Binder} objects.
- * <p/>
- * You must first register some binders via the {@code registerBinder} api.
- * <pre>
- * Binder<User,UserDTO> mybinder = ...;
- * registerBinder(myNewBinder);
- * </pre>
- * To use several binders of the the same types, you can moreover specify
- * a context name of your binder :
- * <pre>
- * Binder<User,UserDTO> mybinder = ...;
- * registerBinder(myBinder, "One");
- * </pre>
- * <p/>
- * Then you can obtained them back via the api
- * <pre>
- * Binder<User,UserDTO> mybinder = getBinder(User.class,UserDTO);
- * </pre>
- * <p/>
- * or with a context name :
- * <pre>
- * Binder<User,UserDTO> mybinder = getBinder(User.class,UserDTO.class, "One");
- * </pre>
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @see Binder
- * @see BinderBuilder
- * @since 1.1.5
- * @deprecated since 1.5.3, use now the {@link BinderFactory} instead, will be remove in version {@code 1.6}.
- */
-@Deprecated
-public class BinderProvider {
-
- /** Logger */
- private static final Log log = LogFactory.getLog(BinderProvider.class);
-
- /** Cache of registred binders indexed by their unique entry */
- protected static Map<BinderEntry, Binder<?, ?>> binders;
-
- /**
- * Gets the registred mirror binder (source type = target type) with no
- * context name specified.
- *
- * @param sourceType the type of source and target
- * @param <S> the type of source and target
- * @return the registred binder or {@code null} if not found.
- */
- public static <S> Binder<S, S> getBinder(Class<S> sourceType) {
- return getBinder(sourceType, sourceType, null);
- }
-
- /**
- * Gets the registred mirror binder (source type = target type) with the
- * given context name.
- *
- * @param sourceType the type of source and target
- * @param name the context's name of the searched binder
- * @param <S> the type of source and target
- * @return the registred binder or {@code null} if not found.
- */
- public static <S> Binder<S, S> getBinder(Class<S> sourceType,
- String name) {
- return getBinder(sourceType, sourceType, name);
- }
-
-
- /**
- * Gets the registred binder given his types with no context name.
- *
- * @param sourceType the type of source
- * @param targetType the type of target
- * @param <S> the type of source
- * @param <T> the type of target
- * @return the registred binder or {@code null} if not found.
- */
- public static <S, T> Binder<S, T> getBinder(Class<S> sourceType,
- Class<T> targetType) {
- return getBinder(sourceType, targetType, null);
- }
-
- /**
- * Gets the registred binder given his types and his context's name.
- *
- * @param sourceType the type of source
- * @param targetType the type of target
- * @param name the context's name of the searched binder
- * @param <S> the type of source
- * @param <T> the type of target
- * @return the registred binder or {@code null} if not found.
- */
- public static <S, T> Binder<S, T> getBinder(Class<S> sourceType,
- Class<T> targetType,
- String name) {
- BinderEntry entry = new BinderEntry(sourceType, targetType, name);
- if (log.isDebugEnabled()) {
- log.debug("for entry " + entry);
- }
- Binder<?, ?> result = getBinders().get(entry);
- if (result == null) {
- // binder not found
- if (log.isWarnEnabled()) {
- log.warn("Could not find binder " + entry);
- }
- }
- return (Binder<S, T>) result;
- }
-
- /**
- * Register a binder with no context name.
- * <p/>
- * <b>Note: </b> If a previous binder with same definition exists, it will
- * be overriden by the new binder.
- *
- * @param binder the binder to register.
- */
- public static void registerBinder(Binder<?, ?> binder) {
- registerBinder(binder, null);
- }
-
- /**
- * Register a binder with no context's name from a {@link BinderBuilder}.
- * <p/>
- * <b>Note: </b> If a previous binder with same definition exists, it will
- * be overriden by the new binder.
- *
- * @param builder the builder which contains builder model to use
- * @see BinderBuilder#createBinder(Class)
- */
- public static void registerBinder(BinderBuilder builder) {
- registerBinder(builder, Binder.class);
- }
-
- /**
- * Register a binder with no context's name from a {@link BinderBuilder}.
- * <p/>
- * <b>Note: </b> If a previous binder with same definition exists, it will
- * be overriden by the new binder.
- *
- * @param builder the builder which contains builder model to use
- * @param binderType the type of binder to instanciate and register.
- * @see BinderBuilder#createBinder(Class)
- */
- public static <B extends Binder<?, ?>> void registerBinder(BinderBuilder builder,
- Class<B> binderType) {
-
- registerBinder(builder, binderType, null);
- }
-
- /**
- * Register a binder with a context's name from a {@link BinderBuilder}.
- * <p/>
- * <b>Note: </b> If a previous binder with same definition exists, it will
- * be overriden by the new binder.
- *
- * @param builder the builder which contains builder model to use
- * @param name the context's name
- * @see BinderBuilder#createBinder(Class)
- */
- public static void registerBinder(BinderBuilder builder, String name) {
-
- registerBinder(builder, Binder.class, name);
- }
-
- /**
- * Register a binder with a context's name from a {@link BinderBuilder}.
- * <p/>
- * <b>Note: </b> If a previous binder with same definition exists, it will
- * be overriden by the new binder.
- *
- * @param builder the builder which contains builder model to use
- * @param binderType the type of binder to instanciate and register.
- * @param name the context's name
- * @see BinderBuilder#createBinder(Class)
- */
- public static <B extends Binder<?, ?>> void registerBinder(BinderBuilder builder,
- Class<B> binderType,
- String name) {
- // instanciate the binder
- B binder = builder.createBinder(binderType);
- // register it
- registerBinder(binder, name);
- }
-
- /**
- * Register a binder with a context name.
- * <p/>
- * <b>Note: </b> If a previous binder with same definition exists, it will
- * be overriden by the new binder.
- *
- * @param binder the binder to register.
- * @param name the context's name
- */
- public static void registerBinder(Binder<?, ?> binder, String name) {
- Binder.BinderModel<?, ?> model = binder.getModel();
- BinderEntry entry = new BinderEntry(
- model.getSourceType(),
- model.getTargetType(),
- name
- );
- if (log.isDebugEnabled()) {
- log.debug("binder to seek : " + entry);
- }
- Binder<?, ?> oldBinder = getBinders().get(entry);
- if (oldBinder != null) {
- // already a binder for this entry
- if (log.isWarnEnabled()) {
- log.warn("Binder already registred for " + entry + " : " +
- oldBinder);
- log.warn("Will be replace by the new binder " + binder);
- }
- }
- // register the binder
- if (log.isDebugEnabled()) {
- log.debug("entry : " + entry + " : " + binder);
- }
- getBinders().put(entry, binder);
- }
-
- protected static Map<BinderEntry, Binder<?, ?>> getBinders() {
- if (binders == null) {
- binders = new HashMap<BinderEntry, Binder<?, ?>>();
- }
- return binders;
- }
-
- public static void clear() {
- if (binders != null) {
- binders.clear();
- binders = null;
- }
- }
-
- /**
- * Definition of an binder entry (source and target types + context name).
- * <p/>
- * <b>Note :</b>When no context is specified, we always use a
- * {@code null} context name.
- */
- public static class BinderEntry {
-
- protected final Class<?> sourceType;
-
- protected final Class<?> targetType;
-
- protected final String name;
-
-
- public BinderEntry(Class<?> sourceType,
- Class<?> targetType,
- String name) {
- this.sourceType = sourceType;
- this.targetType = targetType;
- this.name = name;
- }
-
- public Class<?> getSourceType() {
- return sourceType;
- }
-
- public Class<?> getTargetType() {
- return targetType;
- }
-
- public String getName() {
- return name;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
-
- BinderEntry that = (BinderEntry) o;
-
- return (name == null ? that.name == null : name.equals(that.name)) &&
- sourceType.equals(that.sourceType) &&
- targetType.equals(that.targetType);
- }
-
- @Override
- public int hashCode() {
- int result = sourceType.hashCode();
- result = 31 * result + targetType.hashCode();
- result = 31 * result + (name != null ? name.hashCode() : 0);
- return result;
- }
-
- @Override
- public String toString() {
- StringBuilder buffer = new StringBuilder("<");
- buffer.append(super.toString());
- buffer.append(", sourceType: ").append(getSourceType()).append(',');
- buffer.append(" targetType: ").append(getTargetType()).append(',');
- buffer.append(" name: ").append(getName()).append('>');
-
- return buffer.toString();
- }
- }
-}
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/package-info.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/package-info.java 2011-01-17 18:49:58 UTC (rev 2016)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/package-info.java 2011-01-17 18:50:24 UTC (rev 2017)
@@ -84,17 +84,17 @@
* org.nuiton.util.beans.BinderModelBuilderTest
* </pre>
*
- * <h1> JavaBeans api</h1>
+ * <h1>JavaBeans api</h1>
*
* <h2>{@link BeanMonitor} class</h2>
* This object permits to listen javaBeans and keep modifications made on a bean.
*
- * More exalanations will come soon, meanwhile you can see the test class :
+ * More explanations will come soon, meanwhile you can see the test class :
* <pre>
* org.nuiton.util.beans.BeanMonitorTest
* </pre>
*
- *
+ *
* @since 1.1.5
*/
package org.nuiton.util.beans;
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteMethodExecutor.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteMethodExecutor.java 2011-01-17 18:49:58 UTC (rev 2016)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteMethodExecutor.java 2011-01-17 18:50:24 UTC (rev 2017)
@@ -1,23 +1,23 @@
/*
* #%L
* Nuiton Utils
- *
+ * *
* $Id$
* $HeadURL$
* %%
* Copyright (C) 2004 - 2010 CodeLutin
* %%
* This program 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 3 of the
+ * it under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
- *
+ *
* This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
+ *
+ * You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteMethodExecutorImpl.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteMethodExecutorImpl.java 2011-01-17 18:49:58 UTC (rev 2016)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteMethodExecutorImpl.java 2011-01-17 18:50:24 UTC (rev 2017)
@@ -1,23 +1,23 @@
/*
* #%L
* Nuiton Utils
- *
+ * *
* $Id$
* $HeadURL$
* %%
* Copyright (C) 2004 - 2010 CodeLutin
* %%
* This program 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 3 of the
+ * it under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
- *
+ *
* This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
+ *
+ * You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteProxyFactory.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteProxyFactory.java 2011-01-17 18:49:58 UTC (rev 2016)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteProxyFactory.java 2011-01-17 18:50:24 UTC (rev 2017)
@@ -1,23 +1,23 @@
/*
* #%L
* Nuiton Utils
- *
+ * *
* $Id$
* $HeadURL$
* %%
* Copyright (C) 2004 - 2010 CodeLutin
* %%
* This program 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 3 of the
+ * it under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
- *
+ *
* This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
+ *
+ * You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/ServiceExporter.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/ServiceExporter.java 2011-01-17 18:49:58 UTC (rev 2016)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/ServiceExporter.java 2011-01-17 18:50:24 UTC (rev 2017)
@@ -1,23 +1,23 @@
/*
* #%L
* Nuiton Utils
- *
+ * *
* $Id$
* $HeadURL$
* %%
* Copyright (C) 2004 - 2010 CodeLutin
* %%
* This program 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 3 of the
+ * it under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
- *
+ *
* This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
+ *
+ * You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
Deleted: trunk/nuiton-utils/src/test/java/org/nuiton/util/beans/BinderBuilderTest.java
===================================================================
--- trunk/nuiton-utils/src/test/java/org/nuiton/util/beans/BinderBuilderTest.java 2011-01-17 18:49:58 UTC (rev 2016)
+++ trunk/nuiton-utils/src/test/java/org/nuiton/util/beans/BinderBuilderTest.java 2011-01-17 18:50:24 UTC (rev 2017)
@@ -1,344 +0,0 @@
-/*
- * #%L
- * Nuiton Utils
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2004 - 2010 CodeLutin
- * %%
- * This program 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 3 of the
- * License, or (at your option) any later version.
- *
- * This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/lgpl-3.0.html>.
- * #L%
- */
-
-package org.nuiton.util.beans;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.xml.ws.BindingProvider;
-import java.beans.PropertyDescriptor;
-import java.util.Map;
-
-/**
- * @author tchemit <chemit(a)codelutin.com>
- * @deprecated since 1.5.3, will be removed when {@link BindingProvider} will be removed.
- */
-@Deprecated
-public class BinderBuilderTest {
-
- private BinderBuilder builder;
-
- protected static final String PROPERTY_CLASS = "class";
-
- @Before
- public void setUp() {
-
- builder = new BinderBuilder();
- }
-
- @Test(expected = NullPointerException.class)
- public void testCreateMirroredBinderModel_NPE() throws Exception {
- builder.createBinderModel(null);
- }
-
- @Test
- public void testCreateMirroredBinderModel() throws Exception {
- builder.createBinderModel(BeanA.class);
- Assert.assertNotNull(builder.getModel());
- Map<String, PropertyDescriptor> sourceDescriptors;
- Map<String, PropertyDescriptor> targetDescriptors;
-
- sourceDescriptors = builder.sourceDescriptors;
- Assert.assertNotNull(sourceDescriptors);
- Assert.assertEquals(8, sourceDescriptors.size());
- Assert.assertTrue(sourceDescriptors.containsKey(PROPERTY_CLASS));
- Assert.assertTrue(sourceDescriptors.containsKey(BeanA.PROPERTY_AA));
- Assert.assertTrue(sourceDescriptors.containsKey(BeanA.PROPERTY_A));
- Assert.assertTrue(sourceDescriptors.containsKey(BeanA.PROPERTY_B));
- Assert.assertTrue(sourceDescriptors.containsKey(BeanA.PROPERTY_C));
- Assert.assertTrue(sourceDescriptors.containsKey(BeanA.PROPERTY_D));
- Assert.assertTrue(sourceDescriptors.containsKey(BeanA.PROPERTY_E));
- Assert.assertTrue(sourceDescriptors.containsKey(BeanA.PROPERTY_F));
-
-
- targetDescriptors = builder.targetDescriptors;
- Assert.assertNotNull(targetDescriptors);
- Assert.assertEquals(8, targetDescriptors.size());
- Assert.assertTrue(targetDescriptors.containsKey(PROPERTY_CLASS));
- Assert.assertTrue(targetDescriptors.containsKey(BeanA.PROPERTY_AA));
- Assert.assertTrue(targetDescriptors.containsKey(BeanA.PROPERTY_A));
- Assert.assertTrue(targetDescriptors.containsKey(BeanA.PROPERTY_B));
- Assert.assertTrue(targetDescriptors.containsKey(BeanA.PROPERTY_C));
- Assert.assertTrue(targetDescriptors.containsKey(BeanA.PROPERTY_D));
- Assert.assertTrue(targetDescriptors.containsKey(BeanA.PROPERTY_F));
- Assert.assertTrue(targetDescriptors.containsKey(BeanA.PROPERTY_F));
-
- Assert.assertEquals(BeanA.class, builder.getModel().getSourceType());
- Assert.assertEquals(BeanA.class, builder.getModel().getTargetType());
- }
-
- @Test(expected = IllegalStateException.class)
- public void testCreateMirroredBinderModel_Twice() throws Exception {
- builder.createBinderModel(BeanA.class);
- Assert.assertNotNull(builder.getModel());
- Assert.assertEquals(BeanA.class, builder.getModel().getSourceType());
- Assert.assertEquals(BeanA.class, builder.getModel().getTargetType());
- builder.createBinderModel(BeanA.class);
- }
-
- @Test(expected = NullPointerException.class)
- public void testCreateBinderModel_NPE() throws Exception {
- builder.createBinderModel(null, null);
- }
-
- @Test(expected = NullPointerException.class)
- public void testCreateBinderModel_NPE2() throws Exception {
- builder.createBinderModel(BeanA.class, null);
- }
-
- @Test(expected = NullPointerException.class)
- public void testCreateBinderModel_NPE3() throws Exception {
- builder.createBinderModel(null, BeanA.class);
- }
-
- @Test
- public void testCreateBinderModel() throws Exception {
- builder.createBinderModel(BeanA.class, BeanB.class);
- Assert.assertNotNull(builder.getModel());
- Map<String, PropertyDescriptor> sourceDescriptors;
- Map<String, PropertyDescriptor> targetDescriptors;
-
- sourceDescriptors = builder.sourceDescriptors;
- Assert.assertNotNull(sourceDescriptors);
- Assert.assertEquals(8, sourceDescriptors.size());
- Assert.assertTrue(sourceDescriptors.containsKey(PROPERTY_CLASS));
- Assert.assertTrue(sourceDescriptors.containsKey(BeanA.PROPERTY_AA));
- Assert.assertTrue(sourceDescriptors.containsKey(BeanA.PROPERTY_A));
- Assert.assertTrue(sourceDescriptors.containsKey(BeanA.PROPERTY_B));
- Assert.assertTrue(sourceDescriptors.containsKey(BeanA.PROPERTY_C));
- Assert.assertTrue(sourceDescriptors.containsKey(BeanA.PROPERTY_D));
- Assert.assertTrue(sourceDescriptors.containsKey(BeanA.PROPERTY_E));
- Assert.assertTrue(sourceDescriptors.containsKey(BeanA.PROPERTY_F));
-
-
- targetDescriptors = builder.targetDescriptors;
- Assert.assertNotNull(targetDescriptors);
- Assert.assertEquals(15, targetDescriptors.size());
- Assert.assertTrue(targetDescriptors.containsKey(PROPERTY_CLASS));
- Assert.assertTrue(targetDescriptors.containsKey(BeanA.PROPERTY_AA));
- Assert.assertTrue(targetDescriptors.containsKey(BeanA.PROPERTY_A));
- Assert.assertTrue(targetDescriptors.containsKey(BeanA.PROPERTY_B));
- Assert.assertTrue(targetDescriptors.containsKey(BeanA.PROPERTY_C));
- Assert.assertTrue(targetDescriptors.containsKey(BeanA.PROPERTY_D));
- Assert.assertTrue(targetDescriptors.containsKey(BeanA.PROPERTY_E));
- Assert.assertTrue(targetDescriptors.containsKey(BeanA.PROPERTY_F));
- Assert.assertTrue(targetDescriptors.containsKey(BeanB.PROPERTY_BB));
- Assert.assertTrue(targetDescriptors.containsKey(BeanB.PROPERTY_A2));
- Assert.assertTrue(targetDescriptors.containsKey(BeanB.PROPERTY_B2));
- Assert.assertTrue(targetDescriptors.containsKey(BeanB.PROPERTY_C2));
- Assert.assertTrue(targetDescriptors.containsKey(BeanB.PROPERTY_D2));
- Assert.assertTrue(targetDescriptors.containsKey(BeanB.PROPERTY_E2));
- Assert.assertTrue(targetDescriptors.containsKey(BeanB.PROPERTY_F2));
-
- Assert.assertEquals(BeanA.class, builder.getModel().getSourceType());
- Assert.assertEquals(BeanB.class, builder.getModel().getTargetType());
- }
-
- @Test(expected = IllegalStateException.class)
- public void testCreateBinderModel_Twice() throws Exception {
- builder.createBinderModel(BeanA.class, BeanB.class);
- Assert.assertNotNull(builder.getModel());
- Assert.assertEquals(BeanA.class, builder.getModel().getSourceType());
- Assert.assertEquals(BeanB.class, builder.getModel().getTargetType());
- builder.createBinderModel(BeanA.class, BeanB.class);
- }
-
- @Test(expected = IllegalStateException.class)
- public void testCreateBinder_NO_Model() throws Exception {
- builder.createBinder(Binder.class);
- }
-
- @Test(expected = NullPointerException.class)
- public void testCreateBinder_NPE() throws Exception {
- builder.createBinderModel(BeanA.class, BeanB.class);
- builder.createBinder(null);
- }
-
- @Test
- public void testAddSimpleProperties() throws Exception {
-
- builder.createBinderModel(BeanA.class);
- Binder.BinderModel<?, ?> model = builder.getModel();
-
- try {
- builder.addSimpleProperties((String) null);
- Assert.fail();
- } catch (NullPointerException e) {
- Assert.assertTrue(true);
- }
- builder.addSimpleProperties(BeanA.PROPERTY_A);
- Assert.assertEquals(1, model.getSourceDescriptors().length);
- Assert.assertEquals(1, model.getTargetDescriptors().length);
- Map<String, String> map = model.getPropertiesMapping();
- Assert.assertEquals(1, map.size());
- Assert.assertTrue(map.containsKey(BeanA.PROPERTY_A));
- Assert.assertTrue(map.containsValue(BeanA.PROPERTY_A));
- Assert.assertEquals(BeanA.PROPERTY_A, map.get(BeanA.PROPERTY_A));
-
- try {
- builder.addSimpleProperties(BeanA.PROPERTY_A);
- Assert.fail();
- } catch (IllegalArgumentException e) {
- Assert.assertTrue(true);
- }
-
- try {
- builder.addSimpleProperties(BeanB.PROPERTY_A2);
- Assert.fail();
- } catch (IllegalArgumentException e) {
- Assert.assertTrue(true);
- }
-
- builder.addSimpleProperties(BeanA.PROPERTY_B);
- Assert.assertEquals(2, model.getSourceDescriptors().length);
- Assert.assertEquals(2, model.getTargetDescriptors().length);
- Assert.assertEquals(2, map.size());
- Assert.assertTrue(map.containsKey(BeanA.PROPERTY_B));
- Assert.assertTrue(map.containsValue(BeanA.PROPERTY_B));
- Assert.assertEquals(BeanA.PROPERTY_B, map.get(BeanA.PROPERTY_B));
-
- }
-
- @Test
- public void testAddProperty() throws Exception {
- builder.createBinderModel(BeanA.class, BeanB.class);
- Binder.BinderModel<?, ?> model = builder.getModel();
-
- try {
- builder.addProperty(null, null);
- Assert.fail();
- } catch (NullPointerException e) {
- Assert.assertTrue(true);
- }
- try {
- builder.addProperty(BeanA.PROPERTY_A, null);
- Assert.fail();
- } catch (NullPointerException e) {
- Assert.assertTrue(true);
- }
- try {
- builder.addProperty(null, BeanA.PROPERTY_A);
- Assert.fail();
- } catch (NullPointerException e) {
- Assert.assertTrue(true);
- }
- builder.addProperty(BeanA.PROPERTY_A, BeanA.PROPERTY_A);
- Assert.assertEquals(1, model.getSourceDescriptors().length);
- Assert.assertEquals(1, model.getTargetDescriptors().length);
- Map<String, String> map = model.getPropertiesMapping();
- Assert.assertEquals(1, map.size());
- Assert.assertTrue(map.containsKey(BeanA.PROPERTY_A));
- Assert.assertTrue(map.containsValue(BeanA.PROPERTY_A));
- Assert.assertEquals(BeanA.PROPERTY_A, map.get(BeanA.PROPERTY_A));
-
- try {
- builder.addProperty(BeanB.PROPERTY_A, BeanB.PROPERTY_A2);
- Assert.fail();
- } catch (IllegalArgumentException e) {
- Assert.assertTrue(true);
- }
-
- try {
- builder.addProperty(BeanB.PROPERTY_A2, BeanB.PROPERTY_A);
- Assert.fail();
- } catch (IllegalArgumentException e) {
- Assert.assertTrue(true);
- }
-
- builder.addProperty(BeanA.PROPERTY_B, BeanB.PROPERTY_B2);
- Assert.assertEquals(2, model.getSourceDescriptors().length);
- Assert.assertEquals(2, model.getTargetDescriptors().length);
- Assert.assertEquals(2, map.size());
- Assert.assertTrue(map.containsKey(BeanA.PROPERTY_B));
- Assert.assertTrue(map.containsValue(BeanB.PROPERTY_B2));
- Assert.assertEquals(BeanB.PROPERTY_B2, map.get(BeanB.PROPERTY_B));
- }
-
- @Test
- public void testAddProperties() throws Exception {
- builder.createBinderModel(BeanA.class, BeanB.class);
-
- try {
- builder.addProperties(BeanB.PROPERTY_A, BeanB.PROPERTY_A2,
- BeanB.PROPERTY_B);
- Assert.fail();
- } catch (IllegalArgumentException e) {
- Assert.assertTrue(true);
- }
-
- try {
- builder.addProperties(BeanB.PROPERTY_A, null,
- BeanB.PROPERTY_B, BeanB.PROPERTY_B);
- Assert.fail();
- } catch (NullPointerException e) {
- Assert.assertTrue(true);
- }
-
- builder.addProperties(BeanB.PROPERTY_A, BeanB.PROPERTY_A,
- BeanB.PROPERTY_B, BeanB.PROPERTY_B2);
-
- Binder.BinderModel<?, ?> model = builder.getModel();
- Assert.assertEquals(2, model.getSourceDescriptors().length);
- Assert.assertEquals(2, model.getTargetDescriptors().length);
- Map<String, String> map = model.getPropertiesMapping();
- Assert.assertEquals(2, map.size());
- Assert.assertTrue(map.containsKey(BeanA.PROPERTY_A));
- Assert.assertTrue(map.containsValue(BeanA.PROPERTY_A));
- Assert.assertEquals(BeanA.PROPERTY_A, map.get(BeanA.PROPERTY_A));
-
- Assert.assertTrue(map.containsKey(BeanA.PROPERTY_B));
- Assert.assertTrue(map.containsValue(BeanB.PROPERTY_B2));
- Assert.assertEquals(BeanB.PROPERTY_B2, map.get(BeanB.PROPERTY_B));
- }
-
- @Test
- public void testCreateBinder() throws Exception {
- builder.createBinderModel(BeanA.class, BeanB.class);
- builder.addProperties(BeanB.PROPERTY_A, BeanB.PROPERTY_A,
- BeanB.PROPERTY_B, BeanB.PROPERTY_B2);
-
- Binder<BeanA, BeanB> binder =
- (Binder<BeanA, BeanB>) builder.createBinder();
-
- Assert.assertNull(builder.getModel());
- Assert.assertNull(builder.sourceDescriptors);
- Assert.assertNull(builder.targetDescriptors);
-
- BeanA a = new BeanA();
- BeanB b = new BeanB();
-
- a.setA("a");
- a.setB("b");
- b.setA("a2");
- b.setB2("b2");
-
- binder.copy(a, b);
- Assert.assertEquals("a", b.getA());
- Assert.assertEquals("b", b.getB2());
- Assert.assertNull(b.getB());
- }
-}
Deleted: trunk/nuiton-utils/src/test/java/org/nuiton/util/beans/BinderProviderTest.java
===================================================================
--- trunk/nuiton-utils/src/test/java/org/nuiton/util/beans/BinderProviderTest.java 2011-01-17 18:49:58 UTC (rev 2016)
+++ trunk/nuiton-utils/src/test/java/org/nuiton/util/beans/BinderProviderTest.java 2011-01-17 18:50:24 UTC (rev 2017)
@@ -1,199 +0,0 @@
-/*
- * #%L
- * Nuiton Utils
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2004 - 2010 CodeLutin
- * %%
- * This program 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 3 of the
- * License, or (at your option) any later version.
- *
- * This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/lgpl-3.0.html>.
- * #L%
- */
-
-package org.nuiton.util.beans;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.xml.ws.BindingProvider;
-
-/**
- * @author tchemit <chemit(a)codelutin.com>
- * @deprecated since 1.5.3, will be removed when {@link BindingProvider} will be removed.
- */
-@Deprecated
-public class BinderProviderTest {
-
- Binder<BeanA, BeanA> binderA;
- Binder<BeanA, BeanB> binderB;
- private static final String MY_BINDER_NAME = "myBinder";
- private static final String MY_BINDER2_NAME = "myBinder2";
-
- @Before
- public void setUp() {
-
- BinderProvider.binders = null;
-
- BinderBuilder builder = new BinderBuilder();
- binderA = (Binder<BeanA, BeanA>)
- builder.createBinderModel(BeanA.class).
- addSimpleProperties(BeanA.PROPERTY_A).
- createBinder();
- binderB = (Binder<BeanA, BeanB>)
- builder.createBinderModel(BeanA.class, BeanB.class).
- addSimpleProperties(BeanA.PROPERTY_A, BeanA.PROPERTY_B).
- addProperty(BeanA.PROPERTY_C, BeanB.PROPERTY_C2).
- createBinder();
-
- }
-
- @Test
- public void testRegisterBinder() throws Exception {
-
- Assert.assertNull(BinderProvider.binders);
-
- try {
- BinderProvider.registerBinder((Binder<?,?>) null);
- Assert.fail();
- } catch (NullPointerException e) {
-
- Assert.assertTrue(true);
- }
- try {
- BinderProvider.registerBinder((BinderBuilder) null);
- Assert.fail();
- } catch (NullPointerException e) {
-
- Assert.assertTrue(true);
- }
-
- BinderProvider.registerBinder(binderA);
-
- Assert.assertNotNull(BinderProvider.binders);
- Assert.assertEquals(1, BinderProvider.getBinders().size());
- Assert.assertTrue(BinderProvider.getBinders().containsValue(binderA));
-
- }
-
- @Test
- public void testRegisterBinderWithName() throws Exception {
- Assert.assertNull(BinderProvider.binders);
-
- String yo = "yo";
- try {
- BinderProvider.registerBinder((Binder<?,?>) null, null);
- Assert.fail();
- } catch (NullPointerException e) {
-
- Assert.assertTrue(true);
- }
-
- try {
- BinderProvider.registerBinder((Binder<?,?>) null, MY_BINDER_NAME);
- Assert.fail();
- } catch (NullPointerException e) {
-
- Assert.assertTrue(true);
- }
- try {
- BinderProvider.registerBinder((BinderBuilder) null, (String) null);
- Assert.fail();
- } catch (NullPointerException e) {
-
- Assert.assertTrue(true);
- }
- try {
- BinderProvider.registerBinder((BinderBuilder) null, MY_BINDER_NAME);
- Assert.fail();
- } catch (NullPointerException e) {
-
- Assert.assertTrue(true);
- }
-
- BinderProvider.registerBinder(binderA, MY_BINDER_NAME);
-
- Assert.assertNotNull(BinderProvider.binders);
- Assert.assertEquals(1, BinderProvider.getBinders().size());
- Assert.assertTrue(BinderProvider.getBinders().containsValue(binderA));
- }
-
- @Test
- public void testGetMirroredBinder() throws Exception {
- BinderProvider.registerBinder(binderA);
- Binder<BeanA, BeanA> aBeanABinder = BinderProvider.getBinder(BeanA.class);
- Assert.assertNotNull(aBeanABinder);
- Assert.assertEquals(binderA, aBeanABinder);
- Binder<BeanB, BeanB> beanBBinder = BinderProvider.getBinder(BeanB.class);
- Assert.assertNull(beanBBinder);
-
-
- }
-
- @Test
- public void testGetMirroredBinderWithName() throws Exception {
- BinderProvider.registerBinder(binderA, MY_BINDER_NAME);
- Binder<BeanA, BeanA> beanABinder;
- Binder<BeanB, BeanB> beanBBinder;
-
- beanABinder = BinderProvider.getBinder(BeanA.class);
- Assert.assertNull(beanABinder);
- beanABinder = BinderProvider.getBinder(BeanA.class, MY_BINDER_NAME);
- Assert.assertNotNull(beanABinder);
- Assert.assertEquals(binderA, beanABinder);
- beanBBinder = BinderProvider.getBinder(BeanB.class);
-
- Assert.assertNull(beanBBinder);
- beanBBinder = BinderProvider.getBinder(BeanB.class, MY_BINDER_NAME);
-
- Assert.assertNull(beanBBinder);
- }
-
- @Test
- public void testGetBinder() throws Exception {
-
- BinderProvider.registerBinder(binderB);
- Binder<BeanA, BeanA> beanABinder;
- Binder<BeanA, BeanB> beanBBinder;
-
- beanABinder = BinderProvider.getBinder(BeanA.class);
- Assert.assertNull(beanABinder);
-
- beanBBinder = BinderProvider.getBinder(BeanA.class, BeanB.class);
- Assert.assertNotNull(beanBBinder);
- Assert.assertEquals(binderB, beanBBinder);
-
- }
-
- @Test
- public void testGetBinderWithName() throws Exception {
- BinderProvider.registerBinder(binderB, MY_BINDER2_NAME);
- Binder<BeanA, BeanA> beanABinder;
- Binder<BeanA, BeanB> beanBBinder;
-
- beanABinder = BinderProvider.getBinder(BeanA.class);
- Assert.assertNull(beanABinder);
-
- beanBBinder = BinderProvider.getBinder(BeanA.class, BeanB.class);
- Assert.assertNull(beanBBinder);
-
- beanBBinder = BinderProvider.getBinder(BeanA.class, BeanB.class, MY_BINDER2_NAME);
- Assert.assertNotNull(beanBBinder);
- Assert.assertEquals(binderB, beanBBinder);
-
-
- }
-}
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2011-01-17 18:49:58 UTC (rev 2016)
+++ trunk/pom.xml 2011-01-17 18:50:24 UTC (rev 2017)
@@ -57,14 +57,14 @@
<version>${nuitonI18nVersion}</version>
</dependency>
- <!-- Dependency for WarLauncher deprecated since 2.0, will be removed in 2.1 -->
+ <!-- Dependency for WarLauncher deprecated since 2.0, will be removed in 2.1 -->
<dependency>
<groupId>org.jvnet.hudson.winstone</groupId>
<artifactId>winstone</artifactId>
<version>0.9.10-hudson-24</version>
</dependency>
- <!-- Dependency for WarLauncher deprecated since 2.0, will be removed in 2.1 -->
+ <!-- Dependency for WarLauncher deprecated since 2.0, will be removed in 2.1 -->
<dependency>
<groupId>org.eclipse.jetty.aggregate</groupId>
<artifactId>jetty-webapp</artifactId>
@@ -200,6 +200,8 @@
<nuitonI18nVersion>2.0.1</nuitonI18nVersion>
+ <hibernateValidatorVersion>4.1.0.Final</hibernateValidatorVersion>
+
<aspectwerkzVersion>2.0</aspectwerkzVersion>
<tapestryVersion>5.1.0.5</tapestryVersion>
1
0
r2016 - in trunk/nuiton-validator/src/main/java/org/nuiton/validator: . xwork2
by tchemit@users.nuiton.org 17 Jan '11
by tchemit@users.nuiton.org 17 Jan '11
17 Jan '11
Author: tchemit
Date: 2011-01-17 19:49:58 +0100 (Mon, 17 Jan 2011)
New Revision: 2016
Url: http://nuiton.org/repositories/revision/nuiton-utils/2016
Log:
begin of documentation for the new validator api
Added:
trunk/nuiton-validator/src/main/java/org/nuiton/validator/package-info.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/package-info.java
Added: trunk/nuiton-validator/src/main/java/org/nuiton/validator/package-info.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/package-info.java (rev 0)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/package-info.java 2011-01-17 18:49:58 UTC (rev 2016)
@@ -0,0 +1,60 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+/**
+ * Package of Nuiton-validator api.
+ *
+ * <h1>The <b>Validator</b> api</h1>
+ * <p>
+ * The {@link NuitonValidator} is the object responsible to launch validation
+ * for a given object and then return the result of validation in a
+ * {@link NuitonValidatorResult} via the method {@code validate}.
+ * </p>
+ *
+ * <pre>
+ * NuitonValidator<O> validator = XXX;
+ * NuitonValidatorResult result = validator.validate(o);
+ * </pre>
+ *
+ * <h2>Obtain a validator</h2>
+ * To obtain a validator use the factory of validators ({@link NuitonValidatorFactory}.
+ * <br/>
+ * <pre>
+ * NuitonValidator<O> validator = NuitonValidatorFactory.newValidator(O.class);
+ * </pre>
+ *
+ * <h2>Implements the validator api</h2>
+ *
+ * At the moment, there is an offered implementation based on xwork2 framework.
+ *
+ * <strong>To be continued...</strong>
+ *
+ * @since 2.0
+ */
+package org.nuiton.validator;
+
+
+import org.nuiton.validator.NuitonValidator;
+import org.nuiton.validator.NuitonValidatorFactory;
+import org.nuiton.validator.NuitonValidatorResult;
\ No newline at end of file
Property changes on: trunk/nuiton-validator/src/main/java/org/nuiton/validator/package-info.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/package-info.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/package-info.java (rev 0)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/package-info.java 2011-01-17 18:49:58 UTC (rev 2016)
@@ -0,0 +1,36 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+/**
+ * Package of xworks2 implementation of the Nuiton-validator api.
+ *
+ * <strong>To be continued...</strong>
+ *
+ * @since 2.0
+ */
+package org.nuiton.validator.xwork2;
+
+import org.nuiton.validator.NuitonValidator;
+import org.nuiton.validator.NuitonValidatorFactory;
+import org.nuiton.validator.NuitonValidatorResult;
\ No newline at end of file
Property changes on: trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/package-info.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
1
0
r2015 - in trunk/nuiton-validator/src: main/java/org/nuiton/validator main/java/org/nuiton/validator/legacy test/java/org/nuiton/validator test/java/org/nuiton/validator/legacy test/resources/org/nuiton/validator test/resources/org/nuiton/validator/legacy
by tchemit@users.nuiton.org 17 Jan '11
by tchemit@users.nuiton.org 17 Jan '11
17 Jan '11
Author: tchemit
Date: 2011-01-17 19:36:18 +0100 (Mon, 17 Jan 2011)
New Revision: 2015
Url: http://nuiton.org/repositories/revision/nuiton-utils/2015
Log:
move all old code to a legacy package (will be removed before version 2.0)
Added:
trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidator.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorDetector.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorEvent.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorField.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorListener.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorMessage.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorScope.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorUtil.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/ValidatorsMap.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/XWorkBeanValidator.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/
trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/AbstractBeanValidatorDetectorTest.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/BeanValidatorDetectorTest.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/BeanValidatorTest.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/SimpleBean.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/XWorkBeanValidatorTest.java
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-error-validation.xml
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-fatal-validation.xml
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-info-validation.xml
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-simple-validation.xml
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-warning-validation.xml
Removed:
trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidator.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorDetector.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorEvent.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorField.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorListener.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorMessage.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorScope.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorUtil.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/ValidatorsMap.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/XWorkBeanValidator.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/AbstractBeanValidatorDetectorTest.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/BeanValidatorDetectorTest.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/BeanValidatorTest.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/SimpleBean.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/XWorkBeanValidatorTest.java
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-error-validation.xml
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-fatal-validation.xml
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-info-validation.xml
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-simple-validation.xml
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-warning-validation.xml
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/field/
Deleted: trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidator.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidator.java 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidator.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,635 +0,0 @@
-/*
- * #%L
- * Nuiton Utils :: Nuiton Validator
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 CodeLutin, Tony Chemit
- * %%
- * This program 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 3 of the
- * License, or (at your option) any later version.
- *
- * This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/lgpl-3.0.html>.
- * #L%
- */
-package org.nuiton.validator;
-
-import org.apache.commons.beanutils.ConversionException;
-import org.apache.commons.beanutils.Converter;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.util.converter.ConverterUtil;
-
-import javax.swing.event.EventListenerList;
-import java.beans.EventSetDescriptor;
-import java.beans.Introspector;
-import java.beans.PropertyChangeEvent;
-import java.beans.PropertyChangeListener;
-import java.beans.PropertyChangeSupport;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.TreeMap;
-
-/**
- * A customized validator for a given bean.
- * <p/>
- * <b>Note:</b> The bean must be listenable on properyChange events (means must
- * have public addPropertychangeListener and removePropertyChangeListener
- * methods).
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @param <B> type of the bean to validate.
- */
-public class BeanValidator<B> {
-
- /** la nom de la propriété bean */
- static public final String BEAN_PROERTY = "bean";
-
- /** la nom de la propriété contextName */
- static public final String CONTEXT_NAME_PROPERTY = "contextName";
-
- /** la nom de l'état valid */
- static public final String VALID_PROERTY = "valid";
-
- /** la nom de l'état changed */
- static public final String CHANGED_PROERTY = "changed";
-
- /** Logger */
- static protected final Log log = LogFactory.getLog(BeanValidator.class);
-
- protected static final BeanValidatorScope[] FILTER_SCOPES_EMPTY =
- new BeanValidatorScope[0];
-
- /** the type of bean to watch */
- protected final Class<B> beanClass;
-
- /** the validation named context (can be null) */
- protected String contextName;
-
- /** to chain to a prent validator */
- protected BeanValidator<?> parentValidator;
-
- /**
- * state to indicate that validator has changed since the last time bean was
- * setted
- */
- protected boolean changed;
-
- /** state of the validator (is true if no errors of error scope is found) */
- protected boolean valid = true;
-
- /** bean to be watched */
- protected B bean;
-
- /** to add and remove PropertyChangeListener on watched beans */
- protected EventSetDescriptor beanEventDescriptor;
-
- /** list of fields watched by this validator */
- protected Set<BeanValidatorField<B>> fields;
-
- /** map of conversion errors detected by this validator */
- protected Map<String, String> conversionErrors;
-
- /** xworks scope validator * */
- protected EnumMap<BeanValidatorScope, XWorkBeanValidator<B>> validators;
-
- /** filter scopes (if {@code null}, no filter on scopes) */
- protected BeanValidatorScope[] filterScopes;
-
- /** listener that listens on bean modification */
- protected PropertyChangeListener l;
-
- /** delegate property change support */
- protected PropertyChangeSupport pcs;
-
- /** A list of event listeners for this validators */
- protected EventListenerList listenerList = new EventListenerList();
-
- public BeanValidator(Class<B> beanClass,
- String contextName) {
- this(beanClass,
- contextName,
- BeanValidatorScope.values()
- );
- }
-
- public BeanValidator(Class<B> beanClass,
- String contextName,
- BeanValidatorScope... filterScopes) {
- this.beanClass = beanClass;
- if (filterScopes != null && filterScopes.length > 0) {
- this.filterScopes = filterScopes;
- }
- pcs = new PropertyChangeSupport(this);
- conversionErrors = new TreeMap<String, String>();
- validators = new EnumMap<BeanValidatorScope, XWorkBeanValidator<B>>(
- BeanValidatorScope.class);
-
- setContextName(contextName);
-
- l = new PropertyChangeListener() {
-
- @Override
- public void propertyChange(PropertyChangeEvent evt) {
- // chaque modification lance la validation
- doValidate();
- }
- };
- }
-
- public Class<B> getBeanClass() {
- return beanClass;
- }
-
- public BeanValidator<?> getParentValidator() {
- return parentValidator;
- }
-
- public String getContextName() {
- return contextName;
- }
-
- public Set<BeanValidatorField<B>> getFields() {
- return fields;
- }
-
- public Set<BeanValidatorScope> getScopes() {
- return new HashSet<BeanValidatorScope>(validators.keySet());
- }
-
- /**
- * Retourne vrai si l'objet bean a ete modifie depuis le dernier {@link
- * #setBean}
- *
- * @return <code>true</code> if bean was modify since last {@link
- * #setBean(Object)} invocation
- */
- public boolean isChanged() {
- return changed;
- }
-
- public boolean isValid() {
- return valid;
- }
-
- public B getBean() {
- return bean;
- }
-
- public BeanValidatorField<B> getField(String fieldName) {
- for (BeanValidatorField<B> field : fields) {
- if (fieldName.equals(field.getName())) {
- return field;
- }
- }
- return null;
- }
-
- public boolean hasFatalErrors() {
- for (BeanValidatorField<B> field : fields) {
- if (field.hasFatalErrors()) {
- return true;
- }
- }
- return false;
- }
-
- public boolean hasErrors() {
- for (BeanValidatorField<B> field : fields) {
- if (field.hasErrors()) {
- return true;
- }
- }
- return false;
- }
-
- public boolean hasWarnings() {
- for (BeanValidatorField<B> field : fields) {
- if (field.hasWarnings()) {
- return true;
- }
- }
- return false;
- }
-
- public boolean hasInfos() {
- for (BeanValidatorField<B> field : fields) {
- if (field.hasInfos()) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Test a the validator contains the field given his name
- *
- * @param fieldName the name of the searched field
- * @return <code>true</code> if validator contaisn this field,
- * <code>false</code> otherwise
- */
- public boolean containsField(String fieldName) {
- BeanValidatorField<B> field = getField(fieldName);
- return field != null;
- }
-
- public boolean isValid(String fieldName) {
- BeanValidatorField<B> field = getField(fieldName);
- if (field == null) {
- throw new IllegalArgumentException(
- "could not find a validator field " + fieldName);
- }
- return field.isValid();
- }
-
- /**
- * Permet de force la remise a false de l'etat de changement du bean
- *
- * @param changed flag to force reset of property {@link #changed}
- */
- public void setChanged(boolean changed) {
- this.changed = changed;
- // force the property to be fired (never pass the older value)
- pcs.firePropertyChange(CHANGED_PROERTY, null, changed);
- }
-
- public void setValid(boolean valid) {
- this.valid = valid;
- // force the property to be fired (never pass the older value)
- pcs.firePropertyChange(VALID_PROERTY, null, valid);
- }
-
- public void setBean(B bean) {
- B oldBean = this.bean;
- if (log.isDebugEnabled()) {
- log.debug(this + " : " + bean);
- }
-
- // clean conversions of previous bean
- conversionErrors.clear();
-
- if (oldBean != null) {
- try {
- EventSetDescriptor descriptor = getBeanEventDescriptor(oldBean);
- descriptor.getRemoveListenerMethod().invoke(oldBean, l);
- } catch (Exception eee) {
- if (log.isInfoEnabled()) {
- log.info("Can't register as listener for bean " + beanClass +
- " for reason " + eee.getMessage(), eee);
- }
- }
- }
- this.bean = bean;
-
- if (bean == null) {
-
- // remove all messages for all fields of the validator
-
- for (BeanValidatorField<B> f : fields) {
-
- f.updateMessages(this, null, null);
- }
-
- } else {
- try {
- EventSetDescriptor descriptor = getBeanEventDescriptor(bean);
- descriptor.getAddListenerMethod().invoke(bean, l);
- } catch (Exception eee) {
- if (log.isInfoEnabled()) {
- log.info("Can't register as listener for bean " + beanClass +
- " for reason " + eee.getMessage(), eee);
- }
- }
- validate();
- }
- setChanged(false);
- setValid(!hasFatalErrors() && !hasErrors());
- pcs.firePropertyChange(BEAN_PROERTY, oldBean, bean);
- }
-
- public void setContextName(String contextName) {
- String oldContextName = this.contextName;
- this.contextName = contextName;
- // changing contextName could change fields definition
- // so dettach bean, must rebuild the fields
- if (bean != null) {
- setBean(null);
- }
- // rebuild the fields
- initFields();
- pcs.firePropertyChange(CONTEXT_NAME_PROPERTY,
- oldContextName,
- contextName
- );
- }
-
- /**
- * Sets the filter scopes.
- *
- * @param filterScopes the scopes to used
- */
- public void setFilterScopes(BeanValidatorScope... filterScopes) {
- this.filterScopes = filterScopes;
- // changing contextName could change fields definition
- // so dettach bean, must rebuild the fields
- if (bean != null) {
- setBean(null);
- }
- // rebuild the fields
- initFields();
- }
-
- public void setParentValidator(BeanValidator<?> parentValidator) {
- this.parentValidator = parentValidator;
- }
-
- /**
- * Convert a value.
- * <p/>
- * If an error occurs, then add an error in validator.
- *
- * @param <T> the type of conversion
- * @param fieldName the name of the bean property
- * @param value the value to convert
- * @param valueClass the type of converted value
- * @return the converted value, or null if conversion was not ok
- */
- @SuppressWarnings({"unchecked"})
- public <T> T convert(String fieldName, String value, Class<T> valueClass) {
- if (fieldName == null) {
- throw new IllegalArgumentException("fieldName can not be null");
- }
- if (valueClass == null) {
- throw new IllegalArgumentException("valueClass can not be null");
- }
-
- // on ne convertit pas si il y a un bean et que le resultat de la
- // validation pourra etre affiche quelque part
- if (!canValidate() || value == null) {
- return null;
- }
-
- // remove the previous conversion error for the field
- conversionErrors.remove(fieldName);
-
- T result;
- try {
- Converter converter = ConverterUtil.getConverter(valueClass);
- if (converter == null) {
- throw new RuntimeException(
- "could not find converter for the type " + valueClass);
- }
- result = (T) converter.convert(valueClass, value);
- /* Why this test ? if (result != null && !value.equals(result.toString())) {
- conversionErrors.put(fieldName, "error.convertor." + Introspector.decapitalize(valueClass.getSimpleName()));
- result = null;
- validate();
- }*/
- } catch (ConversionException e) {
- // get
- String s = Introspector.decapitalize(valueClass.getSimpleName());
- conversionErrors.put(fieldName, "error.convertor." + s);
- result = null;
- validate();
- }
- return result;
- }
-
- /**
- * Methode pour forcer la revalidation d'un bean en mettant a jour les etats
- * internes.
- * <p/>
- * La méthode appelle {@link #validate()} puis met à jour les etats internes
- * {@link #valid} et {@link #changed}.
- *
- * @since 1.5
- */
- public void doValidate() {
- validate();
- setValid(!hasFatalErrors() && !hasErrors());
- setChanged(true);
- }
-
- /**
- * il faut eviter le code re-intrant (durant une validation, une autre est
- * demandee). Pour cela on fait la validation dans un thread, et tant que la
- * premiere validation n'est pas fini, on ne repond pas aux solicitations.
- * Cette method est public pour permettre de force une validation par
- * programmation, ce qui est utile par exemple si le bean ne supporte pas
- * les {@link PropertyChangeListener}
- * <p/>
- * <b>Note:</b> la methode est protected et on utilise la methode
- * {@link #doValidate()} car la méthode ne modifie pas les etats
- * internes et cela en rend son utilisation delicate (le validateur entre
- * dans un etat incoherent par rapport aux messages envoyés).
- */
- protected void validate() {
-
- // on ne valide que si il y a un bean et que le resultat de la validation
- // pourra etre affiche quelque part
- if (!canValidate()) {
- return;
- }
-
- for (BeanValidatorScope scope : validators.keySet()) {
-
- XWorkBeanValidator<B> validator = validators.get(scope);
-
- Map<String, List<String>> newMessages = validator.validate(bean);
-
- if (scope == BeanValidatorScope.ERROR) {
- // treate conversion errors
- // reinject them
- for (Entry<String, String> entry : conversionErrors.entrySet()) {
- // remove from validation, errors occurs on this field
- List<String> errors = newMessages.get(entry.getKey());
- String conversionError = entry.getValue();
- if (errors != null) {
- errors.clear();
- errors.add(conversionError);
- } else {
- errors = Collections.singletonList(conversionError);
- if (XWorkBeanValidator.EMPTY_RESULT.equals(newMessages)) {
- newMessages = new HashMap<String, List<String>>();
- }
- // add the concrete conversion error
- newMessages.put(entry.getKey(), errors);
- }
- }
- }
-
- // for each field, update his list of messages
- for (BeanValidatorField<B> field : fields) {
- List<String> messagesForField = newMessages.get(field.getName());
- if (field.getScopes().contains(scope)) {
- field.updateMessages(this, scope, messagesForField);
- }
- }
- }
-
- if (parentValidator != null) {
- // chained validation
- // the parent validator should not be changed from this validation
- boolean wasModified = parentValidator.isChanged();
- parentValidator.doValidate();
- if (!wasModified) {
- // push back old state
- parentValidator.setChanged(false);
- }
- }
-
- }
-
- @Override
- public String toString() {
- return super.toString() + "<beanClass:" + beanClass +
- ", contextName:" + contextName + ">";
- }
-
- public void addBeanValidatorListener(BeanValidatorListener listener) {
- listenerList.add(BeanValidatorListener.class, listener);
- }
-
- public void removeBeanValidatorListener(BeanValidatorListener listener) {
- listenerList.remove(BeanValidatorListener.class, listener);
- }
-
- public BeanValidatorListener[] getBeanValidatorListeners() {
- return listenerList.getListeners(BeanValidatorListener.class);
- }
-
- public void addPropertyChangeListener(PropertyChangeListener listener) {
- pcs.addPropertyChangeListener(listener);
- }
-
- public void addPropertyChangeListener(String propertyName,
- PropertyChangeListener listener) {
- pcs.addPropertyChangeListener(propertyName, listener);
- }
-
- public void removePropertyChangeListener(PropertyChangeListener listener) {
- pcs.removePropertyChangeListener(listener);
- }
-
- public void removePropertyChangeListener(String propertyName,
- PropertyChangeListener listener) {
- pcs.removePropertyChangeListener(propertyName, listener);
- }
-
- /**
- * @return <code>true</code> if validation is enabled, <code>false</code>
- * otherwise.
- */
- protected boolean canValidate() {
- return !(bean == null || fields.isEmpty());
- }
-
- protected void fireFieldChanged(BeanValidatorField<B> field,
- BeanValidatorScope scope,
- String[] toAdd,
- String[] toDelete) {
-
- BeanValidatorEvent evt = new BeanValidatorEvent(
- this,
- field,
- scope,
- toAdd,
- toDelete
- );
-
- for (BeanValidatorListener listener :
- listenerList.getListeners(BeanValidatorListener.class)) {
- listener.onFieldChanged(evt);
- }
- }
-
- protected void initFields() {
-
- Set<String> detectedFieldNames = new HashSet<String>();
- EnumMap<BeanValidatorScope, Set<String>> tmp;
- tmp = new EnumMap<BeanValidatorScope, Set<String>>(
- BeanValidatorScope.class
- );
- Set<BeanValidatorField<B>> detectedFields =
- new HashSet<BeanValidatorField<B>>();
-
- validators.clear();
-
- BeanValidatorScope[] scopeUniverse;
- if (filterScopes == null) {
- // use all scopes
- scopeUniverse = BeanValidatorScope.values();
- } else {
- // use customized scopes
- scopeUniverse = filterScopes;
- }
-
- for (BeanValidatorScope scope : scopeUniverse) {
- String scopeContext =
- (contextName == null ? "" : contextName + "-") +
- scope.name().toLowerCase();
-
- XWorkBeanValidator<B> newValidator =
- new XWorkBeanValidator<B>(beanClass, scopeContext, false);
- Set<String> fieldNames = newValidator.getFieldNames();
- if (log.isDebugEnabled()) {
- log.debug("detected validators for scope " + scopeContext +
- " : " + fieldNames);
- }
- if (!fieldNames.isEmpty()) {
- // fields detected in this validator, keep it
- validators.put(scope, newValidator);
- detectedFieldNames.addAll(fieldNames);
- tmp.put(scope, fieldNames);
- }
- }
-
- List<BeanValidatorScope> scopes = new ArrayList<BeanValidatorScope>();
- for (String fieldName : detectedFieldNames) {
- scopes.clear();
- // detect scopes for the field
- for (BeanValidatorScope scope : scopeUniverse) {
- if (tmp.containsKey(scope) &&
- tmp.get(scope).contains(fieldName)) {
- scopes.add(scope);
- }
- }
- BeanValidatorField<B> f =
- new BeanValidatorField<B>(beanClass, fieldName, scopes);
- detectedFields.add(f);
- }
- tmp.clear();
- detectedFieldNames.clear();
-
- fields = Collections.unmodifiableSet(detectedFields);
- }
-
- protected EventSetDescriptor getBeanEventDescriptor(B bean) {
- if (beanEventDescriptor == null) {
- // check that the bean is listenable, otherwise, can't use the
- // validator on it
- beanEventDescriptor =
- BeanValidatorUtil.getPropertyChangeListenerDescriptor(
- bean.getClass()
- );
- }
- return beanEventDescriptor;
- }
-}
Deleted: trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorDetector.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorDetector.java 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorDetector.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,342 +0,0 @@
-/*
- * #%L
- * Nuiton Utils :: Nuiton Validator
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 CodeLutin, Tony Chemit
- * %%
- * This program 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 3 of the
- * License, or (at your option) any later version.
- *
- * This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/lgpl-3.0.html>.
- * #L%
- */
-package org.nuiton.validator;
-
-import org.apache.commons.beanutils.ConstructorUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import java.io.File;
-import java.io.FilenameFilter;
-import java.lang.reflect.Constructor;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Set;
-import java.util.SortedSet;
-import java.util.TreeSet;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Un detecteur de validateurs pour un liste de classes données et un répertoire
- * où chercher les fichiers de validation.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 1.6.0
- */
-public class BeanValidatorDetector {
-
- /** Logger */
- private static final Log log =
- LogFactory.getLog(BeanValidatorDetector.class);
-
- public SortedSet<BeanValidator<?>> detect(File sourceRoot,
- Class<?>... types) {
- SortedSet<BeanValidator<?>> result =
- detect(BeanValidator.class, sourceRoot, null, types);
- return result;
- }
-
- public SortedSet<BeanValidator<?>> detect(Class<?> validatorClass,
- File sourceRoot,
- Pattern contextFilter,
- Class<?>... types) {
- SortedSet<BeanValidator<?>> result = detect(validatorClass,
- sourceRoot,
- contextFilter,
- null,
- types);
- return result;
- }
-
- public SortedSet<BeanValidator<?>> detect(Class<?> validatorClass,
- File sourceRoot,
- Pattern contextFilter,
- BeanValidatorScope[] scopes,
- Class<?>... types) {
-
- SortedSet<BeanValidator<?>> result =
- new TreeSet<BeanValidator<?>>(new BeanValidatorComparator());
-
- for (Class<?> c : types) {
- File dir = getClassDir(sourceRoot, c);
- if (!dir.exists()) {
-
- // pas de repertoire adequate
- if (log.isDebugEnabled()) {
- log.debug("skip non existing directory " + dir);
- }
- continue;
- }
- String[] contexts = getContexts(c, dir);
- if (log.isDebugEnabled()) {
- log.debug("contexts : " + Arrays.toString(contexts));
- }
-
- if (contexts.length > 0) {
- String[] realContexts = getContextsWithoutScopes(contexts);
-
- if (log.isDebugEnabled()) {
- log.debug("realContexts : " +
- Arrays.toString(realContexts));
- }
-
- if (contextFilter != null) {
-
- // filter contexts
- realContexts = getFilterContexts(contextFilter,
- realContexts
- );
- if (log.isDebugEnabled()) {
- log.debug("filterContexts : " +
- Arrays.toString(realContexts));
- }
- }
-
- for (String context : realContexts) {
-
- // on cherche le validateur
- BeanValidator<?> validator = getValidator(
- validatorClass,
- c,
- context.isEmpty() ? null : context,
- scopes
- );
- if (validator != null) {
- // on enregistre le validateur
- result.add(validator);
- }
- }
- }
- }
- return result;
- }
-
- /**
- * Pour un context et un type d'entité donné, instancie un validateur et
- * test si ce validateur est utilisable (i.e qu'il admet des champs à
- * valider).
- * <p/>
- * Si aucun champ n'est trouvé dans le validateur, alors on retourne null.
- *
- * @param <B> le type du bean
- * @param validatorClass le type de validateur a instancie
- * @param klass le type du bean
- * @param context le context du validateur
- * @param scopes les scopes a utiliser (si {@code null} alors pas de
- * filtre sur les scopes)
- * @return le validateur initialisé, ou <code>null</code> si aucun scope
- * détecté dans le validateur.
- */
- protected <B> BeanValidator<B> getValidator(Class<?> validatorClass,
- Class<B> klass,
- String context,
- BeanValidatorScope... scopes) {
-
- BeanValidator<B> valitator;
- valitator = createValidator(validatorClass, klass, context, scopes);
-
- Set<BeanValidatorScope> resultScopes = valitator.getScopes();
- if (resultScopes.isEmpty()) {
- valitator = null;
- if (log.isDebugEnabled()) {
- log.debug(klass + " : validator skip (no scopes detected)");
- }
- } else {
- if (log.isDebugEnabled()) {
- log.debug(klass + " : keep validator " + valitator);
- }
- }
- return valitator;
- }
-
- protected <B> BeanValidator<B> createValidator(
- Class<?> validatorClass,
- Class<B> klass,
- String context,
- BeanValidatorScope[] scopes) {
- BeanValidator<B> valitator;
- Constructor<?> con;
- try {
- con = ConstructorUtils.getAccessibleConstructor(
- validatorClass,
- new Class<?>[]{
- Class.class,
- String.class,
- BeanValidatorScope[].class
- }
- );
- if (con != null) {
-
- valitator = (BeanValidator<B>) con.newInstance(
- klass,
- context, scopes
- );
-
- } else {
- con = ConstructorUtils.getAccessibleConstructor(
- validatorClass,
- new Class<?>[]{
- Class.class,
- String.class,
- BeanValidatorScope[].class
- }
- );
-
- if (con == null) {
- throw new IllegalStateException(
- "could not find a constructor with " +
- "(Class.class, String) or " +
- "(Class,String BeanValidatorScope[])");
- }
-
- valitator = (BeanValidator<B>) con.newInstance(
- klass,
- context
- );
- if (scopes != null && scopes.length > 0) {
- valitator.setFilterScopes(scopes);
- }
- }
-
- } catch (Exception ex) {
- throw new RuntimeException(
- "could not instanciate validator " + validatorClass +
- " for reason " + ex.getMessage(), ex);
- }
- return valitator;
- }
-
- protected File getClassDir(File sourceRoot, Class<?> clazz) {
- String path = clazz.getPackage().getName();
- path = path.replaceAll("\\.", File.separator);
- File dir = new File(sourceRoot, path);
- return dir;
- }
-
- protected String[] getContexts(Class<?> clazz, File dir) {
- Set<String> result = new TreeSet<String>();
- ValidatorFilenameFilter filter = new ValidatorFilenameFilter(clazz);
- if (log.isDebugEnabled()) {
- log.debug("dir : " + dir);
- }
- String[] files = dir.list(filter);
- for (String file : files) {
- if (log.isDebugEnabled()) {
- log.debug("file " + file);
- }
- String context = file.substring(
- filter.prefix.length(),
- file.length() - ValidatorFilenameFilter.SUFFIX.length()
- );
- if (log.isDebugEnabled()) {
- log.debug("detect " + clazz.getSimpleName() +
- " context [" + context + "]");
- }
- result.add(context);
- }
- return result.toArray(new String[result.size()]);
- }
-
- protected String[] getContextsWithoutScopes(String[] contexts) {
- Set<String> result = new TreeSet<String>();
- BeanValidatorScope[] scopes = BeanValidatorScope.values();
- for (String context : contexts) {
- for (BeanValidatorScope scope : scopes) {
- String scopeName = scope.name().toLowerCase();
- if (!context.endsWith(scopeName)) {
- // pas concerne par ce scope
- continue;
- }
- if (log.isDebugEnabled()) {
- log.debug("detect context : " + context);
- }
- String realContext = context.substring(
- 0,
- context.length() - scopeName.length()
- );
- if (realContext.endsWith("-")) {
- realContext = realContext.substring(
- 0,
- realContext.length() - 1
- );
- }
- result.add(realContext);
- }
- }
- return result.toArray(new String[result.size()]);
- }
-
- protected String[] getFilterContexts(Pattern contextFilter,
- String[] realContexts) {
- List<String> result = new ArrayList<String>();
- for (String c : realContexts) {
- Matcher m = contextFilter.matcher(c);
- if (m.matches()) {
- result.add(c);
- }
- }
- return result.toArray(new String[result.size()]);
- }
-
- protected static class ValidatorFilenameFilter implements FilenameFilter {
-
- protected static final String SUFFIX = "-validation.xml";
-
- protected Class<?> clazz;
-
- protected String prefix;
-
- public ValidatorFilenameFilter(Class<?> clazz) {
- this.clazz = clazz;
- prefix = clazz.getSimpleName() + "-";
- }
-
- @Override
- public boolean accept(File dir, String name) {
- boolean result = name.endsWith(SUFFIX);
- if (result) {
- result = name.startsWith(prefix);
- }
- return result;
- }
- }
-
- protected static class BeanValidatorComparator implements Comparator<BeanValidator<?>> {
-
- @Override
- public int compare(BeanValidator<?> o1, BeanValidator<?> o2) {
- String contextName1 =
- o1.getBeanClass().getSimpleName() + "-" +
- (o1.getContextName() == null ? "" : o1.getContextName());
- String contextName2 =
- o2.getBeanClass().getSimpleName() + "-" +
- (o2.getContextName() == null ? "" : o2.getContextName());
- return contextName1.compareTo(contextName2);
- }
- }
-}
Deleted: trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorEvent.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorEvent.java 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorEvent.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,86 +0,0 @@
-/*
- * #%L
- * Nuiton Utils :: Nuiton Validator
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 CodeLutin, Tony Chemit
- * %%
- * This program 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 3 of the
- * License, or (at your option) any later version.
- *
- * This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/lgpl-3.0.html>.
- * #L%
- */
-package org.nuiton.validator;
-
-import java.util.EventObject;
-
-/**
- * The definition of an event on {@link BeanValidatorListener}
- * to be fired by a {@link BeanValidator}.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 1.3
- */
-public class BeanValidatorEvent extends EventObject {
-
- private static final long serialVersionUID = 1L;
-
- /** the field impacted by the validator */
- protected BeanValidatorField<?> field;
-
- /** the scope impacted by the event */
- protected BeanValidatorScope scope;
-
- protected String[] messagestoAdd;
-
- protected String[] messagestoDelete;
-
- public BeanValidatorEvent(BeanValidator<?> source,
- BeanValidatorField<?> field,
- BeanValidatorScope scope,
- String[] messagestoAdd,
- String[] messagestoDelete) {
- super(source);
- this.field = field;
- this.scope = scope;
- this.messagestoAdd = messagestoAdd;
- this.messagestoDelete = messagestoDelete;
- }
-
- @Override
- public BeanValidator<?> getSource() {
- return (BeanValidator<?>) super.getSource();
- }
-
- public String getFieldName() {
- return field.getName();
- }
-
- public String[] getMessagesToAdd() {
- return messagestoAdd;
- }
-
- public String[] getMessagesToDelete() {
- return messagestoDelete;
- }
-
- public BeanValidatorScope getScope() {
- return scope;
- }
-
- public BeanValidatorField<?> getField() {
- return field;
- }
-}
Deleted: trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorField.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorField.java 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorField.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,286 +0,0 @@
-/*
- * #%L
- * Nuiton Utils :: Nuiton Validator
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 CodeLutin, Tony Chemit
- * %%
- * This program 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 3 of the
- * License, or (at your option) any later version.
- *
- * This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/lgpl-3.0.html>.
- * #L%
- */
-package org.nuiton.validator;
-
-import com.opensymphony.xwork2.validator.FieldValidator;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.EnumMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.StringTokenizer;
-
-import static org.nuiton.i18n.I18n._;
-
-/**
- * Definition of a field to be handled in a {@link BeanValidator}.
- * <p/>
- * A such class is only registred in {@link BeanValidator } when the field of
- * the bean was found in validator xml configuration file for a {@link
- * FieldValidator} only.
- * <p/>
- * This class use properties {@link #beanClass}, {@link #name} to define his
- * naturel order.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @param <B> the type of the bean handled by the validator and this field of
- * validation.
- * @since 1.3
- */
-public class BeanValidatorField<B> implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- /** the class of bean */
- protected final Class<B> beanClass;
-
- /** name of field in bean */
- protected final String name;
-
- protected EnumMap<BeanValidatorScope, Set<String>> messages;
-
- public BeanValidatorField(Class<B> beanClass,
- String name,
- List<BeanValidatorScope> scopes) {
- this.beanClass = beanClass;
- this.name = name;
- messages = new EnumMap<BeanValidatorScope, Set<String>>(
- BeanValidatorScope.class
- );
- for (BeanValidatorScope scope : scopes) {
- messages.put(scope, new HashSet<String>());
- }
- }
-
- public String getName() {
- return name;
- }
-
- public Class<B> getBeanClass() {
- return beanClass;
- }
-
- /**
- * @return {@code true} if this field is valid : no fatal errors and no
- * errors), {@code false} otherwise.
- */
- public boolean isValid() {
- return !hasFatalErrors() && !hasErrors();
- }
-
- public BeanValidatorScope getScope() {
- if (hasErrors()) {
- return BeanValidatorScope.ERROR;
- }
- if (hasWarnings()) {
- return BeanValidatorScope.WARNING;
- }
- if (hasInfos()) {
- return BeanValidatorScope.INFO;
- }
- return null;
- }
-
- public Set<BeanValidatorScope> getScopes() {
- return messages.keySet();
- }
-
- public boolean hasFatalErrors() {
- return hasMessages(BeanValidatorScope.FATAL);
- }
-
- public boolean hasErrors() {
- return hasMessages(BeanValidatorScope.ERROR);
- }
-
- public boolean hasWarnings() {
- return hasMessages(BeanValidatorScope.WARNING);
- }
-
- public boolean hasInfos() {
- return hasMessages(BeanValidatorScope.INFO);
- }
-
- public Set<String> getFatalErrors() {
- return getMessages(BeanValidatorScope.FATAL);
- }
-
- public Set<String> getErrors() {
- return getMessages(BeanValidatorScope.ERROR);
- }
-
- public Set<String> getWarnings() {
- return getMessages(BeanValidatorScope.WARNING);
- }
-
- public Set<String> getInfos() {
- return getMessages(BeanValidatorScope.INFO);
- }
-
- public boolean hasMessages(BeanValidatorScope scope) {
- return messages.containsKey(scope) && !getMessages(scope).isEmpty();
- }
-
- public Set<String> getMessages(BeanValidatorScope scope) {
- return messages.get(scope);
- }
-
- public void updateMessages(BeanValidator<B> validator,
- BeanValidatorScope scope,
- List<String> messages) {
-
- if (scope == null) {
-
- // special case to reset all messages from all scopes
-
- for (BeanValidatorScope s : getScopes()) {
-
- clearMessages(s, validator);
- }
- return;
- }
-
- if (!this.messages.containsKey(scope)) {
- throw new IllegalArgumentException(
- "the scope " + scope + " was not registred for " + this);
- }
-
- if (messages == null || messages.isEmpty()) {
-
- // no incoming message for this scope
-
- clearMessages(scope, validator);
- return;
- }
-
- // build the diff of messages (the one to delete, the one to add)
-
- boolean hasChanged = false;
-
- Set<String> currentMessages = getMessages(scope);
-
- // detect messages to delete
- Set<String> toDelete = new HashSet<String>(currentMessages);
- toDelete.removeAll(messages);
-
- if (!toDelete.isEmpty()) {
- // apply delete
- currentMessages.removeAll(toDelete);
- hasChanged = true;
- }
-
- // detect messages to add
- Set<String> toAdd = new HashSet<String>(messages);
- toAdd.removeAll(currentMessages);
-
- if (!toAdd.isEmpty()) {
- // apply add
- currentMessages.addAll(toAdd);
- hasChanged = true;
- }
-
- if (hasChanged) {
-
- // something has changed, fire notifications
- String[] del = toDelete.toArray(new String[toDelete.size()]);
- String[] add = toAdd.toArray(new String[toAdd.size()]);
-
- validator.fireFieldChanged(this, scope, add, del);
- }
- toAdd.clear();
- toDelete.clear();
-
- }
-
- public String getI18nError(String error) {
- String text;
- if (!error.contains("##")) {
- text = _(error);
- } else {
- StringTokenizer stk = new StringTokenizer(error, "##");
- String errorName = stk.nextToken();
- List<String> args = new ArrayList<String>();
- while (stk.hasMoreTokens()) {
- args.add(stk.nextToken());
- }
- text = _(errorName, args.toArray());
- }
- return text;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (!(o instanceof BeanValidatorField<?>)) {
- return false;
- }
-
- BeanValidatorField<?> that = (BeanValidatorField<?>) o;
- return beanClass.equals(that.beanClass) && name.equals(that.name);
- }
-
- @Override
- public int hashCode() {
- int result = beanClass.hashCode();
- result = 31 * result + name.hashCode();
- return result;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("<").append(super.toString());
- sb.append(" beanClass:").append(beanClass);
- sb.append(", name:").append(name);
- sb.append(", scopes:");
- sb.append(messages == null ? "[]" : messages.keySet());
- sb.append(", scope:").append(getScope());
- //sb.append(", errors:").append(errors);
- sb.append('>');
- return sb.toString();
- }
-
- protected void clearMessages(BeanValidatorScope scope,
- BeanValidator<B> validator) {
- // remove all messages
- Set<String> toDelete = getMessages(scope);
-
- if (!toDelete.isEmpty()) {
-
- // there is some messages to delete
- String[] toDel = toDelete.toArray(new String[toDelete.size()]);
-
- // apply deletion
- toDelete.clear();
-
- // fire
- validator.fireFieldChanged(this, scope, null, toDel);
- }
- }
-}
Deleted: trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorListener.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorListener.java 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorListener.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,43 +0,0 @@
-/*
- * #%L
- * Nuiton Utils :: Nuiton Validator
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 CodeLutin, Tony Chemit
- * %%
- * This program 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 3 of the
- * License, or (at your option) any later version.
- *
- * This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/lgpl-3.0.html>.
- * #L%
- */
-package org.nuiton.validator;
-
-import java.util.EventListener;
-
-/**
- * The listener contract to be used on {@link BeanValidator}
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 1.3
- */
-public interface BeanValidatorListener extends EventListener {
-
- /**
- * Invoked when a validator detects some changes on a field.
- *
- * @param event the event
- */
- void onFieldChanged(BeanValidatorEvent event);
-}
Deleted: trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorMessage.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorMessage.java 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorMessage.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,118 +0,0 @@
-/*
- * #%L
- * Nuiton Utils :: Nuiton Validator
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 CodeLutin, Tony Chemit
- * %%
- * This program 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 3 of the
- * License, or (at your option) any later version.
- *
- * This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/lgpl-3.0.html>.
- * #L%
- */
-package org.nuiton.validator;
-
-/**
- * The object to box a validation message.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @param <E> type of message (use for override {@link #compareTo(Object)}
- * method.
- * @since 1.3
- */
-public class BeanValidatorMessage<E extends BeanValidatorMessage<?>> implements Comparable<E> {
-
- /** the validator that produce the message */
- protected BeanValidator<?> validator;
-
- /** the field that produce the message */
- protected BeanValidatorField<?> field;
-
- /** the label of the message (to be displayed somewhere) */
- protected String message;
-
- /** the scope of the message */
- protected BeanValidatorScope scope;
-
- public BeanValidatorMessage(BeanValidator<?> validator,
- BeanValidatorField<?> field,
- String message,
- BeanValidatorScope scope) {
- this.field = field;
- this.validator = validator;
- this.message = message == null ? null : message.trim();
- this.scope = scope;
- }
-
- public BeanValidator<?> getValidator() {
- return validator;
- }
-
- public BeanValidatorField<?> getField() {
- return field;
- }
-
- public BeanValidatorScope getScope() {
- return scope;
- }
-
- public String getMessage() {
- return message;
- }
-
- @Override
- public int compareTo(E o) {
- // sort on scope
- int result = getScope().compareTo(o.getScope());
- if (result == 0) {
- // sort on field name
- result = field.getName().compareTo(o.field.getName());
- if (result == 0) {
- // sort on message
- result = message.compareTo(o.message);
- }
- }
- return result;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
-
- BeanValidatorMessage<?> that = (BeanValidatorMessage<?>) o;
-
- return field.equals(that.field) &&
- message.equals(that.message) &&
- scope == that.scope;
- }
-
- @Override
- public int hashCode() {
- int result = field.hashCode();
- result = 31 * result + message.hashCode();
- result = 31 * result + scope.hashCode();
- return result;
- }
-
- @Override
- public String toString() {
- return scope + " - " + field.getI18nError(message);
- }
-}
Deleted: trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorScope.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorScope.java 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorScope.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,79 +0,0 @@
-/*
- * #%L
- * Nuiton Utils :: Nuiton Validator
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 CodeLutin, Tony Chemit
- * %%
- * This program 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 3 of the
- * License, or (at your option) any later version.
- *
- * This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/lgpl-3.0.html>.
- * #L%
- */
-package org.nuiton.validator;
-
-import static org.nuiton.i18n.I18n.n_;
-
-/**
- * The differents levels of messages in validation process.
- * <p/>
- * The order of the enum defines the severity of validation.
- * <p/>
- * Always begin with fatal, then error, then if no error found, try warning, then info...
- *
- * @author tchemit <chemit(a)codelutin.com>
- */
-public enum BeanValidatorScope {
-
- /**
- * the fatal error scope level.
- * <p/>
- * When a message of a such scope is found on a validator, then the
- * validator is invalid and modified.
- * @since 2.2.4
- */
- FATAL(n_("validator.scope.fatal.label")),
- /**
- * the error scope level.
- * <p/>
- * When a message of a such scope is found on a validator, then the
- * validator is invalid and modified.
- */
- ERROR(n_("validator.scope.error.label")),
- /**
- * the warning scope level.
- * <p/>
- * When a message of a such scope is found on a validator, then the
- * validator is still valid but modified.
- */
- WARNING(n_("validator.scope.warning.label")),
- /**
- * the information scope level.
- * <p/>
- * When a message of a sucg scope is found on a validator, then the
- * validator is still valid and not modified.
- */
- INFO(n_("validator.scope.info.label"));
-
- private final String label;
-
- BeanValidatorScope(String label) {
- this.label = label;
- }
-
- public String getLabel() {
- return label;
- }
-}
Deleted: trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorUtil.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorUtil.java 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorUtil.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,196 +0,0 @@
-/*
- * #%L
- * Nuiton Utils :: Nuiton Validator
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 CodeLutin, Tony Chemit
- * %%
- * This program 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 3 of the
- * License, or (at your option) any later version.
- *
- * This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/lgpl-3.0.html>.
- * #L%
- */
-package org.nuiton.validator;
-
-import com.opensymphony.xwork2.config.Configuration;
-import com.opensymphony.xwork2.config.ConfigurationManager;
-import com.opensymphony.xwork2.inject.Container;
-import com.opensymphony.xwork2.util.ValueStack;
-import com.opensymphony.xwork2.util.ValueStackFactory;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import java.beans.BeanInfo;
-import java.beans.EventSetDescriptor;
-import java.beans.IntrospectionException;
-import java.beans.Introspector;
-import java.beans.PropertyDescriptor;
-import java.util.EnumMap;
-import java.util.EnumSet;
-import java.util.List;
-
-/**
- * The helper class for validation module.
- *
- * @author tchemit <chemit(a)codelutin.com>
- */
-public class BeanValidatorUtil {
-
- /** Logger */
- static private final Log log = LogFactory.getLog(BeanValidatorUtil.class);
-
- /**
- * a shared value stack to allow external operations on it (for example add
- * some datas in stack to be usedby validators
- */
- static private ValueStack sharedValueStack;
-
- public static ValueStack getSharedValueStack() {
- if (sharedValueStack == null) {
-
- // init context
- ConfigurationManager confManager = new ConfigurationManager();
- Configuration conf = confManager.getConfiguration();
-
- Container container = conf.getContainer();
- ValueStackFactory stackFactory = container.getInstance(
- ValueStackFactory.class);
- sharedValueStack = stackFactory.createValueStack();
- if (log.isDebugEnabled()) {
- log.debug("init shared value stack " + sharedValueStack);
- }
- }
- return sharedValueStack;
- }
-
- protected BeanValidatorUtil() {
- // no instance
- }
-
- /**
- * Convert a value to a given type and then if was succesffull try to set it
- * in the bean manage by the validator.
- *
- * @param validator validator to be involved
- * @param fieldName the name of the bean property
- * @param value the actual value to convert
- * @param valueClass the type of the conversion
- */
- public static void convert(BeanValidator<?> validator,
- String fieldName,
- String value,
- Class<?> valueClass) {
-
- Object result = validator.convert(fieldName, value, valueClass);
- if (result != null) {
- try {
- BeanInfo info =
- Introspector.getBeanInfo(validator.getBean().getClass());
-
- for (PropertyDescriptor descriptor :
- info.getPropertyDescriptors()) {
- if (fieldName.equals(descriptor.getName()) &&
- descriptor.getWriteMethod() != null) {
-
- descriptor.getWriteMethod().invoke(
- validator.getBean(),
- result
- );
- break;
- }
- }
- } catch (Exception e) {
- if (log.isErrorEnabled()) {
- log.error("could not obtain beanInfo for " +
- valueClass.getClass() + ", reason : " +
- e.getMessage(), e);
- }
- }
- } else {
- //fixme : conversion failed, we should be able to notify ui
- // that values has changed ?
- // otherwise, bean value has not changed,...
- }
- }
-
- public static EventSetDescriptor getPropertyChangeListenerDescriptor(Class<?> beanClass) {
- try {
- // check that the bean is listenable, otherwise, can't use
- // the validator on it
- BeanInfo infos = Introspector.getBeanInfo(beanClass);
- EventSetDescriptor[] events = infos.getEventSetDescriptors();
- for (EventSetDescriptor event : events) {
- if ("propertyChange".equals(event.getName())) {
-
- if (event.getAddListenerMethod() == null) {
- // no property event listener, so can not use the validator
- throw new IllegalStateException(
- "no addPropertyChangeListener method found " +
- "for " + beanClass);
- }
- if (event.getRemoveListenerMethod() == null) {
- // no property event listener, so can not use the validator
- throw new IllegalStateException(
- "no removePropertyChangeListener method found" +
- " for " + beanClass);
- }
- return event;
- }
- }
-
- // no property event listener, so can not use the validator
- throw new IllegalStateException(
- "no PropertyChangeListener access method found for " +
- beanClass);
- } catch (IntrospectionException ex) {
- throw new IllegalStateException(
- "could not acquire PropertyChangeListener bean info for " +
- beanClass + " for reason " + ex.getMessage(), ex);
- }
- }
-
- public static EnumSet<BeanValidatorScope> getScopes(
- List<BeanValidatorMessage<?>> messages) {
- EnumSet<BeanValidatorScope> result =
- EnumSet.noneOf(BeanValidatorScope.class);
- for (BeanValidatorMessage<?> m : messages) {
- result.add(m.getScope());
- }
- return result;
- }
-
- public static EnumMap<BeanValidatorScope, Integer> getScopesCount(
- List<BeanValidatorMessage<?>> messages) {
- EnumMap<BeanValidatorScope, Integer> result =
- new EnumMap<BeanValidatorScope, Integer>(BeanValidatorScope.class);
- for (BeanValidatorScope s : BeanValidatorScope.values()) {
- result.put(s, 0);
- }
- for (BeanValidatorMessage<?> m : messages) {
-
- BeanValidatorScope scope = m.getScope();
-
- result.put(scope, result.get(scope) + 1);
- }
-
- for (BeanValidatorScope s : BeanValidatorScope.values()) {
- if (result.get(s) == 0) {
- result.remove(s);
- }
- }
- return result;
- }
-
-}
Deleted: trunk/nuiton-validator/src/main/java/org/nuiton/validator/ValidatorsMap.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/ValidatorsMap.java 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/ValidatorsMap.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,126 +0,0 @@
-/*
- * #%L
- * Nuiton Utils :: Nuiton Validator
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 CodeLutin, Tony Chemit
- * %%
- * This program 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 3 of the
- * License, or (at your option) any later version.
- *
- * This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/lgpl-3.0.html>.
- * #L%
- */
-package org.nuiton.validator;
-
-import java.util.Collection;
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Un dictionnaire de validateurs ordonnees par le type de leur bean.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 2.0.1
- */
-public class ValidatorsMap implements Map<Class<?>, BeanValidator<?>> {
-
- protected final Map<Class<?>, BeanValidator<?>> delegate;
-
- public ValidatorsMap() {
- delegate = new HashMap<Class<?>, BeanValidator<?>>();
- }
-
- public BeanValidatorScope[] getScopes() {
- EnumSet<BeanValidatorScope> result =
- EnumSet.noneOf(BeanValidatorScope.class);
- for (BeanValidator<?> b : values()) {
- result.addAll(b.getScopes());
- }
- return result.toArray(new BeanValidatorScope[result.size()]);
- }
-
-// public <X> BeanValidator<X> getValidator(X klass) {
-// BeanValidator<X> beanValidator = (BeanValidator<X>) get(klass.getClass());
-// return beanValidator;
-// }
-
- public <X> BeanValidator<X> getValidator(Class<X> klass) {
- BeanValidator<X> beanValidator = (BeanValidator<X>) get(klass);
- return beanValidator;
- }
-
- @Override
- public int size() {
- return delegate.size();
- }
-
- @Override
- public boolean isEmpty() {
- return delegate.isEmpty();
- }
-
- @Override
- public boolean containsKey(Object key) {
- return delegate.containsKey(key);
- }
-
- @Override
- public boolean containsValue(Object value) {
- return delegate.containsValue(value);
- }
-
- @Override
- public BeanValidator<?> get(Object key) {
- return delegate.get(key);
- }
-
- @Override
- public BeanValidator<?> put(Class<?> key, BeanValidator<?> value) {
- return delegate.put(key, value);
- }
-
- @Override
- public BeanValidator<?> remove(Object key) {
- return delegate.remove(key);
- }
-
- @Override
- public void putAll(Map<? extends Class<?>, ? extends BeanValidator<?>> m) {
- delegate.putAll(m);
- }
-
- @Override
- public void clear() {
- delegate.clear();
- }
-
- @Override
- public Set<Class<?>> keySet() {
- return delegate.keySet();
- }
-
- @Override
- public Collection<BeanValidator<?>> values() {
- return delegate.values();
- }
-
- @Override
- public Set<Entry<Class<?>, BeanValidator<?>>> entrySet() {
- return delegate.entrySet();
- }
-
-}
Deleted: trunk/nuiton-validator/src/main/java/org/nuiton/validator/XWorkBeanValidator.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/XWorkBeanValidator.java 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/XWorkBeanValidator.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,324 +0,0 @@
-/*
- * #%L
- * Nuiton Utils :: Nuiton Validator
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 CodeLutin, Tony Chemit
- * %%
- * This program 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 3 of the
- * License, or (at your option) any later version.
- *
- * This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/lgpl-3.0.html>.
- * #L%
- */
-package org.nuiton.validator;
-
-import com.opensymphony.xwork2.ActionContext;
-import com.opensymphony.xwork2.ValidationAwareSupport;
-import com.opensymphony.xwork2.config.Configuration;
-import com.opensymphony.xwork2.config.ConfigurationManager;
-import com.opensymphony.xwork2.inject.Container;
-import com.opensymphony.xwork2.util.ValueStack;
-import com.opensymphony.xwork2.util.ValueStackFactory;
-import com.opensymphony.xwork2.validator.ActionValidatorManager;
-import com.opensymphony.xwork2.validator.DelegatingValidatorContext;
-import com.opensymphony.xwork2.validator.FieldValidator;
-import com.opensymphony.xwork2.validator.ValidationException;
-import com.opensymphony.xwork2.validator.Validator;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * A customized validator for a given bean.
- * <p/>
- * Use the method {@link #validate(Object)} to obtain the messages detected by
- * the validator for the given bean.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @param <B> type of the bean to validate.
- * @since 1.3
- */
-public class XWorkBeanValidator<B> {
-
- /** Logger */
- private static final Log log = LogFactory.getLog(XWorkBeanValidator.class);
-
- protected final static Map<String, List<String>> EMPTY_RESULT =
- Collections.unmodifiableMap(new HashMap<String, List<String>>());
-
- /** the type of bean to validate */
- protected final Class<B> beanClass;
-
- /** the validation named context (can be null) */
- protected String contextName;
-
- /** the list of field names detected for this validator */
- protected Set<String> fieldNames;
-
- /** a flag to include or not the default context validators */
- protected boolean includeDefaultContext;
-
- // --
- // XWorks fields
- // --
-
- protected ValidationAwareSupport validationSupport;
-
- protected DelegatingValidatorContext validationContext;
-
- protected ActionValidatorManager validator;
-
- protected ActionContext context;
-
- public XWorkBeanValidator(Class<B> beanClass, String contextName) {
- this(beanClass,
- contextName,
- true,
- BeanValidatorUtil.getSharedValueStack()
- );
- }
-
- public XWorkBeanValidator(Class<B> beanClass,
- String contextName,
- ValueStack vs) {
- this(beanClass, contextName, true, vs);
- }
-
- public XWorkBeanValidator(Class<B> beanClass,
- String contextName,
- boolean includeDefaultContext) {
- this(beanClass,
- contextName,
- includeDefaultContext,
- BeanValidatorUtil.getSharedValueStack()
- );
- }
-
- public XWorkBeanValidator(Class<B> beanClass,
- String contextName,
- boolean includeDefaultContext,
- ValueStack vs) {
-
- this.beanClass = beanClass;
- this.includeDefaultContext = includeDefaultContext;
- validationSupport = new ValidationAwareSupport();
- validationContext = new DelegatingValidatorContext(validationSupport);
-
- if (vs == null) {
- // create a standalone value stack
- ConfigurationManager confManager = new ConfigurationManager();
- Configuration conf = confManager.getConfiguration();
- Container container = conf.getContainer();
- ValueStackFactory stackFactory =
- container.getInstance(ValueStackFactory.class);
- vs = stackFactory.createValueStack();
- if (log.isDebugEnabled()) {
- log.debug("create a standalone value stack " + vs);
- }
- } else {
- if (log.isDebugEnabled()) {
- log.debug("use given value stack " + vs);
- }
- }
-
- context = new ActionContext(vs.getContext());
- ActionContext.setContext(context);
-
- // init validator
- Container container = context.getContainer();
- validator = container.getInstance(ActionValidatorManager.class,
- "no-annotations"
- );
-
- // init context
- setContextName(contextName);
- }
-
- public boolean isIncludeDefaultContext() {
- return includeDefaultContext;
- }
-
- public Class<B> getBeanClass() {
- return beanClass;
- }
-
- public String getContextName() {
- return contextName;
- }
-
- public Set<String> getFieldNames() {
- return fieldNames;
- }
-
- public ActionValidatorManager getValidator() {
- return validator;
- }
-
- /**
- * Test a the validator contains the field given his name
- *
- * @param fieldName the name of the searched field
- * @return <code>true</code> if validator contaisn this field,
- * <code>false</code> otherwise
- */
- public boolean containsField(String fieldName) {
- return fieldNames.contains(fieldName);
- }
-
- public void setIncludeDefaultContext(boolean includeDefaultContext) {
- this.includeDefaultContext = includeDefaultContext;
- if (contextName != null) {
- // reload context
- setContextName(contextName);
- }
- }
-
- public void setContextName(String contextName) {
- this.contextName = contextName;
- // changing contextName may change fields definition
- // so reload fields
- initFields();
- }
-
- /**
- * Valide le bean donné et retourne les messages produits.
- *
- * @param bean le bean a valider (il doit etre non null)
- * @return le dictionnaire des messages produits par la validation indexées
- * par le nom du champs du bean impacté.
- */
- public Map<String, List<String>> validate(B bean) {
-
- if (bean == null) {
- throw new NullPointerException(
- "bean can not be null in method validate");
- }
-
- Map<String, List<String>> result = EMPTY_RESULT;
-
- // on lance la validation uniquement si des champs sont a valider
- if (!fieldNames.isEmpty()) {
-
- try {
-
- //TC - 20081024 : since context is in a ThreadLocal variable,
- // we must do the check
- if (ActionContext.getContext() == null) {
- ActionContext.setContext(context);
- }
-
- validator.validate(bean, contextName, validationContext);
-
- if (log.isTraceEnabled()) {
- log.trace("Action errors: " +
- validationContext.getActionErrors());
- log.trace("Action messages: " +
- validationContext.getActionMessages());
- log.trace("Field errors: " +
- validationContext.getFieldErrors());
- }
-
- if (log.isDebugEnabled()) {
- log.debug(this + " : " +
- validationContext.getFieldErrors());
- }
-
- // retreave errors by field
- if (validationContext.hasFieldErrors()) {
- Map<?, ?> messages = validationContext.getFieldErrors();
- result = new HashMap<String, List<String>>(messages.size());
- for (Object fieldName : messages.keySet()) {
- Collection<?> c =
- (Collection<?>) messages.get(fieldName);
- List<String> mm = new ArrayList<String>(c.size());
- for (Object message : c) {
- // tchemit 2010-08-28 : trim the incoming message
- // (I18n will not translate it otherwise)
- String messageStr = message == null ? "" : message + "";
- mm.add(messageStr.trim());
- }
- result.put(fieldName + "", mm);
- }
- }
-
- } catch (ValidationException eee) {
- if (log.isWarnEnabled()) {
- log.warn("Error during validation on " + beanClass +
- " for reason : " + eee.getMessage(), eee);
- }
-
- } finally {
- // on nettoye toujours le validateur apres operation
- validationSupport.clearErrorsAndMessages();
- }
- }
-
- return result;
- }
-
- @Override
- public String toString() {
- return super.toString() + "<beanClass:" + beanClass +
- ", contextName:" + contextName + ">";
- }
-
- /** update the property {@link #fieldNames}, says search in XWorks */
- protected void initFields() {
-
- if (fieldNames != null) {
- fieldNames = null;
- }
-
- Set<String> detectedFieldNames = new HashSet<String>();
-
- int skip = 0;
- if (contextName != null && !includeDefaultContext) {
- // count the number of validator to skip
- for (Validator<?> v : validator.getValidators(beanClass, null)) {
- // we only work on FieldValidator at the moment
- if (v instanceof FieldValidator) {
- skip++;
- }
- }
- }
-
- for (Validator<?> v : validator.getValidators(beanClass, contextName)) {
- // we only work on FieldValidator at the moment
- if (v instanceof FieldValidator) {
- if (skip > 0) {
- skip--;
- continue;
- }
- FieldValidator fieldValidator = (FieldValidator) v;
- if (log.isDebugEnabled()) {
- log.debug("context " + contextName + " - field " +
- fieldValidator.getFieldName());
- }
- String fName = fieldValidator.getFieldName();
- detectedFieldNames.add(fName);
- }
- }
-
- fieldNames = Collections.unmodifiableSet(detectedFieldNames);
- }
-}
Copied: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidator.java (from rev 2013, trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidator.java)
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidator.java (rev 0)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidator.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,635 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin, Tony Chemit
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.legacy;
+
+import org.apache.commons.beanutils.ConversionException;
+import org.apache.commons.beanutils.Converter;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.util.converter.ConverterUtil;
+
+import javax.swing.event.EventListenerList;
+import java.beans.EventSetDescriptor;
+import java.beans.Introspector;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.beans.PropertyChangeSupport;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.EnumMap;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.TreeMap;
+
+/**
+ * A customized validator for a given bean.
+ * <p/>
+ * <b>Note:</b> The bean must be listenable on properyChange events (means must
+ * have public addPropertychangeListener and removePropertyChangeListener
+ * methods).
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @param <B> type of the bean to validate.
+ */
+public class BeanValidator<B> {
+
+ /** la nom de la propriété bean */
+ static public final String BEAN_PROERTY = "bean";
+
+ /** la nom de la propriété contextName */
+ static public final String CONTEXT_NAME_PROPERTY = "contextName";
+
+ /** la nom de l'état valid */
+ static public final String VALID_PROERTY = "valid";
+
+ /** la nom de l'état changed */
+ static public final String CHANGED_PROERTY = "changed";
+
+ /** Logger */
+ static protected final Log log = LogFactory.getLog(BeanValidator.class);
+
+ protected static final BeanValidatorScope[] FILTER_SCOPES_EMPTY =
+ new BeanValidatorScope[0];
+
+ /** the type of bean to watch */
+ protected final Class<B> beanClass;
+
+ /** the validation named context (can be null) */
+ protected String contextName;
+
+ /** to chain to a prent validator */
+ protected BeanValidator<?> parentValidator;
+
+ /**
+ * state to indicate that validator has changed since the last time bean was
+ * setted
+ */
+ protected boolean changed;
+
+ /** state of the validator (is true if no errors of error scope is found) */
+ protected boolean valid = true;
+
+ /** bean to be watched */
+ protected B bean;
+
+ /** to add and remove PropertyChangeListener on watched beans */
+ protected EventSetDescriptor beanEventDescriptor;
+
+ /** list of fields watched by this validator */
+ protected Set<BeanValidatorField<B>> fields;
+
+ /** map of conversion errors detected by this validator */
+ protected Map<String, String> conversionErrors;
+
+ /** xworks scope validator * */
+ protected EnumMap<BeanValidatorScope, XWorkBeanValidator<B>> validators;
+
+ /** filter scopes (if {@code null}, no filter on scopes) */
+ protected BeanValidatorScope[] filterScopes;
+
+ /** listener that listens on bean modification */
+ protected PropertyChangeListener l;
+
+ /** delegate property change support */
+ protected PropertyChangeSupport pcs;
+
+ /** A list of event listeners for this validators */
+ protected EventListenerList listenerList = new EventListenerList();
+
+ public BeanValidator(Class<B> beanClass,
+ String contextName) {
+ this(beanClass,
+ contextName,
+ BeanValidatorScope.values()
+ );
+ }
+
+ public BeanValidator(Class<B> beanClass,
+ String contextName,
+ BeanValidatorScope... filterScopes) {
+ this.beanClass = beanClass;
+ if (filterScopes != null && filterScopes.length > 0) {
+ this.filterScopes = filterScopes;
+ }
+ pcs = new PropertyChangeSupport(this);
+ conversionErrors = new TreeMap<String, String>();
+ validators = new EnumMap<BeanValidatorScope, XWorkBeanValidator<B>>(
+ BeanValidatorScope.class);
+
+ setContextName(contextName);
+
+ l = new PropertyChangeListener() {
+
+ @Override
+ public void propertyChange(PropertyChangeEvent evt) {
+ // chaque modification lance la validation
+ doValidate();
+ }
+ };
+ }
+
+ public Class<B> getBeanClass() {
+ return beanClass;
+ }
+
+ public BeanValidator<?> getParentValidator() {
+ return parentValidator;
+ }
+
+ public String getContextName() {
+ return contextName;
+ }
+
+ public Set<BeanValidatorField<B>> getFields() {
+ return fields;
+ }
+
+ public Set<BeanValidatorScope> getScopes() {
+ return new HashSet<BeanValidatorScope>(validators.keySet());
+ }
+
+ /**
+ * Retourne vrai si l'objet bean a ete modifie depuis le dernier {@link
+ * #setBean}
+ *
+ * @return <code>true</code> if bean was modify since last {@link
+ * #setBean(Object)} invocation
+ */
+ public boolean isChanged() {
+ return changed;
+ }
+
+ public boolean isValid() {
+ return valid;
+ }
+
+ public B getBean() {
+ return bean;
+ }
+
+ public BeanValidatorField<B> getField(String fieldName) {
+ for (BeanValidatorField<B> field : fields) {
+ if (fieldName.equals(field.getName())) {
+ return field;
+ }
+ }
+ return null;
+ }
+
+ public boolean hasFatalErrors() {
+ for (BeanValidatorField<B> field : fields) {
+ if (field.hasFatalErrors()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public boolean hasErrors() {
+ for (BeanValidatorField<B> field : fields) {
+ if (field.hasErrors()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public boolean hasWarnings() {
+ for (BeanValidatorField<B> field : fields) {
+ if (field.hasWarnings()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public boolean hasInfos() {
+ for (BeanValidatorField<B> field : fields) {
+ if (field.hasInfos()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Test a the validator contains the field given his name
+ *
+ * @param fieldName the name of the searched field
+ * @return <code>true</code> if validator contaisn this field,
+ * <code>false</code> otherwise
+ */
+ public boolean containsField(String fieldName) {
+ BeanValidatorField<B> field = getField(fieldName);
+ return field != null;
+ }
+
+ public boolean isValid(String fieldName) {
+ BeanValidatorField<B> field = getField(fieldName);
+ if (field == null) {
+ throw new IllegalArgumentException(
+ "could not find a validator field " + fieldName);
+ }
+ return field.isValid();
+ }
+
+ /**
+ * Permet de force la remise a false de l'etat de changement du bean
+ *
+ * @param changed flag to force reset of property {@link #changed}
+ */
+ public void setChanged(boolean changed) {
+ this.changed = changed;
+ // force the property to be fired (never pass the older value)
+ pcs.firePropertyChange(CHANGED_PROERTY, null, changed);
+ }
+
+ public void setValid(boolean valid) {
+ this.valid = valid;
+ // force the property to be fired (never pass the older value)
+ pcs.firePropertyChange(VALID_PROERTY, null, valid);
+ }
+
+ public void setBean(B bean) {
+ B oldBean = this.bean;
+ if (log.isDebugEnabled()) {
+ log.debug(this + " : " + bean);
+ }
+
+ // clean conversions of previous bean
+ conversionErrors.clear();
+
+ if (oldBean != null) {
+ try {
+ EventSetDescriptor descriptor = getBeanEventDescriptor(oldBean);
+ descriptor.getRemoveListenerMethod().invoke(oldBean, l);
+ } catch (Exception eee) {
+ if (log.isInfoEnabled()) {
+ log.info("Can't register as listener for bean " + beanClass +
+ " for reason " + eee.getMessage(), eee);
+ }
+ }
+ }
+ this.bean = bean;
+
+ if (bean == null) {
+
+ // remove all messages for all fields of the validator
+
+ for (BeanValidatorField<B> f : fields) {
+
+ f.updateMessages(this, null, null);
+ }
+
+ } else {
+ try {
+ EventSetDescriptor descriptor = getBeanEventDescriptor(bean);
+ descriptor.getAddListenerMethod().invoke(bean, l);
+ } catch (Exception eee) {
+ if (log.isInfoEnabled()) {
+ log.info("Can't register as listener for bean " + beanClass +
+ " for reason " + eee.getMessage(), eee);
+ }
+ }
+ validate();
+ }
+ setChanged(false);
+ setValid(!hasFatalErrors() && !hasErrors());
+ pcs.firePropertyChange(BEAN_PROERTY, oldBean, bean);
+ }
+
+ public void setContextName(String contextName) {
+ String oldContextName = this.contextName;
+ this.contextName = contextName;
+ // changing contextName could change fields definition
+ // so dettach bean, must rebuild the fields
+ if (bean != null) {
+ setBean(null);
+ }
+ // rebuild the fields
+ initFields();
+ pcs.firePropertyChange(CONTEXT_NAME_PROPERTY,
+ oldContextName,
+ contextName
+ );
+ }
+
+ /**
+ * Sets the filter scopes.
+ *
+ * @param filterScopes the scopes to used
+ */
+ public void setFilterScopes(BeanValidatorScope... filterScopes) {
+ this.filterScopes = filterScopes;
+ // changing contextName could change fields definition
+ // so dettach bean, must rebuild the fields
+ if (bean != null) {
+ setBean(null);
+ }
+ // rebuild the fields
+ initFields();
+ }
+
+ public void setParentValidator(BeanValidator<?> parentValidator) {
+ this.parentValidator = parentValidator;
+ }
+
+ /**
+ * Convert a value.
+ * <p/>
+ * If an error occurs, then add an error in validator.
+ *
+ * @param <T> the type of conversion
+ * @param fieldName the name of the bean property
+ * @param value the value to convert
+ * @param valueClass the type of converted value
+ * @return the converted value, or null if conversion was not ok
+ */
+ @SuppressWarnings({"unchecked"})
+ public <T> T convert(String fieldName, String value, Class<T> valueClass) {
+ if (fieldName == null) {
+ throw new IllegalArgumentException("fieldName can not be null");
+ }
+ if (valueClass == null) {
+ throw new IllegalArgumentException("valueClass can not be null");
+ }
+
+ // on ne convertit pas si il y a un bean et que le resultat de la
+ // validation pourra etre affiche quelque part
+ if (!canValidate() || value == null) {
+ return null;
+ }
+
+ // remove the previous conversion error for the field
+ conversionErrors.remove(fieldName);
+
+ T result;
+ try {
+ Converter converter = ConverterUtil.getConverter(valueClass);
+ if (converter == null) {
+ throw new RuntimeException(
+ "could not find converter for the type " + valueClass);
+ }
+ result = (T) converter.convert(valueClass, value);
+ /* Why this test ? if (result != null && !value.equals(result.toString())) {
+ conversionErrors.put(fieldName, "error.convertor." + Introspector.decapitalize(valueClass.getSimpleName()));
+ result = null;
+ validate();
+ }*/
+ } catch (ConversionException e) {
+ // get
+ String s = Introspector.decapitalize(valueClass.getSimpleName());
+ conversionErrors.put(fieldName, "error.convertor." + s);
+ result = null;
+ validate();
+ }
+ return result;
+ }
+
+ /**
+ * Methode pour forcer la revalidation d'un bean en mettant a jour les etats
+ * internes.
+ * <p/>
+ * La méthode appelle {@link #validate()} puis met à jour les etats internes
+ * {@link #valid} et {@link #changed}.
+ *
+ * @since 1.5
+ */
+ public void doValidate() {
+ validate();
+ setValid(!hasFatalErrors() && !hasErrors());
+ setChanged(true);
+ }
+
+ /**
+ * il faut eviter le code re-intrant (durant une validation, une autre est
+ * demandee). Pour cela on fait la validation dans un thread, et tant que la
+ * premiere validation n'est pas fini, on ne repond pas aux solicitations.
+ * Cette method est public pour permettre de force une validation par
+ * programmation, ce qui est utile par exemple si le bean ne supporte pas
+ * les {@link PropertyChangeListener}
+ * <p/>
+ * <b>Note:</b> la methode est protected et on utilise la methode
+ * {@link #doValidate()} car la méthode ne modifie pas les etats
+ * internes et cela en rend son utilisation delicate (le validateur entre
+ * dans un etat incoherent par rapport aux messages envoyés).
+ */
+ protected void validate() {
+
+ // on ne valide que si il y a un bean et que le resultat de la validation
+ // pourra etre affiche quelque part
+ if (!canValidate()) {
+ return;
+ }
+
+ for (BeanValidatorScope scope : validators.keySet()) {
+
+ XWorkBeanValidator<B> validator = validators.get(scope);
+
+ Map<String, List<String>> newMessages = validator.validate(bean);
+
+ if (scope == BeanValidatorScope.ERROR) {
+ // treate conversion errors
+ // reinject them
+ for (Entry<String, String> entry : conversionErrors.entrySet()) {
+ // remove from validation, errors occurs on this field
+ List<String> errors = newMessages.get(entry.getKey());
+ String conversionError = entry.getValue();
+ if (errors != null) {
+ errors.clear();
+ errors.add(conversionError);
+ } else {
+ errors = Collections.singletonList(conversionError);
+ if (XWorkBeanValidator.EMPTY_RESULT.equals(newMessages)) {
+ newMessages = new HashMap<String, List<String>>();
+ }
+ // add the concrete conversion error
+ newMessages.put(entry.getKey(), errors);
+ }
+ }
+ }
+
+ // for each field, update his list of messages
+ for (BeanValidatorField<B> field : fields) {
+ List<String> messagesForField = newMessages.get(field.getName());
+ if (field.getScopes().contains(scope)) {
+ field.updateMessages(this, scope, messagesForField);
+ }
+ }
+ }
+
+ if (parentValidator != null) {
+ // chained validation
+ // the parent validator should not be changed from this validation
+ boolean wasModified = parentValidator.isChanged();
+ parentValidator.doValidate();
+ if (!wasModified) {
+ // push back old state
+ parentValidator.setChanged(false);
+ }
+ }
+
+ }
+
+ @Override
+ public String toString() {
+ return super.toString() + "<beanClass:" + beanClass +
+ ", contextName:" + contextName + ">";
+ }
+
+ public void addBeanValidatorListener(BeanValidatorListener listener) {
+ listenerList.add(BeanValidatorListener.class, listener);
+ }
+
+ public void removeBeanValidatorListener(BeanValidatorListener listener) {
+ listenerList.remove(BeanValidatorListener.class, listener);
+ }
+
+ public BeanValidatorListener[] getBeanValidatorListeners() {
+ return listenerList.getListeners(BeanValidatorListener.class);
+ }
+
+ public void addPropertyChangeListener(PropertyChangeListener listener) {
+ pcs.addPropertyChangeListener(listener);
+ }
+
+ public void addPropertyChangeListener(String propertyName,
+ PropertyChangeListener listener) {
+ pcs.addPropertyChangeListener(propertyName, listener);
+ }
+
+ public void removePropertyChangeListener(PropertyChangeListener listener) {
+ pcs.removePropertyChangeListener(listener);
+ }
+
+ public void removePropertyChangeListener(String propertyName,
+ PropertyChangeListener listener) {
+ pcs.removePropertyChangeListener(propertyName, listener);
+ }
+
+ /**
+ * @return <code>true</code> if validation is enabled, <code>false</code>
+ * otherwise.
+ */
+ protected boolean canValidate() {
+ return !(bean == null || fields.isEmpty());
+ }
+
+ protected void fireFieldChanged(BeanValidatorField<B> field,
+ BeanValidatorScope scope,
+ String[] toAdd,
+ String[] toDelete) {
+
+ BeanValidatorEvent evt = new BeanValidatorEvent(
+ this,
+ field,
+ scope,
+ toAdd,
+ toDelete
+ );
+
+ for (BeanValidatorListener listener :
+ listenerList.getListeners(BeanValidatorListener.class)) {
+ listener.onFieldChanged(evt);
+ }
+ }
+
+ protected void initFields() {
+
+ Set<String> detectedFieldNames = new HashSet<String>();
+ EnumMap<BeanValidatorScope, Set<String>> tmp;
+ tmp = new EnumMap<BeanValidatorScope, Set<String>>(
+ BeanValidatorScope.class
+ );
+ Set<BeanValidatorField<B>> detectedFields =
+ new HashSet<BeanValidatorField<B>>();
+
+ validators.clear();
+
+ BeanValidatorScope[] scopeUniverse;
+ if (filterScopes == null) {
+ // use all scopes
+ scopeUniverse = BeanValidatorScope.values();
+ } else {
+ // use customized scopes
+ scopeUniverse = filterScopes;
+ }
+
+ for (BeanValidatorScope scope : scopeUniverse) {
+ String scopeContext =
+ (contextName == null ? "" : contextName + "-") +
+ scope.name().toLowerCase();
+
+ XWorkBeanValidator<B> newValidator =
+ new XWorkBeanValidator<B>(beanClass, scopeContext, false);
+ Set<String> fieldNames = newValidator.getFieldNames();
+ if (log.isDebugEnabled()) {
+ log.debug("detected validators for scope " + scopeContext +
+ " : " + fieldNames);
+ }
+ if (!fieldNames.isEmpty()) {
+ // fields detected in this validator, keep it
+ validators.put(scope, newValidator);
+ detectedFieldNames.addAll(fieldNames);
+ tmp.put(scope, fieldNames);
+ }
+ }
+
+ List<BeanValidatorScope> scopes = new ArrayList<BeanValidatorScope>();
+ for (String fieldName : detectedFieldNames) {
+ scopes.clear();
+ // detect scopes for the field
+ for (BeanValidatorScope scope : scopeUniverse) {
+ if (tmp.containsKey(scope) &&
+ tmp.get(scope).contains(fieldName)) {
+ scopes.add(scope);
+ }
+ }
+ BeanValidatorField<B> f =
+ new BeanValidatorField<B>(beanClass, fieldName, scopes);
+ detectedFields.add(f);
+ }
+ tmp.clear();
+ detectedFieldNames.clear();
+
+ fields = Collections.unmodifiableSet(detectedFields);
+ }
+
+ protected EventSetDescriptor getBeanEventDescriptor(B bean) {
+ if (beanEventDescriptor == null) {
+ // check that the bean is listenable, otherwise, can't use the
+ // validator on it
+ beanEventDescriptor =
+ BeanValidatorUtil.getPropertyChangeListenerDescriptor(
+ bean.getClass()
+ );
+ }
+ return beanEventDescriptor;
+ }
+}
Property changes on: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidator.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorDetector.java (from rev 2013, trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorDetector.java)
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorDetector.java (rev 0)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorDetector.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,342 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin, Tony Chemit
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.legacy;
+
+import org.apache.commons.beanutils.ConstructorUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.lang.reflect.Constructor;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.TreeSet;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Un detecteur de validateurs pour un liste de classes données et un répertoire
+ * où chercher les fichiers de validation.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.6.0
+ */
+public class BeanValidatorDetector {
+
+ /** Logger */
+ private static final Log log =
+ LogFactory.getLog(BeanValidatorDetector.class);
+
+ public SortedSet<BeanValidator<?>> detect(File sourceRoot,
+ Class<?>... types) {
+ SortedSet<BeanValidator<?>> result =
+ detect(BeanValidator.class, sourceRoot, null, types);
+ return result;
+ }
+
+ public SortedSet<BeanValidator<?>> detect(Class<?> validatorClass,
+ File sourceRoot,
+ Pattern contextFilter,
+ Class<?>... types) {
+ SortedSet<BeanValidator<?>> result = detect(validatorClass,
+ sourceRoot,
+ contextFilter,
+ null,
+ types);
+ return result;
+ }
+
+ public SortedSet<BeanValidator<?>> detect(Class<?> validatorClass,
+ File sourceRoot,
+ Pattern contextFilter,
+ BeanValidatorScope[] scopes,
+ Class<?>... types) {
+
+ SortedSet<BeanValidator<?>> result =
+ new TreeSet<BeanValidator<?>>(new BeanValidatorComparator());
+
+ for (Class<?> c : types) {
+ File dir = getClassDir(sourceRoot, c);
+ if (!dir.exists()) {
+
+ // pas de repertoire adequate
+ if (log.isDebugEnabled()) {
+ log.debug("skip non existing directory " + dir);
+ }
+ continue;
+ }
+ String[] contexts = getContexts(c, dir);
+ if (log.isDebugEnabled()) {
+ log.debug("contexts : " + Arrays.toString(contexts));
+ }
+
+ if (contexts.length > 0) {
+ String[] realContexts = getContextsWithoutScopes(contexts);
+
+ if (log.isDebugEnabled()) {
+ log.debug("realContexts : " +
+ Arrays.toString(realContexts));
+ }
+
+ if (contextFilter != null) {
+
+ // filter contexts
+ realContexts = getFilterContexts(contextFilter,
+ realContexts
+ );
+ if (log.isDebugEnabled()) {
+ log.debug("filterContexts : " +
+ Arrays.toString(realContexts));
+ }
+ }
+
+ for (String context : realContexts) {
+
+ // on cherche le validateur
+ BeanValidator<?> validator = getValidator(
+ validatorClass,
+ c,
+ context.isEmpty() ? null : context,
+ scopes
+ );
+ if (validator != null) {
+ // on enregistre le validateur
+ result.add(validator);
+ }
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Pour un context et un type d'entité donné, instancie un validateur et
+ * test si ce validateur est utilisable (i.e qu'il admet des champs à
+ * valider).
+ * <p/>
+ * Si aucun champ n'est trouvé dans le validateur, alors on retourne null.
+ *
+ * @param <B> le type du bean
+ * @param validatorClass le type de validateur a instancie
+ * @param klass le type du bean
+ * @param context le context du validateur
+ * @param scopes les scopes a utiliser (si {@code null} alors pas de
+ * filtre sur les scopes)
+ * @return le validateur initialisé, ou <code>null</code> si aucun scope
+ * détecté dans le validateur.
+ */
+ protected <B> BeanValidator<B> getValidator(Class<?> validatorClass,
+ Class<B> klass,
+ String context,
+ BeanValidatorScope... scopes) {
+
+ BeanValidator<B> valitator;
+ valitator = createValidator(validatorClass, klass, context, scopes);
+
+ Set<BeanValidatorScope> resultScopes = valitator.getScopes();
+ if (resultScopes.isEmpty()) {
+ valitator = null;
+ if (log.isDebugEnabled()) {
+ log.debug(klass + " : validator skip (no scopes detected)");
+ }
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug(klass + " : keep validator " + valitator);
+ }
+ }
+ return valitator;
+ }
+
+ protected <B> BeanValidator<B> createValidator(
+ Class<?> validatorClass,
+ Class<B> klass,
+ String context,
+ BeanValidatorScope[] scopes) {
+ BeanValidator<B> valitator;
+ Constructor<?> con;
+ try {
+ con = ConstructorUtils.getAccessibleConstructor(
+ validatorClass,
+ new Class<?>[]{
+ Class.class,
+ String.class,
+ BeanValidatorScope[].class
+ }
+ );
+ if (con != null) {
+
+ valitator = (BeanValidator<B>) con.newInstance(
+ klass,
+ context, scopes
+ );
+
+ } else {
+ con = ConstructorUtils.getAccessibleConstructor(
+ validatorClass,
+ new Class<?>[]{
+ Class.class,
+ String.class,
+ BeanValidatorScope[].class
+ }
+ );
+
+ if (con == null) {
+ throw new IllegalStateException(
+ "could not find a constructor with " +
+ "(Class.class, String) or " +
+ "(Class,String BeanValidatorScope[])");
+ }
+
+ valitator = (BeanValidator<B>) con.newInstance(
+ klass,
+ context
+ );
+ if (scopes != null && scopes.length > 0) {
+ valitator.setFilterScopes(scopes);
+ }
+ }
+
+ } catch (Exception ex) {
+ throw new RuntimeException(
+ "could not instanciate validator " + validatorClass +
+ " for reason " + ex.getMessage(), ex);
+ }
+ return valitator;
+ }
+
+ protected File getClassDir(File sourceRoot, Class<?> clazz) {
+ String path = clazz.getPackage().getName();
+ path = path.replaceAll("\\.", File.separator);
+ File dir = new File(sourceRoot, path);
+ return dir;
+ }
+
+ protected String[] getContexts(Class<?> clazz, File dir) {
+ Set<String> result = new TreeSet<String>();
+ ValidatorFilenameFilter filter = new ValidatorFilenameFilter(clazz);
+ if (log.isDebugEnabled()) {
+ log.debug("dir : " + dir);
+ }
+ String[] files = dir.list(filter);
+ for (String file : files) {
+ if (log.isDebugEnabled()) {
+ log.debug("file " + file);
+ }
+ String context = file.substring(
+ filter.prefix.length(),
+ file.length() - ValidatorFilenameFilter.SUFFIX.length()
+ );
+ if (log.isDebugEnabled()) {
+ log.debug("detect " + clazz.getSimpleName() +
+ " context [" + context + "]");
+ }
+ result.add(context);
+ }
+ return result.toArray(new String[result.size()]);
+ }
+
+ protected String[] getContextsWithoutScopes(String[] contexts) {
+ Set<String> result = new TreeSet<String>();
+ BeanValidatorScope[] scopes = BeanValidatorScope.values();
+ for (String context : contexts) {
+ for (BeanValidatorScope scope : scopes) {
+ String scopeName = scope.name().toLowerCase();
+ if (!context.endsWith(scopeName)) {
+ // pas concerne par ce scope
+ continue;
+ }
+ if (log.isDebugEnabled()) {
+ log.debug("detect context : " + context);
+ }
+ String realContext = context.substring(
+ 0,
+ context.length() - scopeName.length()
+ );
+ if (realContext.endsWith("-")) {
+ realContext = realContext.substring(
+ 0,
+ realContext.length() - 1
+ );
+ }
+ result.add(realContext);
+ }
+ }
+ return result.toArray(new String[result.size()]);
+ }
+
+ protected String[] getFilterContexts(Pattern contextFilter,
+ String[] realContexts) {
+ List<String> result = new ArrayList<String>();
+ for (String c : realContexts) {
+ Matcher m = contextFilter.matcher(c);
+ if (m.matches()) {
+ result.add(c);
+ }
+ }
+ return result.toArray(new String[result.size()]);
+ }
+
+ protected static class ValidatorFilenameFilter implements FilenameFilter {
+
+ protected static final String SUFFIX = "-validation.xml";
+
+ protected Class<?> clazz;
+
+ protected String prefix;
+
+ public ValidatorFilenameFilter(Class<?> clazz) {
+ this.clazz = clazz;
+ prefix = clazz.getSimpleName() + "-";
+ }
+
+ @Override
+ public boolean accept(File dir, String name) {
+ boolean result = name.endsWith(SUFFIX);
+ if (result) {
+ result = name.startsWith(prefix);
+ }
+ return result;
+ }
+ }
+
+ protected static class BeanValidatorComparator implements Comparator<BeanValidator<?>> {
+
+ @Override
+ public int compare(BeanValidator<?> o1, BeanValidator<?> o2) {
+ String contextName1 =
+ o1.getBeanClass().getSimpleName() + "-" +
+ (o1.getContextName() == null ? "" : o1.getContextName());
+ String contextName2 =
+ o2.getBeanClass().getSimpleName() + "-" +
+ (o2.getContextName() == null ? "" : o2.getContextName());
+ return contextName1.compareTo(contextName2);
+ }
+ }
+}
Property changes on: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorDetector.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorEvent.java (from rev 2013, trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorEvent.java)
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorEvent.java (rev 0)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorEvent.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,86 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin, Tony Chemit
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.legacy;
+
+import java.util.EventObject;
+
+/**
+ * The definition of an event on {@link BeanValidatorListener}
+ * to be fired by a {@link BeanValidator}.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.3
+ */
+public class BeanValidatorEvent extends EventObject {
+
+ private static final long serialVersionUID = 1L;
+
+ /** the field impacted by the validator */
+ protected BeanValidatorField<?> field;
+
+ /** the scope impacted by the event */
+ protected BeanValidatorScope scope;
+
+ protected String[] messagestoAdd;
+
+ protected String[] messagestoDelete;
+
+ public BeanValidatorEvent(BeanValidator<?> source,
+ BeanValidatorField<?> field,
+ BeanValidatorScope scope,
+ String[] messagestoAdd,
+ String[] messagestoDelete) {
+ super(source);
+ this.field = field;
+ this.scope = scope;
+ this.messagestoAdd = messagestoAdd;
+ this.messagestoDelete = messagestoDelete;
+ }
+
+ @Override
+ public BeanValidator<?> getSource() {
+ return (BeanValidator<?>) super.getSource();
+ }
+
+ public String getFieldName() {
+ return field.getName();
+ }
+
+ public String[] getMessagesToAdd() {
+ return messagestoAdd;
+ }
+
+ public String[] getMessagesToDelete() {
+ return messagestoDelete;
+ }
+
+ public BeanValidatorScope getScope() {
+ return scope;
+ }
+
+ public BeanValidatorField<?> getField() {
+ return field;
+ }
+}
Property changes on: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorEvent.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorField.java (from rev 2013, trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorField.java)
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorField.java (rev 0)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorField.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,286 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin, Tony Chemit
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.legacy;
+
+import com.opensymphony.xwork2.validator.FieldValidator;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.StringTokenizer;
+
+import static org.nuiton.i18n.I18n._;
+
+/**
+ * Definition of a field to be handled in a {@link BeanValidator}.
+ * <p/>
+ * A such class is only registred in {@link BeanValidator } when the field of
+ * the bean was found in validator xml configuration file for a {@link
+ * FieldValidator} only.
+ * <p/>
+ * This class use properties {@link #beanClass}, {@link #name} to define his
+ * naturel order.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @param <B> the type of the bean handled by the validator and this field of
+ * validation.
+ * @since 1.3
+ */
+public class BeanValidatorField<B> implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ /** the class of bean */
+ protected final Class<B> beanClass;
+
+ /** name of field in bean */
+ protected final String name;
+
+ protected EnumMap<BeanValidatorScope, Set<String>> messages;
+
+ public BeanValidatorField(Class<B> beanClass,
+ String name,
+ List<BeanValidatorScope> scopes) {
+ this.beanClass = beanClass;
+ this.name = name;
+ messages = new EnumMap<BeanValidatorScope, Set<String>>(
+ BeanValidatorScope.class
+ );
+ for (BeanValidatorScope scope : scopes) {
+ messages.put(scope, new HashSet<String>());
+ }
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Class<B> getBeanClass() {
+ return beanClass;
+ }
+
+ /**
+ * @return {@code true} if this field is valid : no fatal errors and no
+ * errors), {@code false} otherwise.
+ */
+ public boolean isValid() {
+ return !hasFatalErrors() && !hasErrors();
+ }
+
+ public BeanValidatorScope getScope() {
+ if (hasErrors()) {
+ return BeanValidatorScope.ERROR;
+ }
+ if (hasWarnings()) {
+ return BeanValidatorScope.WARNING;
+ }
+ if (hasInfos()) {
+ return BeanValidatorScope.INFO;
+ }
+ return null;
+ }
+
+ public Set<BeanValidatorScope> getScopes() {
+ return messages.keySet();
+ }
+
+ public boolean hasFatalErrors() {
+ return hasMessages(BeanValidatorScope.FATAL);
+ }
+
+ public boolean hasErrors() {
+ return hasMessages(BeanValidatorScope.ERROR);
+ }
+
+ public boolean hasWarnings() {
+ return hasMessages(BeanValidatorScope.WARNING);
+ }
+
+ public boolean hasInfos() {
+ return hasMessages(BeanValidatorScope.INFO);
+ }
+
+ public Set<String> getFatalErrors() {
+ return getMessages(BeanValidatorScope.FATAL);
+ }
+
+ public Set<String> getErrors() {
+ return getMessages(BeanValidatorScope.ERROR);
+ }
+
+ public Set<String> getWarnings() {
+ return getMessages(BeanValidatorScope.WARNING);
+ }
+
+ public Set<String> getInfos() {
+ return getMessages(BeanValidatorScope.INFO);
+ }
+
+ public boolean hasMessages(BeanValidatorScope scope) {
+ return messages.containsKey(scope) && !getMessages(scope).isEmpty();
+ }
+
+ public Set<String> getMessages(BeanValidatorScope scope) {
+ return messages.get(scope);
+ }
+
+ public void updateMessages(BeanValidator<B> validator,
+ BeanValidatorScope scope,
+ List<String> messages) {
+
+ if (scope == null) {
+
+ // special case to reset all messages from all scopes
+
+ for (BeanValidatorScope s : getScopes()) {
+
+ clearMessages(s, validator);
+ }
+ return;
+ }
+
+ if (!this.messages.containsKey(scope)) {
+ throw new IllegalArgumentException(
+ "the scope " + scope + " was not registred for " + this);
+ }
+
+ if (messages == null || messages.isEmpty()) {
+
+ // no incoming message for this scope
+
+ clearMessages(scope, validator);
+ return;
+ }
+
+ // build the diff of messages (the one to delete, the one to add)
+
+ boolean hasChanged = false;
+
+ Set<String> currentMessages = getMessages(scope);
+
+ // detect messages to delete
+ Set<String> toDelete = new HashSet<String>(currentMessages);
+ toDelete.removeAll(messages);
+
+ if (!toDelete.isEmpty()) {
+ // apply delete
+ currentMessages.removeAll(toDelete);
+ hasChanged = true;
+ }
+
+ // detect messages to add
+ Set<String> toAdd = new HashSet<String>(messages);
+ toAdd.removeAll(currentMessages);
+
+ if (!toAdd.isEmpty()) {
+ // apply add
+ currentMessages.addAll(toAdd);
+ hasChanged = true;
+ }
+
+ if (hasChanged) {
+
+ // something has changed, fire notifications
+ String[] del = toDelete.toArray(new String[toDelete.size()]);
+ String[] add = toAdd.toArray(new String[toAdd.size()]);
+
+ validator.fireFieldChanged(this, scope, add, del);
+ }
+ toAdd.clear();
+ toDelete.clear();
+
+ }
+
+ public String getI18nError(String error) {
+ String text;
+ if (!error.contains("##")) {
+ text = _(error);
+ } else {
+ StringTokenizer stk = new StringTokenizer(error, "##");
+ String errorName = stk.nextToken();
+ List<String> args = new ArrayList<String>();
+ while (stk.hasMoreTokens()) {
+ args.add(stk.nextToken());
+ }
+ text = _(errorName, args.toArray());
+ }
+ return text;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (!(o instanceof BeanValidatorField<?>)) {
+ return false;
+ }
+
+ BeanValidatorField<?> that = (BeanValidatorField<?>) o;
+ return beanClass.equals(that.beanClass) && name.equals(that.name);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = beanClass.hashCode();
+ result = 31 * result + name.hashCode();
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("<").append(super.toString());
+ sb.append(" beanClass:").append(beanClass);
+ sb.append(", name:").append(name);
+ sb.append(", scopes:");
+ sb.append(messages == null ? "[]" : messages.keySet());
+ sb.append(", scope:").append(getScope());
+ //sb.append(", errors:").append(errors);
+ sb.append('>');
+ return sb.toString();
+ }
+
+ protected void clearMessages(BeanValidatorScope scope,
+ BeanValidator<B> validator) {
+ // remove all messages
+ Set<String> toDelete = getMessages(scope);
+
+ if (!toDelete.isEmpty()) {
+
+ // there is some messages to delete
+ String[] toDel = toDelete.toArray(new String[toDelete.size()]);
+
+ // apply deletion
+ toDelete.clear();
+
+ // fire
+ validator.fireFieldChanged(this, scope, null, toDel);
+ }
+ }
+}
Property changes on: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorField.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorListener.java (from rev 2013, trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorListener.java)
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorListener.java (rev 0)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorListener.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,43 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin, Tony Chemit
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.legacy;
+
+import java.util.EventListener;
+
+/**
+ * The listener contract to be used on {@link BeanValidator}
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.3
+ */
+public interface BeanValidatorListener extends EventListener {
+
+ /**
+ * Invoked when a validator detects some changes on a field.
+ *
+ * @param event the event
+ */
+ void onFieldChanged(BeanValidatorEvent event);
+}
Property changes on: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorListener.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorMessage.java (from rev 2013, trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorMessage.java)
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorMessage.java (rev 0)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorMessage.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,118 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin, Tony Chemit
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.legacy;
+
+/**
+ * The object to box a validation message.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @param <E> type of message (use for override {@link #compareTo(Object)}
+ * method.
+ * @since 1.3
+ */
+public class BeanValidatorMessage<E extends BeanValidatorMessage<?>> implements Comparable<E> {
+
+ /** the validator that produce the message */
+ protected BeanValidator<?> validator;
+
+ /** the field that produce the message */
+ protected BeanValidatorField<?> field;
+
+ /** the label of the message (to be displayed somewhere) */
+ protected String message;
+
+ /** the scope of the message */
+ protected BeanValidatorScope scope;
+
+ public BeanValidatorMessage(BeanValidator<?> validator,
+ BeanValidatorField<?> field,
+ String message,
+ BeanValidatorScope scope) {
+ this.field = field;
+ this.validator = validator;
+ this.message = message == null ? null : message.trim();
+ this.scope = scope;
+ }
+
+ public BeanValidator<?> getValidator() {
+ return validator;
+ }
+
+ public BeanValidatorField<?> getField() {
+ return field;
+ }
+
+ public BeanValidatorScope getScope() {
+ return scope;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ @Override
+ public int compareTo(E o) {
+ // sort on scope
+ int result = getScope().compareTo(o.getScope());
+ if (result == 0) {
+ // sort on field name
+ result = field.getName().compareTo(o.field.getName());
+ if (result == 0) {
+ // sort on message
+ result = message.compareTo(o.message);
+ }
+ }
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ BeanValidatorMessage<?> that = (BeanValidatorMessage<?>) o;
+
+ return field.equals(that.field) &&
+ message.equals(that.message) &&
+ scope == that.scope;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = field.hashCode();
+ result = 31 * result + message.hashCode();
+ result = 31 * result + scope.hashCode();
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return scope + " - " + field.getI18nError(message);
+ }
+}
Property changes on: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorMessage.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorScope.java (from rev 2013, trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorScope.java)
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorScope.java (rev 0)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorScope.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,79 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin, Tony Chemit
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.legacy;
+
+import static org.nuiton.i18n.I18n.n_;
+
+/**
+ * The differents levels of messages in validation process.
+ * <p/>
+ * The order of the enum defines the severity of validation.
+ * <p/>
+ * Always begin with fatal, then error, then if no error found, try warning, then info...
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ */
+public enum BeanValidatorScope {
+
+ /**
+ * the fatal error scope level.
+ * <p/>
+ * When a message of a such scope is found on a validator, then the
+ * validator is invalid and modified.
+ * @since 2.2.4
+ */
+ FATAL(n_("validator.scope.fatal.label")),
+ /**
+ * the error scope level.
+ * <p/>
+ * When a message of a such scope is found on a validator, then the
+ * validator is invalid and modified.
+ */
+ ERROR(n_("validator.scope.error.label")),
+ /**
+ * the warning scope level.
+ * <p/>
+ * When a message of a such scope is found on a validator, then the
+ * validator is still valid but modified.
+ */
+ WARNING(n_("validator.scope.warning.label")),
+ /**
+ * the information scope level.
+ * <p/>
+ * When a message of a sucg scope is found on a validator, then the
+ * validator is still valid and not modified.
+ */
+ INFO(n_("validator.scope.info.label"));
+
+ private final String label;
+
+ BeanValidatorScope(String label) {
+ this.label = label;
+ }
+
+ public String getLabel() {
+ return label;
+ }
+}
Property changes on: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorScope.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorUtil.java (from rev 2013, trunk/nuiton-validator/src/main/java/org/nuiton/validator/BeanValidatorUtil.java)
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorUtil.java (rev 0)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorUtil.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,196 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin, Tony Chemit
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.legacy;
+
+import com.opensymphony.xwork2.config.Configuration;
+import com.opensymphony.xwork2.config.ConfigurationManager;
+import com.opensymphony.xwork2.inject.Container;
+import com.opensymphony.xwork2.util.ValueStack;
+import com.opensymphony.xwork2.util.ValueStackFactory;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.beans.BeanInfo;
+import java.beans.EventSetDescriptor;
+import java.beans.IntrospectionException;
+import java.beans.Introspector;
+import java.beans.PropertyDescriptor;
+import java.util.EnumMap;
+import java.util.EnumSet;
+import java.util.List;
+
+/**
+ * The helper class for validation module.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ */
+public class BeanValidatorUtil {
+
+ /** Logger */
+ static private final Log log = LogFactory.getLog(BeanValidatorUtil.class);
+
+ /**
+ * a shared value stack to allow external operations on it (for example add
+ * some datas in stack to be usedby validators
+ */
+ static private ValueStack sharedValueStack;
+
+ public static ValueStack getSharedValueStack() {
+ if (sharedValueStack == null) {
+
+ // init context
+ ConfigurationManager confManager = new ConfigurationManager();
+ Configuration conf = confManager.getConfiguration();
+
+ Container container = conf.getContainer();
+ ValueStackFactory stackFactory = container.getInstance(
+ ValueStackFactory.class);
+ sharedValueStack = stackFactory.createValueStack();
+ if (log.isDebugEnabled()) {
+ log.debug("init shared value stack " + sharedValueStack);
+ }
+ }
+ return sharedValueStack;
+ }
+
+ protected BeanValidatorUtil() {
+ // no instance
+ }
+
+ /**
+ * Convert a value to a given type and then if was succesffull try to set it
+ * in the bean manage by the validator.
+ *
+ * @param validator validator to be involved
+ * @param fieldName the name of the bean property
+ * @param value the actual value to convert
+ * @param valueClass the type of the conversion
+ */
+ public static void convert(BeanValidator<?> validator,
+ String fieldName,
+ String value,
+ Class<?> valueClass) {
+
+ Object result = validator.convert(fieldName, value, valueClass);
+ if (result != null) {
+ try {
+ BeanInfo info =
+ Introspector.getBeanInfo(validator.getBean().getClass());
+
+ for (PropertyDescriptor descriptor :
+ info.getPropertyDescriptors()) {
+ if (fieldName.equals(descriptor.getName()) &&
+ descriptor.getWriteMethod() != null) {
+
+ descriptor.getWriteMethod().invoke(
+ validator.getBean(),
+ result
+ );
+ break;
+ }
+ }
+ } catch (Exception e) {
+ if (log.isErrorEnabled()) {
+ log.error("could not obtain beanInfo for " +
+ valueClass.getClass() + ", reason : " +
+ e.getMessage(), e);
+ }
+ }
+ } else {
+ //fixme : conversion failed, we should be able to notify ui
+ // that values has changed ?
+ // otherwise, bean value has not changed,...
+ }
+ }
+
+ public static EventSetDescriptor getPropertyChangeListenerDescriptor(Class<?> beanClass) {
+ try {
+ // check that the bean is listenable, otherwise, can't use
+ // the validator on it
+ BeanInfo infos = Introspector.getBeanInfo(beanClass);
+ EventSetDescriptor[] events = infos.getEventSetDescriptors();
+ for (EventSetDescriptor event : events) {
+ if ("propertyChange".equals(event.getName())) {
+
+ if (event.getAddListenerMethod() == null) {
+ // no property event listener, so can not use the validator
+ throw new IllegalStateException(
+ "no addPropertyChangeListener method found " +
+ "for " + beanClass);
+ }
+ if (event.getRemoveListenerMethod() == null) {
+ // no property event listener, so can not use the validator
+ throw new IllegalStateException(
+ "no removePropertyChangeListener method found" +
+ " for " + beanClass);
+ }
+ return event;
+ }
+ }
+
+ // no property event listener, so can not use the validator
+ throw new IllegalStateException(
+ "no PropertyChangeListener access method found for " +
+ beanClass);
+ } catch (IntrospectionException ex) {
+ throw new IllegalStateException(
+ "could not acquire PropertyChangeListener bean info for " +
+ beanClass + " for reason " + ex.getMessage(), ex);
+ }
+ }
+
+ public static EnumSet<BeanValidatorScope> getScopes(
+ List<BeanValidatorMessage<?>> messages) {
+ EnumSet<BeanValidatorScope> result =
+ EnumSet.noneOf(BeanValidatorScope.class);
+ for (BeanValidatorMessage<?> m : messages) {
+ result.add(m.getScope());
+ }
+ return result;
+ }
+
+ public static EnumMap<BeanValidatorScope, Integer> getScopesCount(
+ List<BeanValidatorMessage<?>> messages) {
+ EnumMap<BeanValidatorScope, Integer> result =
+ new EnumMap<BeanValidatorScope, Integer>(BeanValidatorScope.class);
+ for (BeanValidatorScope s : BeanValidatorScope.values()) {
+ result.put(s, 0);
+ }
+ for (BeanValidatorMessage<?> m : messages) {
+
+ BeanValidatorScope scope = m.getScope();
+
+ result.put(scope, result.get(scope) + 1);
+ }
+
+ for (BeanValidatorScope s : BeanValidatorScope.values()) {
+ if (result.get(s) == 0) {
+ result.remove(s);
+ }
+ }
+ return result;
+ }
+
+}
Property changes on: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/BeanValidatorUtil.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/ValidatorsMap.java (from rev 2013, trunk/nuiton-validator/src/main/java/org/nuiton/validator/ValidatorsMap.java)
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/ValidatorsMap.java (rev 0)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/ValidatorsMap.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,126 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin, Tony Chemit
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.legacy;
+
+import java.util.Collection;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Un dictionnaire de validateurs ordonnees par le type de leur bean.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.0.1
+ */
+public class ValidatorsMap implements Map<Class<?>, BeanValidator<?>> {
+
+ protected final Map<Class<?>, BeanValidator<?>> delegate;
+
+ public ValidatorsMap() {
+ delegate = new HashMap<Class<?>, BeanValidator<?>>();
+ }
+
+ public BeanValidatorScope[] getScopes() {
+ EnumSet<BeanValidatorScope> result =
+ EnumSet.noneOf(BeanValidatorScope.class);
+ for (BeanValidator<?> b : values()) {
+ result.addAll(b.getScopes());
+ }
+ return result.toArray(new BeanValidatorScope[result.size()]);
+ }
+
+// public <X> BeanValidator<X> getValidator(X klass) {
+// BeanValidator<X> beanValidator = (BeanValidator<X>) get(klass.getClass());
+// return beanValidator;
+// }
+
+ public <X> BeanValidator<X> getValidator(Class<X> klass) {
+ BeanValidator<X> beanValidator = (BeanValidator<X>) get(klass);
+ return beanValidator;
+ }
+
+ @Override
+ public int size() {
+ return delegate.size();
+ }
+
+ @Override
+ public boolean isEmpty() {
+ return delegate.isEmpty();
+ }
+
+ @Override
+ public boolean containsKey(Object key) {
+ return delegate.containsKey(key);
+ }
+
+ @Override
+ public boolean containsValue(Object value) {
+ return delegate.containsValue(value);
+ }
+
+ @Override
+ public BeanValidator<?> get(Object key) {
+ return delegate.get(key);
+ }
+
+ @Override
+ public BeanValidator<?> put(Class<?> key, BeanValidator<?> value) {
+ return delegate.put(key, value);
+ }
+
+ @Override
+ public BeanValidator<?> remove(Object key) {
+ return delegate.remove(key);
+ }
+
+ @Override
+ public void putAll(Map<? extends Class<?>, ? extends BeanValidator<?>> m) {
+ delegate.putAll(m);
+ }
+
+ @Override
+ public void clear() {
+ delegate.clear();
+ }
+
+ @Override
+ public Set<Class<?>> keySet() {
+ return delegate.keySet();
+ }
+
+ @Override
+ public Collection<BeanValidator<?>> values() {
+ return delegate.values();
+ }
+
+ @Override
+ public Set<Entry<Class<?>, BeanValidator<?>>> entrySet() {
+ return delegate.entrySet();
+ }
+
+}
Property changes on: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/ValidatorsMap.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/XWorkBeanValidator.java (from rev 2013, trunk/nuiton-validator/src/main/java/org/nuiton/validator/XWorkBeanValidator.java)
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/XWorkBeanValidator.java (rev 0)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/XWorkBeanValidator.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,324 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin, Tony Chemit
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.legacy;
+
+import com.opensymphony.xwork2.ActionContext;
+import com.opensymphony.xwork2.ValidationAwareSupport;
+import com.opensymphony.xwork2.config.Configuration;
+import com.opensymphony.xwork2.config.ConfigurationManager;
+import com.opensymphony.xwork2.inject.Container;
+import com.opensymphony.xwork2.util.ValueStack;
+import com.opensymphony.xwork2.util.ValueStackFactory;
+import com.opensymphony.xwork2.validator.ActionValidatorManager;
+import com.opensymphony.xwork2.validator.DelegatingValidatorContext;
+import com.opensymphony.xwork2.validator.FieldValidator;
+import com.opensymphony.xwork2.validator.ValidationException;
+import com.opensymphony.xwork2.validator.Validator;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A customized validator for a given bean.
+ * <p/>
+ * Use the method {@link #validate(Object)} to obtain the messages detected by
+ * the validator for the given bean.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @param <B> type of the bean to validate.
+ * @since 1.3
+ */
+public class XWorkBeanValidator<B> {
+
+ /** Logger */
+ private static final Log log = LogFactory.getLog(XWorkBeanValidator.class);
+
+ protected final static Map<String, List<String>> EMPTY_RESULT =
+ Collections.unmodifiableMap(new HashMap<String, List<String>>());
+
+ /** the type of bean to validate */
+ protected final Class<B> beanClass;
+
+ /** the validation named context (can be null) */
+ protected String contextName;
+
+ /** the list of field names detected for this validator */
+ protected Set<String> fieldNames;
+
+ /** a flag to include or not the default context validators */
+ protected boolean includeDefaultContext;
+
+ // --
+ // XWorks fields
+ // --
+
+ protected ValidationAwareSupport validationSupport;
+
+ protected DelegatingValidatorContext validationContext;
+
+ protected ActionValidatorManager validator;
+
+ protected ActionContext context;
+
+ public XWorkBeanValidator(Class<B> beanClass, String contextName) {
+ this(beanClass,
+ contextName,
+ true,
+ BeanValidatorUtil.getSharedValueStack()
+ );
+ }
+
+ public XWorkBeanValidator(Class<B> beanClass,
+ String contextName,
+ ValueStack vs) {
+ this(beanClass, contextName, true, vs);
+ }
+
+ public XWorkBeanValidator(Class<B> beanClass,
+ String contextName,
+ boolean includeDefaultContext) {
+ this(beanClass,
+ contextName,
+ includeDefaultContext,
+ BeanValidatorUtil.getSharedValueStack()
+ );
+ }
+
+ public XWorkBeanValidator(Class<B> beanClass,
+ String contextName,
+ boolean includeDefaultContext,
+ ValueStack vs) {
+
+ this.beanClass = beanClass;
+ this.includeDefaultContext = includeDefaultContext;
+ validationSupport = new ValidationAwareSupport();
+ validationContext = new DelegatingValidatorContext(validationSupport);
+
+ if (vs == null) {
+ // create a standalone value stack
+ ConfigurationManager confManager = new ConfigurationManager();
+ Configuration conf = confManager.getConfiguration();
+ Container container = conf.getContainer();
+ ValueStackFactory stackFactory =
+ container.getInstance(ValueStackFactory.class);
+ vs = stackFactory.createValueStack();
+ if (log.isDebugEnabled()) {
+ log.debug("create a standalone value stack " + vs);
+ }
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug("use given value stack " + vs);
+ }
+ }
+
+ context = new ActionContext(vs.getContext());
+ ActionContext.setContext(context);
+
+ // init validator
+ Container container = context.getContainer();
+ validator = container.getInstance(ActionValidatorManager.class,
+ "no-annotations"
+ );
+
+ // init context
+ setContextName(contextName);
+ }
+
+ public boolean isIncludeDefaultContext() {
+ return includeDefaultContext;
+ }
+
+ public Class<B> getBeanClass() {
+ return beanClass;
+ }
+
+ public String getContextName() {
+ return contextName;
+ }
+
+ public Set<String> getFieldNames() {
+ return fieldNames;
+ }
+
+ public ActionValidatorManager getValidator() {
+ return validator;
+ }
+
+ /**
+ * Test a the validator contains the field given his name
+ *
+ * @param fieldName the name of the searched field
+ * @return <code>true</code> if validator contaisn this field,
+ * <code>false</code> otherwise
+ */
+ public boolean containsField(String fieldName) {
+ return fieldNames.contains(fieldName);
+ }
+
+ public void setIncludeDefaultContext(boolean includeDefaultContext) {
+ this.includeDefaultContext = includeDefaultContext;
+ if (contextName != null) {
+ // reload context
+ setContextName(contextName);
+ }
+ }
+
+ public void setContextName(String contextName) {
+ this.contextName = contextName;
+ // changing contextName may change fields definition
+ // so reload fields
+ initFields();
+ }
+
+ /**
+ * Valide le bean donné et retourne les messages produits.
+ *
+ * @param bean le bean a valider (il doit etre non null)
+ * @return le dictionnaire des messages produits par la validation indexées
+ * par le nom du champs du bean impacté.
+ */
+ public Map<String, List<String>> validate(B bean) {
+
+ if (bean == null) {
+ throw new NullPointerException(
+ "bean can not be null in method validate");
+ }
+
+ Map<String, List<String>> result = EMPTY_RESULT;
+
+ // on lance la validation uniquement si des champs sont a valider
+ if (!fieldNames.isEmpty()) {
+
+ try {
+
+ //TC - 20081024 : since context is in a ThreadLocal variable,
+ // we must do the check
+ if (ActionContext.getContext() == null) {
+ ActionContext.setContext(context);
+ }
+
+ validator.validate(bean, contextName, validationContext);
+
+ if (log.isTraceEnabled()) {
+ log.trace("Action errors: " +
+ validationContext.getActionErrors());
+ log.trace("Action messages: " +
+ validationContext.getActionMessages());
+ log.trace("Field errors: " +
+ validationContext.getFieldErrors());
+ }
+
+ if (log.isDebugEnabled()) {
+ log.debug(this + " : " +
+ validationContext.getFieldErrors());
+ }
+
+ // retreave errors by field
+ if (validationContext.hasFieldErrors()) {
+ Map<?, ?> messages = validationContext.getFieldErrors();
+ result = new HashMap<String, List<String>>(messages.size());
+ for (Object fieldName : messages.keySet()) {
+ Collection<?> c =
+ (Collection<?>) messages.get(fieldName);
+ List<String> mm = new ArrayList<String>(c.size());
+ for (Object message : c) {
+ // tchemit 2010-08-28 : trim the incoming message
+ // (I18n will not translate it otherwise)
+ String messageStr = message == null ? "" : message + "";
+ mm.add(messageStr.trim());
+ }
+ result.put(fieldName + "", mm);
+ }
+ }
+
+ } catch (ValidationException eee) {
+ if (log.isWarnEnabled()) {
+ log.warn("Error during validation on " + beanClass +
+ " for reason : " + eee.getMessage(), eee);
+ }
+
+ } finally {
+ // on nettoye toujours le validateur apres operation
+ validationSupport.clearErrorsAndMessages();
+ }
+ }
+
+ return result;
+ }
+
+ @Override
+ public String toString() {
+ return super.toString() + "<beanClass:" + beanClass +
+ ", contextName:" + contextName + ">";
+ }
+
+ /** update the property {@link #fieldNames}, says search in XWorks */
+ protected void initFields() {
+
+ if (fieldNames != null) {
+ fieldNames = null;
+ }
+
+ Set<String> detectedFieldNames = new HashSet<String>();
+
+ int skip = 0;
+ if (contextName != null && !includeDefaultContext) {
+ // count the number of validator to skip
+ for (Validator<?> v : validator.getValidators(beanClass, null)) {
+ // we only work on FieldValidator at the moment
+ if (v instanceof FieldValidator) {
+ skip++;
+ }
+ }
+ }
+
+ for (Validator<?> v : validator.getValidators(beanClass, contextName)) {
+ // we only work on FieldValidator at the moment
+ if (v instanceof FieldValidator) {
+ if (skip > 0) {
+ skip--;
+ continue;
+ }
+ FieldValidator fieldValidator = (FieldValidator) v;
+ if (log.isDebugEnabled()) {
+ log.debug("context " + contextName + " - field " +
+ fieldValidator.getFieldName());
+ }
+ String fName = fieldValidator.getFieldName();
+ detectedFieldNames.add(fName);
+ }
+ }
+
+ fieldNames = Collections.unmodifiableSet(detectedFieldNames);
+ }
+}
Property changes on: trunk/nuiton-validator/src/main/java/org/nuiton/validator/legacy/XWorkBeanValidator.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Deleted: trunk/nuiton-validator/src/test/java/org/nuiton/validator/AbstractBeanValidatorDetectorTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/AbstractBeanValidatorDetectorTest.java 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/AbstractBeanValidatorDetectorTest.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,196 +0,0 @@
-/*
- * #%L
- * Nuiton Utils :: Nuiton Validator
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 CodeLutin, Tony Chemit
- * %%
- * This program 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 3 of the
- * License, or (at your option) any later version.
- *
- * This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/lgpl-3.0.html>.
- * #L%
- */
-package org.nuiton.validator;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.io.File;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.SortedSet;
-import java.util.regex.Pattern;
-
-import static org.junit.Assert.assertEquals;
-
-/**
- * An abstract test to detects validators for a given list of objets types and
- * <p/>
- * a given sourceroot directory where to find validations definitions.
- * <p/>
- * You just have to implements to {@link #assertDetect(SortedSet)} which contains
- * the set of validators detected.
- * <p/>
- * See {@link BeanValidatorDetectorTest} for an example.
- * <p/>
- * Note : An implementation of this test should be produced in evry projects which
- * defines some validation definitions just to test they are syntax valid.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 1.6.0
- */
-public abstract class AbstractBeanValidatorDetectorTest {
-
- /** Logger */
- private static final Log log =
- LogFactory.getLog(AbstractBeanValidatorDetectorTest.class);
-
- protected static File basedir;
-
- protected BeanValidatorDetector instance;
-
- protected Class<?>[] classes;
-
- protected Class<?> validatorClass;
-
- protected File sourceRoot;
-
- protected AbstractBeanValidatorDetectorTest(
- File sourceRoot,
- Class<?>... classes) {
- this(BeanValidator.class, sourceRoot, classes);
- }
-
- protected AbstractBeanValidatorDetectorTest(
- Class<?> validatorClass,
- File sourceRoot,
- Class<?>... classes) {
- this.sourceRoot = sourceRoot;
- this.classes = classes;
- this.validatorClass = validatorClass;
-
- if (log.isInfoEnabled()) {
- log.info("sourceRoot " + sourceRoot);
- log.info("validatorClass " + validatorClass);
- log.info("classes " + Arrays.toString(classes));
- }
- }
-
- protected AbstractBeanValidatorDetectorTest(
- File sourceRoot,
- Collection<Class<?>> classes) {
- this(sourceRoot, classes.toArray(new Class<?>[classes.size()]));
- }
-
- public static void setUpClass() throws Exception {
- String b = System.getenv("basedir");
- if (b == null) {
- b = new File("").getAbsolutePath();
- }
- basedir = new File(b);
- if (log.isInfoEnabled()) {
- log.info("basedir " + basedir);
- }
- }
-
- @Before
- public void setUp() {
- instance = new BeanValidatorDetector();
- }
-
- @After
- public void tearDown() {
- instance = null;
- }
-
- /** Test of detect method, of class BeanValidatorDetector. */
- @Test
- public void testDetect() {
- SortedSet<BeanValidator<?>> result = detect(sourceRoot, classes, null);
- if (log.isInfoEnabled()) {
- log.info(printValidators("testDetect : ", result));
- }
- assertDetect(result);
- }
-
- protected abstract void assertDetect(
- SortedSet<BeanValidator<?>> validators);
-
- protected SortedSet<BeanValidator<?>> detect(
- File sourceRoot,
- Class<?>[] classes,
- Pattern contextPattern) {
-
- SortedSet<BeanValidator<?>> result = instance.detect(
- validatorClass,
- sourceRoot,
- contextPattern,
- classes);
- return result;
- }
-
- protected static void assertValidator(
- Class<?> expectedBeanClass,
- String expectedContextName,
- BeanValidator<?> validator) {
- assertEquals(expectedBeanClass, validator.getBeanClass());
- assertEquals(expectedContextName, validator.getContextName());
- }
-
- protected static void assertValidatorSetWithSameContextName(
- SortedSet<BeanValidator<?>> validators,
- String contextName,
- Class<?>... expectedClasses) {
-
- assertEquals(expectedClasses.length, validators.size());
- Iterator<BeanValidator<?>> itrV = validators.iterator();
-
- for (Class<?> expectedClass : expectedClasses) {
- assertValidator(expectedClass, contextName, itrV.next());
- }
- }
-
- protected static void assertValidatorSetWithMultiContextName(
- SortedSet<BeanValidator<?>> validators,
- Object... expecteds) {
-
- assertEquals(expecteds.length % 2, 0);
- assertEquals(expecteds.length / 2, validators.size());
- Iterator<BeanValidator<?>> itrV = validators.iterator();
-
- for (int i = 0; i < expecteds.length / 2; i++) {
- String contextName = (String) expecteds[2 * i];
- Class<?> expectedClass = (Class<?>) expecteds[2 * i + 1];
- assertValidator(expectedClass, contextName, itrV.next());
- }
-
- }
-
- protected static String printValidators(
- String prefix,
- SortedSet<BeanValidator<?>> result) {
- StringBuilder buffer;
- buffer = new StringBuilder(result.size() * (prefix.length() + 50));
- buffer.append(prefix).append(result.size()).append('\n');
- for (BeanValidator<?> v : result) {
- buffer.append(prefix).append(v).append('\n');
- }
- return buffer.toString();
- }
-}
\ No newline at end of file
Deleted: trunk/nuiton-validator/src/test/java/org/nuiton/validator/BeanValidatorDetectorTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/BeanValidatorDetectorTest.java 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/BeanValidatorDetectorTest.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,116 +0,0 @@
-/*
- * #%L
- * Nuiton Utils :: Nuiton Validator
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 CodeLutin, Tony Chemit
- * %%
- * This program 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 3 of the
- * License, or (at your option) any later version.
- *
- * This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/lgpl-3.0.html>.
- * #L%
- */
-package org.nuiton.validator;
-
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import java.io.File;
-import java.util.SortedSet;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-
-/** @author tchemit <chemit(a)codelutin.com> */
-public class BeanValidatorDetectorTest extends AbstractBeanValidatorDetectorTest {
-
- private static final Class<?>[] TYPES = new Class<?>[]{Object.class};
-
- @BeforeClass
- public static void setUpClass() throws Exception {
- AbstractBeanValidatorDetectorTest.setUpClass();
-
- }
-
- public BeanValidatorDetectorTest() {
- super(new File(basedir, "src" + File.separator + "test" + File.separator + "resources"), SimpleBean.class);
- }
-
- /** Test of detect method, of class BeanValidatorDetector. */
- @Test
- public void testDetectNothing() {
-
- SortedSet<BeanValidator<?>> validators = instance.detect(sourceRoot, TYPES);
- assertEquals(0, validators.size());
- }
-
- @Override
- protected void assertDetect(SortedSet<BeanValidator<?>> validators) {
- assertEquals(1, validators.size());
- BeanValidator<?> validator = validators.iterator().next();
- assertEquals(classes[0], validator.getBeanClass());
- assertNull(validator.getContextName());
- }
-
- /** Test of getValidator method, of class BeanValidatorDetector. */
- @Test
- public void testGetValidator() {
- Class<?>[] types = {SimpleBean.class};
- SortedSet<BeanValidator<?>> result = instance.detect(sourceRoot, types);
- assertEquals(1, result.size());
- BeanValidator<?> validator = result.iterator().next();
- assertEquals(types[0], validator.getBeanClass());
- assertNull(validator.getContextName());
-
- types = TYPES;
- result = instance.detect(sourceRoot, types);
- assertEquals(0, result.size());
-
- }
-
- /** Test of getClassDir method, of class BeanValidatorDetector. */
- @Test
- public void testGetClassDir() {
- Class<?> clazz = classes[0];
-
- File expected = new File(sourceRoot, "org" + File.separator + "nuiton" + File.separator + "validator");
- File result = instance.getClassDir(sourceRoot, clazz);
- assertEquals(expected, result);
- }
-
- /** Test of getContexts method, of class BeanValidatorDetector. */
- @Test
- public void testGetContexts() {
-
- String[] expResult = {"fatal", "error", "info", "simple", "warning"};
- Class<?> clazz = classes[0];
- File dir = instance.getClassDir(sourceRoot, clazz);
- String[] result = instance.getContexts(clazz, dir);
- assertEquals(expResult.length, result.length);
- }
-
- /** Test of getContextsWithoutScopes method, of class BeanValidatorDetector. */
- @Test
- public void testGetContextsWithoutScopes() {
-
- Class<?> clazz = SimpleBean.class;
- String[] expResult = {""};
- File dir = instance.getClassDir(sourceRoot, clazz);
- String[] contexts = instance.getContexts(clazz, dir);
- String[] result = instance.getContextsWithoutScopes(contexts);
- assertEquals(expResult.length, result.length);
-
- }
-}
\ No newline at end of file
Deleted: trunk/nuiton-validator/src/test/java/org/nuiton/validator/BeanValidatorTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/BeanValidatorTest.java 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/BeanValidatorTest.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,290 +0,0 @@
-/*
- * #%L
- * Nuiton Utils :: Nuiton Validator
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 CodeLutin, Tony Chemit
- * %%
- * This program 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 3 of the
- * License, or (at your option) any later version.
- *
- * This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/lgpl-3.0.html>.
- * #L%
- */
-package org.nuiton.validator;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-/** @author tchemit <chemit(a)codelutin.com> */
-public class BeanValidatorTest {
-
- /** Logger */
- static protected final Log log = LogFactory.getLog(BeanValidator.class);
-
- protected BeanValidator<SimpleBean> validator;
-
- protected SimpleBean bean;
-
- BeanValidatorListenerImpl fatalListener;
-
- BeanValidatorListenerImpl errorListener;
-
- BeanValidatorListenerImpl warningListener;
-
- BeanValidatorListenerImpl infoListener;
-
- @Before
- public void setUp() {
- bean = new SimpleBean();
- validator = new BeanValidator<SimpleBean>(SimpleBean.class, null);
- validator.addBeanValidatorListener(fatalListener = new BeanValidatorListenerImpl(BeanValidatorScope.FATAL));
- validator.addBeanValidatorListener(errorListener = new BeanValidatorListenerImpl(BeanValidatorScope.ERROR));
- validator.addBeanValidatorListener(warningListener = new BeanValidatorListenerImpl(BeanValidatorScope.WARNING));
- validator.addBeanValidatorListener(infoListener = new BeanValidatorListenerImpl(BeanValidatorScope.INFO));
- }
-
- @After
- public void tearDown() {
- bean = null;
- if (validator != null) {
- validator.setBean(null);
- validator = null;
- }
- }
-
- private static final String STRING_VALUE_FATAL= "stringValue.fatal";
-
- private static final String STRING_VALUE_ERROR = "stringValue.error";
-
- private static final String STRING_VALUE_WARNING = "stringValue.warning";
-
- private static final String INT_VALUE_FATAL = "intValue.fatal";
-
- private static final String INT_VALUE_ERROR = "intValue.error";
-
- private static final String INT_VALUE_INFO = "intValue.info";
-
- @Test
- public void testValidate() {
-
- assertMessages(fatalListener);
- assertMessages(errorListener);
- assertMessages(warningListener);
- assertMessages(infoListener);
-
- if (log.isInfoEnabled()) {
- log.info("-----------------------------------------------");
- }
- validator.setBean(bean);
-
- assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
- assertMessages(errorListener, STRING_VALUE_ERROR, INT_VALUE_ERROR);
- assertMessages(warningListener, STRING_VALUE_WARNING);
- assertMessages(infoListener, INT_VALUE_INFO);
-
- if (log.isInfoEnabled()) {
- log.info("-----------------------------------------------");
- }
- bean.setStringValue("one");
-
- assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
- assertMessages(errorListener, INT_VALUE_ERROR);
- assertMessages(warningListener, STRING_VALUE_WARNING);
- assertMessages(infoListener, INT_VALUE_INFO);
-
- if (log.isInfoEnabled()) {
- log.info("-----------------------------------------------");
- }
- bean.setStringValue("oneone");
-
- assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
- assertMessages(errorListener, INT_VALUE_ERROR);
- assertMessages(warningListener);
- assertMessages(infoListener, INT_VALUE_INFO);
-
- if (log.isInfoEnabled()) {
- log.info("-----------------------------------------------");
- }
- bean.setIntValue(1);
-
- assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
- assertMessages(errorListener);
- assertMessages(warningListener);
- assertMessages(infoListener, INT_VALUE_INFO);
-
- if (log.isInfoEnabled()) {
- log.info("-----------------------------------------------");
- }
- bean.setIntValue(10);
-
- assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
- assertMessages(errorListener);
- assertMessages(warningListener);
- assertMessages(infoListener);
-
- if (log.isInfoEnabled()) {
- log.info("-----------------------------------------------");
- }
-
- bean.setStringValue(null);
- bean.setIntValue(0);
-
- assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
- assertMessages(errorListener, STRING_VALUE_ERROR, INT_VALUE_ERROR);
- assertMessages(warningListener, STRING_VALUE_WARNING);
- assertMessages(infoListener, INT_VALUE_INFO);
-
-
- if (log.isInfoEnabled()) {
- log.info("-----------------------------------------------");
- }
-
- bean.setStringValue("5");
- bean.setIntValue(5);
- assertMessages(fatalListener);
- assertMessages(errorListener);
- assertMessages(warningListener,STRING_VALUE_WARNING);
- assertMessages(infoListener,INT_VALUE_INFO);
- }
-
- @Test
- public void testConvert() {
-
-
- assertMessages(errorListener);
- assertMessages(warningListener);
- assertMessages(infoListener);
-
- if (log.isInfoEnabled()) {
- log.info("-----------------------------------------------");
- }
-
- validator.setBean(bean);
-
- assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
- assertMessages(errorListener, STRING_VALUE_ERROR, INT_VALUE_ERROR);
- assertMessages(warningListener, STRING_VALUE_WARNING);
- assertMessages(infoListener, INT_VALUE_INFO);
-
-
- if (log.isInfoEnabled()) {
- log.info("-----------------------------------------------");
- }
-
- Object value = validator.convert("intValue", "abc", Class.class);
-
- Assert.assertNull(value);
-
- assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
- assertMessages(errorListener, STRING_VALUE_ERROR, "error.convertor.class");
- assertMessages(warningListener, STRING_VALUE_WARNING);
- assertMessages(infoListener, INT_VALUE_INFO);
-
- if (log.isInfoEnabled()) {
- log.info("-----------------------------------------------");
- }
- bean.setStringValue("one");
-
- assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
- assertMessages(errorListener, "error.convertor.class");
- assertMessages(warningListener, STRING_VALUE_WARNING);
- assertMessages(infoListener, INT_VALUE_INFO);
-
- if (log.isInfoEnabled()) {
- log.info("-----------------------------------------------");
- }
-
- value = validator.convert("intValue", "3", Integer.class);
-
- bean.setIntValue((Integer) value);
-
- assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
- assertMessages(errorListener);
- assertMessages(warningListener, STRING_VALUE_WARNING);
- assertMessages(infoListener, INT_VALUE_INFO);
-
- if (log.isInfoEnabled()) {
- log.info("-----------------------------------------------");
- }
-
- bean.setIntValue(-1);
- assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
- assertMessages(errorListener, INT_VALUE_ERROR);
- assertMessages(warningListener, STRING_VALUE_WARNING);
- assertMessages(infoListener, INT_VALUE_INFO);
-
- if (log.isInfoEnabled()) {
- log.info("-----------------------------------------------");
- }
- }
-
- void assertMessages(BeanValidatorListenerImpl listener,
- String... expected) {
- List<String> actual = listener.getMessages();
- Assert.assertEquals(" shoudl have " +
- Arrays.toString(expected) + " but had " + actual,
- expected.length, actual.size());
- for (String m : expected) {
- Assert.assertEquals("could not find " + m + " in " + actual,
- true, actual.contains(m));
- }
- }
-
- class BeanValidatorListenerImpl implements BeanValidatorListener {
-
- final BeanValidatorScope scope;
-
- public BeanValidatorListenerImpl(BeanValidatorScope scope) {
- this.scope = scope;
- }
-
- List<String> messages = new ArrayList<String>();
-
- public List<String> getMessages() {
- return messages;
- }
-
- @Override
- public void onFieldChanged(BeanValidatorEvent event) {
- if (scope != event.getScope()) {
- return;
- }
- String[] messagesToDelete = event.getMessagesToDelete();
- if (messagesToDelete != null && messagesToDelete.length > 0) {
- if (log.isInfoEnabled()) {
- log.info(event.getScope() + " messages to delete : " + Arrays.toString(messagesToDelete));
- }
- for (String m : messagesToDelete) {
- messages.remove(m);
- }
- }
- String[] messagesToAdd = event.getMessagesToAdd();
- if (messagesToAdd != null && messagesToAdd.length > 0) {
- if (log.isInfoEnabled()) {
- log.info(event.getScope() + " messages to add : " + Arrays.toString(messagesToAdd));
- }
- messages.addAll(Arrays.asList(messagesToAdd));
- }
- }
- }
-}
Deleted: trunk/nuiton-validator/src/test/java/org/nuiton/validator/SimpleBean.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/SimpleBean.java 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/SimpleBean.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,79 +0,0 @@
-/*
- * #%L
- * Nuiton Utils :: Nuiton Validator
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 CodeLutin, Tony Chemit
- * %%
- * This program 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 3 of the
- * License, or (at your option) any later version.
- *
- * This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/lgpl-3.0.html>.
- * #L%
- */
-package org.nuiton.validator;
-
-import java.beans.PropertyChangeListener;
-import java.beans.PropertyChangeSupport;
-
-public class SimpleBean {
-
- protected int intValue;
-
- protected String stringValue;
-
- final PropertyChangeSupport p;
-
- public SimpleBean() {
- p = new PropertyChangeSupport(this);
- }
-
- public int getIntValue() {
- return intValue;
- }
-
- public String getStringValue() {
- return stringValue;
- }
-
- public void setStringValue(String stringValue) {
- String old = this.stringValue;
- this.stringValue = stringValue;
- p.firePropertyChange("stringValue", old, stringValue);
- }
-
- public void setIntValue(int intValue) {
- int old = this.intValue;
- this.intValue = intValue;
- p.firePropertyChange("intValue", old, intValue);
- }
-
- public void addPropertyChangeListener(PropertyChangeListener listener) {
- p.addPropertyChangeListener(listener);
- }
-
- public void addPropertyChangeListener(String propertyName,
- PropertyChangeListener listener) {
- p.addPropertyChangeListener(propertyName, listener);
- }
-
- public void removePropertyChangeListener(PropertyChangeListener listener) {
- p.removePropertyChangeListener(listener);
- }
-
- public void removePropertyChangeListener(String propertyName,
- PropertyChangeListener listener) {
- p.removePropertyChangeListener(propertyName, listener);
- }
-}
\ No newline at end of file
Deleted: trunk/nuiton-validator/src/test/java/org/nuiton/validator/XWorkBeanValidatorTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/XWorkBeanValidatorTest.java 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/XWorkBeanValidatorTest.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,182 +0,0 @@
-/*
- * #%L
- * Nuiton Utils :: Nuiton Validator
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2011 CodeLutin, Tony Chemit
- * %%
- * This program 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 3 of the
- * License, or (at your option) any later version.
- *
- * This program 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 General Lesser Public License for more details.
- *
- * You should have received a copy of the GNU General Lesser Public
- * License along with this program. If not, see
- * <http://www.gnu.org/licenses/lgpl-3.0.html>.
- * #L%
- */
-package org.nuiton.validator;
-
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.List;
-import java.util.Map;
-
-/**
- * @author tchemit <chemit(a)codelutin.com>
- * @since 1.3
- */
-public class XWorkBeanValidatorTest {
-
- protected XWorkBeanValidator<SimpleBean> validator;
-
- protected SimpleBean bean;
-
- protected Map<String, List<String>> messages;
-
- @Before
- public void setUp() {
- bean = new SimpleBean();
- validator = new XWorkBeanValidator<SimpleBean>(SimpleBean.class, "simple");
- }
-
- @After
- public void tearDown() {
- bean = null;
- messages = null;
- }
-
- @Test
- public void testUnknownField() {
- Assert.assertEquals(false, validator.containsField("fake_" + System.nanoTime()));
- }
-
- @Test(expected = NullPointerException.class)
- public void testValidateNPE() {
- validator.validate(null);
- }
-
- @Test
- public void testValidate() {
-
-
- messages = validator.validate(bean);
-
- assertFieldInError("stringValue", "stringValue.null", true, messages);
- assertFieldInError("intValue", "intValue.null", true, messages);
-
- bean.setStringValue("notnull");
- messages = validator.validate(bean);
-
- assertFieldInError("stringValue", "stringValue.null", false, messages);
- assertFieldInError("intValue", "intValue.null", true, messages);
-
- bean.setIntValue(1);
- messages = validator.validate(bean);
-
- assertFieldInError("stringValue", "stringValue.null", false, messages);
- assertFieldInError("intValue", "intValue.null", false, messages);
-
- }
-
- @Test
- public void testSetContextName() {
-
-
- String expected = "simple";
-
- Assert.assertEquals(expected, validator.getContextName());
- Assert.assertEquals(true, validator.containsField("stringValue"));
- Assert.assertEquals(true, validator.containsField("intValue"));
-
- validator.setContextName(expected = "error");
-
- Assert.assertEquals(expected, validator.getContextName());
- Assert.assertEquals(true, validator.containsField("stringValue"));
- Assert.assertEquals(true, validator.containsField("intValue"));
-
- validator.setContextName(expected = "warning");
-
- Assert.assertEquals(expected, validator.getContextName());
- Assert.assertEquals(true, validator.containsField("stringValue"));
- Assert.assertEquals(false, validator.containsField("intValue"));
-
- validator.setContextName(expected = "info");
-
- Assert.assertEquals(expected, validator.getContextName());
- Assert.assertEquals(false, validator.containsField("stringValue"));
- Assert.assertEquals(true, validator.containsField("intValue"));
-
- validator.setContextName(expected = "fake_" + System.nanoTime());
-
- Assert.assertEquals(expected, validator.getContextName());
- Assert.assertEquals(false, validator.containsField("stringValue"));
- Assert.assertEquals(false, validator.containsField("intValue"));
-
- }
-
- @Test
- public void testSetIncludeDefaultContext() {
-
- validator.setIncludeDefaultContext(false);
-
- String expected = "simple";
-
- Assert.assertEquals(expected, validator.getContextName());
- Assert.assertEquals(true, validator.containsField("stringValue"));
- Assert.assertEquals(true, validator.containsField("intValue"));
-
- validator.setContextName(expected = "error");
-
- Assert.assertEquals(expected, validator.getContextName());
- Assert.assertEquals(true, validator.containsField("stringValue"));
- Assert.assertEquals(true, validator.containsField("intValue"));
-
- validator.setContextName(expected = "warning");
-
- Assert.assertEquals(expected, validator.getContextName());
- Assert.assertEquals(true, validator.containsField("stringValue"));
- Assert.assertEquals(false, validator.containsField("intValue"));
-
- validator.setContextName(expected = "info");
-
- Assert.assertEquals(expected, validator.getContextName());
- Assert.assertEquals(false, validator.containsField("stringValue"));
- Assert.assertEquals(true, validator.containsField("intValue"));
-
- validator.setContextName(expected = "fake_" + System.nanoTime());
-
- Assert.assertEquals(expected, validator.getContextName());
- Assert.assertEquals(false, validator.containsField("stringValue"));
- Assert.assertEquals(false, validator.containsField("intValue"));
-
- }
-
- protected void assertFieldInError(String fieldName, String error, boolean required, Map<String, List<String>> messages) {
-
- Assert.assertEquals(true, validator.containsField(fieldName));
- List<String> fieldMessages = messages.get(fieldName);
- //Assert.assertEquals(true,validator.containsField(fieldName));
- if (fieldMessages != null) {
- for (String o : fieldMessages) {
- if (o.equals(error)) {
- Assert.assertTrue(required);
- return;
- }
- }
- }
-
- // error was not found
- Assert.assertFalse(required);
- }
-}
Copied: trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/AbstractBeanValidatorDetectorTest.java (from rev 2013, trunk/nuiton-validator/src/test/java/org/nuiton/validator/AbstractBeanValidatorDetectorTest.java)
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/AbstractBeanValidatorDetectorTest.java (rev 0)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/AbstractBeanValidatorDetectorTest.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,196 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin, Tony Chemit
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.legacy;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.File;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.SortedSet;
+import java.util.regex.Pattern;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * An abstract test to detects validators for a given list of objets types and
+ * <p/>
+ * a given sourceroot directory where to find validations definitions.
+ * <p/>
+ * You just have to implements to {@link #assertDetect(SortedSet)} which contains
+ * the set of validators detected.
+ * <p/>
+ * See {@link BeanValidatorDetectorTest} for an example.
+ * <p/>
+ * Note : An implementation of this test should be produced in evry projects which
+ * defines some validation definitions just to test they are syntax valid.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.6.0
+ */
+public abstract class AbstractBeanValidatorDetectorTest {
+
+ /** Logger */
+ private static final Log log =
+ LogFactory.getLog(AbstractBeanValidatorDetectorTest.class);
+
+ protected static File basedir;
+
+ protected BeanValidatorDetector instance;
+
+ protected Class<?>[] classes;
+
+ protected Class<?> validatorClass;
+
+ protected File sourceRoot;
+
+ protected AbstractBeanValidatorDetectorTest(
+ File sourceRoot,
+ Class<?>... classes) {
+ this(BeanValidator.class, sourceRoot, classes);
+ }
+
+ protected AbstractBeanValidatorDetectorTest(
+ Class<?> validatorClass,
+ File sourceRoot,
+ Class<?>... classes) {
+ this.sourceRoot = sourceRoot;
+ this.classes = classes;
+ this.validatorClass = validatorClass;
+
+ if (log.isInfoEnabled()) {
+ log.info("sourceRoot " + sourceRoot);
+ log.info("validatorClass " + validatorClass);
+ log.info("classes " + Arrays.toString(classes));
+ }
+ }
+
+ protected AbstractBeanValidatorDetectorTest(
+ File sourceRoot,
+ Collection<Class<?>> classes) {
+ this(sourceRoot, classes.toArray(new Class<?>[classes.size()]));
+ }
+
+ public static void setUpClass() throws Exception {
+ String b = System.getenv("basedir");
+ if (b == null) {
+ b = new File("").getAbsolutePath();
+ }
+ basedir = new File(b);
+ if (log.isInfoEnabled()) {
+ log.info("basedir " + basedir);
+ }
+ }
+
+ @Before
+ public void setUp() {
+ instance = new BeanValidatorDetector();
+ }
+
+ @After
+ public void tearDown() {
+ instance = null;
+ }
+
+ /** Test of detect method, of class BeanValidatorDetector. */
+ @Test
+ public void testDetect() {
+ SortedSet<BeanValidator<?>> result = detect(sourceRoot, classes, null);
+ if (log.isInfoEnabled()) {
+ log.info(printValidators("testDetect : ", result));
+ }
+ assertDetect(result);
+ }
+
+ protected abstract void assertDetect(
+ SortedSet<BeanValidator<?>> validators);
+
+ protected SortedSet<BeanValidator<?>> detect(
+ File sourceRoot,
+ Class<?>[] classes,
+ Pattern contextPattern) {
+
+ SortedSet<BeanValidator<?>> result = instance.detect(
+ validatorClass,
+ sourceRoot,
+ contextPattern,
+ classes);
+ return result;
+ }
+
+ protected static void assertValidator(
+ Class<?> expectedBeanClass,
+ String expectedContextName,
+ BeanValidator<?> validator) {
+ assertEquals(expectedBeanClass, validator.getBeanClass());
+ assertEquals(expectedContextName, validator.getContextName());
+ }
+
+ protected static void assertValidatorSetWithSameContextName(
+ SortedSet<BeanValidator<?>> validators,
+ String contextName,
+ Class<?>... expectedClasses) {
+
+ assertEquals(expectedClasses.length, validators.size());
+ Iterator<BeanValidator<?>> itrV = validators.iterator();
+
+ for (Class<?> expectedClass : expectedClasses) {
+ assertValidator(expectedClass, contextName, itrV.next());
+ }
+ }
+
+ protected static void assertValidatorSetWithMultiContextName(
+ SortedSet<BeanValidator<?>> validators,
+ Object... expecteds) {
+
+ assertEquals(expecteds.length % 2, 0);
+ assertEquals(expecteds.length / 2, validators.size());
+ Iterator<BeanValidator<?>> itrV = validators.iterator();
+
+ for (int i = 0; i < expecteds.length / 2; i++) {
+ String contextName = (String) expecteds[2 * i];
+ Class<?> expectedClass = (Class<?>) expecteds[2 * i + 1];
+ assertValidator(expectedClass, contextName, itrV.next());
+ }
+
+ }
+
+ protected static String printValidators(
+ String prefix,
+ SortedSet<BeanValidator<?>> result) {
+ StringBuilder buffer;
+ buffer = new StringBuilder(result.size() * (prefix.length() + 50));
+ buffer.append(prefix).append(result.size()).append('\n');
+ for (BeanValidator<?> v : result) {
+ buffer.append(prefix).append(v).append('\n');
+ }
+ return buffer.toString();
+ }
+}
\ No newline at end of file
Property changes on: trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/AbstractBeanValidatorDetectorTest.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/BeanValidatorDetectorTest.java (from rev 2013, trunk/nuiton-validator/src/test/java/org/nuiton/validator/BeanValidatorDetectorTest.java)
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/BeanValidatorDetectorTest.java (rev 0)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/BeanValidatorDetectorTest.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,116 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin, Tony Chemit
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.legacy;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.io.File;
+import java.util.SortedSet;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+/** @author tchemit <chemit(a)codelutin.com> */
+public class BeanValidatorDetectorTest extends AbstractBeanValidatorDetectorTest {
+
+ private static final Class<?>[] TYPES = new Class<?>[]{Object.class};
+
+ @BeforeClass
+ public static void setUpClass() throws Exception {
+ AbstractBeanValidatorDetectorTest.setUpClass();
+
+ }
+
+ public BeanValidatorDetectorTest() {
+ super(new File(basedir, "src" + File.separator + "test" + File.separator + "resources"), SimpleBean.class);
+ }
+
+ /** Test of detect method, of class BeanValidatorDetector. */
+ @Test
+ public void testDetectNothing() {
+
+ SortedSet<BeanValidator<?>> validators = instance.detect(sourceRoot, TYPES);
+ assertEquals(0, validators.size());
+ }
+
+ @Override
+ protected void assertDetect(SortedSet<BeanValidator<?>> validators) {
+ assertEquals(1, validators.size());
+ BeanValidator<?> validator = validators.iterator().next();
+ assertEquals(classes[0], validator.getBeanClass());
+ assertNull(validator.getContextName());
+ }
+
+ /** Test of getValidator method, of class BeanValidatorDetector. */
+ @Test
+ public void testGetValidator() {
+ Class<?>[] types = {SimpleBean.class};
+ SortedSet<BeanValidator<?>> result = instance.detect(sourceRoot, types);
+ assertEquals(1, result.size());
+ BeanValidator<?> validator = result.iterator().next();
+ assertEquals(types[0], validator.getBeanClass());
+ assertNull(validator.getContextName());
+
+ types = TYPES;
+ result = instance.detect(sourceRoot, types);
+ assertEquals(0, result.size());
+
+ }
+
+ /** Test of getClassDir method, of class BeanValidatorDetector. */
+ @Test
+ public void testGetClassDir() {
+ Class<?> clazz = classes[0];
+
+ File expected = new File(sourceRoot, "org" + File.separator + "nuiton" + File.separator + "validator" + File.separator + "legacy");
+ File result = instance.getClassDir(sourceRoot, clazz);
+ assertEquals(expected, result);
+ }
+
+ /** Test of getContexts method, of class BeanValidatorDetector. */
+ @Test
+ public void testGetContexts() {
+
+ String[] expResult = {"fatal", "error", "info", "simple", "warning"};
+ Class<?> clazz = classes[0];
+ File dir = instance.getClassDir(sourceRoot, clazz);
+ String[] result = instance.getContexts(clazz, dir);
+ assertEquals(expResult.length, result.length);
+ }
+
+ /** Test of getContextsWithoutScopes method, of class BeanValidatorDetector. */
+ @Test
+ public void testGetContextsWithoutScopes() {
+
+ Class<?> clazz = SimpleBean.class;
+ String[] expResult = {""};
+ File dir = instance.getClassDir(sourceRoot, clazz);
+ String[] contexts = instance.getContexts(clazz, dir);
+ String[] result = instance.getContextsWithoutScopes(contexts);
+ assertEquals(expResult.length, result.length);
+
+ }
+}
\ No newline at end of file
Property changes on: trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/BeanValidatorDetectorTest.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/BeanValidatorTest.java (from rev 2013, trunk/nuiton-validator/src/test/java/org/nuiton/validator/BeanValidatorTest.java)
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/BeanValidatorTest.java (rev 0)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/BeanValidatorTest.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,290 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin, Tony Chemit
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.legacy;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+/** @author tchemit <chemit(a)codelutin.com> */
+public class BeanValidatorTest {
+
+ /** Logger */
+ static protected final Log log = LogFactory.getLog(BeanValidator.class);
+
+ protected BeanValidator<SimpleBean> validator;
+
+ protected SimpleBean bean;
+
+ BeanValidatorListenerImpl fatalListener;
+
+ BeanValidatorListenerImpl errorListener;
+
+ BeanValidatorListenerImpl warningListener;
+
+ BeanValidatorListenerImpl infoListener;
+
+ @Before
+ public void setUp() {
+ bean = new SimpleBean();
+ validator = new BeanValidator<SimpleBean>(SimpleBean.class, null);
+ validator.addBeanValidatorListener(fatalListener = new BeanValidatorListenerImpl(BeanValidatorScope.FATAL));
+ validator.addBeanValidatorListener(errorListener = new BeanValidatorListenerImpl(BeanValidatorScope.ERROR));
+ validator.addBeanValidatorListener(warningListener = new BeanValidatorListenerImpl(BeanValidatorScope.WARNING));
+ validator.addBeanValidatorListener(infoListener = new BeanValidatorListenerImpl(BeanValidatorScope.INFO));
+ }
+
+ @After
+ public void tearDown() {
+ bean = null;
+ if (validator != null) {
+ validator.setBean(null);
+ validator = null;
+ }
+ }
+
+ private static final String STRING_VALUE_FATAL= "stringValue.fatal";
+
+ private static final String STRING_VALUE_ERROR = "stringValue.error";
+
+ private static final String STRING_VALUE_WARNING = "stringValue.warning";
+
+ private static final String INT_VALUE_FATAL = "intValue.fatal";
+
+ private static final String INT_VALUE_ERROR = "intValue.error";
+
+ private static final String INT_VALUE_INFO = "intValue.info";
+
+ @Test
+ public void testValidate() {
+
+ assertMessages(fatalListener);
+ assertMessages(errorListener);
+ assertMessages(warningListener);
+ assertMessages(infoListener);
+
+ if (log.isInfoEnabled()) {
+ log.info("-----------------------------------------------");
+ }
+ validator.setBean(bean);
+
+ assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
+ assertMessages(errorListener, STRING_VALUE_ERROR, INT_VALUE_ERROR);
+ assertMessages(warningListener, STRING_VALUE_WARNING);
+ assertMessages(infoListener, INT_VALUE_INFO);
+
+ if (log.isInfoEnabled()) {
+ log.info("-----------------------------------------------");
+ }
+ bean.setStringValue("one");
+
+ assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
+ assertMessages(errorListener, INT_VALUE_ERROR);
+ assertMessages(warningListener, STRING_VALUE_WARNING);
+ assertMessages(infoListener, INT_VALUE_INFO);
+
+ if (log.isInfoEnabled()) {
+ log.info("-----------------------------------------------");
+ }
+ bean.setStringValue("oneone");
+
+ assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
+ assertMessages(errorListener, INT_VALUE_ERROR);
+ assertMessages(warningListener);
+ assertMessages(infoListener, INT_VALUE_INFO);
+
+ if (log.isInfoEnabled()) {
+ log.info("-----------------------------------------------");
+ }
+ bean.setIntValue(1);
+
+ assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
+ assertMessages(errorListener);
+ assertMessages(warningListener);
+ assertMessages(infoListener, INT_VALUE_INFO);
+
+ if (log.isInfoEnabled()) {
+ log.info("-----------------------------------------------");
+ }
+ bean.setIntValue(10);
+
+ assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
+ assertMessages(errorListener);
+ assertMessages(warningListener);
+ assertMessages(infoListener);
+
+ if (log.isInfoEnabled()) {
+ log.info("-----------------------------------------------");
+ }
+
+ bean.setStringValue(null);
+ bean.setIntValue(0);
+
+ assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
+ assertMessages(errorListener, STRING_VALUE_ERROR, INT_VALUE_ERROR);
+ assertMessages(warningListener, STRING_VALUE_WARNING);
+ assertMessages(infoListener, INT_VALUE_INFO);
+
+
+ if (log.isInfoEnabled()) {
+ log.info("-----------------------------------------------");
+ }
+
+ bean.setStringValue("5");
+ bean.setIntValue(5);
+ assertMessages(fatalListener);
+ assertMessages(errorListener);
+ assertMessages(warningListener,STRING_VALUE_WARNING);
+ assertMessages(infoListener,INT_VALUE_INFO);
+ }
+
+ @Test
+ public void testConvert() {
+
+
+ assertMessages(errorListener);
+ assertMessages(warningListener);
+ assertMessages(infoListener);
+
+ if (log.isInfoEnabled()) {
+ log.info("-----------------------------------------------");
+ }
+
+ validator.setBean(bean);
+
+ assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
+ assertMessages(errorListener, STRING_VALUE_ERROR, INT_VALUE_ERROR);
+ assertMessages(warningListener, STRING_VALUE_WARNING);
+ assertMessages(infoListener, INT_VALUE_INFO);
+
+
+ if (log.isInfoEnabled()) {
+ log.info("-----------------------------------------------");
+ }
+
+ Object value = validator.convert("intValue", "abc", Class.class);
+
+ Assert.assertNull(value);
+
+ assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
+ assertMessages(errorListener, STRING_VALUE_ERROR, "error.convertor.class");
+ assertMessages(warningListener, STRING_VALUE_WARNING);
+ assertMessages(infoListener, INT_VALUE_INFO);
+
+ if (log.isInfoEnabled()) {
+ log.info("-----------------------------------------------");
+ }
+ bean.setStringValue("one");
+
+ assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
+ assertMessages(errorListener, "error.convertor.class");
+ assertMessages(warningListener, STRING_VALUE_WARNING);
+ assertMessages(infoListener, INT_VALUE_INFO);
+
+ if (log.isInfoEnabled()) {
+ log.info("-----------------------------------------------");
+ }
+
+ value = validator.convert("intValue", "3", Integer.class);
+
+ bean.setIntValue((Integer) value);
+
+ assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
+ assertMessages(errorListener);
+ assertMessages(warningListener, STRING_VALUE_WARNING);
+ assertMessages(infoListener, INT_VALUE_INFO);
+
+ if (log.isInfoEnabled()) {
+ log.info("-----------------------------------------------");
+ }
+
+ bean.setIntValue(-1);
+ assertMessages(fatalListener,STRING_VALUE_FATAL,INT_VALUE_FATAL);
+ assertMessages(errorListener, INT_VALUE_ERROR);
+ assertMessages(warningListener, STRING_VALUE_WARNING);
+ assertMessages(infoListener, INT_VALUE_INFO);
+
+ if (log.isInfoEnabled()) {
+ log.info("-----------------------------------------------");
+ }
+ }
+
+ void assertMessages(BeanValidatorListenerImpl listener,
+ String... expected) {
+ List<String> actual = listener.getMessages();
+ Assert.assertEquals(" shoudl have " +
+ Arrays.toString(expected) + " but had " + actual,
+ expected.length, actual.size());
+ for (String m : expected) {
+ Assert.assertEquals("could not find " + m + " in " + actual,
+ true, actual.contains(m));
+ }
+ }
+
+ class BeanValidatorListenerImpl implements BeanValidatorListener {
+
+ final BeanValidatorScope scope;
+
+ public BeanValidatorListenerImpl(BeanValidatorScope scope) {
+ this.scope = scope;
+ }
+
+ List<String> messages = new ArrayList<String>();
+
+ public List<String> getMessages() {
+ return messages;
+ }
+
+ @Override
+ public void onFieldChanged(BeanValidatorEvent event) {
+ if (scope != event.getScope()) {
+ return;
+ }
+ String[] messagesToDelete = event.getMessagesToDelete();
+ if (messagesToDelete != null && messagesToDelete.length > 0) {
+ if (log.isInfoEnabled()) {
+ log.info(event.getScope() + " messages to delete : " + Arrays.toString(messagesToDelete));
+ }
+ for (String m : messagesToDelete) {
+ messages.remove(m);
+ }
+ }
+ String[] messagesToAdd = event.getMessagesToAdd();
+ if (messagesToAdd != null && messagesToAdd.length > 0) {
+ if (log.isInfoEnabled()) {
+ log.info(event.getScope() + " messages to add : " + Arrays.toString(messagesToAdd));
+ }
+ messages.addAll(Arrays.asList(messagesToAdd));
+ }
+ }
+ }
+}
Property changes on: trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/BeanValidatorTest.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/SimpleBean.java (from rev 2013, trunk/nuiton-validator/src/test/java/org/nuiton/validator/SimpleBean.java)
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/SimpleBean.java (rev 0)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/SimpleBean.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,79 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin, Tony Chemit
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.legacy;
+
+import java.beans.PropertyChangeListener;
+import java.beans.PropertyChangeSupport;
+
+public class SimpleBean {
+
+ protected int intValue;
+
+ protected String stringValue;
+
+ final PropertyChangeSupport p;
+
+ public SimpleBean() {
+ p = new PropertyChangeSupport(this);
+ }
+
+ public int getIntValue() {
+ return intValue;
+ }
+
+ public String getStringValue() {
+ return stringValue;
+ }
+
+ public void setStringValue(String stringValue) {
+ String old = this.stringValue;
+ this.stringValue = stringValue;
+ p.firePropertyChange("stringValue", old, stringValue);
+ }
+
+ public void setIntValue(int intValue) {
+ int old = this.intValue;
+ this.intValue = intValue;
+ p.firePropertyChange("intValue", old, intValue);
+ }
+
+ public void addPropertyChangeListener(PropertyChangeListener listener) {
+ p.addPropertyChangeListener(listener);
+ }
+
+ public void addPropertyChangeListener(String propertyName,
+ PropertyChangeListener listener) {
+ p.addPropertyChangeListener(propertyName, listener);
+ }
+
+ public void removePropertyChangeListener(PropertyChangeListener listener) {
+ p.removePropertyChangeListener(listener);
+ }
+
+ public void removePropertyChangeListener(String propertyName,
+ PropertyChangeListener listener) {
+ p.removePropertyChangeListener(propertyName, listener);
+ }
+}
\ No newline at end of file
Property changes on: trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/SimpleBean.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/XWorkBeanValidatorTest.java (from rev 2013, trunk/nuiton-validator/src/test/java/org/nuiton/validator/XWorkBeanValidatorTest.java)
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/XWorkBeanValidatorTest.java (rev 0)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/XWorkBeanValidatorTest.java 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,182 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin, Tony Chemit
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.legacy;
+
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 1.3
+ */
+public class XWorkBeanValidatorTest {
+
+ protected XWorkBeanValidator<SimpleBean> validator;
+
+ protected SimpleBean bean;
+
+ protected Map<String, List<String>> messages;
+
+ @Before
+ public void setUp() {
+ bean = new SimpleBean();
+ validator = new XWorkBeanValidator<SimpleBean>(SimpleBean.class, "simple");
+ }
+
+ @After
+ public void tearDown() {
+ bean = null;
+ messages = null;
+ }
+
+ @Test
+ public void testUnknownField() {
+ Assert.assertEquals(false, validator.containsField("fake_" + System.nanoTime()));
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void testValidateNPE() {
+ validator.validate(null);
+ }
+
+ @Test
+ public void testValidate() {
+
+
+ messages = validator.validate(bean);
+
+ assertFieldInError("stringValue", "stringValue.null", true, messages);
+ assertFieldInError("intValue", "intValue.null", true, messages);
+
+ bean.setStringValue("notnull");
+ messages = validator.validate(bean);
+
+ assertFieldInError("stringValue", "stringValue.null", false, messages);
+ assertFieldInError("intValue", "intValue.null", true, messages);
+
+ bean.setIntValue(1);
+ messages = validator.validate(bean);
+
+ assertFieldInError("stringValue", "stringValue.null", false, messages);
+ assertFieldInError("intValue", "intValue.null", false, messages);
+
+ }
+
+ @Test
+ public void testSetContextName() {
+
+
+ String expected = "simple";
+
+ Assert.assertEquals(expected, validator.getContextName());
+ Assert.assertEquals(true, validator.containsField("stringValue"));
+ Assert.assertEquals(true, validator.containsField("intValue"));
+
+ validator.setContextName(expected = "error");
+
+ Assert.assertEquals(expected, validator.getContextName());
+ Assert.assertEquals(true, validator.containsField("stringValue"));
+ Assert.assertEquals(true, validator.containsField("intValue"));
+
+ validator.setContextName(expected = "warning");
+
+ Assert.assertEquals(expected, validator.getContextName());
+ Assert.assertEquals(true, validator.containsField("stringValue"));
+ Assert.assertEquals(false, validator.containsField("intValue"));
+
+ validator.setContextName(expected = "info");
+
+ Assert.assertEquals(expected, validator.getContextName());
+ Assert.assertEquals(false, validator.containsField("stringValue"));
+ Assert.assertEquals(true, validator.containsField("intValue"));
+
+ validator.setContextName(expected = "fake_" + System.nanoTime());
+
+ Assert.assertEquals(expected, validator.getContextName());
+ Assert.assertEquals(false, validator.containsField("stringValue"));
+ Assert.assertEquals(false, validator.containsField("intValue"));
+
+ }
+
+ @Test
+ public void testSetIncludeDefaultContext() {
+
+ validator.setIncludeDefaultContext(false);
+
+ String expected = "simple";
+
+ Assert.assertEquals(expected, validator.getContextName());
+ Assert.assertEquals(true, validator.containsField("stringValue"));
+ Assert.assertEquals(true, validator.containsField("intValue"));
+
+ validator.setContextName(expected = "error");
+
+ Assert.assertEquals(expected, validator.getContextName());
+ Assert.assertEquals(true, validator.containsField("stringValue"));
+ Assert.assertEquals(true, validator.containsField("intValue"));
+
+ validator.setContextName(expected = "warning");
+
+ Assert.assertEquals(expected, validator.getContextName());
+ Assert.assertEquals(true, validator.containsField("stringValue"));
+ Assert.assertEquals(false, validator.containsField("intValue"));
+
+ validator.setContextName(expected = "info");
+
+ Assert.assertEquals(expected, validator.getContextName());
+ Assert.assertEquals(false, validator.containsField("stringValue"));
+ Assert.assertEquals(true, validator.containsField("intValue"));
+
+ validator.setContextName(expected = "fake_" + System.nanoTime());
+
+ Assert.assertEquals(expected, validator.getContextName());
+ Assert.assertEquals(false, validator.containsField("stringValue"));
+ Assert.assertEquals(false, validator.containsField("intValue"));
+
+ }
+
+ protected void assertFieldInError(String fieldName, String error, boolean required, Map<String, List<String>> messages) {
+
+ Assert.assertEquals(true, validator.containsField(fieldName));
+ List<String> fieldMessages = messages.get(fieldName);
+ //Assert.assertEquals(true,validator.containsField(fieldName));
+ if (fieldMessages != null) {
+ for (String o : fieldMessages) {
+ if (o.equals(error)) {
+ Assert.assertTrue(required);
+ return;
+ }
+ }
+ }
+
+ // error was not found
+ Assert.assertFalse(required);
+ }
+}
Property changes on: trunk/nuiton-validator/src/test/java/org/nuiton/validator/legacy/XWorkBeanValidatorTest.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Deleted: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-error-validation.xml
===================================================================
--- trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-error-validation.xml 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-error-validation.xml 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,43 +0,0 @@
-<!--
- #%L
- Nuiton Utils :: Nuiton Validator
-
- $Id$
- $HeadURL$
- %%
- Copyright (C) 2011 CodeLutin, Tony Chemit
- %%
- This program 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 3 of the
- License, or (at your option) any later version.
-
- This program 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 General Lesser Public License for more details.
-
- You should have received a copy of the GNU General Lesser Public
- License along with this program. If not, see
- <http://www.gnu.org/licenses/lgpl-3.0.html>.
- #L%
- -->
-<!DOCTYPE validators PUBLIC
- "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
- "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
-<validators>
-
- <field name="stringValue">
- <field-validator type="requiredstring">
- <message>stringValue.error</message>
- </field-validator>
- </field>
-
- <field name="intValue">
- <field-validator type="int">
- <param name="min">1</param>
- <message>intValue.error</message>
- </field-validator>
- </field>
-
-</validators>
\ No newline at end of file
Deleted: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-fatal-validation.xml
===================================================================
--- trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-fatal-validation.xml 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-fatal-validation.xml 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,47 +0,0 @@
-<!--
- #%L
- Nuiton Utils :: Nuiton Validator
-
- $Id$
- $HeadURL$
- %%
- Copyright (C) 2011 CodeLutin, Tony Chemit
- %%
- This program 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 3 of the
- License, or (at your option) any later version.
-
- This program 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 General Lesser Public License for more details.
-
- You should have received a copy of the GNU General Lesser Public
- License along with this program. If not, see
- <http://www.gnu.org/licenses/lgpl-3.0.html>.
- #L%
- -->
-<!DOCTYPE validators PUBLIC
- "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
- "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
-<validators>
-
- <field name="stringValue">
- <field-validator type="fieldexpression">
- <param name="expression">
- <![CDATA[ stringValue != null && stringValue == "5"]]></param>
- <message>stringValue.fatal</message>
- </field-validator>
- </field>
-
-
- <field name="intValue">
- <field-validator type="int">
- <param name="min">5</param>
- <param name="max">5</param>
- <message>intValue.fatal</message>
- </field-validator>
- </field>
-
-</validators>
\ No newline at end of file
Deleted: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-info-validation.xml
===================================================================
--- trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-info-validation.xml 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-info-validation.xml 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,37 +0,0 @@
-<!--
- #%L
- Nuiton Utils :: Nuiton Validator
-
- $Id$
- $HeadURL$
- %%
- Copyright (C) 2011 CodeLutin, Tony Chemit
- %%
- This program 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 3 of the
- License, or (at your option) any later version.
-
- This program 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 General Lesser Public License for more details.
-
- You should have received a copy of the GNU General Lesser Public
- License along with this program. If not, see
- <http://www.gnu.org/licenses/lgpl-3.0.html>.
- #L%
- -->
-<!DOCTYPE validators PUBLIC
- "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
- "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
-<validators>
-
- <field name="intValue">
- <field-validator type="int">
- <param name="min">10</param>
- <message>intValue.info</message>
- </field-validator>
- </field>
-
-</validators>
\ No newline at end of file
Deleted: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-simple-validation.xml
===================================================================
--- trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-simple-validation.xml 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-simple-validation.xml 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,43 +0,0 @@
-<!--
- #%L
- Nuiton Utils :: Nuiton Validator
-
- $Id$
- $HeadURL$
- %%
- Copyright (C) 2011 CodeLutin, Tony Chemit
- %%
- This program 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 3 of the
- License, or (at your option) any later version.
-
- This program 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 General Lesser Public License for more details.
-
- You should have received a copy of the GNU General Lesser Public
- License along with this program. If not, see
- <http://www.gnu.org/licenses/lgpl-3.0.html>.
- #L%
- -->
-<!DOCTYPE validators PUBLIC
- "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
- "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
-<validators>
-
- <field name="stringValue">
- <field-validator type="requiredstring">
- <message>stringValue.null</message>
- </field-validator>
- </field>
-
- <field name="intValue">
- <field-validator type="int">
- <param name="min">1</param>
- <message>intValue.null</message>
- </field-validator>
- </field>
-
-</validators>
\ No newline at end of file
Deleted: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-warning-validation.xml
===================================================================
--- trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-warning-validation.xml 2011-01-17 18:26:47 UTC (rev 2014)
+++ trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-warning-validation.xml 2011-01-17 18:36:18 UTC (rev 2015)
@@ -1,37 +0,0 @@
-<!--
- #%L
- Nuiton Utils :: Nuiton Validator
-
- $Id$
- $HeadURL$
- %%
- Copyright (C) 2011 CodeLutin, Tony Chemit
- %%
- This program 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 3 of the
- License, or (at your option) any later version.
-
- This program 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 General Lesser Public License for more details.
-
- You should have received a copy of the GNU General Lesser Public
- License along with this program. If not, see
- <http://www.gnu.org/licenses/lgpl-3.0.html>.
- #L%
- -->
-<!DOCTYPE validators PUBLIC
- "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
- "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
-<validators>
-
- <field name="stringValue">
- <field-validator type="fieldexpression">
- <param name="expression"><![CDATA[ stringValue != null && stringValue.length() > 5]]></param>
- <message>stringValue.warning</message>
- </field-validator>
- </field>
-
-</validators>
\ No newline at end of file
Copied: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-error-validation.xml (from rev 2013, trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-error-validation.xml)
===================================================================
--- trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-error-validation.xml (rev 0)
+++ trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-error-validation.xml 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,43 @@
+<!--
+ #%L
+ Nuiton Utils :: Nuiton Validator
+
+ $Id$
+ $HeadURL$
+ %%
+ Copyright (C) 2011 CodeLutin, Tony Chemit
+ %%
+ This program 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 3 of the
+ License, or (at your option) any later version.
+
+ This program 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 General Lesser Public License for more details.
+
+ You should have received a copy of the GNU General Lesser Public
+ License along with this program. If not, see
+ <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ #L%
+ -->
+<!DOCTYPE validators PUBLIC
+ "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
+ "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
+<validators>
+
+ <field name="stringValue">
+ <field-validator type="requiredstring">
+ <message>stringValue.error</message>
+ </field-validator>
+ </field>
+
+ <field name="intValue">
+ <field-validator type="int">
+ <param name="min">1</param>
+ <message>intValue.error</message>
+ </field-validator>
+ </field>
+
+</validators>
\ No newline at end of file
Property changes on: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-error-validation.xml
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-fatal-validation.xml (from rev 2013, trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-fatal-validation.xml)
===================================================================
--- trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-fatal-validation.xml (rev 0)
+++ trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-fatal-validation.xml 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,47 @@
+<!--
+ #%L
+ Nuiton Utils :: Nuiton Validator
+
+ $Id$
+ $HeadURL$
+ %%
+ Copyright (C) 2011 CodeLutin, Tony Chemit
+ %%
+ This program 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 3 of the
+ License, or (at your option) any later version.
+
+ This program 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 General Lesser Public License for more details.
+
+ You should have received a copy of the GNU General Lesser Public
+ License along with this program. If not, see
+ <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ #L%
+ -->
+<!DOCTYPE validators PUBLIC
+ "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
+ "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
+<validators>
+
+ <field name="stringValue">
+ <field-validator type="fieldexpression">
+ <param name="expression">
+ <![CDATA[ stringValue != null && stringValue == "5"]]></param>
+ <message>stringValue.fatal</message>
+ </field-validator>
+ </field>
+
+
+ <field name="intValue">
+ <field-validator type="int">
+ <param name="min">5</param>
+ <param name="max">5</param>
+ <message>intValue.fatal</message>
+ </field-validator>
+ </field>
+
+</validators>
\ No newline at end of file
Property changes on: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-fatal-validation.xml
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-info-validation.xml (from rev 2013, trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-info-validation.xml)
===================================================================
--- trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-info-validation.xml (rev 0)
+++ trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-info-validation.xml 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,37 @@
+<!--
+ #%L
+ Nuiton Utils :: Nuiton Validator
+
+ $Id$
+ $HeadURL$
+ %%
+ Copyright (C) 2011 CodeLutin, Tony Chemit
+ %%
+ This program 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 3 of the
+ License, or (at your option) any later version.
+
+ This program 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 General Lesser Public License for more details.
+
+ You should have received a copy of the GNU General Lesser Public
+ License along with this program. If not, see
+ <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ #L%
+ -->
+<!DOCTYPE validators PUBLIC
+ "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
+ "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
+<validators>
+
+ <field name="intValue">
+ <field-validator type="int">
+ <param name="min">10</param>
+ <message>intValue.info</message>
+ </field-validator>
+ </field>
+
+</validators>
\ No newline at end of file
Property changes on: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-info-validation.xml
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-simple-validation.xml (from rev 2013, trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-simple-validation.xml)
===================================================================
--- trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-simple-validation.xml (rev 0)
+++ trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-simple-validation.xml 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,43 @@
+<!--
+ #%L
+ Nuiton Utils :: Nuiton Validator
+
+ $Id$
+ $HeadURL$
+ %%
+ Copyright (C) 2011 CodeLutin, Tony Chemit
+ %%
+ This program 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 3 of the
+ License, or (at your option) any later version.
+
+ This program 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 General Lesser Public License for more details.
+
+ You should have received a copy of the GNU General Lesser Public
+ License along with this program. If not, see
+ <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ #L%
+ -->
+<!DOCTYPE validators PUBLIC
+ "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
+ "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
+<validators>
+
+ <field name="stringValue">
+ <field-validator type="requiredstring">
+ <message>stringValue.null</message>
+ </field-validator>
+ </field>
+
+ <field name="intValue">
+ <field-validator type="int">
+ <param name="min">1</param>
+ <message>intValue.null</message>
+ </field-validator>
+ </field>
+
+</validators>
\ No newline at end of file
Property changes on: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-simple-validation.xml
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-warning-validation.xml (from rev 2013, trunk/nuiton-validator/src/test/resources/org/nuiton/validator/SimpleBean-warning-validation.xml)
===================================================================
--- trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-warning-validation.xml (rev 0)
+++ trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-warning-validation.xml 2011-01-17 18:36:18 UTC (rev 2015)
@@ -0,0 +1,37 @@
+<!--
+ #%L
+ Nuiton Utils :: Nuiton Validator
+
+ $Id$
+ $HeadURL$
+ %%
+ Copyright (C) 2011 CodeLutin, Tony Chemit
+ %%
+ This program 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 3 of the
+ License, or (at your option) any later version.
+
+ This program 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 General Lesser Public License for more details.
+
+ You should have received a copy of the GNU General Lesser Public
+ License along with this program. If not, see
+ <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ #L%
+ -->
+<!DOCTYPE validators PUBLIC
+ "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
+ "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
+<validators>
+
+ <field name="stringValue">
+ <field-validator type="fieldexpression">
+ <param name="expression"><![CDATA[ stringValue != null && stringValue.length() > 5]]></param>
+ <message>stringValue.warning</message>
+ </field-validator>
+ </field>
+
+</validators>
\ No newline at end of file
Property changes on: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/legacy/SimpleBean-warning-validation.xml
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
1
0
r2014 - trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field
by tchemit@users.nuiton.org 17 Jan '11
by tchemit@users.nuiton.org 17 Jan '11
17 Jan '11
Author: tchemit
Date: 2011-01-17 19:26:47 +0100 (Mon, 17 Jan 2011)
New Revision: 2014
Url: http://nuiton.org/repositories/revision/nuiton-utils/2014
Log:
fix test
Modified:
trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/AbstractFieldValidatorTest.java
Modified: trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/AbstractFieldValidatorTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/AbstractFieldValidatorTest.java 2011-01-17 18:24:10 UTC (rev 2013)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/AbstractFieldValidatorTest.java 2011-01-17 18:26:47 UTC (rev 2014)
@@ -117,7 +117,7 @@
List<String> errorMessages = result.getErrorMessages(fieldName);
- boolean errorFound = errorMessages.contains(fieldName);
+ boolean errorFound = errorMessages.contains(error);
if (required) {
1
0
17 Jan '11
Author: tchemit
Date: 2011-01-17 19:24:10 +0100 (Mon, 17 Jan 2011)
New Revision: 2013
Url: http://nuiton.org/repositories/revision/nuiton-utils/2013
Log:
move xwork2 field validator to the new correct package
Added:
trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/
trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/xwork2/
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/xwork2/field/
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/xwork2/field/FieldExpressionBean-error-validation.xml
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/xwork2/field/ValidatorBean-error-validation.xml
Removed:
trunk/nuiton-validator/src/main/java/org/nuiton/validator/field/
trunk/nuiton-validator/src/test/java/org/nuiton/validator/field/
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/field/FieldExpressionBean-error-validation.xml
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/field/ValidatorBean-error-validation.xml
Modified:
trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/CollectionFieldExpressionValidator.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/CollectionUniqueKeyValidator.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/ExistingDirectoryFieldValidator.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/ExistingFileFieldValidator.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/FieldExpressionWithParamsValidator.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/NotExistingDirectoryFieldValidator.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/NotExistingFileFieldValidator.java
trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/RequiredFileFieldValidator.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/AbstractFieldValidatorTest.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/AbstractValidatorBeanFieldValidatorTest.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/CollectionFieldExpressionValidatorTest.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/CollectionUniqueKeyValidatorTest.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/ExistingDirectoryFieldValidatorTest.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/ExistingFileFieldValidatorTest.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/FieldExpressionBean.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/FieldExpressionWithParamsValidatorTest.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/NotExistingDirectoryFieldValidatorTest.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/NotExistingFileFieldValidatorTest.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/RequiredFileFieldValidatorTest.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/ValidatorBean.java
trunk/nuiton-validator/src/test/resources/validators.xml
Modified: trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/CollectionFieldExpressionValidator.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/field/CollectionFieldExpressionValidator.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/CollectionFieldExpressionValidator.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,7 +22,7 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.validator.ValidationException;
Modified: trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/CollectionUniqueKeyValidator.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/field/CollectionUniqueKeyValidator.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/CollectionUniqueKeyValidator.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,7 +22,7 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldExpressionValidator;
Modified: trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/ExistingDirectoryFieldValidator.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/field/ExistingDirectoryFieldValidator.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/ExistingDirectoryFieldValidator.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,7 +22,7 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;
Modified: trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/ExistingFileFieldValidator.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/field/ExistingFileFieldValidator.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/ExistingFileFieldValidator.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,7 +22,7 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;
Modified: trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/FieldExpressionWithParamsValidator.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/field/FieldExpressionWithParamsValidator.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/FieldExpressionWithParamsValidator.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,7 +22,7 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.validator.ValidationException;
Modified: trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/NotExistingDirectoryFieldValidator.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/field/NotExistingDirectoryFieldValidator.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/NotExistingDirectoryFieldValidator.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,7 +22,7 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;
Modified: trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/NotExistingFileFieldValidator.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/field/NotExistingFileFieldValidator.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/NotExistingFileFieldValidator.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,7 +22,7 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;
Modified: trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/RequiredFileFieldValidator.java
===================================================================
--- trunk/nuiton-validator/src/main/java/org/nuiton/validator/field/RequiredFileFieldValidator.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/main/java/org/nuiton/validator/xwork2/field/RequiredFileFieldValidator.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,7 +22,7 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
import com.opensymphony.xwork2.validator.ValidationException;
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;
Modified: trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/AbstractFieldValidatorTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/field/AbstractFieldValidatorTest.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/AbstractFieldValidatorTest.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,10 +22,8 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
-import org.nuiton.validator.BeanValidator;
-import org.nuiton.validator.BeanValidatorField;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
@@ -33,8 +31,12 @@
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
+import org.nuiton.validator.NuitonValidator;
+import org.nuiton.validator.NuitonValidatorFactory;
+import org.nuiton.validator.NuitonValidatorResult;
import java.io.File;
+import java.util.List;
/**
* Abstract class to test a specific validator.
@@ -42,8 +44,8 @@
* To implements a test on a new validator, just extends this class
* and implements the method {@link #testValidator()}.
*
+ * @param <B> the type of bean to validate.
* @author tchemit <chemit(a)codelutin.com>
- * @param <B> the type of bean to validate.
*/
public abstract class AbstractFieldValidatorTest<B> extends Assert {
@@ -51,13 +53,13 @@
static private final Log log =
LogFactory.getLog(AbstractFieldValidatorTest.class);
- protected static BeanValidator<?> cacheValidator;
+ protected static NuitonValidator<?> cacheValidator;
protected static File basedir;
protected final Class<B> type;
- protected BeanValidator<B> validator;
+ protected NuitonValidator<B> validator;
protected B bean;
@@ -81,18 +83,16 @@
log.debug("start test " + getClass().getSimpleName());
bean = type.newInstance();
if (cacheValidator == null) {
- validator = new BeanValidator<B>(type, null);
+ validator = NuitonValidatorFactory.newValidator(type);
cacheValidator = validator;
} else {
- validator = (BeanValidator<B>) cacheValidator;
+ validator = (NuitonValidator<B>) cacheValidator;
}
- validator.setBean(bean);
}
@After
@SuppressWarnings("unchecked")
public void tearDown() {
- validator.setBean(null);
}
@AfterClass
@@ -112,16 +112,22 @@
@SuppressWarnings("unchecked")
protected void assertFieldInError(String fieldName, String error, boolean required) {
- BeanValidatorField<B> field = validator.getField(fieldName);
- if (field != null && field.getErrors() != null) {
- for (String o : field.getErrors()) {
- if (o.equals(error)) {
- assertTrue("error " + error + " should not exist but was found.", required);
- return;
- }
- }
+
+ NuitonValidatorResult result = validator.validate(bean);
+
+ List<String> errorMessages = result.getErrorMessages(fieldName);
+
+ boolean errorFound = errorMessages.contains(fieldName);
+
+ if (required) {
+
+ // must have this error
+
+ assertTrue("error " + error + " should not exist but was found.", errorFound);
+ } else {
+
+ // must not have this error
+ assertFalse("error " + error + " should exist but was not found.", errorFound);
}
- // error was not found
- assertFalse("error " + error + " should exist but was not found.", required);
}
}
\ No newline at end of file
Modified: trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/AbstractValidatorBeanFieldValidatorTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/field/AbstractValidatorBeanFieldValidatorTest.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/AbstractValidatorBeanFieldValidatorTest.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,7 +22,7 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
/**
* Abstract class to test a specific validator for the {@link ValidatorBean}.
Modified: trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/CollectionFieldExpressionValidatorTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/field/CollectionFieldExpressionValidatorTest.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/CollectionFieldExpressionValidatorTest.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,10 +22,10 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
-import org.nuiton.validator.field.ValidatorBean.ValidatorBeanEntry;
import org.junit.Test;
+import org.nuiton.validator.xwork2.field.ValidatorBean.ValidatorBeanEntry;
import java.util.Arrays;
Modified: trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/CollectionUniqueKeyValidatorTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/field/CollectionUniqueKeyValidatorTest.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/CollectionUniqueKeyValidatorTest.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,9 +22,9 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
-import org.nuiton.validator.field.ValidatorBean.ValidatorBeanEntry;
+import org.nuiton.validator.xwork2.field.ValidatorBean.ValidatorBeanEntry;
import org.junit.Test;
import java.util.Arrays;
Modified: trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/ExistingDirectoryFieldValidatorTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/field/ExistingDirectoryFieldValidatorTest.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/ExistingDirectoryFieldValidatorTest.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,7 +22,7 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
import org.junit.Test;
Modified: trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/ExistingFileFieldValidatorTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/field/ExistingFileFieldValidatorTest.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/ExistingFileFieldValidatorTest.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,7 +22,7 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
import org.junit.Test;
Modified: trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/FieldExpressionBean.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/field/FieldExpressionBean.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/FieldExpressionBean.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,7 +22,7 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
Modified: trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/FieldExpressionWithParamsValidatorTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/field/FieldExpressionWithParamsValidatorTest.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/FieldExpressionWithParamsValidatorTest.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,7 +22,7 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
import org.junit.Test;
Modified: trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/NotExistingDirectoryFieldValidatorTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/field/NotExistingDirectoryFieldValidatorTest.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/NotExistingDirectoryFieldValidatorTest.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,7 +22,7 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
import org.junit.Test;
Modified: trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/NotExistingFileFieldValidatorTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/field/NotExistingFileFieldValidatorTest.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/NotExistingFileFieldValidatorTest.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,7 +22,7 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
import org.junit.Test;
@@ -31,7 +31,6 @@
/** @author tchemit <chemit(a)codelutin.com> */
public class NotExistingFileFieldValidatorTest extends AbstractValidatorBeanFieldValidatorTest {
-
@Test
@Override
public void testValidator() throws Exception {
Modified: trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/RequiredFileFieldValidatorTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/field/RequiredFileFieldValidatorTest.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/RequiredFileFieldValidatorTest.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,7 +22,7 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
import org.junit.Test;
Modified: trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/ValidatorBean.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/field/ValidatorBean.java 2011-01-12 14:31:01 UTC (rev 2010)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/field/ValidatorBean.java 2011-01-17 18:24:10 UTC (rev 2013)
@@ -22,7 +22,7 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.validator.field;
+package org.nuiton.validator.xwork2.field;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
Deleted: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/field/FieldExpressionBean-error-validation.xml
===================================================================
--- trunk/nuiton-validator/src/test/resources/org/nuiton/validator/field/FieldExpressionBean-error-validation.xml 2011-01-17 18:01:10 UTC (rev 2012)
+++ trunk/nuiton-validator/src/test/resources/org/nuiton/validator/field/FieldExpressionBean-error-validation.xml 2011-01-17 18:24:10 UTC (rev 2013)
@@ -1,123 +0,0 @@
-<!--
- #%L
- Nuiton Utils :: Nuiton Validator
-
- $Id$
- $HeadURL$
- %%
- Copyright (C) 2011 CodeLutin, Tony Chemit
- %%
- This program 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 3 of the
- License, or (at your option) any later version.
-
- This program 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 General Lesser Public License for more details.
-
- You should have received a copy of the GNU General Lesser Public
- License along with this program. If not, see
- <http://www.gnu.org/licenses/lgpl-3.0.html>.
- #L%
- -->
-<!DOCTYPE validators PUBLIC
- "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
- "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
-<validators>
-
-<field name="booleanValue">
- <field-validator type="fieldexpressionwithparams">
- <param name="booleanParams">boolean:true</param>
- <param name="expression"><![CDATA[ booleanValue == booleans.boolean]]>
- </param>
- <message>expression.boolean.not.equals##${booleans.boolean}</message>
- </field-validator>
- <field-validator type="fieldexpressionwithparams">
- <param name="booleanParams">boolean:false</param>
- <param name="expression"><![CDATA[ booleanValue == booleans.boolean]]>
- </param>
- <message>expression.boolean.not.equals##${booleans.boolean}</message>
- </field-validator>
- </field>
-
- <field name="shortValue">
- <field-validator type="fieldexpressionwithparams">
- <param name="shortParams">short:100</param>
- <param name="expression"><![CDATA[ shortValue < shorts.short]]>
- </param>
- <message>expression.too.big##${shorts.short}</message>
- </field-validator>
- <field-validator type="fieldexpressionwithparams">
- <param name="shortParams">short:100|short2:2000</param>
- <param name="expression"><![CDATA[ shortValue < shorts.short || shortValue < shorts.short2]]>
- </param>
- <message>expression.too.big##${shorts.short}##${shorts.short2}</message>
- </field-validator>
- </field>
-
- <field name="intValue">
- <field-validator type="fieldexpressionwithparams">
- <param name="intParams">int:100</param>
- <param name="expression"><![CDATA[ intValue < ints.int]]>
- </param>
- <message>expression.too.big##${ints.int}</message>
- </field-validator>
- <field-validator type="fieldexpressionwithparams">
- <param name="intParams">int:100|int2:2000</param>
- <param name="expression"><![CDATA[ intValue < ints.int || intValue < ints.int2]]>
- </param>
- <message>expression.too.big##${ints.int}##${ints.int2}</message>
- </field-validator>
- </field>
-
- <field name="longValue">
- <field-validator type="fieldexpressionwithparams">
- <param name="longParams">long:100</param>
- <param name="expression"><![CDATA[ longValue < longs.long]]>
- </param>
- <message>expression.too.big##${longs.long}</message>
- </field-validator>
- <field-validator type="fieldexpressionwithparams">
- <param name="longParams">long:100|long2:2000</param>
- <param name="expression"><![CDATA[ longValue < longs.long || longValue < longs.long2]]>
- </param>
- <message>expression.too.big##${longs.long}##${longs.long2}</message>
- </field-validator>
- </field>
-
- <field name="doubleValue">
- <field-validator type="fieldexpressionwithparams">
- <param name="doubleParams">double:100.0</param>
- <param name="expression"><![CDATA[ doubleValue < doubles.double]]>
- </param>
- <message>expression.too.big##${doubles.double}</message>
- </field-validator>
- <field-validator type="fieldexpressionwithparams">
- <param name="doubleParams">double:100.0|double2:2000.0</param>
- <param name="expression"><![CDATA[ doubleValue < doubles.double || doubleValue < doubles.double2]]>
- </param>
- <message>expression.too.big##${doubles.double}##${doubles.double2}</message>
- </field-validator>
- </field>
-
- <field name="stringValue">
- <field-validator type="fieldexpressionwithparams">
- <param name="stringParams">string:1000</param>
- <param name="expression"><![CDATA[ stringValue.equals(strings.string)]]>
- </param>
- <message>expression.stringNotValue##${strings.string}</message>
- </field-validator>
- <field-validator type="fieldexpressionwithparams">
- <param name="stringParams">string:1000|string2:3000</param>
- <param name="expression"><![CDATA[ stringValue.equals(strings.string) || stringValue.equals(strings.string2)]]>
- </param>
- <message>expression.stringNotValue##${strings.string}##${strings.string2}</message>
- </field-validator>
- </field>
-
-
-
-
-</validators>
\ No newline at end of file
Deleted: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/field/ValidatorBean-error-validation.xml
===================================================================
--- trunk/nuiton-validator/src/test/resources/org/nuiton/validator/field/ValidatorBean-error-validation.xml 2011-01-17 18:01:10 UTC (rev 2012)
+++ trunk/nuiton-validator/src/test/resources/org/nuiton/validator/field/ValidatorBean-error-validation.xml 2011-01-17 18:24:10 UTC (rev 2013)
@@ -1,179 +0,0 @@
-<!--
- #%L
- Nuiton Utils :: Nuiton Validator
-
- $Id$
- $HeadURL$
- %%
- Copyright (C) 2011 CodeLutin, Tony Chemit
- %%
- This program 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 3 of the
- License, or (at your option) any later version.
-
- This program 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 General Lesser Public License for more details.
-
- You should have received a copy of the GNU General Lesser Public
- License along with this program. If not, see
- <http://www.gnu.org/licenses/lgpl-3.0.html>.
- #L%
- -->
-<!DOCTYPE validators PUBLIC
- "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
- "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
-<validators>
-
- <field name="stringValue">
- <field-validator type="requiredstring" short-circuit="true">
- <message>stringValue.required</message>
- </field-validator>
- </field>
-
- <field name="existingFile">
- <field-validator type="requiredFile" short-circuit="true">
- <message>existingFile.required</message>
- </field-validator>
- <field-validator type="existingFile" short-circuit="true">
- <message>existingFile.not.exist</message>
- </field-validator>
- </field>
-
- <field name="notExistingFile">
- <field-validator type="requiredFile" short-circuit="true">
- <message>notExistingFile.required</message>
- </field-validator>
- <field-validator type="notExistingFile" short-circuit="true">
- <message>notExistingFile.exist</message>
- </field-validator>
- </field>
-
- <field name="existingDirectory">
- <field-validator type="requiredFile" short-circuit="true">
- <message>existingDirectory.required</message>
- </field-validator>
-
- <field-validator type="existingDirectory" short-circuit="true">
- <message>existingDirectory.not.exist</message>
- </field-validator>
- </field>
-
- <field name="notExistingDirectory">
- <field-validator type="requiredFile" short-circuit="true">
- <message>notExistingDirectory.required</message>
- </field-validator>
-
- <field-validator type="notExistingDirectory" short-circuit="true">
- <message>notExistingDirectory.exist</message>
- </field-validator>
- </field>
-
- <field name="entries">
-
- <field-validator type="collectionUniqueKey">
- <param name="keys">intValue</param>
- <message>collectionUniqueKey.one.failed</message>
- </field-validator>
- <field-validator type="collectionUniqueKey">
- <param name="keys">stringValue</param>
- <message>collectionUniqueKey.two.failed</message>
- </field-validator>
- <field-validator type="collectionUniqueKey">
- <param name="keys">intValue,stringValue</param>
- <message>collectionUniqueKey.three.failed</message>
- </field-validator>
- <field-validator type="collectionUniqueKey">
- <param name="keys">intValue,stringValue,stringValue2</param>
- <message>collectionUniqueKey.four.failed</message>
- </field-validator>
- <field-validator type="collectionUniqueKey">
- <param name="keys">stringValue</param>
- <param name="againstProperty">entry</param>
- <message>collectionUniqueKey.five.failed</message>
- </field-validator>
-
- <field-validator type="collectionFieldExpression">
- <param name="mode">AT_LEAST_ONE</param>
- <param name="expression"><![CDATA[ intValue == 0 && stringValue == "stringValue" ]]>
- </param>
- <message>collectionFieldExpression.atLeastOne</message>
- </field-validator>
- <field-validator type="collectionFieldExpression">
- <param name="mode">EXACTLY_ONE</param>
- <param name="expression"><![CDATA[ intValue == 0 && stringValue == "stringValue" ]]>
- </param>
- <message>collectionFieldExpression.exactlyOne</message>
- </field-validator>
- <field-validator type="collectionFieldExpression">
- <param name="mode">ALL</param>
- <param name="expression"><![CDATA[ intValue == 0 && stringValue == "stringValue" ]]>
- </param>
- <message>collectionFieldExpression.all</message>
- </field-validator>
- <field-validator type="collectionFieldExpression">
- <param name="mode">NONE</param>
- <param name="expression"><![CDATA[ intValue == 0 && stringValue == "stringValue" ]]>
- </param>
- <message>collectionFieldExpression.none</message>
- </field-validator>
-
- <!-- useContext -->
- <field-validator type="collectionFieldExpression">
- <param name="mode">AT_LEAST_ONE</param>
- <param name="useSensitiveContext">true</param>
- <param name="expression"><![CDATA[ size > 1 && previous != null && previous.intValue < current.intValue]]></param>
- <message>collectionFieldExpression.atLeastOne.useSensitiveContext</message>
- </field-validator>
- <field-validator type="collectionFieldExpression">
- <param name="mode">EXACTLY_ONE</param>
- <param name="useSensitiveContext">true</param>
- <param name="expression"><![CDATA[ size > 1 && previous != null && ( previous.intValue == 2 + current.intValue || current.intValue == 2 + previous.intValue) ]]></param>
- <message>collectionFieldExpression.exactlyOne.useSensitiveContext</message>
- </field-validator>
- <field-validator type="collectionFieldExpression">
- <param name="mode">ALL</param>
- <param name="useSensitiveContext">true</param>
- <param name="expression"><![CDATA[ size > 1 && (previous == null || previous.intValue < current.intValue)]]></param>
- <message>collectionFieldExpression.all.useSensitiveContext</message>
- </field-validator>
- <field-validator type="collectionFieldExpression">
- <param name="mode">NONE</param>
- <param name="useSensitiveContext">true</param>
- <param name="expression"><![CDATA[ size > 1 && previous != null && ( current.intValue == 2 + previous.intValue)]]></param>
- <message>collectionFieldExpression.none.useSensitiveContext</message>
- </field-validator>
-
- <!-- useFirst -->
- <field-validator type="collectionFieldExpression">
- <param name="mode">ALL</param>
- <param name="useSensitiveContext">true</param>
- <param name="expressionForFirst"><![CDATA[ current.intValue == 0]]></param>
- <param name="expression"><![CDATA[ previous == null || previous.intValue < current.intValue]]></param>
- <message>collectionFieldExpression.all.useFirst</message>
- </field-validator>
-
- <!-- useLast -->
- <field-validator type="collectionFieldExpression">
- <param name="mode">ALL</param>
- <param name="useSensitiveContext">true</param>
- <param name="expressionForLast"><![CDATA[ current.intValue > 0]]></param>
- <param name="expression"><![CDATA[ previous == null || previous.intValue < current.intValue]]></param>
- <message>collectionFieldExpression.all.useLast</message>
- </field-validator>
-
- <!-- useFirstAndLast -->
- <field-validator type="collectionFieldExpression">
- <param name="mode">ALL</param>
- <param name="useSensitiveContext">true</param>
- <param name="expressionForFirst"><![CDATA[ current.intValue == 0]]></param>
- <param name="expressionForLast"><![CDATA[ current.intValue > 0]]></param>
- <param name="expression"><![CDATA[ previous == null || previous.intValue < current.intValue]]></param>
- <message>collectionFieldExpression.all.useFirstAndLast</message>
- </field-validator>
-
- </field>
-
-</validators>
\ No newline at end of file
Copied: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/xwork2/field/FieldExpressionBean-error-validation.xml (from rev 2010, trunk/nuiton-validator/src/test/resources/org/nuiton/validator/field/FieldExpressionBean-error-validation.xml)
===================================================================
--- trunk/nuiton-validator/src/test/resources/org/nuiton/validator/xwork2/field/FieldExpressionBean-error-validation.xml (rev 0)
+++ trunk/nuiton-validator/src/test/resources/org/nuiton/validator/xwork2/field/FieldExpressionBean-error-validation.xml 2011-01-17 18:24:10 UTC (rev 2013)
@@ -0,0 +1,123 @@
+<!--
+ #%L
+ Nuiton Utils :: Nuiton Validator
+
+ $Id$
+ $HeadURL$
+ %%
+ Copyright (C) 2011 CodeLutin, Tony Chemit
+ %%
+ This program 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 3 of the
+ License, or (at your option) any later version.
+
+ This program 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 General Lesser Public License for more details.
+
+ You should have received a copy of the GNU General Lesser Public
+ License along with this program. If not, see
+ <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ #L%
+ -->
+<!DOCTYPE validators PUBLIC
+ "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
+ "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
+<validators>
+
+<field name="booleanValue">
+ <field-validator type="fieldexpressionwithparams">
+ <param name="booleanParams">boolean:true</param>
+ <param name="expression"><![CDATA[ booleanValue == booleans.boolean]]>
+ </param>
+ <message>expression.boolean.not.equals##${booleans.boolean}</message>
+ </field-validator>
+ <field-validator type="fieldexpressionwithparams">
+ <param name="booleanParams">boolean:false</param>
+ <param name="expression"><![CDATA[ booleanValue == booleans.boolean]]>
+ </param>
+ <message>expression.boolean.not.equals##${booleans.boolean}</message>
+ </field-validator>
+ </field>
+
+ <field name="shortValue">
+ <field-validator type="fieldexpressionwithparams">
+ <param name="shortParams">short:100</param>
+ <param name="expression"><![CDATA[ shortValue < shorts.short]]>
+ </param>
+ <message>expression.too.big##${shorts.short}</message>
+ </field-validator>
+ <field-validator type="fieldexpressionwithparams">
+ <param name="shortParams">short:100|short2:2000</param>
+ <param name="expression"><![CDATA[ shortValue < shorts.short || shortValue < shorts.short2]]>
+ </param>
+ <message>expression.too.big##${shorts.short}##${shorts.short2}</message>
+ </field-validator>
+ </field>
+
+ <field name="intValue">
+ <field-validator type="fieldexpressionwithparams">
+ <param name="intParams">int:100</param>
+ <param name="expression"><![CDATA[ intValue < ints.int]]>
+ </param>
+ <message>expression.too.big##${ints.int}</message>
+ </field-validator>
+ <field-validator type="fieldexpressionwithparams">
+ <param name="intParams">int:100|int2:2000</param>
+ <param name="expression"><![CDATA[ intValue < ints.int || intValue < ints.int2]]>
+ </param>
+ <message>expression.too.big##${ints.int}##${ints.int2}</message>
+ </field-validator>
+ </field>
+
+ <field name="longValue">
+ <field-validator type="fieldexpressionwithparams">
+ <param name="longParams">long:100</param>
+ <param name="expression"><![CDATA[ longValue < longs.long]]>
+ </param>
+ <message>expression.too.big##${longs.long}</message>
+ </field-validator>
+ <field-validator type="fieldexpressionwithparams">
+ <param name="longParams">long:100|long2:2000</param>
+ <param name="expression"><![CDATA[ longValue < longs.long || longValue < longs.long2]]>
+ </param>
+ <message>expression.too.big##${longs.long}##${longs.long2}</message>
+ </field-validator>
+ </field>
+
+ <field name="doubleValue">
+ <field-validator type="fieldexpressionwithparams">
+ <param name="doubleParams">double:100.0</param>
+ <param name="expression"><![CDATA[ doubleValue < doubles.double]]>
+ </param>
+ <message>expression.too.big##${doubles.double}</message>
+ </field-validator>
+ <field-validator type="fieldexpressionwithparams">
+ <param name="doubleParams">double:100.0|double2:2000.0</param>
+ <param name="expression"><![CDATA[ doubleValue < doubles.double || doubleValue < doubles.double2]]>
+ </param>
+ <message>expression.too.big##${doubles.double}##${doubles.double2}</message>
+ </field-validator>
+ </field>
+
+ <field name="stringValue">
+ <field-validator type="fieldexpressionwithparams">
+ <param name="stringParams">string:1000</param>
+ <param name="expression"><![CDATA[ stringValue.equals(strings.string)]]>
+ </param>
+ <message>expression.stringNotValue##${strings.string}</message>
+ </field-validator>
+ <field-validator type="fieldexpressionwithparams">
+ <param name="stringParams">string:1000|string2:3000</param>
+ <param name="expression"><![CDATA[ stringValue.equals(strings.string) || stringValue.equals(strings.string2)]]>
+ </param>
+ <message>expression.stringNotValue##${strings.string}##${strings.string2}</message>
+ </field-validator>
+ </field>
+
+
+
+
+</validators>
\ No newline at end of file
Property changes on: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/xwork2/field/FieldExpressionBean-error-validation.xml
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/xwork2/field/ValidatorBean-error-validation.xml (from rev 2010, trunk/nuiton-validator/src/test/resources/org/nuiton/validator/field/ValidatorBean-error-validation.xml)
===================================================================
--- trunk/nuiton-validator/src/test/resources/org/nuiton/validator/xwork2/field/ValidatorBean-error-validation.xml (rev 0)
+++ trunk/nuiton-validator/src/test/resources/org/nuiton/validator/xwork2/field/ValidatorBean-error-validation.xml 2011-01-17 18:24:10 UTC (rev 2013)
@@ -0,0 +1,179 @@
+<!--
+ #%L
+ Nuiton Utils :: Nuiton Validator
+
+ $Id$
+ $HeadURL$
+ %%
+ Copyright (C) 2011 CodeLutin, Tony Chemit
+ %%
+ This program 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 3 of the
+ License, or (at your option) any later version.
+
+ This program 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 General Lesser Public License for more details.
+
+ You should have received a copy of the GNU General Lesser Public
+ License along with this program. If not, see
+ <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ #L%
+ -->
+<!DOCTYPE validators PUBLIC
+ "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
+ "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
+<validators>
+
+ <field name="stringValue">
+ <field-validator type="requiredstring" short-circuit="true">
+ <message>stringValue.required</message>
+ </field-validator>
+ </field>
+
+ <field name="existingFile">
+ <field-validator type="requiredFile" short-circuit="true">
+ <message>existingFile.required</message>
+ </field-validator>
+ <field-validator type="existingFile" short-circuit="true">
+ <message>existingFile.not.exist</message>
+ </field-validator>
+ </field>
+
+ <field name="notExistingFile">
+ <field-validator type="requiredFile" short-circuit="true">
+ <message>notExistingFile.required</message>
+ </field-validator>
+ <field-validator type="notExistingFile" short-circuit="true">
+ <message>notExistingFile.exist</message>
+ </field-validator>
+ </field>
+
+ <field name="existingDirectory">
+ <field-validator type="requiredFile" short-circuit="true">
+ <message>existingDirectory.required</message>
+ </field-validator>
+
+ <field-validator type="existingDirectory" short-circuit="true">
+ <message>existingDirectory.not.exist</message>
+ </field-validator>
+ </field>
+
+ <field name="notExistingDirectory">
+ <field-validator type="requiredFile" short-circuit="true">
+ <message>notExistingDirectory.required</message>
+ </field-validator>
+
+ <field-validator type="notExistingDirectory" short-circuit="true">
+ <message>notExistingDirectory.exist</message>
+ </field-validator>
+ </field>
+
+ <field name="entries">
+
+ <field-validator type="collectionUniqueKey">
+ <param name="keys">intValue</param>
+ <message>collectionUniqueKey.one.failed</message>
+ </field-validator>
+ <field-validator type="collectionUniqueKey">
+ <param name="keys">stringValue</param>
+ <message>collectionUniqueKey.two.failed</message>
+ </field-validator>
+ <field-validator type="collectionUniqueKey">
+ <param name="keys">intValue,stringValue</param>
+ <message>collectionUniqueKey.three.failed</message>
+ </field-validator>
+ <field-validator type="collectionUniqueKey">
+ <param name="keys">intValue,stringValue,stringValue2</param>
+ <message>collectionUniqueKey.four.failed</message>
+ </field-validator>
+ <field-validator type="collectionUniqueKey">
+ <param name="keys">stringValue</param>
+ <param name="againstProperty">entry</param>
+ <message>collectionUniqueKey.five.failed</message>
+ </field-validator>
+
+ <field-validator type="collectionFieldExpression">
+ <param name="mode">AT_LEAST_ONE</param>
+ <param name="expression"><![CDATA[ intValue == 0 && stringValue == "stringValue" ]]>
+ </param>
+ <message>collectionFieldExpression.atLeastOne</message>
+ </field-validator>
+ <field-validator type="collectionFieldExpression">
+ <param name="mode">EXACTLY_ONE</param>
+ <param name="expression"><![CDATA[ intValue == 0 && stringValue == "stringValue" ]]>
+ </param>
+ <message>collectionFieldExpression.exactlyOne</message>
+ </field-validator>
+ <field-validator type="collectionFieldExpression">
+ <param name="mode">ALL</param>
+ <param name="expression"><![CDATA[ intValue == 0 && stringValue == "stringValue" ]]>
+ </param>
+ <message>collectionFieldExpression.all</message>
+ </field-validator>
+ <field-validator type="collectionFieldExpression">
+ <param name="mode">NONE</param>
+ <param name="expression"><![CDATA[ intValue == 0 && stringValue == "stringValue" ]]>
+ </param>
+ <message>collectionFieldExpression.none</message>
+ </field-validator>
+
+ <!-- useContext -->
+ <field-validator type="collectionFieldExpression">
+ <param name="mode">AT_LEAST_ONE</param>
+ <param name="useSensitiveContext">true</param>
+ <param name="expression"><![CDATA[ size > 1 && previous != null && previous.intValue < current.intValue]]></param>
+ <message>collectionFieldExpression.atLeastOne.useSensitiveContext</message>
+ </field-validator>
+ <field-validator type="collectionFieldExpression">
+ <param name="mode">EXACTLY_ONE</param>
+ <param name="useSensitiveContext">true</param>
+ <param name="expression"><![CDATA[ size > 1 && previous != null && ( previous.intValue == 2 + current.intValue || current.intValue == 2 + previous.intValue) ]]></param>
+ <message>collectionFieldExpression.exactlyOne.useSensitiveContext</message>
+ </field-validator>
+ <field-validator type="collectionFieldExpression">
+ <param name="mode">ALL</param>
+ <param name="useSensitiveContext">true</param>
+ <param name="expression"><![CDATA[ size > 1 && (previous == null || previous.intValue < current.intValue)]]></param>
+ <message>collectionFieldExpression.all.useSensitiveContext</message>
+ </field-validator>
+ <field-validator type="collectionFieldExpression">
+ <param name="mode">NONE</param>
+ <param name="useSensitiveContext">true</param>
+ <param name="expression"><![CDATA[ size > 1 && previous != null && ( current.intValue == 2 + previous.intValue)]]></param>
+ <message>collectionFieldExpression.none.useSensitiveContext</message>
+ </field-validator>
+
+ <!-- useFirst -->
+ <field-validator type="collectionFieldExpression">
+ <param name="mode">ALL</param>
+ <param name="useSensitiveContext">true</param>
+ <param name="expressionForFirst"><![CDATA[ current.intValue == 0]]></param>
+ <param name="expression"><![CDATA[ previous == null || previous.intValue < current.intValue]]></param>
+ <message>collectionFieldExpression.all.useFirst</message>
+ </field-validator>
+
+ <!-- useLast -->
+ <field-validator type="collectionFieldExpression">
+ <param name="mode">ALL</param>
+ <param name="useSensitiveContext">true</param>
+ <param name="expressionForLast"><![CDATA[ current.intValue > 0]]></param>
+ <param name="expression"><![CDATA[ previous == null || previous.intValue < current.intValue]]></param>
+ <message>collectionFieldExpression.all.useLast</message>
+ </field-validator>
+
+ <!-- useFirstAndLast -->
+ <field-validator type="collectionFieldExpression">
+ <param name="mode">ALL</param>
+ <param name="useSensitiveContext">true</param>
+ <param name="expressionForFirst"><![CDATA[ current.intValue == 0]]></param>
+ <param name="expressionForLast"><![CDATA[ current.intValue > 0]]></param>
+ <param name="expression"><![CDATA[ previous == null || previous.intValue < current.intValue]]></param>
+ <message>collectionFieldExpression.all.useFirstAndLast</message>
+ </field-validator>
+
+ </field>
+
+</validators>
\ No newline at end of file
Property changes on: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/xwork2/field/ValidatorBean-error-validation.xml
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/nuiton-validator/src/test/resources/validators.xml
===================================================================
--- trunk/nuiton-validator/src/test/resources/validators.xml 2011-01-17 18:01:10 UTC (rev 2012)
+++ trunk/nuiton-validator/src/test/resources/validators.xml 2011-01-17 18:24:10 UTC (rev 2013)
@@ -24,7 +24,6 @@
#L%
-->
-
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator Config 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-validator-config-1.0.dtd">
@@ -49,13 +48,13 @@
class="com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator"/>
<!-- default nuiton-validator validators -->
- <validator name="collectionFieldExpression" class="org.nuiton.validator.field.CollectionFieldExpressionValidator"/>
- <validator name="collectionUniqueKey" class="org.nuiton.validator.field.CollectionUniqueKeyValidator"/>
- <validator name="requiredFile" class="org.nuiton.validator.field.RequiredFileFieldValidator"/>
- <validator name="existingFile" class="org.nuiton.validator.field.ExistingFileFieldValidator"/>
- <validator name="notExistingFile" class="org.nuiton.validator.field.NotExistingFileFieldValidator"/>
- <validator name="existingDirectory" class="org.nuiton.validator.field.ExistingDirectoryFieldValidator"/>
- <validator name="notExistingDirectory" class="org.nuiton.validator.field.NotExistingDirectoryFieldValidator"/>
- <validator name="fieldexpressionwithparams" class="org.nuiton.validator.field.FieldExpressionWithParamsValidator"/>
+ <validator name="collectionFieldExpression" class="org.nuiton.validator.xwork2.field.CollectionFieldExpressionValidator"/>
+ <validator name="collectionUniqueKey" class="org.nuiton.validator.xwork2.field.CollectionUniqueKeyValidator"/>
+ <validator name="requiredFile" class="org.nuiton.validator.xwork2.field.RequiredFileFieldValidator"/>
+ <validator name="existingFile" class="org.nuiton.validator.xwork2.field.ExistingFileFieldValidator"/>
+ <validator name="notExistingFile" class="org.nuiton.validator.xwork2.field.NotExistingFileFieldValidator"/>
+ <validator name="existingDirectory" class="org.nuiton.validator.xwork2.field.ExistingDirectoryFieldValidator"/>
+ <validator name="notExistingDirectory" class="org.nuiton.validator.xwork2.field.NotExistingDirectoryFieldValidator"/>
+ <validator name="fieldexpressionwithparams" class="org.nuiton.validator.xwork2.field.FieldExpressionWithParamsValidator"/>
</validators>
\ No newline at end of file
1
0
r2012 - in trunk/nuiton-validator/src/test: java/org/nuiton/validator java/org/nuiton/validator/model java/org/nuiton/validator/xwork2 resources resources/org/nuiton/validator resources/org/nuiton/validator/model
by tchemit@users.nuiton.org 17 Jan '11
by tchemit@users.nuiton.org 17 Jan '11
17 Jan '11
Author: tchemit
Date: 2011-01-17 19:01:10 +0100 (Mon, 17 Jan 2011)
New Revision: 2012
Url: http://nuiton.org/repositories/revision/nuiton-utils/2012
Log:
add test for new validation api
Added:
trunk/nuiton-validator/src/test/java/org/nuiton/validator/NuitonValidatorFactoryTest.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/ValidatorTestHelper.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/model/
trunk/nuiton-validator/src/test/java/org/nuiton/validator/model/Person.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/model/Pet.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/model/Race.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/
trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/XWork2NuitonValidatorProviderTest.java
trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/XWork2NuitonValidatorTest.java
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/model/
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/model/Person-error-validation.xml
trunk/nuiton-validator/src/test/resources/org/nuiton/validator/model/Person-warning-validation.xml
Modified:
trunk/nuiton-validator/src/test/resources/validators.xml
Added: trunk/nuiton-validator/src/test/java/org/nuiton/validator/NuitonValidatorFactoryTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/NuitonValidatorFactoryTest.java (rev 0)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/NuitonValidatorFactoryTest.java 2011-01-17 18:01:10 UTC (rev 2012)
@@ -0,0 +1,60 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.nuiton.validator.model.Person;
+import org.nuiton.validator.xwork2.XWork2NuitonValidatorProvider;
+
+import java.util.Map;
+
+/**
+ * To test {@link NuitonValidatorFactory}.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.0
+ */
+public class NuitonValidatorFactoryTest {
+
+ @Test
+ public void testGetProviders() throws Exception {
+ Map<String, NuitonValidatorProvider> providers = NuitonValidatorFactory.getProviders();
+ Assert.assertNotNull(providers);
+ Assert.assertEquals(1, providers.size());
+ Assert.assertTrue(providers.containsKey(XWork2NuitonValidatorProvider.PROVIDER_NAME));
+ Assert.assertTrue(providers.get(XWork2NuitonValidatorProvider.PROVIDER_NAME) instanceof XWork2NuitonValidatorProvider);
+ }
+
+ @Test
+ public void testNewValidator() throws Exception {
+
+ NuitonValidator<Person> validator =
+ NuitonValidatorFactory.newValidator(Person.class);
+
+ ValidatorTestHelper.testPerson(validator);
+ }
+
+}
Property changes on: trunk/nuiton-validator/src/test/java/org/nuiton/validator/NuitonValidatorFactoryTest.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/nuiton-validator/src/test/java/org/nuiton/validator/ValidatorTestHelper.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/ValidatorTestHelper.java (rev 0)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/ValidatorTestHelper.java 2011-01-17 18:01:10 UTC (rev 2012)
@@ -0,0 +1,108 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator;
+
+import org.junit.Assert;
+import org.nuiton.validator.model.Person;
+import org.nuiton.validator.model.Pet;
+
+import java.util.List;
+
+/**
+ * Helper methods to test the validator api.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.0
+ */
+public class ValidatorTestHelper {
+ public static void testPerson(NuitonValidator<Person> validator) {
+ Assert.assertNotNull(validator);
+
+ Person person = new Person();
+
+ NuitonValidatorResult result;
+
+ result = validator.validate(person);
+
+ // two errors : no name, no firstname
+ // one warning : no pet
+ assertFieldMessages(result, NuitonValidatorScope.ERROR, Person.PROPERTY_FIRSTNAME, "person.firstname.required");
+ assertFieldMessages(result, NuitonValidatorScope.ERROR, Person.PROPERTY_NAME, "person.name.required");
+ assertFieldMessages(result, NuitonValidatorScope.WARNING, Person.PROPERTY_PET, "person.with.no.pet");
+
+ person.setFirstname("Joe");
+ result = validator.validate(person);
+
+ // one error : no name
+ // one warning : no pet
+ assertFieldMessages(result, NuitonValidatorScope.ERROR, Person.PROPERTY_FIRSTNAME);
+ assertFieldMessages(result, NuitonValidatorScope.ERROR, Person.PROPERTY_NAME, "person.name.required");
+ assertFieldMessages(result, NuitonValidatorScope.WARNING, Person.PROPERTY_PET, "person.with.no.pet");
+
+ person.setName("Black");
+ result = validator.validate(person);
+
+ // no error
+ // one warning : no pet
+ assertFieldMessages(result, NuitonValidatorScope.ERROR, Person.PROPERTY_FIRSTNAME);
+ assertFieldMessages(result, NuitonValidatorScope.ERROR, Person.PROPERTY_NAME);
+ assertFieldMessages(result, NuitonValidatorScope.WARNING, Person.PROPERTY_PET, "person.with.no.pet");
+
+ person.addPet(new Pet());
+ result = validator.validate(person);
+
+ // no error
+ // no warning
+ assertFieldMessages(result, NuitonValidatorScope.ERROR, Person.PROPERTY_FIRSTNAME);
+ assertFieldMessages(result, NuitonValidatorScope.ERROR, Person.PROPERTY_NAME);
+ assertFieldMessages(result, NuitonValidatorScope.WARNING, Person.PROPERTY_PET);
+
+ }
+
+ public static void assertFieldMessages(NuitonValidatorResult result,
+ NuitonValidatorScope scope,
+ String field,
+ String... expectedMessages) {
+
+ if (expectedMessages.length == 0) {
+
+ // no messages
+ boolean hasMessages = result.hasMessagesForScope(field, scope);
+ Assert.assertFalse(hasMessages);
+ } else {
+
+ // with messages
+ boolean hasMessages = result.hasMessagesForScope(field, scope);
+ Assert.assertTrue(hasMessages);
+
+ List<String> messages = result.getMessagesForScope(field, scope);
+ Assert.assertNotNull(hasMessages);
+ Assert.assertEquals(expectedMessages.length, messages.size());
+ for (String expectedMessage : expectedMessages) {
+ Assert.assertTrue(messages.contains(expectedMessage));
+ }
+ }
+ }
+}
Property changes on: trunk/nuiton-validator/src/test/java/org/nuiton/validator/ValidatorTestHelper.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/nuiton-validator/src/test/java/org/nuiton/validator/model/Person.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/model/Person.java (rev 0)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/model/Person.java 2011-01-17 18:01:10 UTC (rev 2012)
@@ -0,0 +1,94 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.model;
+
+import org.apache.commons.lang.builder.ToStringBuilder;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.0
+ */
+public class Person {
+
+ public static final String PROPERTY_NAME = "name";
+
+ public static final String PROPERTY_FIRSTNAME = "firstname";
+
+ public static final String PROPERTY_PET = "pet";
+
+ protected String name;
+
+ protected String firstname;
+
+ protected Collection<Pet> pet;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getFirstname() {
+ return firstname;
+ }
+
+ public void setFirstname(String firstname) {
+ this.firstname = firstname;
+ }
+
+ public Collection<Pet> getPet() {
+ return pet;
+ }
+
+ public void setPet(Collection<Pet> pet) {
+ this.pet = pet;
+ }
+
+ public void addPet(Pet pet) {
+ if (this.pet == null) {
+ this.pet = new ArrayList<Pet>();
+ }
+
+ pet.setPerson(this);
+
+ this.pet.add(pet);
+ }
+
+ @Override
+ public String toString() {
+ String result = new ToStringBuilder(this).
+ append(PROPERTY_NAME, name).
+ append(PROPERTY_FIRSTNAME, firstname).
+ toString();
+ return result;
+ }
+}
Property changes on: trunk/nuiton-validator/src/test/java/org/nuiton/validator/model/Person.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/nuiton-validator/src/test/java/org/nuiton/validator/model/Pet.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/model/Pet.java (rev 0)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/model/Pet.java 2011-01-17 18:01:10 UTC (rev 2012)
@@ -0,0 +1,99 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.model;
+
+import org.apache.commons.lang.builder.ToStringBuilder;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.0
+ */
+public class Pet {
+
+ public static final String PROPERTY_NAME = "name";
+
+ public static final String PROPERTY_TYPE = "type";
+
+ public static final String PROPERTY_PERSON = "person";
+
+ public static final String PROPERTY_RACE = "race";
+
+ protected String name;
+
+ protected String type;
+
+ protected Person person;
+
+ protected Race race;
+
+
+ public void setName(String name) {
+
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+
+ public String getType() {
+ return type;
+ }
+
+ public void setPerson(Person person) {
+ this.person = person;
+ }
+
+
+ public Person getPerson() {
+ return person;
+ }
+
+ public void setRace(Race race) {
+ this.race = race;
+ }
+
+ public Race getRace() {
+ return race;
+ }
+
+ @Override
+ public String toString() {
+ String result = new ToStringBuilder(this).
+ append(PROPERTY_NAME, this.name).
+ append(PROPERTY_TYPE, this.type).
+ append(PROPERTY_RACE, this.race).
+ toString();
+ return result;
+ }
+
+}
Property changes on: trunk/nuiton-validator/src/test/java/org/nuiton/validator/model/Pet.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/nuiton-validator/src/test/java/org/nuiton/validator/model/Race.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/model/Race.java (rev 0)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/model/Race.java 2011-01-17 18:01:10 UTC (rev 2012)
@@ -0,0 +1,56 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.model;
+
+import org.apache.commons.lang.builder.ToStringBuilder;
+
+/**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.0
+ */
+public class Race {
+
+ public static final String PROPERTY_NAME = "name";
+
+ protected String name;
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public String toString() {
+ String result = new ToStringBuilder(this).
+ append(PROPERTY_NAME, this.name).
+ toString();
+ return result;
+ }
+}
Property changes on: trunk/nuiton-validator/src/test/java/org/nuiton/validator/model/Race.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/XWork2NuitonValidatorProviderTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/XWork2NuitonValidatorProviderTest.java (rev 0)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/XWork2NuitonValidatorProviderTest.java 2011-01-17 18:01:10 UTC (rev 2012)
@@ -0,0 +1,83 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.xwork2;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.nuiton.validator.NuitonValidator;
+import org.nuiton.validator.NuitonValidatorModel;
+import org.nuiton.validator.NuitonValidatorScope;
+import org.nuiton.validator.model.Person;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * To test {@link XWork2NuitonValidatorProvider}.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.0
+ */
+public class XWork2NuitonValidatorProviderTest {
+
+ protected XWork2NuitonValidatorProvider provider;
+
+ @Before
+ public void setUp() {
+ provider = new XWork2NuitonValidatorProvider();
+ }
+
+ @Test
+ public void testGetModel() throws Exception {
+
+ NuitonValidatorModel<Person> model =
+ provider.getModel(Person.class, null);
+
+ Assert.assertNotNull(model);
+ Assert.assertNull(model.getContext());
+ Assert.assertEquals(Person.class, model.getType());
+ Set<NuitonValidatorScope> scopes = new HashSet<NuitonValidatorScope>(
+ Arrays.asList(NuitonValidatorScope.values()));
+ Assert.assertEquals(scopes, model.getScopes());
+ }
+
+ @Test
+ public void testNewValidator() throws Exception {
+
+
+ NuitonValidatorModel<Person> model =
+ provider.getModel(Person.class, null);
+
+ NuitonValidator<Person> validator = provider.newValidator(model);
+
+ Assert.assertNotNull(validator);
+ Assert.assertNotNull(validator.getModel());
+ Assert.assertEquals(model, validator.getModel());
+
+ }
+
+}
Property changes on: trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/XWork2NuitonValidatorProviderTest.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/XWork2NuitonValidatorTest.java
===================================================================
--- trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/XWork2NuitonValidatorTest.java (rev 0)
+++ trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/XWork2NuitonValidatorTest.java 2011-01-17 18:01:10 UTC (rev 2012)
@@ -0,0 +1,62 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Validator
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2011 CodeLutin
+ * %%
+ * This program 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 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program 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 General Lesser Public License for more details.
+ *
+ * You should have received a copy of the GNU General Lesser Public
+ * License along with this program. If not, see
+ * <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ * #L%
+ */
+package org.nuiton.validator.xwork2;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.nuiton.validator.NuitonValidator;
+import org.nuiton.validator.NuitonValidatorModel;
+import org.nuiton.validator.ValidatorTestHelper;
+import org.nuiton.validator.model.Person;
+
+/**
+ * To test {@link XWork2NuitonValidator}.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.0
+ */
+public class XWork2NuitonValidatorTest {
+
+ @Test
+ public void testNewValidator() throws Exception {
+
+ XWork2NuitonValidatorProvider provider =
+ new XWork2NuitonValidatorProvider();
+
+
+ NuitonValidatorModel<Person> model =
+ provider.getModel(Person.class, null);
+
+ NuitonValidator<Person> validator = provider.newValidator(model);
+
+ Assert.assertNotNull(validator);
+ Assert.assertNotNull(validator.getModel());
+ Assert.assertEquals(model, validator.getModel());
+
+ ValidatorTestHelper.testPerson(validator);
+
+ }
+
+}
Property changes on: trunk/nuiton-validator/src/test/java/org/nuiton/validator/xwork2/XWork2NuitonValidatorTest.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/model/Person-error-validation.xml
===================================================================
--- trunk/nuiton-validator/src/test/resources/org/nuiton/validator/model/Person-error-validation.xml (rev 0)
+++ trunk/nuiton-validator/src/test/resources/org/nuiton/validator/model/Person-error-validation.xml 2011-01-17 18:01:10 UTC (rev 2012)
@@ -0,0 +1,42 @@
+<!--
+ #%L
+ Nuiton Utils :: Nuiton Validator
+
+ $Id$
+ $HeadURL$
+ %%
+ Copyright (C) 2011 CodeLutin
+ %%
+ This program 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 3 of the
+ License, or (at your option) any later version.
+
+ This program 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 General Lesser Public License for more details.
+
+ You should have received a copy of the GNU General Lesser Public
+ License along with this program. If not, see
+ <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ #L%
+ -->
+<!DOCTYPE validators PUBLIC
+ "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
+ "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
+<validators>
+
+ <field name="name">
+ <field-validator type="requiredstring">
+ <message>person.name.required</message>
+ </field-validator>
+ </field>
+
+ <field name="firstname">
+ <field-validator type="requiredstring">
+ <message>person.firstname.required</message>
+ </field-validator>
+ </field>
+
+</validators>
\ No newline at end of file
Property changes on: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/model/Person-error-validation.xml
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/model/Person-warning-validation.xml
===================================================================
--- trunk/nuiton-validator/src/test/resources/org/nuiton/validator/model/Person-warning-validation.xml (rev 0)
+++ trunk/nuiton-validator/src/test/resources/org/nuiton/validator/model/Person-warning-validation.xml 2011-01-17 18:01:10 UTC (rev 2012)
@@ -0,0 +1,38 @@
+<!--
+ #%L
+ Nuiton Utils :: Nuiton Validator
+
+ $Id$
+ $HeadURL$
+ %%
+ Copyright (C) 2011 CodeLutin
+ %%
+ This program 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 3 of the
+ License, or (at your option) any later version.
+
+ This program 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 General Lesser Public License for more details.
+
+ You should have received a copy of the GNU General Lesser Public
+ License along with this program. If not, see
+ <http://www.gnu.org/licenses/lgpl-3.0.html>.
+ #L%
+ -->
+<!DOCTYPE validators PUBLIC
+ "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
+ "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
+<validators>
+
+ <field name="pet">
+ <field-validator type="fieldexpression">
+ <param name="expression">
+ <![CDATA[ pet!=null || !pet.empty]]></param>
+ <message>person.with.no.pet</message>
+ </field-validator>
+ </field>
+
+</validators>
\ No newline at end of file
Property changes on: trunk/nuiton-validator/src/test/resources/org/nuiton/validator/model/Person-warning-validation.xml
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/nuiton-validator/src/test/resources/validators.xml
===================================================================
--- trunk/nuiton-validator/src/test/resources/validators.xml 2011-01-17 18:00:50 UTC (rev 2011)
+++ trunk/nuiton-validator/src/test/resources/validators.xml 2011-01-17 18:01:10 UTC (rev 2012)
@@ -48,7 +48,7 @@
<validator name="conditionalvisitor"
class="com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator"/>
- <!-- jaxx validators -->
+ <!-- default nuiton-validator validators -->
<validator name="collectionFieldExpression" class="org.nuiton.validator.field.CollectionFieldExpressionValidator"/>
<validator name="collectionUniqueKey" class="org.nuiton.validator.field.CollectionUniqueKeyValidator"/>
<validator name="requiredFile" class="org.nuiton.validator.field.RequiredFileFieldValidator"/>
1
0