Hibernate SVN: r16322 - core/branches/antlr3/src/main/antlr.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2009-04-14 12:41:30 -0400 (Tue, 14 Apr 2009)
New Revision: 16322
Removed:
core/branches/antlr3/src/main/antlr/sql-gen.g
Log:
creating antlr3 branch
Deleted: core/branches/antlr3/src/main/antlr/sql-gen.g
===================================================================
--- core/branches/antlr3/src/main/antlr/sql-gen.g 2009-04-14 16:41:16 UTC (rev 16321)
+++ core/branches/antlr3/src/main/antlr/sql-gen.g 2009-04-14 16:41:30 UTC (rev 16322)
@@ -1,427 +0,0 @@
-header
-{
-// $Id: sql-gen.g 10001 2006-06-08 21:08:04Z steve.ebersole(a)jboss.com $
-package org.hibernate.hql.antlr;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-}
-/**
- * SQL Generator Tree Parser, providing SQL rendering of SQL ASTs produced by the previous phase, HqlSqlWalker. All
- * syntax decoration such as extra spaces, lack of spaces, extra parens, etc. should be added by this class.
- * <br>
- * This grammar processes the HQL/SQL AST and produces an SQL string. The intent is to move dialect-specific
- * code into a sub-class that will override some of the methods, just like the other two grammars in this system.
- * @author Joshua Davis (joshua(a)hibernate.org)
- */
-class SqlGeneratorBase extends TreeParser;
-
-options {
- // Note: importVocab and exportVocab cause ANTLR to share the token type numbers between the
- // two grammars. This means that the token type constants from the source tree are the same
- // as those in the target tree. If this is not the case, tree translation can result in
- // token types from the *source* tree being present in the target tree.
- importVocab=HqlSql; // import definitions from "HqlSql"
- exportVocab=Sql; // Call the resulting definitions "Sql"
- buildAST=false; // Don't build an AST.
-}
-
-{
- private static Logger log = LoggerFactory.getLogger(SqlGeneratorBase.class);
-
- /** the buffer resulting SQL statement is written to */
- private StringBuffer buf = new StringBuffer();
-
- protected void out(String s) {
- buf.append(s);
- }
-
- /**
- * Returns the last character written to the output, or -1 if there isn't one.
- */
- protected int getLastChar() {
- int len = buf.length();
- if ( len == 0 )
- return -1;
- else
- return buf.charAt( len - 1 );
- }
-
- /**
- * Add a aspace if the previous token was not a space or a parenthesis.
- */
- protected void optionalSpace() {
- // Implemented in the sub-class.
- }
-
- protected void out(AST n) {
- out(n.getText());
- }
-
- protected void separator(AST n, String sep) {
- if (n.getNextSibling() != null)
- out(sep);
- }
-
- protected boolean hasText(AST a) {
- String t = a.getText();
- return t != null && t.length() > 0;
- }
-
- protected void fromFragmentSeparator(AST a) {
- // moved this impl into the subclass...
- }
-
- protected void nestedFromFragment(AST d,AST parent) {
- // moved this impl into the subclass...
- }
-
- protected StringBuffer getStringBuffer() {
- return buf;
- }
-
- protected void nyi(AST n) {
- throw new UnsupportedOperationException("Unsupported node: " + n);
- }
-
- protected void beginFunctionTemplate(AST m,AST i) {
- // if template is null we just write the function out as it appears in the hql statement
- out(i);
- out("(");
- }
-
- protected void endFunctionTemplate(AST m) {
- out(")");
- }
-
- protected void commaBetweenParameters(String comma) {
- out(comma);
- }
-}
-
-statement
- : selectStatement
- | updateStatement
- | deleteStatement
- | insertStatement
- ;
-
-selectStatement
- : #(SELECT { out("select "); }
- selectClause
- from
- ( #(WHERE { out(" where "); } whereExpr ) )?
- ( #(GROUP { out(" group by "); } groupExprs ( #(HAVING { out(" having "); } booleanExpr[false]) )? ) )?
- ( #(ORDER { out(" order by "); } orderExprs ) )?
- )
- ;
-
-// Note: eats the FROM token node, as it is not valid in an update statement.
-// It's outlived its usefulness after analysis phase :)
-// TODO : needed to use conditionList directly here and deleteStatement, as whereExprs no longer works for this stuff
-updateStatement
- : #(UPDATE { out("update "); }
- #( FROM fromTable )
- setClause
- (whereClause)?
- )
- ;
-
-deleteStatement
- // Note: not space needed at end of "delete" because the from rule included one before the "from" it outputs
- : #(DELETE { out("delete"); }
- from
- (whereClause)?
- )
- ;
-
-insertStatement
- : #(INSERT { out( "insert " ); }
- i:INTO { out( i ); out( " " ); }
- selectStatement
- )
- ;
-
-setClause
- // Simply re-use comparisionExpr, because it already correctly defines the EQ rule the
- // way it is needed here; not the most aptly named, but ah
- : #( SET { out(" set "); } comparisonExpr[false] ( { out(", "); } comparisonExpr[false] )* )
- ;
-
-whereClause
- : #(WHERE { out(" where "); } whereClauseExpr )
- ;
-
-whereClauseExpr
- : (SQL_TOKEN) => conditionList
- | booleanExpr[ false ]
- ;
-
-orderExprs
- // TODO: remove goofy space before the comma when we don't have to regression test anymore.
- : ( expr ) (dir:orderDirection { out(" "); out(dir); })? ( {out(", "); } orderExprs)?
- ;
-
-groupExprs
- // TODO: remove goofy space before the comma when we don't have to regression test anymore.
- : expr ( {out(" , "); } groupExprs)?
- ;
-
-orderDirection
- : ASCENDING
- | DESCENDING
- ;
-
-whereExpr
- // Expect the filter subtree, followed by the theta join subtree, followed by the HQL condition subtree.
- // Might need parens around the HQL condition if there is more than one subtree.
- // Put 'and' between each subtree.
- : filters
- ( { out(" and "); } thetaJoins )?
- ( { out(" and "); } booleanExpr [ true ] )?
- | thetaJoins
- ( { out(" and "); } booleanExpr [ true ] )?
- | booleanExpr[false]
- ;
-
-filters
- : #(FILTERS conditionList )
- ;
-
-thetaJoins
- : #(THETA_JOINS conditionList )
- ;
-
-conditionList
- : sqlToken ( { out(" and "); } conditionList )?
- ;
-
-selectClause
- : #(SELECT_CLAUSE (distinctOrAll)? ( selectColumn )+ )
- ;
-
-selectColumn
- : p:selectExpr (sc:SELECT_COLUMNS { out(sc); } )? { separator( (sc != null) ? sc : p,", "); }
- ;
-
-selectExpr
- : e:selectAtom { out(e); }
- | count
- | #(CONSTRUCTOR (DOT | IDENT) ( selectColumn )+ )
- | methodCall
- | aggregate
- | c:constant { out(c); }
- | arithmeticExpr
- | param:PARAM { out(param); }
- | sn:SQL_NODE { out(sn); }
- | { out("("); } selectStatement { out(")"); }
- ;
-
-count
- : #(COUNT { out("count("); } ( distinctOrAll ) ? countExpr { out(")"); } )
- ;
-
-distinctOrAll
- : DISTINCT { out("distinct "); }
- | ALL { out("all "); }
- ;
-
-countExpr
- // Syntacitic predicate resolves star all by itself, avoiding a conflict with STAR in expr.
- : ROW_STAR { out("*"); }
- | simpleExpr
- ;
-
-selectAtom
- : DOT
- | SQL_TOKEN
- | ALIAS_REF
- | SELECT_EXPR
- ;
-
-// The from-clause piece is all goofed up. Currently, nodes of type FROM_FRAGMENT
-// and JOIN_FRAGMENT can occur at any level in the FromClause sub-tree. We really
-// should come back and clean this up at some point; which I think will require
-// a post-HqlSqlWalker phase to "re-align" the FromElements in a more sensible
-// manner.
-from
- : #(f:FROM { out(" from "); }
- (fromTable)* )
- ;
-
-fromTable
- // Write the table node (from fragment) and all the join fragments associated with it.
- : #( a:FROM_FRAGMENT { out(a); } (tableJoin [ a ])* { fromFragmentSeparator(a); } )
- | #( b:JOIN_FRAGMENT { out(b); } (tableJoin [ b ])* { fromFragmentSeparator(b); } )
- ;
-
-tableJoin [ AST parent ]
- : #( c:JOIN_FRAGMENT { out(" "); out(c); } (tableJoin [ c ] )* )
- | #( d:FROM_FRAGMENT { nestedFromFragment(d,parent); } (tableJoin [ d ] )* )
- ;
-
-booleanOp[ boolean parens ]
- : #(AND booleanExpr[true] { out(" and "); } booleanExpr[true])
- | #(OR { if (parens) out("("); } booleanExpr[false] { out(" or "); } booleanExpr[false] { if (parens) out(")"); })
- | #(NOT { out(" not ("); } booleanExpr[false] { out(")"); } )
- ;
-
-booleanExpr[ boolean parens ]
- : booleanOp [ parens ]
- | comparisonExpr [ parens ]
- | st:SQL_TOKEN { out(st); } // solely for the purpose of mapping-defined where-fragments
- ;
-
-comparisonExpr[ boolean parens ]
- : binaryComparisonExpression
- | { if (parens) out("("); } exoticComparisonExpression { if (parens) out(")"); }
- ;
-
-binaryComparisonExpression
- : #(EQ expr { out("="); } expr)
- | #(NE expr { out("<>"); } expr)
- | #(GT expr { out(">"); } expr)
- | #(GE expr { out(">="); } expr)
- | #(LT expr { out("<"); } expr)
- | #(LE expr { out("<="); } expr)
- ;
-
-exoticComparisonExpression
- : #(LIKE expr { out(" like "); } expr likeEscape )
- | #(NOT_LIKE expr { out(" not like "); } expr likeEscape)
- | #(BETWEEN expr { out(" between "); } expr { out(" and "); } expr)
- | #(NOT_BETWEEN expr { out(" not between "); } expr { out(" and "); } expr)
- | #(IN expr { out(" in"); } inList )
- | #(NOT_IN expr { out(" not in "); } inList )
- | #(EXISTS { optionalSpace(); out("exists "); } quantified )
- | #(IS_NULL expr) { out(" is null"); }
- | #(IS_NOT_NULL expr) { out(" is not null"); }
- ;
-
-likeEscape
- : ( #(ESCAPE { out(" escape "); } expr) )?
- ;
-
-inList
- : #(IN_LIST { out(" "); } ( parenSelect | simpleExprList ) )
- ;
-
-simpleExprList
- : { out("("); } (e:simpleExpr { separator(e," , "); } )* { out(")"); }
- ;
-
-// A simple expression, or a sub-select with parens around it.
-expr
- : simpleExpr
- | #( VECTOR_EXPR { out("("); } (e:expr { separator(e," , "); } )* { out(")"); } )
- | parenSelect
- | #(ANY { out("any "); } quantified )
- | #(ALL { out("all "); } quantified )
- | #(SOME { out("some "); } quantified )
- ;
-
-quantified
- : { out("("); } ( sqlToken | selectStatement ) { out(")"); }
- ;
-
-parenSelect
- : { out("("); } selectStatement { out(")"); }
- ;
-
-simpleExpr
- : c:constant { out(c); }
- | NULL { out("null"); }
- | addrExpr
- | sqlToken
- | aggregate
- | methodCall
- | count
- | parameter
- | arithmeticExpr
- ;
-
-constant
- : NUM_DOUBLE
- | NUM_FLOAT
- | NUM_INT
- | NUM_LONG
- | QUOTED_STRING
- | CONSTANT
- | JAVA_CONSTANT
- | TRUE
- | FALSE
- | IDENT
- ;
-
-arithmeticExpr
- : additiveExpr
- | multiplicativeExpr
-// | #(CONCAT { out("("); } expr ( { out("||"); } expr )+ { out(")"); } )
- | #(UNARY_MINUS { out("-"); } expr)
- | caseExpr
- ;
-
-additiveExpr
- : #(PLUS expr { out("+"); } expr)
- | #(MINUS expr { out("-"); } nestedExprAfterMinusDiv)
- ;
-
-multiplicativeExpr
- : #(STAR nestedExpr { out("*"); } nestedExpr)
- | #(DIV nestedExpr { out("/"); } nestedExprAfterMinusDiv)
- ;
-
-nestedExpr
- // Generate parens around nested additive expressions, use a syntactic predicate to avoid conflicts with 'expr'.
- : (additiveExpr) => { out("("); } additiveExpr { out(")"); }
- | expr
- ;
-
-nestedExprAfterMinusDiv
- // Generate parens around nested arithmetic expressions, use a syntactic predicate to avoid conflicts with 'expr'.
- : (arithmeticExpr) => { out("("); } arithmeticExpr { out(")"); }
- | expr
- ;
-
-caseExpr
- : #(CASE { out("case"); }
- ( #(WHEN { out( " when "); } booleanExpr[false] { out(" then "); } expr) )+
- ( #(ELSE { out(" else "); } expr) )?
- { out(" end"); } )
- | #(CASE2 { out("case "); } expr
- ( #(WHEN { out( " when "); } expr { out(" then "); } expr) )+
- ( #(ELSE { out(" else "); } expr) )?
- { out(" end"); } )
- ;
-
-aggregate
- : #(a:AGGREGATE { out(a); out("("); } expr { out(")"); } )
- ;
-
-
-methodCall
- : #(m:METHOD_CALL i:METHOD_NAME { beginFunctionTemplate(m,i); }
- ( #(EXPR_LIST (arguments)? ) )?
- { endFunctionTemplate(m); } )
- ;
-
-arguments
- : expr ( { commaBetweenParameters(", "); } expr )*
- ;
-
-parameter
- : n:NAMED_PARAM { out(n); }
- | p:PARAM { out(p); }
- ;
-
-addrExpr
- : #(r:DOT . .) { out(r); }
- | i:ALIAS_REF { out(i); }
- | j:INDEX_OP { out(j); }
- ;
-
-sqlToken
- : t:SQL_TOKEN { out(t); }
- ;
-
15 years, 7 months
Hibernate SVN: r16321 - core/branches/antlr3/src/main/antlr.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2009-04-14 12:41:16 -0400 (Tue, 14 Apr 2009)
New Revision: 16321
Removed:
core/branches/antlr3/src/main/antlr/hql-sql.g
Log:
creating antlr3 branch
Deleted: core/branches/antlr3/src/main/antlr/hql-sql.g
===================================================================
--- core/branches/antlr3/src/main/antlr/hql-sql.g 2009-04-14 16:41:06 UTC (rev 16320)
+++ core/branches/antlr3/src/main/antlr/hql-sql.g 2009-04-14 16:41:16 UTC (rev 16321)
@@ -1,699 +0,0 @@
-header
-{
-// $Id: hql-sql.g 10001 2006-06-08 21:08:04Z steve.ebersole(a)jboss.com $
-package org.hibernate.hql.antlr;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-}
-
-/**
- * Hibernate Query Language to SQL Tree Transform.<br>
- * This is a tree grammar that transforms an HQL AST into a intermediate SQL AST
- * with bindings to Hibernate interfaces (Queryable, etc.). The Hibernate specific methods
- * are all implemented in the HqlSqlWalker subclass, allowing the ANTLR-generated class
- * to have only the minimum dependencies on the Hibernate code base. This will also allow
- * the sub-class to be easily edited using an IDE (most IDE's don't support ANTLR).
- * <br>
- * <i>NOTE:</i> The java class is generated from hql-sql.g by ANTLR.
- * <i>DO NOT EDIT THE GENERATED JAVA SOURCE CODE.</i>
- * @author Joshua Davis (joshua(a)hibernate.org)
- */
-class HqlSqlBaseWalker extends TreeParser;
-
-options
-{
- // Note: importVocab and exportVocab cause ANTLR to share the token type numbers between the
- // two grammars. This means that the token type constants from the source tree are the same
- // as those in the target tree. If this is not the case, tree translation can result in
- // token types from the *source* tree being present in the target tree.
- importVocab=Hql; // import definitions from "Hql"
- exportVocab=HqlSql; // Call the resulting definitions "HqlSql"
- buildAST=true;
-}
-
-tokens
-{
- FROM_FRAGMENT; // A fragment of SQL that represents a table reference in a FROM clause.
- IMPLIED_FROM; // An implied FROM element.
- JOIN_FRAGMENT; // A JOIN fragment.
- SELECT_CLAUSE;
- LEFT_OUTER;
- RIGHT_OUTER;
- ALIAS_REF; // An IDENT that is a reference to an entity via it's alias.
- PROPERTY_REF; // A DOT that is a reference to a property in an entity.
- SQL_TOKEN; // A chunk of SQL that is 'rendered' already.
- SELECT_COLUMNS; // A chunk of SQL representing a bunch of select columns.
- SELECT_EXPR; // A select expression, generated from a FROM element.
- THETA_JOINS; // Root of theta join condition subtree.
- FILTERS; // Root of the filters condition subtree.
- METHOD_NAME; // An IDENT that is a method name.
- NAMED_PARAM; // A named parameter (:foo).
- BOGUS; // Used for error state detection, etc.
-}
-
-// -- Declarations --
-{
- private static Logger log = LoggerFactory.getLogger( HqlSqlBaseWalker.class );
-
- private int level = 0;
- private boolean inSelect = false;
- private boolean inFunctionCall = false;
- private boolean inCase = false;
- private boolean inFrom = false;
- private int statementType;
- private String statementTypeName;
- // Note: currentClauseType tracks the current clause within the current
- // statement, regardless of level; currentTopLevelClauseType, on the other
- // hand, tracks the current clause within the top (or primary) statement.
- // Thus, currentTopLevelClauseType ignores the clauses from any subqueries.
- private int currentClauseType;
- private int currentTopLevelClauseType;
- private int currentStatementType;
-
- public final boolean isSubQuery() {
- return level > 1;
- }
-
- public final boolean isInFrom() {
- return inFrom;
- }
-
- public final boolean isInFunctionCall() {
- return inFunctionCall;
- }
-
- public final boolean isInSelect() {
- return inSelect;
- }
-
- public final boolean isInCase() {
- return inCase;
- }
-
- public final int getStatementType() {
- return statementType;
- }
-
- public final int getCurrentClauseType() {
- return currentClauseType;
- }
-
- public final int getCurrentTopLevelClauseType() {
- return currentTopLevelClauseType;
- }
-
- public final int getCurrentStatementType() {
- return currentStatementType;
- }
-
- public final boolean isComparativeExpressionClause() {
- // Note: once we add support for "JOIN ... ON ...",
- // the ON clause needs to get included here
- return getCurrentClauseType() == WHERE ||
- getCurrentClauseType() == WITH ||
- isInCase();
- }
-
- public final boolean isSelectStatement() {
- return statementType == SELECT;
- }
-
- private void beforeStatement(String statementName, int statementType) {
- inFunctionCall = false;
- level++;
- if ( level == 1 ) {
- this.statementTypeName = statementName;
- this.statementType = statementType;
- }
- currentStatementType = statementType;
- if ( log.isDebugEnabled() ) {
- log.debug( statementName + " << begin [level=" + level + ", statement=" + this.statementTypeName + "]" );
- }
- }
-
- private void beforeStatementCompletion(String statementName) {
- if ( log.isDebugEnabled() ) {
- log.debug( statementName + " : finishing up [level=" + level + ", statement=" + statementTypeName + "]" );
- }
- }
-
- private void afterStatementCompletion(String statementName) {
- if ( log.isDebugEnabled() ) {
- log.debug( statementName + " >> end [level=" + level + ", statement=" + statementTypeName + "]" );
- }
- level--;
- }
-
- private void handleClauseStart(int clauseType) {
- currentClauseType = clauseType;
- if ( level == 1 ) {
- currentTopLevelClauseType = clauseType;
- }
- }
-
- ///////////////////////////////////////////////////////////////////////////
- // NOTE: The real implementations for the following are in the subclass.
-
- protected void evaluateAssignment(AST eq) throws SemanticException { }
-
- /** Pre-process the from clause input tree. **/
- protected void prepareFromClauseInputTree(AST fromClauseInput) {}
-
- /** Sets the current 'FROM' context. **/
- protected void pushFromClause(AST fromClause,AST inputFromNode) {}
-
- protected AST createFromElement(String path,AST alias,AST propertyFetch) throws SemanticException {
- return null;
- }
-
- protected void createFromJoinElement(AST path,AST alias,int joinType,AST fetch,AST propertyFetch,AST with) throws SemanticException {}
-
- protected AST createFromFilterElement(AST filterEntity,AST alias) throws SemanticException {
- return null;
- }
-
- protected void processQuery(AST select,AST query) throws SemanticException { }
-
- protected void postProcessUpdate(AST update) throws SemanticException { }
-
- protected void postProcessDelete(AST delete) throws SemanticException { }
-
- protected void postProcessInsert(AST insert) throws SemanticException { }
-
- protected void beforeSelectClause() throws SemanticException { }
-
- protected void processIndex(AST indexOp) throws SemanticException { }
-
- protected void processConstant(AST constant) throws SemanticException { }
-
- protected void processBoolean(AST constant) throws SemanticException { }
-
- protected void processNumericLiteral(AST literal) throws SemanticException { }
-
- protected void resolve(AST node) throws SemanticException { }
-
- protected void resolveSelectExpression(AST dotNode) throws SemanticException { }
-
- protected void processFunction(AST functionCall,boolean inSelect) throws SemanticException { }
-
- protected void processConstructor(AST constructor) throws SemanticException { }
-
- protected AST generateNamedParameter(AST delimiterNode, AST nameNode) throws SemanticException {
- return #( [NAMED_PARAM, nameNode.getText()] );
- }
-
- protected AST generatePositionalParameter(AST inputNode) throws SemanticException {
- return #( [PARAM, "?"] );
- }
-
- protected void lookupAlias(AST ident) throws SemanticException { }
-
- protected void setAlias(AST selectExpr, AST ident) { }
-
- protected AST lookupProperty(AST dot,boolean root,boolean inSelect) throws SemanticException {
- return dot;
- }
-
- protected boolean isNonQualifiedPropertyRef(AST ident) { return false; }
-
- protected AST lookupNonQualifiedProperty(AST property) throws SemanticException { return property; }
-
- protected void setImpliedJoinType(int joinType) { }
-
- protected AST createIntoClause(String path, AST propertySpec) throws SemanticException {
- return null;
- };
-
- protected void prepareVersioned(AST updateNode, AST versionedNode) throws SemanticException {}
-
- protected void prepareLogicOperator(AST operator) throws SemanticException { }
-
- protected void prepareArithmeticOperator(AST operator) throws SemanticException { }
-}
-
-// The main statement rule.
-statement
- : selectStatement | updateStatement | deleteStatement | insertStatement
- ;
-
-selectStatement
- : query
- ;
-
-// Cannot use just the fromElement rule here in the update and delete queries
-// because fromElement essentially relies on a FromClause already having been
-// built :(
-updateStatement!
- : #( u:UPDATE { beforeStatement( "update", UPDATE ); } (v:VERSIONED)? f:fromClause s:setClause (w:whereClause)? ) {
- #updateStatement = #(#u, #f, #s, #w);
- beforeStatementCompletion( "update" );
- prepareVersioned( #updateStatement, #v );
- postProcessUpdate( #updateStatement );
- afterStatementCompletion( "update" );
- }
- ;
-
-deleteStatement
- : #( DELETE { beforeStatement( "delete", DELETE ); } fromClause (whereClause)? ) {
- beforeStatementCompletion( "delete" );
- postProcessDelete( #deleteStatement );
- afterStatementCompletion( "delete" );
- }
- ;
-
-insertStatement
- // currently only "INSERT ... SELECT ..." statements supported;
- // do we also need support for "INSERT ... VALUES ..."?
- //
- : #( INSERT { beforeStatement( "insert", INSERT ); } intoClause query ) {
- beforeStatementCompletion( "insert" );
- postProcessInsert( #insertStatement );
- afterStatementCompletion( "insert" );
- }
- ;
-
-intoClause! {
- String p = null;
- }
- : #( INTO { handleClauseStart( INTO ); } (p=path) ps:insertablePropertySpec ) {
- #intoClause = createIntoClause(p, ps);
- }
- ;
-
-insertablePropertySpec
- : #( RANGE (IDENT)+ )
- ;
-
-setClause
- : #( SET { handleClauseStart( SET ); } (assignment)* )
- ;
-
-assignment
- // Note: the propertyRef here needs to be resolved
- // *before* we evaluate the newValue rule...
- : #( EQ (p:propertyRef) { resolve(#p); } (newValue) ) {
- evaluateAssignment( #assignment );
- }
- ;
-
-// For now, just use expr. Revisit after ejb3 solidifies this.
-newValue
- : expr | query
- ;
-
-// The query / subquery rule. Pops the current 'from node' context
-// (list of aliases).
-query!
- : #( QUERY { beforeStatement( "select", SELECT ); }
- // The first phase places the FROM first to make processing the SELECT simpler.
- #(SELECT_FROM
- f:fromClause
- (s:selectClause)?
- )
- (w:whereClause)?
- (g:groupClause)?
- (o:orderClause)?
- ) {
- // Antlr note: #x_in refers to the input AST, #x refers to the output AST
- #query = #([SELECT,"SELECT"], #s, #f, #w, #g, #o);
- beforeStatementCompletion( "select" );
- processQuery( #s, #query );
- afterStatementCompletion( "select" );
- }
- ;
-
-orderClause
- : #(ORDER { handleClauseStart( ORDER ); } orderExprs)
- ;
-
-orderExprs
- : expr ( ASCENDING | DESCENDING )? (orderExprs)?
- ;
-
-groupClause
- : #(GROUP { handleClauseStart( GROUP ); } (expr)+ ( #(HAVING logicalExpr) )? )
- ;
-
-selectClause!
- : #(SELECT { handleClauseStart( SELECT ); beforeSelectClause(); } (d:DISTINCT)? x:selectExprList ) {
- #selectClause = #([SELECT_CLAUSE,"{select clause}"], #d, #x);
- }
- ;
-
-selectExprList {
- boolean oldInSelect = inSelect;
- inSelect = true;
- }
- : ( selectExpr | aliasedSelectExpr )+ {
- inSelect = oldInSelect;
- }
- ;
-
-aliasedSelectExpr!
- : #(AS se:selectExpr i:identifier) {
- setAlias(#se,#i);
- #aliasedSelectExpr = #se;
- }
- ;
-
-selectExpr
- : p:propertyRef { resolveSelectExpression(#p); }
- | #(ALL ar2:aliasRef) { resolveSelectExpression(#ar2); #selectExpr = #ar2; }
- | #(OBJECT ar3:aliasRef) { resolveSelectExpression(#ar3); #selectExpr = #ar3; }
- | con:constructor { processConstructor(#con); }
- | functionCall
- | count
- | collectionFunction // elements() or indices()
- | literal
- | arithmeticExpr
- | query
- ;
-
-count
- : #(COUNT ( DISTINCT | ALL )? ( aggregateExpr | ROW_STAR ) )
- ;
-
-constructor
- { String className = null; }
- : #(CONSTRUCTOR className=path ( selectExpr | aliasedSelectExpr )* )
- ;
-
-aggregateExpr
- : expr //p:propertyRef { resolve(#p); }
- | collectionFunction
- ;
-
-// Establishes the list of aliases being used by this query.
-fromClause {
- // NOTE: This references the INPUT AST! (see http://www.antlr.org/doc/trees.html#Action%20Translation)
- // the ouput AST (#fromClause) has not been built yet.
- prepareFromClauseInputTree(#fromClause_in);
- }
- : #(f:FROM { pushFromClause(#fromClause,f); handleClauseStart( FROM ); } fromElementList )
- ;
-
-fromElementList {
- boolean oldInFrom = inFrom;
- inFrom = true;
- }
- : (fromElement)+ {
- inFrom = oldInFrom;
- }
- ;
-
-fromElement! {
- String p = null;
- }
- // A simple class name, alias element.
- : #(RANGE p=path (a:ALIAS)? (pf:FETCH)? ) {
- #fromElement = createFromElement(p,a, pf);
- }
- | je:joinElement {
- #fromElement = #je;
- }
- // A from element created due to filter compilation
- | fe:FILTER_ENTITY a3:ALIAS {
- #fromElement = createFromFilterElement(fe,a3);
- }
- ;
-
-joinElement! {
- int j = INNER;
- }
- // A from element with a join. This time, the 'path' should be treated as an AST
- // and resolved (like any path in a WHERE clause). Make sure all implied joins
- // generated by the property ref use the join type, if it was specified.
- : #(JOIN (j=joinType { setImpliedJoinType(j); } )? (f:FETCH)? ref:propertyRef (a:ALIAS)? (pf:FETCH)? (with:WITH)? ) {
- //createFromJoinElement(#ref,a,j,f, pf);
- createFromJoinElement(#ref,a,j,f, pf, with);
- setImpliedJoinType(INNER); // Reset the implied join type.
- }
- ;
-
-// Returns an node type integer that represents the join type
-// tokens.
-joinType returns [int j] {
- j = INNER;
- }
- : ( (left:LEFT | right:RIGHT) (outer:OUTER)? ) {
- if (left != null) j = LEFT_OUTER;
- else if (right != null) j = RIGHT_OUTER;
- else if (outer != null) j = RIGHT_OUTER;
- }
- | FULL {
- j = FULL;
- }
- | INNER {
- j = INNER;
- }
- ;
-
-// Matches a path and returns the normalized string for the path (usually
-// fully qualified a class name).
-path returns [String p] {
- p = "???";
- String x = "?x?";
- }
- : a:identifier { p = a.getText(); }
- | #(DOT x=path y:identifier) {
- StringBuffer buf = new StringBuffer();
- buf.append(x).append(".").append(y.getText());
- p = buf.toString();
- }
- ;
-
-// Returns a path as a single identifier node.
-pathAsIdent {
- String text = "?text?";
- }
- : text=path {
- #pathAsIdent = #([IDENT,text]);
- }
- ;
-
-withClause
- // Note : this is used internally from the HqlSqlWalker to
- // parse the node recognized with the with keyword earlier.
- // Done this way because it relies on the join it "qualifies"
- // already having been processed, which would not be the case
- // if withClause was simply referenced from the joinElement
- // rule during recognition...
- : #(w:WITH { handleClauseStart( WITH ); } b:logicalExpr ) {
- #withClause = #(w , #b);
- }
- ;
-
-whereClause
- : #(w:WHERE { handleClauseStart( WHERE ); } b:logicalExpr ) {
- // Use the *output* AST for the boolean expression!
- #whereClause = #(w , #b);
- }
- ;
-
-logicalExpr
- : #(AND logicalExpr logicalExpr)
- | #(OR logicalExpr logicalExpr)
- | #(NOT logicalExpr)
- | comparisonExpr
- ;
-
-// TODO: Add any other comparison operators here.
-comparisonExpr
- :
- ( #(EQ exprOrSubquery exprOrSubquery)
- | #(NE exprOrSubquery exprOrSubquery)
- | #(LT exprOrSubquery exprOrSubquery)
- | #(GT exprOrSubquery exprOrSubquery)
- | #(LE exprOrSubquery exprOrSubquery)
- | #(GE exprOrSubquery exprOrSubquery)
- | #(LIKE exprOrSubquery expr ( #(ESCAPE expr) )? )
- | #(NOT_LIKE exprOrSubquery expr ( #(ESCAPE expr) )? )
- | #(BETWEEN exprOrSubquery exprOrSubquery exprOrSubquery)
- | #(NOT_BETWEEN exprOrSubquery exprOrSubquery exprOrSubquery)
- | #(IN exprOrSubquery inRhs )
- | #(NOT_IN exprOrSubquery inRhs )
- | #(IS_NULL exprOrSubquery)
- | #(IS_NOT_NULL exprOrSubquery)
-// | #(IS_TRUE expr)
-// | #(IS_FALSE expr)
- | #(EXISTS ( expr | collectionFunctionOrSubselect ) )
- ) {
- prepareLogicOperator( #comparisonExpr );
- }
- ;
-
-inRhs
- : #(IN_LIST ( collectionFunctionOrSubselect | ( (expr)* ) ) )
- ;
-
-exprOrSubquery
- : expr
- | query
- | #(ANY collectionFunctionOrSubselect)
- | #(ALL collectionFunctionOrSubselect)
- | #(SOME collectionFunctionOrSubselect)
- ;
-
-collectionFunctionOrSubselect
- : collectionFunction
- | query
- ;
-
-expr
- : ae:addrExpr [ true ] { resolve(#ae); } // Resolve the top level 'address expression'
- | #( VECTOR_EXPR (expr)* )
- | constant
- | arithmeticExpr
- | functionCall // Function call, not in the SELECT clause.
- | parameter
- | count // Count, not in the SELECT clause.
- ;
-
-arithmeticExpr
- : #(PLUS expr expr) { prepareArithmeticOperator( #arithmeticExpr ); }
- | #(MINUS expr expr) { prepareArithmeticOperator( #arithmeticExpr ); }
- | #(DIV expr expr) { prepareArithmeticOperator( #arithmeticExpr ); }
- | #(STAR expr expr) { prepareArithmeticOperator( #arithmeticExpr ); }
-// | #(CONCAT expr (expr)+ ) { prepareArithmeticOperator( #arithmeticExpr ); }
- | #(UNARY_MINUS expr) { prepareArithmeticOperator( #arithmeticExpr ); }
- | caseExpr
- ;
-
-caseExpr
- : #(CASE { inCase = true; } (#(WHEN logicalExpr expr))+ (#(ELSE expr))?) { inCase = false; }
- | #(CASE2 { inCase = true; } expr (#(WHEN expr expr))+ (#(ELSE expr))?) { inCase = false; }
- ;
-
-//TODO: I don't think we need this anymore .. how is it different to
-// maxelements, etc, which are handled by functionCall
-collectionFunction
- : #(e:ELEMENTS {inFunctionCall=true;} p1:propertyRef { resolve(#p1); } )
- { processFunction(#e,inSelect); } {inFunctionCall=false;}
- | #(i:INDICES {inFunctionCall=true;} p2:propertyRef { resolve(#p2); } )
- { processFunction(#i,inSelect); } {inFunctionCall=false;}
- ;
-
-functionCall
- : #(METHOD_CALL {inFunctionCall=true;} pathAsIdent ( #(EXPR_LIST (expr)* ) )? )
- { processFunction(#functionCall,inSelect); } {inFunctionCall=false;}
- | #(AGGREGATE aggregateExpr )
- ;
-
-constant
- : literal
- | NULL
- | TRUE { processBoolean(#constant); }
- | FALSE { processBoolean(#constant); }
- | JAVA_CONSTANT
- ;
-
-literal
- : NUM_INT { processNumericLiteral( #literal ); }
- | NUM_LONG { processNumericLiteral( #literal ); }
- | NUM_FLOAT { processNumericLiteral( #literal ); }
- | NUM_DOUBLE { processNumericLiteral( #literal ); }
- | QUOTED_STRING
- ;
-
-identifier
- : (IDENT | WEIRD_IDENT)
- ;
-
-addrExpr! [ boolean root ]
- : #(d:DOT lhs:addrExprLhs rhs:propertyName ) {
- // This gives lookupProperty() a chance to transform the tree
- // to process collection properties (.elements, etc).
- #addrExpr = #(#d, #lhs, #rhs);
- #addrExpr = lookupProperty(#addrExpr,root,false);
- }
- | #(i:INDEX_OP lhs2:addrExprLhs rhs2:expr) {
- #addrExpr = #(#i, #lhs2, #rhs2);
- processIndex(#addrExpr);
- }
- | p:identifier {
-// #addrExpr = #p;
-// resolve(#addrExpr);
- // In many cases, things other than property-refs are recognized
- // by this addrExpr rule. Some of those I have seen:
- // 1) select-clause from-aliases
- // 2) sql-functions
- if ( isNonQualifiedPropertyRef(#p) ) {
- #addrExpr = lookupNonQualifiedProperty(#p);
- }
- else {
- resolve(#p);
- #addrExpr = #p;
- }
- }
- ;
-
-addrExprLhs
- : addrExpr [ false ]
- ;
-
-propertyName
- : identifier
- | CLASS
- | ELEMENTS
- | INDICES
- ;
-
-propertyRef!
- : #(d:DOT lhs:propertyRefLhs rhs:propertyName ) {
- // This gives lookupProperty() a chance to transform the tree to process collection properties (.elements, etc).
- #propertyRef = #(#d, #lhs, #rhs);
- #propertyRef = lookupProperty(#propertyRef,false,true);
- }
- |
- p:identifier {
- // In many cases, things other than property-refs are recognized
- // by this propertyRef rule. Some of those I have seen:
- // 1) select-clause from-aliases
- // 2) sql-functions
- if ( isNonQualifiedPropertyRef(#p) ) {
- #propertyRef = lookupNonQualifiedProperty(#p);
- }
- else {
- resolve(#p);
- #propertyRef = #p;
- }
- }
- ;
-
-propertyRefLhs
- : propertyRef
- ;
-
-aliasRef!
- : i:identifier {
- #aliasRef = #([ALIAS_REF,i.getText()]); // Create an ALIAS_REF node instead of an IDENT node.
- lookupAlias(#aliasRef);
- }
- ;
-
-parameter!
- : #(c:COLON a:identifier) {
- // Create a NAMED_PARAM node instead of (COLON IDENT).
- #parameter = generateNamedParameter( c, a );
-// #parameter = #([NAMED_PARAM,a.getText()]);
-// namedParameter(#parameter);
- }
- | #(p:PARAM (n:NUM_INT)?) {
- if ( n != null ) {
- // An ejb3-style "positional parameter", which we handle internally as a named-param
- #parameter = generateNamedParameter( p, n );
-// #parameter = #([NAMED_PARAM,n.getText()]);
-// namedParameter(#parameter);
- }
- else {
- #parameter = generatePositionalParameter( p );
-// #parameter = #([PARAM,"?"]);
-// positionalParameter(#parameter);
- }
- }
- ;
-
-numericInteger
- : NUM_INT
- ;
\ No newline at end of file
15 years, 7 months
Hibernate SVN: r16316 - core/branches/antlr3.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2009-04-14 12:39:48 -0400 (Tue, 14 Apr 2009)
New Revision: 16316
Added:
core/branches/antlr3/pom.xml
Log:
creating antlr3 branch
Copied: core/branches/antlr3/pom.xml (from rev 16315, core/branches/SQL_GEN_REDESIGN/pom.xml)
===================================================================
--- core/branches/antlr3/pom.xml (rev 0)
+++ core/branches/antlr3/pom.xml 2009-04-14 16:39:48 UTC (rev 16316)
@@ -0,0 +1,236 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-core</artifactId>
+ <version>3.4.0.SQL_GEN_REDESIGN</version>
+ <packaging>jar</packaging>
+
+ <name>Hibernate Core (SQL Generation Redesign)</name>
+ <description>The core functionality of Hibernate (with redesign of SQL generation)</description>
+
+ <dependencies>
+ <dependency>
+ <groupId>antlr</groupId>
+ <artifactId>antlr</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>commons-collections</groupId>
+ <artifactId>commons-collections</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>dom4j</groupId>
+ <artifactId>dom4j</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ </dependency>
+
+ <dependency>
+ <!-- YUCK, YUCK, YUCK!!!! -->
+ <groupId>javax.transaction</groupId>
+ <artifactId>jta</artifactId>
+ <version>1.1</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.security</groupId>
+ <artifactId>jaas</artifactId>
+ <version>1.0.01</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.security</groupId>
+ <artifactId>jacc</artifactId>
+ <version>1.0</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>ant</groupId>
+ <artifactId>ant</artifactId>
+ <version>1.6.5</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <!-- optional deps for bytecode providers until those are finally properly scoped -->
+ <dependency>
+ <groupId>javassist</groupId>
+ <artifactId>javassist</artifactId>
+ <version>3.4.GA</version>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-cglib-repack</artifactId>
+ <version>2.1_3</version>
+ <optional>true</optional>
+ </dependency>
+ <!-- test-scoped dependencies for common testing dependencies -->
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>3.8.1</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>jcl-over-slf4j</artifactId>
+ <version>1.5.2</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ <version>1.5.2</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ <version>1.2.14</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ <version>99.0-does-not-exist</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging-api</artifactId>
+ <version>99.0-does-not-exist</version>
+ <scope>test</scope>
+ </dependency>
+ <!-- / test-scoped dependencies for common testing dependencies -->
+ </dependencies>
+
+ <dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <version>1.5.2</version>
+ </dependency>
+ <dependency>
+ <groupId>antlr</groupId>
+ <artifactId>antlr</artifactId>
+ <version>2.7.6</version>
+ </dependency>
+ <dependency>
+ <groupId>commons-collections</groupId>
+ <artifactId>commons-collections</artifactId>
+ <version>3.1</version>
+ </dependency>
+ <dependency>
+ <groupId>dom4j</groupId>
+ <artifactId>dom4j</artifactId>
+ <version>1.6.1</version>
+ </dependency>
+ </dependencies>
+ </dependencyManagement>
+
+ <distributionManagement>
+ <repository>
+ <!-- Copy the dist to the local checkout of the JBoss maven2 repo ${maven.repository.root} -->
+ <!-- It is anticipated that ${maven.repository.root} be set in user's settings.xml -->
+ <!-- todo : replace this with direct svn access once the svnkit providers are available -->
+ <id>repository.jboss.org</id>
+ <url>file://${maven.repository.root}</url>
+ </repository>
+ <snapshotRepository>
+ <id>snapshots.jboss.org</id>
+ <name>JBoss Snapshot Repository</name>
+ <url>dav:https://snapshots.jboss.org/maven2</url>
+ </snapshotRepository>
+ </distributionManagement>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-enforcer-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>enforce-java</id>
+ <goals>
+ <goal>enforce</goal>
+ </goals>
+ <configuration>
+ <rules>
+ <requireJavaVersion>
+ <version>[1.5,)</version>
+ </requireJavaVersion>
+ <requireMavenVersion>
+ <version>(2.0.7,)</version>
+ </requireMavenVersion>
+ </rules>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>1.4</source>
+ <target>1.4</target>
+ </configuration>
+ </plugin>
+
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>antlr-maven-plugin</artifactId>
+ <version>${antlrPluginVersion}</version>
+ <configuration>
+ <traceParser>true</traceParser>
+ <traceTreeParser>true</traceTreeParser>
+ <grammarDefs>
+ <grammar>
+ <name>sql/common.g</name>
+ </grammar>
+ <grammar>
+ <name>hql/parse.g</name>
+ </grammar>
+ <grammar>
+ <name>hql/normalize.g</name>
+ </grammar>
+ <grammar>
+ <name>hql/resolve.g</name>
+ </grammar>
+ <grammar>
+ <name>order/parse.g</name>
+ </grammar>
+ <grammar>
+ <name>order/render.g</name>
+ </grammar>
+ <!-- temporary -->
+ <grammar>
+ <name>hql.g</name>
+ </grammar>
+ <grammar>
+ <name>hql-sql.g</name>
+ </grammar>
+ <grammar>
+ <name>sql-gen.g</name>
+ </grammar>
+ <!-- / temporary -->
+ </grammarDefs>
+ </configuration>
+ <executions>
+ <execution>
+ <goals>
+ <goal>generate</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
+ </plugins>
+ </build>
+
+ <properties>
+ <antlrPluginVersion>2.2-SNAPSHOT</antlrPluginVersion>
+ </properties>
+</project>
15 years, 7 months
Hibernate SVN: r16315 - core/branches/antlr3.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2009-04-14 12:39:05 -0400 (Tue, 14 Apr 2009)
New Revision: 16315
Added:
core/branches/antlr3/src/
Log:
creating antlr3 branch
Copied: core/branches/antlr3/src (from rev 16314, core/branches/SQL_GEN_REDESIGN/src)
15 years, 7 months
Hibernate SVN: r16314 - search/trunk/src/main/java/org/hibernate/search/event.
by hibernate-commits@lists.jboss.org
Author: sannegrinovero
Date: 2009-04-14 10:49:35 -0400 (Tue, 14 Apr 2009)
New Revision: 16314
Modified:
search/trunk/src/main/java/org/hibernate/search/event/FullTextIndexEventListener.java
Log:
HSEARCH-178 changing from ThreadLocals to WeakIdentityHashMap
Modified: search/trunk/src/main/java/org/hibernate/search/event/FullTextIndexEventListener.java
===================================================================
--- search/trunk/src/main/java/org/hibernate/search/event/FullTextIndexEventListener.java 2009-04-14 13:51:42 UTC (rev 16313)
+++ search/trunk/src/main/java/org/hibernate/search/event/FullTextIndexEventListener.java 2009-04-14 14:49:35 UTC (rev 16314)
@@ -5,8 +5,8 @@
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
-import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
+import java.util.Map;
import javax.transaction.Status;
import javax.transaction.Synchronization;
@@ -40,6 +40,7 @@
import org.hibernate.search.backend.impl.EventSourceTransactionContext;
import org.hibernate.search.engine.SearchFactoryImplementor;
import org.hibernate.search.util.LoggerFactory;
+import org.hibernate.search.util.WeakIdentityHashMap;
/**
* This listener supports setting a parent directory for all generated index files.
@@ -66,11 +67,9 @@
//only used by the FullTextIndexEventListener instance playing in the FlushEventListener role.
// transient because it's not serializable (and state doesn't need to live longer than a flush).
// final because it's initialization should be published to other threads.
- // T.Local because different threads could be flushing on this listener, still the reference
- // to session should be weak so that sessions which had errors on flush can be discarded.
// ! update the readObject() method in case of name changes !
- // It's not static as we couldn't properly cleanup otherwise.
- private transient final ThreadLocal<FlushContextContainer> flushSynch = new ThreadLocal<FlushContextContainer>();
+ // make sure the Synchronization doesn't contain references to Session, otherwise we'll leak memory.
+ private transient final Map<Session,Synchronization> flushSynch = new WeakIdentityHashMap<Session,Synchronization>(0);
/**
* Initialize method called by Hibernate Core when the SessionFactory starts
@@ -186,28 +185,19 @@
public void onFlush(FlushEvent event) {
if ( used ) {
Session session = event.getSession();
- FlushContextContainer flushContextContainer = this.flushSynch.get();
- if ( flushContextContainer != null ) {
- //first cleanup the ThreadLocal
- this.flushSynch.set( null );
- EventSource registeringEventSource = flushContextContainer.eventSource.get();
- //check that we are still in the same session which registered the flushSync:
- if ( registeringEventSource != null && registeringEventSource == session ) {
- log.debug( "flush event causing index update out of transaction" );
- Synchronization synchronization = flushContextContainer.synchronization;
- synchronization.beforeCompletion();
- synchronization.afterCompletion( Status.STATUS_COMMITTED );
- }
+ Synchronization synchronization = flushSynch.get( session );
+ if ( synchronization != null ) {
+ //first cleanup
+ flushSynch.remove( session );
+ log.debug( "flush event causing index update out of transaction" );
+ synchronization.beforeCompletion();
+ synchronization.afterCompletion( Status.STATUS_COMMITTED );
}
}
}
public void addSynchronization(EventSource eventSource, Synchronization synchronization) {
- //no need to check for "unused" state, as this method is used by Search itself only.
- FlushContextContainer flushContext = new FlushContextContainer(eventSource, synchronization);
- //ignoring previously set data: if there was something, it's coming from a previous thread
- //which had some error when flushing and couldn't cleanup.
- this.flushSynch.set( flushContext );
+ this.flushSynch.put( eventSource, synchronization );
}
/* Might want to implement AutoFlushEventListener in future?
@@ -217,18 +207,6 @@
}
*/
- private static class FlushContextContainer {
-
- private final WeakReference<EventSource> eventSource;
- private final Synchronization synchronization;
-
- public FlushContextContainer(EventSource eventSource, Synchronization synchronization) {
- this.eventSource = new WeakReference<EventSource>( eventSource );
- this.synchronization = synchronization;
- }
-
- }
-
private void writeObject(ObjectOutputStream os) throws IOException {
os.defaultWriteObject();
}
@@ -239,7 +217,7 @@
Class<FullTextIndexEventListener> cl = FullTextIndexEventListener.class;
Field f = cl.getDeclaredField("flushSynch");
f.setAccessible( true );
- ThreadLocal<FlushContextContainer> flushSynch = new ThreadLocal<FlushContextContainer>();
+ Map<Session,Synchronization> flushSynch = new WeakIdentityHashMap<Session,Synchronization>(0);
// setting a final field by reflection during a readObject is considered as safe as in a constructor:
f.set( this, flushSynch );
}
15 years, 7 months
Hibernate SVN: r16313 - in validator/trunk/hibernate-validator/src: test/java/org/hibernate/validation/engine and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2009-04-14 09:51:42 -0400 (Tue, 14 Apr 2009)
New Revision: 16313
Removed:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintValidatorDefinitionsCache.java
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaData.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataCache.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintDescriptorImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintHelper.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorContextImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImpl.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java
Log:
HV-139
Made BeanMetaDataCache non static and merged ConstraintValidatorDefinitionsCache into ConstraintHelper
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaData.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaData.java 2009-04-13 23:29:04 UTC (rev 16312)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaData.java 2009-04-14 13:51:42 UTC (rev 16313)
@@ -17,9 +17,8 @@
*/
package org.hibernate.validation.engine;
-import java.lang.reflect.Field;
+import java.lang.annotation.Annotation;
import java.lang.reflect.Member;
-import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
import javax.validation.BeanDescriptor;
@@ -56,7 +55,7 @@
* @return A list of <code>MetaConstraint</code> instances encapsulating the information of all the constraints
* defined on the bean.
*/
- List<MetaConstraint<T, ?>> geMetaConstraintList();
+ List<MetaConstraint<T, ? extends Annotation>> geMetaConstraintList();
/**
* Return <code>PropertyDescriptor</code> for the given property.
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataCache.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataCache.java 2009-04-13 23:29:04 UTC (rev 16312)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataCache.java 2009-04-14 13:51:42 UTC (rev 16313)
@@ -21,6 +21,8 @@
import java.util.concurrent.ConcurrentHashMap;
/**
+ * Cache for created instances of <code>BeanMetaData</code>.
+ *
* @author Hardy Ferentschik
*/
public class BeanMetaDataCache {
@@ -28,19 +30,19 @@
* A map for the meta data for each entity. The key is the class and the value the bean meta data for this
* entity.
*/
- private static Map<Class<?>, BeanMetaDataImpl<?>> metadataProviders
- = new ConcurrentHashMap<Class<?>, BeanMetaDataImpl<?>>( 10 );
+ private Map<Class<?>, BeanMetaDataImpl<?>> metadataProviders = new ConcurrentHashMap<Class<?>, BeanMetaDataImpl<?>>(
+ 10
+ );
- public static <T> BeanMetaDataImpl<T> getBeanMetaData(Class<T> beanClass) {
+ @SuppressWarnings("unchecked")
+ public <T> BeanMetaDataImpl<T> getBeanMetaData(Class<T> beanClass) {
if ( beanClass == null ) {
throw new IllegalArgumentException( "Class cannot be null" );
}
- @SuppressWarnings("unchecked")
- BeanMetaDataImpl<T> metadata = ( BeanMetaDataImpl<T> ) metadataProviders.get( beanClass );
- return metadata;
+ return ( BeanMetaDataImpl<T> ) metadataProviders.get( beanClass );
}
- static void addBeanMetaData(Class<?> beanClass, BeanMetaDataImpl<?> metaData) {
+ public <T> void addBeanMetaData(Class<T> beanClass, BeanMetaDataImpl<T> metaData) {
metadataProviders.put( beanClass, metaData );
}
}
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java 2009-04-13 23:29:04 UTC (rev 16312)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/BeanMetaDataImpl.java 2009-04-14 13:51:42 UTC (rev 16313)
@@ -68,7 +68,7 @@
/**
* List of constraints.
*/
- private List<MetaConstraint<T, ?>> metaConstraintList = new ArrayList<MetaConstraint<T, ?>>();
+ private List<MetaConstraint<T, ? extends Annotation>> metaConstraintList = new ArrayList<MetaConstraint<T, ? extends Annotation>>();
/**
* List of cascaded members.
@@ -86,10 +86,11 @@
private List<Class<?>> defaultGroupSequence = new ArrayList<Class<?>>();
/**
- * Object keeping track of all builtin constraints.
+ * Object keeping track of all constraints.
*/
private final ConstraintHelper constraintHelper;
+
public BeanMetaDataImpl(Class<T> beanClass, ConstraintHelper constraintHelper) {
this(
beanClass,
@@ -116,11 +117,11 @@
return cascadedMembers;
}
- public List<MetaConstraint<T, ?>> geMetaConstraintList() {
+ public List<MetaConstraint<T, ? extends Annotation>> geMetaConstraintList() {
return metaConstraintList;
}
- public void addMetaConstraint(MetaConstraint<?, ?> metaConstraint) {
+ public void addMetaConstraint(MetaConstraint<?, ? extends Annotation> metaConstraint) {
metaConstraintList.add( ( MetaConstraint<T, ?> ) metaConstraint );
}
@@ -323,10 +324,14 @@
Class<?>[] groups = ReflectionHelper.getAnnotationParameter( annotation, "groups", Class[].class );
ConstraintDescriptorImpl constraintDescriptor;
if ( clazz.isInterface() ) {
- constraintDescriptor = new ConstraintDescriptorImpl( annotation, groups, constraintHelper, clazz );
+ constraintDescriptor = new ConstraintDescriptorImpl(
+ annotation, groups, constraintHelper, clazz
+ );
}
else {
- constraintDescriptor = new ConstraintDescriptorImpl( annotation, groups, constraintHelper );
+ constraintDescriptor = new ConstraintDescriptorImpl(
+ annotation, groups, constraintHelper
+ );
}
return constraintDescriptor;
}
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-04-13 23:29:04 UTC (rev 16312)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConfigurationImpl.java 2009-04-14 13:51:42 UTC (rev 16313)
@@ -67,10 +67,10 @@
private static final Logger log = LoggerFactory.make();
private static final String VALIDATION_XML_FILE = "/META-INF/validation.xml";
private static final String VALIDATION_CONFIGURATION_XSD = "META-INF/validation-configuration-1.0.xsd";
- private static final MessageInterpolator defaultMessageInterpolator = new ResourceBundleMessageInterpolator();
- private static final TraversableResolver defaultTraversableResolver = new DefaultTraversableResolver();
- private static final ConstraintValidatorFactory defaultValidatorFactory = new ConstraintValidatorFactoryImpl();
+ private final MessageInterpolator defaultMessageInterpolator = new ResourceBundleMessageInterpolator();
+ private final TraversableResolver defaultTraversableResolver = new DefaultTraversableResolver();
+ private final ConstraintValidatorFactory defaultValidatorFactory = new ConstraintValidatorFactoryImpl();
private final ValidationProviderResolver providerResolver;
private ParameterHolder parameterHolder;
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintDescriptorImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintDescriptorImpl.java 2009-04-13 23:29:04 UTC (rev 16312)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintDescriptorImpl.java 2009-04-14 13:51:42 UTC (rev 16313)
@@ -119,11 +119,9 @@
}
private void findConstraintValidatorClasses() {
- if ( ConstraintValidatorDefinitionsCache.containsConstraintValidatorDefinition( annotation.annotationType())) {
- for ( Class<? extends ConstraintValidator<? extends Annotation, ?>> validator : ConstraintValidatorDefinitionsCache
- .getConstraintValidatorDefinition(
- annotation.annotationType()
- ) ) {
+ if ( constraintHelper.containsConstraintValidatorDefinition( annotation.annotationType() ) ) {
+ for ( Class<? extends ConstraintValidator<? extends Annotation, ?>> validator : constraintHelper
+ .getConstraintValidatorDefinition( annotation.annotationType() ) ) {
constraintValidatorDefinitonClasses.add( ( Class<? extends ConstraintValidator<T, ?>> ) validator );
}
return;
@@ -141,7 +139,7 @@
constraintDefinitonClasses.addAll( Arrays.asList( validatedBy ) );
}
- ConstraintValidatorDefinitionsCache.addConstraintValidatorDefinition(
+ constraintHelper.addConstraintValidatorDefinition(
annotation.annotationType(), constraintDefinitonClasses
);
@@ -304,7 +302,9 @@
}
}
U annotationProxy = AnnotationFactory.create( annotationDescriptor );
- return new ConstraintDescriptorImpl<U>( annotationProxy, groups, constraintHelper );
+ return new ConstraintDescriptorImpl<U>(
+ annotationProxy, groups, constraintHelper
+ );
}
private class ClassIndexWrapper {
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintHelper.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintHelper.java 2009-04-13 23:29:04 UTC (rev 16312)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintHelper.java 2009-04-14 13:51:42 UTC (rev 16313)
@@ -64,7 +64,7 @@
import org.hibernate.validation.util.ReflectionHelper;
/**
- * Keeps track of builtin constraints and their validator implementations.
+ * Keeps track of builtin constraints and their validator implementations, as well as already resolved validator definitions.
*
* @author Hardy Ferentschik
* @author Alaa Nassef
@@ -76,6 +76,9 @@
private final Map<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<?, ?>>>> builtinConstraints =
new HashMap<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<?, ?>>>>();
+ private final Map<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<? extends Annotation, ?>>>> constraintValidatorDefinitons =
+ new HashMap<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<? extends Annotation, ?>>>>();
+
public ConstraintHelper() {
List<Class<? extends ConstraintValidator<?, ?>>> constraintList =
@@ -152,7 +155,7 @@
return constraints;
}
- private List<Class<? extends ConstraintValidator<? , ?>>> getBuiltInFromAnnotationType(Class<? extends Annotation> annotationType) {
+ private List<Class<? extends ConstraintValidator<?, ?>>> getBuiltInFromAnnotationType(Class<? extends Annotation> annotationType) {
return builtinConstraints.get( annotationType );
}
@@ -234,7 +237,7 @@
}
/**
- * Checks whehter the specified annotation is a valid constraint annotation. A constraint annotations has to
+ * Checks whether the specified annotation is a valid constraint annotation. A constraint annotations has to
* fulfill the following conditions:
* <ul>
* <li>Has to contain a <code>ConstraintValidator</code> implementation.</li>
@@ -284,4 +287,19 @@
}
return true;
}
+
+ public List<Class<? extends ConstraintValidator<? extends Annotation, ?>>> getConstraintValidatorDefinition(Class<? extends Annotation> annotationClass) {
+ if ( annotationClass == null ) {
+ throw new IllegalArgumentException( "Class cannot be null" );
+ }
+ return constraintValidatorDefinitons.get( annotationClass );
+ }
+
+ public <A extends Annotation> void addConstraintValidatorDefinition(Class<A> annotationClass, List<Class<? extends ConstraintValidator<? extends Annotation, ?>>> definitionClasses) {
+ constraintValidatorDefinitons.put( annotationClass, definitionClasses );
+ }
+
+ public boolean containsConstraintValidatorDefinition(Class<? extends Annotation> annotationClass) {
+ return constraintValidatorDefinitons.containsKey( annotationClass );
+ }
}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintValidatorDefinitionsCache.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintValidatorDefinitionsCache.java 2009-04-13 23:29:04 UTC (rev 16312)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ConstraintValidatorDefinitionsCache.java 2009-04-14 13:51:42 UTC (rev 16313)
@@ -1,48 +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 java.lang.annotation.Annotation;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import javax.validation.ConstraintValidator;
-
-/**
- * Caches the constraint classes for a given annotation.
- *
- * @author Hardy Ferentschik
- */
-public class ConstraintValidatorDefinitionsCache {
- private static final Map<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<? extends Annotation, ?>>>> constraintValidatorDefinitons = new HashMap<Class<? extends Annotation>, List<Class<? extends ConstraintValidator<? extends Annotation, ?>>>>();
-
- public static List<Class<? extends ConstraintValidator<? extends Annotation, ?>>> getConstraintValidatorDefinition(Class<? extends Annotation> annotationClass) {
- if ( annotationClass == null ) {
- throw new IllegalArgumentException( "Class cannot be null" );
- }
- return constraintValidatorDefinitons.get( annotationClass );
- }
-
- public static <A extends Annotation> void addConstraintValidatorDefinition(Class<A> annotationClass, List<Class<? extends ConstraintValidator<? extends Annotation, ?>>> definitionClasses) {
- constraintValidatorDefinitons.put( annotationClass, definitionClasses );
- }
-
- public static boolean containsConstraintValidatorDefinition(Class<? extends Annotation> annotationClass) {
- return constraintValidatorDefinitons.containsKey( annotationClass );
- }
-}
\ No newline at end of file
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorContextImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorContextImpl.java 2009-04-13 23:29:04 UTC (rev 16312)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorContextImpl.java 2009-04-14 13:51:42 UTC (rev 16313)
@@ -17,15 +17,18 @@
private final TraversableResolver factoryTraversableResolver;
private final ConstraintValidatorFactory constraintValidatorFactory;
private final ConstraintHelper constraintHelper;
+ private final BeanMetaDataCache beanMetaDataCache;
public ValidatorContextImpl(ConstraintValidatorFactory constraintValidatorFactory,
MessageInterpolator factoryMessageInterpolator,
TraversableResolver factoryTraversableResolver,
- ConstraintHelper constraintHelper) {
+ ConstraintHelper constraintHelper,
+ BeanMetaDataCache beanMetaDataCache) {
this.constraintValidatorFactory = constraintValidatorFactory;
this.factoryMessageInterpolator = factoryMessageInterpolator;
this.factoryTraversableResolver = factoryTraversableResolver;
this.constraintHelper = constraintHelper;
+ this.beanMetaDataCache = beanMetaDataCache;
messageInterpolator( factoryMessageInterpolator );
traversableResolver( factoryTraversableResolver );
}
@@ -61,7 +64,11 @@
*/
public Validator getValidator() {
return new ValidatorImpl(
- constraintValidatorFactory, messageInterpolator, traversableResolver, constraintHelper
+ constraintValidatorFactory,
+ messageInterpolator,
+ traversableResolver,
+ constraintHelper,
+ beanMetaDataCache
);
}
}
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImpl.java 2009-04-13 23:29:04 UTC (rev 16312)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorFactoryImpl.java 2009-04-14 13:51:42 UTC (rev 16313)
@@ -71,6 +71,8 @@
import org.hibernate.validation.xml.ValidatedByType;
/**
+ * Factory returning initialized <code>Validator</code> instances.
+ *
* @author Emmanuel Bernard
* @author Hardy Ferentschik
*/
@@ -85,24 +87,26 @@
private final MessageInterpolator messageInterpolator;
private final TraversableResolver traversableResolver;
private final ConstraintValidatorFactory constraintValidatorFactory;
- private final ConstraintHelper constraintHelper = new ConstraintHelper();
+ private final ConstraintHelper constraintHelper;
+ private final BeanMetaDataCache beanMetaDataCache;
private final Set<Class<?>> processedClasses = new HashSet<Class<?>>();
+ private final AnnotationIgnores annotationIgnores;
+ private final Map<Class<?>, List<MetaConstraint<?, ? extends Annotation>>> constraintMap;
+ private final Map<Class<?>, List<Member>> cascadedMembers;
+ private final Map<Class<?>, List<Class<?>>> defaultSequences;
- private AnnotationIgnores annotationIgnores;
- private Map<Class<?>, List<MetaConstraint<?, ?>>> constraintMap;
- private Map<Class<?>, List<Member>> cascadedMembers;
- private Map<Class<?>, List<Class<?>>> defaultSequences;
-
public ValidatorFactoryImpl(ConfigurationState configurationState) {
this.messageInterpolator = configurationState.getMessageInterpolator();
this.constraintValidatorFactory = configurationState.getConstraintValidatorFactory();
this.traversableResolver = configurationState.getTraversableResolver();
+ this.constraintHelper = new ConstraintHelper();
+ this.beanMetaDataCache = new BeanMetaDataCache();
- annotationIgnores = new AnnotationIgnores();
- constraintMap = new HashMap<Class<?>, List<MetaConstraint<?, ?>>>();
- cascadedMembers = new HashMap<Class<?>, List<Member>>();
- defaultSequences = new HashMap<Class<?>, List<Class<?>>>();
+ this.annotationIgnores = new AnnotationIgnores();
+ this.constraintMap = new HashMap<Class<?>, List<MetaConstraint<?, ? extends Annotation>>>();
+ this.cascadedMembers = new HashMap<Class<?>, List<Member>>();
+ this.defaultSequences = new HashMap<Class<?>, List<Class<?>>>();
parseMappingFiles( configurationState.getMappingStreams() );
initBeanMetaData();
@@ -127,7 +131,11 @@
*/
public ValidatorContext usingContext() {
return new ValidatorContextImpl(
- constraintValidatorFactory, messageInterpolator, traversableResolver, constraintHelper
+ constraintValidatorFactory,
+ messageInterpolator,
+ traversableResolver,
+ constraintHelper,
+ beanMetaDataCache
);
}
@@ -171,6 +179,7 @@
}
}
+ @SuppressWarnings("unchecked")
private void parseConstraintDefinitions(List<ConstraintDefinitionType> constraintDefinitionList) {
for ( ConstraintDefinitionType constraintDefinition : constraintDefinitionList ) {
String annotationClassName = constraintDefinition.getAnnotation();
@@ -184,6 +193,10 @@
throw new ValidationException( "Unable to load class " + annotationClassName );
}
+ if ( !annotationClass.isAnnotation() ) {
+ throw new ValidationException( annotationClassName + " is not an annotation" );
+ }
+
ValidatedByType validatedByType = constraintDefinition.getValidatedBy();
List<Class<? extends ConstraintValidator<? extends Annotation, ?>>> constraintValidatorClasses = new ArrayList<Class<? extends ConstraintValidator<? extends Annotation, ?>>>();
if ( validatedByType.isIncludeExistingValidators() != null && validatedByType.isIncludeExistingValidators() ) {
@@ -192,7 +205,6 @@
for ( String validatorClassName : validatedByType.getValue() ) {
Class<? extends ConstraintValidator<?, ?>> validatorClass;
try {
- // TODO validate this class!
validatorClass = ( Class<? extends ConstraintValidator<?, ?>> ) ReflectionHelper.classForName(
validatorClassName,
this.getClass()
@@ -201,9 +213,14 @@
catch ( ClassNotFoundException e ) {
throw new ValidationException( "Unable to load class " + validatorClassName );
}
+
+ if ( !ConstraintValidator.class.isAssignableFrom(validatorClass) ) {
+ throw new ValidationException( validatorClass + " is not a constraint validator class" );
+ }
+
constraintValidatorClasses.add( validatorClass );
}
- ConstraintValidatorDefinitionsCache.addConstraintValidatorDefinition(
+ constraintHelper.addConstraintValidatorDefinition(
annotationClass, constraintValidatorClasses
);
}
@@ -311,7 +328,7 @@
constraintMap.get( beanClass ).add( metaConstraint );
}
else {
- List<MetaConstraint<?, ?>> constraintList = new ArrayList<MetaConstraint<?, ?>>();
+ List<MetaConstraint<?, ? extends Annotation>> constraintList = new ArrayList<MetaConstraint<?, ? extends Annotation>>();
constraintList.add( metaConstraint );
constraintMap.put( beanClass, constraintList );
}
@@ -585,10 +602,12 @@
return constraintMappings;
}
- private void initBeanMetaData() {
+ private <T> void initBeanMetaData() {
for ( Class<?> beanClass : processedClasses ) {
- BeanMetaDataImpl<?> metaData = new BeanMetaDataImpl( beanClass, constraintHelper, annotationIgnores );
- for ( MetaConstraint<?, ?> constraint : constraintMap.get( beanClass ) ) {
+ BeanMetaDataImpl<?> metaData = new BeanMetaDataImpl<T>(
+ ( Class<T> ) beanClass, constraintHelper, annotationIgnores
+ );
+ for ( MetaConstraint<?, ? extends Annotation> constraint : constraintMap.get( beanClass ) ) {
metaData.addMetaConstraint( constraint );
}
for ( Member m : cascadedMembers.get( beanClass ) ) {
@@ -597,7 +616,7 @@
if ( defaultSequences.containsKey( beanClass ) ) {
metaData.setDefaultGroupSequence( defaultSequences.get( beanClass ) );
}
- BeanMetaDataCache.addBeanMetaData( beanClass, metaData );
+ beanMetaDataCache.addBeanMetaData( ( Class<T> ) beanClass, ( BeanMetaDataImpl<T> ) metaData );
}
}
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java 2009-04-13 23:29:04 UTC (rev 16312)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validation/engine/ValidatorImpl.java 2009-04-14 13:51:42 UTC (rev 16313)
@@ -19,6 +19,7 @@
import java.lang.reflect.Member;
import java.lang.reflect.Type;
+import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -77,18 +78,18 @@
private GroupChainGenerator groupChainGenerator;
private final ConstraintValidatorFactory constraintValidatorFactory;
-
private final MessageInterpolator messageInterpolator;
-
private final TraversableResolver traversableResolver;
-
private final ConstraintHelper constraintHelper;
+ private final BeanMetaDataCache beanMetaDataCache;
- public ValidatorImpl(ConstraintValidatorFactory constraintValidatorFactory, MessageInterpolator messageInterpolator, TraversableResolver traversableResolver, ConstraintHelper constraintHelper) {
+
+ public ValidatorImpl(ConstraintValidatorFactory constraintValidatorFactory, MessageInterpolator messageInterpolator, TraversableResolver traversableResolver, ConstraintHelper constraintHelper, BeanMetaDataCache beanMetaDataCache) {
this.constraintValidatorFactory = constraintValidatorFactory;
this.messageInterpolator = messageInterpolator;
this.traversableResolver = traversableResolver;
this.constraintHelper = constraintHelper;
+ this.beanMetaDataCache = beanMetaDataCache;
groupChainGenerator = new GroupChainGenerator();
}
@@ -516,7 +517,7 @@
throw new IllegalArgumentException( "Invalid property path." );
}
- List<MetaConstraint<T, ?>> metaConstraintList = getBeanMetaData( clazz ).geMetaConstraintList();
+ List<MetaConstraint<T, ? extends Annotation>> metaConstraintList = getBeanMetaData( clazz ).geMetaConstraintList();
for ( MetaConstraint<T, ?> metaConstraint : metaConstraintList ) {
if ( metaConstraint.getPropertyName().equals( propertyIter.getHead() ) ) {
metaConstraints.add( metaConstraint );
@@ -551,10 +552,10 @@
* {@inheritDoc}
*/
private <T> BeanMetaData<T> getBeanMetaData(Class<T> beanClass) {
- BeanMetaDataImpl<T> metadata = BeanMetaDataCache.getBeanMetaData( beanClass );
+ BeanMetaDataImpl<T> metadata = beanMetaDataCache.getBeanMetaData( beanClass );
if ( metadata == null ) {
- metadata = new BeanMetaDataImpl<T>( beanClass, constraintHelper );
- BeanMetaDataCache.addBeanMetaData( beanClass, metadata );
+ metadata = new BeanMetaDataImpl<T>( beanClass, constraintHelper);
+ beanMetaDataCache.addBeanMetaData( beanClass, metadata );
}
return metadata;
}
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-04-13 23:29:04 UTC (rev 16312)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validation/engine/ResourceBundleMessageInterpolatorTest.java 2009-04-14 13:51:42 UTC (rev 16313)
@@ -45,26 +45,30 @@
private ResourceBundleMessageInterpolator interpolator;
private NotNull notNull;
+ private ConstraintDescriptorImpl<NotNull> notNullDescriptor;
private Size size;
+ private ConstraintDescriptorImpl<Size> sizeDescriptor;
@BeforeTest
public void setUp() {
// Create some annotations for testing using AnnotationProxies
AnnotationDescriptor<NotNull> descriptor = new AnnotationDescriptor<NotNull>( NotNull.class );
notNull = AnnotationFactory.create( descriptor );
+ notNullDescriptor = new ConstraintDescriptorImpl<NotNull>(
+ notNull, new Class<?>[] { }, new ConstraintHelper()
+ );
- AnnotationDescriptor<Size> sizeDescriptor = new AnnotationDescriptor<Size>( Size.class );
- size = AnnotationFactory.create( sizeDescriptor );
+ AnnotationDescriptor<Size> sizeAnnotationDescriptor = new AnnotationDescriptor<Size>( Size.class );
+ size = AnnotationFactory.create( sizeAnnotationDescriptor );
+ sizeDescriptor = new ConstraintDescriptorImpl<Size>(
+ size, new Class<?>[] { }, new ConstraintHelper()
+ );
}
@Test
public void testSuccessfulInterpolation() {
- ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
- notNull, new Class<?>[] { }, new ConstraintHelper()
- );
-
interpolator = new ResourceBundleMessageInterpolator( new TestResourceBundle() );
- MessageInterpolator.Context context = new MessageInterpolatorContext( descriptor, null );
+ MessageInterpolator.Context context = new MessageInterpolatorContext( notNullDescriptor, null );
String expected = "replacement worked";
String actual = interpolator.interpolate( "{foo}", context );
assertEquals( actual, expected, "Wrong substitution" );
@@ -84,12 +88,8 @@
@Test
public void testUnSuccessfulInterpolation() {
- ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
- notNull, new Class<?>[] { }, new ConstraintHelper()
- );
-
interpolator = new ResourceBundleMessageInterpolator( new TestResourceBundle() );
- MessageInterpolator.Context context = new MessageInterpolatorContext( descriptor, null );
+ MessageInterpolator.Context context = new MessageInterpolatorContext( notNullDescriptor, null );
String expected = "foo"; // missing {}
String actual = interpolator.interpolate( "foo", context );
@@ -102,12 +102,8 @@
@Test
public void testUnkownTokenInterpolation() {
- ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
- notNull, new Class<?>[] { }, new ConstraintHelper()
- );
-
interpolator = new ResourceBundleMessageInterpolator( new TestResourceBundle() );
- MessageInterpolator.Context context = new MessageInterpolatorContext( descriptor, null );
+ MessageInterpolator.Context context = new MessageInterpolatorContext( notNullDescriptor, null );
String expected = "{bar}"; // unkown token {}
String actual = interpolator.interpolate( "{bar}", context );
@@ -116,20 +112,13 @@
@Test
public void testDefaultInterpolation() {
- ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
- notNull, new Class<?>[] { }, new ConstraintHelper()
- );
-
interpolator = new ResourceBundleMessageInterpolator( new TestResourceBundle() );
- MessageInterpolator.Context context = new MessageInterpolatorContext( descriptor, null );
+ MessageInterpolator.Context context = new MessageInterpolatorContext( notNullDescriptor, null );
String expected = "may not be null";
String actual = interpolator.interpolate( notNull.message(), context );
assertEquals( actual, expected, "Wrong substitution" );
- ConstraintDescriptorImpl<Size> sizeDescriptor = new ConstraintDescriptorImpl<Size>(
- size, new Class<?>[] { }, new ConstraintHelper()
- );
expected = "size must be between 0 and 2147483647"; // unkown token {}
context = new MessageInterpolatorContext( sizeDescriptor, null );
actual = interpolator.interpolate( size.message(), context );
@@ -138,26 +127,18 @@
@Test
public void testMessageInterpolationWithLocale() {
- ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
- notNull, new Class<?>[] { }, new ConstraintHelper()
- );
-
interpolator = new ResourceBundleMessageInterpolator();
String expected = "kann nicht null sein";
- MessageInterpolator.Context context = new MessageInterpolatorContext( descriptor, null );
+ MessageInterpolator.Context context = new MessageInterpolatorContext( notNullDescriptor, null );
String actual = interpolator.interpolate( notNull.message(), context, Locale.GERMAN );
assertEquals( actual, expected, "Wrong substitution" );
}
@Test
public void testFallbackToDefaultLocale() {
- ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
- notNull, new Class<?>[] { }, new ConstraintHelper()
- );
-
interpolator = new ResourceBundleMessageInterpolator();
- MessageInterpolator.Context context = new MessageInterpolatorContext( descriptor, null );
+ MessageInterpolator.Context context = new MessageInterpolatorContext( notNullDescriptor, null );
String expected = "may not be null";
String actual = interpolator.interpolate( notNull.message(), context, Locale.JAPAN );
@@ -166,12 +147,8 @@
@Test
public void testUserResourceBundle() {
- ConstraintDescriptorImpl<NotNull> descriptor = new ConstraintDescriptorImpl<NotNull>(
- notNull, new Class<?>[] { }, new ConstraintHelper()
- );
-
interpolator = new ResourceBundleMessageInterpolator();
- MessageInterpolator.Context context = new MessageInterpolatorContext( descriptor, null );
+ MessageInterpolator.Context context = new MessageInterpolatorContext( notNullDescriptor, null );
String expected = "no puede ser null";
String actual = interpolator.interpolate( notNull.message(), context, new Locale( "es", "ES" ) );
15 years, 7 months