Hibernate SVN: r20680 - in search/trunk: hibernate-search/src/main/java/org/hibernate/search/engine and 3 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-09-22 09:28:23 -0400 (Wed, 22 Sep 2010)
New Revision: 20680
Added:
search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/Article.java
search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/DuplicateDocumentIdTest.java
search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/ExplicitIdTest.java
search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/Foo.java
Modified:
search/trunk/hibernate-search-solr-analyzers/pom.xml
search/trunk/hibernate-search/pom.xml
search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/AbstractLoader.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/DocumentBuilderIndexedEntity.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/DocumentExtractor.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/EntityInfo.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/LoaderHelper.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/ObjectLoaderHelper.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/util/HibernateHelper.java
search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/ImplicitIdTest.java
Log:
HSEARCH-574
* Refactored ObjectLoaderHelper to verify wether the document id is also the entity id. Depending on the outcome the entity is either loaded via session.load or via a Criteria query
* Added a exception case for multiple @DocumentId annotation in the same entity
* Added tests for different document id scenarios
Modified: search/trunk/hibernate-search/pom.xml
===================================================================
--- search/trunk/hibernate-search/pom.xml 2010-09-22 13:27:42 UTC (rev 20679)
+++ search/trunk/hibernate-search/pom.xml 2010-09-22 13:28:23 UTC (rev 20680)
@@ -1,26 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
- * Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2009, Red Hat, Inc. and/or its affiliates 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, Inc.
- *
- * 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
+ ~ Hibernate, Relational Persistence for Idiomatic Java
+ ~
+ ~ Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ ~
+ ~ 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
-->
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/AbstractLoader.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/AbstractLoader.java 2010-09-22 13:27:42 UTC (rev 20679)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/AbstractLoader.java 2010-09-22 13:28:23 UTC (rev 20680)
@@ -62,7 +62,9 @@
if ( takeTimings ) {
startTime = System.nanoTime();
}
+
List loadedObjects = executeLoad( entityInfos );
+
if ( takeTimings ) {
statisticsImplementor.objectLoadExecuted( loadedObjects.size(), System.nanoTime() - startTime );
}
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/DocumentBuilderIndexedEntity.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/DocumentBuilderIndexedEntity.java 2010-09-22 13:27:42 UTC (rev 20679)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/DocumentBuilderIndexedEntity.java 2010-09-22 13:28:23 UTC (rev 20680)
@@ -42,11 +42,11 @@
import org.slf4j.Logger;
import org.hibernate.annotations.common.AssertionFailure;
-import org.hibernate.annotations.common.util.ReflectHelper;
import org.hibernate.annotations.common.reflection.ReflectionManager;
import org.hibernate.annotations.common.reflection.XClass;
import org.hibernate.annotations.common.reflection.XMember;
import org.hibernate.annotations.common.reflection.XProperty;
+import org.hibernate.annotations.common.util.ReflectHelper;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.search.SearchException;
import org.hibernate.search.analyzer.Discriminator;
@@ -182,13 +182,14 @@
if ( idAnnotation != null ) {
String attributeName = getIdAttributeName( member, idAnnotation );
if ( isRoot ) {
- if ( idKeywordName != null && explicitDocumentId ) {
- throw new AssertionFailure(
- "Two document id assigned: "
- + idKeywordName + " and " + attributeName
- );
+ if ( explicitDocumentId ) {
+ throw new SearchException( "More than one @DocumentId specified on entity " + beanClass.getName() );
}
+ if ( idAnnotation instanceof DocumentId ) {
+ explicitDocumentId = true;
+ }
idKeywordName = prefix + attributeName;
+
FieldBridge fieldBridge = BridgeFactory.guessType( null, member, reflectionManager );
if ( fieldBridge instanceof TwoWayFieldBridge ) {
idBridge = ( TwoWayFieldBridge ) fieldBridge;
@@ -244,17 +245,16 @@
// check for explicit DocumentId
DocumentId documentIdAnn = member.getAnnotation( DocumentId.class );
if ( documentIdAnn != null ) {
- explicitDocumentId = true;
idAnnotation = documentIdAnn;
}
// check for JPA @Id
- else if ( !explicitDocumentId && context.isJpaPresent() ) {
+ else if ( context.isJpaPresent() ) {
Annotation jpaId;
try {
@SuppressWarnings("unchecked")
Class<? extends Annotation> jpaIdClass =
org.hibernate.annotations.common.util.ReflectHelper
- .classForName( "javax.persistence.Id", ConfigContext.class );
+ .classForName( "javax.persistence.Id", ConfigContext.class );
jpaId = member.getAnnotation( jpaIdClass );
}
catch ( ClassNotFoundException e ) {
@@ -279,6 +279,7 @@
}
//TODO could we use T instead of EntityClass?
+
public void addWorkToQueue(Class<T> entityClass, T entity, Serializable id, WorkType workType, List<LuceneWork> queue, SearchFactoryImplementor searchFactoryImplementor) {
//TODO with the caller loop we are in a n^2: optimize it using a HashMap for work recognition
@@ -407,7 +408,7 @@
LuceneOptions luceneOptions = new LuceneOptionsImpl(
Store.YES,
Field.Index.NOT_ANALYZED_NO_NORMS, Field.TermVector.NO, idBoost
- );
+ );
idBridge.set( idKeywordName, id, doc, luceneOptions );
// finally add all other document fields
@@ -590,13 +591,15 @@
/**
* Return the entity id if possible
* An IllegalStateException otherwise
- *
+ * <p/>
* If the id is provided, we can't extract it from the entity
*
* @return entity id
*/
public Serializable getId(Object entity) {
- if( entity == null || idGetter == null) throw new IllegalStateException( "Cannot guess id form entity");
+ if ( entity == null || idGetter == null ) {
+ throw new IllegalStateException( "Cannot guess id form entity" );
+ }
return ( Serializable ) ReflectionHelper.getMemberValue( entity, idGetter );
}
@@ -611,6 +614,16 @@
.get( builderIndexedEntity.getIdKeywordName(), document );
}
+ public static String getDocumentIdName(SearchFactoryImplementor searchFactoryImplementor, Class<?> clazz) {
+ DocumentBuilderIndexedEntity<?> builderIndexedEntity = searchFactoryImplementor.getDocumentBuilderIndexedEntity(
+ clazz
+ );
+ if ( builderIndexedEntity == null ) {
+ throw new SearchException( "No Lucene configuration set up for: " + clazz.getName() );
+ }
+ return builderIndexedEntity.getIdentifierName();
+ }
+
public static Object[] getDocumentFields(SearchFactoryImplementor searchFactoryImplementor, Class<?> clazz, Document document, String[] fields) {
DocumentBuilderIndexedEntity<?> builderIndexedEntity = searchFactoryImplementor.getDocumentBuilderIndexedEntity(
clazz
@@ -660,7 +673,7 @@
}
private static void processFieldsForProjection(PropertiesMetadata metadata, String[] fields, Object[] result, Document document) {
- //process base fields
+ //process base fields
final int nbrFoEntityFields = metadata.fieldNames.size();
for ( int index = 0; index < nbrFoEntityFields; index++ ) {
populateResult(
@@ -673,7 +686,7 @@
);
}
- //process fields of embedded
+ //process fields of embedded
final int nbrOfEmbeddedObjects = metadata.embeddedPropertiesMetadata.size();
for ( int index = 0; index < nbrOfEmbeddedObjects; index++ ) {
//there is nothing we can do for collections
@@ -684,17 +697,17 @@
}
}
- //process class bridges
- final int nbrOfClassBridges = metadata.classBridges.size();
+ //process class bridges
+ final int nbrOfClassBridges = metadata.classBridges.size();
for ( int index = 0; index < nbrOfClassBridges; index++ ) {
populateResult(
- metadata.classNames.get(index),
- metadata.classBridges.get(index),
- metadata.classStores.get(index),
- fields,
- result,
- document
- );
+ metadata.classNames.get( index ),
+ metadata.classBridges.get( index ),
+ metadata.classStores.get( index ),
+ fields,
+ result,
+ document
+ );
}
}
@@ -710,23 +723,24 @@
public String objectToString(String fieldName, Object value) {
if ( fieldName == null ) {
- throw new AssertionFailure( "Field name should not be null");
+ throw new AssertionFailure( "Field name should not be null" );
}
if ( fieldName.equals( idKeywordName ) ) {
return idBridge.objectToString( value );
}
else {
FieldBridge bridge = getBridge( metadata, fieldName );
- if (bridge!=null) {
+ if ( bridge != null ) {
final Class<? extends FieldBridge> bridgeClass = bridge.getClass();
if ( TwoWayFieldBridge.class.isAssignableFrom( bridgeClass ) ) {
- return ( (TwoWayFieldBridge) bridge ).objectToString( value );
+ return ( ( TwoWayFieldBridge ) bridge ).objectToString( value );
}
else if ( StringBridge.class.isAssignableFrom( bridgeClass ) ) {
- return ( (StringBridge) bridge ).objectToString( value );
+ return ( ( StringBridge ) bridge ).objectToString( value );
}
- throw new SearchException( "FieldBridge " + bridgeClass + "does not have a objectToString method: field "
- + fieldName + " in " + beanXClass
+ throw new SearchException(
+ "FieldBridge " + bridgeClass + "does not have a objectToString method: field "
+ + fieldName + " in " + beanXClass
);
}
}
@@ -744,20 +758,26 @@
}
private FieldBridge getBridge(PropertiesMetadata metadata, String fieldName) {
- //process base fields
+ //process base fields
FieldBridge fieldBridge = getBridge( metadata.fieldNames, metadata.fieldBridges, fieldName );
- if ( fieldBridge != null ) return fieldBridge;
+ if ( fieldBridge != null ) {
+ return fieldBridge;
+ }
//process fields of embedded
final int nbrOfEmbeddedObjects = metadata.embeddedPropertiesMetadata.size();
for ( int index = 0; index < nbrOfEmbeddedObjects; index++ ) {
fieldBridge = getBridge( metadata.embeddedPropertiesMetadata.get( index ), fieldName );
- if ( fieldBridge != null ) return fieldBridge;
+ if ( fieldBridge != null ) {
+ return fieldBridge;
+ }
}
//process class bridges
fieldBridge = getBridge( metadata.classNames, metadata.classBridges, fieldName );
- if ( fieldBridge != null ) return fieldBridge;
+ if ( fieldBridge != null ) {
+ return fieldBridge;
+ }
return null;
}
@@ -777,11 +797,11 @@
return;
}
}
- for ( FieldBridge bridge : metadata.classBridges ) {
- if ( !( bridge instanceof TwoWayStringBridge || bridge instanceof TwoWayString2FieldBridgeAdaptor ) ) {
- allowFieldSelectionInProjection = false;
- return;
- }
- }
+ for ( FieldBridge bridge : metadata.classBridges ) {
+ if ( !( bridge instanceof TwoWayStringBridge || bridge instanceof TwoWayString2FieldBridgeAdaptor ) ) {
+ allowFieldSelectionInProjection = false;
+ return;
+ }
+ }
}
}
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/DocumentExtractor.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/DocumentExtractor.java 2010-09-22 13:27:42 UTC (rev 20679)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/DocumentExtractor.java 2010-09-22 13:28:23 UTC (rev 20680)
@@ -54,7 +54,12 @@
public DocumentExtractor(QueryHits queryHits, SearchFactoryImplementor searchFactoryImplementor, String[] projection, Set<String> idFieldNames, boolean allowFieldSelection) {
this.searchFactoryImplementor = searchFactoryImplementor;
- this.projection = projection;
+ if ( projection != null ) {
+ this.projection = projection.clone();
+ }
+ else {
+ this.projection = null;
+ }
this.queryHits = queryHits;
this.allowFieldSelection = allowFieldSelection;
initFieldSelection( projection, idFieldNames );
@@ -88,6 +93,7 @@
private EntityInfo extract(Document document) {
Class clazz = DocumentBuilderIndexedEntity.getDocumentClass( document );
+ String idName = DocumentBuilderIndexedEntity.getDocumentIdName( searchFactoryImplementor, clazz );
Serializable id = DocumentBuilderIndexedEntity.getDocumentId( searchFactoryImplementor, clazz, document );
Object[] projected = null;
if ( projection != null && projection.length > 0 ) {
@@ -95,7 +101,7 @@
searchFactoryImplementor, clazz, document, projection
);
}
- return new EntityInfo( clazz, id, projected );
+ return new EntityInfo( clazz, idName, id, projected );
}
public EntityInfo extract(int index) throws IOException {
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/EntityInfo.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/EntityInfo.java 2010-09-22 13:27:42 UTC (rev 20679)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/EntityInfo.java 2010-09-22 13:28:23 UTC (rev 20680)
@@ -1,26 +1,25 @@
-/* $Id$
- *
+/*
* Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2009, Red Hat, Inc. and/or its affiliates 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, Inc.
- *
- * 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
+ *
+ * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ *
+ * 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.search.engine;
@@ -29,20 +28,43 @@
import java.util.List;
/**
+ * Wrapper class for the loading of a single entity.
*
* @author Emmanuel Bernard
+ * @author Hardy Ferentschik
*/
public class EntityInfo {
-
+ /**
+ * The entity class.
+ */
public final Class clazz;
+
+ /**
+ * The document id.
+ */
public final Serializable id;
+
+ /**
+ * The name of the document id property.
+ */
+ public final String idName;
+
+ /**
+ * Array of projected values. {@code null} in case there are no projections.
+ */
public final Object[] projection;
+
public final List<Integer> indexesOfThis = new LinkedList<Integer>();
-
- public EntityInfo(Class clazz, Serializable id, Object[] projection) {
+
+ public EntityInfo(Class clazz, String idName, Serializable id, Object[] projection) {
this.clazz = clazz;
+ this.idName = idName;
this.id = id;
- this.projection = projection;
+ if ( projection != null ) {
+ this.projection = projection.clone();
+ }
+ else {
+ this.projection = null;
+ }
}
-
}
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/LoaderHelper.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/LoaderHelper.java 2010-09-22 13:27:42 UTC (rev 20679)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/LoaderHelper.java 2010-09-22 13:28:23 UTC (rev 20680)
@@ -1,26 +1,25 @@
-/* $Id$
- *
+/*
* Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2009, Red Hat, Inc. and/or its affiliates 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, Inc.
- *
- * 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
+ *
+ * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ *
+ * 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.search.engine;
@@ -37,13 +36,13 @@
private static final List<Class> objectNotFoundExceptions;
static {
- objectNotFoundExceptions = new ArrayList<Class>(2);
+ objectNotFoundExceptions = new ArrayList<Class>( 2 );
try {
objectNotFoundExceptions.add(
ReflectHelper.classForName( "org.hibernate.ObjectNotFoundException" )
);
}
- catch (ClassNotFoundException e) {
+ catch ( ClassNotFoundException e ) {
//leave it alone
}
try {
@@ -51,7 +50,7 @@
ReflectHelper.classForName( "javax.persistence.EntityNotFoundException" )
);
}
- catch (ClassNotFoundException e) {
+ catch ( ClassNotFoundException e ) {
//leave it alone
}
}
@@ -59,7 +58,7 @@
public static boolean isObjectNotFoundException(RuntimeException e) {
boolean objectNotFound = false;
Class exceptionClass = e.getClass();
- for ( Class clazz : objectNotFoundExceptions) {
+ for ( Class clazz : objectNotFoundExceptions ) {
if ( clazz.isAssignableFrom( exceptionClass ) ) {
objectNotFound = true;
break;
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/ObjectLoaderHelper.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/ObjectLoaderHelper.java 2010-09-22 13:27:42 UTC (rev 20679)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/ObjectLoaderHelper.java 2010-09-22 13:28:23 UTC (rev 20680)
@@ -1,26 +1,25 @@
-/* $Id$
- *
+/*
* Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2009, Red Hat, Inc. and/or its affiliates 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, Inc.
- *
- * 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
+ *
+ * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ *
+ * 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.search.engine;
@@ -32,14 +31,17 @@
import org.slf4j.Logger;
import org.hibernate.Criteria;
+import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Restrictions;
+import org.hibernate.search.SearchException;
import org.hibernate.search.util.HibernateHelper;
import org.hibernate.search.util.LoggerFactory;
/**
* @author Emmanuel Bernard
+ * @author Hardy Ferentschik
*/
public class ObjectLoaderHelper {
@@ -47,15 +49,16 @@
private static final Logger log = LoggerFactory.make();
public static Object load(EntityInfo entityInfo, Session session) {
- //be sure to get an initialized object but save from ONFE and ENFE
- Object maybeProxy = session.load( entityInfo.clazz, entityInfo.id );
+ Object maybeProxy = executeLoad( entityInfo, session );
try {
HibernateHelper.initialize( maybeProxy );
}
- catch (RuntimeException e) {
+ catch ( RuntimeException e ) {
if ( LoaderHelper.isObjectNotFoundException( e ) ) {
- log.debug( "Object found in Search index but not in database: {} with id {}",
- entityInfo.clazz, entityInfo.id );
+ log.debug(
+ "Object found in Search index but not in database: {} with id {}",
+ entityInfo.clazz, entityInfo.id
+ );
maybeProxy = null;
}
else {
@@ -69,22 +72,28 @@
Criteria criteria, Class<?> entityType,
SearchFactoryImplementor searchFactoryImplementor) {
final int maxResults = entityInfos.length;
- if ( maxResults == 0 ) return;
+ if ( maxResults == 0 ) {
+ return;
+ }
- Set<Class<?>> indexedEntities = searchFactoryImplementor.getIndexedTypesPolymorphic( new Class<?>[]{entityType} );
- DocumentBuilderIndexedEntity<?> builder = searchFactoryImplementor.getDocumentBuilderIndexedEntity( indexedEntities.iterator().next() );
+ Set<Class<?>> indexedEntities = searchFactoryImplementor.getIndexedTypesPolymorphic( new Class<?>[] { entityType } );
+ DocumentBuilderIndexedEntity<?> builder = searchFactoryImplementor.getDocumentBuilderIndexedEntity(
+ indexedEntities.iterator().next()
+ );
String idName = builder.getIdentifierName();
Disjunction disjunction = Restrictions.disjunction();
int loop = maxResults / MAX_IN_CLAUSE;
boolean exact = maxResults % MAX_IN_CLAUSE == 0;
- if ( !exact ) loop++;
- for (int index = 0; index < loop; index++) {
+ if ( !exact ) {
+ loop++;
+ }
+ for ( int index = 0; index < loop; index++ ) {
int max = index * MAX_IN_CLAUSE + MAX_IN_CLAUSE <= maxResults ?
index * MAX_IN_CLAUSE + MAX_IN_CLAUSE :
maxResults;
List<Serializable> ids = new ArrayList<Serializable>( max - index * MAX_IN_CLAUSE );
- for (int entityInfoIndex = index * MAX_IN_CLAUSE; entityInfoIndex < max; entityInfoIndex++) {
+ for ( int entityInfoIndex = index * MAX_IN_CLAUSE; entityInfoIndex < max; entityInfoIndex++ ) {
ids.add( entityInfos[entityInfoIndex].id );
}
disjunction.add( Restrictions.in( idName, ids ) );
@@ -97,8 +106,8 @@
public static List returnAlreadyLoadedObjectsInCorrectOrder(EntityInfo[] entityInfos, Session session) {
//mandatory to keep the same ordering
List result = new ArrayList( entityInfos.length );
- for (EntityInfo entityInfo : entityInfos) {
- Object element = session.load( entityInfo.clazz, entityInfo.id );
+ for ( EntityInfo entityInfo : entityInfos ) {
+ Object element = executeLoad( entityInfo, session );
if ( HibernateHelper.isInitialized( element ) ) {
//all existing elements should have been loaded by the query,
//the other ones are missing ones
@@ -106,11 +115,42 @@
}
else {
if ( log.isDebugEnabled() ) {
- log.debug( "Object found in Search index but not in database: {} with {}",
- entityInfo.clazz, entityInfo.id );
+ log.debug(
+ "Object found in Search index but not in database: {} with {}",
+ entityInfo.clazz, entityInfo.id
+ );
}
}
}
return result;
}
+
+ private static Object executeLoad(EntityInfo entityInfo, Session session) {
+ Object maybeProxy;
+ String hibernateIdentifierProperty = session.getSessionFactory()
+ .getClassMetadata( entityInfo.clazz )
+ .getIdentifierPropertyName();
+
+ if ( entityInfo.idName.equals( hibernateIdentifierProperty ) ) {
+ //be sure to get an initialized object but save from ONFE and ENFE
+ maybeProxy = session.load( entityInfo.clazz, entityInfo.id );
+ }
+ else {
+ Criteria criteria = session.createCriteria( entityInfo.clazz );
+ criteria.add( Restrictions.eq( entityInfo.idName, entityInfo.id ) );
+ try {
+ maybeProxy = criteria.uniqueResult();
+ }
+ catch ( HibernateException e ) {
+ throw new SearchException(
+ "Loading entity of type " + entityInfo.clazz.getName() + " using '"
+ + entityInfo.idName
+ + "' as document id and '"
+ + entityInfo.id
+ + "' as value was not unique"
+ );
+ }
+ }
+ return maybeProxy;
+ }
}
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/util/HibernateHelper.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/util/HibernateHelper.java 2010-09-22 13:27:42 UTC (rev 20679)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/util/HibernateHelper.java 2010-09-22 13:28:23 UTC (rev 20680)
@@ -1,3 +1,27 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ *
+ * 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.search.util;
import org.hibernate.Hibernate;
@@ -7,7 +31,8 @@
* @author Emmanuel Bernard
*/
public final class HibernateHelper {
- private HibernateHelper() {};
+ private HibernateHelper() {
+ }
/**
* Get the real class type.
Added: search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/Article.java
===================================================================
--- search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/Article.java (rev 0)
+++ search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/Article.java 2010-09-22 13:28:23 UTC (rev 20680)
@@ -0,0 +1,73 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ *
+ * 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
+ */
+
+// $Id:$
+package org.hibernate.search.test.id;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+import org.hibernate.search.annotations.DocumentId;
+import org.hibernate.search.annotations.Field;
+import org.hibernate.search.annotations.Index;
+import org.hibernate.search.annotations.Indexed;
+import org.hibernate.search.annotations.Store;
+
+/**
+ * @author Hardy Ferentschik
+ */
+@Entity
+@Indexed
+public class Article {
+ @Id
+ @GeneratedValue
+ long articleId;
+
+ @DocumentId
+ int documentId;
+
+ @Field(index = Index.TOKENIZED, store = Store.NO)
+ String text;
+
+ public long getArticleId() {
+ return articleId;
+ }
+
+ public int getDocumentId() {
+ return documentId;
+ }
+
+ public void setDocumentId(int documentId) {
+ this.documentId = documentId;
+ }
+
+ public String getText() {
+ return text;
+ }
+
+ public void setText(String text) {
+ this.text = text;
+ }
+}
\ No newline at end of file
Added: search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/DuplicateDocumentIdTest.java
===================================================================
--- search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/DuplicateDocumentIdTest.java (rev 0)
+++ search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/DuplicateDocumentIdTest.java 2010-09-22 13:28:23 UTC (rev 20680)
@@ -0,0 +1,61 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ *
+ * 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.search.test.id;
+
+import org.hibernate.HibernateException;
+import org.hibernate.search.test.SearchTestCase;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class DuplicateDocumentIdTest extends SearchTestCase {
+
+ public void setUp() {
+ // don't call super.setUp - we want to build the configuration in the test
+ }
+
+ /**
+ * Tests that an exception is thrown in case @DocumentId is specified on more than one property
+ *
+ * @throws Exception in case the test fails.
+ */
+ public void testDuplicateDocumentId() throws Exception {
+ try {
+ buildConfiguration();
+ fail( "Building of configuration should fail, because Foo defines multiple document ids." );
+ }
+ catch ( HibernateException e ) { // getting a HibernateException here, because the listener registration fails
+ assertEquals(
+ "More than one @DocumentId specified on entity org.hibernate.search.test.id.Foo",
+ e.getCause().getMessage()
+ );
+ }
+ }
+
+ protected Class<?>[] getAnnotatedClasses() {
+ return new Class[] {
+ Foo.class
+ };
+ }
+}
Added: search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/ExplicitIdTest.java
===================================================================
--- search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/ExplicitIdTest.java (rev 0)
+++ search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/ExplicitIdTest.java 2010-09-22 13:28:23 UTC (rev 20680)
@@ -0,0 +1,140 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ *
+ * 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.search.test.id;
+
+import java.util.List;
+
+import org.apache.lucene.index.Term;
+import org.apache.lucene.search.TermQuery;
+
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.hibernate.search.Search;
+import org.hibernate.search.SearchException;
+import org.hibernate.search.test.SearchTestCase;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class ExplicitIdTest extends SearchTestCase {
+
+ /**
+ * Tests that @DocumentId can be specified on a field other than the @Id annotated one. See HSEARCH-574.
+ *
+ * @throws Exception in case the test fails.
+ */
+ public void testExplicitDocumentIdSingleResult() throws Exception {
+ Article hello = new Article();
+ hello.setDocumentId( 1 );
+ hello.setText( "Hello World" );
+
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ s.save( hello );
+ tx.commit();
+ s.clear();
+
+ tx = s.beginTransaction();
+ List results = Search.getFullTextSession( s ).createFullTextQuery(
+ new TermQuery( new Term( "text", "world" ) )
+ ).list();
+ assertEquals( 1, results.size() );
+ tx.commit();
+ s.close();
+ }
+
+ /**
+ * Tests that @DocumentId can be specified on a field other than the @Id annotated one. See HSEARCH-574.
+ *
+ * @throws Exception in case the test fails.
+ */
+ public void testExplicitDocumentIdMultipleResults() throws Exception {
+ Article hello = new Article();
+ hello.setDocumentId( 1 );
+ hello.setText( "Hello World" );
+
+ Article goodbye = new Article();
+ goodbye.setDocumentId( 2 );
+ goodbye.setText( "Goodbye World" );
+
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ s.save( hello );
+ s.save( goodbye );
+ tx.commit();
+ s.clear();
+
+ tx = s.beginTransaction();
+ List results = Search.getFullTextSession( s ).createFullTextQuery(
+ new TermQuery( new Term( "text", "world" ) )
+ ).list();
+ assertEquals( 2, results.size() );
+ tx.commit();
+ s.close();
+ }
+
+ /**
+ * Tests that the document id must be unique
+ *
+ * @throws Exception in case the test fails.
+ */
+ public void testDocumentIdMustBeUnique() throws Exception {
+ Article hello = new Article();
+ hello.setDocumentId( 1 );
+ hello.setText( "Hello World" );
+
+ Article goodbye = new Article();
+ goodbye.setDocumentId( 1 );
+ goodbye.setText( "Goodbye World" );
+
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+ s.save( hello );
+ s.save( goodbye );
+ tx.commit();
+ s.clear();
+
+ tx = s.beginTransaction();
+ try {
+ Search.getFullTextSession( s ).createFullTextQuery(
+ new TermQuery( new Term( "text", "world" ) )
+ ).list();
+ fail( "Test should fail, because document id is not unique." );
+ }
+ catch ( SearchException e ) {
+ assertEquals(
+ "Loading entity of type org.hibernate.search.test.id.Article using 'documentId' as document id and '1' as value was not unique",
+ e.getMessage()
+ );
+ }
+ tx.commit();
+ s.close();
+ }
+
+ protected Class<?>[] getAnnotatedClasses() {
+ return new Class[] {
+ Article.class
+ };
+ }
+}
Added: search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/Foo.java
===================================================================
--- search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/Foo.java (rev 0)
+++ search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/Foo.java 2010-09-22 13:28:23 UTC (rev 20680)
@@ -0,0 +1,65 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ *
+ * 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.search.test.id;
+
+import java.lang.annotation.Documented;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+import org.hibernate.search.annotations.DocumentId;
+import org.hibernate.search.annotations.Field;
+import org.hibernate.search.annotations.Index;
+import org.hibernate.search.annotations.Indexed;
+
+/**
+ * @author Hardy Ferentschik
+ */
+@Entity
+@Indexed
+public class Foo {
+ @Id
+ @DocumentId
+ private Integer id;
+
+ @DocumentId
+ private String name;
+
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Modified: search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/ImplicitIdTest.java
===================================================================
--- search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/ImplicitIdTest.java 2010-09-22 13:27:42 UTC (rev 20679)
+++ search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/id/ImplicitIdTest.java 2010-09-22 13:28:23 UTC (rev 20680)
@@ -1,26 +1,25 @@
-/* $Id$
- *
+/*
* Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2009, Red Hat, Inc. and/or its affiliates 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, Inc.
- *
- * 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
+ *
+ * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ *
+ * 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.search.test.id;
Modified: search/trunk/hibernate-search-solr-analyzers/pom.xml
===================================================================
--- search/trunk/hibernate-search-solr-analyzers/pom.xml 2010-09-22 13:27:42 UTC (rev 20679)
+++ search/trunk/hibernate-search-solr-analyzers/pom.xml 2010-09-22 13:28:23 UTC (rev 20680)
@@ -1,26 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
- * Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2009, Red Hat, Inc. and/or its affiliates 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, Inc.
- *
- * 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
+ ~ Hibernate, Relational Persistence for Idiomatic Java
+ ~
+ ~ Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ ~
+ ~ 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
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
14 years, 2 months
Hibernate SVN: r20678 - in search/trunk/hibernate-search/src: main/java/org/hibernate/search/backend/impl and 6 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-09-21 11:42:42 -0400 (Tue, 21 Sep 2010)
New Revision: 20678
Added:
search/trunk/hibernate-search/src/main/java/org/hibernate/search/util/ClassLoaderHelper.java
search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/util/BarAnalyzer.java
search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/util/ClassLoaderHelperTest.java
search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/util/FooAnalyzer.java
Removed:
search/trunk/hibernate-search/src/main/java/org/hibernate/search/util/PluginLoader.java
search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/util/PluginLoaderTest.java
Modified:
search/trunk/hibernate-search/src/main/java/org/hibernate/search/backend/WorkerFactory.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/backend/impl/BatchedQueueingProcessor.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/DocumentBuilderContainedEntity.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/impl/ConfigContext.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/impl/ImmutableSearchFactory.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/impl/SearchFactoryBuilder.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/reader/ReaderProviderFactory.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/store/DirectoryProviderFactory.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/store/DirectoryProviderHelper.java
Log:
HSEARCH-457 Renamed PluginLoader to ClassLoaderHelper. Added tests for ClassLoaderHelper.analyzerInstanceFromClass
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/backend/WorkerFactory.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/backend/WorkerFactory.java 2010-09-21 14:30:34 UTC (rev 20677)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/backend/WorkerFactory.java 2010-09-21 15:42:42 UTC (rev 20678)
@@ -1,26 +1,25 @@
-/* $Id$
- *
+/*
* Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2009, Red Hat, Inc. and/or its affiliates 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, Inc.
- *
- * 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
+ *
+ * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ *
+ * 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.search.backend;
@@ -29,10 +28,10 @@
import org.hibernate.annotations.common.util.StringHelper;
import org.hibernate.search.Environment;
-import org.hibernate.search.spi.WorkerBuildContext;
import org.hibernate.search.backend.impl.TransactionalWorker;
import org.hibernate.search.cfg.SearchConfiguration;
-import org.hibernate.search.util.PluginLoader;
+import org.hibernate.search.spi.WorkerBuildContext;
+import org.hibernate.search.util.ClassLoaderHelper;
/**
* @author Emmanuel Bernard
@@ -42,11 +41,11 @@
private static Properties getProperties(SearchConfiguration cfg) {
Properties props = cfg.getProperties();
Properties workerProperties = new Properties();
- for (Map.Entry entry : props.entrySet()) {
- String key = (String) entry.getKey();
+ for ( Map.Entry entry : props.entrySet() ) {
+ String key = ( String ) entry.getKey();
if ( key.startsWith( Environment.WORKER_PREFIX ) ) {
//key.substring( Environment.WORKER_PREFIX.length() )
- workerProperties.setProperty( key, (String) entry.getValue() );
+ workerProperties.setProperty( key, ( String ) entry.getValue() );
}
}
return workerProperties;
@@ -63,11 +62,12 @@
worker = new TransactionalWorker();
}
else {
- worker = PluginLoader.instanceFromName( Worker.class,
- impl, WorkerFactory.class, "worker" );
+ worker = ClassLoaderHelper.instanceFromName(
+ Worker.class,
+ impl, WorkerFactory.class, "worker"
+ );
}
worker.initialize( props, context );
return worker;
}
-
}
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/backend/impl/BatchedQueueingProcessor.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/backend/impl/BatchedQueueingProcessor.java 2010-09-21 14:30:34 UTC (rev 20677)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/backend/impl/BatchedQueueingProcessor.java 2010-09-21 15:42:42 UTC (rev 20678)
@@ -1,26 +1,25 @@
-/* $Id$
- *
+/*
* Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2009, Red Hat, Inc. and/or its affiliates 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, Inc.
- *
- * 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
+ *
+ * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ *
+ * 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.search.backend.impl;
@@ -58,9 +57,9 @@
import org.hibernate.search.engine.DocumentBuilderContainedEntity;
import org.hibernate.search.engine.DocumentBuilderIndexedEntity;
import org.hibernate.search.engine.SearchFactoryImplementor;
+import org.hibernate.search.util.ClassLoaderHelper;
import org.hibernate.search.util.HibernateHelper;
import org.hibernate.search.util.LoggerFactory;
-import org.hibernate.search.util.PluginLoader;
/**
* Batch work until {@link #performWorks} is called.
@@ -116,7 +115,7 @@
backendQueueProcessorFactory = new SlaveJGroupsBackendQueueProcessorFactory();
}
else {
- backendQueueProcessorFactory = PluginLoader.instanceFromName( BackendQueueProcessorFactory.class,
+ backendQueueProcessorFactory = ClassLoaderHelper.instanceFromName( BackendQueueProcessorFactory.class,
backend, BatchedQueueingProcessor.class, "processor" );
}
backendQueueProcessorFactory.initialize( properties, context );
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/DocumentBuilderContainedEntity.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/DocumentBuilderContainedEntity.java 2010-09-21 14:30:34 UTC (rev 20677)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/DocumentBuilderContainedEntity.java 2010-09-21 15:42:42 UTC (rev 20678)
@@ -1,26 +1,25 @@
-/* $Id$
- *
+/*
* Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2009, Red Hat, Inc. and/or its affiliates 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, Inc.
- *
- * 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
+ *
+ * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ *
+ * 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.search.engine;
@@ -38,7 +37,6 @@
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Field;
import org.apache.lucene.search.Similarity;
-import org.apache.lucene.util.Version;
import org.slf4j.Logger;
import org.hibernate.annotations.common.AssertionFailure;
@@ -71,7 +69,7 @@
import org.hibernate.search.util.HibernateHelper;
import org.hibernate.search.util.LoggerFactory;
import org.hibernate.search.util.PassThroughAnalyzer;
-import org.hibernate.search.util.PluginLoader;
+import org.hibernate.search.util.ClassLoaderHelper;
import org.hibernate.search.util.ReflectionHelper;
import org.hibernate.search.util.ScopedAnalyzer;
@@ -249,13 +247,12 @@
return null;
}
else {
-
return context.buildLazyAnalyzer( definition );
}
}
else {
try {
- return PluginLoader.analyzerInstanceFromClass( analyzerClass, context.getLuceneMatchVersion() );
+ return ClassLoaderHelper.analyzerInstanceFromClass( analyzerClass, context.getLuceneMatchVersion() );
}
catch ( ClassCastException e ) {
throw new SearchException(
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/impl/ConfigContext.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/impl/ConfigContext.java 2010-09-21 14:30:34 UTC (rev 20677)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/impl/ConfigContext.java 2010-09-21 15:42:42 UTC (rev 20678)
@@ -41,9 +41,9 @@
import org.hibernate.search.SearchException;
import org.hibernate.search.annotations.AnalyzerDef;
import org.hibernate.search.cfg.SearchConfiguration;
+import org.hibernate.search.util.ClassLoaderHelper;
import org.hibernate.search.util.DelegateNamedAnalyzer;
import org.hibernate.search.util.LoggerFactory;
-import org.hibernate.search.util.PluginLoader;
/**
* Provides access to some default configuration settings (eg default <code>Analyzer</code> or default
@@ -114,7 +114,7 @@
else {
analyzerClass = StandardAnalyzer.class;
}
- return PluginLoader.analyzerInstanceFromClass( analyzerClass, luceneMatchVersion );
+ return ClassLoaderHelper.analyzerInstanceFromClass( analyzerClass, luceneMatchVersion );
}
/**
@@ -131,7 +131,7 @@
defaultSimilarity = Similarity.getDefault();
}
else {
- defaultSimilarity = PluginLoader.instanceFromName(
+ defaultSimilarity = ClassLoaderHelper.instanceFromName(
Similarity.class, similarityClassName, ConfigContext.class, "default similarity"
);
}
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/impl/ImmutableSearchFactory.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/impl/ImmutableSearchFactory.java 2010-09-21 14:30:34 UTC (rev 20677)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/impl/ImmutableSearchFactory.java 2010-09-21 15:42:42 UTC (rev 20678)
@@ -71,8 +71,8 @@
import org.hibernate.search.stat.StatisticsImplementor;
import org.hibernate.search.store.DirectoryProvider;
import org.hibernate.search.store.optimization.OptimizerStrategy;
+import org.hibernate.search.util.ClassLoaderHelper;
import org.hibernate.search.util.LoggerFactory;
-import org.hibernate.search.util.PluginLoader;
/**
* This implementation is never directly exposed to the user, it is always wrapped into a {@link org.hibernate.search.impl.MutableSearchFactory}
@@ -332,7 +332,7 @@
batchBackend = new LuceneBatchBackend();
}
else {
- batchBackend = PluginLoader.instanceFromName(
+ batchBackend = ClassLoaderHelper.instanceFromName(
BatchBackend.class, impl, ImmutableSearchFactory.class,
"batchbackend"
);
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/impl/SearchFactoryBuilder.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/impl/SearchFactoryBuilder.java 2010-09-21 14:30:34 UTC (rev 20677)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/impl/SearchFactoryBuilder.java 2010-09-21 15:42:42 UTC (rev 20678)
@@ -87,8 +87,8 @@
import org.hibernate.search.store.DirectoryProvider;
import org.hibernate.search.store.DirectoryProviderFactory;
import org.hibernate.search.store.optimization.OptimizerStrategy;
+import org.hibernate.search.util.ClassLoaderHelper;
import org.hibernate.search.util.LoggerFactory;
-import org.hibernate.search.util.PluginLoader;
import org.hibernate.search.util.ReflectionHelper;
/**
@@ -332,7 +332,7 @@
filterCachingStrategy = new MRUFilterCachingStrategy();
}
else {
- filterCachingStrategy = PluginLoader.instanceFromName(
+ filterCachingStrategy = ClassLoaderHelper.instanceFromName(
FilterCachingStrategy.class,
impl, ImmutableSearchFactory.class, "filterCachingStrategy"
);
@@ -519,7 +519,7 @@
return new LogErrorHandler();
}
else {
- return PluginLoader.instanceFromName(
+ return ClassLoaderHelper.instanceFromName(
ErrorHandler.class, errorHandlerClassName,
ImmutableSearchFactory.class, "Error Handler"
);
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/reader/ReaderProviderFactory.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/reader/ReaderProviderFactory.java 2010-09-21 14:30:34 UTC (rev 20677)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/reader/ReaderProviderFactory.java 2010-09-21 15:42:42 UTC (rev 20678)
@@ -1,26 +1,25 @@
-/* $Id$
- *
+/*
* Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2009, Red Hat, Inc. and/or its affiliates 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, Inc.
- *
- * 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
+ *
+ * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ *
+ * 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.search.reader;
@@ -29,9 +28,9 @@
import org.hibernate.annotations.common.util.StringHelper;
import org.hibernate.search.Environment;
+import org.hibernate.search.cfg.SearchConfiguration;
import org.hibernate.search.spi.BuildContext;
-import org.hibernate.search.cfg.SearchConfiguration;
-import org.hibernate.search.util.PluginLoader;
+import org.hibernate.search.util.ClassLoaderHelper;
/**
* @author Emmanuel Bernard
@@ -41,10 +40,10 @@
private static Properties getProperties(SearchConfiguration cfg) {
Properties props = cfg.getProperties();
Properties workerProperties = new Properties();
- for (Map.Entry entry : props.entrySet()) {
- String key = (String) entry.getKey();
+ for ( Map.Entry entry : props.entrySet() ) {
+ String key = ( String ) entry.getKey();
if ( key.startsWith( Environment.READER_PREFIX ) ) {
- workerProperties.setProperty( key, (String) entry.getValue() );
+ workerProperties.setProperty( key, ( String ) entry.getValue() );
}
}
return workerProperties;
@@ -69,8 +68,10 @@
readerProvider = new SharingBufferReaderProvider();
}
else {
- readerProvider = PluginLoader.instanceFromName( ReaderProvider.class, impl,
- ReaderProviderFactory.class, "readerProvider" );
+ readerProvider = ClassLoaderHelper.instanceFromName(
+ ReaderProvider.class, impl,
+ ReaderProviderFactory.class, "readerProvider"
+ );
}
readerProvider.initialize( props, context );
return readerProvider;
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/store/DirectoryProviderFactory.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/store/DirectoryProviderFactory.java 2010-09-21 14:30:34 UTC (rev 20677)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/store/DirectoryProviderFactory.java 2010-09-21 15:42:42 UTC (rev 20678)
@@ -1,26 +1,25 @@
-/* $Id$
- *
+/*
* Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2009, Red Hat, Inc. and/or its affiliates 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, Inc.
- *
- * 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
+ *
+ * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ *
+ * 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.search.store;
@@ -43,7 +42,7 @@
import org.hibernate.search.store.optimization.IncrementalOptimizerStrategy;
import org.hibernate.search.store.optimization.NoOpOptimizerStrategy;
import org.hibernate.search.store.optimization.OptimizerStrategy;
-import org.hibernate.search.util.PluginLoader;
+import org.hibernate.search.util.ClassLoaderHelper;
/**
* Create a Lucene directory provider which can be configured
@@ -102,7 +101,7 @@
}
}
else {
- shardingStrategy = PluginLoader.instanceFromName( IndexShardingStrategy.class,
+ shardingStrategy = ClassLoaderHelper.instanceFromName( IndexShardingStrategy.class,
shardingStrategyName, DirectoryProviderFactory.class, "IndexShardingStrategy" );
}
shardingStrategy.initialize(
@@ -124,7 +123,7 @@
provider = new FSDirectoryProvider();
}
else {
- provider = PluginLoader.instanceFromName( DirectoryProvider.class, className,
+ provider = ClassLoaderHelper.instanceFromName( DirectoryProvider.class, className,
DirectoryProviderFactory.class, "directory provider" );
}
try {
@@ -176,7 +175,7 @@
* in a global scope it will take priority on local transaction parameters.
* </p>
*
- * @param searchFactoryImplementor the search factory.
+ * @param context the build context.
* @param directoryProperties The properties extracted from the configuration.
* @param provider The directory provider for which to configure the indexing parameters.
*/
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/store/DirectoryProviderHelper.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/store/DirectoryProviderHelper.java 2010-09-21 14:30:34 UTC (rev 20677)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/store/DirectoryProviderHelper.java 2010-09-21 15:42:42 UTC (rev 20678)
@@ -1,26 +1,25 @@
-/* $Id$
- *
+/*
* Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2009, Red Hat, Inc. and/or its affiliates 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, Inc.
- *
- * 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
+ *
+ * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ *
+ * 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.search.store;
@@ -41,9 +40,9 @@
import org.hibernate.annotations.common.util.StringHelper;
import org.hibernate.search.SearchException;
+import org.hibernate.search.util.ClassLoaderHelper;
import org.hibernate.search.util.FileHelper;
import org.hibernate.search.util.LoggerFactory;
-import org.hibernate.search.util.PluginLoader;
/**
* @author Emmanuel Bernard
@@ -161,7 +160,7 @@
return new NoLockFactory();
}
else {
- LockFactoryFactory lockFactoryFactory = PluginLoader.instanceFromName( LockFactoryFactory.class,
+ LockFactoryFactory lockFactoryFactory = ClassLoaderHelper.instanceFromName( LockFactoryFactory.class,
lockFactoryName, DirectoryProviderHelper.class, "locking_strategy" );
return lockFactoryFactory.createLockFactory( indexDir, dirConfiguration );
}
Copied: search/trunk/hibernate-search/src/main/java/org/hibernate/search/util/ClassLoaderHelper.java (from rev 20676, search/trunk/hibernate-search/src/main/java/org/hibernate/search/util/PluginLoader.java)
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/util/ClassLoaderHelper.java (rev 0)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/util/ClassLoaderHelper.java 2010-09-21 15:42:42 UTC (rev 20678)
@@ -0,0 +1,225 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ *
+ * 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.search.util;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+
+import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.util.Version;
+
+import org.hibernate.annotations.common.util.ReflectHelper;
+import org.hibernate.search.SearchException;
+
+/**
+ * Utility class to load instances of other classes by using a fully qualified name,
+ * or from a class type.
+ * Uses reflection and throws SearchException(s) with proper descriptions of the error,
+ * like the target class is missing a proper constructor, is an interface, is not found...
+ *
+ * @author Sanne Grinovero
+ * @author Hardy Ferentschik
+ */
+public class ClassLoaderHelper {
+
+ private ClassLoaderHelper() {
+ }
+
+ /**
+ * Creates an instance of a target class designed by fully qualified name
+ *
+ * @param <T> matches the type of targetSuperType: defines the return type
+ * @param targetSuperType the return type of the function, the classNameToLoad will be checked
+ * to be assignable to this type.
+ * @param classNameToLoad a fully qualified class name, whose type is assignable to targetSuperType
+ * @param caller the class of the caller, needed for classloading purposes
+ * @param componentDescription a meaningful description of the role the instance will have,
+ * used to enrich error messages to describe the context of the error
+ *
+ * @return a new instance of classNameToLoad
+ *
+ * @throws SearchException wrapping other error types with a proper error message for all kind of problems, like
+ * classNotFound, missing proper constructor, wrong type, security errors.
+ */
+ public static <T> T instanceFromName(Class<T> targetSuperType, String classNameToLoad,
+ Class<?> caller, String componentDescription) {
+ final Class<?> clazzDef;
+ clazzDef = classForName( classNameToLoad, caller, componentDescription );
+ return instanceFromClass( targetSuperType, clazzDef, componentDescription );
+ }
+
+ /**
+ * Creates an instance of target class
+ *
+ * @param <T> the type of targetSuperType: defines the return type
+ * @param targetSuperType the created instance will be checked to be assignable to this type
+ * @param classToLoad the class to be instantiated
+ * @param componentDescription a role name/description to contextualize error messages
+ *
+ * @return a new instance of classToLoad
+ *
+ * @throws SearchException wrapping other error types with a proper error message for all kind of problems, like
+ * missing proper constructor, wrong type, security errors.
+ */
+ @SuppressWarnings("unchecked")
+ public static <T> T instanceFromClass(Class<T> targetSuperType, Class<?> classToLoad, String componentDescription) {
+ checkClassType( classToLoad, componentDescription );
+ checkHasNoArgConstructor( classToLoad, componentDescription );
+ Object instance;
+ try {
+ instance = classToLoad.newInstance();
+ }
+ catch ( IllegalAccessException e ) {
+ throw new SearchException(
+ "Unable to instantiate " + componentDescription + " class: " + classToLoad.getName() +
+ ". Class or constructor is not accessible.", e
+ );
+ }
+ catch ( InstantiationException e ) {
+ throw new SearchException(
+ "Unable to instantiate " + componentDescription + " class: " + classToLoad.getName() +
+ ". Verify it has a no-args public constructor and is not abstract.", e
+ );
+ }
+ if ( !targetSuperType.isInstance( instance ) ) {
+ // have a proper error message according to interface implementation or subclassing
+ if ( targetSuperType.isInterface() ) {
+ throw new SearchException(
+ "Wrong configuration of " + componentDescription + ": class " + classToLoad.getName()
+ + " does not implement interface " + targetSuperType.getName()
+ );
+ }
+ else {
+ throw new SearchException(
+ "Wrong configuration of " + componentDescription + ": class " + classToLoad.getName()
+ + " is not a subtype of " + targetSuperType.getName()
+ );
+ }
+ }
+ else {
+ return ( T ) instance;
+ }
+ }
+
+ public static Analyzer analyzerInstanceFromClass(Class<?> classToInstantiate, Version luceneMatchVersion) {
+ checkClassType( classToInstantiate, "analyzer" );
+ Analyzer analyzerInstance;
+
+ // try to get a constructor with a version parameter
+ Constructor constructor;
+ boolean useVersionParameter = true;
+ try {
+ constructor = classToInstantiate.getConstructor( Version.class );
+ }
+ catch ( NoSuchMethodException e ) {
+ try {
+ constructor = classToInstantiate.getConstructor();
+ useVersionParameter = false;
+ }
+ catch ( NoSuchMethodException nsme ) {
+ StringBuilder msg = new StringBuilder( "Unable to instantiate analyzer class: " );
+ msg.append( classToInstantiate.getName() );
+ msg.append( ". Class neither has a default constructor nor a constructor with a Version parameter" );
+ throw new SearchException( msg.toString(), e );
+ }
+ }
+
+ try {
+ if ( useVersionParameter ) {
+ analyzerInstance = ( Analyzer ) constructor.newInstance( luceneMatchVersion );
+ }
+ else {
+ analyzerInstance = ( Analyzer ) constructor.newInstance();
+ }
+ }
+ catch ( IllegalAccessException e ) {
+ throw new SearchException(
+ "Unable to instantiate analyzer class: " + classToInstantiate.getName() +
+ ". Class or constructor is not accessible.", e
+ );
+ }
+ catch ( InstantiationException e ) {
+ throw new SearchException(
+ "Unable to instantiate analyzer class: " + classToInstantiate.getName() +
+ ". Verify it has a no-args public constructor and is not abstract.", e
+ );
+ }
+ catch ( InvocationTargetException e ) {
+ throw new SearchException(
+ "Unable to instantiate analyzer class: " + classToInstantiate.getName() +
+ ". Verify it has a no-args public constructor and is not abstract.", e
+ );
+ }
+ return analyzerInstance;
+ }
+
+ private static void checkClassType(Class<?> classToLoad, String componentDescription) {
+ if ( classToLoad.isInterface() ) {
+ throw new SearchException(
+ classToLoad.getName() + " defined for component " + componentDescription
+ + " is an interface: implementation required."
+ );
+ }
+ }
+
+ /**
+ * Verifies if target class has a no-args constructor, and that it is
+ * accessible in current security manager.
+ *
+ * @param classToLoad the class type to check
+ * @param componentDescription adds a meaningful description to the type to describe in the
+ * exception message
+ */
+ private static void checkHasNoArgConstructor(Class<?> classToLoad, String componentDescription) {
+ try {
+ classToLoad.getConstructor();
+ }
+ catch ( SecurityException e ) {
+ throw new SearchException(
+ classToLoad.getName() + " defined for component " + componentDescription
+ + " could not be instantiated because of a security manager error", e
+ );
+ }
+ catch ( NoSuchMethodException e ) {
+ throw new SearchException(
+ classToLoad.getName() + " defined for component " + componentDescription
+ + " is missing a no-arguments constructor"
+ );
+ }
+ }
+
+ private static Class<?> classForName(String classNameToLoad, Class<?> caller, String componentDescription) {
+ Class<?> clazzDef;
+ try {
+ clazzDef = ReflectHelper.classForName( classNameToLoad, caller );
+ }
+ catch ( ClassNotFoundException e ) {
+ throw new SearchException(
+ "Unable to find " + componentDescription +
+ " implementation class: " + classNameToLoad, e
+ );
+ }
+ return clazzDef;
+ }
+}
Deleted: search/trunk/hibernate-search/src/main/java/org/hibernate/search/util/PluginLoader.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/util/PluginLoader.java 2010-09-21 14:30:34 UTC (rev 20677)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/util/PluginLoader.java 2010-09-21 15:42:42 UTC (rev 20678)
@@ -1,225 +0,0 @@
-/*
- * Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
- *
- * 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.search.util;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-
-import org.apache.lucene.analysis.Analyzer;
-import org.apache.lucene.util.Version;
-
-import org.hibernate.annotations.common.util.ReflectHelper;
-import org.hibernate.search.SearchException;
-
-/**
- * Utility class to load instances of other classes by using a fully qualified name,
- * or from a class type.
- * Uses reflection and throws SearchException(s) with proper descriptions of the error,
- * like the target class is missing a proper constructor, is an interface, is not found...
- *
- * @author Sanne Grinovero
- * @author Hardy Ferentschik
- */
-public class PluginLoader {
-
- private PluginLoader() {
- }
-
- /**
- * Creates an instance of a target class designed by fully qualified name
- *
- * @param <T> matches the type of targetSuperType: defines the return type
- * @param targetSuperType the return type of the function, the classNameToLoad will be checked
- * to be assignable to this type.
- * @param classNameToLoad a fully qualified class name, whose type is assignable to targetSuperType
- * @param caller the class of the caller, needed for classloading purposes
- * @param componentDescription a meaningful description of the role the instance will have,
- * used to enrich error messages to describe the context of the error
- *
- * @return a new instance of classNameToLoad
- *
- * @throws SearchException wrapping other error types with a proper error message for all kind of problems, like
- * classNotFound, missing proper constructor, wrong type, security errors.
- */
- public static <T> T instanceFromName(Class<T> targetSuperType, String classNameToLoad,
- Class<?> caller, String componentDescription) {
- final Class<?> clazzDef;
- clazzDef = classForName( classNameToLoad, caller, componentDescription );
- return instanceFromClass( targetSuperType, clazzDef, componentDescription );
- }
-
- /**
- * Creates an instance of target class
- *
- * @param <T> the type of targetSuperType: defines the return type
- * @param targetSuperType the created instance will be checked to be assignable to this type
- * @param classToLoad the class to be instantiated
- * @param componentDescription a role name/description to contextualize error messages
- *
- * @return a new instance of classToLoad
- *
- * @throws SearchException wrapping other error types with a proper error message for all kind of problems, like
- * missing proper constructor, wrong type, security errors.
- */
- @SuppressWarnings("unchecked")
- public static <T> T instanceFromClass(Class<T> targetSuperType, Class<?> classToLoad, String componentDescription) {
- checkClassType( classToLoad, componentDescription );
- checkHasNoArgConstructor( classToLoad, componentDescription );
- Object instance;
- try {
- instance = classToLoad.newInstance();
- }
- catch ( IllegalAccessException e ) {
- throw new SearchException(
- "Unable to instantiate " + componentDescription + " class: " + classToLoad.getName() +
- ". Class or constructor is not accessible.", e
- );
- }
- catch ( InstantiationException e ) {
- throw new SearchException(
- "Unable to instantiate " + componentDescription + " class: " + classToLoad.getName() +
- ". Verify it has a no-args public constructor and is not abstract.", e
- );
- }
- if ( !targetSuperType.isInstance( instance ) ) {
- // have a proper error message according to interface implementation or subclassing
- if ( targetSuperType.isInterface() ) {
- throw new SearchException(
- "Wrong configuration of " + componentDescription + ": class " + classToLoad.getName()
- + " does not implement interface " + targetSuperType.getName()
- );
- }
- else {
- throw new SearchException(
- "Wrong configuration of " + componentDescription + ": class " + classToLoad.getName()
- + " is not a subtype of " + targetSuperType.getName()
- );
- }
- }
- else {
- return ( T ) instance;
- }
- }
-
- public static Analyzer analyzerInstanceFromClass(Class<?> classToInstantiate, Version luceneMatchVersion) {
- checkClassType( classToInstantiate, "analyzer" );
- Analyzer analyzerInstance;
-
- // try to get a constructor with a version parameter
- Constructor constructor;
- boolean useVersionParameter = true;
- try {
- constructor = classToInstantiate.getConstructor( Version.class );
- }
- catch ( NoSuchMethodException e ) {
- try {
- constructor = classToInstantiate.getConstructor();
- useVersionParameter = false;
- }
- catch ( NoSuchMethodException nsme ) {
- StringBuilder msg = new StringBuilder( "Unable to instantiate analyzer class: " );
- msg.append( classToInstantiate.getName() );
- msg.append( ". Class neither has a default constructor nor a constructor with a Version parameter" );
- throw new SearchException( msg.toString(), e );
- }
- }
-
- try {
- if ( useVersionParameter ) {
- analyzerInstance = ( Analyzer ) constructor.newInstance( luceneMatchVersion );
- }
- else {
- analyzerInstance = ( Analyzer ) constructor.newInstance();
- }
- }
- catch ( IllegalAccessException e ) {
- throw new SearchException(
- "Unable to instantiate analyzer class: " + classToInstantiate.getName() +
- ". Class or constructor is not accessible.", e
- );
- }
- catch ( InstantiationException e ) {
- throw new SearchException(
- "Unable to instantiate analyzer class: " + classToInstantiate.getName() +
- ". Verify it has a no-args public constructor and is not abstract.", e
- );
- }
- catch ( InvocationTargetException e ) {
- throw new SearchException(
- "Unable to instantiate analyzer class: " + classToInstantiate.getName() +
- ". Verify it has a no-args public constructor and is not abstract.", e
- );
- }
- return analyzerInstance;
- }
-
- private static void checkClassType(Class<?> classToLoad, String componentDescription) {
- if ( classToLoad.isInterface() ) {
- throw new SearchException(
- classToLoad.getName() + " defined for component " + componentDescription
- + " is an interface: implementation required."
- );
- }
- }
-
- /**
- * Verifies if target class has a no-args constructor, and that it is
- * accessible in current security manager.
- *
- * @param classToLoad the class type to check
- * @param componentDescription adds a meaningful description to the type to describe in the
- * exception message
- */
- private static void checkHasNoArgConstructor(Class<?> classToLoad, String componentDescription) {
- try {
- classToLoad.getConstructor();
- }
- catch ( SecurityException e ) {
- throw new SearchException(
- classToLoad.getName() + " defined for component " + componentDescription
- + " could not be instantiated because of a security manager error", e
- );
- }
- catch ( NoSuchMethodException e ) {
- throw new SearchException(
- classToLoad.getName() + " defined for component " + componentDescription
- + " is missing a no-arguments constructor"
- );
- }
- }
-
- private static Class<?> classForName(String classNameToLoad, Class<?> caller, String componentDescription) {
- Class<?> clazzDef;
- try {
- clazzDef = ReflectHelper.classForName( classNameToLoad, caller );
- }
- catch ( ClassNotFoundException e ) {
- throw new SearchException(
- "Unable to find " + componentDescription +
- " implementation class: " + classNameToLoad, e
- );
- }
- return clazzDef;
- }
-}
Added: search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/util/BarAnalyzer.java
===================================================================
--- search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/util/BarAnalyzer.java (rev 0)
+++ search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/util/BarAnalyzer.java 2010-09-21 15:42:42 UTC (rev 20678)
@@ -0,0 +1,45 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ *
+ * 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.search.test.util;
+
+import java.io.Reader;
+
+import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.analysis.TokenStream;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class BarAnalyzer extends Analyzer {
+
+ private BarAnalyzer() {
+ }
+
+ @Override
+ public TokenStream tokenStream(String fieldName, Reader reader) {
+ return null;
+ }
+}
+
+
Added: search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/util/ClassLoaderHelperTest.java
===================================================================
--- search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/util/ClassLoaderHelperTest.java (rev 0)
+++ search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/util/ClassLoaderHelperTest.java 2010-09-21 15:42:42 UTC (rev 20678)
@@ -0,0 +1,154 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ *
+ * 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.search.test.util;
+
+import junit.framework.TestCase;
+import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.analysis.standard.StandardAnalyzer;
+import org.apache.lucene.search.DefaultSimilarity;
+import org.apache.lucene.search.Similarity;
+
+import org.hibernate.Session;
+import org.hibernate.search.FullTextSession;
+import org.hibernate.search.SearchException;
+import org.hibernate.search.backend.BackendQueueProcessorFactory;
+import org.hibernate.search.backend.impl.batchlucene.BatchBackend;
+import org.hibernate.search.backend.impl.batchlucene.LuceneBatchBackend;
+import org.hibernate.search.impl.FullTextSessionImpl;
+import org.hibernate.search.util.ClassLoaderHelper;
+
+/**
+ * Tests for {@code ClassLoaderHelper}. Verifying amongst other that it throws easy to understand exceptions.
+ *
+ * @author Sanne Grinovero
+ * @author Hardy Ferentschik
+ */
+public class ClassLoaderHelperTest extends TestCase {
+
+ public void testInstanceFromName() {
+ BatchBackend batchBackend = ClassLoaderHelper.instanceFromName(
+ BatchBackend.class, LuceneBatchBackend.class.getName(), getClass(), "Lucene batch backend"
+ );
+ assertNotNull( batchBackend );
+ assertTrue( batchBackend.getClass().equals( LuceneBatchBackend.class ) );
+
+ try {
+ ClassLoaderHelper.instanceFromName(
+ BackendQueueProcessorFactory.class, "HeyThisClassIsNotThere", getClass(), "backend"
+ );
+ fail( "was expecting a SearchException" );
+ }
+ catch ( Exception e ) {
+ assertEquals( e.getClass(), SearchException.class );
+ assertEquals( "Unable to find backend implementation class: HeyThisClassIsNotThere", e.getMessage() );
+ }
+ }
+
+ public void testInstanceFromClass() {
+ //testing for interface implementation:
+ BatchBackend batchBackend = ClassLoaderHelper.instanceFromClass(
+ BatchBackend.class, LuceneBatchBackend.class, "Lucene batch backend"
+ );
+ assertNotNull( batchBackend );
+ assertTrue( batchBackend.getClass().equals( LuceneBatchBackend.class ) );
+
+ //testing for subclasses:
+ Similarity sim = ClassLoaderHelper.instanceFromClass(
+ Similarity.class, DefaultSimilarity.class, "default similarity"
+ );
+ assertNotNull( sim );
+ assertTrue( sim.getClass().equals( DefaultSimilarity.class ) );
+
+ //testing proper error messages:
+ wrappingTestFromClass(
+ "Wrong configuration of Lucene batch backend: class " +
+ "org.hibernate.search.test.util.ClassLoaderHelperTest does not implement " +
+ "interface org.hibernate.search.backend.impl.batchlucene.BatchBackend",
+ BatchBackend.class, ClassLoaderHelperTest.class, "Lucene batch backend"
+ );
+ wrappingTestFromClass(
+ "org.hibernate.search.impl.FullTextSessionImpl defined for component session " +
+ "is missing a no-arguments constructor",
+ FullTextSession.class, FullTextSessionImpl.class, "session"
+ );
+ wrappingTestFromClass(
+ "org.hibernate.Session defined for component session is an interface: implementation required.",
+ FullTextSession.class, Session.class, "session"
+ );
+ wrappingTestFromClass(
+ "Wrong configuration of default similarity: " +
+ "class org.hibernate.search.backend.impl.batchlucene.LuceneBatchBackend " +
+ "is not a subtype of org.apache.lucene.search.Similarity",
+ Similarity.class, LuceneBatchBackend.class, "default similarity"
+ );
+ wrappingTestFromClass(
+ "Unable to instantiate default similarity class: org.apache.lucene.search.Similarity. " +
+ "Verify it has a no-args public constructor and is not abstract.",
+ Similarity.class, Similarity.class, "default similarity"
+ );
+ }
+
+ public void testLoadingAnalyzerWithVersionConstructor() {
+ Analyzer analyzer = ClassLoaderHelper.analyzerInstanceFromClass(
+ StandardAnalyzer.class, org.apache.lucene.util.Version.LUCENE_30
+ );
+ assertNotNull( "We should be able to instantiate an analyzer with a Lucene version parameter", analyzer );
+ }
+
+ public void testLoadingAnalyzerWithDefaultConstructor() {
+ Analyzer analyzer = ClassLoaderHelper.analyzerInstanceFromClass(
+ FooAnalyzer.class, org.apache.lucene.util.Version.LUCENE_30
+ );
+ assertNotNull( "We should be able to instantiate an analyzer which has only a default constructor", analyzer );
+ }
+
+ public void testLoadingAnalyzerWithNoVersionOrDefaultConstructor() {
+ try {
+ ClassLoaderHelper.analyzerInstanceFromClass(
+ BarAnalyzer.class, org.apache.lucene.util.Version.LUCENE_30
+ );
+ fail( "We should not be able to instantiate a analyzer with no default constructor or simple Version parameter." );
+ }
+ catch ( SearchException e ) {
+ assertEquals( e.getClass(), SearchException.class );
+ assertEquals(
+ "Unable to instantiate analyzer class: org.hibernate.search.test.util.BarAnalyzer. " +
+ "Class neither has a default constructor nor a constructor with a Version parameter",
+ e.getMessage()
+ );
+ }
+ }
+
+ private void wrappingTestFromClass(String expectedErrorMessage, Class<?> interf, Class<?> impl, String componentName) {
+ try {
+ ClassLoaderHelper.instanceFromClass( interf, impl, componentName );
+ fail( "was expecting a SearchException" );
+ }
+ catch ( Exception e ) {
+ assertEquals( e.getClass(), SearchException.class );
+ assertEquals( expectedErrorMessage, e.getMessage() );
+ }
+ }
+}
+
Added: search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/util/FooAnalyzer.java
===================================================================
--- search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/util/FooAnalyzer.java (rev 0)
+++ search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/util/FooAnalyzer.java 2010-09-21 15:42:42 UTC (rev 20678)
@@ -0,0 +1,41 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates 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, Inc.
+ *
+ * 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.search.test.util;
+
+import java.io.Reader;
+
+import org.apache.lucene.analysis.Analyzer;
+import org.apache.lucene.analysis.TokenStream;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class FooAnalyzer extends Analyzer {
+ @Override
+ public TokenStream tokenStream(String fieldName, Reader reader) {
+ return null;
+ }
+}
+
+
Deleted: search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/util/PluginLoaderTest.java
===================================================================
--- search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/util/PluginLoaderTest.java 2010-09-21 14:30:34 UTC (rev 20677)
+++ search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/util/PluginLoaderTest.java 2010-09-21 15:42:42 UTC (rev 20678)
@@ -1,114 +0,0 @@
-/* $Id$
- *
- * Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2009, Red Hat, Inc. and/or its affiliates 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, Inc.
- *
- * 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.search.test.util;
-
-import org.apache.lucene.search.DefaultSimilarity;
-import org.apache.lucene.search.Similarity;
-import org.hibernate.Session;
-import org.hibernate.search.FullTextSession;
-import org.hibernate.search.SearchException;
-import org.hibernate.search.backend.BackendQueueProcessorFactory;
-import org.hibernate.search.backend.impl.batchlucene.BatchBackend;
-import org.hibernate.search.backend.impl.batchlucene.LuceneBatchBackend;
-import org.hibernate.search.impl.FullTextSessionImpl;
-import org.hibernate.search.util.PluginLoader;
-
-import junit.framework.TestCase;
-
-/**
- * Test for PluginLoader, also verifying it throws easy to understand exceptions
- *
- * @author Sanne Grinovero
- */
-public class PluginLoaderTest extends TestCase {
-
- public void testInstanceFromName() {
- BatchBackend batchBackend = PluginLoader.instanceFromName(BatchBackend.class, LuceneBatchBackend.class.getName(), getClass(), "Lucene batch backend");
- assertNotNull( batchBackend );
- assertTrue( batchBackend.getClass().equals( LuceneBatchBackend.class ) );
-
- try {
- PluginLoader.instanceFromName( BackendQueueProcessorFactory.class, "HeyThisClassIsNotThere", getClass(), "backend" );
- fail( "was expecting a SearchException" );
- }
- catch (Exception e) {
- assertEquals( e.getClass(), SearchException.class );
- assertEquals( "Unable to find backend implementation class: HeyThisClassIsNotThere", e.getMessage() );
- }
- }
-
- public void testInstanceFromClass() {
- //testing for interface implementation:
- BatchBackend batchBackend = PluginLoader.instanceFromClass( BatchBackend.class, LuceneBatchBackend.class, "Lucene batch backend" );
- assertNotNull( batchBackend );
- assertTrue( batchBackend.getClass().equals( LuceneBatchBackend.class ) );
-
- //testing for subclasses:
- Similarity sim = PluginLoader.instanceFromClass( Similarity.class, DefaultSimilarity.class, "default similarity" );
- assertNotNull( sim );
- assertTrue( sim.getClass().equals( DefaultSimilarity.class ) );
-
- //testing proper error messages:
- wrappingTestFromClass(
- "Wrong configuration of Lucene batch backend: class " +
- "org.hibernate.search.test.util.PluginLoaderTest does not implement " +
- "interface org.hibernate.search.backend.impl.batchlucene.BatchBackend",
- BatchBackend.class, PluginLoaderTest.class, "Lucene batch backend"
- );
- wrappingTestFromClass(
- "org.hibernate.search.impl.FullTextSessionImpl defined for component session " +
- "is missing a no-arguments constructor",
- FullTextSession.class, FullTextSessionImpl.class, "session"
- );
- wrappingTestFromClass(
- "org.hibernate.Session defined for component session is an interface: implementation required.",
- FullTextSession.class, Session.class, "session"
- );
- wrappingTestFromClass(
- "Wrong configuration of default similarity: " +
- "class org.hibernate.search.backend.impl.batchlucene.LuceneBatchBackend " +
- "is not a subtype of org.apache.lucene.search.Similarity",
- Similarity.class, LuceneBatchBackend.class, "default similarity"
- );
- wrappingTestFromClass(
- "Unable to instantiate default similarity class: org.apache.lucene.search.Similarity. " +
- "Verify it has a no-args public constructor and is not abstract.",
- Similarity.class, Similarity.class, "default similarity"
- );
- }
-
- private void wrappingTestFromClass(String expectedErrorMessage, Class<?> interf, Class<?> impl, String componentName) {
- try {
- PluginLoader.instanceFromClass( interf, impl, componentName );
- fail( "was expecting a SearchException" );
- }
- catch (Exception e) {
- assertEquals( e.getClass(), SearchException.class );
- assertEquals( expectedErrorMessage, e.getMessage() );
- }
- }
-
-}
-
14 years, 2 months
Hibernate SVN: r20677 - tools/trunk/src/test/org/hibernate/tool/stat.
by hibernate-commits@lists.jboss.org
Author: max.andersen(a)jboss.com
Date: 2010-09-21 10:30:34 -0400 (Tue, 21 Sep 2010)
New Revision: 20677
Added:
tools/trunk/src/test/org/hibernate/tool/stat/StatisticsBrowserDemo.java
Removed:
tools/trunk/src/test/org/hibernate/tool/stat/StatisticsBrowserTest.java
Log:
Renamed non-unittest to Demo to avoid it to mess up with other unit tests.
Added: tools/trunk/src/test/org/hibernate/tool/stat/StatisticsBrowserDemo.java
===================================================================
--- tools/trunk/src/test/org/hibernate/tool/stat/StatisticsBrowserDemo.java (rev 0)
+++ tools/trunk/src/test/org/hibernate/tool/stat/StatisticsBrowserDemo.java 2010-09-21 14:30:34 UTC (rev 20677)
@@ -0,0 +1,101 @@
+package org.hibernate.tool.stat;
+
+import java.sql.Connection;
+import java.sql.Statement;
+import java.util.Properties;
+
+import org.hibernate.Transaction;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.cfg.Settings;
+import org.hibernate.classic.Session;
+import org.hibernate.tool.NonReflectiveTestCase;
+
+public class StatisticsBrowserDemo extends NonReflectiveTestCase {
+
+ public StatisticsBrowserDemo(String name) {
+ super( name );
+ }
+ /*
+ protected void configure(Configuration cfg) {
+ super.configure( cfg );
+ cfg.setProperty( Environment.USE_STRUCTURED_CACHE, "true" );
+ }*/
+
+ protected void setUp() throws Exception {
+ // TODO Auto-generated method stub
+ super.setUp();
+ if(getSessions()==null) {
+ buildSessionFactory();
+ }
+ }
+ public void testBrowser() throws Exception {
+ getSessions().getStatistics().setStatisticsEnabled( true );
+
+ new StatisticsBrowser().showStatistics( getSessions().getStatistics(), false );
+
+
+ Session s = openSession();
+ Transaction tx = s.beginTransaction();
+
+ for(int i=0; i<100; i++) {
+ Group group = new Group( "Hibernate" + i );
+ group.addUser(new User("gavin" + i, "figo123"));
+ group.addUser(new User("cbauer" + i, "figo123"));
+ group.addUser(new User("steve" + i, "figo123"));
+ group.addUser(new User("max" + i, "figo123"));
+ group.addUser(new User("anthony" + i, "figo123"));
+
+ s.saveOrUpdate( group );
+ if(i % 20==0) s.flush();
+ }
+ s.flush();
+ s.clear();
+ s.createQuery( "from java.lang.Object" ).list();
+ tx.commit();
+ s.close();
+
+
+
+ //Uncomment if you want to look on StatisticsBrowser
+ //Thread.sleep( 100000 );
+
+ }
+
+ protected void tearDown() throws Exception {
+ Statement statement = null;
+ Connection con = null;
+ Settings settings = null;
+ try {
+ settings = getConfiguration().buildSettings();
+ con = settings.getConnectionProvider().getConnection();
+ statement = con.createStatement();
+ statement.execute("drop table Session_attributes");
+ statement.execute("drop table Users");
+ statement.execute("drop table Groups");
+ con.commit();
+ } finally {
+ if (statement!=null) statement.close();
+ settings.getConnectionProvider().closeConnection(con);
+ }
+
+ super.tearDown();
+ }
+
+ protected String getBaseForMappings() {
+ return "org/hibernate/tool/stat/";
+ }
+
+ protected void addMappings(String[] files, Configuration cfg) {
+ Properties prop = new Properties();
+ prop.put(Environment.CACHE_PROVIDER,
+ "org.hibernate.cache.EhCacheProvider");
+ cfg.addProperties(prop);
+ super.addMappings(files, cfg);
+ }
+
+ protected String[] getMappings() {
+ return new String[] { "UserGroup.hbm.xml"};
+ }
+
+}
Deleted: tools/trunk/src/test/org/hibernate/tool/stat/StatisticsBrowserTest.java
===================================================================
--- tools/trunk/src/test/org/hibernate/tool/stat/StatisticsBrowserTest.java 2010-09-21 14:12:42 UTC (rev 20676)
+++ tools/trunk/src/test/org/hibernate/tool/stat/StatisticsBrowserTest.java 2010-09-21 14:30:34 UTC (rev 20677)
@@ -1,96 +0,0 @@
-package org.hibernate.tool.stat;
-
-import java.sql.Connection;
-import java.sql.Statement;
-import java.util.Properties;
-
-import org.hibernate.Transaction;
-import org.hibernate.cfg.Configuration;
-import org.hibernate.cfg.Environment;
-import org.hibernate.cfg.Settings;
-import org.hibernate.classic.Session;
-import org.hibernate.tool.NonReflectiveTestCase;
-
-public class StatisticsBrowserTest extends NonReflectiveTestCase {
-
- public StatisticsBrowserTest(String name) {
- super( name );
- }
- /*
- protected void configure(Configuration cfg) {
- super.configure( cfg );
- cfg.setProperty( Environment.USE_STRUCTURED_CACHE, "true" );
- }*/
-
- protected void setUp() throws Exception {
- // TODO Auto-generated method stub
- super.setUp();
- if(getSessions()==null) {
- buildSessionFactory();
- }
- }
- public void testBrowser() throws Exception {
- getSessions().getStatistics().setStatisticsEnabled( true );
-
- new StatisticsBrowser().showStatistics( getSessions().getStatistics(), false );
-
-
- Session s = openSession();
- Transaction tx = s.beginTransaction();
-
- for(int i=0; i<100; i++) {
- Group group = new Group( "Hibernate" + i );
- group.addUser(new User("gavin" + i, "figo123"));
- group.addUser(new User("cbauer" + i, "figo123"));
- group.addUser(new User("steve" + i, "figo123"));
- group.addUser(new User("max" + i, "figo123"));
- group.addUser(new User("anthony" + i, "figo123"));
-
- s.saveOrUpdate( group );
- if(i % 20==0) s.flush();
- }
- s.flush();
- s.clear();
- s.createQuery( "from java.lang.Object" ).list();
- tx.commit();
- s.close();
-
- Statement statement = null;
- Connection con = null;
- Settings settings = null;
- try {
- settings = getConfiguration().buildSettings();
- con = settings.getConnectionProvider().getConnection();
- statement = con.createStatement();
- statement.execute("drop table Session_attributes");
- statement.execute("drop table Users");
- statement.execute("drop table Groups");
- con.commit();
- } finally {
- if (statement!=null) statement.close();
- settings.getConnectionProvider().closeConnection(con);
- }
-
- //Uncomment if you want to look on StatisticsBrowser
- //Thread.sleep( 100000 );
-
- }
-
-
- protected String getBaseForMappings() {
- return "org/hibernate/tool/stat/";
- }
-
- protected void addMappings(String[] files, Configuration cfg) {
- Properties prop = new Properties();
- prop.put(Environment.CACHE_PROVIDER,
- "org.hibernate.cache.EhCacheProvider");
- cfg.addProperties(prop);
- super.addMappings(files, cfg);
- }
-
- protected String[] getMappings() {
- return new String[] { "UserGroup.hbm.xml"};
- }
-
-}
14 years, 2 months
Hibernate SVN: r20676 - in search/trunk/hibernate-search/src: main/java/org/hibernate/search/engine and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-09-21 10:12:42 -0400 (Tue, 21 Sep 2010)
New Revision: 20676
Modified:
search/trunk/hibernate-search/src/main/java/org/hibernate/search/bridge/LuceneOptions.java
search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/LuceneOptionsImpl.java
search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/compression/CompressionTest.java
search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/compression/HTMLBoldFieldBridge.java
Log:
HSEARCH-596 Updated CompressionTest
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/bridge/LuceneOptions.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/bridge/LuceneOptions.java 2010-09-21 12:26:03 UTC (rev 20675)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/bridge/LuceneOptions.java 2010-09-21 14:12:42 UTC (rev 20676)
@@ -35,8 +35,19 @@
*/
public interface LuceneOptions {
- void addFieldToDocument(String name, String indexedString, Document document);
+ /**
+ * Add a new field with the name {@code fieldName} to the Lucene Document {@code document} using the value
+ * {@code indexedString}.
+ *
+ * @param fieldName The field name
+ * @param indexedString The value to index
+ * @param document the document to which to add the the new field
+ */
+ void addFieldToDocument(String fieldName, String indexedString, Document document);
+ /**
+ * @return {@code true} if the field value is compressed, {@code false} otherwise.
+ */
boolean isCompressed();
/**
Modified: search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/LuceneOptionsImpl.java
===================================================================
--- search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/LuceneOptionsImpl.java 2010-09-21 12:26:03 UTC (rev 20675)
+++ search/trunk/hibernate-search/src/main/java/org/hibernate/search/engine/LuceneOptionsImpl.java 2010-09-21 14:12:42 UTC (rev 20676)
@@ -59,7 +59,6 @@
public void addFieldToDocument(String name, String indexedString, Document document) {
//Do not add fields on empty strings, seems a sensible default in most situations
- //TODO if Store, probably also save empty ones
if ( StringHelper.isNotEmpty( indexedString ) ) {
if ( !( indexMode.equals( Index.NO ) && storeCompressed ) ) {
standardFieldAdd( name, indexedString, document );
Modified: search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/compression/CompressionTest.java
===================================================================
--- search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/compression/CompressionTest.java 2010-09-21 12:26:03 UTC (rev 20675)
+++ search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/compression/CompressionTest.java 2010-09-21 14:12:42 UTC (rev 20676)
@@ -47,10 +47,16 @@
import org.hibernate.search.store.DirectoryProvider;
import org.hibernate.search.test.SearchTestCase;
+/**
+ * @author Sanne Grinovero
+ * @author Hardy Ferentschik
+ */
public class CompressionTest extends SearchTestCase {
/**
- * verifies the fields are really stored in compressed format
+ * Verifies the fields are really stored in compressed format
+ *
+ * @throws Exception in case the test fails
*/
public void testFieldWasCompressed() throws Exception {
DirectoryProvider[] directoryProviders = getSearchFactory().getDirectoryProviders( LargeDocument.class );
@@ -64,30 +70,29 @@
Document document = indexReader.document( doc.doc );
{
Field[] fields = document.getFields( "title" );
- Assert.assertEquals( 1, fields.length );
-// Assert.assertFalse( fields[0].isCompressed() );
- Assert.assertTrue( fields[0].isIndexed() );
- Assert.assertTrue( fields[0].isStored() );
- Assert.assertEquals(
+ assertEquals( 1, fields.length );
+ assertTrue( fields[0].isIndexed() );
+ assertTrue( fields[0].isStored() );
+ assertFalse( isCompressed( fields[0] ) );
+ assertEquals(
"Hibernate in Action, third edition",
fields[0].stringValue()
);
}
{
Field[] fields = document.getFields( "abstract" );
- Assert.assertEquals( 1, fields.length );
-// Assert.assertTrue( isCompressed( fields[0] ) );
-// Assert.assertTrue( fields[0].isCompressed() );
- Assert.assertEquals(
+ assertEquals( 1, fields.length );
+ assertTrue( isCompressed( fields[0] ) );
+ assertEquals(
"<b>JPA2 with Hibernate</b>",
restoreValue( fields[0] )
);
}
{
Field[] fields = document.getFields( "text" );
- Assert.assertEquals( 1, fields.length );
- Assert.assertTrue( isCompressed( fields[0] ) );
- Assert.assertEquals(
+ assertEquals( 1, fields.length );
+ assertTrue( isCompressed( fields[0] ) );
+ assertEquals(
"This is a placeholder for the new text that you should write",
restoreValue( fields[0] )
);
@@ -99,25 +104,28 @@
}
/**
- * Verifies the compressed fields are also searchable
+ * Verifies the compressed fields are also searchable.
+ *
+ * @throws Exception in case the test fails
*/
-// public void testCompressedFieldSearch() throws ParseException {
-// assertFindsN( 1, "title:third" );
-// assertFindsN( 1, "abstract:jpa2" );
-// assertFindsN( 1, "text:write" );
-// assertFindsN( 0, "text:jpa2" );
-// }
+ public void testCompressedFieldSearch() throws Exception {
+ assertFindsN( 1, "title:third" );
+ assertFindsN( 1, "abstract:jpa2" );
+ assertFindsN( 1, "text:write" );
+ assertFindsN( 0, "text:jpa2" );
+ }
private void assertFindsN(int expectedToFind, String queryString) throws ParseException {
openSession().beginTransaction();
try {
FullTextSession fullTextSession = Search.getFullTextSession( session );
- QueryParser qparser = new QueryParser( getTargetLuceneVersion(), "", new SimpleAnalyzer() );
- Query query = qparser.parse( queryString );
+ QueryParser queryParser = new QueryParser( getTargetLuceneVersion(), "", new SimpleAnalyzer() );
+ Query query = queryParser.parse( queryString );
FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(
query,
LargeDocument.class
);
+ @SuppressWarnings("unchecked")
List<LargeDocument> list = fullTextQuery.list();
Assert.assertEquals( expectedToFind, list.size() );
if ( expectedToFind == 1 ) {
@@ -133,29 +141,27 @@
/**
* Verify that projection is able to inflate stored data
*/
-// public void testProjectionOnCompressedFields() {
-// openSession().beginTransaction();
-// try {
-// FullTextSession fullTextSession = Search.getFullTextSession( session );
-// FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(
-// new MatchAllDocsQuery(),
-// LargeDocument.class
-// );
-// List list = fullTextQuery.setProjection( "title", "abstract", "text" ).list();
-// Assert.assertEquals( 1, list.size() );
-// Object[] results = ( Object[] ) list.get( 0 );
-// Assert.assertEquals( "Hibernate in Action, third edition", results[0] );
-// Assert.assertEquals( "JPA2 with Hibernate", results[1] );
-// Assert.assertEquals( "This is a placeholder for the new text that you should write", results[2] );
-// }
-// finally {
-// session.getTransaction().commit();
-// session.close();
-// }
-// }
+ public void testProjectionOnCompressedFields() {
+ openSession().beginTransaction();
+ try {
+ FullTextSession fullTextSession = Search.getFullTextSession( session );
+ FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(
+ new MatchAllDocsQuery(),
+ LargeDocument.class
+ );
+ List list = fullTextQuery.setProjection( "title", "abstract", "text" ).list();
+ Assert.assertEquals( 1, list.size() );
+ Object[] results = ( Object[] ) list.get( 0 );
+ Assert.assertEquals( "Hibernate in Action, third edition", results[0] );
+ Assert.assertEquals( "JPA2 with Hibernate", results[1] );
+ Assert.assertEquals( "This is a placeholder for the new text that you should write", results[2] );
+ }
+ finally {
+ session.getTransaction().commit();
+ session.close();
+ }
+ }
- // test helpers:
-
private String restoreValue(Field field) throws DataFormatException {
if ( field.isBinary() ) {
Assert.assertNull( "we rely on this in the Projection implementation", field.stringValue() );
@@ -167,11 +173,20 @@
}
private boolean isCompressed(Field field) {
- return field.isBinary(); // ( field.isBinary() || field.isCompressed() );
+ if ( !field.isBinary() ) {
+ return false;
+ }
+ else {
+ try {
+ CompressionTools.decompressString( field.getBinaryValue() );
+ return true;
+ }
+ catch ( DataFormatException e ) {
+ return false;
+ }
+ }
}
- // test setup:
-
protected Class<?>[] getAnnotatedClasses() {
return new Class[] {
LargeDocument.class
Modified: search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/compression/HTMLBoldFieldBridge.java
===================================================================
--- search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/compression/HTMLBoldFieldBridge.java 2010-09-21 12:26:03 UTC (rev 20675)
+++ search/trunk/hibernate-search/src/test/java/org/hibernate/search/test/compression/HTMLBoldFieldBridge.java 2010-09-21 14:12:42 UTC (rev 20676)
@@ -24,41 +24,50 @@
*/
package org.hibernate.search.test.compression;
+import java.util.zip.DataFormatException;
+
+import org.apache.lucene.document.CompressionTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
+
+import org.hibernate.search.SearchException;
import org.hibernate.search.bridge.FieldBridge;
import org.hibernate.search.bridge.LuceneOptions;
import org.hibernate.search.bridge.TwoWayFieldBridge;
/**
- * This FieldBridge is storing strings in the index wrapping the
- * entity value in html bold tags.
- * It's using deprecated method "getStore" to verify backwards compatibility
- * Almost useless, needed for CompressionTest
+ * This FieldBridge is storing strings in the index wrapping the entity value in html bold tags.
+ *
+ * @author Sanne Grinovero
* @see LuceneOptions
- * @author Sanne Grinovero
*/
public class HTMLBoldFieldBridge implements FieldBridge, TwoWayFieldBridge {
public void set(String name, Object value, Document document, LuceneOptions luceneOptions) {
String fieldValue = objectToString( value );
- Field field = new Field( name, fieldValue, luceneOptions.getStore(),
- luceneOptions.getIndex(), luceneOptions.getTermVector() );
- field.setBoost( luceneOptions.getBoost() );
- document.add( field );
+ luceneOptions.addFieldToDocument( name, fieldValue, document );
}
public Object get(String name, Document document) {
Field field = document.getField( name );
- String stringValue = field.stringValue();
- return stringValue.substring( 3, stringValue.length()-4 );
+ String stringValue;
+ if ( field.isBinary() ) {
+ try {
+ stringValue = CompressionTools.decompressString( field.getBinaryValue() );
+ }
+ catch ( DataFormatException e) {
+ throw new SearchException( "Field " + name + " looks like binary but couldn't be decompressed" );
+ }
+ }
+ else {
+ stringValue = field.stringValue();
+ }
+ return stringValue.substring( 3, stringValue.length() - 4 );
}
public String objectToString(Object value) {
String originalValue = value.toString();
- String fieldValue = "<b>" + originalValue + "</b>";
- return fieldValue;
+ return "<b>" + originalValue + "</b>";
}
-
}
14 years, 2 months
Hibernate SVN: r20675 - in tools/trunk/src/test/org/hibernate/tool: stat and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: dgeraskov
Date: 2010-09-21 08:26:03 -0400 (Tue, 21 Sep 2010)
New Revision: 20675
Modified:
tools/trunk/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest.java
tools/trunk/src/test/org/hibernate/tool/stat/StatisticsBrowserTest.java
Log:
Fix failing tests
Modified: tools/trunk/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest.java
===================================================================
--- tools/trunk/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest.java 2010-09-21 03:16:47 UTC (rev 20674)
+++ tools/trunk/src/test/org/hibernate/tool/hbm2x/hbm2hbmxml/MapAndAnyTest.java 2010-09-21 12:26:03 UTC (rev 20675)
@@ -36,8 +36,6 @@
*/
public class MapAndAnyTest extends NonReflectiveTestCase {
- private String mappingFile = "Properties.hbm.xml";
-
private Exporter hbmexporter;
/**
@@ -50,7 +48,8 @@
protected String[] getMappings() {
return new String[] {
- mappingFile
+ "Properties.hbm.xml",
+ "Person2.hbm.xml"
};
}
@@ -116,11 +115,6 @@
}
public void testMetaValueRead() throws Exception{
- String oldMappingFile = mappingFile;
- mappingFile = "Person2.hbm.xml";
-
- super.setUp();//rebuld cfg
-
Configuration config = getCfg();
PersistentClass pc = config.getClassMapping("org.hibernate.tool.hbm2x.hbm2hbmxml.Person2");
assertNotNull(pc);
@@ -130,7 +124,7 @@
Any any = (Any) prop.getValue();
assertTrue("Expected to get one meta-value element", any.getMetaValues() != null);
assertEquals("Expected to get one meta-value element", 1, any.getMetaValues().size());
- mappingFile = oldMappingFile;
+
}
public void testMapManyToAny() throws DocumentException {
Modified: tools/trunk/src/test/org/hibernate/tool/stat/StatisticsBrowserTest.java
===================================================================
--- tools/trunk/src/test/org/hibernate/tool/stat/StatisticsBrowserTest.java 2010-09-21 03:16:47 UTC (rev 20674)
+++ tools/trunk/src/test/org/hibernate/tool/stat/StatisticsBrowserTest.java 2010-09-21 12:26:03 UTC (rev 20675)
@@ -1,6 +1,13 @@
package org.hibernate.tool.stat;
+import java.sql.Connection;
+import java.sql.Statement;
+import java.util.Properties;
+
import org.hibernate.Transaction;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.cfg.Settings;
import org.hibernate.classic.Session;
import org.hibernate.tool.NonReflectiveTestCase;
@@ -48,13 +55,40 @@
tx.commit();
s.close();
- Thread.sleep( 100000 );
+ Statement statement = null;
+ Connection con = null;
+ Settings settings = null;
+ try {
+ settings = getConfiguration().buildSettings();
+ con = settings.getConnectionProvider().getConnection();
+ statement = con.createStatement();
+ statement.execute("drop table Session_attributes");
+ statement.execute("drop table Users");
+ statement.execute("drop table Groups");
+ con.commit();
+ } finally {
+ if (statement!=null) statement.close();
+ settings.getConnectionProvider().closeConnection(con);
+ }
+ //Uncomment if you want to look on StatisticsBrowser
+ //Thread.sleep( 100000 );
+
}
+
protected String getBaseForMappings() {
return "org/hibernate/tool/stat/";
}
+
+ protected void addMappings(String[] files, Configuration cfg) {
+ Properties prop = new Properties();
+ prop.put(Environment.CACHE_PROVIDER,
+ "org.hibernate.cache.EhCacheProvider");
+ cfg.addProperties(prop);
+ super.addMappings(files, cfg);
+ }
+
protected String[] getMappings() {
return new String[] { "UserGroup.hbm.xml"};
}
14 years, 2 months
Hibernate SVN: r20674 - core/branches/Branch_3_3_2_GA_CP/parent.
by hibernate-commits@lists.jboss.org
Author: stliu
Date: 2010-09-20 23:16:47 -0400 (Mon, 20 Sep 2010)
New Revision: 20674
Modified:
core/branches/Branch_3_3_2_GA_CP/parent/pom.xml
Log:
JBPAPP-4999 update db profiles
Modified: core/branches/Branch_3_3_2_GA_CP/parent/pom.xml
===================================================================
--- core/branches/Branch_3_3_2_GA_CP/parent/pom.xml 2010-09-20 17:42:39 UTC (rev 20673)
+++ core/branches/Branch_3_3_2_GA_CP/parent/pom.xml 2010-09-21 03:16:47 UTC (rev 20674)
@@ -732,7 +732,7 @@
<properties>
<db.dialect>org.hibernate.dialect.SybaseASE15Dialect</db.dialect>
<jdbc.driver>com.sybase.jdbc4.jdbc.SybDriver</jdbc.driver>
- <jdbc.url>jdbc:sybase:Tds:dev77.qa.atl2.redhat.com:5000/hibbr330?DYNAMIC_PREPARE=true</jdbc.url>
+ <jdbc.url>jdbc:sybase:Tds:dev77.qa.atl2.redhat.com:5000/hibbr330?SQLINITSTRING=set quoted_identifier on</jdbc.url>
<jdbc.user>hibbr330</jdbc.user>
<jdbc.pass>hibbr330</jdbc.pass>
<jdbc.isolation />
@@ -751,7 +751,7 @@
<properties>
<db.dialect>org.hibernate.dialect.SybaseASE15Dialect</db.dialect>
<jdbc.driver>com.sybase.jdbc4.jdbc.SybDriver</jdbc.driver>
- <jdbc.url>jdbc:sybase:Tds:vmg09.mw.lab.eng.bos.redhat.com:5000/hibbr330?DYNAMIC_PREPARE=true</jdbc.url>
+ <jdbc.url>jdbc:sybase:Tds:vmg09.mw.lab.eng.bos.redhat.com:5000/hibbr330?SQLINITSTRING=set quoted_identifier on</jdbc.url>
<jdbc.user>hibbr330</jdbc.user>
<jdbc.pass>hibbr330</jdbc.pass>
<jdbc.isolation />
14 years, 2 months
Hibernate SVN: r20673 - in core/trunk: core/src/main/java/org/hibernate/dialect and 4 other directories.
by hibernate-commits@lists.jboss.org
Author: gbadner
Date: 2010-09-20 13:42:39 -0400 (Mon, 20 Sep 2010)
New Revision: 20673
Added:
core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/ResultVariableRefNode.java
Modified:
core/trunk/core/src/main/antlr/hql-sql.g
core/trunk/core/src/main/antlr/sql-gen.g
core/trunk/core/src/main/java/org/hibernate/dialect/Dialect.java
core/trunk/core/src/main/java/org/hibernate/hql/ast/HqlSqlWalker.java
core/trunk/core/src/main/java/org/hibernate/hql/ast/SqlASTFactory.java
core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/AbstractSelectExpression.java
core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/ConstructorNode.java
core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/MapEntryNode.java
core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/QueryNode.java
core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/SelectClause.java
core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/SelectExpression.java
core/trunk/testsuite/src/test/java/org/hibernate/test/hql/ASTParserLoadingOrderByTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/hql/ASTParserLoadingTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/hql/Animal.hbm.xml
core/trunk/testsuite/src/test/java/org/hibernate/test/hql/HQLTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/hql/Mammal.java
core/trunk/testsuite/src/test/java/org/hibernate/test/hql/Zoo.java
core/trunk/testsuite/src/test/java/org/hibernate/test/jpa/ql/JPAQLComplianceTest.java
Log:
HHH-892 : HQL parser does not resolve alias in ORDER BY clause
Modified: core/trunk/core/src/main/antlr/hql-sql.g
===================================================================
--- core/trunk/core/src/main/antlr/hql-sql.g 2010-09-20 15:18:39 UTC (rev 20672)
+++ core/trunk/core/src/main/antlr/hql-sql.g 2010-09-20 17:42:39 UTC (rev 20673)
@@ -50,6 +50,8 @@
METHOD_NAME; // An IDENT that is a method name.
NAMED_PARAM; // A named parameter (:foo).
BOGUS; // Used for error state detection, etc.
+ RESULT_VARIABLE_REF; // An IDENT that refers to result variable
+ // (i.e, an alias for a select expression)
}
// -- Declarations --
@@ -211,8 +213,15 @@
protected void lookupAlias(AST ident) throws SemanticException { }
- protected void setAlias(AST selectExpr, AST ident) { }
+ protected void setAlias(AST selectExpr, AST ident) { }
+ protected boolean isOrderExpressionResultVariableRef(AST ident) throws SemanticException {
+ return false;
+ }
+
+ protected void handleResultVariableRef(AST resultVariableRef) throws SemanticException {
+ }
+
protected AST lookupProperty(AST dot,boolean root,boolean inSelect) throws SemanticException {
return dot;
}
@@ -334,9 +343,22 @@
;
orderExprs
- : expr ( ASCENDING | DESCENDING )? (orderExprs)?
+ : orderExpr ( ASCENDING | DESCENDING )? (orderExprs)?
;
+orderExpr
+ : { isOrderExpressionResultVariableRef( _t ) }? resultVariableRef
+ | expr
+ ;
+
+resultVariableRef!
+ : i:identifier {
+ // Create a RESULT_VARIABLE_REF node instead of an IDENT node.
+ #resultVariableRef = #([RESULT_VARIABLE_REF, i.getText()]);
+ handleResultVariableRef(#resultVariableRef);
+ }
+ ;
+
groupClause
: #(GROUP { handleClauseStart( GROUP ); } (expr)+ ( #(HAVING logicalExpr) )? )
;
@@ -358,7 +380,7 @@
aliasedSelectExpr!
: #(AS se:selectExpr i:identifier) {
- setAlias(#se,#i);
+ setAlias(#se,#i);
#aliasedSelectExpr = #se;
}
;
@@ -723,4 +745,4 @@
numericInteger
: NUM_INT
- ;
\ No newline at end of file
+ ;
Modified: core/trunk/core/src/main/antlr/sql-gen.g
===================================================================
--- core/trunk/core/src/main/antlr/sql-gen.g 2010-09-20 15:18:39 UTC (rev 20672)
+++ core/trunk/core/src/main/antlr/sql-gen.g 2010-09-20 17:42:39 UTC (rev 20673)
@@ -432,6 +432,7 @@
: #(r:DOT . .) { out(r); }
| i:ALIAS_REF { out(i); }
| j:INDEX_OP { out(j); }
+ | v:RESULT_VARIABLE_REF { out(v); }
;
sqlToken
Modified: core/trunk/core/src/main/java/org/hibernate/dialect/Dialect.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/Dialect.java 2010-09-20 15:18:39 UTC (rev 20672)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/Dialect.java 2010-09-20 17:42:39 UTC (rev 20673)
@@ -1724,6 +1724,20 @@
}
/**
+ * Does this dialect require that references to result variables
+ * (i.e, select expresssion aliases) in an ORDER BY clause be
+ * replaced by column positions (1-origin) as defined
+ * by the select clause?
+
+ * @return true if result variable references in the ORDER BY
+ * clause should be replaced by column positions;
+ * false otherwise.
+ */
+ public boolean replaceResultVariableInOrderByClauseWithPosition() {
+ return false;
+ }
+
+ /**
* Does this dialect require that parameters appearing in the <tt>SELECT</tt> clause be wrapped in <tt>cast()</tt>
* calls to tell the db parser the expected type.
*
Modified: core/trunk/core/src/main/java/org/hibernate/hql/ast/HqlSqlWalker.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/hql/ast/HqlSqlWalker.java 2010-09-20 15:18:39 UTC (rev 20672)
+++ core/trunk/core/src/main/java/org/hibernate/hql/ast/HqlSqlWalker.java 2010-09-20 17:42:39 UTC (rev 20673)
@@ -66,6 +66,7 @@
import org.hibernate.hql.ast.tree.QueryNode;
import org.hibernate.hql.ast.tree.ResolvableNode;
import org.hibernate.hql.ast.tree.RestrictableStatement;
+import org.hibernate.hql.ast.tree.ResultVariableRefNode;
import org.hibernate.hql.ast.tree.SelectClause;
import org.hibernate.hql.ast.tree.SelectExpression;
import org.hibernate.hql.ast.tree.UpdateStatement;
@@ -132,6 +133,12 @@
private FromClause currentFromClause = null;
private SelectClause selectClause;
+ /**
+ * Maps each top-level result variable to its SelectExpression;
+ * (excludes result variables defined in subqueries)
+ **/
+ private Map<String, SelectExpression> selectExpressionsByResultVariable = new HashMap();
+
private Set querySpaces = new HashSet();
private int parameterCount;
@@ -991,8 +998,35 @@
protected void setAlias(AST selectExpr, AST ident) {
((SelectExpression) selectExpr).setAlias(ident.getText());
+ // only put the alias (i.e., result variable) in selectExpressionsByResultVariable
+ // if is not defined in a subquery.
+ if ( ! isSubQuery() ) {
+ selectExpressionsByResultVariable.put( ident.getText(), ( SelectExpression ) selectExpr );
+ }
}
+ protected boolean isOrderExpressionResultVariableRef(AST orderExpressionNode) throws SemanticException {
+ // ORDER BY is not supported in a subquery
+ // TODO: should an exception be thrown if an ORDER BY is in a subquery?
+ if ( ! isSubQuery() &&
+ orderExpressionNode.getType() == IDENT &&
+ selectExpressionsByResultVariable.containsKey( orderExpressionNode.getText() ) ) {
+ return true;
+ }
+ return false;
+ }
+
+ protected void handleResultVariableRef(AST resultVariableRef) throws SemanticException {
+ if ( isSubQuery() ) {
+ throw new SemanticException(
+ "References to result variables in subqueries are not supported."
+ );
+ }
+ ( ( ResultVariableRefNode ) resultVariableRef ).setSelectExpression(
+ selectExpressionsByResultVariable.get( resultVariableRef.getText() )
+ );
+ }
+
/**
* Returns the locations of all occurrences of the named parameter.
*/
Modified: core/trunk/core/src/main/java/org/hibernate/hql/ast/SqlASTFactory.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/hql/ast/SqlASTFactory.java 2010-09-20 15:18:39 UTC (rev 20672)
+++ core/trunk/core/src/main/java/org/hibernate/hql/ast/SqlASTFactory.java 2010-09-20 17:42:39 UTC (rev 20673)
@@ -51,6 +51,7 @@
import org.hibernate.hql.ast.tree.OrderByClause;
import org.hibernate.hql.ast.tree.ParameterNode;
import org.hibernate.hql.ast.tree.QueryNode;
+import org.hibernate.hql.ast.tree.ResultVariableRefNode;
import org.hibernate.hql.ast.tree.SelectClause;
import org.hibernate.hql.ast.tree.SelectExpressionImpl;
import org.hibernate.hql.ast.tree.SqlFragment;
@@ -124,6 +125,8 @@
case ALIAS_REF:
case IDENT:
return IdentNode.class;
+ case RESULT_VARIABLE_REF:
+ return ResultVariableRefNode.class;
case SQL_TOKEN:
return SqlFragment.class;
case METHOD_CALL:
Modified: core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/AbstractSelectExpression.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/AbstractSelectExpression.java 2010-09-20 15:18:39 UTC (rev 20672)
+++ core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/AbstractSelectExpression.java 2010-09-20 17:42:39 UTC (rev 20673)
@@ -36,6 +36,7 @@
public abstract class AbstractSelectExpression extends HqlSqlWalkerNode implements SelectExpression {
private String alias;
+ private int scalarColumnIndex = -1;
public final void setAlias(String alias) {
this.alias = alias;
@@ -63,4 +64,13 @@
Type type = getDataType();
return type != null && !type.isAssociationType(); // Moved here from SelectClause [jsd]
}
+
+ public void setScalarColumn(int i) throws SemanticException {
+ this.scalarColumnIndex = i;
+ setScalarColumnText( i );
+ }
+
+ public int getScalarColumnIndex() {
+ return scalarColumnIndex;
+ }
}
Modified: core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/ConstructorNode.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/ConstructorNode.java 2010-09-20 15:18:39 UTC (rev 20672)
+++ core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/ConstructorNode.java 2010-09-20 17:42:39 UTC (rev 20673)
@@ -51,6 +51,7 @@
private Type[] constructorArgumentTypes;
private boolean isMap;
private boolean isList;
+ private int scalarColumnIndex = -1;
public ResultTransformer getResultTransformer() {
if ( constructor != null ) {
@@ -92,6 +93,19 @@
return aliases;
}
+ public void setScalarColumn(int i) throws SemanticException {
+ SelectExpression[] selectExpressions = collectSelectExpressions();
+ // Invoke setScalarColumnText on each constructor argument.
+ for ( int j = 0; j < selectExpressions.length; j++ ) {
+ SelectExpression selectExpression = selectExpressions[j];
+ selectExpression.setScalarColumn( j );
+ }
+ }
+
+ public int getScalarColumnIndex() {
+ return scalarColumnIndex;
+ }
+
public void setScalarColumnText(int i) throws SemanticException {
SelectExpression[] selectExpressions = collectSelectExpressions();
// Invoke setScalarColumnText on each constructor argument.
Modified: core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/MapEntryNode.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/MapEntryNode.java 2010-09-20 15:18:39 UTC (rev 20672)
+++ core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/MapEntryNode.java 2010-09-20 17:42:39 UTC (rev 20673)
@@ -60,6 +60,8 @@
}
}
+ private int scalarColumnIndex = -1;
+
protected String expressionDescription() {
return "entry(*)";
}
@@ -190,6 +192,14 @@
super.setText( s );
}
+ public void setScalarColumn(int i) throws SemanticException {
+ this.scalarColumnIndex = i;
+ }
+
+ public int getScalarColumnIndex() {
+ return scalarColumnIndex;
+ }
+
public void setScalarColumnText(int i) throws SemanticException {
}
Modified: core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/QueryNode.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/QueryNode.java 2010-09-20 15:18:39 UTC (rev 20672)
+++ core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/QueryNode.java 2010-09-20 17:42:39 UTC (rev 20673)
@@ -46,6 +46,7 @@
private static final Logger log = LoggerFactory.getLogger( QueryNode.class );
private OrderByClause orderByClause;
+ private int scalarColumnIndex = -1;
/**
* @see Statement#getStatementType()
@@ -145,6 +146,15 @@
this.alias = alias;
}
+ public void setScalarColumn(int i) throws SemanticException {
+ scalarColumnIndex = i;
+ setScalarColumnText( i );
+ }
+
+ public int getScalarColumnIndex() {
+ return scalarColumnIndex;
+ }
+
public void setScalarColumnText(int i) throws SemanticException {
ColumnHelper.generateSingleScalarColumn( this, i );
}
Added: core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/ResultVariableRefNode.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/ResultVariableRefNode.java (rev 0)
+++ core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/ResultVariableRefNode.java 2010-09-20 17:42:39 UTC (rev 20673)
@@ -0,0 +1,93 @@
+/*
+ * 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.hql.ast.tree;
+
+import antlr.SemanticException;
+
+import org.hibernate.engine.SessionFactoryImplementor;
+import org.hibernate.util.StringHelper;
+
+/**
+ * Represents a reference to a result_variable as defined in the JPA 2 spec.
+ * For example:
+ * <code>
+ * select v as value from tab1 order by value
+ * </code>
+ * <p/>
+ * "value" used in the order by clause is a reference to the
+ * result_variable, "value", defined in the select clause.
+ *
+ * @author Gail Badner
+ */
+public class ResultVariableRefNode extends HqlSqlWalkerNode {
+ private SelectExpression selectExpression;
+
+ /**
+ * Set the select expression that defines the result variable.
+ *
+ * @param selectExpression the select expression;
+ * selectExpression.getAlias() must be non-null
+ * @throws SemanticException if selectExpression or
+ * selectExpression.getAlias() is null.
+ */
+ public void setSelectExpression(SelectExpression selectExpression) throws SemanticException {
+ if ( selectExpression == null || selectExpression.getAlias() == null ) {
+ throw new SemanticException( "A ResultVariableRefNode must refer to a non-null alias." );
+ }
+ this.selectExpression = selectExpression;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String getRenderText(SessionFactoryImplementor sessionFactory) {
+ int scalarColumnIndex = selectExpression.getScalarColumnIndex();
+ if ( scalarColumnIndex < 0 ) {
+ throw new IllegalStateException(
+ "selectExpression.getScalarColumnIndex() must be >= 0; actual = " + scalarColumnIndex
+ );
+ }
+ return sessionFactory.getDialect().replaceResultVariableInOrderByClauseWithPosition() ?
+ getColumnPositionsString( scalarColumnIndex ) :
+ getColumnNamesString( scalarColumnIndex );
+
+ }
+
+ private String getColumnPositionsString(int scalarColumnIndex ) {
+ int startPosition = getWalker().getSelectClause().getColumnNamesStartPosition( scalarColumnIndex );
+ StringBuffer buf = new StringBuffer();
+ int nColumns = getWalker().getSelectClause().getColumnNames()[ scalarColumnIndex ].length;
+ for ( int i = startPosition; i < startPosition + nColumns; i++ ) {
+ if ( i > startPosition ) {
+ buf.append( ", " );
+ }
+ buf.append( i );
+ }
+ return buf.toString();
+ }
+
+ private String getColumnNamesString(int scalarColumnIndex) {
+ return StringHelper.join( ", ", getWalker().getSelectClause().getColumnNames()[ scalarColumnIndex ] );
+ }
+}
Modified: core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/SelectClause.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/SelectClause.java 2010-09-20 15:18:39 UTC (rev 20672)
+++ core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/SelectClause.java 2010-09-20 17:42:39 UTC (rev 20673)
@@ -25,6 +25,7 @@
package org.hibernate.hql.ast.tree;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -54,6 +55,7 @@
private String[][] columnNames;
private List collectionFromElements;
private String[] aliases;
+ private int[] columnNamesStartPositions;
// Currently we can only have one...
private AggregatedSelectExpression aggregatedSelectExpression;
@@ -253,8 +255,18 @@
// todo: we should really just collect these from the various SelectExpressions, rather than regenerating here
columnNames = getSessionFactoryHelper().generateColumnNames( queryReturnTypes );
+ columnNamesStartPositions = new int[ columnNames.length ];
+ int startPosition = 1;
+ for ( int i = 0 ; i < columnNames.length ; i ++ ) {
+ columnNamesStartPositions[ i ] = startPosition;
+ startPosition += columnNames[ i ].length;
+ }
}
+ public int getColumnNamesStartPosition(int i) {
+ return columnNamesStartPositions[ i ];
+ }
+
/**
* Prepares a derived (i.e., not explicitly defined in the query) select clause.
*
@@ -356,7 +368,7 @@
if ( !currentFromClause.isSubQuery() ) {
for ( int i = 0; i < se.length; i++ ) {
SelectExpression expr = se[i];
- expr.setScalarColumnText( i ); // Create SQL_TOKEN nodes for the columns.
+ expr.setScalarColumn( i ); // Create SQL_TOKEN nodes for the columns.
}
}
}
Modified: core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/SelectExpression.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/SelectExpression.java 2010-09-20 15:18:39 UTC (rev 20672)
+++ core/trunk/core/src/main/java/org/hibernate/hql/ast/tree/SelectExpression.java 2010-09-20 17:42:39 UTC (rev 20673)
@@ -50,6 +50,21 @@
void setScalarColumnText(int i) throws SemanticException;
/**
+ * Sets the index and text for select expression in the projection list.
+ *
+ * @param i The index of the select expression in the projection list.
+ * @throws SemanticException
+ */
+ void setScalarColumn(int i) throws SemanticException;
+
+ /**
+ * Gets index of the select expression in the projection list.
+ *
+ * @returns The index of the select expression in the projection list.
+ */
+ int getScalarColumnIndex();
+
+ /**
* Returns the FROM element that this expression refers to.
*
* @return The FROM element.
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/hql/ASTParserLoadingOrderByTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/hql/ASTParserLoadingOrderByTest.java 2010-09-20 15:18:39 UTC (rev 20672)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/hql/ASTParserLoadingOrderByTest.java 2010-09-20 17:42:39 UTC (rev 20673)
@@ -100,6 +100,10 @@
private Zoo zoo4;
Set<Zoo> zoosWithSameName;
Set<Zoo> zoosWithSameAddress;
+ Mammal zoo1Mammal1;
+ Mammal zoo1Mammal2;
+ Human zoo2Director1;
+ Human zoo2Director2;
public ASTParserLoadingOrderByTest(String name) {
super( name );
@@ -138,6 +142,14 @@
address1.setStateProvince( stateProvince );
address1.setCountry( "USA" );
zoo1.setAddress( address1 );
+ zoo1Mammal1 = new Mammal();
+ zoo1Mammal1.setDescription( "zoo1Mammal1" );
+ zoo1Mammal1.setZoo( zoo1 );
+ zoo1.getMammals().put( "type1", zoo1Mammal1);
+ zoo1Mammal2 = new Mammal();
+ zoo1Mammal2.setDescription( "zoo1Mammal2" );
+ zoo1Mammal2.setZoo( zoo1 );
+ zoo1.getMammals().put( "type1", zoo1Mammal2);
zoo2 = new Zoo();
zoo2.setName( "A Zoo" );
@@ -147,8 +159,13 @@
address2.setStateProvince( stateProvince );
address2.setCountry( "USA" );
zoo2.setAddress( address2 );
+ zoo2Director1 = new Human();
+ zoo2Director1.setName( new Name( "Duh", 'A', "Man" ) );
+ zoo2Director2 = new Human();
+ zoo2Director2.setName( new Name( "Fat", 'A', "Cat" ) );
+ zoo2.getDirectors().put( "Head Honcho", zoo2Director1 );
+ zoo2.getDirectors().put( "Asst. Head Honcho", zoo2Director2 );
-
zoo3 = new Zoo();
zoo3.setName( "Zoo" );
Address address3 = new Address();
@@ -170,7 +187,11 @@
Session s = openSession();
Transaction t = s.beginTransaction();
s.save( stateProvince );
+ s.save( zoo1Mammal1 );
+ s.save( zoo1Mammal2 );
s.save( zoo1 );
+ s.save( zoo2Director1 );
+ s.save( zoo2Director2 );
s.save( zoo2 );
s.save( zoo3 );
s.save( zoo4 );
@@ -204,6 +225,25 @@
s.delete( zoo4 );
zoo4 = null;
}
+ if ( zoo1Mammal1 != null ) {
+ s.delete( zoo1Mammal1 );
+ zoo1Mammal1 = null;
+ }
+ if ( zoo1Mammal2 != null ) {
+ s.delete( zoo1Mammal2 );
+ zoo1Mammal2 = null;
+ }
+ if ( zoo2Director1 != null ) {
+ s.delete( zoo2Director1 );
+ zoo2Director1 = null;
+ }
+ if ( zoo2Director2 != null ) {
+ s.delete( zoo2Director2 );
+ zoo2Director2 = null;
+ }
+ if ( stateProvince != null ) {
+ s.delete( stateProvince );
+ }
t.commit();
s.close();
}
@@ -346,7 +386,7 @@
cleanupData();
}
- public void testOrderBySelectAliasRefFailureExpected() {
+ public void testOrderBySelectAliasRef() {
createData();
Session s = openSession();
@@ -492,22 +532,6 @@
t.commit();
s.close();
- s = openSession();
- t = s.beginTransaction();
- try {
- s.createQuery(
- "select z2.name as zname, z2.address as zooAddress from Zoo z2 where z2.name in ( select name as zname from Zoo order by zname ) order by zooAddress"
- ).list();
- fail( "Exception should have been thrown because subquery has ORDER BY" );
- }
- catch ( QuerySyntaxException ex ) {
- // expected
- }
- finally {
- t.rollback();
- s.close();
- }
-
cleanupData();
}
@@ -536,6 +560,143 @@
cleanupData();
}
+ public void testOrderByEntityWithFetchJoinedCollection() {
+ createData();
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ // ordered by address desc, name desc:
+ // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA
+ // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA
+ // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA
+ // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA
+ // using DESC
+ List list = s.createQuery( "from Zoo z join fetch z.mammals" ).list();
+
+ t.commit();
+ s.close();
+
+ cleanupData();
+ }
+
+ public void testOrderBySelectNewArgAliasRef() {
+ createData();
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ // ordered by name, address:
+ // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA
+ // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA
+ // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA
+ // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA
+ List list =
+ s.createQuery(
+ "select new Zoo( z.name as zname, z.address as zaddress) from Zoo z order by zname, zaddress"
+ ).list();
+ assertEquals( 4, list.size() );
+ assertEquals( zoo2, list.get( 0 ) );
+ assertEquals( zoo4, list.get( 1 ) );
+ assertEquals( zoo3, list.get( 2 ) );
+ assertEquals( zoo1, list.get( 3 ) );
+
+ // ordered by address, name:
+ // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA
+ // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA
+ // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA
+ // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA
+ list =
+ s.createQuery(
+ "select new Zoo( z.name as zname, z.address as zaddress) from Zoo z order by zaddress, zname"
+ ).list();
+ assertEquals( 4, list.size() );
+ assertEquals( zoo3, list.get( 0 ) );
+ assertEquals( zoo4, list.get( 1 ) );
+ assertEquals( zoo2, list.get( 2 ) );
+ assertEquals( zoo1, list.get( 3 ) );
+
+
+ t.commit();
+ s.close();
+
+ cleanupData();
+ }
+
+ public void testOrderBySelectNewMapArgAliasRef() {
+ createData();
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ // ordered by name, address:
+ // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA
+ // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA
+ // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA
+ // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA
+ List list =
+ s.createQuery(
+ "select new map( z.name as zname, z.address as zaddress ) from Zoo z left join z.mammals m order by zname, zaddress"
+ ).list();
+ assertEquals( 4, list.size() );
+ assertEquals( zoo2.getName(), ( ( Map ) list.get( 0 ) ).get( "zname" ) );
+ assertEquals( zoo2.getAddress(), ( ( Map ) list.get( 0 ) ).get( "zaddress" ) );
+ assertEquals( zoo4.getName(), ( ( Map ) list.get( 1 ) ).get( "zname" ) );
+ assertEquals( zoo4.getAddress(), ( ( Map ) list.get( 1 ) ).get( "zaddress" ) );
+ assertEquals( zoo3.getName(), ( ( Map ) list.get( 2 ) ).get( "zname" ) );
+ assertEquals( zoo3.getAddress(), ( ( Map ) list.get( 2 ) ).get( "zaddress" ) );
+ assertEquals( zoo1.getName(), ( ( Map ) list.get( 3 ) ).get( "zname" ) );
+ assertEquals( zoo1.getAddress(), ( ( Map ) list.get( 3 ) ).get( "zaddress" ) );
+
+ // ordered by address, name:
+ // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA
+ // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA
+ // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA
+ // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA
+ list =
+ s.createQuery(
+ "select new map( z.name as zname, z.address as zaddress ) from Zoo z left join z.mammals m order by zaddress, zname"
+ ).list();
+ assertEquals( 4, list.size() );
+ assertEquals( zoo3.getName(), ( ( Map ) list.get( 0 ) ).get( "zname" ) );
+ assertEquals( zoo3.getAddress(), ( ( Map ) list.get( 0 ) ).get( "zaddress" ) );
+ assertEquals( zoo4.getName(), ( ( Map ) list.get( 1 ) ).get( "zname" ) );
+ assertEquals( zoo4.getAddress(), ( ( Map ) list.get( 1 ) ).get( "zaddress" ) );
+ assertEquals( zoo2.getName(), ( ( Map ) list.get( 2 ) ).get( "zname" ) );
+ assertEquals( zoo2.getAddress(), ( ( Map ) list.get( 2 ) ).get( "zaddress" ) );
+ assertEquals( zoo1.getName(), ( ( Map ) list.get( 3 ) ).get( "zname" ) );
+ assertEquals( zoo1.getAddress(), ( ( Map ) list.get( 3 ) ).get( "zaddress" ) );
+ t.commit();
+ s.close();
+
+ cleanupData();
+ }
+
+ public void testOrderByAggregatedArgAliasRef() {
+ createData();
+
+ Session s = openSession();
+ Transaction t = s.beginTransaction();
+
+ // ordered by name, address:
+ // zoo2 A Zoo 1313 Mockingbird Lane, Anywhere, IL USA
+ // zoo4 Duh Zoo 1312 Mockingbird Lane, Nowhere, IL USA
+ // zoo3 Zoo 1312 Mockingbird Lane, Anywhere, IL USA
+ // zoo1 Zoo 1313 Mockingbird Lane, Anywhere, IL USA
+ List list =
+ s.createQuery(
+ "select z.name as zname, count(*) as cnt from Zoo z group by z.name order by cnt desc, zname"
+ ).list();
+ assertEquals( 3, list.size() );
+ assertEquals( zoo3.getName(), ( ( Object[] ) list.get( 0 ) )[ 0 ] );
+ assertEquals( Long.valueOf( 2 ), ( ( Object[] ) list.get( 0 ) )[ 1 ] );
+ assertEquals( zoo2.getName(), ( ( Object[] ) list.get( 1 ) )[ 0 ] );
+ assertEquals( Long.valueOf( 1 ), ( ( Object[] ) list.get( 1 ) )[ 1 ] );
+ assertEquals( zoo4.getName(), ( ( Object[] ) list.get( 2 ) )[ 0 ] );
+ assertEquals( Long.valueOf( 1 ), ( ( Object[] ) list.get( 2 ) )[ 1 ] );
+ cleanupData();
+ }
+
private void checkTestOrderByResults(List results,
Zoo zoo1,
Zoo zoo2,
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/hql/ASTParserLoadingTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/hql/ASTParserLoadingTest.java 2010-09-20 15:18:39 UTC (rev 20672)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/hql/ASTParserLoadingTest.java 2010-09-20 17:42:39 UTC (rev 20673)
@@ -2068,6 +2068,96 @@
destroyTestBaseData();
}
+ public void testJoinFetchedCollectionOfJoinedSubclass() throws Exception {
+ Mammal mammal = new Mammal();
+ mammal.setDescription( "A Zebra" );
+ Zoo zoo = new Zoo();
+ zoo.setName( "A Zoo" );
+ zoo.getMammals().put( "zebra", mammal );
+ mammal.setZoo( zoo );
+
+ Session session = openSession();
+ Transaction txn = session.beginTransaction();
+ session.save( mammal );
+ session.save( zoo );
+ txn.commit();
+
+ session = openSession();
+ txn = session.beginTransaction();
+ List results = session.createQuery( "from Zoo z join fetch z.mammals" ).list();
+ assertEquals( "Incorrect result size", 1, results.size() );
+ assertTrue( "Incorrect result return type", results.get( 0 ) instanceof Zoo );
+ Zoo zooRead = ( Zoo ) results.get( 0 );
+ assertEquals( zoo, zooRead );
+ assertTrue( Hibernate.isInitialized( zooRead.getMammals() ) );
+ Mammal mammalRead = ( Mammal ) ( ( Map ) zooRead.getMammals() ).get( "zebra" );
+ assertEquals( mammal, mammalRead );
+ session.delete( mammalRead );
+ session.delete( zooRead );
+ txn.commit();
+ session.close();
+ }
+
+ public void testJoinedCollectionOfJoinedSubclass() throws Exception {
+ Mammal mammal = new Mammal();
+ mammal.setDescription( "A Zebra" );
+ Zoo zoo = new Zoo();
+ zoo.setName( "A Zoo" );
+ zoo.getMammals().put( "zebra", mammal );
+ mammal.setZoo( zoo );
+
+ Session session = openSession();
+ Transaction txn = session.beginTransaction();
+ session.save( mammal );
+ session.save( zoo );
+ txn.commit();
+
+ session = openSession();
+ txn = session.beginTransaction();
+ List results = session.createQuery( "from Zoo z join z.mammals m" ).list();
+ assertEquals( "Incorrect result size", 1, results.size() );
+ assertTrue( "Incorrect result return type", results.get( 0 ) instanceof Object[] );
+ Object[] resultObjects = ( Object[] ) results.get( 0 );
+ Zoo zooRead = ( Zoo ) resultObjects[ 0 ];
+ Mammal mammalRead = ( Mammal ) resultObjects[ 1 ];
+ assertEquals( zoo, zooRead );
+ assertEquals( mammal, mammalRead );
+ session.delete( mammalRead );
+ session.delete( zooRead );
+ txn.commit();
+ session.close();
+ }
+
+ public void testJoinedCollectionOfJoinedSubclassProjection() throws Exception {
+ Mammal mammal = new Mammal();
+ mammal.setDescription( "A Zebra" );
+ Zoo zoo = new Zoo();
+ zoo.setName( "A Zoo" );
+ zoo.getMammals().put( "zebra", mammal );
+ mammal.setZoo( zoo );
+
+ Session session = openSession();
+ Transaction txn = session.beginTransaction();
+ session.save( mammal );
+ session.save( zoo );
+ txn.commit();
+
+ session = openSession();
+ txn = session.beginTransaction();
+ List results = session.createQuery( "select z, m from Zoo z join z.mammals m" ).list();
+ assertEquals( "Incorrect result size", 1, results.size() );
+ assertTrue( "Incorrect result return type", results.get( 0 ) instanceof Object[] );
+ Object[] resultObjects = ( Object[] ) results.get( 0 );
+ Zoo zooRead = ( Zoo ) resultObjects[ 0 ];
+ Mammal mammalRead = ( Mammal ) resultObjects[ 1 ];
+ assertEquals( zoo, zooRead );
+ assertEquals( mammal, mammalRead );
+ session.delete( mammalRead );
+ session.delete( zooRead );
+ txn.commit();
+ session.close();
+ }
+
public void testProjectionQueries() throws Exception {
createTestBaseData();
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/hql/Animal.hbm.xml
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/hql/Animal.hbm.xml 2010-09-20 15:18:39 UTC (rev 20672)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/hql/Animal.hbm.xml 2010-09-20 17:42:39 UTC (rev 20673)
@@ -112,6 +112,11 @@
<discriminator column="zooType" type="character"/>
<property name="name" type="string"/>
<property name="classification" type="org.hibernate.test.hql.ClassificationType"/>
+ <map name="directors">
+ <key column="directorZoo_id"/>
+ <index type="string" column="title"/>
+ <many-to-many class="Human"/>
+ </map>
<map name="mammals">
<key column="mammalZoo_id"/>
<index type="string" column="name"/>
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/hql/HQLTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/hql/HQLTest.java 2010-09-20 15:18:39 UTC (rev 20672)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/hql/HQLTest.java 2010-09-20 17:42:39 UTC (rev 20673)
@@ -1199,7 +1199,7 @@
IndexNode n = new IndexNode();
Exception ex = null;
try {
- n.setScalarColumnText( 0 );
+ n.setScalarColumn( 0 );
}
catch ( UnsupportedOperationException e ) {
ex = e;
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/hql/Mammal.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/hql/Mammal.java 2010-09-20 15:18:39 UTC (rev 20672)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/hql/Mammal.java 2010-09-20 17:42:39 UTC (rev 20673)
@@ -26,5 +26,32 @@
public void setBirthdate(Date birthdate) {
this.birthdate = birthdate;
}
-
+
+ @Override
+ public boolean equals(Object o) {
+ if ( this == o ) {
+ return true;
+ }
+ if ( !( o instanceof Mammal ) ) {
+ return false;
+ }
+
+ Mammal mammal = ( Mammal ) o;
+
+ if ( pregnant != mammal.pregnant ) {
+ return false;
+ }
+ if ( birthdate != null ? !birthdate.equals( mammal.birthdate ) : mammal.birthdate != null ) {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = ( pregnant ? 1 : 0 );
+ result = 31 * result + ( birthdate != null ? birthdate.hashCode() : 0 );
+ return result;
+ }
}
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/hql/Zoo.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/hql/Zoo.java 2010-09-20 15:18:39 UTC (rev 20672)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/hql/Zoo.java 2010-09-20 17:42:39 UTC (rev 20673)
@@ -1,6 +1,7 @@
//$Id: Zoo.java 10653 2006-10-26 13:38:50Z steve.ebersole(a)jboss.com $
package org.hibernate.test.hql;
+import java.util.HashMap;
import java.util.Map;
/**
@@ -10,10 +11,18 @@
private Long id;
private String name;
private Classification classification;
- private Map animals;
- private Map mammals;
+ private Map directors = new HashMap();
+ private Map animals = new HashMap();
+ private Map mammals = new HashMap();
private Address address;
+ public Zoo() {
+ }
+ public Zoo(String name, Address address) {
+ this.name = name;
+ this.address = address;
+ }
+
public Long getId() {
return id;
}
@@ -30,6 +39,14 @@
this.name = name;
}
+ public Map getDirectors() {
+ return directors;
+ }
+
+ public void setDirectors(Map directors) {
+ this.directors = directors;
+ }
+
public Map getMammals() {
return mammals;
}
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/jpa/ql/JPAQLComplianceTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/jpa/ql/JPAQLComplianceTest.java 2010-09-20 15:18:39 UTC (rev 20672)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/jpa/ql/JPAQLComplianceTest.java 2010-09-20 17:42:39 UTC (rev 20673)
@@ -52,4 +52,11 @@
s.createQuery( "select c FROM Item c WHERE c.parts IS EMPTY" ).list();
s.close();
}
+
+ public void testOrderByAlias() {
+ Session s = openSession();
+ s.createQuery( "select c.name as myname FROM Item c ORDER BY myname" ).list();
+ s.createQuery( "select p.name as name, p.stockNumber as stockNo, p.unitPrice as uPrice FROM Part p ORDER BY name, abs( p.unitPrice ), stockNo" ).list();
+ s.close();
+ }
}
14 years, 2 months
Hibernate SVN: r20672 - in validator/trunk: hibernate-validator-tck-runner and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-09-20 11:18:39 -0400 (Mon, 20 Sep 2010)
New Revision: 20672
Modified:
validator/trunk/hibernate-validator-tck-runner/pom.xml
validator/trunk/pom.xml
Log:
HV-375 updated dependencies
Modified: validator/trunk/hibernate-validator-tck-runner/pom.xml
===================================================================
--- validator/trunk/hibernate-validator-tck-runner/pom.xml 2010-09-20 14:28:54 UTC (rev 20671)
+++ validator/trunk/hibernate-validator-tck-runner/pom.xml 2010-09-20 15:18:39 UTC (rev 20672)
@@ -1,5 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
-<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/maven-v4_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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>hibernate-validator-parent</artifactId>
@@ -35,7 +37,7 @@
</dependency>
<dependency>
<groupId>org.jboss.test-harness</groupId>
- <artifactId>jboss-test-harness-jboss-as-51</artifactId>
+ <artifactId>jboss-test-harness-jboss-as-60</artifactId>
<exclusions>
<exclusion>
<groupId>org.hibernate</groupId>
@@ -43,6 +45,7 @@
</exclusion>
</exclusions>
</dependency>
+
<!--
Provided dependencies.
JAXB is needed when running on Java5. In this environment these dependencies have to be added
@@ -61,9 +64,9 @@
</dependencies>
<properties>
- <jboss.home>/opt/java/jboss-5.1.0.GA</jboss.home>
+ <jboss.home>/opt/java/jboss-6</jboss.home>
<validation.provider>org.hibernate.validator.HibernateValidator</validation.provider>
- <remote.debug />
+ <remote.debug/>
</properties>
<build>
@@ -192,7 +195,7 @@
</property>
<property>
<name>org.jboss.testharness.container.javaOpts</name>
- <value>-Xms128m -Xmx384m -XX:MaxPermSize=128m -Dorg.jboss.resolver.warning=true
+ <value>-Xms128m -Xmx512m -XX:MaxPermSize=256m -Dorg.jboss.resolver.warning=true
-Dvalidation.provider=${validation.provider} ${remote.debug}
</value>
</property>
Modified: validator/trunk/pom.xml
===================================================================
--- validator/trunk/pom.xml 2010-09-20 14:28:54 UTC (rev 20671)
+++ validator/trunk/pom.xml 2010-09-20 15:18:39 UTC (rev 20672)
@@ -96,7 +96,7 @@
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
- <version>3.5.0-Final</version>
+ <version>3.5.5-Final</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
@@ -117,12 +117,12 @@
<dependency>
<groupId>org.hibernate.jsr303.tck</groupId>
<artifactId>jsr303-tck</artifactId>
- <version>1.0.3.GA</version>
+ <version>1.0.4.GA</version>
</dependency>
<dependency>
<groupId>org.jboss.test-harness</groupId>
- <artifactId>jboss-test-harness-jboss-as-51</artifactId>
- <version>1.0.0</version>
+ <artifactId>jboss-test-harness-jboss-as-60</artifactId>
+ <version>1.1.0-CR6</version>
</dependency>
</dependencies>
</dependencyManagement>
@@ -167,11 +167,11 @@
<configuration>
<archive>
<manifestEntries>
- <Implementation-Title>${pom.artifactId}</Implementation-Title>
- <Implementation-Version>${pom.version}</Implementation-Version>
- <Implementation-Vendor>${pom.groupId}</Implementation-Vendor>
- <Implementation-Vendor-Id>${pom.groupId}</Implementation-Vendor-Id>
- <Implementation-URL>${pom.url}</Implementation-URL>
+ <Implementation-Title>${project.artifactId}</Implementation-Title>
+ <Implementation-Version>${project.version}</Implementation-Version>
+ <Implementation-Vendor>${project.groupId}</Implementation-Vendor>
+ <Implementation-Vendor-Id>${project.groupId}</Implementation-Vendor-Id>
+ <Implementation-URL>${project.url}</Implementation-URL>
<Specification-Title>Bean Validation</Specification-Title>
</manifestEntries>
</archive>
14 years, 2 months
Hibernate SVN: r20670 - beanvalidation/tck/tags.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-09-20 10:28:47 -0400 (Mon, 20 Sep 2010)
New Revision: 20670
Added:
beanvalidation/tck/tags/v1_0_4_GA/
Log:
[maven-scm] copy for tag v1_0_4_GA
Copied: beanvalidation/tck/tags/v1_0_4_GA (from rev 20669, beanvalidation/tck/trunk)
14 years, 2 months