Hibernate SVN: r15913 - in core/branches/Branch_3_3: testsuite and 9 other directories.
by hibernate-commits@lists.jboss.org
Author: gbadner
Date: 2009-02-06 18:46:33 -0500 (Fri, 06 Feb 2009)
New Revision: 15913
Added:
core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/AbstractTransactSQLDialect.java
core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/SybaseASE15Dialect.java
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/dialect/unit/lockhint/SybaseASE15LockHintsTest.java
Modified:
core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/SQLServerDialect.java
core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/Sybase11Dialect.java
core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/SybaseAnywhereDialect.java
core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/SybaseDialect.java
core/branches/Branch_3_3/testsuite/pom.xml
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/connections/AggressiveReleaseTest.java
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/generated/TimestampGeneratedValuesWithCachingTest.java
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/hql/ASTParserLoadingTest.java
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/hql/HQLTest.java
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/interfaceproxy/InterfaceProxyTest.java
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/legacy/FooBarTest.java
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/legacy/SQLFunctionsTest.java
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/lob/SerializableTypeTest.java
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/mixed/MixedTest.java
core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/stats/StatsTest.java
Log:
HHH-3712 : Reorganize the Sybase dialect class hierarchy, add SybaseASE15Dialect, and mark SybaseDialect as deprecated
Added: core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/AbstractTransactSQLDialect.java
===================================================================
--- core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/AbstractTransactSQLDialect.java (rev 0)
+++ core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/AbstractTransactSQLDialect.java 2009-02-06 23:46:33 UTC (rev 15913)
@@ -0,0 +1,263 @@
+//$Id: $
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * 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 Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ *
+ */
+package org.hibernate.dialect;
+
+import java.sql.CallableStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
+import java.util.Map;
+import java.util.Iterator;
+
+import org.hibernate.Hibernate;
+import org.hibernate.LockMode;
+import org.hibernate.cfg.Environment;
+import org.hibernate.dialect.function.CharIndexFunction;
+import org.hibernate.dialect.function.NoArgSQLFunction;
+import org.hibernate.dialect.function.SQLFunctionTemplate;
+import org.hibernate.dialect.function.StandardSQLFunction;
+import org.hibernate.dialect.function.VarArgsSQLFunction;
+
+/**
+ * An abstract base class for Sybase and MS SQL Server dialects.
+ * @author Gavin King
+ */
+
+/* package-private */
+abstract class AbstractTransactSQLDialect extends Dialect {
+ public AbstractTransactSQLDialect() {
+ super();
+ registerColumnType( Types.BIT, "tinyint" ); //Sybase BIT type does not support null values
+ registerColumnType( Types.BIGINT, "numeric(19,0)" );
+ registerColumnType( Types.SMALLINT, "smallint" );
+ registerColumnType( Types.TINYINT, "tinyint" );
+ registerColumnType( Types.INTEGER, "int" );
+ registerColumnType( Types.CHAR, "char(1)" );
+ registerColumnType( Types.VARCHAR, "varchar($l)" );
+ registerColumnType( Types.FLOAT, "float" );
+ registerColumnType( Types.DOUBLE, "double precision" );
+ registerColumnType( Types.DATE, "datetime" );
+ registerColumnType( Types.TIME, "datetime" );
+ registerColumnType( Types.TIMESTAMP, "datetime" );
+ registerColumnType( Types.VARBINARY, "varbinary($l)" );
+ registerColumnType( Types.NUMERIC, "numeric($p,$s)" );
+ registerColumnType( Types.BLOB, "image" );
+ registerColumnType( Types.CLOB, "text" );
+
+ registerFunction( "ascii", new StandardSQLFunction("ascii", Hibernate.INTEGER) );
+ registerFunction( "char", new StandardSQLFunction("char", Hibernate.CHARACTER) );
+ registerFunction( "len", new StandardSQLFunction("len", Hibernate.LONG) );
+ registerFunction( "lower", new StandardSQLFunction("lower") );
+ registerFunction( "upper", new StandardSQLFunction("upper") );
+ registerFunction( "str", new StandardSQLFunction("str", Hibernate.STRING) );
+ registerFunction( "ltrim", new StandardSQLFunction("ltrim") );
+ registerFunction( "rtrim", new StandardSQLFunction("rtrim") );
+ registerFunction( "reverse", new StandardSQLFunction("reverse") );
+ registerFunction( "space", new StandardSQLFunction("space", Hibernate.STRING) );
+
+ registerFunction( "user", new NoArgSQLFunction("user", Hibernate.STRING) );
+
+ registerFunction( "current_timestamp", new NoArgSQLFunction("getdate", Hibernate.TIMESTAMP) );
+ registerFunction( "current_time", new NoArgSQLFunction("getdate", Hibernate.TIME) );
+ registerFunction( "current_date", new NoArgSQLFunction("getdate", Hibernate.DATE) );
+
+ registerFunction( "getdate", new NoArgSQLFunction("getdate", Hibernate.TIMESTAMP) );
+ registerFunction( "getutcdate", new NoArgSQLFunction("getutcdate", Hibernate.TIMESTAMP) );
+ registerFunction( "day", new StandardSQLFunction("day", Hibernate.INTEGER) );
+ registerFunction( "month", new StandardSQLFunction("month", Hibernate.INTEGER) );
+ registerFunction( "year", new StandardSQLFunction("year", Hibernate.INTEGER) );
+ registerFunction( "datename", new StandardSQLFunction("datename", Hibernate.STRING) );
+
+ registerFunction( "abs", new StandardSQLFunction("abs") );
+ registerFunction( "sign", new StandardSQLFunction("sign", Hibernate.INTEGER) );
+
+ registerFunction( "acos", new StandardSQLFunction("acos", Hibernate.DOUBLE) );
+ registerFunction( "asin", new StandardSQLFunction("asin", Hibernate.DOUBLE) );
+ registerFunction( "atan", new StandardSQLFunction("atan", Hibernate.DOUBLE) );
+ registerFunction( "cos", new StandardSQLFunction("cos", Hibernate.DOUBLE) );
+ registerFunction( "cot", new StandardSQLFunction("cot", Hibernate.DOUBLE) );
+ registerFunction( "exp", new StandardSQLFunction("exp", Hibernate.DOUBLE) );
+ registerFunction( "log", new StandardSQLFunction( "log", Hibernate.DOUBLE) );
+ registerFunction( "log10", new StandardSQLFunction("log10", Hibernate.DOUBLE) );
+ registerFunction( "sin", new StandardSQLFunction("sin", Hibernate.DOUBLE) );
+ registerFunction( "sqrt", new StandardSQLFunction("sqrt", Hibernate.DOUBLE) );
+ registerFunction( "tan", new StandardSQLFunction("tan", Hibernate.DOUBLE) );
+ registerFunction( "pi", new NoArgSQLFunction("pi", Hibernate.DOUBLE) );
+ registerFunction( "square", new StandardSQLFunction("square") );
+ registerFunction( "rand", new StandardSQLFunction("rand", Hibernate.FLOAT) );
+
+ registerFunction("radians", new StandardSQLFunction("radians", Hibernate.DOUBLE) );
+ registerFunction("degrees", new StandardSQLFunction("degrees", Hibernate.DOUBLE) );
+
+ registerFunction( "round", new StandardSQLFunction("round") );
+ registerFunction( "ceiling", new StandardSQLFunction("ceiling") );
+ registerFunction( "floor", new StandardSQLFunction("floor") );
+
+ registerFunction( "isnull", new StandardSQLFunction("isnull") );
+
+ registerFunction( "concat", new VarArgsSQLFunction( Hibernate.STRING, "(","+",")" ) );
+
+ registerFunction( "length", new StandardSQLFunction( "len", Hibernate.INTEGER ) );
+ registerFunction( "trim", new SQLFunctionTemplate( Hibernate.STRING, "ltrim(rtrim(?1))") );
+ registerFunction( "locate", new CharIndexFunction() );
+
+ getDefaultProperties().setProperty(Environment.STATEMENT_BATCH_SIZE, NO_BATCH);
+ }
+
+ public String getAddColumnString() {
+ return "add";
+ }
+ public String getNullColumnString() {
+ return " null";
+ }
+ public boolean qualifyIndexName() {
+ return false;
+ }
+
+ public String getForUpdateString() {
+ return "";
+ }
+
+ public boolean supportsIdentityColumns() {
+ return true;
+ }
+ public String getIdentitySelectString() {
+ return "select @@identity";
+ }
+ public String getIdentityColumnString() {
+ return "identity not null"; //starts with 1, implicitly
+ }
+
+ public boolean supportsInsertSelectIdentity() {
+ return true;
+ }
+
+ public String appendIdentitySelectToInsert(String insertSQL) {
+ return insertSQL + "\nselect @@identity";
+ }
+
+ public String appendLockHint(LockMode mode, String tableName) {
+ if ( mode.greaterThan( LockMode.READ ) ) {
+ return tableName + " holdlock";
+ }
+ else {
+ return tableName;
+ }
+ }
+
+ public String applyLocksToSql(String sql, Map aliasedLockModes, Map keyColumnNames) {
+ Iterator itr = aliasedLockModes.entrySet().iterator();
+ StringBuffer buffer = new StringBuffer( sql );
+ int correction = 0;
+ while ( itr.hasNext() ) {
+ final Map.Entry entry = ( Map.Entry ) itr.next();
+ final LockMode lockMode = ( LockMode ) entry.getValue();
+ if ( lockMode.greaterThan( LockMode.READ ) ) {
+ final String alias = ( String ) entry.getKey();
+ int start = -1, end = -1;
+ if ( sql.endsWith( " " + alias ) ) {
+ start = ( sql.length() - alias.length() ) + correction;
+ end = start + alias.length();
+ }
+ else {
+ int position = sql.indexOf( " " + alias + " " );
+ if ( position <= -1 ) {
+ position = sql.indexOf( " " + alias + "," );
+ }
+ if ( position > -1 ) {
+ start = position + correction + 1;
+ end = start + alias.length();
+ }
+ }
+
+ if ( start > -1 ) {
+ final String lockHint = appendLockHint( lockMode, alias );
+ buffer.replace( start, end, lockHint );
+ correction += ( lockHint.length() - alias.length() );
+ }
+ }
+ }
+ return buffer.toString();
+ }
+
+ public int registerResultSetOutParameter(CallableStatement statement, int col) throws SQLException {
+ return col; // sql server just returns automatically
+ }
+
+ public ResultSet getResultSet(CallableStatement ps) throws SQLException {
+ boolean isResultSet = ps.execute();
+// This assumes you will want to ignore any update counts
+ while ( !isResultSet && ps.getUpdateCount() != -1 ) {
+ isResultSet = ps.getMoreResults();
+ }
+// You may still have other ResultSets or update counts left to process here
+// but you can't do it now or the ResultSet you just got will be closed
+ return ps.getResultSet();
+ }
+
+ public boolean supportsCurrentTimestampSelection() {
+ return true;
+ }
+
+ public boolean isCurrentTimestampSelectStringCallable() {
+ return false;
+ }
+
+ public String getCurrentTimestampSelectString() {
+ return "select getdate()";
+ }
+
+ public boolean supportsTemporaryTables() {
+ return true;
+ }
+
+ public String generateTemporaryTableName(String baseTableName) {
+ return "#" + baseTableName;
+ }
+
+ public boolean dropTemporaryTableAfterUse() {
+ return true; // sql-server, at least needed this dropped after use; strange!
+ }
+
+
+ // Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+ public boolean supportsEmptyInList() {
+ return false;
+ }
+
+ public boolean supportsExistsInSelect() {
+ return false;
+ }
+
+ public boolean doesReadCommittedCauseWritersToBlockReaders() {
+ return true;
+ }
+
+ public boolean doesRepeatableReadCauseReadersToBlockWriters() {
+ return true;
+ }
+}
Modified: core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/SQLServerDialect.java
===================================================================
--- core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/SQLServerDialect.java 2009-02-06 23:10:40 UTC (rev 15912)
+++ core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/SQLServerDialect.java 2009-02-06 23:46:33 UTC (rev 15913)
@@ -43,8 +43,12 @@
registerColumnType( Types.VARBINARY, "image" );
registerColumnType( Types.VARBINARY, 8000, "varbinary($l)" );
+ registerFunction( "second", new SQLFunctionTemplate( Hibernate.INTEGER, "datepart(second, ?1)" ) );
+ registerFunction( "minute", new SQLFunctionTemplate( Hibernate.INTEGER, "datepart(minute, ?1)" ) );
+ registerFunction( "hour", new SQLFunctionTemplate( Hibernate.INTEGER, "datepart(hour, ?1)" ) );
registerFunction( "locate", new StandardSQLFunction( "charindex", Hibernate.INTEGER ) );
+ registerFunction( "extract", new SQLFunctionTemplate( Hibernate.INTEGER, "datepart(?1, ?3)" ) );
registerFunction( "mod", new SQLFunctionTemplate( Hibernate.INTEGER, "?1 % ?2" ) );
registerFunction( "bit_length", new SQLFunctionTemplate( Hibernate.INTEGER, "datalength(?1) * 8" ) );
@@ -134,10 +138,6 @@
return false;
}
- public boolean supportsCascadeDelete() {
- return true;
- }
-
public boolean supportsCircularCascadeDeleteConstraints() {
// SQL Server (at least up through 2005) does not support defining
// cascade delete constraints which can circel back to the mutating
@@ -145,10 +145,6 @@
return false;
}
- public boolean supportsExpectedLobUsagePattern() {
- return true;
- }
-
public boolean supportsLobValueChangePropogation() {
// note: at least my local SQL Server 2005 Express shows this not working...
return false;
Modified: core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/Sybase11Dialect.java
===================================================================
--- core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/Sybase11Dialect.java 2009-02-06 23:10:40 UTC (rev 15912)
+++ core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/Sybase11Dialect.java 2009-02-06 23:46:33 UTC (rev 15913)
@@ -31,7 +31,7 @@
* A SQL dialect suitable for use with Sybase 11.9.2 (specifically: avoids ANSI JOIN syntax)
* @author Colm O' Flaherty
*/
-public class Sybase11Dialect extends SybaseDialect {
+public class Sybase11Dialect extends AbstractTransactSQLDialect {
public Sybase11Dialect() {
super();
}
Added: core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/SybaseASE15Dialect.java
===================================================================
--- core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/SybaseASE15Dialect.java (rev 0)
+++ core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/SybaseASE15Dialect.java 2009-02-06 23:46:33 UTC (rev 15913)
@@ -0,0 +1,67 @@
+//$Id $
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * 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 Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ *
+ */
+package org.hibernate.dialect;
+
+import java.sql.CallableStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Types;
+import java.util.Map;
+import java.util.Iterator;
+
+import org.hibernate.Hibernate;
+import org.hibernate.LockMode;
+import org.hibernate.cfg.Environment;
+import org.hibernate.dialect.function.CharIndexFunction;
+import org.hibernate.dialect.function.NoArgSQLFunction;
+import org.hibernate.dialect.function.SQLFunctionTemplate;
+import org.hibernate.dialect.function.StandardSQLFunction;
+import org.hibernate.dialect.function.VarArgsSQLFunction;
+
+/**
+ * An SQL dialect compatible with Sybase and MS SQL Server.
+ * @author Gavin King
+ */
+
+public class SybaseASE15Dialect extends AbstractTransactSQLDialect {
+ public SybaseASE15Dialect() {
+ super();
+ registerFunction( "second", new SQLFunctionTemplate(Hibernate.INTEGER, "datepart(second, ?1)") );
+ registerFunction( "minute", new SQLFunctionTemplate(Hibernate.INTEGER, "datepart(minute, ?1)") );
+ registerFunction( "hour", new SQLFunctionTemplate(Hibernate.INTEGER, "datepart(hour, ?1)") );
+ registerFunction( "extract", new SQLFunctionTemplate( Hibernate.INTEGER, "datepart(?1, ?3)" ) );
+ }
+
+ // Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+ public boolean supportsCascadeDelete() {
+ return false;
+ }
+
+ public boolean supportsExpectedLobUsagePattern() {
+ return false;
+ }
+}
Modified: core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/SybaseAnywhereDialect.java
===================================================================
--- core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/SybaseAnywhereDialect.java 2009-02-06 23:10:40 UTC (rev 15912)
+++ core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/SybaseAnywhereDialect.java 2009-02-06 23:46:33 UTC (rev 15913)
@@ -30,7 +30,7 @@
* (Tested on ASA 8.x)
* @author ?
*/
-public class SybaseAnywhereDialect extends SybaseDialect {
+public class SybaseAnywhereDialect extends AbstractTransactSQLDialect {
/**
* Sybase Anywhere syntax would require a "DEFAULT" for each column specified,
Modified: core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/SybaseDialect.java
===================================================================
--- core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/SybaseDialect.java 2009-02-06 23:10:40 UTC (rev 15912)
+++ core/branches/Branch_3_3/core/src/main/java/org/hibernate/dialect/SybaseDialect.java 2009-02-06 23:46:33 UTC (rev 15913)
@@ -1,3 +1,4 @@
+//$Id $
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
@@ -24,253 +25,16 @@
*/
package org.hibernate.dialect;
-import java.sql.CallableStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Types;
-import java.util.Map;
-import java.util.Iterator;
-
-import org.hibernate.Hibernate;
-import org.hibernate.LockMode;
-import org.hibernate.cfg.Environment;
-import org.hibernate.dialect.function.CharIndexFunction;
-import org.hibernate.dialect.function.NoArgSQLFunction;
-import org.hibernate.dialect.function.SQLFunctionTemplate;
-import org.hibernate.dialect.function.StandardSQLFunction;
-import org.hibernate.dialect.function.VarArgsSQLFunction;
-
/**
- * An SQL dialect compatible with Sybase and MS SQL Server.
- * @author Gavin King
+ * SybaseDialect is being deprecated.
+ *
+ * AbstractTransactSQLDialect should be used as a base
+ * class for Sybase and MS SQL Server dialects.
+ *
+ * @author Gail Badner
+ * @deprecated SybaseASE15Dialect or SQLServerDialect should be
+ * used instead.
*/
-public class SybaseDialect extends Dialect {
- public SybaseDialect() {
- super();
- registerColumnType( Types.BIT, "tinyint" ); //Sybase BIT type does not support null values
- registerColumnType( Types.BIGINT, "numeric(19,0)" );
- registerColumnType( Types.SMALLINT, "smallint" );
- registerColumnType( Types.TINYINT, "tinyint" );
- registerColumnType( Types.INTEGER, "int" );
- registerColumnType( Types.CHAR, "char(1)" );
- registerColumnType( Types.VARCHAR, "varchar($l)" );
- registerColumnType( Types.FLOAT, "float" );
- registerColumnType( Types.DOUBLE, "double precision" );
- registerColumnType( Types.DATE, "datetime" );
- registerColumnType( Types.TIME, "datetime" );
- registerColumnType( Types.TIMESTAMP, "datetime" );
- registerColumnType( Types.VARBINARY, "varbinary($l)" );
- registerColumnType( Types.NUMERIC, "numeric($p,$s)" );
- registerColumnType( Types.BLOB, "image" );
- registerColumnType( Types.CLOB, "text" );
-
- registerFunction( "ascii", new StandardSQLFunction("ascii", Hibernate.INTEGER) );
- registerFunction( "char", new StandardSQLFunction("char", Hibernate.CHARACTER) );
- registerFunction( "len", new StandardSQLFunction("len", Hibernate.LONG) );
- registerFunction( "lower", new StandardSQLFunction("lower") );
- registerFunction( "upper", new StandardSQLFunction("upper") );
- registerFunction( "str", new StandardSQLFunction("str", Hibernate.STRING) );
- registerFunction( "ltrim", new StandardSQLFunction("ltrim") );
- registerFunction( "rtrim", new StandardSQLFunction("rtrim") );
- registerFunction( "reverse", new StandardSQLFunction("reverse") );
- registerFunction( "space", new StandardSQLFunction("space", Hibernate.STRING) );
-
- registerFunction( "user", new NoArgSQLFunction("user", Hibernate.STRING) );
-
- registerFunction( "current_timestamp", new NoArgSQLFunction("getdate", Hibernate.TIMESTAMP) );
- registerFunction( "current_time", new NoArgSQLFunction("getdate", Hibernate.TIME) );
- registerFunction( "current_date", new NoArgSQLFunction("getdate", Hibernate.DATE) );
-
- registerFunction( "getdate", new NoArgSQLFunction("getdate", Hibernate.TIMESTAMP) );
- registerFunction( "getutcdate", new NoArgSQLFunction("getutcdate", Hibernate.TIMESTAMP) );
- registerFunction( "day", new StandardSQLFunction("day", Hibernate.INTEGER) );
- registerFunction( "month", new StandardSQLFunction("month", Hibernate.INTEGER) );
- registerFunction( "year", new StandardSQLFunction("year", Hibernate.INTEGER) );
- registerFunction( "datename", new StandardSQLFunction("datename", Hibernate.STRING) );
- registerFunction( "second", new SQLFunctionTemplate(Hibernate.INTEGER, "datepart(second, ?1)") );
- registerFunction( "minute", new SQLFunctionTemplate(Hibernate.INTEGER, "datepart(minute, ?1)") );
- registerFunction( "hour", new SQLFunctionTemplate(Hibernate.INTEGER, "datepart(hour, ?1)") );
- registerFunction( "extract", new SQLFunctionTemplate( Hibernate.INTEGER, "datepart(?1, ?3)" ) );
-
- registerFunction( "abs", new StandardSQLFunction("abs") );
- registerFunction( "sign", new StandardSQLFunction("sign", Hibernate.INTEGER) );
-
- registerFunction( "acos", new StandardSQLFunction("acos", Hibernate.DOUBLE) );
- registerFunction( "asin", new StandardSQLFunction("asin", Hibernate.DOUBLE) );
- registerFunction( "atan", new StandardSQLFunction("atan", Hibernate.DOUBLE) );
- registerFunction( "cos", new StandardSQLFunction("cos", Hibernate.DOUBLE) );
- registerFunction( "cot", new StandardSQLFunction("cot", Hibernate.DOUBLE) );
- registerFunction( "exp", new StandardSQLFunction("exp", Hibernate.DOUBLE) );
- registerFunction( "log", new StandardSQLFunction( "log", Hibernate.DOUBLE) );
- registerFunction( "log10", new StandardSQLFunction("log10", Hibernate.DOUBLE) );
- registerFunction( "sin", new StandardSQLFunction("sin", Hibernate.DOUBLE) );
- registerFunction( "sqrt", new StandardSQLFunction("sqrt", Hibernate.DOUBLE) );
- registerFunction( "tan", new StandardSQLFunction("tan", Hibernate.DOUBLE) );
- registerFunction( "pi", new NoArgSQLFunction("pi", Hibernate.DOUBLE) );
- registerFunction( "square", new StandardSQLFunction("square") );
- registerFunction( "rand", new StandardSQLFunction("rand", Hibernate.FLOAT) );
-
- registerFunction("radians", new StandardSQLFunction("radians", Hibernate.DOUBLE) );
- registerFunction("degrees", new StandardSQLFunction("degrees", Hibernate.DOUBLE) );
-
- registerFunction( "round", new StandardSQLFunction("round") );
- registerFunction( "ceiling", new StandardSQLFunction("ceiling") );
- registerFunction( "floor", new StandardSQLFunction("floor") );
-
- registerFunction( "isnull", new StandardSQLFunction("isnull") );
-
- registerFunction( "concat", new VarArgsSQLFunction( Hibernate.STRING, "(","+",")" ) );
-
- registerFunction( "length", new StandardSQLFunction( "len", Hibernate.INTEGER ) );
- registerFunction( "trim", new SQLFunctionTemplate( Hibernate.STRING, "ltrim(rtrim(?1))") );
- registerFunction( "locate", new CharIndexFunction() );
-
- registerFunction( "mod", new SQLFunctionTemplate( Hibernate.INTEGER, "?1 % ?2" ) );
- registerFunction( "bit_length", new SQLFunctionTemplate( Hibernate.INTEGER, "datalength(?1) * 8" ) );
-
- getDefaultProperties().setProperty(Environment.STATEMENT_BATCH_SIZE, NO_BATCH);
- }
-
- public String getAddColumnString() {
- return "add";
- }
- public String getNullColumnString() {
- return " null";
- }
- public boolean qualifyIndexName() {
- return false;
- }
-
- public String getForUpdateString() {
- return "";
- }
-
- public boolean supportsIdentityColumns() {
- return true;
- }
- public String getIdentitySelectString() {
- return "select @@identity";
- }
- public String getIdentityColumnString() {
- return "identity not null"; //starts with 1, implicitly
- }
-
- public boolean supportsInsertSelectIdentity() {
- return true;
- }
-
- public String appendIdentitySelectToInsert(String insertSQL) {
- return insertSQL + "\nselect @@identity";
- }
-
- public String appendLockHint(LockMode mode, String tableName) {
- if ( mode.greaterThan( LockMode.READ ) ) {
- return tableName + " holdlock";
- }
- else {
- return tableName;
- }
- }
-
- public String applyLocksToSql(String sql, Map aliasedLockModes, Map keyColumnNames) {
- Iterator itr = aliasedLockModes.entrySet().iterator();
- StringBuffer buffer = new StringBuffer( sql );
- int correction = 0;
- while ( itr.hasNext() ) {
- final Map.Entry entry = ( Map.Entry ) itr.next();
- final LockMode lockMode = ( LockMode ) entry.getValue();
- if ( lockMode.greaterThan( LockMode.READ ) ) {
- final String alias = ( String ) entry.getKey();
- int start = -1, end = -1;
- if ( sql.endsWith( " " + alias ) ) {
- start = ( sql.length() - alias.length() ) + correction;
- end = start + alias.length();
- }
- else {
- int position = sql.indexOf( " " + alias + " " );
- if ( position <= -1 ) {
- position = sql.indexOf( " " + alias + "," );
- }
- if ( position > -1 ) {
- start = position + correction + 1;
- end = start + alias.length();
- }
- }
-
- if ( start > -1 ) {
- final String lockHint = appendLockHint( lockMode, alias );
- buffer.replace( start, end, lockHint );
- correction += ( lockHint.length() - alias.length() );
- }
- }
- }
- return buffer.toString();
- }
-
- public int registerResultSetOutParameter(CallableStatement statement, int col) throws SQLException {
- return col; // sql server just returns automatically
- }
-
- public ResultSet getResultSet(CallableStatement ps) throws SQLException {
- boolean isResultSet = ps.execute();
-// This assumes you will want to ignore any update counts
- while ( !isResultSet && ps.getUpdateCount() != -1 ) {
- isResultSet = ps.getMoreResults();
- }
-// You may still have other ResultSets or update counts left to process here
-// but you can't do it now or the ResultSet you just got will be closed
- return ps.getResultSet();
- }
-
- public boolean supportsCurrentTimestampSelection() {
- return true;
- }
-
- public boolean isCurrentTimestampSelectStringCallable() {
- return false;
- }
-
- public String getCurrentTimestampSelectString() {
- return "select getdate()";
- }
-
- public boolean supportsTemporaryTables() {
- return true;
- }
-
- public String generateTemporaryTableName(String baseTableName) {
- return "#" + baseTableName;
- }
-
- public boolean dropTemporaryTableAfterUse() {
- return true; // sql-server, at least needed this dropped after use; strange!
- }
-
-
- // Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- public boolean supportsCascadeDelete() {
- return false;
- }
-
- public boolean supportsExpectedLobUsagePattern() {
- return false;
- }
-
- public boolean supportsEmptyInList() {
- return false;
- }
-
- public boolean supportsExistsInSelect() {
- return false;
- }
-
- public boolean doesReadCommittedCauseWritersToBlockReaders() {
- return true;
- }
-
- public boolean doesRepeatableReadCauseReadersToBlockWriters() {
- return true;
- }
+public class SybaseDialect extends AbstractTransactSQLDialect {
}
Modified: core/branches/Branch_3_3/testsuite/pom.xml
===================================================================
--- core/branches/Branch_3_3/testsuite/pom.xml 2009-02-06 23:10:40 UTC (rev 15912)
+++ core/branches/Branch_3_3/testsuite/pom.xml 2009-02-06 23:46:33 UTC (rev 15913)
@@ -283,6 +283,25 @@
</properties>
</profile>
+ <profile>
+ <id>sybase15</id>
+ <dependencies>
+ <dependency>
+ <groupId>com.sybase</groupId>
+ <artifactId>jconnect</artifactId>
+ <version>6.0.5</version>
+ </dependency>
+ </dependencies>
+ <properties>
+ <db.dialect>org.hibernate.dialect.SybaseASE15Dialect</db.dialect>
+ <jdbc.driver>com.sybase.jdbc3.jdbc.SybDriver</jdbc.driver>
+ <jdbc.url>jdbc:sybase:Tds:dev77.qa.atl2.redhat.com:5000/hibernate</jdbc.url>
+ <jdbc.user>hibernate</jdbc.user>
+ <jdbc.pass>hibernate</jdbc.pass>
+ <jdbc.isolation />
+ </properties>
+ </profile>
+
<!-- The SQLServer2005 (jTDS) test envionment -->
<profile>
<id>sqlserver-jtds</id>
Modified: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/connections/AggressiveReleaseTest.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/connections/AggressiveReleaseTest.java 2009-02-06 23:10:40 UTC (rev 15912)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/connections/AggressiveReleaseTest.java 2009-02-06 23:46:33 UTC (rev 15913)
@@ -107,7 +107,7 @@
// expected behavior
}
- // getting the first row only because Sybase throws NullPointerException
+ // getting the first row only because SybaseASE15Dialect throws NullPointerException
// if data is not read before closing the ResultSet
sr.next();
Added: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/dialect/unit/lockhint/SybaseASE15LockHintsTest.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/dialect/unit/lockhint/SybaseASE15LockHintsTest.java (rev 0)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/dialect/unit/lockhint/SybaseASE15LockHintsTest.java 2009-02-06 23:46:33 UTC (rev 15913)
@@ -0,0 +1,56 @@
+//$Id $
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2009, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * 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 Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ *
+ */
+package org.hibernate.test.dialect.unit.lockhint;
+
+import junit.framework.TestSuite;
+
+import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.SybaseASE15Dialect;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Gail Badner
+ */
+public class SybaseASE15LockHintsTest extends AbstractLockHintTest {
+ public static final Dialect DIALECT = new SybaseASE15Dialect();
+
+ public SybaseASE15LockHintsTest(String string) {
+ super( string );
+ }
+
+ protected String getLockHintUsed() {
+ return "holdlock";
+ }
+
+ protected Dialect getDialectUnderTest() {
+ return DIALECT;
+ }
+
+ public static TestSuite suite() {
+ return new TestSuite( SybaseASE15LockHintsTest.class );
+ }
+}
Modified: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/generated/TimestampGeneratedValuesWithCachingTest.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/generated/TimestampGeneratedValuesWithCachingTest.java 2009-02-06 23:10:40 UTC (rev 15912)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/generated/TimestampGeneratedValuesWithCachingTest.java 2009-02-06 23:46:33 UTC (rev 15913)
@@ -5,6 +5,10 @@
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.SybaseDialect;
+import org.hibernate.dialect.Sybase11Dialect;
+import org.hibernate.dialect.SybaseAnywhereDialect;
+import org.hibernate.dialect.SybaseASE15Dialect;
+import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
/**
@@ -25,7 +29,9 @@
public boolean appliesTo(Dialect dialect) {
// this test is specific to Sybase/SQLServer as it is testing support
// for their TIMESTAMP datatype...
- return ( dialect instanceof SybaseDialect );
+ return ( dialect instanceof SybaseDialect || dialect instanceof Sybase11Dialect ||
+ dialect instanceof SybaseAnywhereDialect || dialect instanceof SybaseASE15Dialect ||
+ dialect instanceof SQLServerDialect);
}
public static Test suite() {
Modified: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/hql/ASTParserLoadingTest.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/hql/ASTParserLoadingTest.java 2009-02-06 23:10:40 UTC (rev 15912)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/hql/ASTParserLoadingTest.java 2009-02-06 23:46:33 UTC (rev 15913)
@@ -31,6 +31,9 @@
import org.hibernate.dialect.PostgreSQLDialect;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.dialect.SybaseDialect;
+import org.hibernate.dialect.Sybase11Dialect;
+import org.hibernate.dialect.SybaseASE15Dialect;
+import org.hibernate.dialect.SybaseAnywhereDialect;
import org.hibernate.dialect.Oracle8iDialect;
import org.hibernate.hql.ast.ASTQueryTranslatorFactory;
import org.hibernate.junit.functional.FunctionalTestCase;
@@ -1221,7 +1224,7 @@
if ( getDialect() instanceof DB2Dialect ) {
assertTrue( str.startsWith("1.234") );
}
- else if ( getDialect() instanceof SybaseDialect ) {
+ else if ( getDialect() instanceof SybaseDialect || getDialect() instanceof Sybase11Dialect || getDialect() instanceof SybaseASE15Dialect || getDialect() instanceof SybaseAnywhereDialect || getDialect() instanceof SQLServerDialect ) {
// str(val) on sybase assumes a default of 10 characters with no decimal point or decimal values
// str(val) on sybase result is right-justified
assertEquals( str.length(), 10 );
@@ -1233,7 +1236,7 @@
else {
assertTrue( str.startsWith("123.4") );
}
- if ( ! ( getDialect() instanceof SybaseDialect ) ) {
+ if ( ! ( getDialect() instanceof SybaseDialect ) && ! ( getDialect() instanceof Sybase11Dialect ) && ! ( getDialect() instanceof SybaseASE15Dialect ) && ! ( getDialect() instanceof SybaseAnywhereDialect ) && ! ( getDialect() instanceof SQLServerDialect ) ) {
// In TransactSQL (the variant spoken by Sybase and SQLServer), the str() function
// is explicitly intended for numeric values only...
String dateStr1 = (String) session.createQuery("select str(current_date) from Animal").uniqueResult();
Modified: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/hql/HQLTest.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/hql/HQLTest.java 2009-02-06 23:10:40 UTC (rev 15912)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/hql/HQLTest.java 2009-02-06 23:46:33 UTC (rev 15913)
@@ -20,7 +20,11 @@
import org.hibernate.dialect.MySQLDialect;
import org.hibernate.dialect.Oracle9Dialect;
import org.hibernate.dialect.PostgreSQLDialect;
+import org.hibernate.dialect.SQLServerDialect;
+import org.hibernate.dialect.SybaseAnywhereDialect;
import org.hibernate.dialect.SybaseDialect;
+import org.hibernate.dialect.Sybase11Dialect;
+import org.hibernate.dialect.SybaseASE15Dialect;
import org.hibernate.dialect.Oracle8iDialect;
import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.engine.SessionFactoryImplementor;
@@ -219,11 +223,14 @@
assertTranslation("from Animal a where abs(:param - a.bodyWeight) < 2.0");
assertTranslation("from Animal where abs(:x - :y) < 2.0");
assertTranslation("from Animal where lower(upper(:foo)) like 'f%'");
- if ( ! ( getDialect() instanceof SybaseDialect ) ) {
- // SybaseDialect maps the length function -> len; classic translator does not consider that *when nested*
+ if ( ! ( getDialect() instanceof SybaseDialect ) && ! ( getDialect() instanceof Sybase11Dialect ) && ! ( getDialect() instanceof SybaseASE15Dialect ) && ! ( getDialect() instanceof SQLServerDialect ) ) {
+ // Transact-SQL dialects (except SybaseAnywhereDialect) map the length function -> len;
+ // classic translator does not consider that *when nested*;
+ // SybaseAnywhereDialect supports the length function
+
assertTranslation("from Animal a where abs(abs(a.bodyWeight - 1.0 + :param) * abs(length('ffobar')-3)) = 3.0");
}
- if ( !( getDialect() instanceof MySQLDialect || getDialect() instanceof SybaseDialect ) ) {
+ if ( !( getDialect() instanceof MySQLDialect ) && ! ( getDialect() instanceof SybaseDialect ) && ! ( getDialect() instanceof Sybase11Dialect ) && !( getDialect() instanceof SybaseASE15Dialect ) && ! ( getDialect() instanceof SybaseAnywhereDialect ) && ! ( getDialect() instanceof SQLServerDialect ) ) {
assertTranslation("from Animal where lower(upper('foo') || upper(:bar)) like 'f%'");
}
if ( getDialect() instanceof PostgreSQLDialect ) {
@@ -594,7 +601,8 @@
}
public void testConcatenation() {
- if ( getDialect() instanceof MySQLDialect || getDialect() instanceof SybaseDialect ) {
+ if ( getDialect() instanceof MySQLDialect || getDialect() instanceof SybaseDialect || getDialect() instanceof Sybase11Dialect || getDialect() instanceof SybaseASE15Dialect || getDialect() instanceof SybaseAnywhereDialect || getDialect() instanceof SQLServerDialect ) {
+ // SybaseASE15Dialect and SybaseAnywhereDialect support '||'
// MySQL uses concat(x, y, z)
// SQL Server replaces '||' with '+'
//
Modified: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/interfaceproxy/InterfaceProxyTest.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/interfaceproxy/InterfaceProxyTest.java 2009-02-06 23:10:40 UTC (rev 15912)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/interfaceproxy/InterfaceProxyTest.java 2009-02-06 23:46:33 UTC (rev 15913)
@@ -46,7 +46,7 @@
SecureDocument d2 = new SecureDocumentImpl();
d2.setName("Secret");
d2.setContent( Hibernate.createBlob( "wxyz wxyz".getBytes() ) );
- // Sybase only allows 7-bits in a byte to be inserted into a tinyint
+ // SybaseASE15Dialect only allows 7-bits in a byte to be inserted into a tinyint
// column (0 <= val < 128)
d2.setPermissionBits( (byte) 127 );
d2.setOwner("gavin");
Modified: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/legacy/FooBarTest.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/legacy/FooBarTest.java 2009-02-06 23:10:40 UTC (rev 15912)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/legacy/FooBarTest.java 2009-02-06 23:46:33 UTC (rev 15913)
@@ -58,6 +58,8 @@
import org.hibernate.dialect.SAPDBDialect;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.dialect.SybaseDialect;
+import org.hibernate.dialect.Sybase11Dialect;
+import org.hibernate.dialect.SybaseASE15Dialect;
import org.hibernate.dialect.TimesTenDialect;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
@@ -2136,7 +2138,8 @@
s.find("select count(*) from Baz as baz where 1 in indices(baz.fooArray)");
s.find("select count(*) from Bar as bar where 'abc' in elements(bar.baz.fooArray)");
s.find("select count(*) from Bar as bar where 1 in indices(bar.baz.fooArray)");
- if ( !(getDialect() instanceof DB2Dialect) && !(getDialect() instanceof Oracle9Dialect) && !(getDialect() instanceof Oracle8iDialect ) && !( getDialect() instanceof SybaseDialect && !(getDialect() instanceof SQLServerDialect ) ) ) {
+ if ( !(getDialect() instanceof DB2Dialect) && !(getDialect() instanceof Oracle9Dialect) && !(getDialect() instanceof Oracle8iDialect ) && !( getDialect() instanceof SybaseDialect ) && !( getDialect() instanceof Sybase11Dialect ) && !( getDialect() instanceof SybaseASE15Dialect )) {
+ // SybaseAnywhereDialect supports implicit conversions from strings to ints
s.find("select count(*) from Bar as bar, bar.component.glarch.proxyArray as g where g.id in indices(bar.baz.fooArray)");
s.find("select max( elements(bar.baz.fooArray) ) from Bar as bar, bar.component.glarch.proxyArray as g where g.id in indices(bar.baz.fooArray)");
}
Modified: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/legacy/SQLFunctionsTest.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/legacy/SQLFunctionsTest.java 2009-02-06 23:10:40 UTC (rev 15912)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/legacy/SQLFunctionsTest.java 2009-02-06 23:46:33 UTC (rev 15913)
@@ -26,6 +26,9 @@
import org.hibernate.dialect.Oracle9Dialect;
import org.hibernate.dialect.OracleDialect;
import org.hibernate.dialect.SybaseDialect;
+import org.hibernate.dialect.Sybase11Dialect;
+import org.hibernate.dialect.SybaseASE15Dialect;
+import org.hibernate.dialect.SybaseAnywhereDialect;
import org.hibernate.dialect.TimesTenDialect;
import org.hibernate.dialect.SQLServerDialect;
import org.hibernate.dialect.function.SQLFunction;
@@ -370,7 +373,7 @@
s.find("from Simple s where not( upper( s.name ) ='yada' or 1=2 or 'foo'='bar' or not('foo'='foo') or 'foo' like 'bar' )").size()==1
);
}
- if ( !(getDialect() instanceof MySQLDialect) && !(getDialect() instanceof SybaseDialect) && !(getDialect() instanceof MckoiDialect) && !(getDialect() instanceof InterbaseDialect) && !(getDialect() instanceof TimesTenDialect) ) { //My SQL has a funny concatenation operator
+ if ( !(getDialect() instanceof MySQLDialect) && !(getDialect() instanceof SybaseDialect) && !(getDialect() instanceof SQLServerDialect) && !(getDialect() instanceof MckoiDialect) && !(getDialect() instanceof InterbaseDialect) && !(getDialect() instanceof TimesTenDialect) ) { //My SQL has a funny concatenation operator
assertTrue(
s.find("from Simple s where lower( s.name || ' foo' ) ='simple 1 foo'").size()==1
);
@@ -500,8 +503,8 @@
//assertTrue( b.getClob() instanceof ClobImpl );
s.flush();
- // Sybase ASE does not support ResultSet.getBlob(String)
- if ( getDialect() instanceof SybaseDialect && ! ( getDialect() instanceof SQLServerDialect ) ) {
+ // Sybase does not support ResultSet.getBlob(String)
+ if ( getDialect() instanceof SybaseDialect || getDialect() instanceof Sybase11Dialect || getDialect() instanceof SybaseASE15Dialect || getDialect() instanceof SybaseAnywhereDialect ) {
s.connection().rollback();
s.close();
return;
Modified: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/lob/SerializableTypeTest.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/lob/SerializableTypeTest.java 2009-02-06 23:10:40 UTC (rev 15912)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/lob/SerializableTypeTest.java 2009-02-06 23:46:33 UTC (rev 15913)
@@ -6,7 +6,9 @@
import org.hibernate.Session;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.SybaseDialect;
-import org.hibernate.dialect.SQLServerDialect;
+import org.hibernate.dialect.Sybase11Dialect;
+import org.hibernate.dialect.SybaseASE15Dialect;
+import org.hibernate.dialect.SybaseAnywhereDialect;
import org.hibernate.junit.functional.FunctionalTestCase;
import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
@@ -35,8 +37,8 @@
}
public void testNewSerializableType() {
- // Sybase ASE does not support ResultSet.getBlob(String)
- if ( getDialect() instanceof SybaseDialect && ! ( getDialect() instanceof SQLServerDialect ) ) {
+ // Sybase dialects do not support ResultSet.getBlob(String)
+ if ( getDialect() instanceof SybaseDialect || getDialect() instanceof Sybase11Dialect || getDialect() instanceof SybaseASE15Dialect || getDialect() instanceof SybaseAnywhereDialect ) {
return;
}
Modified: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/mixed/MixedTest.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/mixed/MixedTest.java 2009-02-06 23:10:40 UTC (rev 15912)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/mixed/MixedTest.java 2009-02-06 23:46:33 UTC (rev 15913)
@@ -46,7 +46,7 @@
SecureDocument d2 = new SecureDocument();
d2.setName( "Secret" );
d2.setContent( Hibernate.createBlob( "wxyz wxyz".getBytes() ) );
- // Sybase only allows 7-bits in a byte to be inserted into a tinyint
+ // SybaseASE15Dialect only allows 7-bits in a byte to be inserted into a tinyint
// column (0 <= val < 128)
d2.setPermissionBits( (byte) 127 );
d2.setOwner( "gavin" );
@@ -96,7 +96,7 @@
assertNotNull( d2.getContent() );
assertEquals( "max", d2.getOwner() );
assertEquals( "/", d2.getParent().getName() );
- // Sybase only allows 7-bits in a byte to be inserted into a tinyint
+ // SybaseASE15Dialect only allows 7-bits in a byte to be inserted into a tinyint
// column (0 <= val < 128)
assertEquals( (byte) 127, d2.getPermissionBits() );
assertNotNull( d2.getCreated() );
Modified: core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/stats/StatsTest.java
===================================================================
--- core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/stats/StatsTest.java 2009-02-06 23:10:40 UTC (rev 15912)
+++ core/branches/Branch_3_3/testsuite/src/test/java/org/hibernate/test/stats/StatsTest.java 2009-02-06 23:46:33 UTC (rev 15913)
@@ -165,7 +165,7 @@
// same deal with scroll()...
assertEquals( "unexpected execution count", 3, continentStats.getExecutionCount() );
assertEquals( "unexpected row count", results, continentStats.getExecutionRowCount() );
- // scroll through data because Sybase throws NullPointerException
+ // scroll through data because SybaseASE15Dialect throws NullPointerException
// if data is not read before closing the ResultSet
while ( scrollableResults.next() ) {
// do nothing
15 years, 2 months
Hibernate SVN: r15912 - in core/trunk/envers/src: main/java/org/hibernate/envers/synchronization/work and 3 other directories.
by hibernate-commits@lists.jboss.org
Author: adamw
Date: 2009-02-06 18:10:40 -0500 (Fri, 06 Feb 2009)
New Revision: 15912
Added:
core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/
core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/AbstractContainedEntity.java
core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/AbstractSetEntity.java
core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/ContainedEntity.java
core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/SetEntity.java
core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/UnidirectionalDoubleAbstract.java
Modified:
core/trunk/envers/src/main/java/org/hibernate/envers/event/AuditEventListener.java
core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java
core/trunk/envers/src/test/resources/testng.xml
Log:
HHH-3741: fix and testcase; properly computing the referencing property name in a unidirectional collection
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/event/AuditEventListener.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/event/AuditEventListener.java 2009-02-06 12:20:43 UTC (rev 15911)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/event/AuditEventListener.java 2009-02-06 23:10:40 UTC (rev 15912)
@@ -57,6 +57,7 @@
import org.hibernate.event.PreCollectionUpdateEvent;
import org.hibernate.event.PreCollectionUpdateEventListener;
import org.hibernate.persister.entity.EntityPersister;
+import org.hibernate.persister.collection.AbstractCollectionPersister;
import org.hibernate.proxy.HibernateProxy;
/**
@@ -206,7 +207,7 @@
AuditSync verSync = verCfg.getSyncManager().get(event.getSession());
PersistentCollectionChangeWorkUnit workUnit = new PersistentCollectionChangeWorkUnit(entityName, verCfg,
- newColl, collectionEntry.getRole(), oldColl, event.getAffectedOwnerIdOrNull());
+ newColl, collectionEntry, oldColl, event.getAffectedOwnerIdOrNull());
verSync.addWorkUnit(workUnit);
if (workUnit.containsWork()) {
Modified: core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java
===================================================================
--- core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java 2009-02-06 12:20:43 UTC (rev 15911)
+++ core/trunk/envers/src/main/java/org/hibernate/envers/synchronization/work/PersistentCollectionChangeWorkUnit.java 2009-02-06 23:10:40 UTC (rev 15912)
@@ -32,6 +32,8 @@
import org.hibernate.envers.entities.mapper.PersistentCollectionChangeData;
import org.hibernate.Session;
+import org.hibernate.persister.collection.AbstractCollectionPersister;
+import org.hibernate.engine.CollectionEntry;
import org.hibernate.collection.PersistentCollection;
/**
@@ -42,11 +44,12 @@
private final String referencingPropertyName;
public PersistentCollectionChangeWorkUnit(String entityName, AuditConfiguration verCfg,
- PersistentCollection collection, String role,
+ PersistentCollection collection, CollectionEntry collectionEntry,
Serializable snapshot, Serializable id) {
super(entityName, verCfg, null);
- referencingPropertyName = role.substring(entityName.length() + 1);
+ String ownerEntityName = ((AbstractCollectionPersister) collectionEntry.getLoadedPersister()).getOwnerEntityName();
+ referencingPropertyName = collectionEntry.getRole().substring(ownerEntityName.length() + 1);
collectionChanges = verCfg.getEntCfg().get(getEntityName()).getPropertyMapper()
.mapCollectionChanges(referencingPropertyName, collection, snapshot, id);
Added: core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/AbstractContainedEntity.java
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/AbstractContainedEntity.java (rev 0)
+++ core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/AbstractContainedEntity.java 2009-02-06 23:10:40 UTC (rev 15912)
@@ -0,0 +1,73 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * 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 Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+
+package org.hibernate.envers.test.integration.inheritance.joined.relation.unidirectional;
+
+import javax.persistence.Entity;
+import javax.persistence.Inheritance;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.InheritanceType;
+
+import org.hibernate.envers.Audited;
+
+/**
+ * @author Adam Warski (adam at warski dot org)
+ */
+@Entity
+@Audited
+@Inheritance(strategy = InheritanceType.JOINED)
+public abstract class AbstractContainedEntity {
+ @Id
+ @GeneratedValue
+ private Long id;
+
+ public AbstractContainedEntity() {
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof AbstractContainedEntity)) return false;
+
+ AbstractContainedEntity that = (AbstractContainedEntity) o;
+
+ if (id != null ? !id.equals(that.id) : that.id != null) return false;
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ return id != null ? id.hashCode() : 0;
+ }
+}
\ No newline at end of file
Added: core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/AbstractSetEntity.java
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/AbstractSetEntity.java (rev 0)
+++ core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/AbstractSetEntity.java 2009-02-06 23:10:40 UTC (rev 15912)
@@ -0,0 +1,71 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * 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 Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+
+package org.hibernate.envers.test.integration.inheritance.joined.relation.unidirectional;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.OneToMany;
+
+import org.hibernate.envers.Audited;
+
+import java.util.Set;
+import java.util.HashSet;
+
+/**
+ * @author Adam Warski (adam at warski dot org)
+ */
+@Entity
+@Inheritance(strategy = InheritanceType.JOINED)
+@Audited
+public abstract class AbstractSetEntity {
+ @Id
+ @GeneratedValue
+ private Integer id;
+
+ @OneToMany
+ private Set<AbstractContainedEntity> entities = new HashSet<AbstractContainedEntity>();
+
+ public AbstractSetEntity() {
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Set<AbstractContainedEntity> getEntities() {
+ return entities;
+ }
+
+ public void setEntities(Set<AbstractContainedEntity> entities) {
+ this.entities = entities;
+ }
+}
\ No newline at end of file
Added: core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/ContainedEntity.java
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/ContainedEntity.java (rev 0)
+++ core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/ContainedEntity.java 2009-02-06 23:10:40 UTC (rev 15912)
@@ -0,0 +1,37 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * 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 Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+
+package org.hibernate.envers.test.integration.inheritance.joined.relation.unidirectional;
+
+import javax.persistence.Entity;
+
+import org.hibernate.envers.Audited;
+
+/**
+ * @author Adam Warski (adam at warski dot org)
+ */
+@Entity
+@Audited
+public class ContainedEntity extends AbstractContainedEntity {
+}
\ No newline at end of file
Added: core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/SetEntity.java
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/SetEntity.java (rev 0)
+++ core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/SetEntity.java 2009-02-06 23:10:40 UTC (rev 15912)
@@ -0,0 +1,37 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * 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 Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+
+package org.hibernate.envers.test.integration.inheritance.joined.relation.unidirectional;
+
+import javax.persistence.Entity;
+
+import org.hibernate.envers.Audited;
+
+/**
+ * @author Adam Warski (adam at warski dot org)
+ */
+@Entity
+@Audited
+public class SetEntity extends AbstractSetEntity {
+}
\ No newline at end of file
Added: core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/UnidirectionalDoubleAbstract.java
===================================================================
--- core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/UnidirectionalDoubleAbstract.java (rev 0)
+++ core/trunk/envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/UnidirectionalDoubleAbstract.java 2009-02-06 23:10:40 UTC (rev 15912)
@@ -0,0 +1,87 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors. All third-party contributions are
+ * distributed under license by Red Hat Middleware LLC.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * 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 Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA 02110-1301 USA
+ */
+
+package org.hibernate.envers.test.integration.inheritance.joined.relation.unidirectional;
+
+import javax.persistence.EntityManager;
+
+import org.hibernate.envers.test.AbstractEntityTest;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+import org.hibernate.ejb.Ejb3Configuration;
+
+import java.util.Arrays;
+import java.util.Set;
+
+/**
+ * @author Adam Warski (adam at warski dot org)
+ */
+public class UnidirectionalDoubleAbstract extends AbstractEntityTest {
+ private Long cce1_id;
+ private Integer cse1_id;
+
+ public void configure(Ejb3Configuration cfg) {
+ cfg.addAnnotatedClass(AbstractContainedEntity.class);
+ cfg.addAnnotatedClass(AbstractSetEntity.class);
+ cfg.addAnnotatedClass(ContainedEntity.class);
+ cfg.addAnnotatedClass(SetEntity.class);
+ }
+
+ @BeforeClass(dependsOnMethods = "init")
+ public void initData() {
+ EntityManager em = getEntityManager();
+
+ // Rev 1
+ em.getTransaction().begin();
+
+ ContainedEntity cce1 = new ContainedEntity();
+ em.persist(cce1);
+
+ SetEntity cse1 = new SetEntity();
+ cse1.getEntities().add(cce1);
+ em.persist(cse1);
+
+ em.getTransaction().commit();
+
+ cce1_id = cce1.getId();
+ cse1_id = cse1.getId();
+ }
+
+ @Test
+ public void testRevisionsCounts() {
+ assert Arrays.asList(1).equals(getAuditReader().getRevisions(ContainedEntity.class, cce1_id));
+ assert Arrays.asList(1).equals(getAuditReader().getRevisions(SetEntity.class, cse1_id));
+ }
+
+ @Test
+ public void testHistoryOfReferencedCollection() {
+ ContainedEntity cce1 = getEntityManager().find(ContainedEntity.class, cce1_id);
+
+ Set<AbstractContainedEntity> entities = getAuditReader().find(SetEntity.class, cse1_id, 1).getEntities();
+ assert entities.size() == 1;
+ assert entities.iterator().next() instanceof ContainedEntity;
+ assert entities.contains(cce1);
+ }
+}
\ No newline at end of file
Modified: core/trunk/envers/src/test/resources/testng.xml
===================================================================
--- core/trunk/envers/src/test/resources/testng.xml 2009-02-06 12:20:43 UTC (rev 15911)
+++ core/trunk/envers/src/test/resources/testng.xml 2009-02-06 23:10:40 UTC (rev 15912)
@@ -19,6 +19,7 @@
<package name="org.hibernate.envers.test.integration.inheritance.joined.emptychild" />
<package name="org.hibernate.envers.test.integration.inheritance.joined.notownedrelation" />
<package name="org.hibernate.envers.test.integration.inheritance.joined.relation" />
+ <package name="org.hibernate.envers.test.integration.inheritance.joined.relation.unidirectional" />
<package name="org.hibernate.envers.test.integration.inheritance.single" />
<package name="org.hibernate.envers.test.integration.inheritance.single.childrelation" />
<package name="org.hibernate.envers.test.integration.inheritance.single.notownedrelation" />
15 years, 2 months
Hibernate SVN: r15911 - in validator/trunk/hibernate-validator/src: test/java/org/hibernate/validation/engine and 2 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-02-06 07:20:43 -0500 (Fri, 06 Feb 2009)
New Revision: 15911
Added:
validator/trunk/hibernate-validator/src/test/resources/ValidationMessages_es.properties
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolator.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java
validator/trunk/hibernate-validator/src/test/resources/org/hibernate/validation/ValidationMessages_de.properties
Log:
BVAL-69 made message interpolation work with locales
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolator.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolator.java 2009-02-06 10:38:22 UTC (rev 15910)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolator.java 2009-02-06 12:20:43 UTC (rev 15911)
@@ -17,6 +17,7 @@
*/
package org.hibernate.validation.engine;
+import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
@@ -45,48 +46,64 @@
* Regular expression used to do message interpolation.
*/
private static final Pattern messagePattern = Pattern.compile( "\\{([\\w\\.]+)\\}" );
- private ResourceBundle defaultResourceBundle;
- private ResourceBundle userResourceBundle;
+ /**
+ * The default locale for the current user.
+ */
+ private final Locale defaultLocale;
+
+ private final Map<Locale, ResourceBundle> userBundlesMap = new HashMap<Locale, ResourceBundle>();
+
+ private final Map<Locale, ResourceBundle> defaultBundlesMap = new HashMap<Locale, ResourceBundle>();
+
public ResourceBundleMessageInterpolator() {
- userResourceBundle = getFileBasedResourceBundle();
- defaultResourceBundle = ResourceBundle.getBundle( DEFAULT_VALIDATION_MESSAGES );
+ this( null );
}
public ResourceBundleMessageInterpolator(ResourceBundle resourceBundle) {
+
+ defaultLocale = Locale.getDefault();
+
if ( resourceBundle == null ) {
- userResourceBundle = getFileBasedResourceBundle();
+ ResourceBundle bundle = getFileBasedResourceBundle( defaultLocale );
+ userBundlesMap.put( defaultLocale, bundle );
+
}
else {
- this.userResourceBundle = resourceBundle;
+ userBundlesMap.put( defaultLocale, resourceBundle );
}
- defaultResourceBundle = ResourceBundle.getBundle( DEFAULT_VALIDATION_MESSAGES );
+
+ defaultBundlesMap.put( defaultLocale, ResourceBundle.getBundle( DEFAULT_VALIDATION_MESSAGES, defaultLocale ) );
}
public String interpolate(String message, ConstraintDescriptor constraintDescriptor, Object value) {
// probably no need for caching, but it could be done by parameters since the map
// is immutable and uniquely built per Validation definition, the comparaison has to be based on == and not equals though
- return replace( message, constraintDescriptor.getParameters() );
+ return replace( message, constraintDescriptor.getParameters(), defaultLocale );
}
public String interpolate(String message, ConstraintDescriptor constraintDescriptor, Object value, Locale locale) {
- throw new UnsupportedOperationException( "Interpolation for Locale. Has to be done." );
+ return replace( message, constraintDescriptor.getParameters(), locale );
}
/**
* Search current thread classloader for the resource bundle. If not found, search validator (this) classloader.
*
+ * @param locale The locale of the bundle to load.
+ *
* @return the resource bundle or <code>null</code> if none is found.
*/
- private ResourceBundle getFileBasedResourceBundle() {
+ private ResourceBundle getFileBasedResourceBundle(Locale locale) {
ResourceBundle rb = null;
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if ( classLoader != null ) {
- rb = loadBundle( classLoader, USER_VALIDATION_MESSAGES + " not found by thread local classloader" );
+ rb = loadBundle( classLoader, locale, USER_VALIDATION_MESSAGES + " not found by thread local classloader" );
}
if ( rb == null ) {
rb = loadBundle(
- this.getClass().getClassLoader(), USER_VALIDATION_MESSAGES + " not found by validator classloader"
+ this.getClass().getClassLoader(),
+ locale,
+ USER_VALIDATION_MESSAGES + " not found by validator classloader"
);
}
if ( log.isDebugEnabled() ) {
@@ -100,10 +117,10 @@
return rb;
}
- private ResourceBundle loadBundle(ClassLoader classLoader, String message) {
+ private ResourceBundle loadBundle(ClassLoader classLoader, Locale locale, String message) {
ResourceBundle rb = null;
try {
- rb = ResourceBundle.getBundle( USER_VALIDATION_MESSAGES, Locale.getDefault(), classLoader );
+ rb = ResourceBundle.getBundle( USER_VALIDATION_MESSAGES, locale, classLoader );
}
catch ( MissingResourceException e ) {
log.trace( message );
@@ -111,22 +128,25 @@
return rb;
}
- private String replace(String message, Map<String, Object> parameters) {
+ private String replace(String message, Map<String, Object> parameters, Locale locale) {
Matcher matcher = messagePattern.matcher( message );
StringBuffer sb = new StringBuffer();
while ( matcher.find() ) {
- matcher.appendReplacement( sb, resolveParameter( matcher.group( 1 ), parameters ) );
+ matcher.appendReplacement( sb, resolveParameter( matcher.group( 1 ), parameters, locale ) );
}
matcher.appendTail( sb );
return sb.toString();
}
- private String resolveParameter(String token, Map<String, Object> parameters) {
+ private String resolveParameter(String token, Map<String, Object> parameters, Locale locale) {
Object variable = parameters.get( token );
if ( variable != null ) {
return variable.toString();
}
+ ResourceBundle userResourceBundle = findUserResourceBundle( locale );
+ ResourceBundle defaultResourceBundle = findDefaultResourceBundle( locale );
+
StringBuffer buffer = new StringBuffer();
String string = null;
try {
@@ -146,8 +166,28 @@
}
if ( string != null ) {
// call resolve recusively!
- buffer.append( replace( string, parameters ) );
+ buffer.append( replace( string, parameters, locale ) );
}
return buffer.toString();
}
+
+ private ResourceBundle findDefaultResourceBundle(Locale locale) {
+ if ( defaultBundlesMap.containsKey( locale ) ) {
+ return defaultBundlesMap.get( locale );
+ }
+
+ ResourceBundle bundle = ResourceBundle.getBundle( DEFAULT_VALIDATION_MESSAGES, locale );
+ defaultBundlesMap.put( locale, bundle );
+ return bundle;
+ }
+
+ private ResourceBundle findUserResourceBundle(Locale locale) {
+ if ( userBundlesMap.containsKey( locale ) ) {
+ return userBundlesMap.get( locale );
+ }
+
+ ResourceBundle bundle = getFileBasedResourceBundle( locale );
+ userBundlesMap.put( locale, bundle );
+ return bundle;
+ }
}
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java 2009-02-06 10:38:22 UTC (rev 15910)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java 2009-02-06 12:20:43 UTC (rev 15911)
@@ -20,6 +20,7 @@
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
+import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.ResourceBundle;
@@ -57,7 +58,7 @@
@Test
public void testSuccessfulInterpolation() {
- ConstraintDescriptorImpl descriptor = new ConstraintDescriptorImpl(
+ ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
notNull, new Class<?>[] { }, new BuiltinConstraints()
);
@@ -80,7 +81,7 @@
@Test
public void testUnSuccessfulInterpolation() {
- ConstraintDescriptorImpl descriptor = new ConstraintDescriptorImpl(
+ ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
notNull, new Class<?>[] { }, new BuiltinConstraints()
);
String expected = "foo"; // missing {}
@@ -94,7 +95,7 @@
@Test
public void testUnkownTokenInterpolation() {
- ConstraintDescriptorImpl descriptor = new ConstraintDescriptorImpl(
+ ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
notNull, new Class<?>[] { }, new BuiltinConstraints()
);
String expected = "{bar}"; // unkown token {}
@@ -104,20 +105,60 @@
@Test
public void testDefaultInterpolation() {
- ConstraintDescriptorImpl descriptor = new ConstraintDescriptorImpl(
+ ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
notNull, new Class<?>[] { }, new BuiltinConstraints()
);
String expected = "may not be null";
String actual = interpolator.interpolate( notNull.message(), descriptor, null );
assertEquals( "Wrong substitution", expected, actual );
- descriptor = new ConstraintDescriptorImpl( size, new Class<?>[] { }, new BuiltinConstraints() );
+ ConstraintDescriptorImpl<Size> sizeDescriptor = new ConstraintDescriptorImpl<Size>(
+ size, new Class<?>[] { }, new BuiltinConstraints()
+ );
expected = "size must be between -2147483648 and 2147483647"; // unkown token {}
- actual = interpolator.interpolate( size.message(), descriptor, null );
+ actual = interpolator.interpolate( size.message(), sizeDescriptor, null );
assertEquals( "Wrong substitution", expected, actual );
}
+ @Test
+ public void testMessageInterpolationWithLocale() {
+ interpolator = new ResourceBundleMessageInterpolator();
+ ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
+ notNull, new Class<?>[] { }, new BuiltinConstraints()
+ );
+
+ String expected = "kann nicht null sein";
+ String actual = interpolator.interpolate( notNull.message(), descriptor, null, Locale.GERMAN );
+ assertEquals( "Wrong substitution", expected, actual );
+ }
+
+ @Test
+ public void testFallbackToDefaultLocale() {
+ interpolator = new ResourceBundleMessageInterpolator();
+
+ ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
+ notNull, new Class<?>[] { }, new BuiltinConstraints()
+ );
+
+ String expected = "may not be null";
+ String actual = interpolator.interpolate( notNull.message(), descriptor, null, Locale.JAPAN );
+ assertEquals( "Wrong substitution", expected, actual );
+ }
+
+ @Test
+ public void testUserResourceBundle() {
+ interpolator = new ResourceBundleMessageInterpolator();
+
+ ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
+ notNull, new Class<?>[] { }, new BuiltinConstraints()
+ );
+
+ String expected = "no puede ser null";
+ String actual = interpolator.interpolate( notNull.message(), descriptor, null, new Locale( "es", "ES" ) );
+ assertEquals( "Wrong substitution", expected, actual );
+ }
+
class TestResources extends ResourceBundle implements Enumeration<String> {
private Map<String, String> testResources;
Iterator<String> iter;
Added: validator/trunk/hibernate-validator/src/test/resources/ValidationMessages_es.properties
===================================================================
--- validator/trunk/hibernate-validator/src/test/resources/ValidationMessages_es.properties (rev 0)
+++ validator/trunk/hibernate-validator/src/test/resources/ValidationMessages_es.properties 2009-02-06 12:20:43 UTC (rev 15911)
@@ -0,0 +1 @@
+validator.notNull=no puede ser null
\ No newline at end of file
Modified: validator/trunk/hibernate-validator/src/test/resources/org/hibernate/validation/ValidationMessages_de.properties
===================================================================
--- validator/trunk/hibernate-validator/src/test/resources/org/hibernate/validation/ValidationMessages_de.properties 2009-02-06 10:38:22 UTC (rev 15910)
+++ validator/trunk/hibernate-validator/src/test/resources/org/hibernate/validation/ValidationMessages_de.properties 2009-02-06 12:20:43 UTC (rev 15911)
@@ -1,11 +1,2 @@
# $Id: ValidationMessages.properties 15846 2009-02-02 11:56:15Z hardy.ferentschik $
-validator.notNull=may not be null
-validator.size=size must be between {min} and {max}
-validator.length=length must be between {min} and {max}
-validator.notEmpty=may not be empty
-validator.pattern=must match "{regex}"
-validator.min=must be greater than {value}
-validator.max=must be less than {value}
-validator.null=must be null
-validator.past=must be in the past
-validator.future=must be in the future
+validator.notNull=kann nicht null sein
15 years, 2 months
Hibernate SVN: r15910 - in validator/trunk: tck-utils and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-02-06 05:38:22 -0500 (Fri, 06 Feb 2009)
New Revision: 15910
Modified:
validator/trunk/pom.xml
validator/trunk/tck-utils/pom.xml
Log:
switched back to java5 for now
Modified: validator/trunk/pom.xml
===================================================================
--- validator/trunk/pom.xml 2009-02-06 10:26:41 UTC (rev 15909)
+++ validator/trunk/pom.xml 2009-02-06 10:38:22 UTC (rev 15910)
@@ -114,8 +114,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
- <source>1.6</source>
- <target>1.6</target>
+ <source>1.5</source>
+ <target>1.5</target>
</configuration>
</plugin>
<plugin>
Modified: validator/trunk/tck-utils/pom.xml
===================================================================
--- validator/trunk/tck-utils/pom.xml 2009-02-06 10:26:41 UTC (rev 15909)
+++ validator/trunk/tck-utils/pom.xml 2009-02-06 10:38:22 UTC (rev 15910)
@@ -115,8 +115,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
- <source>1.6</source>
- <target>1.6</target>
+ <source>1.5</source>
+ <target>1.5</target>
</configuration>
</plugin>
<plugin>
15 years, 2 months
Hibernate SVN: r15909 - in validator/trunk: hibernate-validator and 5 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-02-06 05:26:41 -0500 (Fri, 06 Feb 2009)
New Revision: 15909
Added:
validator/trunk/tck-utils/src/main/java/org/hibernate/tck/annotations/SpecAssertions.java
Modified:
validator/trunk/hibernate-validator/pom.xml
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java
validator/trunk/pom.xml
validator/trunk/tck-utils/src/main/java/org/hibernate/tck/TCKAnnotationProcessor.java
validator/trunk/tck-utils/src/main/java/org/hibernate/tck/annotations/SpecAssertion.java
validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageProcessor.java
validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageProcessorFactory.java
validator/trunk/tck-utils/src/main/resources/META-INF/services/com.sun.mirror.apt.AnnotationProcessorFactory
Log:
Changes to tck-utils in order to get it compile. Changed to jvm target 1.6 in pom.
Modified: validator/trunk/hibernate-validator/pom.xml
===================================================================
--- validator/trunk/hibernate-validator/pom.xml 2009-02-05 18:18:05 UTC (rev 15908)
+++ validator/trunk/hibernate-validator/pom.xml 2009-02-06 10:26:41 UTC (rev 15909)
@@ -41,6 +41,7 @@
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>tck-utils</artifactId>
+ <version>0.9-SNAPSHOT</version>
<scope>test</scope>
</dependency>
</dependencies>
@@ -149,24 +150,6 @@
<report>javadoc</report>
</reports>
</reportSet>
- <reportSet>
- <id>specCheck</id>
- <configuration>
- <doclet>org.hibernate.javadoc.JSRDoclet</doclet>
- <docletPath>${basedir}/target/test-classes</docletPath>
- <additionalparam>
- -d ${project.build.directory}/site
- </additionalparam>
- <!--Other dir than apidocs-->
- <destDir>tck</destDir>
- <!--For the project-reports page-->
- <name>JSR Tests</name>
- <description>Cross references unit tests to JSR 303 specification.</description>
- </configuration>
- <reports>
- <report>test-javadoc</report>
- </reports>
- </reportSet>
</reportSets>
</plugin>
</plugins>
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java 2009-02-05 18:18:05 UTC (rev 15908)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ValidatorImplTest.java 2009-02-06 10:26:41 UTC (rev 15909)
@@ -55,7 +55,7 @@
*/
public class ValidatorImplTest {
- @SpecAssertion( section = {"3.1"} )
+ @SpecAssertion( section = "3.1" )
@Test
public void testWrongMethodName() {
try {
@@ -324,7 +324,7 @@
}
@Test
- @SpecAssertion( section = {"2.2"} )
+ @SpecAssertion( section = "2.2" )
public void testMultiValueConstraint() {
Validator validator = TestUtil.getValidator();
@@ -343,7 +343,7 @@
}
@Test
- @SpecAssertion( section = {"3.5.1"} )
+ @SpecAssertion( section = "3.5.1" )
public void testGraphValidation() {
Validator validator = TestUtil.getValidator();
Modified: validator/trunk/pom.xml
===================================================================
--- validator/trunk/pom.xml 2009-02-05 18:18:05 UTC (rev 15908)
+++ validator/trunk/pom.xml 2009-02-06 10:26:41 UTC (rev 15909)
@@ -79,11 +79,6 @@
<artifactId>junit</artifactId>
<version>4.4</version>
</dependency>
- <dependency>
- <groupId>org.hibernate</groupId>
- <artifactId>tck-utils</artifactId>
- <version>${version}</version>
- </dependency>
</dependencies>
</dependencyManagement>
@@ -119,8 +114,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
- <source>1.5</source>
- <target>1.5</target>
+ <source>1.6</source>
+ <target>1.6</target>
</configuration>
</plugin>
<plugin>
Modified: validator/trunk/tck-utils/src/main/java/org/hibernate/tck/TCKAnnotationProcessor.java
===================================================================
--- validator/trunk/tck-utils/src/main/java/org/hibernate/tck/TCKAnnotationProcessor.java 2009-02-05 18:18:05 UTC (rev 15908)
+++ validator/trunk/tck-utils/src/main/java/org/hibernate/tck/TCKAnnotationProcessor.java 2009-02-06 10:26:41 UTC (rev 15909)
@@ -94,7 +94,7 @@
public void visitMethodDeclaration(MethodDeclaration d) {
SpecAssertion annotation = d.getAnnotation( SpecAssertion.class );
JSRReference ref = new JSRReference(
- annotation.section()[0], d.getDeclaringType().getQualifiedName(), d.getSimpleName()
+ annotation.section(), d.getDeclaringType().getQualifiedName(), d.getSimpleName()
);
if ( annotation.note().length() > 0 ) {
ref.note = annotation.note();
Modified: validator/trunk/tck-utils/src/main/java/org/hibernate/tck/annotations/SpecAssertion.java
===================================================================
--- validator/trunk/tck-utils/src/main/java/org/hibernate/tck/annotations/SpecAssertion.java 2009-02-05 18:18:05 UTC (rev 15908)
+++ validator/trunk/tck-utils/src/main/java/org/hibernate/tck/annotations/SpecAssertion.java 2009-02-06 10:26:41 UTC (rev 15909)
@@ -25,8 +25,10 @@
@Documented
public @interface SpecAssertion {
- public String[] section();
+ public String section();
+ public String id() default "";
+
public String note() default "";
}
Added: validator/trunk/tck-utils/src/main/java/org/hibernate/tck/annotations/SpecAssertions.java
===================================================================
--- validator/trunk/tck-utils/src/main/java/org/hibernate/tck/annotations/SpecAssertions.java (rev 0)
+++ validator/trunk/tck-utils/src/main/java/org/hibernate/tck/annotations/SpecAssertions.java 2009-02-06 10:26:41 UTC (rev 15909)
@@ -0,0 +1,30 @@
+// $Id: SpecAssertion.java 15705 2008-12-18 16:21:24Z hardy.ferentschik $
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.tck.annotations;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Target;
+
+(a)Target(ElementType.METHOD)
+@Documented
+public @interface SpecAssertions {
+
+ SpecAssertion[] value();
+
+}
\ No newline at end of file
Modified: validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageProcessor.java
===================================================================
--- validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageProcessor.java 2009-02-05 18:18:05 UTC (rev 15908)
+++ validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageProcessor.java 2009-02-06 10:26:41 UTC (rev 15909)
@@ -2,11 +2,11 @@
import java.io.File;
import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
-import org.hibernate.tck.annotations.SpecAssertion;
-
import com.sun.mirror.apt.AnnotationProcessor;
import com.sun.mirror.apt.AnnotationProcessorEnvironment;
import com.sun.mirror.declaration.AnnotationTypeDeclaration;
@@ -15,91 +15,125 @@
import com.sun.mirror.util.DeclarationVisitors;
import com.sun.mirror.util.SimpleDeclarationVisitor;
+import org.hibernate.tck.annotations.SpecAssertion;
+import org.hibernate.tck.annotations.SpecAssertions;
+
/**
* Annotation processor for generating TCK coverage report
- *
+ *
* @author Shane Bryzak
*/
-public class CoverageProcessor implements AnnotationProcessor
-{
- private static final String OUTDIR_OPTION_NAME = "-s";
- private static final String REPORT_FILE_NAME = "coverage.html";
-
- private static final String AUDIT_FILE_NAME = "tck-audit.xml";
-
- private final AnnotationProcessorEnvironment env;
- private final File baseDir;
-
- private final List<SpecReference> references = new ArrayList<SpecReference>();
-
- private AuditParser auditParser;
-
- public CoverageProcessor(AnnotationProcessorEnvironment env)
- {
- this.env = env;
- String baseDirName = env.getOptions().get( OUTDIR_OPTION_NAME );
- baseDir = new File( baseDirName );
- baseDir.mkdirs();
-
- try
- {
- auditParser = new AuditParser(new FileInputStream(AUDIT_FILE_NAME));
- auditParser.parse();
- }
- catch (Exception ex)
- {
- throw new RuntimeException("Error parsing tck-audit.xml: " +
- ex.getClass().getName() + " - " + ex.getMessage(), ex);
- }
- }
+public class CoverageProcessor implements AnnotationProcessor {
+ private static final String OUTDIR_OPTION_FLAG = "-s";
+ private static final String AUDITFILE_OPTION_FLAG = "-a";
+ private static final String REPORT_FILE_NAME = "coverage.html";
- public void process()
- {
- AnnotationTypeDeclaration annotationType = (AnnotationTypeDeclaration)
- env.getTypeDeclaration(SpecAssertion.class.getCanonicalName());
-
- for (Declaration d : env.getDeclarationsAnnotatedWith(annotationType))
- {
- d.accept(DeclarationVisitors.getDeclarationScanner(
- new CreateReferenceVisitor(), DeclarationVisitors.NO_OP));
- }
-
- annotationType = (AnnotationTypeDeclaration)
- env.getTypeDeclaration(SpecAssertions.class.getCanonicalName());
- for (Declaration d : env.getDeclarationsAnnotatedWith(annotationType))
- {
- d.accept(DeclarationVisitors.getDeclarationScanner(
- new CreateReferenceVisitor(), DeclarationVisitors.NO_OP));
- }
-
-
- new CoverageReport(references, auditParser).writeToFile(new File(baseDir, REPORT_FILE_NAME));
- }
-
- private class CreateReferenceVisitor extends SimpleDeclarationVisitor
- {
- public void visitMethodDeclaration(MethodDeclaration d)
- {
- SpecAssertions assertions = d.getAnnotation ( SpecAssertions.class );
- if (assertions != null)
- {
- for (SpecAssertion assertion : assertions.value())
- {
- SpecReference ref = new SpecReference(
- assertion.section(), assertion.id(),
- d.getDeclaringType().getSimpleName(), d.getSimpleName());
- references.add( ref );
- }
- }
-
- SpecAssertion assertion = d.getAnnotation( SpecAssertion.class );
- if (assertion != null)
- {
- SpecReference ref = new SpecReference(
- assertion.section(), assertion.id(),
- d.getDeclaringType().getSimpleName(), d.getSimpleName());
- references.add( ref );
- }
- }
- }
+ private static final String DEFAULT_AUDIT_FILE_NAME = "tck-audit.xml";
+
+ private final AnnotationProcessorEnvironment env;
+
+ private final List<SpecReference> references = new ArrayList<SpecReference>();
+
+ private AuditParser auditParser;
+
+ private File baseDir;
+
+ public CoverageProcessor(AnnotationProcessorEnvironment env) {
+ this.env = env;
+
+ createOutputDir( env );
+ InputStream in = getAuditFileInputStream( env );
+
+ if ( in == null ) {
+ return;
+ }
+
+ try {
+ auditParser = new AuditParser( in );
+ auditParser.parse();
+ }
+ catch ( Exception e ) {
+ throw new RuntimeException( "Unable to parse audit file." );
+ }
+ }
+
+ private InputStream getAuditFileInputStream(AnnotationProcessorEnvironment env) {
+ InputStream in;
+ String auditFileName = env.getOptions().get( AUDITFILE_OPTION_FLAG );
+ if ( auditFileName == null || auditFileName.length() == 0 ) {
+ env.getMessager()
+ .printNotice( "No audit file specified on the command line. Trying default: " + DEFAULT_AUDIT_FILE_NAME );
+ auditFileName = DEFAULT_AUDIT_FILE_NAME;
+ }
+ try {
+ in = new FileInputStream( auditFileName );
+ }
+ catch ( IOException ex ) {
+ env.getMessager().printWarning( "Unable to open audit file - " + auditFileName );
+ env.getMessager().printWarning( "No report generated" );
+ return null;
+ }
+ return in;
+ }
+
+ private void createOutputDir(AnnotationProcessorEnvironment env) {
+ String baseDirName = env.getOptions().get( OUTDIR_OPTION_FLAG );
+ baseDir = new File( baseDirName );
+ baseDir.mkdirs();
+ }
+
+ public void process() {
+ if ( auditParser == null ) {
+ return;
+ }
+
+ AnnotationTypeDeclaration annotationType = ( AnnotationTypeDeclaration )
+ env.getTypeDeclaration( SpecAssertion.class.getCanonicalName() );
+
+
+ for ( Declaration d : env.getDeclarationsAnnotatedWith( annotationType ) ) {
+ d.accept(
+ DeclarationVisitors.getDeclarationScanner(
+ new CreateReferenceVisitor(), DeclarationVisitors.NO_OP
+ )
+ );
+ }
+
+ annotationType = ( AnnotationTypeDeclaration )
+ env.getTypeDeclaration( SpecAssertions.class.getCanonicalName() );
+ for ( Declaration d : env.getDeclarationsAnnotatedWith( annotationType ) ) {
+ d.accept(
+ DeclarationVisitors.getDeclarationScanner(
+ new CreateReferenceVisitor(), DeclarationVisitors.NO_OP
+ )
+ );
+ }
+
+
+ new CoverageReport( references, auditParser ).writeToFile( new File( baseDir, REPORT_FILE_NAME ) );
+ }
+
+ private class CreateReferenceVisitor extends SimpleDeclarationVisitor {
+ public void visitMethodDeclaration(MethodDeclaration d) {
+ SpecAssertions assertions = d.getAnnotation( SpecAssertions.class );
+ if ( assertions != null ) {
+ for ( SpecAssertion assertion : assertions.value() ) {
+ SpecReference ref = new SpecReference(
+ assertion.section(), assertion.id(),
+ d.getDeclaringType().getSimpleName(), d.getSimpleName()
+ );
+ references.add( ref );
+ }
+ }
+
+ SpecAssertion assertion = d.getAnnotation( SpecAssertion.class );
+ if ( assertion != null ) {
+ SpecReference ref = new SpecReference(
+ assertion.section(), assertion.id(),
+ d.getDeclaringType().getSimpleName(), d.getSimpleName()
+ );
+ references.add( ref );
+ }
+ }
+ }
}
Modified: validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageProcessorFactory.java
===================================================================
--- validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageProcessorFactory.java 2009-02-05 18:18:05 UTC (rev 15908)
+++ validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageProcessorFactory.java 2009-02-06 10:26:41 UTC (rev 15909)
@@ -6,6 +6,7 @@
import java.util.Set;
import org.hibernate.tck.annotations.SpecAssertion;
+import org.hibernate.tck.annotations.SpecAssertions;
import com.sun.mirror.apt.AnnotationProcessor;
import com.sun.mirror.apt.AnnotationProcessorEnvironment;
Modified: validator/trunk/tck-utils/src/main/resources/META-INF/services/com.sun.mirror.apt.AnnotationProcessorFactory
===================================================================
--- validator/trunk/tck-utils/src/main/resources/META-INF/services/com.sun.mirror.apt.AnnotationProcessorFactory 2009-02-05 18:18:05 UTC (rev 15908)
+++ validator/trunk/tck-utils/src/main/resources/META-INF/services/com.sun.mirror.apt.AnnotationProcessorFactory 2009-02-06 10:26:41 UTC (rev 15909)
@@ -1 +1 @@
-org.hibernate.tck.TCKAnnotationProcessorFactory
\ No newline at end of file
+org.hibernate.tck.report.CoverageProcessorFactory
\ No newline at end of file
15 years, 2 months
Hibernate SVN: r15908 - validator/trunk/validation-api/src/main/java/javax/validation.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2009-02-05 13:18:05 -0500 (Thu, 05 Feb 2009)
New Revision: 15908
Modified:
validator/trunk/validation-api/src/main/java/javax/validation/Constraint.java
validator/trunk/validation-api/src/main/java/javax/validation/Validator.java
Log:
Typos
Modified: validator/trunk/validation-api/src/main/java/javax/validation/Constraint.java
===================================================================
--- validator/trunk/validation-api/src/main/java/javax/validation/Constraint.java 2009-02-05 17:43:34 UTC (rev 15907)
+++ validator/trunk/validation-api/src/main/java/javax/validation/Constraint.java 2009-02-05 18:18:05 UTC (rev 15908)
@@ -29,7 +29,7 @@
* Link between a constraint annotation and its constraint validation implementations.
* <p/>
* A given constraint annotation should be annotated by a @Constraint
- * annotation which refers to its list of constraint validation implementation.
+ * annotation which refers to its list of constraint validation implementations.
*
* @author Emmanuel Bernard (emmanuel at hibernate.org)
* @author Gavin King
@@ -39,11 +39,11 @@
@Target({ ANNOTATION_TYPE })
@Retention(RUNTIME)
public @interface Constraint {
- /**
- * ConstraintValidator classes must reference distinct target types.
- * If two validators refer to the same type, an exception will occur
- *
- * @return aray of ConstraintValidator classes implementing the constraint
- */
- public Class<? extends ConstraintValidator<?,?>>[] validatedBy();
+ /**
+ * ConstraintValidator classes must reference distinct target types.
+ * If two validators refer to the same type, an exception will occur.
+ *
+ * @return array of ConstraintValidator classes implementing the constraint
+ */
+ public Class<? extends ConstraintValidator<?,?>>[] validatedBy();
}
\ No newline at end of file
Modified: validator/trunk/validation-api/src/main/java/javax/validation/Validator.java
===================================================================
--- validator/trunk/validation-api/src/main/java/javax/validation/Validator.java 2009-02-05 17:43:34 UTC (rev 15907)
+++ validator/trunk/validation-api/src/main/java/javax/validation/Validator.java 2009-02-05 18:18:05 UTC (rev 15908)
@@ -36,7 +36,7 @@
*
* @return constraint violations or an empty Set if none
*
- * @throws IllegalArgumentException e if object is null
+ * @throws IllegalArgumentException if object is null
*/
<T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups);
@@ -50,7 +50,7 @@
*
* @return constraint violations or an empty Set if none
*
- * @throws IllegalArgumentException e if object is null or if propertyName is not present
+ * @throws IllegalArgumentException if object is null or if propertyName is not present
*/
<T> Set<ConstraintViolation<T>> validateProperty(T object,
String propertyName,
@@ -69,7 +69,7 @@
* (default to {@link javax.validation.groups.Default})
*
* @return constraint violations or an empty Set if none
- * @throws IllegalArgumentException e if propertyName is not present
+ * @throws IllegalArgumentException if propertyName is not present
*/
<T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType,
String propertyName,
15 years, 2 months
Hibernate SVN: r15907 - in validator/trunk/hibernate-validator: src/main and 9 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-02-05 12:43:34 -0500 (Thu, 05 Feb 2009)
New Revision: 15907
Added:
validator/trunk/hibernate-validator/src/main/docbook/
validator/trunk/hibernate-validator/src/main/docbook/en-US/
validator/trunk/hibernate-validator/src/main/docbook/en-US/images/
validator/trunk/hibernate-validator/src/main/docbook/en-US/images/hibernate_logo_a.png
validator/trunk/hibernate-validator/src/main/docbook/en-US/master.xml
validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/
validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/checkconstraints.xml
validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/defineconstraints.xml
validator/trunk/hibernate-validator/src/test/resources/org/
validator/trunk/hibernate-validator/src/test/resources/org/hibernate/
validator/trunk/hibernate-validator/src/test/resources/org/hibernate/validation/
validator/trunk/hibernate-validator/src/test/resources/org/hibernate/validation/ValidationMessages_de.properties
Modified:
validator/trunk/hibernate-validator/pom.xml
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolator.java
Log:
Checked in a shell for the new documentation and added it to the build cycle
Modified: validator/trunk/hibernate-validator/pom.xml
===================================================================
--- validator/trunk/hibernate-validator/pom.xml 2009-02-05 17:41:58 UTC (rev 15906)
+++ validator/trunk/hibernate-validator/pom.xml 2009-02-05 17:43:34 UTC (rev 15907)
@@ -66,6 +66,62 @@
<testOutputDirectory>${project.build.directory}/site</testOutputDirectory>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.jboss.maven.plugins</groupId>
+ <artifactId>maven-jdocbook-plugin</artifactId>
+ <version>2.1.0</version>
+ <extensions>true</extensions>
+ <dependencies>
+ <dependency>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-jdocbook-style</artifactId>
+ <version>1.0.2</version>
+ <type>jdocbook-style</type>
+ </dependency>
+ </dependencies>
+ <configuration>
+ <sourceDocumentName>master.xml</sourceDocumentName>
+ <sourceDirectory>${basedir}/src/main/docbook/en-US</sourceDirectory>
+ <masterTranslation>en-US</masterTranslation>
+ <imageResource>
+ <directory>${basedir}/src/main/docbook/en-US/images</directory>
+ </imageResource>
+ <formats>
+ <format>
+ <formatName>pdf</formatName>
+ <stylesheetResource>classpath:/xslt/hibernate/pdf/main-pdf.xsl</stylesheetResource>
+ <finalName>hibernate-validator-guide.pdf</finalName>
+ </format>
+ <format>
+ <formatName>html_single</formatName>
+ <stylesheetResource>classpath:/xslt/hibernate/html/main-single.xsl
+ </stylesheetResource>
+ <finalName>index.html</finalName>
+ </format>
+ <format>
+ <formatName>html</formatName>
+ <stylesheetResource>classpath:/xslt/hibernate/html/main-chunk.xsl
+ </stylesheetResource>
+ <finalName>index.html</finalName>
+ </format>
+ </formats>
+ <options>
+ <xincludeSupported>true</xincludeSupported>
+ <localeSeparator>-</localeSeparator>
+ <useRelativeImageUris>true</useRelativeImageUris>
+ </options>
+ </configuration>
+ <executions>
+ <execution>
+ <id>make-doc</id>
+ <phase>package</phase>
+ <goals>
+ <goal>resources</goal>
+ <goal>generate</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
</plugins>
</build>
<reporting>
Added: validator/trunk/hibernate-validator/src/main/docbook/en-US/images/hibernate_logo_a.png
===================================================================
(Binary files differ)
Property changes on: validator/trunk/hibernate-validator/src/main/docbook/en-US/images/hibernate_logo_a.png
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: validator/trunk/hibernate-validator/src/main/docbook/en-US/master.xml
===================================================================
--- validator/trunk/hibernate-validator/src/main/docbook/en-US/master.xml (rev 0)
+++ validator/trunk/hibernate-validator/src/main/docbook/en-US/master.xml 2009-02-05 17:43:34 UTC (rev 15907)
@@ -0,0 +1,92 @@
+<?xml version='1.0' encoding="UTF-8"?>
+<!--
+ ~ Hibernate, Relational Persistence for Idiomatic Java
+ ~
+ ~ Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ ~ indicated by the @author tags or express copyright attribution
+ ~ statements applied by the authors. All third-party contributions are
+ ~ distributed under license by Red Hat Middleware LLC.
+ ~
+ ~ This copyrighted material is made available to anyone wishing to use, modify,
+ ~ copy, or redistribute it subject to the terms and conditions of the GNU
+ ~ Lesser General Public License, as published by the Free Software Foundation.
+ ~
+ ~ 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 Lesser General Public License
+ ~ for more details.
+ ~
+ ~ You should have received a copy of the GNU Lesser General Public License
+ ~ along with this distribution; if not, write to:
+ ~ Free Software Foundation, Inc.
+ ~ 51 Franklin Street, Fifth Floor
+ ~ Boston, MA 02110-1301 USA
+ -->
+<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
+ <!ENTITY versionNumber "4.0.0.Alpha1">
+ <!ENTITY copyrightYear "2004">
+ <!ENTITY copyrightHolder "Red Hat Middleware, LLC.">
+]>
+
+<book lang="en">
+ <bookinfo>
+ <title>Hibernate Validator</title>
+ <subtitle>Reference Guide</subtitle>
+ <releaseinfo>&versionNumber;</releaseinfo>
+ <productnumber>&versionNumber;</productnumber>
+ <issuenum>1</issuenum>
+ <mediaobject>
+ <imageobject>
+ <imagedata fileref="images/hibernate_logo_a.png" format="png" />
+ </imageobject>
+ </mediaobject>
+ <copyright>
+ <year>©rightYear;</year>
+ <holder>©rightHolder;</holder>
+ </copyright>
+ <!-- include translators... -->
+ </bookinfo>
+
+ <toc/>
+
+ <preface id="preface" revision="2">
+ <title>Preface</title>
+
+ <para>Annotations are a very convenient and elegant way to specify
+ invariant constraints for a domain model. You can, for example, express
+ that a property should never be null, that the account balance should be
+ strictly positive, etc. These domain model constraints are declared in the
+ bean itself by annotating its properties. A validator can then read them
+ and check for constraint violations. The validation mechanism can be
+ executed in different layers in your application without having to
+ duplicate any of these rules (presentation layer, data access layer).
+ Following the DRY principle, Hibernate Validator has been designed for
+ that purpose.</para>
+
+ <para>Hibernate Validator works at two levels. First, it is able to check
+ in-memory instances of a class for constraint violations. Second, it can
+ apply the constraints to the Hibernate metamodel and incorporate them into
+ the generated database schema.</para>
+
+ <para>Each constraint annotation is associated to a validator
+ implementation responsible for checking the constraint on the entity
+ instance. A validator can also (optionally) apply the constraint to the
+ Hibernate metamodel, allowing Hibernate to generate DDL that expresses the
+ constraint. With the appropriate event listener, you can execute the
+ checking operation on inserts and updates done by Hibernate. Hibernate
+ Validator is not limited to use with Hibernate. You can easily use it
+ anywhere in your application as well as with any Java Persistence provider
+ (entity listener provided).</para>
+
+ <para>When checking instances at runtime, Hibernate Validator returns
+ information about constraint violations in an array of
+ <classname>InvalidValue</classname> s. Among other information, the
+ <classname>InvalidValue</classname> contains an error description message
+ that can embed the parameter values bundle with the annotation (eg. length
+ limit), and message strings that may be externalized to a
+ <classname>ResourceBundle</classname> .</para>
+ </preface>
+
+ <xi:include href="modules/defineconstraints.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
+ <xi:include href="modules/checkconstraints.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
+</book>
\ No newline at end of file
Added: validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/checkconstraints.xml
===================================================================
--- validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/checkconstraints.xml (rev 0)
+++ validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/checkconstraints.xml 2009-02-05 17:43:34 UTC (rev 15907)
@@ -0,0 +1,235 @@
+<?xml version='1.0' encoding="UTF-8"?>
+<!--
+ ~ Hibernate, Relational Persistence for Idiomatic Java
+ ~
+ ~ Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ ~ indicated by the @author tags or express copyright attribution
+ ~ statements applied by the authors. All third-party contributions are
+ ~ distributed under license by Red Hat Middleware LLC.
+ ~
+ ~ This copyrighted material is made available to anyone wishing to use, modify,
+ ~ copy, or redistribute it subject to the terms and conditions of the GNU
+ ~ Lesser General Public License, as published by the Free Software Foundation.
+ ~
+ ~ 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 Lesser General Public License
+ ~ for more details.
+ ~
+ ~ You should have received a copy of the GNU Lesser General Public License
+ ~ along with this distribution; if not, write to:
+ ~ Free Software Foundation, Inc.
+ ~ 51 Franklin Street, Fifth Floor
+ ~ Boston, MA 02110-1301 USA
+ -->
+
+<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
+
+<chapter id="validator-checkconstraints">
+ <title>Using the Validator framework</title>
+
+ <para>Hibernate Validator is intended to be used to implement multi-layered
+ data validation, where constraints are expressed in a single place (the
+ annotated domain model) and checked in various different layers of the
+ application.</para>
+
+ <para>This chapter will cover Hibernate Validator usage for different
+ layers</para>
+
+ <section id="validator-checkconstraints-db" revision="2">
+ <title>Database schema-level validation</title>
+
+ <para>Out of the box, Hibernate Annotations will translate the constraints
+ you have defined for your entities into mapping metadata. For example, if
+ a property of your entity is annotated <literal>@NotNull</literal>, its
+ columns will be declared as <literal>not null</literal> in the DDL schema
+ generated by Hibernate.</para>
+
+ <para>Using hbm2ddl, domain model constraints will be expressed into the
+ database schema.</para>
+
+ <para>If, for some reason, the feature needs to be disabled, set
+ <literal>hibernate.validator.apply_to_ddl</literal> to
+ <literal>false</literal>.</para>
+ </section>
+
+ <section id="validator-checkconstraints-orm">
+ <title>ORM integration</title>
+
+ <para>Hibernate Validator integrates with both Hibernate and all pure Java
+ Persistence providers</para>
+
+ <section id="validator-checkconstraints-orm-hibernateevent" revision="1">
+ <title>Hibernate event-based validation</title>
+
+ <para>Hibernate Validator has two built-in Hibernate event listeners.
+ Whenever a <literal>PreInsertEvent</literal> or
+ <literal>PreUpdateEvent</literal> occurs, the listeners will verify all
+ constraints of the entity instance and throw an exception if any
+ constraint is violated. Basically, objects will be checked before any
+ inserts and before any updates made by Hibernate. This includes changes
+ applied by cascade! This is the most convenient and the easiest way to
+ activate the validation process. On constraint violation, the event will
+ raise a runtime <classname>InvalidStateException</classname> which
+ contains an array of <literal>InvalidValue</literal>s describing each
+ failure.</para>
+
+ <para>If Hibernate Validator is present in the classpath, Hibernate
+ Annotations (or Hibernate EntityManager) will use it transparently. If,
+ for some reason, you want to disable this integration, set
+ <literal>hibernate.validator.autoregister_listeners</literal> to
+ false</para>
+
+ <para><note>
+ <para>If the beans are not annotated with validation annotations,
+ there is no runtime performance cost.</para>
+ </note></para>
+
+ <para>In case you need to manually set the event listeners for Hibernate
+ Core, use the following configuration in
+ <literal>hibernate.cfg.xml</literal>:</para>
+
+ <programlisting><hibernate-configuration>
+ ...
+ <event type="pre-update">
+ <listener
+ class="org.hibernate.validator.event.ValidateEventListener"/>
+ </event>
+ <event type="pre-insert">
+ <listener
+ class="org.hibernate.validator.event.ValidateEventListener"/>
+ </event>
+</hibernate-configuration></programlisting>
+ </section>
+
+ <section id="validator-checkconstraints-orm-jpaevent">
+ <title>Java Persistence event-based validation</title>
+
+ <para>Hibernate Validator is not tied to Hibernate for event based
+ validation: a Java Persistence entity listener is available. Whenever an
+ listened entity is persisted or updated, Hibernate Validator will verify
+ all constraints of the entity instance and throw an exception if any
+ constraint is violated. Basically, objects will be checked before any
+ inserts and before any updates made by the Java Persistence provider.
+ This includes changes applied by cascade! On constraint violation, the
+ event will raise a runtime <classname>InvalidStateException</classname>
+ which contains an array of <literal>InvalidValue</literal>s describing
+ each failure.</para>
+
+ <para>Here is how to make a class validatable:</para>
+
+ <programlisting>@Entity
+@EntityListeners( JPAValidateListener.class )
+public class Submarine {
+ ...
+}</programlisting>
+
+ <para><note>
+ <para>Compared to the Hibernate event, the Java Persistence listener
+ has two drawbacks. You need to define the entity listener on every
+ validatable entity. The DDL generated by your provider will not
+ reflect the constraints.</para>
+ </note></para>
+ </section>
+ </section>
+
+ <section>
+ <title>Application-level validation</title>
+
+ <para>Hibernate Validator can be applied anywhere in your application
+ code.</para>
+
+ <programlisting>ClassValidator personValidator = new ClassValidator( Person.class );
+ClassValidator addressValidator = new ClassValidator( Address.class, ResourceBundle.getBundle("messages", Locale.ENGLISH) );
+
+InvalidValue[] validationMessages = addressValidator.getInvalidValues(address);</programlisting>
+
+ <para>The first two lines prepare the Hibernate Validator for class
+ checking. The first one relies upon the error messages embedded in
+ Hibernate Validator (see <xref
+ linkend="validator-defineconstraints-error" />), the second one uses a
+ resource bundle for these messages. It is considered a good practice to
+ execute these lines once and cache the validator instances.</para>
+
+ <para>The third line actually validates the <literal>Address</literal>
+ instance and returns an array of <literal>InvalidValue</literal>s. Your
+ application logic will then be able to react to the failure.</para>
+
+ <para>You can also check a particular property instead of the whole bean.
+ This might be useful for property per property user interaction</para>
+
+ <programlisting>ClassValidator addressValidator = new ClassValidator( Address.class, ResourceBundle.getBundle("messages", Locale.ENGLISH) );
+
+//only get city property invalid values
+InvalidValue[] validationMessages = addressValidator.getInvalidValues(address, "city");
+
+//only get potential city property invalid values
+InvalidValue[] validationMessages = addressValidator.getPotentialInvalidValues("city", "Paris")</programlisting>
+ </section>
+
+ <section>
+ <title>Presentation layer validation</title>
+
+ <para>When working with JSF and <productname>JBoss Seam</productname>, one
+ can triggers the validation process at the presentation layer using Seam's
+ JSF tags <literal><s:validate></literal> and
+ <literal><s:validateAll/></literal>, letting the constraints be
+ expressed on the model, and the violations presented in the view</para>
+
+ <programlisting><h:form>
+ <div>
+ <h:messages/>
+ </div>
+ <emphasis role="bold"><s:validateAll></emphasis>
+ <div>
+ Country:
+ <h:inputText value="#{location.country}" required="true"/>
+ </div>
+ <div>
+ Zip code:
+ <h:inputText value="#{location.zip}" required="true"/>
+ </div>
+ <div>
+ <h:commandButton/>
+ </div>
+ <emphasis role="bold"></s:validateAll></emphasis>
+</h:form></programlisting>
+
+ <para>Going even further, and adding <productname>Ajax4JSF</productname>
+ to the loop will bring client side validation with just a couple of
+ additional JSF tags, again without validation definition
+ duplication.</para>
+
+ <para>Check the <ulink url="http://www.jboss.com/products/seam">JBoss
+ Seam</ulink> documentation for more information.</para>
+ </section>
+
+ <section>
+ <title>Validation informations</title>
+
+ <para>As a validation information carrier, hibernate provide an array of
+ <classname>InvalidValue</classname>. Each <literal>InvalidValue</literal>
+ has a buch of methods describing the individual issues.</para>
+
+ <para><methodname>getBeanClass()</methodname> retrieves the failing bean
+ type</para>
+
+ <para><methodname>getBean()</methodname>retrieves the failing instance (if
+ any ie not when using
+ <methodname>getPotentianInvalidValues()</methodname>)</para>
+
+ <para><methodname>getValue()</methodname> retrieves the failing
+ value</para>
+
+ <para><methodname>getMessage()</methodname> retrieves the proper
+ internationalized error message</para>
+
+ <para><methodname>getRootBean()</methodname> retrieves the root bean
+ instance generating the issue (useful in conjunction with
+ <literal>@Valid</literal>), is null if getPotentianInvalidValues() is
+ used.</para>
+
+ <para><literal>getPropertyPath()</literal> retrieves the dotted path of
+ the failing property starting from the root bean</para>
+ </section>
+</chapter>
\ No newline at end of file
Added: validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/defineconstraints.xml
===================================================================
--- validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/defineconstraints.xml (rev 0)
+++ validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/defineconstraints.xml 2009-02-05 17:43:34 UTC (rev 15907)
@@ -0,0 +1,494 @@
+<?xml version='1.0' encoding="UTF-8"?>
+<!--
+ ~ Hibernate, Relational Persistence for Idiomatic Java
+ ~
+ ~ Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ ~ indicated by the @author tags or express copyright attribution
+ ~ statements applied by the authors. All third-party contributions are
+ ~ distributed under license by Red Hat Middleware LLC.
+ ~
+ ~ This copyrighted material is made available to anyone wishing to use, modify,
+ ~ copy, or redistribute it subject to the terms and conditions of the GNU
+ ~ Lesser General Public License, as published by the Free Software Foundation.
+ ~
+ ~ 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 Lesser General Public License
+ ~ for more details.
+ ~
+ ~ You should have received a copy of the GNU Lesser General Public License
+ ~ along with this distribution; if not, write to:
+ ~ Free Software Foundation, Inc.
+ ~ 51 Franklin Street, Fifth Floor
+ ~ Boston, MA 02110-1301 USA
+ -->
+
+<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
+
+<chapter id="validator-defineconstraints">
+ <title>Defining constraints</title>
+
+ <section id="validator-defineconstraints-definition" revision="1">
+ <title>What is a constraint?</title>
+
+ <para>A constraint is a rule that a given element (field, property or
+ bean) has to comply to. The rule semantic is expressed by an annotation. A
+ constraint usually has some attributes used to parameterize the
+ constraints limits. The constraint applies to the annotated
+ element.</para>
+ </section>
+
+ <section id="validator-defineconstraints-builtin" revision="2">
+ <title>Built in constraints</title>
+
+ <para>Hibernate Validator comes with some built-in constraints, which
+ covers most basic data checks. As we'll see later, you're not limited to
+ them, you can literally in a minute write your own constraints.</para>
+
+ <table>
+ <title>Built-in constraints</title>
+
+ <tgroup cols="4">
+ <colspec align="center" />
+
+ <thead>
+ <row>
+ <entry>Annotation</entry>
+
+ <entry>Apply on</entry>
+
+ <entry>Runtime checking</entry>
+
+ <entry>Hibernate Metadata impact</entry>
+ </row>
+ </thead>
+
+ <tbody>
+ <row>
+ <entry>@Length(min=, max=)</entry>
+
+ <entry>property (String)</entry>
+
+ <entry>check if the string length match the range</entry>
+
+ <entry>Column length will be set to max</entry>
+ </row>
+
+ <row>
+ <entry>@Max(value=)</entry>
+
+ <entry>property (numeric or string representation of a
+ numeric)</entry>
+
+ <entry>check if the value is less than or equals to max</entry>
+
+ <entry>Add a check constraint on the column</entry>
+ </row>
+
+ <row>
+ <entry>@Min(value=)</entry>
+
+ <entry>property (numeric or string representation of a
+ numeric)</entry>
+
+ <entry>check if the value is more than or equals to min</entry>
+
+ <entry>Add a check constraint on the column</entry>
+ </row>
+
+ <row>
+ <entry>@NotNull</entry>
+
+ <entry>property</entry>
+
+ <entry>check if the value is not null</entry>
+
+ <entry>Column(s) are not null</entry>
+ </row>
+
+ <row>
+ <entry>@NotEmpty</entry>
+
+ <entry>property</entry>
+
+ <entry>check if the string is not null nor empty. Check if the
+ connection is not null nor empty</entry>
+
+ <entry>Column(s) are not null (for String)</entry>
+ </row>
+
+ <row>
+ <entry>@Past</entry>
+
+ <entry>property (date or calendar)</entry>
+
+ <entry>check if the date is in the past</entry>
+
+ <entry>Add a check constraint on the column</entry>
+ </row>
+
+ <row>
+ <entry>@Future</entry>
+
+ <entry>property (date or calendar)</entry>
+
+ <entry>check if the date is in the future</entry>
+
+ <entry>none</entry>
+ </row>
+
+ <row>
+ <entry>@Pattern(regex="regexp", flag=) or @Patterns(
+ {@Pattern(...)} )</entry>
+
+ <entry>property (string)</entry>
+
+ <entry>check if the property match the regular expression given a
+ match flag (see <classname>java.util.regex.Pattern </classname>
+ )</entry>
+
+ <entry>none</entry>
+ </row>
+
+ <row>
+ <entry>@Range(min=, max=)</entry>
+
+ <entry>property (numeric or string representation of a
+ numeric)</entry>
+
+ <entry>check if the value is between min and max
+ (included)</entry>
+
+ <entry>Add a check constraint on the column</entry>
+ </row>
+
+ <row>
+ <entry>@Size(min=, max=)</entry>
+
+ <entry>property (array, collection, map)</entry>
+
+ <entry>check if the element size is between min and max
+ (included)</entry>
+
+ <entry>none</entry>
+ </row>
+
+ <row>
+ <entry>@AssertFalse</entry>
+
+ <entry>property</entry>
+
+ <entry>check that the method evaluates to false (useful for
+ constraints expressed in code rather than annotations)</entry>
+
+ <entry>none</entry>
+ </row>
+
+ <row>
+ <entry>@AssertTrue</entry>
+
+ <entry>property</entry>
+
+ <entry>check that the method evaluates to true (useful for
+ constraints expressed in code rather than annotations)</entry>
+
+ <entry>none</entry>
+ </row>
+
+ <row>
+ <entry>@Valid</entry>
+
+ <entry>property (object)</entry>
+
+ <entry>perform validation recursively on the associated object. If
+ the object is a Collection or an array, the elements are validated
+ recursively. If the object is a Map, the value elements are
+ validated recursively.</entry>
+
+ <entry>none</entry>
+ </row>
+
+ <row>
+ <entry>@Email</entry>
+
+ <entry>property (String)</entry>
+
+ <entry>check whether the string is conform to the email address
+ specification</entry>
+
+ <entry>none</entry>
+ </row>
+
+ <row>
+ <entry>@CreditCardNumber</entry>
+
+ <entry>property (String)</entry>
+
+ <entry>check whether the string is a well formated credit card
+ number (derivative of the Luhn algorithm)</entry>
+
+ <entry>none</entry>
+ </row>
+
+ <row>
+ <entry>@Digits</entry>
+
+ <entry>property (numeric or string representation of a
+ numeric)</entry>
+
+ <entry>check whether the property is a number having up to
+ <literal>integerDigits</literal> integer digits and
+ <literal>fractionalDigits</literal> fractonal digits</entry>
+
+ <entry>define column precision and scale</entry>
+ </row>
+
+ <row>
+ <entry>@EAN</entry>
+
+ <entry>property (string)</entry>
+
+ <entry>check whether the string is a properly formated EAN or
+ UPC-A code</entry>
+
+ <entry>none</entry>
+ </row>
+ </tbody>
+ </tgroup>
+ </table>
+ </section>
+
+ <section id="validator-defineconstraints-error" xreflabel="Error messages">
+ <title>Error messages</title>
+
+ <para>Hibernate Validator comes with a default set of error messages
+ translated in about ten languages (if yours is not part of it, please sent
+ us a patch). You can override those messages by creating a
+ <filename>ValidatorMessages.properties</filename> or (
+ <filename>ValidatorMessages_loc.properties</filename> ) and override the
+ needed keys. You can even add your own additional set of messages while
+ writing your validator annotations. If Hibernate Validator cannot resolve
+ a key from your resourceBundle nor from ValidatorMessage, it falls back to
+ the default built-in values.</para>
+
+ <para>Alternatively you can provide a
+ <classname>ResourceBundle</classname> while checking programmatically the
+ validation rules on a bean or if you want a completly different
+ interpolation mechanism, you can provide an implementation of
+ <literal>org.hibernate.validator.MessageInterpolator</literal> (check the
+ JavaDoc for more informations).</para>
+ </section>
+
+ <section id="validator-defineconstraints-own" revision="1">
+ <title>Writing your own constraints</title>
+
+ <para>Extending the set of built-in constraints is extremely easy. Any
+ constraint consists of two pieces: the constraint
+ <emphasis>descriptor</emphasis> (the annotation) and the constraint
+ <emphasis>validator</emphasis> (the implementation class). Here is a
+ simple user-defined descriptor:</para>
+
+ <programlisting>@ValidatorClass(CapitalizedValidator.class)
+@Target(METHOD)
+@Retention(RUNTIME)
+@Documented
+public @interface Capitalized {
+ CapitalizeType type() default Capitalize.FIRST;
+ String message() default "has incorrect capitalization"
+} </programlisting>
+
+ <para><literal>type</literal> is a parameter describing how the property
+ should to be capitalized. This is a user parameter fully dependant on the
+ annotation business.</para>
+
+ <para><literal>message</literal> is the default string used to describe
+ the constraint violation and is mandatory. You can hard code the string or
+ you can externalize part/all of it through the Java ResourceBundle
+ mechanism. Parameters values are going to be injected inside the message
+ when the <literal>{parameter}</literal> string is found (in our example
+ <literal>Capitalization is not {type}</literal> would generate
+ <literal>Capitalization is not FIRST</literal> ), externalizing the whole
+ string in <filename>ValidatorMessages.properties</filename> is considered
+ good practice. See <xref linkend="validator-defineconstraints-error" />
+ .</para>
+
+ <programlisting>@ValidatorClass(CapitalizedValidator.class)
+@Target(METHOD)
+@Retention(RUNTIME)
+@Documented
+public @interface Capitalized {
+ CapitalizeType type() default Capitalize.FIRST;
+ String message() default "{validator.capitalized}";
+}
+
+
+#in ValidatorMessages.properties
+validator.capitalized = <literal>Capitalization is not {type}</literal>
+ </programlisting>
+
+ <para>As you can see the {} notation is recursive.</para>
+
+ <para>To link a descriptor to its validator implementation, we use the
+ <literal>@ValidatorClass</literal> meta-annotation. The validator class
+ parameter must name a class which implements
+ <literal>Validator<ConstraintAnnotation></literal> .</para>
+
+ <para>We now have to implement the validator (ie. the rule checking
+ implementation). A validation implementation can check the value of the a
+ property (by implementing <literal>PropertyConstraint</literal> ) and/or
+ can modify the hibernate mapping metadata to express the constraint at the
+ database level (by implementing
+ <literal>PersistentClassConstraint</literal> )</para>
+
+ <programlisting>public class CapitalizedValidator
+ implements Validator<Capitalized>, PropertyConstraint {
+ private CapitalizeType type;
+
+ //part of the Validator<Annotation> contract,
+ //allows to get and use the annotation values
+ public void initialize(Capitalized parameters) {
+ type = parameters.type();
+ }
+
+ //part of the property constraint contract
+ public boolean isValid(Object value) {
+ if (value==null) return true;
+ if ( !(value instanceof String) ) return false;
+ String string = (String) value;
+ if (type == CapitalizeType.ALL) {
+ return string.equals( string.toUpperCase() );
+ }
+ else {
+ String first = string.substring(0,1);
+ return first.equals( first.toUpperCase();
+ }
+ }
+} </programlisting>
+
+ <para>The <literal>isValid()</literal> method should return false if the
+ constraint has been violated. For more examples, refer to the built-in
+ validator implementations.</para>
+
+ <para>We only have seen property level validation, but you can write a
+ Bean level validation annotation. Instead of receiving the return instance
+ of a property, the bean itself will be passed to the validator. To
+ activate the validation checking, just annotated the bean itself instead.
+ A small sample can be found in the unit test suite.</para>
+
+ <para>If your constraint can be applied multiple times (with different
+ parameters) on the same property or type, you can use the following
+ annotation form:</para>
+
+ <programlisting>@Target(METHOD)
+@Retention(RUNTIME)
+@Documented
+<emphasis role="bold">public @interface Patterns {</emphasis>
+ Pattern[] value();
+}
+
+@Target(METHOD)
+@Retention(RUNTIME)
+@Documented
+(a)ValidatorClass(PatternValidator.class)
+public @interface Pattern {
+ String regexp();
+}</programlisting>
+
+ <para>Basically an annotation containing the value attribute as an array
+ of validator annotations.</para>
+ </section>
+
+ <section>
+ <title>Annotating your domain model</title>
+
+ <para>Since you are already familiar with annotations now, the syntax
+ should be very familiar</para>
+
+ <programlisting>public class Address {
+ private String line1;
+ private String line2;
+ private String zip;
+ private String state;
+ private String country;
+ private long id;
+
+ // a not null string of 20 characters maximum
+ @Length(max=20)
+ @NotNull
+ public String getCountry() {
+ return country;
+ }
+
+ // a non null string
+ @NotNull
+ public String getLine1() {
+ return line1;
+ }
+
+ //no constraint
+ public String getLine2() {
+ return line2;
+ }
+
+ // a not null string of 3 characters maximum
+ @Length(max=3) @NotNull
+ public String getState() {
+ return state;
+ }
+
+ // a not null numeric string of 5 characters maximum
+ // if the string is longer, the message will
+ //be searched in the resource bundle at key 'long'
+ @Length(max=5, message="{long}")
+ @Pattern(regex="[0-9]+")
+ @NotNull
+ public String getZip() {
+ return zip;
+ }
+
+ // should always be true
+ @AssertTrue
+ public boolean isValid() {
+ return true;
+ }
+
+ // a numeric between 1 and 2000
+ @Id @Min(1)
+ @Range(max=2000)
+ public long getId() {
+ return id;
+ }
+} </programlisting>
+
+ <para>While the example only shows public property validation, you can
+ also annotate fields of any kind of visibility</para>
+
+ <programlisting>@MyBeanConstraint(max=45
+public class Dog {
+ @AssertTrue private boolean isMale;
+ @NotNull protected String getName() { ... };
+ ...
+} </programlisting>
+
+ <para>You can also annotate interfaces. Hibernate Validator will check all
+ superclasses and interfaces extended or implemented by a given bean to
+ read the appropriate validator annotations.</para>
+
+ <programlisting>public interface Named {
+ @NotNull String getName();
+ ...
+}
+
+public class Dog implements Named {
+
+ @AssertTrue private boolean isMale;
+
+ public String getName() { ... };
+
+}
+ </programlisting>
+
+ <para>The name property will be checked for nullity when the Dog bean is
+ validated.</para>
+ </section>
+</chapter>
\ No newline at end of file
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolator.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolator.java 2009-02-05 17:41:58 UTC (rev 15906)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolator.java 2009-02-05 17:43:34 UTC (rev 15907)
@@ -30,11 +30,11 @@
import org.hibernate.validation.util.LoggerFactory;
-
/**
* Resource bundle backed message interpolator.
*
* @author Emmanuel Bernard
+ * @author Hardy Ferentschik
*/
public class ResourceBundleMessageInterpolator implements MessageInterpolator {
private static final String DEFAULT_VALIDATION_MESSAGES = "org.hibernate.validation.ValidationMessages";
@@ -63,6 +63,16 @@
defaultResourceBundle = ResourceBundle.getBundle( DEFAULT_VALIDATION_MESSAGES );
}
+ public String interpolate(String message, ConstraintDescriptor constraintDescriptor, Object value) {
+ // probably no need for caching, but it could be done by parameters since the map
+ // is immutable and uniquely built per Validation definition, the comparaison has to be based on == and not equals though
+ return replace( message, constraintDescriptor.getParameters() );
+ }
+
+ public String interpolate(String message, ConstraintDescriptor constraintDescriptor, Object value, Locale locale) {
+ throw new UnsupportedOperationException( "Interpolation for Locale. Has to be done." );
+ }
+
/**
* Search current thread classloader for the resource bundle. If not found, search validator (this) classloader.
*
@@ -101,17 +111,6 @@
return rb;
}
- public String interpolate(String message, ConstraintDescriptor constraintDescriptor, Object value) {
- //probably no need for caching, but it could be done by parameters since the map
- //is immutable and uniquely built per Validation definition, the comparaison has to be based on == and not equals though
- return replace( message, constraintDescriptor.getParameters() );
- }
-
- public String interpolate(String message, ConstraintDescriptor constraintDescriptor, Object value, Locale locale) {
- throw new UnsupportedOperationException( "Interpolation for Locale. Has to be done." );
- }
-
-
private String replace(String message, Map<String, Object> parameters) {
Matcher matcher = messagePattern.matcher( message );
StringBuffer sb = new StringBuffer();
@@ -122,7 +121,6 @@
return sb.toString();
}
-
private String resolveParameter(String token, Map<String, Object> parameters) {
Object variable = parameters.get( token );
if ( variable != null ) {
Added: validator/trunk/hibernate-validator/src/test/resources/org/hibernate/validation/ValidationMessages_de.properties
===================================================================
--- validator/trunk/hibernate-validator/src/test/resources/org/hibernate/validation/ValidationMessages_de.properties (rev 0)
+++ validator/trunk/hibernate-validator/src/test/resources/org/hibernate/validation/ValidationMessages_de.properties 2009-02-05 17:43:34 UTC (rev 15907)
@@ -0,0 +1,11 @@
+# $Id: ValidationMessages.properties 15846 2009-02-02 11:56:15Z hardy.ferentschik $
+validator.notNull=may not be null
+validator.size=size must be between {min} and {max}
+validator.length=length must be between {min} and {max}
+validator.notEmpty=may not be empty
+validator.pattern=must match "{regex}"
+validator.min=must be greater than {value}
+validator.max=must be less than {value}
+validator.null=must be null
+validator.past=must be in the past
+validator.future=must be in the future
15 years, 2 months
Hibernate SVN: r15906 - in validator/trunk/tck-utils: src/main/java/org/hibernate/tck and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: pete.muir(a)jboss.org
Date: 2009-02-05 12:41:58 -0500 (Thu, 05 Feb 2009)
New Revision: 15906
Added:
validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/
validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/AuditAssertion.java
validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/AuditParser.java
validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageProcessor.java
validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageProcessorFactory.java
validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageReport.java
validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/SpecReference.java
Modified:
validator/trunk/tck-utils/pom.xml
Log:
Add Shane's xml audit code, change to Java6 build
Modified: validator/trunk/tck-utils/pom.xml
===================================================================
--- validator/trunk/tck-utils/pom.xml 2009-02-05 17:39:20 UTC (rev 15905)
+++ validator/trunk/tck-utils/pom.xml 2009-02-05 17:41:58 UTC (rev 15906)
@@ -115,8 +115,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
- <source>1.5</source>
- <target>1.5</target>
+ <source>1.6</source>
+ <target>1.6</target>
</configuration>
</plugin>
<plugin>
Added: validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/AuditAssertion.java
===================================================================
--- validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/AuditAssertion.java (rev 0)
+++ validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/AuditAssertion.java 2009-02-05 17:41:58 UTC (rev 15906)
@@ -0,0 +1,51 @@
+package org.hibernate.tck.report;
+
+/**
+ * Represents a single assertion as defined in the audit xml
+ *
+ * @author Shane Bryzak
+ *
+ */
+public class AuditAssertion implements Comparable<AuditAssertion>
+{
+ private String section;
+ private String id;
+ private String text;
+ private String note;
+
+ public AuditAssertion(String section, String id, String text, String note)
+ {
+ this.section = section;
+ this.id = id;
+ this.text = text;
+ this.note = note;
+ }
+
+ public String getSection()
+ {
+ return section;
+ }
+
+ public String getId()
+ {
+ return id;
+ }
+
+ public String getText()
+ {
+ return text;
+ }
+
+ public String getNote()
+ {
+ return note;
+ }
+
+ public int compareTo(AuditAssertion other)
+ {
+ int i = section.compareTo(other.section);
+ return i != 0 ? i : id.compareTo(other.id);
+ }
+
+
+}
Property changes on: validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/AuditAssertion.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/AuditParser.java
===================================================================
--- validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/AuditParser.java (rev 0)
+++ validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/AuditParser.java 2009-02-05 17:41:58 UTC (rev 15906)
@@ -0,0 +1,200 @@
+package org.hibernate.tck.report;
+
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * Parsing utilities for tck-audit.xml
+ *
+ * @author Shane Bryzak
+ *
+ */
+public class AuditParser
+{
+ private String version;
+
+ private Map<String,List<AuditAssertion>> assertions = new HashMap<String,List<AuditAssertion>>();
+
+ private Map<String,String> titles = new HashMap<String,String>();
+
+ private InputStream source;
+
+ public AuditParser(InputStream source)
+ {
+ this.source = source;
+ }
+
+ public String getVersion()
+ {
+ return version;
+ }
+
+ public String getSectionTitle(String sectionId)
+ {
+ return titles.get(sectionId);
+ }
+
+ public Map<String,List<AuditAssertion>> getAssertions()
+ {
+ return assertions;
+ }
+
+ public List<String> getSectionIds()
+ {
+ List<String> sectionIds = new ArrayList<String>(assertions.keySet());
+
+ Collections.sort(sectionIds, new Comparator<String>() {
+ public int compare(String value1, String value2)
+ {
+ String[] parts1 = value1.split("[.]");
+ String[] parts2 = value2.split("[.]");
+
+ for (int i = 0;;i++)
+ {
+ if (parts1.length < (i + 1))
+ {
+ return parts2.length < (i + 1) ? 0 : 0;
+ }
+ else if (parts2.length < (i + 1))
+ {
+ return parts1.length < (i + 1) ? 0 : 1;
+ }
+
+ try
+ {
+ int val1 = Integer.parseInt(parts1[i]);
+ int val2 = Integer.parseInt(parts2[i]);
+
+ if (val1 != val2) return val1 - val2;
+ }
+ catch (NumberFormatException ex)
+ {
+ int comp = parts1[i].compareTo(parts2[i]);
+ if (comp != 0)
+ {
+ return comp;
+ }
+ }
+ }
+ }
+ });
+
+ return sectionIds;
+ }
+
+ /**
+ * Returns a sorted list of assertions for the specified section ID
+ *
+ * @param sectionId
+ * @return
+ */
+ public List<AuditAssertion> getAssertionsForSection(String sectionId)
+ {
+ List<AuditAssertion> sectionAssertions = new ArrayList<AuditAssertion>(assertions.get(sectionId));
+ Collections.sort(sectionAssertions);
+ return sectionAssertions;
+ }
+
+ /**
+ *
+ * @param sectionId
+ * @param assertionId
+ * @return
+ */
+ public boolean hasAssertion(String sectionId, String assertionId)
+ {
+ if (!assertions.containsKey(sectionId)) return false;
+
+ for (AuditAssertion assertion : assertions.get(sectionId))
+ {
+ if (assertion.getId().equals(assertionId)) return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Load the spec assertions defined in tck-audit.xml
+ */
+ public void parse() throws Exception
+ {
+ DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
+
+ Document doc = builder.parse(source);
+ NodeList sectionNodes = doc.getDocumentElement().getChildNodes();
+
+ version = doc.getDocumentElement().getAttribute("version");
+
+ for (int i = 0; i < sectionNodes.getLength(); i++)
+ {
+ if (sectionNodes.item(i) instanceof Element &&
+ "section".equals(sectionNodes.item(i).getNodeName()))
+ {
+ processSectionNode((Element) sectionNodes.item(i));
+ }
+ }
+ }
+
+ private void processSectionNode(Element node)
+ {
+ String sectionId = node.getAttribute("id");
+ titles.put(sectionId, node.getAttribute("title"));
+
+ NodeList assertionNodes = node.getChildNodes();
+
+ for (int i = 0; i < assertionNodes.getLength(); i++)
+ {
+ if (assertionNodes.item(i) instanceof Element &&
+ "assertion".equals(assertionNodes.item(i).getNodeName()))
+ {
+ processAssertionNode(sectionId, (Element) assertionNodes.item(i));
+ }
+ }
+ }
+
+ private void processAssertionNode(String sectionId, Element node)
+ {
+ List<AuditAssertion> value = assertions.get(sectionId);
+ if (value == null)
+ {
+ value = new ArrayList<AuditAssertion>();
+ assertions.put(sectionId, value);
+ }
+
+ String text = null;
+ String note = null;
+
+ for (int i = 0; i < node.getChildNodes().getLength(); i++)
+ {
+ Node child = node.getChildNodes().item(i);
+
+ if (child instanceof Element)
+ {
+ if ("text".equals(child.getNodeName()))
+ {
+ text = child.getTextContent();
+ }
+ else if ("note".equals(child.getNodeName()))
+ {
+ note = child.getTextContent();
+ }
+ }
+ }
+
+ value.add(new AuditAssertion(node.getAttribute("section"),
+ node.getAttribute("id"), text, note));
+ }
+}
Property changes on: validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/AuditParser.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageProcessor.java
===================================================================
--- validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageProcessor.java (rev 0)
+++ validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageProcessor.java 2009-02-05 17:41:58 UTC (rev 15906)
@@ -0,0 +1,105 @@
+package org.hibernate.tck.report;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.hibernate.tck.annotations.SpecAssertion;
+
+import com.sun.mirror.apt.AnnotationProcessor;
+import com.sun.mirror.apt.AnnotationProcessorEnvironment;
+import com.sun.mirror.declaration.AnnotationTypeDeclaration;
+import com.sun.mirror.declaration.Declaration;
+import com.sun.mirror.declaration.MethodDeclaration;
+import com.sun.mirror.util.DeclarationVisitors;
+import com.sun.mirror.util.SimpleDeclarationVisitor;
+
+/**
+ * Annotation processor for generating TCK coverage report
+ *
+ * @author Shane Bryzak
+ */
+public class CoverageProcessor implements AnnotationProcessor
+{
+ private static final String OUTDIR_OPTION_NAME = "-s";
+ private static final String REPORT_FILE_NAME = "coverage.html";
+
+ private static final String AUDIT_FILE_NAME = "tck-audit.xml";
+
+ private final AnnotationProcessorEnvironment env;
+ private final File baseDir;
+
+ private final List<SpecReference> references = new ArrayList<SpecReference>();
+
+ private AuditParser auditParser;
+
+ public CoverageProcessor(AnnotationProcessorEnvironment env)
+ {
+ this.env = env;
+ String baseDirName = env.getOptions().get( OUTDIR_OPTION_NAME );
+ baseDir = new File( baseDirName );
+ baseDir.mkdirs();
+
+ try
+ {
+ auditParser = new AuditParser(new FileInputStream(AUDIT_FILE_NAME));
+ auditParser.parse();
+ }
+ catch (Exception ex)
+ {
+ throw new RuntimeException("Error parsing tck-audit.xml: " +
+ ex.getClass().getName() + " - " + ex.getMessage(), ex);
+ }
+ }
+
+ public void process()
+ {
+ AnnotationTypeDeclaration annotationType = (AnnotationTypeDeclaration)
+ env.getTypeDeclaration(SpecAssertion.class.getCanonicalName());
+
+ for (Declaration d : env.getDeclarationsAnnotatedWith(annotationType))
+ {
+ d.accept(DeclarationVisitors.getDeclarationScanner(
+ new CreateReferenceVisitor(), DeclarationVisitors.NO_OP));
+ }
+
+ annotationType = (AnnotationTypeDeclaration)
+ env.getTypeDeclaration(SpecAssertions.class.getCanonicalName());
+ for (Declaration d : env.getDeclarationsAnnotatedWith(annotationType))
+ {
+ d.accept(DeclarationVisitors.getDeclarationScanner(
+ new CreateReferenceVisitor(), DeclarationVisitors.NO_OP));
+ }
+
+
+ new CoverageReport(references, auditParser).writeToFile(new File(baseDir, REPORT_FILE_NAME));
+ }
+
+ private class CreateReferenceVisitor extends SimpleDeclarationVisitor
+ {
+ public void visitMethodDeclaration(MethodDeclaration d)
+ {
+ SpecAssertions assertions = d.getAnnotation ( SpecAssertions.class );
+ if (assertions != null)
+ {
+ for (SpecAssertion assertion : assertions.value())
+ {
+ SpecReference ref = new SpecReference(
+ assertion.section(), assertion.id(),
+ d.getDeclaringType().getSimpleName(), d.getSimpleName());
+ references.add( ref );
+ }
+ }
+
+ SpecAssertion assertion = d.getAnnotation( SpecAssertion.class );
+ if (assertion != null)
+ {
+ SpecReference ref = new SpecReference(
+ assertion.section(), assertion.id(),
+ d.getDeclaringType().getSimpleName(), d.getSimpleName());
+ references.add( ref );
+ }
+ }
+ }
+}
Property changes on: validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageProcessor.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageProcessorFactory.java
===================================================================
--- validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageProcessorFactory.java (rev 0)
+++ validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageProcessorFactory.java 2009-02-05 17:41:58 UTC (rev 15906)
@@ -0,0 +1,40 @@
+package org.hibernate.tck.report;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Set;
+
+import org.hibernate.tck.annotations.SpecAssertion;
+
+import com.sun.mirror.apt.AnnotationProcessor;
+import com.sun.mirror.apt.AnnotationProcessorEnvironment;
+import com.sun.mirror.apt.AnnotationProcessorFactory;
+import com.sun.mirror.declaration.AnnotationTypeDeclaration;
+
+public class CoverageProcessorFactory implements AnnotationProcessorFactory
+{
+ private static final Collection<String> supportedAnnotations = Collections.unmodifiableCollection(
+ Arrays.asList(
+ SpecAssertion.class.getCanonicalName(),
+ SpecAssertions.class.getCanonicalName()
+ )
+ );
+
+ public AnnotationProcessor getProcessorFor(Set<AnnotationTypeDeclaration> annotationTypeDeclarations,
+ AnnotationProcessorEnvironment env)
+ {
+ return new CoverageProcessor(env);
+ }
+
+ public Collection<String> supportedAnnotationTypes()
+ {
+ return supportedAnnotations;
+ }
+
+ public Collection<String> supportedOptions()
+ {
+ return null;
+ }
+
+}
Property changes on: validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageProcessorFactory.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageReport.java
===================================================================
--- validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageReport.java (rev 0)
+++ validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageReport.java 2009-02-05 17:41:58 UTC (rev 15906)
@@ -0,0 +1,253 @@
+package org.hibernate.tck.report;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Generates the TCK spec coverage report
+ *
+ * @author Shane Bryzak
+ */
+public class CoverageReport
+{
+ /*
+ * References to the spec assertions made by the tck tests
+ */
+ private final Map<String,List<SpecReference>> references;
+
+ private AuditParser auditParser;
+
+ public CoverageReport(List<SpecReference> references, AuditParser auditParser)
+ {
+ this.references = new HashMap<String,List<SpecReference>>();
+
+ for (SpecReference ref : references)
+ {
+ if (!this.references.containsKey(ref.getSection()))
+ {
+ this.references.put(ref.getSection(), new ArrayList<SpecReference>());
+ }
+
+ this.references.get(ref.getSection()).add(ref);
+ }
+
+ this.auditParser = auditParser;
+ }
+
+ public void generate(OutputStream out) throws IOException
+ {
+ writeHeader(out);
+ writeCoverage(out);
+ writeUnmatched(out);
+ writeFooter(out);
+ }
+
+ private void writeHeader(OutputStream out) throws IOException
+ {
+ StringBuilder sb = new StringBuilder();
+
+ sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+ sb.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n");
+ sb.append("\"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">\n");
+ sb.append("<html>\n");
+ sb.append("<head><title>JSR-299 TCK Coverage Report</title>\n");
+
+ sb.append("<style type=\"text/css\">\n");
+ sb.append(" .code {\n");
+ sb.append(" float: left;\n");
+ sb.append(" font-weight: bold;\n");
+ sb.append(" width: 50px;\n");
+ sb.append(" margin-top: 0px;\n");
+ sb.append(" height: 100%; }\n");
+ sb.append(" .results {\n");
+ sb.append(" margin-left: 50px; }\n");
+ sb.append(" .description {\n");
+ sb.append(" margin-top: 2px;\n");
+ sb.append(" margin-bottom: 2px; }\n");
+ sb.append(" .sectionHeader {\n");
+ sb.append(" font-weight: bold; }\n");
+ sb.append(" .noCoverage {\n");
+ sb.append(" margin-top: 2px;\n");
+ sb.append(" margin-bottom: 2px;\n");
+ sb.append(" font-weight: bold;\n");
+ sb.append(" font-style: italic;\n");
+ sb.append(" color: #ff0000; }\n");
+ sb.append(" .coverageHeader {\n");
+ sb.append(" font-weight: bold;\n");
+ sb.append(" text-decoration: underline;\n");
+ sb.append(" margin-top: 2px;\n");
+ sb.append(" margin-bottom: 2px; }\n");
+ sb.append(" .pass {\n");
+ sb.append(" background-color: #dfd; }\n");
+ sb.append(" .fail {\n");
+ sb.append(" background-color: #fdd; }\n");
+
+ sb.append("</style>\n");
+
+ sb.append("</head><body>");
+ sb.append("<h1>JSR-299 TCK Coverage</h1>");
+ sb.append("<h2>");
+ sb.append(auditParser.getVersion());
+ sb.append("</h2>\n");
+
+ out.write(sb.toString().getBytes());
+ }
+
+ private void writeCoverage(OutputStream out) throws IOException
+ {
+ for (String sectionId : auditParser.getSectionIds())
+ {
+ out.write(("<div class=\"sectionHeader\">Section " + sectionId + " - " +
+ auditParser.getSectionTitle(sectionId) + "</div>\n").getBytes());
+
+ List<AuditAssertion> sectionAssertions = auditParser.getAssertionsForSection(sectionId);
+
+ if (sectionAssertions != null && !sectionAssertions.isEmpty())
+ {
+ StringBuilder sb = new StringBuilder();
+
+ for (AuditAssertion assertion : sectionAssertions)
+ {
+ List<SpecReference> coverage = getCoverageForAssertion(sectionId, assertion.getId());
+
+ sb.append(" <div class=\"" + (coverage.isEmpty() ? "fail" : "pass") + "\">\n");
+
+ sb.append(" <span class=\"code\">");
+ sb.append(assertion.getId());
+ sb.append(")");
+ sb.append("</span>\n");
+
+ sb.append(" <div class=\"results\">");
+ sb.append("<p class=\"description\">");
+ sb.append(assertion.getText());
+ sb.append("</p>\n");
+
+ sb.append(" <div class=\"coverage\">\n");
+ sb.append(" <p class=\"coverageHeader\">Coverage</p>\n");
+
+ if (coverage.isEmpty())
+ {
+ sb.append(" <p class=\"noCoverage\">No tests exist for this assertion</p>\n");
+ }
+ else
+ {
+ for (SpecReference ref : coverage)
+ {
+ sb.append(" <p>");
+ sb.append(ref.getClassName());
+ sb.append(".");
+ sb.append(ref.getMethodName());
+ sb.append("()");
+ sb.append("</p>\n");
+ }
+ }
+
+ sb.append(" </div>\n </div>\n</div>");
+ }
+
+ out.write(sb.toString().getBytes());
+ }
+ }
+ }
+
+ private void writeUnmatched(OutputStream out) throws IOException
+ {
+ List<SpecReference> unmatched = new ArrayList<SpecReference>();
+
+ for (String sectionId : references.keySet())
+ {
+ for (SpecReference ref : references.get(sectionId))
+ {
+ if (!auditParser.hasAssertion(ref.getSection(), ref.getAssertion()))
+ {
+ unmatched.add(ref);
+ }
+ }
+ }
+
+ if (unmatched.isEmpty()) return;
+
+ StringBuilder sb = new StringBuilder();
+
+ sb.append("<h3>Unmatched tests</h3>\n");
+ sb.append(String.format("<p>The following %d tests do not match any known assertions:</p>",
+ unmatched.size()));
+
+ sb.append("<table border=\"1\" cellspacing=\"0\" cellpadding=\"0\">\n");
+ sb.append(" <tr><th>Section</th><th>Assertion</th><th>Test Class</th><th>Test Method</th></tr>\n");
+
+ for (SpecReference ref : unmatched)
+ {
+ sb.append("<tr>");
+
+ sb.append("<td>");
+ sb.append(ref.getSection());
+ sb.append("</td>");
+
+ sb.append("<td>");
+ sb.append(ref.getAssertion());
+ sb.append("</td>");
+
+ sb.append("<td>");
+ sb.append(ref.getClassName());
+ sb.append("</td>");
+
+ sb.append("<td>");
+ sb.append(ref.getMethodName());
+ sb.append("()");
+ sb.append("</td>");
+
+ sb.append("</tr>");
+ }
+
+ sb.append("</table>");
+
+ out.write(sb.toString().getBytes());
+ }
+
+ private List<SpecReference> getCoverageForAssertion(String sectionId, String assertionId)
+ {
+ List<SpecReference> refs = new ArrayList<SpecReference>();
+
+ if (references.containsKey(sectionId))
+ {
+ for (SpecReference ref : references.get(sectionId))
+ {
+ if (ref.getAssertion().equals(assertionId))
+ {
+ refs.add(ref);
+ }
+ }
+ }
+
+ return refs;
+ }
+
+ private void writeFooter(OutputStream out) throws IOException
+ {
+ out.write("</table>".getBytes());
+ out.write("</body></html>".getBytes());
+ }
+
+ public void writeToFile(File file)
+ {
+ try
+ {
+ FileOutputStream out = new FileOutputStream(file);
+ generate(out);
+ out.flush();
+ out.close();
+ }
+ catch (IOException ex)
+ {
+ throw new RuntimeException("Error generating report file", ex);
+ }
+ }
+}
Property changes on: validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/CoverageReport.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/SpecReference.java
===================================================================
--- validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/SpecReference.java (rev 0)
+++ validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/SpecReference.java 2009-02-05 17:41:58 UTC (rev 15906)
@@ -0,0 +1,42 @@
+package org.hibernate.tck.report;
+
+/**
+ * Represents the metadata for a single instance of @SpecAssertion
+ *
+ * @author Shane Bryzak
+ */
+public class SpecReference
+{
+ private String section;
+ private String assertion;
+ private String className;
+ private String methodName;
+
+ SpecReference(String section, String assertion, String className, String methodName)
+ {
+ this.section = section;
+ this.assertion = assertion;
+ this.className = className;
+ this.methodName = methodName;
+ }
+
+ public String getSection()
+ {
+ return section;
+ }
+
+ public String getAssertion()
+ {
+ return assertion;
+ }
+
+ public String getClassName()
+ {
+ return className;
+ }
+
+ public String getMethodName()
+ {
+ return methodName;
+ }
+}
Property changes on: validator/trunk/tck-utils/src/main/java/org/hibernate/tck/report/SpecReference.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
15 years, 2 months
Hibernate SVN: r15904 - in validator/trunk/hibernate-validator/src: main/java/org/hibernate/validation/engine and 3 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-02-05 11:10:27 -0500 (Thu, 05 Feb 2009)
New Revision: 15904
Added:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/HibernateValidationProvider.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/Version.java
Removed:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/Version.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/HibernateValidationProvider.java
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.java
validator/trunk/hibernate-validator/src/main/resources/META-INF/services/javax.validation.spi.ValidationProvider
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/bootstrap/ValidationTest.java
Log:
some class refactoring
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/HibernateValidationProvider.java (from rev 15883, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/HibernateValidationProvider.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/HibernateValidationProvider.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/HibernateValidationProvider.java 2009-02-05 16:10:27 UTC (rev 15904)
@@ -0,0 +1,69 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.validation;
+
+import javax.validation.Configuration;
+import javax.validation.ValidationException;
+import javax.validation.ValidatorFactory;
+import javax.validation.spi.BootstrapState;
+import javax.validation.spi.ConfigurationState;
+import javax.validation.spi.ValidationProvider;
+
+import org.hibernate.validation.engine.HibernateValidatorConfiguration;
+import org.hibernate.validation.engine.ConfigurationImpl;
+import org.hibernate.validation.engine.ValidatorFactoryImpl;
+
+/**
+ * Default implementation of <code>ValidationProvider</code> within Hibernate validator.
+ *
+ * @author Emmanuel Bernard
+ * @author Hardy Ferentschik
+ */
+public class HibernateValidationProvider implements ValidationProvider {
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isSuitable(Class<? extends Configuration<?>> builderClass) {
+ return builderClass == HibernateValidatorConfiguration.class;
+ }
+
+ public <T extends Configuration<T>> T createSpecializedConfiguration(BootstrapState state, Class<T> configurationClass) {
+ if ( !isSuitable( configurationClass ) ) {
+ throw new ValidationException(
+ "Illegal call to createSpecializedConfiguration() for a non suitable provider"
+ );
+ }
+ //cast protected by isSuitable call
+ return configurationClass.cast( new ConfigurationImpl( this ) );
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Configuration<?> createGenericConfiguration(BootstrapState state) {
+ return new ConfigurationImpl( state );
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public ValidatorFactory buildValidatorFactory(ConfigurationState configurationState) {
+ return new ValidatorFactoryImpl( configurationState );
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/HibernateValidationProvider.java
___________________________________________________________________
Name: svn:executable
+ *
Name: svn:keywords
+ Id
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/Version.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/Version.java 2009-02-05 11:55:06 UTC (rev 15903)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/Version.java 2009-02-05 16:10:27 UTC (rev 15904)
@@ -1,61 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.validation;
-
-import java.net.URL;
-import java.util.jar.Attributes;
-import java.util.jar.Manifest;
-
-import org.slf4j.Logger;
-
-/**
- * @author Hardy Ferentschik
- */
-public class Version {
- private static final Logger log = org.hibernate.validation.util.LoggerFactory.make();
-
- static {
- Class clazz = Version.class;
- String classFileName = clazz.getSimpleName() + ".class";
- String classFilePath = clazz.getCanonicalName().replace( '.', '/' )
- + ".class";
- String pathToThisClass =
- clazz.getResource( classFileName ).toString();
- String pathToManifest = pathToThisClass.substring( 0, pathToThisClass.indexOf( classFilePath ) - 1 )
- + "/META-INF/MANIFEST.MF";
- log.trace( "Manifest file {}", pathToManifest );
- Manifest manifest = null;
- String version;
- try {
- manifest = new Manifest( new URL( pathToManifest ).openStream() );
- }
- catch ( Exception e ) {
- log.warn( "Unable to determine version of Hibernate Validator" );
- }
- if ( manifest == null ) {
- version = "?";
- }
- else {
- version = manifest.getMainAttributes().getValue( Attributes.Name.IMPLEMENTATION_VERSION );
- }
- log.info( "Hibernate Commons Annotations {}", version );
- }
-
- public static void touch() {
- }
-}
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.java 2009-02-05 11:55:06 UTC (rev 15903)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.java 2009-02-05 16:10:27 UTC (rev 15904)
@@ -33,7 +33,7 @@
import javax.validation.spi.ConfigurationState;
import javax.validation.spi.ValidationProvider;
-import org.hibernate.validation.Version;
+import org.hibernate.validation.util.Version;
/**
* @author Emmanuel Bernard
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/HibernateValidationProvider.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/HibernateValidationProvider.java 2009-02-05 11:55:06 UTC (rev 15903)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/HibernateValidationProvider.java 2009-02-05 16:10:27 UTC (rev 15904)
@@ -1,65 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-* http://www.apache.org/licenses/LICENSE-2.0
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*/
-package org.hibernate.validation.engine;
-
-import javax.validation.Configuration;
-import javax.validation.ValidationException;
-import javax.validation.ValidatorFactory;
-import javax.validation.spi.BootstrapState;
-import javax.validation.spi.ConfigurationState;
-import javax.validation.spi.ValidationProvider;
-
-/**
- * Default implementation of <code>ValidationProvider</code> within Hibernate validator.
- *
- * @author Emmanuel Bernard
- * @author Hardy Ferentschik
- */
-public class HibernateValidationProvider implements ValidationProvider {
-
- /**
- * {@inheritDoc}
- */
- public boolean isSuitable(Class<? extends Configuration<?>> builderClass) {
- return builderClass == HibernateValidatorConfiguration.class;
- }
-
- public <T extends Configuration<T>> T createSpecializedConfiguration(BootstrapState state, Class<T> configurationClass) {
- if ( !isSuitable( configurationClass ) ) {
- throw new ValidationException(
- "Illegal call to createSpecializedConfiguration() for a non suitable provider"
- );
- }
- //cast protected by isSuitable call
- return configurationClass.cast( new ConfigurationImpl( this ) );
- }
-
- /**
- * {@inheritDoc}
- */
- public Configuration<?> createGenericConfiguration(BootstrapState state) {
- return new ConfigurationImpl( state );
- }
-
- /**
- * {@inheritDoc}
- */
- public ValidatorFactory buildValidatorFactory(ConfigurationState configurationState) {
- return new ValidatorFactoryImpl( configurationState );
- }
-}
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/Version.java (from rev 15883, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/Version.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/Version.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/Version.java 2009-02-05 16:10:27 UTC (rev 15904)
@@ -0,0 +1,61 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+* http://www.apache.org/licenses/LICENSE-2.0
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.hibernate.validation.util;
+
+import java.net.URL;
+import java.util.jar.Attributes;
+import java.util.jar.Manifest;
+
+import org.slf4j.Logger;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class Version {
+ private static final Logger log = org.hibernate.validation.util.LoggerFactory.make();
+
+ static {
+ Class clazz = Version.class;
+ String classFileName = clazz.getSimpleName() + ".class";
+ String classFilePath = clazz.getCanonicalName().replace( '.', '/' )
+ + ".class";
+ String pathToThisClass =
+ clazz.getResource( classFileName ).toString();
+ String pathToManifest = pathToThisClass.substring( 0, pathToThisClass.indexOf( classFilePath ) - 1 )
+ + "/META-INF/MANIFEST.MF";
+ log.trace( "Manifest file {}", pathToManifest );
+ Manifest manifest = null;
+ String version;
+ try {
+ manifest = new Manifest( new URL( pathToManifest ).openStream() );
+ }
+ catch ( Exception e ) {
+ log.warn( "Unable to determine version of Hibernate Validator" );
+ }
+ if ( manifest == null ) {
+ version = "?";
+ }
+ else {
+ version = manifest.getMainAttributes().getValue( Attributes.Name.IMPLEMENTATION_VERSION );
+ }
+ log.info( "Hibernate Commons Annotations {}", version );
+ }
+
+ public static void touch() {
+ }
+}
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/util/Version.java
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: validator/trunk/hibernate-validator/src/main/resources/META-INF/services/javax.validation.spi.ValidationProvider
===================================================================
--- validator/trunk/hibernate-validator/src/main/resources/META-INF/services/javax.validation.spi.ValidationProvider 2009-02-05 11:55:06 UTC (rev 15903)
+++ validator/trunk/hibernate-validator/src/main/resources/META-INF/services/javax.validation.spi.ValidationProvider 2009-02-05 16:10:27 UTC (rev 15904)
@@ -1 +1 @@
-org.hibernate.validation.engine.HibernateValidationProvider
\ No newline at end of file
+org.hibernate.validation.HibernateValidationProvider
\ No newline at end of file
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/bootstrap/ValidationTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/bootstrap/ValidationTest.java 2009-02-05 11:55:06 UTC (rev 15903)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/bootstrap/ValidationTest.java 2009-02-05 16:10:27 UTC (rev 15904)
@@ -43,7 +43,7 @@
import org.junit.Test;
import org.hibernate.validation.engine.HibernateValidatorConfiguration;
-import org.hibernate.validation.engine.HibernateValidationProvider;
+import org.hibernate.validation.HibernateValidationProvider;
import org.hibernate.validation.constraints.NotNullValidator;
import org.hibernate.validation.eg.Customer;
import org.hibernate.validation.engine.ConfigurationImpl;
15 years, 2 months
Hibernate SVN: r15903 - validator/trunk/validation-api/src/main/java/javax/validation.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-02-05 06:55:06 -0500 (Thu, 05 Feb 2009)
New Revision: 15903
Modified:
validator/trunk/validation-api/src/main/java/javax/validation/UnexpectedTypeForConstraintException.java
Log:
BVAL-99 javadoc
Modified: validator/trunk/validation-api/src/main/java/javax/validation/UnexpectedTypeForConstraintException.java
===================================================================
--- validator/trunk/validation-api/src/main/java/javax/validation/UnexpectedTypeForConstraintException.java 2009-02-05 11:53:49 UTC (rev 15902)
+++ validator/trunk/validation-api/src/main/java/javax/validation/UnexpectedTypeForConstraintException.java 2009-02-05 11:55:06 UTC (rev 15903)
@@ -20,7 +20,7 @@
import javax.validation.ValidationException;
/**
- * Exception raised in the case that the constraint validator resolution returns more than one possible validators for
+ * Exception raised in the case that the constraint validator resolution cannot determine a suitable validators for
* a given type.
*
* @author Hardy Ferentschik
15 years, 2 months