Hibernate SVN: r19637 - in validator/trunk/hibernate-validator/src/main/docbook/en-US: modules and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-05-31 10:55:26 -0400 (Mon, 31 May 2010)
New Revision: 19637
Added:
validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/extensions.xml
validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/programmaticapi.xml
Modified:
validator/trunk/hibernate-validator/src/main/docbook/en-US/master.xml
validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/annotationprocessor.xml
validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/furtherreading.xml
Log:
HV-274 restructured docs to allow new section for programmatic API
Modified: validator/trunk/hibernate-validator/src/main/docbook/en-US/master.xml
===================================================================
--- validator/trunk/hibernate-validator/src/main/docbook/en-US/master.xml 2010-05-31 14:31:14 UTC (rev 19636)
+++ validator/trunk/hibernate-validator/src/main/docbook/en-US/master.xml 2010-05-31 14:55:26 UTC (rev 19637)
@@ -68,7 +68,7 @@
<xi:include href="modules/integration.xml"
xmlns:xi="http://www.w3.org/2001/XInclude"/>
- <xi:include href="modules/annotationprocessor.xml"
+ <xi:include href="modules/extensions.xml"
xmlns:xi="http://www.w3.org/2001/XInclude"/>
<xi:include href="modules/furtherreading.xml"
Modified: validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/annotationprocessor.xml
===================================================================
--- validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/annotationprocessor.xml 2010-05-31 14:31:14 UTC (rev 19636)
+++ validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/annotationprocessor.xml 2010-05-31 14:55:26 UTC (rev 19637)
@@ -21,8 +21,8 @@
<!ENTITY % BOOK_ENTITIES SYSTEM "../hv.ent">
%BOOK_ENTITIES;
]>
-<chapter>
- <title id="chapter-annotation-processor">Hibernate Validator Annotation
+<section>
+ <title id="annotation-processor">Hibernate Validator Annotation
Processor (EXPERIMENTAL)</title>
<para>Have you ever caught yourself by unintentionally doing things
@@ -482,4 +482,4 @@
</listitem>
</itemizedlist>
</section>
-</chapter>
+</section>
Added: validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/extensions.xml
===================================================================
--- validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/extensions.xml (rev 0)
+++ validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/extensions.xml 2010-05-31 14:55:26 UTC (rev 19637)
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- $Id$ -->
+<!--
+ ~ JBoss, Home of Professional Open Source
+ ~ Copyright 2009, Red Hat, Inc. and/or its affiliates, 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.
+-->
+<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
+"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
+<!ENTITY % BOOK_ENTITIES SYSTEM "../hv.ent">
+%BOOK_ENTITIES;
+]>
+<chapter id="extensions">
+ <title>Hibernate Validator Specific Extensions</title>
+
+ <para>Hibernate Validator offers on top of the Bean Validation requirements additional extensions which are described in the following sections.</para>
+
+ <xi:include href="programmaticapi.xml"
+ xmlns:xi="http://www.w3.org/2001/XInclude"/>
+ <xi:include href="annotationprocessor.xml"
+ xmlns:xi="http://www.w3.org/2001/XInclude"/>
+
+</chapter>
Property changes on: validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/extensions.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Modified: validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/furtherreading.xml
===================================================================
--- validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/furtherreading.xml 2010-05-31 14:31:14 UTC (rev 19636)
+++ validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/furtherreading.xml 2010-05-31 14:55:26 UTC (rev 19637)
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
-<!-- $Id: bootstrapping.xml 17523 2009-09-16 15:51:58Z hardy.ferentschik $ -->
+<!-- $Id$ -->
<!--
~ JBoss, Home of Professional Open Source
~ Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors
Property changes on: validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/furtherreading.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Added: validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/programmaticapi.xml
===================================================================
--- validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/programmaticapi.xml (rev 0)
+++ validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/programmaticapi.xml 2010-05-31 14:55:26 UTC (rev 19637)
@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- $Id$ -->
+<!--
+ ~ JBoss, Home of Professional Open Source
+ ~ Copyright 2009, Red Hat, Inc. and/or its affiliates, 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.
+-->
+<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
+"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
+<!ENTITY % BOOK_ENTITIES SYSTEM "../hv.ent">
+%BOOK_ENTITIES;
+]>
+<section id="programmaticapi">
+ <title>Programmatic constraint definitions</title>
+
+ <para><example>
+ <title>Creating a Hibernate Validator specific configuration</title>
+
+ <programlisting>HibernateValidatorConfiguration config = Validation.byProvider( HibernateValidator.class ).configure();</programlisting>
+ </example></para>
+
+ <para><example>
+ <title>Programmatic constraint definition</title>
+
+ <programlisting>ConstraintMapping mapping = new ConstraintMapping();
+mapping.type( Marathon.class )
+ .property( "name", METHOD )
+ .constraint( NotNullDef.class )
+ .property( "numberOfHelpers", FIELD )
+ .constraint( MinDef.class ).value( 1 );
+
+
+HibernateValidatorConfiguration config = Validation.byProvider( HibernateValidator.class ).configure();
+ValidatorFactory factory = config.buildValidatorFactory();
+Validator validator = factory.getValidator();
+validator.validate( new Marathon() );</programlisting>
+
+ <para></para>
+ </example></para>
+</section>
Property changes on: validator/trunk/hibernate-validator/src/main/docbook/en-US/modules/programmaticapi.xml
___________________________________________________________________
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
14 years, 7 months
Hibernate SVN: r19636 - validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-05-31 10:31:14 -0400 (Mon, 31 May 2010)
New Revision: 19636
Modified:
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/MarathonConstraint.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/MarathonConstraintValidator.java
Log:
HV-274 svn keyword substitution
Property changes on: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/MarathonConstraint.java
___________________________________________________________________
Name: svn:keywords
+ Id
Property changes on: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/MarathonConstraintValidator.java
___________________________________________________________________
Name: svn:keywords
+ Id
14 years, 7 months
Hibernate SVN: r19635 - in validator/trunk/hibernate-validator/src: main/java/org/hibernate/validator/cfg/defs and 3 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-05-31 10:03:26 -0400 (Mon, 31 May 2010)
New Revision: 19635
Added:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintDefWrapper.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/defs/GenericConstraintDef.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/MarathonConstraint.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/MarathonConstraintValidator.java
Removed:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintDefAccessor.java
Modified:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintDef.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintMapping.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintsForType.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/engine/ValidatorFactoryImpl.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/ConstraintMappingTest.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/Marathon.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/util/TestUtil.java
Log:
HV-274 Added implementation for Generic ConstraintDef
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintDef.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintDef.java 2010-05-31 10:48:08 UTC (rev 19634)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintDef.java 2010-05-31 14:03:26 UTC (rev 19635)
@@ -30,7 +30,7 @@
* @author Hardy Ferentschik
*/
public class ConstraintDef<A extends Annotation> {
- protected final Class<A> constraintType;
+ protected Class<A> constraintType;
protected final Map<String, Object> parameters;
protected final Class<?> beanType;
protected final ElementType elementType;
@@ -46,10 +46,6 @@
throw new ValidationException( "Null is not a valid bean type" );
}
- if ( constraintType == null ) {
- throw new ValidationException( "Null is not a valid constraint type" );
- }
-
if ( mapping == null ) {
throw new ValidationException( "ConstraintMapping cannot be null" );
}
Deleted: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintDefAccessor.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintDefAccessor.java 2010-05-31 10:48:08 UTC (rev 19634)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintDefAccessor.java 2010-05-31 14:03:26 UTC (rev 19635)
@@ -1,52 +0,0 @@
-// $Id$
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2010, Red Hat, Inc. and/or its affiliates, 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.validator.cfg;
-
-import java.lang.annotation.Annotation;
-import java.lang.annotation.ElementType;
-import java.util.Map;
-
-/**
- * @author Hardy Ferentschik
- */
-public class ConstraintDefAccessor<A extends Annotation> extends ConstraintDef<A> {
-
- public ConstraintDefAccessor(Class<?> beanType, Class<A> constraintType, String property, ElementType elementType, Map<String, Object> parameters, ConstraintMapping mapping) {
- super( beanType, constraintType, property, elementType, parameters, mapping );
- }
-
- public Class<A> getConstraintType() {
- return constraintType;
- }
-
- public Map<String, Object> getParameters() {
- return this.parameters;
- }
-
- public ElementType getElementType() {
- return elementType;
- }
-
- public Class<?> getBeanType() {
- return beanType;
- }
-
- public String getProperty() {
- return property;
- }
-}
\ No newline at end of file
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintDefWrapper.java (from rev 19608, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintDefAccessor.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintDefWrapper.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintDefWrapper.java 2010-05-31 14:03:26 UTC (rev 19635)
@@ -0,0 +1,52 @@
+// $Id$
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2010, Red Hat, Inc. and/or its affiliates, 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.validator.cfg;
+
+import java.lang.annotation.Annotation;
+import java.lang.annotation.ElementType;
+import java.util.Map;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class ConstraintDefWrapper<A extends Annotation> extends ConstraintDef<A> {
+
+ public ConstraintDefWrapper(Class<?> beanType, Class<A> constraintType, String property, ElementType elementType, Map<String, Object> parameters, ConstraintMapping mapping) {
+ super( beanType, constraintType, property, elementType, parameters, mapping );
+ }
+
+ public Class<A> getConstraintType() {
+ return constraintType;
+ }
+
+ public Map<String, Object> getParameters() {
+ return this.parameters;
+ }
+
+ public ElementType getElementType() {
+ return elementType;
+ }
+
+ public Class<?> getBeanType() {
+ return beanType;
+ }
+
+ public String getProperty() {
+ return property;
+ }
+}
\ No newline at end of file
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintDefWrapper.java
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintMapping.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintMapping.java 2010-05-31 10:48:08 UTC (rev 19634)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintMapping.java 2010-05-31 14:03:26 UTC (rev 19635)
@@ -33,75 +33,62 @@
* @author Hardy Ferentschik
*/
public class ConstraintMapping {
- private final Map<Class<?>, List<ConstraintDefAccessor<?>>> constraintConfig;
+ private final Map<Class<?>, List<ConstraintDef<?>>> constraintConfig;
private final Map<Class<?>, List<CascadeDef>> cascadeConfig;
private final Set<Class<?>> configuredClasses;
private final Map<Class<?>, List<Class<?>>> defaultGroupSequences;
public ConstraintMapping() {
- this.constraintConfig = new HashMap<Class<?>, List<ConstraintDefAccessor<?>>>();
+ this.constraintConfig = new HashMap<Class<?>, List<ConstraintDef<?>>>();
this.cascadeConfig = new HashMap<Class<?>, List<CascadeDef>>();
this.configuredClasses = new HashSet<Class<?>>();
this.defaultGroupSequences = new HashMap<Class<?>, List<Class<?>>>();
}
- public ConstraintsForType type(Class<?> beanClass) {
+ /**
+ * Starts defining constraints on the specified bean class.
+ *
+ * @param beanClass The bean class on which to define constraints. All constraints defined after calling this method
+ * are added to the bean of the type {@code beanClass} until the next call of {@code type}.
+ *
+ * @return Instance allowing for defining constraints on the specified class.
+ */
+ public final ConstraintsForType type(Class<?> beanClass) {
return new ConstraintsForType( beanClass, this );
}
- protected <A extends Annotation> void addConstraintConfig(ConstraintDef<?> definition) {
- Class<?> beanClass = definition.beanType;
- @SuppressWarnings( "unchecked")
- ConstraintDefAccessor<A> defAccessor = new ConstraintDefAccessor<A>(
- beanClass,
- ( Class<A> ) definition.constraintType,
- definition.property,
- definition.elementType,
- definition.parameters,
- this
- );
+ public final <A extends Annotation> Map<Class<?>, List<ConstraintDefWrapper<?>>> getConstraintConfig() {
+ Map<Class<?>, List<ConstraintDefWrapper<?>>> newDefinitions = new HashMap<Class<?>, List<ConstraintDefWrapper<?>>>();
+ for ( Map.Entry<Class<?>, List<ConstraintDef<?>>> entry : constraintConfig.entrySet() ) {
- configuredClasses.add( beanClass );
- if ( constraintConfig.containsKey( beanClass ) ) {
- constraintConfig.get( beanClass ).add( defAccessor );
+ List<ConstraintDefWrapper<?>> newList = new ArrayList<ConstraintDefWrapper<?>>();
+ for ( ConstraintDef<?> definition : entry.getValue() ) {
+ Class<?> beanClass = definition.beanType;
+ @SuppressWarnings("unchecked")
+ ConstraintDefWrapper<A> defAccessor = new ConstraintDefWrapper<A>(
+ beanClass,
+ ( Class<A> ) definition.constraintType,
+ definition.property,
+ definition.elementType,
+ definition.parameters,
+ this
+ );
+ newList.add( defAccessor );
+ }
+ newDefinitions.put( entry.getKey(), newList );
}
- else {
- List<ConstraintDefAccessor<?>> definitionList = new ArrayList<ConstraintDefAccessor<?>>();
- definitionList.add( defAccessor );
- constraintConfig.put( beanClass, definitionList );
- }
+ return newDefinitions;
}
- protected void addCascadeConfig(CascadeDef cascade) {
- Class<?> beanClass = cascade.getBeanType();
- configuredClasses.add( beanClass );
- if ( cascadeConfig.containsKey( beanClass ) ) {
- cascadeConfig.get( beanClass ).add( cascade );
- }
- else {
- List<CascadeDef> cascadeList = new ArrayList<CascadeDef>();
- cascadeList.add( cascade );
- cascadeConfig.put( beanClass, cascadeList );
- }
- }
-
- protected void addDefaultGroupSequence(Class<?> beanClass, List<Class<?>> defaultGroupSequence) {
- defaultGroupSequences.put( beanClass, defaultGroupSequence );
- }
-
- public Map<Class<?>, List<ConstraintDefAccessor<?>>> getConstraintConfig() {
- return constraintConfig;
- }
-
- public Map<Class<?>, List<CascadeDef>> getCascadeConfig() {
+ public final Map<Class<?>, List<CascadeDef>> getCascadeConfig() {
return cascadeConfig;
}
- public Collection<Class<?>> getConfiguredClasses() {
+ public final Collection<Class<?>> getConfiguredClasses() {
return configuredClasses;
}
- public List<Class<?>> getDefaultSequence(Class<?> beanType) {
+ public final List<Class<?>> getDefaultSequence(Class<?> beanType) {
if ( defaultGroupSequences.containsKey( beanType ) ) {
return defaultGroupSequences.get( beanType );
}
@@ -121,6 +108,36 @@
sb.append( '}' );
return sb.toString();
}
+
+ protected final void addCascadeConfig(CascadeDef cascade) {
+ Class<?> beanClass = cascade.getBeanType();
+ configuredClasses.add( beanClass );
+ if ( cascadeConfig.containsKey( beanClass ) ) {
+ cascadeConfig.get( beanClass ).add( cascade );
+ }
+ else {
+ List<CascadeDef> cascadeList = new ArrayList<CascadeDef>();
+ cascadeList.add( cascade );
+ cascadeConfig.put( beanClass, cascadeList );
+ }
+ }
+
+ protected final void addDefaultGroupSequence(Class<?> beanClass, List<Class<?>> defaultGroupSequence) {
+ defaultGroupSequences.put( beanClass, defaultGroupSequence );
+ }
+
+ protected final void addConstraintConfig(ConstraintDef<?> definition) {
+ Class<?> beanClass = definition.beanType;
+ configuredClasses.add( beanClass );
+ if ( constraintConfig.containsKey( beanClass ) ) {
+ constraintConfig.get( beanClass ).add( definition );
+ }
+ else {
+ List<ConstraintDef<?>> definitionList = new ArrayList<ConstraintDef<?>>();
+ definitionList.add( definition );
+ constraintConfig.put( beanClass, definitionList );
+ }
+ }
}
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintsForType.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintsForType.java 2010-05-31 10:48:08 UTC (rev 19634)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/ConstraintsForType.java 2010-05-31 14:03:26 UTC (rev 19635)
@@ -27,9 +27,11 @@
import static java.lang.annotation.ElementType.TYPE;
/**
+ * Via instances of this class constraints and cascading properties can be configured for a single bean class.
+ *
* @author Hardy Ferentschik
*/
-public class ConstraintsForType {
+public final class ConstraintsForType {
private static final String EMPTY_PROPERTY = "";
private final ConstraintMapping mapping;
@@ -48,6 +50,13 @@
this.elementType = type;
}
+ /**
+ * Add a new constraint.
+ *
+ * @param definition The constraint definition class
+ *
+ * @return A constraint definition class allowing to specify additional constraint parameters.
+ */
public <A extends Annotation, T extends ConstraintDef<A>> T constraint(Class<T> definition) {
final Constructor<T> constructor = ReflectionHelper.getConstructor(
definition, Class.class, String.class, ElementType.class, ConstraintMapping.class
@@ -60,6 +69,15 @@
return constraintDefinition;
}
+ /**
+ * Changes the property for which added constraints apply. Until this method is called constraints apply on
+ * class level. After calling this method constraints apply on the specified property with the given access type.
+ *
+ * @param property The property on which to apply the following constraints (Java Bean notation)
+ * @param type The access type (field/property)
+ *
+ * @return Returns itself for method chaining
+ */
public ConstraintsForType property(String property, ElementType type) {
return new ConstraintsForType( beanClass, property, type, mapping );
}
@@ -69,13 +87,26 @@
return this;
}
+ /**
+ * Defines the default groups sequence for the bean class of this instance.
+ *
+ * @param defaultGroupSequence the default group sequence.
+ *
+ * @return Returns itself for method chaining.
+ */
public ConstraintsForType defaultGroupSequence(Class<?>... defaultGroupSequence) {
mapping.addDefaultGroupSequence( beanClass, Arrays.asList( defaultGroupSequence ) );
return this;
}
- public ConstraintsForType type(Class<?> type, Class<?>... defaultGroupSequence) {
- mapping.addDefaultGroupSequence( type, Arrays.asList( defaultGroupSequence ) );
+ /**
+ * Creates a new {@code ConstraintsForType} in order to define constraints on a new bean type.
+ *
+ * @param type the bean type
+ *
+ * @return a new {@code ConstraintsForType} instance
+ */
+ public ConstraintsForType type(Class<?> type) {
return new ConstraintsForType( type, mapping );
}
}
Copied: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/defs/GenericConstraintDef.java (from rev 19606, validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/defs/AssertFalseDef.java)
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/defs/GenericConstraintDef.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/defs/GenericConstraintDef.java 2010-05-31 14:03:26 UTC (rev 19635)
@@ -0,0 +1,65 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2010, Red Hat, Inc. and/or its affiliates, 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.
+ */
+
+// $Id$
+
+package org.hibernate.validator.cfg.defs;
+
+import java.lang.annotation.ElementType;
+import javax.validation.Payload;
+
+import org.hibernate.validator.cfg.ConstraintDef;
+import org.hibernate.validator.cfg.ConstraintMapping;
+
+/**
+ * A {@code ConstraintDef} class which can be used to configure any constraint type. For this purpose the class defines
+ * a {@code constraintType} method to specify the constraint type and a generic {@code param(Stringkey,Objectvalue)}
+ * to add arbitrary constraint parameters.
+ *
+ * @author Hardy Ferentschik
+ */
+public class GenericConstraintDef extends ConstraintDef {
+
+ public GenericConstraintDef(Class<?> beanType, String property, ElementType elementType, ConstraintMapping mapping) {
+ super( beanType, null, property, elementType, mapping );
+ }
+
+ public GenericConstraintDef message(String message) {
+ addParameter( "message", message );
+ return this;
+ }
+
+ public GenericConstraintDef groups(Class<?>... groups) {
+ addParameter( "groups", groups );
+ return this;
+ }
+
+ public GenericConstraintDef payload(Class<? extends Payload>... payload) {
+ addParameter( "payload", payload );
+ return this;
+ }
+
+ public GenericConstraintDef param(String key, Object value) {
+ addParameter( key, value );
+ return this;
+ }
+
+ public GenericConstraintDef constraintType(Class<?> constraintType) {
+ this.constraintType = constraintType;
+ return this;
+ }
+}
\ No newline at end of file
Property changes on: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/cfg/defs/GenericConstraintDef.java
___________________________________________________________________
Name: svn:keywords
+ Id
Modified: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/engine/ValidatorFactoryImpl.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/engine/ValidatorFactoryImpl.java 2010-05-31 10:48:08 UTC (rev 19634)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/engine/ValidatorFactoryImpl.java 2010-05-31 14:03:26 UTC (rev 19635)
@@ -35,7 +35,7 @@
import javax.validation.spi.ConfigurationState;
import org.hibernate.validator.cfg.CascadeDef;
-import org.hibernate.validator.cfg.ConstraintDefAccessor;
+import org.hibernate.validator.cfg.ConstraintDefWrapper;
import org.hibernate.validator.cfg.ConstraintMapping;
import org.hibernate.validator.metadata.AnnotationIgnores;
import org.hibernate.validator.metadata.BeanMetaDataCache;
@@ -228,19 +228,22 @@
}
@SuppressWarnings("unchecked")
- private <T, A extends Annotation> void addProgrammaticConfiguredConstraints(List<ConstraintDefAccessor<?>> definitions,
+ private <T, A extends Annotation> void addProgrammaticConfiguredConstraints(List<ConstraintDefWrapper<?>> definitions,
Class<T> rootClass, Class<?> hierarchyClass,
Map<Class<?>, List<MetaConstraint<T, ?>>> constraints) {
- for ( ConstraintDefAccessor<?> config : definitions ) {
+ for ( ConstraintDefWrapper<?> config : definitions ) {
A annotation = ( A ) createAnnotationProxy( config );
ConstraintOrigin definedIn = definedIn( rootClass, hierarchyClass );
ConstraintDescriptorImpl<A> constraintDescriptor = new ConstraintDescriptorImpl<A>(
annotation, constraintHelper, config.getElementType(), definedIn
);
- Member member = ReflectionHelper.getMember(
- config.getBeanType(), config.getProperty(), config.getElementType()
- );
+ Member member = null;
+ if ( !config.getProperty().isEmpty() ) {
+ member = ReflectionHelper.getMember(
+ config.getBeanType(), config.getProperty(), config.getElementType()
+ );
+ }
MetaConstraint<T, ?> metaConstraint = new MetaConstraint(
config.getBeanType(), member, constraintDescriptor
@@ -299,7 +302,7 @@
}
@SuppressWarnings("unchecked")
- private <A extends Annotation> Annotation createAnnotationProxy(ConstraintDefAccessor<?> config) {
+ private <A extends Annotation> Annotation createAnnotationProxy(ConstraintDefWrapper<?> config) {
Class<A> constraintType = ( Class<A> ) config.getConstraintType();
AnnotationDescriptor<A> annotationDescriptor = new AnnotationDescriptor<A>( constraintType );
for ( Map.Entry<String, Object> parameter : config.getParameters().entrySet() ) {
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/ConstraintMappingTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/ConstraintMappingTest.java 2010-05-31 10:48:08 UTC (rev 19634)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/ConstraintMappingTest.java 2010-05-31 14:03:26 UTC (rev 19635)
@@ -30,9 +30,10 @@
import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.HibernateValidatorConfiguration;
+import org.hibernate.validator.cfg.ConstraintMapping;
import org.hibernate.validator.cfg.defs.AssertTrueDef;
-import org.hibernate.validator.cfg.ConstraintMapping;
import org.hibernate.validator.cfg.defs.FutureDef;
+import org.hibernate.validator.cfg.defs.GenericConstraintDef;
import org.hibernate.validator.cfg.defs.MinDef;
import org.hibernate.validator.cfg.defs.NotEmptyDef;
import org.hibernate.validator.cfg.defs.NotNullDef;
@@ -43,6 +44,7 @@
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static org.hibernate.validator.test.util.TestUtil.assertConstraintViolation;
+import static org.hibernate.validator.test.util.TestUtil.assertCorrectConstraintViolationMessages;
import static org.hibernate.validator.test.util.TestUtil.assertNumberOfViolations;
import static org.testng.Assert.assertTrue;
import static org.testng.FileAssert.fail;
@@ -58,9 +60,9 @@
ConstraintMapping mapping = new ConstraintMapping();
mapping.type( Marathon.class )
.property( "name", METHOD )
- .constraint( NotNullDef.class )
- .property( "numberOfRunners", FIELD )
- .constraint( MinDef.class ).value( 1 );
+ .constraint( NotNullDef.class )
+ .property( "numberOfHelpers", FIELD )
+ .constraint( MinDef.class ).value( 1 );
assertTrue( mapping.getConstraintConfig().containsKey( Marathon.class ) );
assertTrue( mapping.getConstraintConfig().get( Marathon.class ).size() == 2 );
@@ -83,7 +85,7 @@
ConstraintMapping mapping = new ConstraintMapping();
mapping.type( Marathon.class )
.property( "name", METHOD )
- .constraint( NotNullDef.class );
+ .constraint( NotNullDef.class );
config.addMapping( mapping );
@@ -101,12 +103,12 @@
ConstraintMapping mapping = new ConstraintMapping();
mapping
- .type( Marathon.class )
+ .type( Marathon.class )
.property( "name", METHOD )
- .constraint( NotNullDef.class )
- .type( Tournament.class )
+ .constraint( NotNullDef.class )
+ .type( Tournament.class )
.property( "tournamentDate", METHOD )
- .constraint( FutureDef.class );
+ .constraint( FutureDef.class );
config.addMapping( mapping );
@@ -130,10 +132,10 @@
ConstraintMapping mapping = new ConstraintMapping();
mapping.type( Marathon.class )
- .valid( "runners", METHOD )
+ .valid( "runners", METHOD )
.type( Runner.class )
- .property( "paidEntryFee", FIELD )
- .constraint( AssertTrueDef.class );
+ .property( "paidEntryFee", FIELD )
+ .constraint( AssertTrueDef.class );
config.addMapping( mapping );
@@ -157,9 +159,9 @@
ConstraintMapping mapping = new ConstraintMapping();
try {
mapping
- .type( Marathon.class )
- .property( "numberOfRunners", METHOD )
- .constraint( NotNullDef.class );
+ .type( Marathon.class )
+ .property( "numberOfHelpers", METHOD )
+ .constraint( NotNullDef.class );
fail();
}
catch ( ValidationException e ) {
@@ -173,12 +175,12 @@
ConstraintMapping mapping = new ConstraintMapping();
mapping
- .type( Marathon.class )
+ .type( Marathon.class )
.defaultGroupSequence( Foo.class, Marathon.class )
.property( "name", METHOD )
- .constraint( NotNullDef.class ).groups( Foo.class )
+ .constraint( NotNullDef.class ).groups( Foo.class )
.property( "runners", METHOD )
- .constraint( NotEmptyDef.class );
+ .constraint( NotEmptyDef.class );
config.addMapping( mapping );
@@ -197,15 +199,15 @@
assertConstraintViolation( violations.iterator().next(), "may not be empty" );
}
- @Test
+ @Test
public void testMultipleConstraintOfTheSameType() {
HibernateValidatorConfiguration config = TestUtil.getConfiguration( HibernateValidator.class );
ConstraintMapping mapping = new ConstraintMapping();
mapping.type( Marathon.class )
.property( "name", METHOD )
- .constraint( SizeDef.class ).min( 5 )
- .constraint( SizeDef.class ).min( 10 );
+ .constraint( SizeDef.class ).min( 5 )
+ .constraint( SizeDef.class ).min( 10 );
config.addMapping( mapping );
@@ -227,6 +229,65 @@
assertNumberOfViolations( violations, 0 );
}
+ @Test
+ public void testCustomConstraintTypeMissingParameter() {
+ ConstraintMapping mapping = new ConstraintMapping();
+ mapping.type( Marathon.class )
+ .constraint( GenericConstraintDef.class )
+ .constraintType( MarathonConstraint.class );
+
+ HibernateValidatorConfiguration config = TestUtil.getConfiguration( HibernateValidator.class );
+ config.addMapping( mapping );
+ try {
+ config.buildValidatorFactory();
+ fail( "MarathonConstraints needs a parameter" );
+ }
+ catch ( ValidationException e ) {
+ assertTrue( e.getMessage().contains( "No value provided for minRunner" ) );
+ }
+ }
+
+ @Test
+ public void testCustomConstraintType() {
+ ConstraintMapping mapping = new ConstraintMapping();
+ mapping.type( Marathon.class )
+ .constraint( GenericConstraintDef.class )
+ .constraintType( MarathonConstraint.class )
+ .param( "minRunner", 100 )
+ .message( "Needs more runners" );
+
+ HibernateValidatorConfiguration config = TestUtil.getConfiguration( HibernateValidator.class );
+ config.addMapping( mapping );
+
+ ValidatorFactory factory = config.buildValidatorFactory();
+ Validator validator = factory.getValidator();
+
+ Marathon marathon = new Marathon();
+ marathon.setName( "Stockholm Marathon" );
+
+ Set<ConstraintViolation<Marathon>> violations = validator.validate( marathon );
+ assertNumberOfViolations( violations, 1 );
+ assertCorrectConstraintViolationMessages( violations, "Needs more runners" );
+
+ for ( int i = 0; i < 100; i++ ) {
+ marathon.addRunner( new Runner() );
+ }
+ violations = validator.validate( marathon );
+ assertNumberOfViolations( violations, 0 );
+ }
+
+ @Test(expectedExceptions = ValidationException.class)
+ public void testNullBean() {
+ ConstraintMapping mapping = new ConstraintMapping();
+ mapping.type( null )
+ .constraint( GenericConstraintDef.class )
+ .constraintType( MarathonConstraint.class );
+
+ HibernateValidatorConfiguration config = TestUtil.getConfiguration( HibernateValidator.class );
+ config.addMapping( mapping );
+ config.buildValidatorFactory();
+ }
+
public interface Foo {
}
}
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/Marathon.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/Marathon.java 2010-05-31 10:48:08 UTC (rev 19634)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/Marathon.java 2010-05-31 14:03:26 UTC (rev 19635)
@@ -25,9 +25,10 @@
* @author Hardy Ferentschik
*/
public class Marathon implements Tournament {
+
private String name;
- private long numberOfRunners;
+ private long numberOfHelpers;
private Date tournamentDate;
Added: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/MarathonConstraint.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/MarathonConstraint.java (rev 0)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/MarathonConstraint.java 2010-05-31 14:03:26 UTC (rev 19635)
@@ -0,0 +1,44 @@
+// $Id:$
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2010, Red Hat, Inc. and/or its affiliates, 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.validator.test.cfg;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+import javax.validation.Constraint;
+import javax.validation.Payload;
+
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+/**
+ * @author Hardy Ferentschik
+ */
+@Target({ TYPE })
+@Retention(RUNTIME)
+@Constraint(validatedBy = { MarathonConstraintValidator.class })
+public @interface MarathonConstraint {
+ public String message() default "invalid name";
+
+ public Class<?>[] groups() default { };
+
+ public Class<? extends Payload>[] payload() default { };
+
+ public int minRunner();
+}
+
+
Added: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/MarathonConstraintValidator.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/MarathonConstraintValidator.java (rev 0)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/cfg/MarathonConstraintValidator.java 2010-05-31 14:03:26 UTC (rev 19635)
@@ -0,0 +1,39 @@
+// $Id:$
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2010, Red Hat, Inc. and/or its affiliates, 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.validator.test.cfg;
+
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class MarathonConstraintValidator implements ConstraintValidator<MarathonConstraint, Marathon> {
+ private int minRunners;
+
+ public void initialize(MarathonConstraint constraintAnnotation) {
+ minRunners = constraintAnnotation.minRunner();
+ }
+
+ public boolean isValid(Marathon m, ConstraintValidatorContext context) {
+ return m.getRunners().size() >= minRunners;
+ }
+}
+
+
Modified: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/util/TestUtil.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/util/TestUtil.java 2010-05-31 10:48:08 UTC (rev 19634)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/test/util/TestUtil.java 2010-05-31 14:03:26 UTC (rev 19635)
@@ -29,8 +29,6 @@
import javax.validation.Path;
import javax.validation.Validation;
import javax.validation.Validator;
-import javax.validation.metadata.ConstraintDescriptor;
-import javax.validation.metadata.ElementDescriptor;
import javax.validation.metadata.PropertyDescriptor;
import javax.validation.spi.ValidationProvider;
@@ -162,16 +160,6 @@
}
}
- public static void assertConstraintViolation(ConstraintViolation violation, String errorMessage, Class rootBean, Object invalidValue, String propertyPath, Class leafBean) {
- assertEquals(
-
- violation.getLeafBean().getClass(),
- leafBean,
- "Wrong leaf bean type"
- );
- assertConstraintViolation( violation, errorMessage, rootBean, invalidValue, propertyPath );
- }
-
public static void assertConstraintViolation(ConstraintViolation violation, String errorMessage, Class rootBean, Object invalidValue, String propertyPath) {
assertEquals(
violation.getPropertyPath(),
@@ -271,18 +259,4 @@
return super.getResourceAsStream( finalPath );
}
}
-
- private static class IgnoringValidationXmlClassLoader extends ClassLoader {
- IgnoringValidationXmlClassLoader() {
- super( IgnoringValidationXmlClassLoader.class.getClassLoader() );
- }
-
- public InputStream getResourceAsStream(String path) {
- if ( "META-INF/validation.xml".equals( path ) ) {
- log.info( "Ignoring call to load validation.xml" );
- return null;
- }
- return super.getResourceAsStream( path );
- }
- }
}
14 years, 7 months
Hibernate SVN: r19634 - in core/trunk/annotations: src/main/java/org/hibernate/cfg and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-05-31 06:48:08 -0400 (Mon, 31 May 2010)
New Revision: 19634
Modified:
core/trunk/annotations/pom.xml
core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/ExtendedMappings.java
core/trunk/annotations/src/main/java/org/hibernate/cfg/VerifyFetchProfileReferenceSecondPass.java
core/trunk/annotations/src/test/java/org/hibernate/test/annotations/fetchprofile/MoreFetchProfileTest.java
Log:
HHH-5233 Fixed implementation for multiple fetch profiles overrides. Cleaned up pom.
Modified: core/trunk/annotations/pom.xml
===================================================================
--- core/trunk/annotations/pom.xml 2010-05-30 20:47:31 UTC (rev 19633)
+++ core/trunk/annotations/pom.xml 2010-05-31 10:48:08 UTC (rev 19634)
@@ -22,7 +22,9 @@
~ 51 Franklin Street, Fifth Floor
~ Boston, MA 02110-1301 USA
-->
-<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">
+<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>
@@ -44,7 +46,7 @@
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
- <version>${version}</version>
+ <version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
@@ -54,12 +56,12 @@
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
</dependency>
- <dependency>
- <groupId>${groupId}</groupId>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
<artifactId>hibernate-testing</artifactId>
- <version>${version}</version>
- <scope>test</scope>
- </dependency>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
@@ -85,13 +87,6 @@
<build>
<testResources>
<testResource>
- <filtering>false</filtering>
- <directory>src/test/java</directory>
- <includes>
- <include>**/*.xml</include>
- </includes>
- </testResource>
- <testResource>
<filtering>true</filtering>
<directory>src/test/resources</directory>
</testResource>
@@ -116,17 +111,17 @@
<configuration>
<bytecodeInjections>
<bytecodeInjection>
- <expression>${pom.version}</expression>
+ <expression>${project.version}</expression>
<targetMembers>
- <methodBodyReturn>
- <className>org.hibernate.cfg.annotations.Version</className>
- <methodName>getVersionString</methodName>
- </methodBodyReturn>
+ <methodBodyReturn>
+ <className>org.hibernate.cfg.annotations.Version</className>
+ <methodName>getVersionString</methodName>
+ </methodBodyReturn>
</targetMembers>
</bytecodeInjection>
</bytecodeInjections>
</configuration>
- </plugin>
+ </plugin>
<plugin>
<groupId>org.twdata.maven</groupId>
<artifactId>maven-cli-plugin</artifactId>
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java 2010-05-30 20:47:31 UTC (rev 19633)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/AnnotationConfiguration.java 2010-05-31 10:48:08 UTC (rev 19634)
@@ -163,6 +163,7 @@
private boolean isValidatorNotPresentLogged;
private Map<XClass, Map<String, PropertyData>> propertiesAnnotatedWithMapsId;
private Map<XClass, Map<String, PropertyData>> propertiesAnnotatedWithIdAndToOne;
+ private Collection<FetchProfile> annotationConfiguredProfiles;
public AnnotationConfiguration() {
super();
@@ -268,7 +269,7 @@
}
public ExtendedMappings createExtendedMappings() {
- return new ExtendedMappingsImpl();
+ return new ExtendedMappingsImpl( annotationConfiguredProfiles );
}
@Override
@@ -311,6 +312,7 @@
reflectionManager = new JavaReflectionManager();
( ( MetadataProviderInjector ) reflectionManager ).setMetadataProvider( new JPAMetadataProvider() );
configurationArtefactPrecedence = Collections.emptyList();
+ annotationConfiguredProfiles = new HashSet<FetchProfile>();
}
@Override
@@ -1255,8 +1257,8 @@
private Boolean useNewGeneratorMappings;
private Collection<FetchProfile> annotationConfiguredProfile;
- public ExtendedMappingsImpl() {
- annotationConfiguredProfile = new ArrayList<FetchProfile>();
+ public ExtendedMappingsImpl(Collection<FetchProfile> fetchProfiles) {
+ annotationConfiguredProfile = fetchProfiles;
}
public void addDefaultGenerator(IdGenerator generator) {
@@ -1528,11 +1530,15 @@
return anyMetaDefs.get( name );
}
- public void addAnnotationConfiguredFetchProfile(FetchProfile fetchProfile) {
- annotationConfiguredProfile.add( fetchProfile );
+ public FetchProfile findOrCreateFetchProfile(String name) {
+ FetchProfile profile = super.findOrCreateFetchProfile( name );
+ if ( profile.getFetches().isEmpty() ) {
+ annotationConfiguredProfile.add( profile );
+ }
+ return profile;
}
- public boolean containsAnnotationConfiguredFetchProfile(FetchProfile fetchProfile) {
+ public boolean isAnnotationConfiguredFetchProfile(FetchProfile fetchProfile) {
for ( FetchProfile profile : annotationConfiguredProfile ) {
// we need reference equality there!!
if ( profile == fetchProfile ) {
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/ExtendedMappings.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/ExtendedMappings.java 2010-05-30 20:47:31 UTC (rev 19633)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/ExtendedMappings.java 2010-05-31 10:48:08 UTC (rev 19634)
@@ -1,4 +1,4 @@
-// $Id:$
+// $Id$
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
@@ -207,14 +207,8 @@
void addToOneAndIdProperty(XClass entity, PropertyData property);
/**
- * Add the specified profile to the list of fetch profiles configured via annotations.
- *
- * @param fetchProfile the fetch profile
+ * @param fetchProfile The fetch profile to test.
+ * @return {@code true} if the provided fetch profile has been configured via annotations, {@code false} otherwise.
*/
- void addAnnotationConfiguredFetchProfile(FetchProfile fetchProfile);
-
- /**
- * @return {@true} if the provided fetch profile has been configured via xml, {@false otherwise}.
- */
- boolean containsAnnotationConfiguredFetchProfile(FetchProfile fetchProfile);
+ boolean isAnnotationConfiguredFetchProfile(FetchProfile fetchProfile);
}
\ No newline at end of file
Modified: core/trunk/annotations/src/main/java/org/hibernate/cfg/VerifyFetchProfileReferenceSecondPass.java
===================================================================
--- core/trunk/annotations/src/main/java/org/hibernate/cfg/VerifyFetchProfileReferenceSecondPass.java 2010-05-30 20:47:31 UTC (rev 19633)
+++ core/trunk/annotations/src/main/java/org/hibernate/cfg/VerifyFetchProfileReferenceSecondPass.java 2010-05-31 10:48:08 UTC (rev 19634)
@@ -1,4 +1,4 @@
-// $Id:$
+// $Id$
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
@@ -47,7 +47,7 @@
public void doSecondPass(Map persistentClasses) throws MappingException {
org.hibernate.mapping.FetchProfile profile = mappings.findOrCreateFetchProfile( fetchProfileName );
- if ( skipProfile( profile ) ) {
+ if ( !mappings.isAnnotationConfiguredFetchProfile( profile ) ) {
return;
}
@@ -59,15 +59,6 @@
fetch.entity().getName(), fetch.association(), fetch.mode().toString().toLowerCase()
);
}
-
- private boolean skipProfile(org.hibernate.mapping.FetchProfile profile) {
- if ( mappings.containsAnnotationConfiguredFetchProfile( profile ) ) {
- return false;
- }
-
- // if there are fetches they must come from xml. If there are xml profiles the annotations get ignored
- return !profile.getFetches().isEmpty();
- }
}
Modified: core/trunk/annotations/src/test/java/org/hibernate/test/annotations/fetchprofile/MoreFetchProfileTest.java
===================================================================
--- core/trunk/annotations/src/test/java/org/hibernate/test/annotations/fetchprofile/MoreFetchProfileTest.java 2010-05-30 20:47:31 UTC (rev 19633)
+++ core/trunk/annotations/src/test/java/org/hibernate/test/annotations/fetchprofile/MoreFetchProfileTest.java 2010-05-31 10:48:08 UTC (rev 19634)
@@ -1,3 +1,28 @@
+// $Id: FetchProfileTest.java 19528 2010-05-17 14:28:55Z epbernard $
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, 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.annotations.fetchprofile;
import java.util.Date;
@@ -5,17 +30,16 @@
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
-import org.hibernate.junit.FailureExpected;
import org.hibernate.test.annotations.TestCase;
/**
* @author Emmanuel Bernard
+ * @author Hardy Ferentschik
*/
-public class MoreFetchProfileTest extends TestCase{
+public class MoreFetchProfileTest extends TestCase {
- @FailureExpected( jiraKey = "HHH-5233")
public void testFetchWithTwoOverrides() throws Exception {
- Session s = openSession( );
+ Session s = openSession();
s.enableFetchProfile( "customer-with-orders-and-country" );
final Transaction transaction = s.beginTransaction();
Country ctry = new Country();
@@ -43,10 +67,10 @@
s.clear();
- c = (Customer) s.get( Customer.class, c.getId() );
+ c = ( Customer ) s.get( Customer.class, c.getId() );
assertTrue( Hibernate.isInitialized( c.getLastOrder() ) );
assertTrue( Hibernate.isInitialized( c.getOrders() ) );
- for(Order so : c.getOrders() ) {
+ for ( Order so : c.getOrders() ) {
assertTrue( Hibernate.isInitialized( so.getCountry() ) );
}
final Order order = c.getOrders().iterator().next();
@@ -62,7 +86,7 @@
s.close();
}
-
+
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
14 years, 7 months
Hibernate SVN: r19633 - in search/trunk/hibernate-search/src: test/java/org/hibernate/search/test/batchindexing and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: sannegrinovero
Date: 2010-05-30 16:47:31 -0400 (Sun, 30 May 2010)
New Revision: 19633
Modified:
search/trunk/hibernate-search/src/main/java/org/hibernate/search/batchindexing/EntityConsumerLuceneworkProducer.java
search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/batchindexing/Book.java
search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/batchindexing/IndexingGeneratedCorpusTest.java
search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/batchindexing/Nation.java
Log:
HSEARCH-534 circular graphs of IndexedEmbedded might break MassIndexer
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/batchindexing/EntityConsumerLuceneworkProducer.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/batchindexing/EntityConsumerLuceneworkProducer.java 2010-05-28 23:42:47 UTC (rev 19632)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/batchindexing/EntityConsumerLuceneworkProducer.java 2010-05-30 20:47:31 UTC (rev 19633)
@@ -60,7 +60,6 @@
private final Map<Class<?>, DocumentBuilderIndexedEntity<?>> documentBuilders;
private final MassIndexerProgressMonitor monitor;
- private static final int CLEAR_PERIOD = 50;
private final CacheMode cacheMode;
private final CountDownLatch producerEndSignal;
@@ -104,7 +103,7 @@
private void indexAllQueue(Session session) {
try {
- for ( int cycle=0; true; cycle++ ) {
+ while ( true ) {
List<?> takeList = source.take();
if ( takeList == null ) {
break;
@@ -116,11 +115,7 @@
session.buildLockRequest( LockOptions.NONE ).lock( take );
index( take, session );
monitor.documentsBuilt( 1 );
- session.evict( take );
- if ( cycle == CLEAR_PERIOD ) {
- cycle = 0;
- session.clear();
- }
+ session.clear();
}
}
}
Modified: search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/batchindexing/Book.java
===================================================================
--- search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/batchindexing/Book.java 2010-05-28 23:42:47 UTC (rev 19632)
+++ search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/batchindexing/Book.java 2010-05-30 20:47:31 UTC (rev 19633)
@@ -66,7 +66,7 @@
@ManyToOne(fetch=FetchType.LAZY,optional=false)
@Fetch(FetchMode.SELECT)
- @IndexedEmbedded
+ @IndexedEmbedded(depth=3)
public Nation getFirstPublishedIn() {
return firstPublishedIn;
}
Modified: search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/batchindexing/IndexingGeneratedCorpusTest.java
===================================================================
--- search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/batchindexing/IndexingGeneratedCorpusTest.java 2010-05-28 23:42:47 UTC (rev 19632)
+++ search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/batchindexing/IndexingGeneratedCorpusTest.java 2010-05-30 20:47:31 UTC (rev 19633)
@@ -24,6 +24,8 @@
*/
package org.hibernate.search.test.batchindexing;
+import java.util.List;
+
import junit.framework.TestCase;
import org.apache.lucene.search.MatchAllDocsQuery;
@@ -66,6 +68,7 @@
createMany( Book.class, BOOK_NUM );
createMany( Dvd.class, DVD_NUM );
createMany( AncientBook.class, ANCIENTBOOK_NUM );
+ storeAllBooksInNation();
}
@Override
@@ -102,6 +105,24 @@
}
}
+ /**
+ * Adds all stored books to the Nation.
+ * Needed to test for HSEARCH-534 and makes the dataset to index quite bigger.
+ */
+ private void storeAllBooksInNation() {
+ FullTextSession fullTextSession = builder.openFullTextSession();
+ try {
+ Transaction tx = fullTextSession.beginTransaction();
+ List<Book> allBooks = fullTextSession.createCriteria( Book.class ).list();
+ Nation italy = (Nation) fullTextSession.load( Nation.class, 1 );
+ italy.getLibrariesHave().addAll( allBooks );
+ tx.commit();
+ }
+ finally {
+ fullTextSession.close();
+ }
+ }
+
public void testBatchIndexing() throws InterruptedException {
verifyResultNumbers(); //initial count of entities should match expectations
purgeAll(); // empty indexes
Modified: search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/batchindexing/Nation.java
===================================================================
--- search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/batchindexing/Nation.java 2010-05-28 23:42:47 UTC (rev 19632)
+++ search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/batchindexing/Nation.java 2010-05-30 20:47:31 UTC (rev 19633)
@@ -24,12 +24,20 @@
*/
package org.hibernate.search.test.batchindexing;
+import java.util.HashSet;
+import java.util.Set;
+
import javax.persistence.Entity;
+import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
+import javax.persistence.OneToMany;
+import org.hibernate.annotations.Fetch;
+import org.hibernate.annotations.FetchMode;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
+import org.hibernate.search.annotations.IndexedEmbedded;
@Entity
public class Nation {
@@ -37,6 +45,7 @@
private Integer id;
private String name;
private String code;
+ private Set<Book> librariesHave = new HashSet<Book>();
public Nation() {}
@@ -71,6 +80,17 @@
public void setCode(String code) {
this.code = code;
}
+
+ @IndexedEmbedded
+ @OneToMany(fetch=FetchType.LAZY)
+ @Fetch(FetchMode.SELECT)
+ public Set<Book> getLibrariesHave() {
+ return librariesHave;
+ }
+ public void setLibrariesHave(Set<Book> librariesHave) {
+ this.librariesHave = librariesHave;
+ }
+
}
14 years, 7 months
Hibernate SVN: r19632 - in search/trunk/hibernate-search/src: main/java/org/hibernate/search/query/dsl/v2/impl and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2010-05-28 19:42:47 -0400 (Fri, 28 May 2010)
New Revision: 19632
Modified:
search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/QueryBuilder.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/TermContext.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedFuzzyContext.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedQueryBuilder.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedTermContext.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedWildcardContext.java
search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/query/dsl/DSLTest.java
Log:
HSEARCH-507 Query DSL Rename exact() to keyword() and put fuzzy() and wildcard() as options
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/QueryBuilder.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/QueryBuilder.java 2010-05-28 23:41:39 UTC (rev 19631)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/QueryBuilder.java 2010-05-28 23:42:47 UTC (rev 19632)
@@ -9,21 +9,17 @@
/**
* build a term query
*/
- TermContext exact();
+ TermContext keyword();
/**
- * Use a fuzzy search approximation (aka edit distance)
+ * find matching elements within a range
*/
- FuzzyContext fuzzy();
+ RangeContext range();
/**
- * Treat the query as a wildcard:
- * - ? represents any single character
- * - * represents any character sequence
- * For faster results, it is recommended that the query text does not
- * start with ? or *
+ * find an sentence (words can be inversed according to the slop factor
*/
- WildcardContext wildcard();
+ PhraseContext phrase();
/**
* Boolean query
@@ -31,16 +27,6 @@
BooleanJunction<BooleanJunction> bool();
/**
- * find matching elements within a range
- */
- RangeContext range();
-
- /**
- * find an sentence (words can be inversed according to the slop factor
- */
- PhraseContext phrase();
-
- /**
* Query matching all documents
* Typically mixed with a boolean query.
*/
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/TermContext.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/TermContext.java 2010-05-28 23:41:39 UTC (rev 19631)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/TermContext.java 2010-05-28 23:42:47 UTC (rev 19632)
@@ -13,4 +13,17 @@
TermMatchingContext onFields(String... field);
+ /**
+ * Use a fuzzy search approximation (aka edit distance)
+ */
+ FuzzyContext fuzzy();
+
+ /**
+ * Treat the query as a wildcard:
+ * - ? represents any single character
+ * - * represents any character sequence
+ * For faster results, it is recommended that the query text does not
+ * start with ? or *
+ */
+ WildcardContext wildcard();
}
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedFuzzyContext.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedFuzzyContext.java 2010-05-28 23:41:39 UTC (rev 19631)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedFuzzyContext.java 2010-05-28 23:42:47 UTC (rev 19632)
@@ -16,10 +16,10 @@
private final QueryCustomizer queryCustomizer;
private final TermQueryContext context;
- public ConnectedFuzzyContext(Analyzer queryAnalyzer, SearchFactory factory) {
+ public ConnectedFuzzyContext(Analyzer queryAnalyzer, SearchFactory factory, QueryCustomizer queryCustomizer) {
this.factory = factory;
this.queryAnalyzer = queryAnalyzer;
- this.queryCustomizer = new QueryCustomizer();
+ this.queryCustomizer = queryCustomizer;
this.context = new TermQueryContext( TermQueryContext.Approximation.FUZZY);
}
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedQueryBuilder.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedQueryBuilder.java 2010-05-28 23:41:39 UTC (rev 19631)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedQueryBuilder.java 2010-05-28 23:42:47 UTC (rev 19632)
@@ -26,18 +26,10 @@
this.factory = factory;
}
- public TermContext exact() {
+ public TermContext keyword() {
return new ConnectedTermContext(queryAnalyzer, factory);
}
- public FuzzyContext fuzzy() {
- return new ConnectedFuzzyContext(queryAnalyzer, factory);
- }
-
- public WildcardContext wildcard() {
- return new ConnectedWildcardContext(queryAnalyzer, factory);
- }
-
public RangeContext range() {
return new ConnectedRangeContext( queryAnalyzer, factory );
}
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedTermContext.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedTermContext.java 2010-05-28 23:41:39 UTC (rev 19631)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedTermContext.java 2010-05-28 23:42:47 UTC (rev 19632)
@@ -4,8 +4,10 @@
import org.apache.lucene.search.Filter;
import org.hibernate.search.SearchFactory;
+import org.hibernate.search.query.dsl.v2.FuzzyContext;
import org.hibernate.search.query.dsl.v2.TermContext;
import org.hibernate.search.query.dsl.v2.TermMatchingContext;
+import org.hibernate.search.query.dsl.v2.WildcardContext;
/**
* @author Emmanuel Bernard
@@ -31,17 +33,25 @@
return new ConnectedTermMatchingContext(context, fields, queryCustomizer, queryAnalyzer, factory);
}
- public TermContext boostedTo(float boost) {
+ public FuzzyContext fuzzy() {
+ return new ConnectedFuzzyContext( queryAnalyzer, factory, queryCustomizer );
+ }
+
+ public WildcardContext wildcard() {
+ return new ConnectedWildcardContext( queryAnalyzer, factory, queryCustomizer);
+ }
+
+ public ConnectedTermContext boostedTo(float boost) {
queryCustomizer.boostedTo( boost );
return this;
}
- public TermContext constantScore() {
+ public ConnectedTermContext constantScore() {
queryCustomizer.constantScore();
return this;
}
- public TermContext filter(Filter filter) {
+ public ConnectedTermContext filter(Filter filter) {
queryCustomizer.filter(filter);
return this;
}
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedWildcardContext.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedWildcardContext.java 2010-05-28 23:41:39 UTC (rev 19631)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedWildcardContext.java 2010-05-28 23:42:47 UTC (rev 19632)
@@ -16,10 +16,10 @@
private final QueryCustomizer queryCustomizer;
private final TermQueryContext context;
- public ConnectedWildcardContext(Analyzer queryAnalyzer, SearchFactory factory) {
+ public ConnectedWildcardContext(Analyzer queryAnalyzer, SearchFactory factory, QueryCustomizer queryCustomizer) {
this.factory = factory;
this.queryAnalyzer = queryAnalyzer;
- this.queryCustomizer = new QueryCustomizer();
+ this.queryCustomizer = queryCustomizer;
this.context = new TermQueryContext( TermQueryContext.Approximation.WILDCARD);
}
Modified: search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/query/dsl/DSLTest.java
===================================================================
--- search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/query/dsl/DSLTest.java 2010-05-28 23:41:39 UTC (rev 19631)
+++ search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/query/dsl/DSLTest.java 2010-05-28 23:42:47 UTC (rev 19632)
@@ -1,6 +1,5 @@
package org.hibernate.search.test.query.dsl;
-import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
@@ -40,32 +39,30 @@
.buildQueryBuilder().forEntity( Month.class ).get();
Query
//regular term query
- query = monthQb.exact().onField( "mythology" ).matching( "cold" ).createQuery();
+ query = monthQb.keyword().onField( "mythology" ).matching( "cold" ).createQuery();
assertEquals( 0, fts.createFullTextQuery( query, Month.class ).getResultSize() );
//term query based on several words
- query = monthQb.exact().onField( "mythology" ).matching( "colder darker" ).createQuery();
+ query = monthQb.keyword().onField( "mythology" ).matching( "colder darker" ).createQuery();
assertEquals( 1, fts.createFullTextQuery( query, Month.class ).getResultSize() );
//term query applying the analyzer and generating one term per word
- query = monthQb.exact().onField( "mythology_stem" ).matching( "snowboard" ).createQuery();
+ query = monthQb.keyword().onField( "mythology_stem" ).matching( "snowboard" ).createQuery();
assertEquals( 1, fts.createFullTextQuery( query, Month.class ).getResultSize() );
//term query applying the analyzer and generating several terms per word
- query = monthQb.exact().onField( "mythology_ngram" ).matching( "snobored" ).createQuery();
+ query = monthQb.keyword().onField( "mythology_ngram" ).matching( "snobored" ).createQuery();
assertEquals( 1, fts.createFullTextQuery( query, Month.class ).getResultSize() );
//term query not using analyzers
- query = monthQb.exact().onField( "mythology" ).ignoreAnalyzer().matching( "Month" ).createQuery();
+ query = monthQb.keyword().onField( "mythology" ).ignoreAnalyzer().matching( "Month" ).createQuery();
assertEquals( 0, fts.createFullTextQuery( query, Month.class ).getResultSize() );
- query = monthQb.exact().onField( "mythology" ).matching( "Month" ).createQuery();
-
transaction.commit();
cleanData( fts );
@@ -81,9 +78,10 @@
//fuzzy search with custom threshold and prefix
query = monthQb
- .fuzzy()
- .threshold( .8f )
- .prefixLength( 1 )
+ .keyword()
+ .fuzzy()
+ .threshold( .8f )
+ .prefixLength( 1 )
.onField( "mythology" )
.matching( "calder" )
.createQuery();
@@ -92,7 +90,8 @@
//wildcard query
query = monthQb
- .wildcard()
+ .keyword()
+ .wildcard()
.onField( "mythology" )
.matching( "mon*" )
.createQuery();
@@ -115,8 +114,8 @@
//combined query, January and february both contain whitening but February in a longer text
query = monthQb
.bool()
- .should( monthQb.exact().onField( "mythology" ).matching( "whitening" ).createQuery() )
- .should( monthQb.exact().onField( "history" ).matching( "whitening" ).createQuery() )
+ .should( monthQb.keyword().onField( "mythology" ).matching( "whitening" ).createQuery() )
+ .should( monthQb.keyword().onField( "history" ).matching( "whitening" ).createQuery() )
.createQuery();
List<Month> results = fts.createFullTextQuery( query, Month.class ).list();
@@ -127,8 +126,8 @@
//since history is boosted, February should come first though
query = monthQb
.bool()
- .should( monthQb.exact().onField( "mythology" ).matching( "whitening" ).createQuery() )
- .should( monthQb.exact().onField( "history" ).boostedTo( 30 ).matching( "whitening" ).createQuery() )
+ .should( monthQb.keyword().onField( "mythology" ).matching( "whitening" ).createQuery() )
+ .should( monthQb.keyword().onField( "history" ).boostedTo( 30 ).matching( "whitening" ).createQuery() )
.createQuery();
results = fts.createFullTextQuery( query, Month.class ).list();
@@ -151,7 +150,7 @@
Query
//combined query, January and february both contain whitening but February in a longer text
- query = monthQb.exact()
+ query = monthQb.keyword()
.onField( "mythology" )
.andField( "history" )
.matching( "whitening" ).createQuery();
@@ -161,7 +160,7 @@
assertEquals( "January", results.get( 0 ).getName() );
//combined query, January and february both contain whitening but February in a longer text
- query = monthQb.exact()
+ query = monthQb.keyword()
.onFields( "mythology", "history" )
.boostedTo( 30 )
.matching( "whitening" ).createQuery();
@@ -172,7 +171,7 @@
//boosted query, January and february both contain whitening but February in a longer text
//since history is boosted, February should come first though
- query = monthQb.exact()
+ query = monthQb.keyword()
.onField( "mythology" )
.andField( "history" )
.boostedTo( 30 )
@@ -199,7 +198,7 @@
//must
query = monthQb
.bool()
- .must( monthQb.exact().onField( "mythology" ).matching( "colder" ).createQuery() )
+ .must( monthQb.keyword().onField( "mythology" ).matching( "colder" ).createQuery() )
.createQuery();
List<Month> results = fts.createFullTextQuery( query, Month.class ).list();
@@ -210,7 +209,7 @@
query = monthQb
.bool()
.should( monthQb.all().createQuery() )
- .must( monthQb.exact().onField( "mythology" ).matching( "colder" ).createQuery() )
+ .must( monthQb.keyword().onField( "mythology" ).matching( "colder" ).createQuery() )
.not()
.createQuery();
results = fts.createFullTextQuery( query, Month.class ).list();
@@ -220,7 +219,7 @@
//implicit must not + all (not recommended)
query = monthQb
.bool()
- .must( monthQb.exact().onField( "mythology" ).matching( "colder" ).createQuery() )
+ .must( monthQb.keyword().onField( "mythology" ).matching( "colder" ).createQuery() )
.not()
.createQuery();
results = fts.createFullTextQuery( query, Month.class ).list();
@@ -230,7 +229,7 @@
//all except (recommended)
query = monthQb
.all()
- .except( monthQb.exact().onField( "mythology" ).matching( "colder" ).createQuery() )
+ .except( monthQb.keyword().onField( "mythology" ).matching( "colder" ).createQuery() )
.createQuery();
results = fts.createFullTextQuery( query, Month.class ).list();
14 years, 7 months
Hibernate SVN: r19631 - search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2010-05-28 19:41:39 -0400 (Fri, 28 May 2010)
New Revision: 19631
Modified:
search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedMultiFieldsPhraseQueryBuilder.java
Log:
HSEARCH-414 Remove no longer needed TODO
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedMultiFieldsPhraseQueryBuilder.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedMultiFieldsPhraseQueryBuilder.java 2010-05-28 16:54:22 UTC (rev 19630)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedMultiFieldsPhraseQueryBuilder.java 2010-05-28 23:41:39 UTC (rev 19631)
@@ -123,7 +123,6 @@
if ( size == 0 ) {
throw new SearchException( "phrase query returns no term. Is there a problem with your analyzers? " + sentence);
}
- //TODO
if ( size == 1 ) {
final List<Term> terms = termsPerPosition.values().iterator().next();
if ( terms.size() == 1 ) {
14 years, 7 months
Hibernate SVN: r19630 - in search/trunk/hibernate-search/src: test/java/org/hibernate/search/test/query/dsl and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2010-05-28 12:54:22 -0400 (Fri, 28 May 2010)
New Revision: 19630
Modified:
search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedMultiFieldsPhraseQueryBuilder.java
search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/query/dsl/DSLTest.java
Log:
HSEARCH-414 Optimize phrase query when the "phrase" is one word
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedMultiFieldsPhraseQueryBuilder.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedMultiFieldsPhraseQueryBuilder.java 2010-05-28 16:44:27 UTC (rev 19629)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedMultiFieldsPhraseQueryBuilder.java 2010-05-28 16:54:22 UTC (rev 19630)
@@ -18,6 +18,7 @@
import org.apache.lucene.search.MultiPhraseQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.Query;
+import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TermRangeQuery;
import org.hibernate.annotations.common.AssertionFailure;
@@ -123,27 +124,38 @@
throw new SearchException( "phrase query returns no term. Is there a problem with your analyzers? " + sentence);
}
//TODO
- //if ( size == 1 ) {
- //optimization
- //}
- //else {
- if (isMultiPhrase) {
- MultiPhraseQuery query = new MultiPhraseQuery();
- query.setSlop( queryContext.getSlop() );
- for ( Map.Entry<Integer,List<Term>> entry : termsPerPosition.entrySet() ) {
- final List<Term> value = entry.getValue();
- query.add( value.toArray( new Term[value.size()] ), entry.getKey() );
+ if ( size == 1 ) {
+ final List<Term> terms = termsPerPosition.values().iterator().next();
+ if ( terms.size() == 1 ) {
+ perFieldQuery = new TermQuery( terms.get( 0 ) );
}
- perFieldQuery = query;
+ else {
+ BooleanQuery query = new BooleanQuery( );
+ for ( Term term : terms ) {
+ query.add( new TermQuery(term), BooleanClause.Occur.SHOULD );
+ }
+ perFieldQuery = query;
+ }
}
else {
- PhraseQuery query = new PhraseQuery();
- query.setSlop( queryContext.getSlop() );
- for ( Map.Entry<Integer,List<Term>> entry : termsPerPosition.entrySet() ) {
- final List<Term> value = entry.getValue();
- query.add( value.get(0), entry.getKey() );
+ if (isMultiPhrase) {
+ MultiPhraseQuery query = new MultiPhraseQuery();
+ query.setSlop( queryContext.getSlop() );
+ for ( Map.Entry<Integer,List<Term>> entry : termsPerPosition.entrySet() ) {
+ final List<Term> value = entry.getValue();
+ query.add( value.toArray( new Term[value.size()] ), entry.getKey() );
+ }
+ perFieldQuery = query;
}
- perFieldQuery = query;
+ else {
+ PhraseQuery query = new PhraseQuery();
+ query.setSlop( queryContext.getSlop() );
+ for ( Map.Entry<Integer,List<Term>> entry : termsPerPosition.entrySet() ) {
+ final List<Term> value = entry.getValue();
+ query.add( value.get(0), entry.getKey() );
+ }
+ perFieldQuery = query;
+ }
}
return fieldContext.getFieldCustomizer().setWrappedQuery( perFieldQuery ).createQuery();
}
Modified: search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/query/dsl/DSLTest.java
===================================================================
--- search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/query/dsl/DSLTest.java 2010-05-28 16:44:27 UTC (rev 19629)
+++ search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/query/dsl/DSLTest.java 2010-05-28 16:54:22 UTC (rev 19630)
@@ -311,7 +311,7 @@
.sentence( "colder and whitening" )
.createQuery();
- assertEquals( 1, fts.createFullTextQuery( query, Month.class ).getResultSize() );
+ assertEquals( "test exact phrase", 1, fts.createFullTextQuery( query, Month.class ).getResultSize() );
query = monthQb.
phrase()
@@ -319,7 +319,7 @@
.sentence( "Month whitening" )
.createQuery();
- assertEquals( 0, fts.createFullTextQuery( query, Month.class ).getResultSize() );
+ assertEquals( "test slop", 0, fts.createFullTextQuery( query, Month.class ).getResultSize() );
query = monthQb.
phrase()
@@ -328,8 +328,18 @@
.sentence( "Month whitening" )
.createQuery();
- assertEquals( 1, fts.createFullTextQuery( query, Month.class ).getResultSize() );
+ assertEquals( "test slop", 1, fts.createFullTextQuery( query, Month.class ).getResultSize() );
+ query = monthQb.
+ phrase()
+ .onField( "mythology" )
+ .sentence( "whitening" )
+ .createQuery();
+
+ assertEquals( "test one term optimization", 1, fts.createFullTextQuery( query, Month.class ).getResultSize() );
+
+
+
//Does not work as the NGram filter does not seem to be skipping posiional increment between ngrams.
// query = monthQb
// .phrase()
14 years, 7 months
Hibernate SVN: r19629 - in search/trunk/hibernate-search/src: main/java/org/hibernate/search/query/dsl/v2/impl and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2010-05-28 12:44:27 -0400 (Fri, 28 May 2010)
New Revision: 19629
Added:
search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/PhraseContext.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/PhraseMatchingContext.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/PhraseTermination.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedMultiFieldsPhraseQueryBuilder.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedPhraseContext.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedPhraseMatchingContext.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/PhraseQueryContext.java
Modified:
search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/QueryBuilder.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedQueryBuilder.java
search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/query/dsl/DSLTest.java
Log:
HSEARCH-414 Add support for phrase query
Support phrase queries by applying the analyzer on a sentence
Still to do is the ability to add words (terms really)
Added: search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/PhraseContext.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/PhraseContext.java (rev 0)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/PhraseContext.java 2010-05-28 16:44:27 UTC (rev 19629)
@@ -0,0 +1,20 @@
+package org.hibernate.search.query.dsl.v2;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public interface PhraseContext extends QueryCustomization<PhraseContext> {
+ /**
+ * Sets the number of other words permitted between words in query phrase.
+ * If zero, then this is an exact phrase search. For larger values this works
+ * like a <code>WITHIN</code> or <code>NEAR</code> operator.
+ *
+ * Defaults to 0
+ */
+ PhraseContext slop(int slop);
+
+ /**
+ * field / property the term query is executed on
+ */
+ PhraseMatchingContext onField(String fieldName);
+}
Added: search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/PhraseMatchingContext.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/PhraseMatchingContext.java (rev 0)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/PhraseMatchingContext.java 2010-05-28 16:44:27 UTC (rev 19629)
@@ -0,0 +1,16 @@
+package org.hibernate.search.query.dsl.v2;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public interface PhraseMatchingContext extends FieldCustomization<PhraseMatchingContext> {
+ /**
+ * field / property the term query is executed on
+ */
+ PhraseMatchingContext andField(String field);
+
+ /**
+ * Sentence to match. It will be processed by the analyzer
+ */
+ PhraseTermination sentence(String sentence);
+}
Added: search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/PhraseTermination.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/PhraseTermination.java (rev 0)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/PhraseTermination.java 2010-05-28 16:44:27 UTC (rev 19629)
@@ -0,0 +1,7 @@
+package org.hibernate.search.query.dsl.v2;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public interface PhraseTermination extends Termination<PhraseTermination> {
+}
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/QueryBuilder.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/QueryBuilder.java 2010-05-28 16:43:05 UTC (rev 19628)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/QueryBuilder.java 2010-05-28 16:44:27 UTC (rev 19629)
@@ -36,6 +36,11 @@
RangeContext range();
/**
+ * find an sentence (words can be inversed according to the slop factor
+ */
+ PhraseContext phrase();
+
+ /**
* Query matching all documents
* Typically mixed with a boolean query.
*/
Added: search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedMultiFieldsPhraseQueryBuilder.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedMultiFieldsPhraseQueryBuilder.java (rev 0)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedMultiFieldsPhraseQueryBuilder.java 2010-05-28 16:44:27 UTC (rev 19629)
@@ -0,0 +1,150 @@
+package org.hibernate.search.query.dsl.v2.impl;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.analysis.TokenStream;
+import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
+import org.apache.lucene.analysis.tokenattributes.TermAttribute;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.search.BooleanClause;
+import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.MultiPhraseQuery;
+import org.apache.lucene.search.PhraseQuery;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.TermRangeQuery;
+
+import org.hibernate.annotations.common.AssertionFailure;
+import org.hibernate.search.SearchException;
+import org.hibernate.search.query.dsl.v2.PhraseTermination;
+import org.hibernate.search.query.dsl.v2.RangeTerminationExcludable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class ConnectedMultiFieldsPhraseQueryBuilder implements PhraseTermination {
+ private final PhraseQueryContext queryContext;
+ private final Analyzer queryAnalyzer;
+ private final QueryCustomizer queryCustomizer;
+ private final List<FieldContext> fieldContexts;
+
+ public ConnectedMultiFieldsPhraseQueryBuilder(PhraseQueryContext queryContext, Analyzer queryAnalyzer, QueryCustomizer queryCustomizer, List<FieldContext> fieldContexts) {
+ this.queryContext = queryContext;
+ this.queryAnalyzer = queryAnalyzer;
+ this.queryCustomizer = queryCustomizer;
+ this.fieldContexts = fieldContexts;
+ }
+
+ public Query createQuery() {
+ final int size = fieldContexts.size();
+ if ( size == 1 ) {
+ return queryCustomizer.setWrappedQuery( createQuery( fieldContexts.get( 0 ) ) ).createQuery();
+ }
+ else {
+ BooleanQuery aggregatedFieldsQuery = new BooleanQuery( );
+ for ( FieldContext fieldContext : fieldContexts ) {
+ aggregatedFieldsQuery.add( createQuery( fieldContext ), BooleanClause.Occur.SHOULD );
+ }
+ return queryCustomizer.setWrappedQuery( aggregatedFieldsQuery ).createQuery();
+ }
+ }
+
+ public Query createQuery(FieldContext fieldContext) {
+ final Query perFieldQuery;
+ final String fieldName = fieldContext.getField();
+
+ /*
+ * Store terms per position and detect if for a given position more than one term is present
+ */
+ TokenStream stream = null;
+ boolean isMultiPhrase = false;
+ Map<Integer, List<Term>> termsPerPosition = new HashMap<Integer, List<Term>>();
+ final String sentence = queryContext.getSentence();
+ try {
+ Reader reader = new StringReader( sentence );
+ stream = queryAnalyzer.reusableTokenStream( fieldName, reader);
+
+ TermAttribute termAttribute = (TermAttribute) stream.addAttribute( TermAttribute.class );
+ PositionIncrementAttribute positionAttribute = (PositionIncrementAttribute) stream.addAttribute( PositionIncrementAttribute.class );
+
+ stream.reset();
+ int position = -1; //start at -1 since we apply at least one increment
+ List<Term> termsAtSamePosition = null;
+ while ( stream.incrementToken() ) {
+ int positionIncrement = 1;
+ if ( positionAttribute != null ) {
+ positionIncrement = positionAttribute.getPositionIncrement();
+ }
+
+ if ( positionIncrement > 0 ) {
+ position+=positionIncrement;
+ termsAtSamePosition = termsPerPosition.get(position);
+ }
+
+ if (termsAtSamePosition == null) {
+ termsAtSamePosition = new ArrayList<Term>();
+ termsPerPosition.put( position, termsAtSamePosition );
+ }
+
+ termsAtSamePosition.add( new Term( fieldName, termAttribute.term() ) );
+ if ( termsAtSamePosition.size() > 1 ) {
+ isMultiPhrase = true;
+ }
+ }
+ }
+ catch ( IOException e ) {
+ throw new AssertionFailure( "IOException while reading a string. Doh!", e);
+ }
+ finally {
+ if ( stream != null ) {
+ try {
+ stream.end();
+ stream.close();
+ }
+ catch ( IOException e ) {
+ throw new AssertionFailure( "IOException while reading a string. Doh!", e);
+ }
+ }
+ }
+
+ /*
+ * Create the appropriate query depending on the conditions
+ * note that a MultiPhraseQuery is needed if several terms share the same position
+ * as it will do a OR and not a AND like PhraseQuery
+ */
+ final int size = termsPerPosition.size();
+ if ( size == 0 ) {
+ throw new SearchException( "phrase query returns no term. Is there a problem with your analyzers? " + sentence);
+ }
+ //TODO
+ //if ( size == 1 ) {
+ //optimization
+ //}
+ //else {
+ if (isMultiPhrase) {
+ MultiPhraseQuery query = new MultiPhraseQuery();
+ query.setSlop( queryContext.getSlop() );
+ for ( Map.Entry<Integer,List<Term>> entry : termsPerPosition.entrySet() ) {
+ final List<Term> value = entry.getValue();
+ query.add( value.toArray( new Term[value.size()] ), entry.getKey() );
+ }
+ perFieldQuery = query;
+ }
+ else {
+ PhraseQuery query = new PhraseQuery();
+ query.setSlop( queryContext.getSlop() );
+ for ( Map.Entry<Integer,List<Term>> entry : termsPerPosition.entrySet() ) {
+ final List<Term> value = entry.getValue();
+ query.add( value.get(0), entry.getKey() );
+ }
+ perFieldQuery = query;
+ }
+ return fieldContext.getFieldCustomizer().setWrappedQuery( perFieldQuery ).createQuery();
+ }
+}
\ No newline at end of file
Added: search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedPhraseContext.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedPhraseContext.java (rev 0)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedPhraseContext.java 2010-05-28 16:44:27 UTC (rev 19629)
@@ -0,0 +1,146 @@
+package org.hibernate.search.query.dsl.v2.impl;
+
+import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.search.Filter;
+
+import org.hibernate.search.SearchFactory;
+import org.hibernate.search.query.dsl.v2.PhraseContext;
+import org.hibernate.search.query.dsl.v2.PhraseMatchingContext;
+import org.hibernate.search.query.dsl.v2.RangeContext;
+import org.hibernate.search.query.dsl.v2.RangeMatchingContext;
+
+/**
+ * @author Emmanuel Bernard
+ */
+class ConnectedPhraseContext implements PhraseContext {
+ private final SearchFactory factory;
+ private final Analyzer queryAnalyzer;
+ private final QueryCustomizer queryCustomizer;
+ private final PhraseQueryContext queryContext;
+
+
+ public ConnectedPhraseContext(Analyzer queryAnalyzer, SearchFactory factory) {
+ this.factory = factory;
+ this.queryAnalyzer = queryAnalyzer;
+ this.queryCustomizer = new QueryCustomizer();
+ this.queryContext = new PhraseQueryContext();
+ }
+
+ public PhraseContext slop(int slop) {
+ queryContext.setSlop( slop );
+ return this;
+ }
+
+ public PhraseMatchingContext onField(String fieldName) {
+ return new ConnectedPhraseMatchingContext(fieldName, queryContext, queryCustomizer, queryAnalyzer, factory);
+ }
+
+ public PhraseContext boostedTo(float boost) {
+ queryCustomizer.boostedTo( boost );
+ return this;
+ }
+
+ public PhraseContext constantScore() {
+ queryCustomizer.constantScore();
+ return this;
+ }
+
+ public PhraseContext filter(Filter filter) {
+ queryCustomizer.filter(filter);
+ return this;
+ }
+
+
+//
+// public <T> FromRangeContext<T> from(T from) {
+// context.setFrom( from );
+// return new ConnectedFromRangeContext<T>(this);
+// }
+//
+//
+//
+// SearchFactory getFactory() {
+// return factory;
+// }
+//
+// Analyzer getQueryAnalyzer() {
+// return queryAnalyzer;
+// }
+//
+// QueryCustomizer getQueryCustomizer() {
+// return queryCustomizer;
+// }
+//
+// static class ConnectedFromRangeContext<T> implements FromRangeContext<T> {
+// private ConnectedRangeContext mother;
+//
+// public ConnectedFromRangeContext(ConnectedRangeContext mother) {
+// this.mother = mother;
+// }
+//
+// public ToRangeContext to(Object to) {
+// mother.getContext().setTo( to );
+// return new ConnectedToRangeContext(mother);
+// }
+//
+// public FromRangeContext<T> exclude() {
+// mother.getContext().setExcludeFrom( true );
+// return this;
+// }
+//
+// public FromRangeContext<T> boostedTo(float boost) {
+// mother.boostedTo( boost );
+// return this;
+// }
+//
+// public FromRangeContext<T> constantScore() {
+// mother.constantScore();
+// return this;
+// }
+//
+// public FromRangeContext<T> filter(Filter filter) {
+// mother.filter( filter );
+// return this;
+// }
+// }
+//
+// static class ConnectedToRangeContext implements ToRangeContext {
+// private ConnectedRangeContext mother;
+//
+// public ConnectedToRangeContext(ConnectedRangeContext mother) {
+// this.mother = mother;
+// }
+//
+// public TermMatchingContext onField(String field) {
+// return new ConnectedTermMatchingContext(
+// mother.getContext(),
+// field,
+// mother.getQueryCustomizer(),
+// mother.getQueryAnalyzer(),
+// mother.getFactory()
+// );
+// }
+//
+// public ToRangeContext exclude() {
+// mother.getContext().setExcludeTo( true );
+// return this;
+// }
+//
+// public ToRangeContext boostedTo(float boost) {
+// mother.boostedTo( boost );
+// return this;
+// }
+//
+// public ToRangeContext constantScore() {
+// mother.constantScore();
+// return this;
+// }
+//
+// public ToRangeContext filter(Filter filter) {
+// mother.filter( filter );
+// return this;
+// }
+// }
+
+
+}
\ No newline at end of file
Added: search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedPhraseMatchingContext.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedPhraseMatchingContext.java (rev 0)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedPhraseMatchingContext.java 2010-05-28 16:44:27 UTC (rev 19629)
@@ -0,0 +1,68 @@
+package org.hibernate.search.query.dsl.v2.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.lucene.analysis.Analyzer;
+
+import org.hibernate.search.SearchFactory;
+import org.hibernate.search.query.dsl.v2.PhraseMatchingContext;
+import org.hibernate.search.query.dsl.v2.PhraseTermination;
+import org.hibernate.search.query.dsl.v2.RangeMatchingContext;
+import org.hibernate.search.query.dsl.v2.RangeTerminationExcludable;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class ConnectedPhraseMatchingContext implements PhraseMatchingContext {
+ private final SearchFactory factory;
+ private final Analyzer queryAnalyzer;
+ private final QueryCustomizer queryCustomizer;
+ private final PhraseQueryContext queryContext;
+ private final List<FieldContext> fieldContexts;
+ //when a varargs of fields are passed, apply the same customization for all.
+ //keep the index of the first context in this queue
+ private int firstOfContext = 0;
+
+ public ConnectedPhraseMatchingContext(String fieldName,
+ PhraseQueryContext queryContext,
+ QueryCustomizer queryCustomizer,
+ Analyzer queryAnalyzer,
+ SearchFactory factory) {
+ this.factory = factory;
+ this.queryAnalyzer = queryAnalyzer;
+ this.queryCustomizer = queryCustomizer;
+ this.queryContext = queryContext;
+ this.fieldContexts = new ArrayList<FieldContext>(4);
+ this.fieldContexts.add( new FieldContext( fieldName ) );
+ }
+
+ public PhraseMatchingContext andField(String field) {
+ this.fieldContexts.add( new FieldContext( field ) );
+ this.firstOfContext = fieldContexts.size() - 1;
+ return this;
+ }
+
+ public PhraseTermination sentence(String sentence) {
+ queryContext.setSentence(sentence);
+ return new ConnectedMultiFieldsPhraseQueryBuilder(queryContext, queryAnalyzer, queryCustomizer, fieldContexts);
+ }
+
+ public PhraseMatchingContext boostedTo(float boost) {
+ for ( FieldContext fieldContext : getCurrentFieldContexts() ) {
+ fieldContext.getFieldCustomizer().boostedTo( boost );
+ }
+ return this;
+ }
+
+ private List<FieldContext> getCurrentFieldContexts() {
+ return fieldContexts.subList( firstOfContext, fieldContexts.size() );
+ }
+
+ public PhraseMatchingContext ignoreAnalyzer() {
+ for ( FieldContext fieldContext : getCurrentFieldContexts() ) {
+ fieldContext.setIgnoreAnalyzer( true );
+ }
+ return this;
+ }
+}
\ No newline at end of file
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedQueryBuilder.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedQueryBuilder.java 2010-05-28 16:43:05 UTC (rev 19628)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/ConnectedQueryBuilder.java 2010-05-28 16:44:27 UTC (rev 19629)
@@ -6,6 +6,7 @@
import org.hibernate.search.query.dsl.v2.AllContext;
import org.hibernate.search.query.dsl.v2.BooleanJunction;
import org.hibernate.search.query.dsl.v2.FuzzyContext;
+import org.hibernate.search.query.dsl.v2.PhraseContext;
import org.hibernate.search.query.dsl.v2.QueryBuilder;
import org.hibernate.search.query.dsl.v2.RangeContext;
import org.hibernate.search.query.dsl.v2.TermContext;
@@ -41,6 +42,10 @@
return new ConnectedRangeContext( queryAnalyzer, factory );
}
+ public PhraseContext phrase() {
+ return new ConnectedPhraseContext( queryAnalyzer, factory );
+ }
+
//fixme Have to use raw types but would be nice to not have to
public BooleanJunction bool() {
return new BooleanQueryBuilder();
Added: search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/PhraseQueryContext.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/PhraseQueryContext.java (rev 0)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/PhraseQueryContext.java 2010-05-28 16:44:27 UTC (rev 19629)
@@ -0,0 +1,25 @@
+package org.hibernate.search.query.dsl.v2.impl;
+
+/**
+ * @author Emmanuel Bernard
+ */
+public class PhraseQueryContext {
+ private int slop = 0;
+ private String sentence;
+
+ public int getSlop() {
+ return slop;
+ }
+
+ public void setSlop(int slop) {
+ this.slop = slop;
+ }
+
+ public String getSentence() {
+ return sentence;
+ }
+
+ public void setSentence(String sentence) {
+ this.sentence = sentence;
+ }
+}
Modified: search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/query/dsl/DSLTest.java
===================================================================
--- search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/query/dsl/DSLTest.java 2010-05-28 16:43:05 UTC (rev 19628)
+++ search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/query/dsl/DSLTest.java 2010-05-28 16:44:27 UTC (rev 19629)
@@ -296,7 +296,55 @@
cleanData( fts );
}
+ public void testPhraseQuery() throws Exception {
+ FullTextSession fts = initData();
+ Transaction transaction = fts.beginTransaction();
+ final QueryBuilder monthQb = fts.getSearchFactory()
+ .buildQueryBuilder().forEntity( Month.class ).get();
+
+ Query
+
+ query = monthQb.
+ phrase()
+ .onField( "mythology" )
+ .sentence( "colder and whitening" )
+ .createQuery();
+
+ assertEquals( 1, fts.createFullTextQuery( query, Month.class ).getResultSize() );
+
+ query = monthQb.
+ phrase()
+ .onField( "mythology" )
+ .sentence( "Month whitening" )
+ .createQuery();
+
+ assertEquals( 0, fts.createFullTextQuery( query, Month.class ).getResultSize() );
+
+ query = monthQb.
+ phrase()
+ .slop( 1 )
+ .onField( "mythology" )
+ .sentence( "Month whitening" )
+ .createQuery();
+
+ assertEquals( 1, fts.createFullTextQuery( query, Month.class ).getResultSize() );
+
+ //Does not work as the NGram filter does not seem to be skipping posiional increment between ngrams.
+// query = monthQb
+// .phrase()
+// .onField( "mythology_ngram" )
+// .sentence( "snobored" )
+// .createQuery();
+//
+// assertEquals( 1, fts.createFullTextQuery( query, Month.class ).getResultSize() );
+
+ transaction.commit();
+
+ cleanData( fts );
+ }
+
+
// public void testTermQueryOnAnalyzer() throws Exception {
// FullTextSession fts = initData();
//
14 years, 7 months
Hibernate SVN: r19628 - search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2010-05-28 12:43:05 -0400 (Fri, 28 May 2010)
New Revision: 19628
Modified:
search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/Helper.java
Log:
HSEARCH-414 Remove useless comment
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/Helper.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/Helper.java 2010-05-28 14:21:57 UTC (rev 19627)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/query/dsl/v2/impl/Helper.java 2010-05-28 16:43:05 UTC (rev 19628)
@@ -36,7 +36,6 @@
}
static List<String> getAllTermsFromText(String fieldName, String localText, Analyzer analyzer) throws IOException {
- //it's better not to apply the analyzer with wildcard as * and ? can be mistakenly removed
List<String> terms = new ArrayList<String>();
Reader reader = new StringReader(localText);
14 years, 7 months