Hibernate SVN: r14781 - in annotations/trunk/src: test/org/hibernate/test/annotations/manytomany and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2008-06-18 14:04:17 -0400 (Wed, 18 Jun 2008)
New Revision: 14781
Modified:
annotations/trunk/src/java/org/hibernate/cfg/annotations/CollectionBinder.java
annotations/trunk/src/test/org/hibernate/test/annotations/manytomany/Employee.java
Log:
ANN-625
* Added a patch in order to make it work for 'table per class hierarchy' strategy. Still not work for joined subclasses, but the problem might lie in hibernate core.
* Changed Employee class to server as test
Modified: annotations/trunk/src/java/org/hibernate/cfg/annotations/CollectionBinder.java
===================================================================
--- annotations/trunk/src/java/org/hibernate/cfg/annotations/CollectionBinder.java 2008-06-18 17:59:30 UTC (rev 14780)
+++ annotations/trunk/src/java/org/hibernate/cfg/annotations/CollectionBinder.java 2008-06-18 18:04:17 UTC (rev 14781)
@@ -77,17 +77,19 @@
import org.hibernate.mapping.Property;
import org.hibernate.mapping.Selectable;
import org.hibernate.mapping.SimpleValue;
+import org.hibernate.mapping.SingleTableSubclass;
import org.hibernate.mapping.Table;
import org.hibernate.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
- * Collection binder
+ * Base class for binding different types of collections to Hibernate configuration objects.
*
* @author inger
* @author Emmanuel Bernard
*/
+@SuppressWarnings({"unchecked", "serial"})
public abstract class CollectionBinder {
private Logger log = LoggerFactory.getLogger( CollectionBinder.class );
@@ -875,12 +877,16 @@
//TODO check whether @ManyToOne @JoinTable in @IdClass used for @OrderBy works: doh!
table = "";
}
- else if ( pc != associatedClass ) {
+
+ else if (pc == associatedClass
+ || (associatedClass instanceof SingleTableSubclass && pc
+ .getMappedClass().isAssignableFrom(
+ associatedClass.getMappedClass()))) {
+ table = "";
+ } else {
table = pc.getTable().getQuotedName() + ".";
}
- else {
- table = "";
- }
+
Iterator propertyColumns = p.getColumnIterator();
while ( propertyColumns.hasNext() ) {
Selectable column = (Selectable) propertyColumns.next();
Modified: annotations/trunk/src/test/org/hibernate/test/annotations/manytomany/Employee.java
===================================================================
--- annotations/trunk/src/test/org/hibernate/test/annotations/manytomany/Employee.java 2008-06-18 17:59:30 UTC (rev 14780)
+++ annotations/trunk/src/test/org/hibernate/test/annotations/manytomany/Employee.java 2008-06-18 18:04:17 UTC (rev 14781)
@@ -7,6 +7,8 @@
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
import javax.persistence.ManyToMany;
import javax.persistence.Column;
@@ -18,6 +20,7 @@
* @author Emmanuel Bernard
*/
@Entity
+@Inheritance(strategy = InheritanceType.JOINED)
@SuppressWarnings("serial")
public class Employee implements Serializable {
private Integer id;
16 years, 6 months
Hibernate SVN: r14780 - annotations/trunk/src/test.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2008-06-18 13:59:30 -0400 (Wed, 18 Jun 2008)
New Revision: 14780
Modified:
annotations/trunk/src/test/hibernate.properties
Log:
Changed some settings to run against mysql.
Modified: annotations/trunk/src/test/hibernate.properties
===================================================================
--- annotations/trunk/src/test/hibernate.properties 2008-06-18 17:56:27 UTC (rev 14779)
+++ annotations/trunk/src/test/hibernate.properties 2008-06-18 17:59:30 UTC (rev 14780)
@@ -32,9 +32,7 @@
hibernate.connection.driver_class org.hsqldb.jdbcDriver
hibernate.connection.username sa
hibernate.connection.password
-hibernate.connection.url jdbc:hsqldb:hsql://localhost
-hibernate.connection.url jdbc:hsqldb:test
-hibernate.connection.url jdbc:hsqldb:.
+hibernate.connection.url jdbc\:hsqldb\:.
## MySQL
@@ -43,8 +41,8 @@
#hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect
#hibernate.dialect org.hibernate.dialect.MySQLMyISAMDialect
#hibernate.connection.driver_class com.mysql.jdbc.Driver
-#hibernate.connection.url jdbc:mysql:///test
-#hibernate.connection.username emmanuel
+#hibernate.connection.url jdbc:mysql://localhost/hibernate
+#hibernate.connection.username hibernate
#hibernate.connection.password hibernate
16 years, 6 months
Hibernate SVN: r14779 - in annotations/trunk/src/java/org/hibernate/cfg: annotations and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2008-06-18 13:56:27 -0400 (Wed, 18 Jun 2008)
New Revision: 14779
Modified:
annotations/trunk/src/java/org/hibernate/cfg/FkSecondPass.java
annotations/trunk/src/java/org/hibernate/cfg/JoinedSubclassFkSecondPass.java
annotations/trunk/src/java/org/hibernate/cfg/annotations/ListBinder.java
Log:
- Documentation fixes
- Added @SuppressWarning annotation
Modified: annotations/trunk/src/java/org/hibernate/cfg/FkSecondPass.java
===================================================================
--- annotations/trunk/src/java/org/hibernate/cfg/FkSecondPass.java 2008-06-18 17:50:35 UTC (rev 14778)
+++ annotations/trunk/src/java/org/hibernate/cfg/FkSecondPass.java 2008-06-18 17:56:27 UTC (rev 14779)
@@ -13,7 +13,7 @@
protected SimpleValue value;
protected Ejb3JoinColumn[] columns;
/**
- * unique counter is needed to differenciate 2 instances of FKSecondPass
+ * unique counter is needed to differentiate 2 instances of FKSecondPass
* as they are compared.
* Fairly hacky but IBM VM sometimes returns the same hashCode for 2 different objects
* TODO is it doable to rely on the Ejb3JoinColumn names? Not sure at they could be inferred
Modified: annotations/trunk/src/java/org/hibernate/cfg/JoinedSubclassFkSecondPass.java
===================================================================
--- annotations/trunk/src/java/org/hibernate/cfg/JoinedSubclassFkSecondPass.java 2008-06-18 17:50:35 UTC (rev 14778)
+++ annotations/trunk/src/java/org/hibernate/cfg/JoinedSubclassFkSecondPass.java 2008-06-18 17:56:27 UTC (rev 14779)
@@ -11,6 +11,7 @@
/**
* @author Emmanuel Bernard
*/
+@SuppressWarnings({"serial", "unchecked"})
public class JoinedSubclassFkSecondPass extends FkSecondPass {
private JoinedSubclass entity;
private ExtendedMappings mappings;
Modified: annotations/trunk/src/java/org/hibernate/cfg/annotations/ListBinder.java
===================================================================
--- annotations/trunk/src/java/org/hibernate/cfg/annotations/ListBinder.java 2008-06-18 17:50:35 UTC (rev 14778)
+++ annotations/trunk/src/java/org/hibernate/cfg/annotations/ListBinder.java 2008-06-18 17:56:27 UTC (rev 14779)
@@ -26,11 +26,12 @@
import org.slf4j.LoggerFactory;
/**
- * Bind a list
+ * Bind a list to the underlying Hibernate configuration
*
* @author Matthew Inger
* @author Emmanuel Bernard
*/
+@SuppressWarnings({"unchecked", "serial"})
public class ListBinder extends CollectionBinder {
private Logger log = LoggerFactory.getLogger( ListBinder.class );
16 years, 6 months
Hibernate SVN: r14778 - annotations/trunk/src/test/org/hibernate/test/annotations/loader.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2008-06-18 13:50:35 -0400 (Wed, 18 Jun 2008)
New Revision: 14778
Removed:
annotations/trunk/src/test/org/hibernate/test/annotations/loader/TestCase.java
Log:
Removed this class since it seemed to be an unused duplicate of org.hibernate.test.annotations.TestCase
Deleted: annotations/trunk/src/test/org/hibernate/test/annotations/loader/TestCase.java
===================================================================
--- annotations/trunk/src/test/org/hibernate/test/annotations/loader/TestCase.java 2008-06-18 17:47:30 UTC (rev 14777)
+++ annotations/trunk/src/test/org/hibernate/test/annotations/loader/TestCase.java 2008-06-18 17:50:35 UTC (rev 14778)
@@ -1,146 +0,0 @@
-package org.hibernate.test.annotations.loader;
-import java.io.InputStream;
-
-import org.hibernate.HibernateException;
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.hibernate.cfg.AnnotationConfiguration;
-import org.hibernate.cfg.Configuration;
-import org.hibernate.cfg.Environment;
-import org.hibernate.dialect.Dialect;
-
-public abstract class TestCase extends junit.framework.TestCase {
-
- private static SessionFactory sessions;
- private static AnnotationConfiguration cfg;
- private static Dialect dialect;
- private static Class lastTestClass;
- private Session session;
-
- public TestCase() {
- super();
- }
-
- public TestCase(String x) {
- super( x );
- }
-
- protected void buildSessionFactory(Class[] classes, String[] packages, String[] xmlFiles) throws Exception {
-
- if ( getSessions() != null ) getSessions().close();
- try {
- setCfg( new AnnotationConfiguration() );
- configure( cfg );
- if ( recreateSchema() ) {
- cfg.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
- }
- for ( int i = 0; i < packages.length ; i++ ) {
- getCfg().addPackage( packages[i] );
- }
- for ( int i = 0; i < classes.length ; i++ ) {
- getCfg().addAnnotatedClass( classes[i] );
- }
- for ( int i = 0; i < xmlFiles.length ; i++ ) {
- InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( xmlFiles[i] );
- getCfg().addInputStream( is );
- }
- setDialect( Dialect.getDialect() );
- setSessions( getCfg().buildSessionFactory( /*new TestInterceptor()*/ ) );
- }
- catch (Exception e) {
- e.printStackTrace();
- throw e;
- }
- }
-
- protected void setUp() throws Exception {
- if ( getSessions() == null || lastTestClass != getClass() ) {
- buildSessionFactory( getMappings(), getAnnotatedPackages(), getXmlFiles() );
- lastTestClass = getClass();
- }
- }
-
- protected void runTest() throws Throwable {
- try {
- super.runTest();
- if ( session != null && session.isOpen() ) {
- if ( session.isConnected() ) session.connection().rollback();
- session.close();
- session = null;
- fail( "unclosed session" );
- }
- else {
- session = null;
- }
- }
- catch (Throwable e) {
- try {
- if ( session != null && session.isOpen() ) {
- if ( session.isConnected() ) session.connection().rollback();
- session.close();
- }
- }
- catch (Exception ignore) {
- }
- try {
- if ( sessions != null ) {
- sessions.close();
- sessions = null;
- }
- }
- catch (Exception ignore) {
- }
- throw e;
- }
- }
-
- public Session openSession() throws HibernateException {
- session = getSessions().openSession();
- return session;
- }
-
- protected abstract Class[] getMappings();
-
- protected String[] getAnnotatedPackages() {
- return new String[]{};
- }
-
- protected String[] getXmlFiles() {
- return new String[]{};
- }
-
- private void setSessions(SessionFactory sessions) {
- TestCase.sessions = sessions;
- }
-
- protected SessionFactory getSessions() {
- return sessions;
- }
-
- private void setDialect(Dialect dialect) {
- TestCase.dialect = dialect;
- }
-
- protected Dialect getDialect() {
- return dialect;
- }
-
- protected static void setCfg(AnnotationConfiguration cfg) {
- TestCase.cfg = cfg;
- }
-
- protected static AnnotationConfiguration getCfg() {
- return cfg;
- }
-
- protected void configure(Configuration cfg) {
- //cfg.setNamingStrategy( AlternativeNamingStrategy.INSTANCE );
- //cfg.getSessionEventListenerConfig().setFlushEventListener( new EJB3FlushEventListener() );
- //cfg.getSessionEventListenerConfig().setAutoFlushEventListener( new EJB3AutoFlushEventListener() );
- }
-
- protected boolean recreateSchema() {
- return true;
- }
-
-}
16 years, 6 months
Hibernate SVN: r14777 - in annotations/trunk/src: test/org/hibernate/test/annotations and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2008-06-18 13:47:30 -0400 (Wed, 18 Jun 2008)
New Revision: 14777
Added:
annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/
annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/A.java
annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/A_PK.java
annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/B.java
annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/C.java
annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassA.java
annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassB.java
annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassC.java
annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassD.java
annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/D.java
annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/D_PK.java
annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/FkCircularityTest.java
Modified:
annotations/trunk/src/java/org/hibernate/cfg/AnnotationConfiguration.java
Log:
ANN-722 / ANN-730
* Added test cases attached to the Jira issues
* Reimplemented processFkSecondPassInOrder() in AnnotationConfiguration using a recursive algorithm for ordering FKSecondPass instances
Modified: annotations/trunk/src/java/org/hibernate/cfg/AnnotationConfiguration.java
===================================================================
--- annotations/trunk/src/java/org/hibernate/cfg/AnnotationConfiguration.java 2008-06-18 14:46:01 UTC (rev 14776)
+++ annotations/trunk/src/java/org/hibernate/cfg/AnnotationConfiguration.java 2008-06-18 17:47:30 UTC (rev 14777)
@@ -9,7 +9,6 @@
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
@@ -18,9 +17,7 @@
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.Set;
-import java.util.SortedSet;
import java.util.StringTokenizer;
-import java.util.TreeSet;
import javax.persistence.Entity;
import javax.persistence.MappedSuperclass;
@@ -57,9 +54,10 @@
/**
* Similar to the {@link Configuration} object but handles EJB3 and Hibernate
- * specific annotations as a metadata facility
+ * specific annotations as a metadata facility.
*
* @author Emmanuel Bernard
+ * @author Hardy Ferentschik
*/
@SuppressWarnings({"unchecked", "serial"})
public class AnnotationConfiguration extends Configuration {
@@ -106,7 +104,7 @@
protected List<XClass> orderAndFillHierarchy(List<XClass> original) {
//TODO remove embeddable
List<XClass> copy = new ArrayList<XClass>( original );
- //for each class, copy all the relevent hierarchy
+ //for each class, copy all the relevant hierarchy
for (XClass clazz : original) {
XClass superClass = clazz.getSuperclass();
while ( superClass != null && !reflectionManager.equals( superClass, Object.class ) && !copy.contains( superClass ) ) {
@@ -384,36 +382,89 @@
}
}
+ /**
+ * Processes FKSecondPass instances trying to resolve any
+ * graph circularity (ie PK made of a many to one linking to
+ * an entity having a PK made of a ManyToOne ...).
+ */
private void processFkSecondPassInOrder() {
log.debug( "processing fk mappings (*ToOne and JoinedSubclass)" );
- Iterator iter = secondPasses.iterator();
- /* We need to process FKSecond pass trying to resolve any
- * graph circularity (ie PK made of a many to one linking to
- * an entity having a PK made of a ManyToOne ...
+ List<FkSecondPass> fkSecondPasses = getFKSecondPassesOnly();
+
+ if (fkSecondPasses.size() == 0) {
+ return; // nothing to do here
+ }
+
+ // split FkSecondPass instances into primary key and non primary key FKs.
+ // While doing so build a map of class names to FkSecondPass instances depending on this class.
+ Map<String, Set<FkSecondPass>> isADependencyOf = new HashMap<String, Set<FkSecondPass>>();
+ List endOfQueueFkSecondPasses = new ArrayList( fkSecondPasses.size() );
+ for (FkSecondPass sp : fkSecondPasses) {
+ if ( sp.isInPrimaryKey() ) {
+ String referenceEntityName = sp.getReferencedEntityName();
+ PersistentClass classMapping = getClassMapping( referenceEntityName );
+ String dependentTable = classMapping.getTable().getQuotedName();
+ if ( !isADependencyOf.containsKey( dependentTable ) ) {
+ isADependencyOf.put( dependentTable, new HashSet<FkSecondPass>() );
+ }
+ isADependencyOf.get( dependentTable ).add( sp );
+ }
+ else {
+ endOfQueueFkSecondPasses.add( sp );
+ }
+ }
+
+ // using the isADependencyOf map we order the FkSecondPass recursively instances into the right order for processing
+ List<FkSecondPass> orderedFkSecondPasses = new ArrayList( fkSecondPasses.size() );
+ for (String tableName : isADependencyOf.keySet()) {
+ buildRecursiveOrderedFkSecondPasses(orderedFkSecondPasses, isADependencyOf, tableName, tableName);
+ }
+
+ // process the ordered FkSecondPasses
+ for ( FkSecondPass sp : orderedFkSecondPasses ) {
+ sp.doSecondPass( classes );
+ }
+
+ processEndOfQueue(endOfQueueFkSecondPasses);
+ }
+
+ private void processEndOfQueue(List endOfQueueFkSecondPasses) {
+ /*
+ * If a second pass raises a recoverableException, queue it for next round
+ * stop of no pass has to be processed or if the number of pass to processes
+ * does not diminish between two rounds.
+ * If some failing pass remain, raise the original exception
*/
- SortedSet<FkSecondPass> fkSecondPasses = new TreeSet<FkSecondPass>(
- new Comparator<FkSecondPass>() {
- //The comparator implementation has to respect the compare=0 => equals() = true for sets
- public int compare(FkSecondPass f1, FkSecondPass f2) {
- int compare = f1.getValue().getTable().getQuotedName().compareTo(
- f2.getValue().getTable().getQuotedName()
- );
- if ( compare == 0 ) {
- //same table, we still need to differenciate true equality
- if ( f1.hashCode() < f2.hashCode() ) {
- compare = -1;
- }
- else if ( f1.hashCode() == f2.hashCode() ) {
- compare = 0;
- }
- else {
- compare = 1;
- }
- }
- return compare;
- }
+ boolean stopProcess = false;
+ RuntimeException originalException = null;
+ while ( ! stopProcess ) {
+ List failingSecondPasses = new ArrayList();
+ Iterator it = endOfQueueFkSecondPasses.listIterator();
+ while ( it.hasNext() ) {
+ final SecondPass pass = (SecondPass) it.next();
+ try {
+ pass.doSecondPass( classes );
}
- );
+ catch (RecoverableException e) {
+ failingSecondPasses.add( pass );
+ if (originalException == null) originalException = (RuntimeException) e.getCause();
+ }
+ }
+ stopProcess = failingSecondPasses.size() == 0 || failingSecondPasses.size() == endOfQueueFkSecondPasses.size();
+ endOfQueueFkSecondPasses = failingSecondPasses;
+ }
+ if (endOfQueueFkSecondPasses.size() > 0) {
+ throw originalException;
+ }
+ }
+
+ /**
+ * @return Returns a list of all <code>secondPasses</code> instances which are a instance of
+ * <code>FkSecondPass</code>.
+ */
+ private List<FkSecondPass> getFKSecondPassesOnly() {
+ Iterator iter = secondPasses.iterator();
+ List<FkSecondPass> fkSecondPasses = new ArrayList<FkSecondPass>(secondPasses.size());
while ( iter.hasNext() ) {
SecondPass sp = (SecondPass) iter.next();
//do the second pass of fk before the others and remove them
@@ -422,90 +473,45 @@
iter.remove();
}
}
- if ( fkSecondPasses.size() > 0 ) {
- Map<String, Set<String>> isADependencyOf = new HashMap<String, Set<String>>();
- List orderedFkSecondPasses = new ArrayList( fkSecondPasses.size() );
- List endOfQueueFkSecondPasses = new ArrayList( fkSecondPasses.size() );
- List orderedTable = new ArrayList( fkSecondPasses.size() );
- Iterator it = fkSecondPasses.iterator();
- while ( it.hasNext() ) {
- FkSecondPass sp = (FkSecondPass) it.next();
- String referenceEntityName = sp.getReferencedEntityName();
- PersistentClass classMapping = getClassMapping( referenceEntityName );
- if ( sp.isInPrimaryKey() ) {
- String dependentTable = classMapping.getTable().getQuotedName();
- if ( !isADependencyOf.containsKey( dependentTable ) ) {
- isADependencyOf.put( dependentTable, new HashSet<String>() );
- }
- String table = sp.getValue().getTable().getQuotedName();
- isADependencyOf.get( dependentTable ).add( table );
- int beAfter = orderedTable.indexOf( dependentTable );
- int beBefore = orderedFkSecondPasses.size();
- Set<String> dependencies = isADependencyOf.get( table );
- if ( dependencies != null ) {
- for (String tableDep : dependencies) {
- //for each declared dependency take the lowest index
- int index = orderedTable.indexOf( tableDep );
- //index = -1 when we have a self dependency
- beBefore = index != -1 && index < beBefore ? index : beBefore;
- }
- }
- int currentIndex = orderedTable.indexOf( table );
- if ( beBefore < beAfter ||
- ( currentIndex != -1 && ( currentIndex < beAfter || currentIndex > beBefore ) )
- ) {
- StringBuilder sb = new StringBuilder(
- "Foreign key circularity dependency involving the following tables: "
- );
- //TODO deduplicate tables
- sb.append( table );
- if ( beAfter > -1 ) sb.append( ", " ).append( dependentTable );
- if ( beBefore < orderedFkSecondPasses.size() ) {
- sb.append( ", " ).append( orderedTable.get( beBefore ) );
- }
- throw new AnnotationException( sb.toString() );
- }
- currentIndex = currentIndex == -1 ? beBefore : currentIndex;
- orderedTable.add( currentIndex, table );
- orderedFkSecondPasses.add( currentIndex, sp );
- }
- else {
- endOfQueueFkSecondPasses.add( sp );
- }
- }
- it = orderedFkSecondPasses.listIterator();
- while ( it.hasNext() ) {
- ( (SecondPass) it.next() ).doSecondPass( classes );
- }
+ return fkSecondPasses;
+ }
- /*
- * If a second pass raises a recoverableException, queue it for next round
- * stop of no pass has to be processed or if the number of pass to processes
- * does not diminish between two rounds.
- * If some failing pass remain, raise the original exception
- */
- boolean stopProcess = false;
- RuntimeException originalException = null;
- while ( ! stopProcess ) {
- List failingSecondPasses = new ArrayList();
- it = endOfQueueFkSecondPasses.listIterator();
- while ( it.hasNext() ) {
- final SecondPass pass = (SecondPass) it.next();
- try {
- pass.doSecondPass( classes );
- }
- catch (RecoverableException e) {
- failingSecondPasses.add( pass );
- if (originalException == null) originalException = (RuntimeException) e.getCause();
- }
- }
- stopProcess = failingSecondPasses.size() == 0 || failingSecondPasses.size() == endOfQueueFkSecondPasses.size();
- endOfQueueFkSecondPasses = failingSecondPasses;
+ /**
+ * Recursively builds a list of FkSecondPass instances ready to be processed in this order.
+ * Checking all dependencies recursively seems quite expensive, but the original code just relied
+ * on some sort of table name sorting which failed in certain circumstances.
+ *
+ * @param orderedFkSecondPasses The list containing the <code>FkSecondPass<code> instances ready
+ * for processing.
+ * @param isADependencyOf Our lookup data structure to determine dependencies between tables
+ * @param startTable Table name to start recursive algorithm.
+ * @param currentTable The current table name used to check for 'new' dependencies.
+ *
+ * @see ANN-722 ANN-730
+ */
+ private void buildRecursiveOrderedFkSecondPasses(
+ List orderedFkSecondPasses,
+ Map<String, Set<FkSecondPass>> isADependencyOf, String startTable, String currentTable) {
+
+ Set<FkSecondPass> dependencies = isADependencyOf.get(currentTable);
+
+ // bottom out
+ if (dependencies == null || dependencies.size() == 0) {
+ return;
+ }
+
+ for (FkSecondPass sp : dependencies) {
+ String dependentTable = sp.getValue().getTable().getQuotedName();
+ if (dependentTable.compareTo(startTable) == 0) {
+ StringBuilder sb = new StringBuilder(
+ "Foreign key circularity dependency involving the following tables: ");
+ throw new AnnotationException(sb.toString());
}
- if (endOfQueueFkSecondPasses.size() > 0) {
- throw originalException;
+ buildRecursiveOrderedFkSecondPasses(orderedFkSecondPasses, isADependencyOf, startTable, dependentTable);
+ if (!orderedFkSecondPasses.contains(sp)) {
+ orderedFkSecondPasses.add(0, sp);
}
- }
+ }
}
private void processArtifactsOfType(String artifact) {
Added: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/A.java
===================================================================
--- annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/A.java (rev 0)
+++ annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/A.java 2008-06-18 17:47:30 UTC (rev 14777)
@@ -0,0 +1,25 @@
+// $Id:$
+package org.hibernate.test.annotations.fkcircularity;
+
+import javax.persistence.EmbeddedId;
+import javax.persistence.Entity;
+
+/**
+ * Test entities ANN-722.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@Entity
+public class A {
+ private A_PK id;
+
+ @EmbeddedId
+ public A_PK getId() {
+ return id;
+ }
+
+ public void setId(A_PK id) {
+ this.id = id;
+ }
+}
Property changes on: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/A.java
___________________________________________________________________
Name: svn:keywords
+ Id
Added: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/A_PK.java
===================================================================
--- annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/A_PK.java (rev 0)
+++ annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/A_PK.java 2008-06-18 17:47:30 UTC (rev 14777)
@@ -0,0 +1,26 @@
+// $Id:$
+package org.hibernate.test.annotations.fkcircularity;
+
+import java.io.Serializable;
+
+import javax.persistence.ManyToOne;
+
+/**
+ * Test entities ANN-722.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@SuppressWarnings("serial")
+public class A_PK implements Serializable {
+ public D d;
+
+ @ManyToOne
+ public D getD() {
+ return d;
+ }
+
+ public void setD(D d) {
+ this.d = d;
+ }
+}
Property changes on: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/A_PK.java
___________________________________________________________________
Name: svn:keywords
+ Id
Added: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/B.java
===================================================================
--- annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/B.java (rev 0)
+++ annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/B.java 2008-06-18 17:47:30 UTC (rev 14777)
@@ -0,0 +1,28 @@
+// $Id:$
+package org.hibernate.test.annotations.fkcircularity;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+
+/**
+ * Test entities ANN-722.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@Entity
+@Inheritance(strategy = InheritanceType.JOINED)
+public class B {
+ @Id
+ private int id;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+}
Property changes on: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/B.java
___________________________________________________________________
Name: svn:keywords
+ Id
Added: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/C.java
===================================================================
--- annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/C.java (rev 0)
+++ annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/C.java 2008-06-18 17:47:30 UTC (rev 14777)
@@ -0,0 +1,14 @@
+// $Id:$
+package org.hibernate.test.annotations.fkcircularity;
+
+import javax.persistence.Entity;
+
+/**
+ * Test entities ANN-722.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@Entity
+public class C extends B {
+}
Property changes on: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/C.java
___________________________________________________________________
Name: svn:keywords
+ Id
Added: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassA.java
===================================================================
--- annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassA.java (rev 0)
+++ annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassA.java 2008-06-18 17:47:30 UTC (rev 14777)
@@ -0,0 +1,33 @@
+// $Id:$
+package org.hibernate.test.annotations.fkcircularity;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Inheritance;
+import javax.persistence.InheritanceType;
+import javax.persistence.Table;
+
+/**
+ * Test entities ANN-730.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@Entity
+@Table(name = "class_a")
+@Inheritance(strategy = InheritanceType.JOINED)
+public class ClassA {
+
+ private int id;
+
+ @Id
+ @Column(name = "id")
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+}
Property changes on: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassA.java
___________________________________________________________________
Name: svn:keywords
+ Id
Added: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassB.java
===================================================================
--- annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassB.java (rev 0)
+++ annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassB.java 2008-06-18 17:47:30 UTC (rev 14777)
@@ -0,0 +1,18 @@
+// $Id:$
+package org.hibernate.test.annotations.fkcircularity;
+
+import javax.persistence.Entity;
+import javax.persistence.PrimaryKeyJoinColumn;
+import javax.persistence.Table;
+
+/**
+ * Test entities ANN-730.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@Entity
+@Table(name = "class_b")
+@PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id")
+public class ClassB extends ClassA {
+}
Property changes on: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassB.java
___________________________________________________________________
Name: svn:keywords
+ Id
Added: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassC.java
===================================================================
--- annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassC.java (rev 0)
+++ annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassC.java 2008-06-18 17:47:30 UTC (rev 14777)
@@ -0,0 +1,18 @@
+// $Id:$
+package org.hibernate.test.annotations.fkcircularity;
+
+import javax.persistence.Entity;
+import javax.persistence.PrimaryKeyJoinColumn;
+import javax.persistence.Table;
+
+/**
+ * Test entities ANN-730.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@Entity
+@Table(name = "class_c")
+@PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id")
+public class ClassC extends ClassB {
+}
Property changes on: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassC.java
___________________________________________________________________
Name: svn:keywords
+ Id
Added: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassD.java
===================================================================
--- annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassD.java (rev 0)
+++ annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassD.java 2008-06-18 17:47:30 UTC (rev 14777)
@@ -0,0 +1,18 @@
+// $Id:$
+package org.hibernate.test.annotations.fkcircularity;
+
+import javax.persistence.Entity;
+import javax.persistence.PrimaryKeyJoinColumn;
+import javax.persistence.Table;
+
+/**
+ * Test entities ANN-730.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@Entity
+@Table(name = "class_1d")
+@PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id")
+public class ClassD extends ClassC {
+}
Property changes on: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/ClassD.java
___________________________________________________________________
Name: svn:keywords
+ Id
Added: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/D.java
===================================================================
--- annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/D.java (rev 0)
+++ annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/D.java 2008-06-18 17:47:30 UTC (rev 14777)
@@ -0,0 +1,25 @@
+// $Id:$
+package org.hibernate.test.annotations.fkcircularity;
+
+import javax.persistence.EmbeddedId;
+import javax.persistence.Entity;
+
+/**
+ * Test entities ANN-722.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@Entity
+public class D {
+ private D_PK id;
+
+ @EmbeddedId
+ public D_PK getId() {
+ return id;
+ }
+
+ public void setId(D_PK id) {
+ this.id = id;
+ }
+}
Property changes on: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/D.java
___________________________________________________________________
Name: svn:keywords
+ Id
Added: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/D_PK.java
===================================================================
--- annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/D_PK.java (rev 0)
+++ annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/D_PK.java 2008-06-18 17:47:30 UTC (rev 14777)
@@ -0,0 +1,26 @@
+// $Id:$
+package org.hibernate.test.annotations.fkcircularity;
+
+import java.io.Serializable;
+
+import javax.persistence.ManyToOne;
+
+/**
+ * Test entities ANN-722.
+ *
+ * @author Hardy Ferentschik
+ *
+ */
+@SuppressWarnings("serial")
+public class D_PK implements Serializable{
+ private C c;
+
+ @ManyToOne
+ public C getC() {
+ return c;
+ }
+
+ public void setC(C c) {
+ this.c = c;
+ }
+}
Property changes on: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/D_PK.java
___________________________________________________________________
Name: svn:keywords
+ Id
Added: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/FkCircularityTest.java
===================================================================
--- annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/FkCircularityTest.java (rev 0)
+++ annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/FkCircularityTest.java 2008-06-18 17:47:30 UTC (rev 14777)
@@ -0,0 +1,67 @@
+// $Id:$
+package org.hibernate.test.annotations.fkcircularity;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+import junit.framework.TestCase;
+
+import org.hibernate.cfg.AnnotationConfiguration;
+import org.hibernate.dialect.HSQLDialect;
+import org.hibernate.dialect.SQLServerDialect;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Test case for ANN-722 and ANN-730.
+ *
+ * @author Hardy Ferentschik
+ */
+public class FkCircularityTest extends TestCase {
+
+ private Logger log = LoggerFactory.getLogger(FkCircularityTest.class);
+
+ public void testJoinedSublcassesInPK() {
+ try {
+ AnnotationConfiguration config = new AnnotationConfiguration();
+ config.addAnnotatedClass(A.class);
+ config.addAnnotatedClass(B.class);
+ config.addAnnotatedClass(C.class);
+ config.addAnnotatedClass(D.class);
+ config.buildSessionFactory();
+ String[] schema = config
+ .generateSchemaCreationScript(new SQLServerDialect());
+ for (String s : schema) {
+ log.debug(s);
+ }
+ log.debug("success");
+ } catch (Exception e) {
+ StringWriter writer = new StringWriter();
+ e.printStackTrace(new PrintWriter(writer));
+ log.debug(writer.toString());
+ fail(e.getMessage());
+ }
+ }
+
+ public void testDeepJoinedSuclassesHierachy() {
+ try {
+ AnnotationConfiguration config = new AnnotationConfiguration();
+ config.addAnnotatedClass(ClassA.class);
+ config.addAnnotatedClass(ClassB.class);
+ config.addAnnotatedClass(ClassC.class);
+ config.addAnnotatedClass(ClassD.class);
+ config.buildSessionFactory();
+ String[] schema = config
+ .generateSchemaCreationScript(new HSQLDialect());
+ for (String s : schema) {
+ log.debug(s);
+ }
+ log.debug("success");
+ } catch (Exception e) {
+ StringWriter writer = new StringWriter();
+ e.printStackTrace(new PrintWriter(writer));
+ log.debug(writer.toString());
+ fail(e.getMessage());
+ }
+ }
+}
\ No newline at end of file
Property changes on: annotations/trunk/src/test/org/hibernate/test/annotations/fkcircularity/FkCircularityTest.java
___________________________________________________________________
Name: svn:keywords
+ Id
16 years, 6 months
Hibernate SVN: r14776 - in search/branches/jboss_cache_integration: src/java/org/hibernate/search and 5 other directories.
by hibernate-commits@lists.jboss.org
Author: navssurtani
Date: 2008-06-18 10:46:01 -0400 (Wed, 18 Jun 2008)
New Revision: 14776
Added:
search/branches/jboss_cache_integration/src/java/org/hibernate/search/transaction/
search/branches/jboss_cache_integration/src/java/org/hibernate/search/transaction/EventSourceTransactionContext.java
search/branches/jboss_cache_integration/src/java/org/hibernate/search/transaction/TransactionContext.java
search/branches/jboss_cache_integration/x.y
Modified:
search/branches/jboss_cache_integration/common-build.xml
search/branches/jboss_cache_integration/src/java/org/hibernate/search/backend/Worker.java
search/branches/jboss_cache_integration/src/java/org/hibernate/search/backend/impl/TransactionalWorker.java
search/branches/jboss_cache_integration/src/java/org/hibernate/search/event/FullTextIndexEventListener.java
search/branches/jboss_cache_integration/src/java/org/hibernate/search/impl/FullTextSessionImpl.java
Log:
Created transaction package with TransactionContext. Changed other classes that call the doWork() method.
Modified: search/branches/jboss_cache_integration/common-build.xml
===================================================================
--- search/branches/jboss_cache_integration/common-build.xml 2008-06-18 06:04:17 UTC (rev 14775)
+++ search/branches/jboss_cache_integration/common-build.xml 2008-06-18 14:46:01 UTC (rev 14776)
@@ -458,7 +458,7 @@
<!-- maven deploy: to be used by the subbuild and delcare deps on jar -->
<target name="install" depends="jar">
- <fail unless="offline.repository.jboss.org" message="offline.repository.jboss.org must be defined"/>
+ <!-- <fail unless="offline.repository.jboss.org" message="offline.repository.jboss.org must be defined"/> -->
<jar jarfile="${src.jar}" basedir="${src.dir}">
<include name="**/*.java" />
<exclude name="**/test/*.java" />
Modified: search/branches/jboss_cache_integration/src/java/org/hibernate/search/backend/Worker.java
===================================================================
--- search/branches/jboss_cache_integration/src/java/org/hibernate/search/backend/Worker.java 2008-06-18 06:04:17 UTC (rev 14775)
+++ search/branches/jboss_cache_integration/src/java/org/hibernate/search/backend/Worker.java 2008-06-18 14:46:01 UTC (rev 14776)
@@ -1,11 +1,11 @@
//$Id$
package org.hibernate.search.backend;
+import org.hibernate.search.engine.SearchFactoryImplementor;
+import org.hibernate.search.transaction.TransactionContext;
+
import java.util.Properties;
-import org.hibernate.event.EventSource;
-import org.hibernate.search.engine.SearchFactoryImplementor;
-
/**
* Perform work for a given session. This implementation has to be multi threaded
* @author Emmanuel Bernard
@@ -13,7 +13,7 @@
public interface Worker {
//Use of EventSource since it's the common subinterface for Session and SessionImplementor
//the alternative would have been to do a subcasting or to retrieve 2 parameters :(
- void performWork(Work work, EventSource session);
+ void performWork(Work work, TransactionContext session);
void initialize(Properties props, SearchFactoryImplementor searchFactoryImplementor);
Modified: search/branches/jboss_cache_integration/src/java/org/hibernate/search/backend/impl/TransactionalWorker.java
===================================================================
--- search/branches/jboss_cache_integration/src/java/org/hibernate/search/backend/impl/TransactionalWorker.java 2008-06-18 06:04:17 UTC (rev 14775)
+++ search/branches/jboss_cache_integration/src/java/org/hibernate/search/backend/impl/TransactionalWorker.java 2008-06-18 14:46:01 UTC (rev 14776)
@@ -1,17 +1,16 @@
//$Id$
package org.hibernate.search.backend.impl;
-import java.util.Properties;
-
-import org.hibernate.Transaction;
-import org.hibernate.event.EventSource;
import org.hibernate.search.backend.QueueingProcessor;
import org.hibernate.search.backend.Work;
import org.hibernate.search.backend.WorkQueue;
import org.hibernate.search.backend.Worker;
import org.hibernate.search.engine.SearchFactoryImplementor;
+import org.hibernate.search.transaction.TransactionContext;
import org.hibernate.search.util.WeakIdentityHashMap;
+import java.util.Properties;
+
/**
* Queue works per transaction.
* If out of transaction, the work is executed right away
@@ -26,14 +25,14 @@
protected final WeakIdentityHashMap synchronizationPerTransaction = new WeakIdentityHashMap();
private QueueingProcessor queueingProcessor;
- public void performWork(Work work, EventSource session) {
- if ( session.isTransactionInProgress() ) {
- Transaction transaction = session.getTransaction();
+ public void performWork(Work work, TransactionContext transactionContext) {
+ if ( transactionContext.isTxInProgress() ) {
+ Object transaction = transactionContext.getTransactionIdentifier();
PostTransactionWorkQueueSynchronization txSync = (PostTransactionWorkQueueSynchronization)
synchronizationPerTransaction.get( transaction );
if ( txSync == null || txSync.isConsumed() ) {
txSync = new PostTransactionWorkQueueSynchronization( queueingProcessor, synchronizationPerTransaction );
- transaction.registerSynchronization( txSync );
+ transactionContext.registerSynchronization( txSync );
synchronizationPerTransaction.put(transaction, txSync);
}
txSync.add( work );
Modified: search/branches/jboss_cache_integration/src/java/org/hibernate/search/event/FullTextIndexEventListener.java
===================================================================
--- search/branches/jboss_cache_integration/src/java/org/hibernate/search/event/FullTextIndexEventListener.java 2008-06-18 06:04:17 UTC (rev 14775)
+++ search/branches/jboss_cache_integration/src/java/org/hibernate/search/event/FullTextIndexEventListener.java 2008-06-18 14:46:01 UTC (rev 14776)
@@ -1,10 +1,9 @@
//$Id$
package org.hibernate.search.event;
-import java.io.Serializable;
-
import org.hibernate.cfg.Configuration;
import org.hibernate.event.AbstractEvent;
+import org.hibernate.event.Destructible;
import org.hibernate.event.Initializable;
import org.hibernate.event.PostDeleteEvent;
import org.hibernate.event.PostDeleteEventListener;
@@ -12,13 +11,15 @@
import org.hibernate.event.PostInsertEventListener;
import org.hibernate.event.PostUpdateEvent;
import org.hibernate.event.PostUpdateEventListener;
-import org.hibernate.event.Destructible;
+import org.hibernate.search.backend.Work;
import org.hibernate.search.backend.WorkType;
-import org.hibernate.search.backend.Work;
import org.hibernate.search.engine.DocumentBuilder;
import org.hibernate.search.engine.SearchFactoryImplementor;
import org.hibernate.search.impl.SearchFactoryImpl;
+import org.hibernate.search.transaction.EventSourceTransactionContext;
+import java.io.Serializable;
+
/**
* This listener supports setting a parent directory for all generated index files.
* It also supports setting the analyzer class to be used.
@@ -30,64 +31,78 @@
//TODO work on sharing the same indexWriters and readers across a single post operation...
//TODO implement and use a LockableDirectoryProvider that wraps a DP to handle the lock inside the LDP
public class FullTextIndexEventListener implements PostDeleteEventListener, PostInsertEventListener,
- PostUpdateEventListener, Initializable, Destructible {
+ PostUpdateEventListener, Initializable, Destructible
+{
+ @SuppressWarnings({"WeakerAccess"})
+ protected boolean used;
+ protected SearchFactoryImplementor searchFactoryImplementor;
- @SuppressWarnings( { "WeakerAccess" } )
- protected boolean used;
- protected SearchFactoryImplementor searchFactoryImplementor;
+ public void initialize(Configuration cfg)
+ {
+ searchFactoryImplementor = SearchFactoryImpl.getSearchFactory(cfg);
+ String indexingStrategy = searchFactoryImplementor.getIndexingStrategy();
+ if ("event".equals(indexingStrategy))
+ {
+ used = searchFactoryImplementor.getDocumentBuilders().size() != 0;
+ }
+ else if ("manual".equals(indexingStrategy))
+ {
+ used = false;
+ }
+ }
- public void initialize(Configuration cfg) {
- searchFactoryImplementor = SearchFactoryImpl.getSearchFactory( cfg );
- String indexingStrategy = searchFactoryImplementor.getIndexingStrategy();
- if ( "event".equals( indexingStrategy ) ) {
- used = searchFactoryImplementor.getDocumentBuilders().size() != 0;
- }
- else if ( "manual".equals( indexingStrategy ) ) {
- used = false;
- }
- }
+ public SearchFactoryImplementor getSearchFactoryImplementor()
+ {
+ return searchFactoryImplementor;
+ }
- public SearchFactoryImplementor getSearchFactoryImplementor() {
- return searchFactoryImplementor;
- }
+ public void onPostDelete(PostDeleteEvent event)
+ {
+ if (used && searchFactoryImplementor.getDocumentBuilders().containsKey(event.getEntity().getClass()))
+ {
+ processWork(event.getEntity(), event.getId(), WorkType.DELETE, event);
+ }
+ }
- public void onPostDelete(PostDeleteEvent event) {
- if ( used && searchFactoryImplementor.getDocumentBuilders().containsKey( event.getEntity().getClass() ) ) {
- processWork( event.getEntity(), event.getId(), WorkType.DELETE, event );
- }
- }
+ public void onPostInsert(PostInsertEvent event)
+ {
+ if (used)
+ {
+ final Object entity = event.getEntity();
+ DocumentBuilder<Object> builder = searchFactoryImplementor.getDocumentBuilders().get(entity.getClass());
+ //not strictly necessary but a small optimization
+ if (builder != null)
+ {
+ Serializable id = event.getId();
+ processWork(entity, id, WorkType.ADD, event);
+ }
+ }
+ }
- public void onPostInsert(PostInsertEvent event) {
- if (used) {
- final Object entity = event.getEntity();
- DocumentBuilder<Object> builder = searchFactoryImplementor.getDocumentBuilders().get( entity.getClass() );
- //not strictly necessary but a small optimization
- if ( builder != null ) {
- Serializable id = event.getId();
- processWork( entity, id, WorkType.ADD, event );
- }
- }
- }
+ public void onPostUpdate(PostUpdateEvent event)
+ {
+ if (used)
+ {
+ final Object entity = event.getEntity();
+ //not strictly necessary but a small optimization
+ DocumentBuilder<Object> builder = searchFactoryImplementor.getDocumentBuilders().get(entity.getClass());
+ if (builder != null)
+ {
+ Serializable id = event.getId();
+ processWork(entity, id, WorkType.UPDATE, event);
+ }
+ }
+ }
- public void onPostUpdate(PostUpdateEvent event) {
- if (used) {
- final Object entity = event.getEntity();
- //not strictly necessary but a small optimization
- DocumentBuilder<Object> builder = searchFactoryImplementor.getDocumentBuilders().get( entity.getClass() );
- if ( builder != null ) {
- Serializable id = event.getId();
- processWork( entity, id, WorkType.UPDATE, event );
- }
- }
- }
+ @SuppressWarnings({"WeakerAccess"})
+ protected void processWork(Object entity, Serializable id, WorkType workType, AbstractEvent event)
+ {
+ Work work = new Work(entity, id, workType);
+ searchFactoryImplementor.getWorker().performWork(work, new EventSourceTransactionContext(event.getSession()));
+ }
- @SuppressWarnings( { "WeakerAccess" } )
- protected void processWork(Object entity, Serializable id, WorkType workType, AbstractEvent event) {
- Work work = new Work(entity, id, workType);
- searchFactoryImplementor.getWorker().performWork( work, event.getSession() );
- }
-
- public void cleanup() {
- searchFactoryImplementor.close();
- }
+ public void cleanup()
+ {
+ searchFactoryImplementor.close();
+ }
}
Modified: search/branches/jboss_cache_integration/src/java/org/hibernate/search/impl/FullTextSessionImpl.java
===================================================================
--- search/branches/jboss_cache_integration/src/java/org/hibernate/search/impl/FullTextSessionImpl.java 2008-06-18 06:04:17 UTC (rev 14775)
+++ search/branches/jboss_cache_integration/src/java/org/hibernate/search/impl/FullTextSessionImpl.java 2008-06-18 14:46:01 UTC (rev 14776)
@@ -1,29 +1,7 @@
//$Id$
package org.hibernate.search.impl;
-import java.io.Serializable;
-import java.sql.Connection;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.hibernate.CacheMode;
-import org.hibernate.Criteria;
-import org.hibernate.EntityMode;
-import org.hibernate.Filter;
-import org.hibernate.FlushMode;
-import org.hibernate.Hibernate;
-import org.hibernate.HibernateException;
-import org.hibernate.Interceptor;
-import org.hibernate.LockMode;
-import org.hibernate.Query;
-import org.hibernate.ReplicationMode;
-import org.hibernate.SQLQuery;
-import org.hibernate.ScrollMode;
-import org.hibernate.ScrollableResults;
-import org.hibernate.SessionFactory;
-import org.hibernate.Transaction;
+import org.hibernate.*;
import org.hibernate.classic.Session;
import org.hibernate.collection.PersistentCollection;
import org.hibernate.engine.EntityKey;
@@ -48,10 +26,19 @@
import org.hibernate.search.engine.DocumentBuilder;
import org.hibernate.search.engine.SearchFactoryImplementor;
import org.hibernate.search.query.FullTextQueryImpl;
+import org.hibernate.search.transaction.EventSourceTransactionContext;
+import org.hibernate.search.transaction.TransactionContext;
import org.hibernate.search.util.ContextHelper;
import org.hibernate.stat.SessionStatistics;
import org.hibernate.type.Type;
+import java.io.Serializable;
+import java.sql.Connection;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
/**
* Lucene full text search aware session.
*
@@ -61,13 +48,13 @@
*/
public class FullTextSessionImpl implements FullTextSession, SessionImplementor {
private final Session session;
- private final EventSource eventSource;
+ private final TransactionContext transactionContext;
private final SessionImplementor sessionImplementor;
private transient SearchFactoryImplementor searchFactory;
public FullTextSessionImpl(org.hibernate.Session session) {
this.session = (Session) session;
- this.eventSource = (EventSource) session;
+ this.transactionContext = new EventSourceTransactionContext((EventSource) session);
this.sessionImplementor = (SessionImplementor) session;
}
@@ -116,7 +103,7 @@
type = WorkType.PURGE;
}
Work work = new Work(entityType, id, type);
- searchFactoryImplementor.getWorker().performWork( work, eventSource );
+ searchFactoryImplementor.getWorker().performWork( work, transactionContext );
}
}
@@ -137,7 +124,7 @@
if ( builder != null ) {
Serializable id = session.getIdentifier( entity );
Work work = new Work(entity, id, WorkType.INDEX);
- searchFactoryImplementor.getWorker().performWork( work, eventSource );
+ searchFactoryImplementor.getWorker().performWork( work, transactionContext );
}
//TODO
//need to add elements in a queue kept at the Session level
Added: search/branches/jboss_cache_integration/src/java/org/hibernate/search/transaction/EventSourceTransactionContext.java
===================================================================
--- search/branches/jboss_cache_integration/src/java/org/hibernate/search/transaction/EventSourceTransactionContext.java (rev 0)
+++ search/branches/jboss_cache_integration/src/java/org/hibernate/search/transaction/EventSourceTransactionContext.java 2008-06-18 14:46:01 UTC (rev 14776)
@@ -0,0 +1,36 @@
+package org.hibernate.search.transaction;
+
+import org.hibernate.Transaction;
+import org.hibernate.event.EventSource;
+
+import javax.transaction.Synchronization;
+
+/**
+@author Navin Surtani - navin(a)surtani.org
+ */
+public class EventSourceTransactionContext implements TransactionContext
+{
+ EventSource eventSource;
+
+ public EventSourceTransactionContext(EventSource eventSource)
+ {
+ this.eventSource = eventSource;
+ }
+
+ public Object getTransactionIdentifier()
+ {
+ return eventSource.getTransaction();
+ }
+
+ public void registerSynchronization(Synchronization synchronization)
+ {
+ Transaction transaction = eventSource.getTransaction();
+ transaction.registerSynchronization(synchronization);
+ }
+
+ public boolean isTxInProgress()
+ {
+ return eventSource.isTransactionInProgress();
+ }
+
+}
Added: search/branches/jboss_cache_integration/src/java/org/hibernate/search/transaction/TransactionContext.java
===================================================================
--- search/branches/jboss_cache_integration/src/java/org/hibernate/search/transaction/TransactionContext.java (rev 0)
+++ search/branches/jboss_cache_integration/src/java/org/hibernate/search/transaction/TransactionContext.java 2008-06-18 14:46:01 UTC (rev 14776)
@@ -0,0 +1,22 @@
+package org.hibernate.search.transaction;
+
+import javax.transaction.Synchronization;
+
+/**
+@author Navin Surtani - navin(a)surtani.org
+ */
+public interface TransactionContext
+{
+ /**
+ *@return A boolean whether a transaction is in progress or not.
+ */
+ public boolean isTxInProgress();
+
+ /**
+ *
+ * @return a transaction object.
+ */
+ public Object getTransactionIdentifier();
+
+ public void registerSynchronization(Synchronization synchronization);
+}
Added: search/branches/jboss_cache_integration/x.y
===================================================================
16 years, 6 months
Hibernate SVN: r14775 - core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/tool/hbm2ddl.
by hibernate-commits@lists.jboss.org
Author: anthonyHib
Date: 2008-06-18 02:04:17 -0400 (Wed, 18 Jun 2008)
New Revision: 14775
Modified:
core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/tool/hbm2ddl/SchemaUpdate.java
core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/tool/hbm2ddl/SchemaUpdateTask.java
Log:
JBPAPP-859
Modified: core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/tool/hbm2ddl/SchemaUpdate.java
===================================================================
--- core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/tool/hbm2ddl/SchemaUpdate.java 2008-06-17 13:36:42 UTC (rev 14774)
+++ core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/tool/hbm2ddl/SchemaUpdate.java 2008-06-18 06:04:17 UTC (rev 14775)
@@ -2,6 +2,8 @@
package org.hibernate.tool.hbm2ddl;
import java.io.FileInputStream;
+import java.io.FileWriter;
+import java.io.Writer;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
@@ -12,10 +14,12 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
+import org.hibernate.JDBCException;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.cfg.Settings;
import org.hibernate.dialect.Dialect;
+import org.hibernate.pretty.DDLFormatter;
import org.hibernate.util.ReflectHelper;
/**
@@ -31,6 +35,10 @@
private Configuration configuration;
private Dialect dialect;
private List exceptions;
+ private boolean haltOnError = false;
+ private boolean format = true;
+ private String outputFile = null;
+ private String delimiter;
public SchemaUpdate(Configuration cfg) throws HibernateException {
this( cfg, cfg.getProperties() );
@@ -116,6 +124,7 @@
Connection connection = null;
Statement stmt = null;
+ Writer outputFileWriter = null;
exceptions.clear();
@@ -137,20 +146,36 @@
log.info( "updating schema" );
+
+ if ( outputFile != null ) {
+ log.info( "writing generated schema to file: " + outputFile );
+ outputFileWriter = new FileWriter( outputFile );
+ }
+
String[] createSQL = configuration.generateSchemaUpdateScript( dialect, meta );
for ( int j = 0; j < createSQL.length; j++ ) {
final String sql = createSQL[j];
+ String formatted = format( sql );
try {
+ if ( delimiter != null ) {
+ formatted += delimiter;
+ }
if ( script ) {
- System.out.println( sql );
+ System.out.println( formatted );
}
+ if ( outputFile != null ) {
+ outputFileWriter.write( formatted + "\n" );
+ }
if ( doUpdate ) {
log.debug( sql );
- stmt.executeUpdate( sql );
+ stmt.executeUpdate( formatted );
}
}
catch ( SQLException e ) {
+ if ( haltOnError ) {
+ throw new JDBCException( "Error during DDL export", e );
+ }
exceptions.add( e );
log.error( "Unsuccessful: " + sql );
log.error( e.getMessage() );
@@ -176,7 +201,15 @@
exceptions.add( e );
log.error( "Error closing connection", e );
}
-
+ try {
+ if( outputFileWriter != null ) {
+ outputFileWriter.close();
+ }
+ }
+ catch(Exception e) {
+ exceptions.add(e);
+ log.error( "Error closing connection", e );
+ }
}
}
@@ -188,4 +221,26 @@
public List getExceptions() {
return exceptions;
}
+
+ public void setHaltOnError(boolean haltOnError) {
+ this.haltOnError = haltOnError;
+ }
+
+ public void setFormat(boolean format) {
+ this.format = format;
+ }
+
+ public void setOutputFile(String outputFile) {
+ this.outputFile = outputFile;
+ }
+
+ public void setDelimiter(String delimiter) {
+ this.delimiter = delimiter;
+ }
+
+ private String format(String sql) {
+ return format ?
+ new DDLFormatter( sql ).format() :
+ sql;
+ }
}
Modified: core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/tool/hbm2ddl/SchemaUpdateTask.java
===================================================================
--- core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/tool/hbm2ddl/SchemaUpdateTask.java 2008-06-17 13:36:42 UTC (rev 14774)
+++ core/branches/Branch_3_2_4_SP1_CP/src/org/hibernate/tool/hbm2ddl/SchemaUpdateTask.java 2008-06-18 06:04:17 UTC (rev 14775)
@@ -47,9 +47,13 @@
private List fileSets = new LinkedList();
private File propertiesFile = null;
private File configurationFile = null;
+ private File outputFile = null;
private boolean quiet = false;
private boolean text = true;
+ private boolean haltOnError = false;
+ private String delimiter = null;
private String namingStrategy = null;
+
public void addFileset(FileSet set) {
fileSets.add(set);
@@ -174,11 +178,39 @@
properties.load( new FileInputStream(propertiesFile) );
}
cfg.setProperties(properties);
- return new SchemaUpdate(cfg);
+ SchemaUpdate su = new SchemaUpdate(cfg);
+ su.setOutputFile( outputFile.getPath() );
+ su.setDelimiter(delimiter);
+ su.setHaltOnError(haltOnError);
+ return su;
}
public void setNamingStrategy(String namingStrategy) {
this.namingStrategy = namingStrategy;
}
+ public File getOutputFile() {
+ return outputFile;
+ }
+
+ public void setOutputFile(File outputFile) {
+ this.outputFile = outputFile;
+ }
+
+ public boolean isHaltOnError() {
+ return haltOnError;
+ }
+
+ public void setHaltOnError(boolean haltOnError) {
+ this.haltOnError = haltOnError;
+ }
+
+ public String getDelimiter() {
+ return delimiter;
+ }
+
+ public void setDelimiter(String delimiter) {
+ this.delimiter = delimiter;
+ }
+
}
16 years, 6 months
Hibernate SVN: r14773 - search/trunk/src/java/org/hibernate/search/reader.
by hibernate-commits@lists.jboss.org
Author: sannegrinovero
Date: 2008-06-17 09:21:29 -0400 (Tue, 17 Jun 2008)
New Revision: 14773
Modified:
search/trunk/src/java/org/hibernate/search/reader/SharingBufferReaderProvider.java
Log:
HSEARCH-212 : new ReaderProvider final cleanups
Modified: search/trunk/src/java/org/hibernate/search/reader/SharingBufferReaderProvider.java
===================================================================
--- search/trunk/src/java/org/hibernate/search/reader/SharingBufferReaderProvider.java 2008-06-17 13:03:13 UTC (rev 14772)
+++ search/trunk/src/java/org/hibernate/search/reader/SharingBufferReaderProvider.java 2008-06-17 13:21:29 UTC (rev 14773)
@@ -35,7 +35,7 @@
* contains all Readers (most current per DP and all unclosed old)
*/
//TODO ConcurrentHashMap's constructor could benefit from some hints as arguments.
- protected final Map<IndexReader,ReaderUsagePair> allReaders = new ConcurrentHashMap<IndexReader,ReaderUsagePair>( 100 );
+ protected final Map<IndexReader,ReaderUsagePair> allReaders = new ConcurrentHashMap<IndexReader,ReaderUsagePair>();
/**
* contains last updated Reader; protected by lockOnOpenLatest (in the values)
@@ -53,7 +53,7 @@
else {
throw new AssertionFailure( "Everything should be wrapped in a MultiReader" );
}
- log.trace( "Closing MultiReader: {}", multiReader );
+ log.debug( "Closing MultiReader: {}", multiReader );
for ( IndexReader reader : readers ) {
ReaderUsagePair container = allReaders.get( reader );
container.close();//virtual
@@ -76,13 +76,14 @@
}
public IndexReader openReader(DirectoryProvider... directoryProviders) {
- boolean trace = log.isTraceEnabled();
int length = directoryProviders.length;
IndexReader[] readers = new IndexReader[length];
- if ( trace ) log.trace( "Opening IndexReader for directoryProviders: {}", length );
- for (int index = 0; index < length; index++) {
+ log.debug( "Opening IndexReader for directoryProviders: {}", length );
+ for ( int index = 0; index < length; index++ ) {
DirectoryProvider directoryProvider = directoryProviders[index];
- if ( trace ) log.trace( "Opening IndexReader from {}", directoryProvider.getDirectory() );
+ if ( log.isTraceEnabled() ) {
+ log.trace( "Opening IndexReader from {}", directoryProvider.getDirectory() );
+ }
PerDirectoryLatestReader directoryLatestReader = currentReaders.get( directoryProvider );
readers[index] = directoryLatestReader.refreshAndGet();
}
16 years, 6 months
Hibernate SVN: r14772 - in search/trunk/src: java/org/hibernate/search/backend/impl and 4 other directories.
by hibernate-commits@lists.jboss.org
Author: sannegrinovero
Date: 2008-06-17 09:03:13 -0400 (Tue, 17 Jun 2008)
New Revision: 14772
Added:
search/trunk/src/java/org/hibernate/search/backend/configuration/ConfigurationParseHelper.java
search/trunk/src/test/org/hibernate/search/test/configuration/ConfigurationParseHelperTest.java
Modified:
search/trunk/src/java/org/hibernate/search/backend/configuration/IndexWriterSetting.java
search/trunk/src/java/org/hibernate/search/backend/impl/BatchedQueueingProcessor.java
search/trunk/src/java/org/hibernate/search/filter/MRUFilterCachingStrategy.java
search/trunk/src/java/org/hibernate/search/store/DirectoryProviderFactory.java
search/trunk/src/java/org/hibernate/search/store/optimization/IncrementalOptimizerStrategy.java
Log:
HSEARCH-217 : Proper errors on parsing of all numeric configuration parameters
Added: search/trunk/src/java/org/hibernate/search/backend/configuration/ConfigurationParseHelper.java
===================================================================
--- search/trunk/src/java/org/hibernate/search/backend/configuration/ConfigurationParseHelper.java (rev 0)
+++ search/trunk/src/java/org/hibernate/search/backend/configuration/ConfigurationParseHelper.java 2008-06-17 13:03:13 UTC (rev 14772)
@@ -0,0 +1,69 @@
+package org.hibernate.search.backend.configuration;
+
+import java.util.Properties;
+
+import org.hibernate.annotations.common.util.StringHelper;
+import org.hibernate.search.SearchException;
+
+/**
+ * Helper class to avoid managing NumberFormatException and similar code
+ * and ensure consistent error messages across Configuration parsing problems.
+ *
+ * @author Sanne Grinovero
+ */
+public abstract class ConfigurationParseHelper {
+
+ /**
+ * Parses a String to get an int value.
+ * @param value A string containing an int value to parse
+ * @param errorMsgOnParseFailure message being wrapped in a SearchException if value is null or not correct.
+ * @return the parsed value
+ * @throws SearchException both for null values and for Strings not containing a valid int.
+ */
+ public static final int parseInt(String value, String errorMsgOnParseFailure) {
+ if ( value == null ) {
+ throw new SearchException( errorMsgOnParseFailure );
+ }
+ else {
+ try {
+ return Integer.parseInt( value.trim() );
+ } catch (NumberFormatException nfe) {
+ throw new SearchException( errorMsgOnParseFailure, nfe );
+ }
+ }
+ }
+
+ /**
+ * In case value is null or an empty string the defValue is returned
+ * @param value
+ * @param defValue
+ * @param errorMsgOnParseFailure
+ * @return the converted int.
+ * @throws SearchException if value can't be parsed.
+ */
+ public static final int parseInt(String value, int defValue, String errorMsgOnParseFailure) {
+ if ( StringHelper.isEmpty( value ) ) {
+ return defValue;
+ }
+ else {
+ return parseInt( value, errorMsgOnParseFailure );
+ }
+ }
+
+ /**
+ * Looks for a numeric value in the Properties, returning
+ * defValue if not found or if an empty string is found.
+ * When the key the value is found but not in valid format
+ * a standard error message is generated.
+ * @param cfg
+ * @param key
+ * @param defValue
+ * @return the converted int.
+ * @throws SearchException for invalid format.
+ */
+ public static final int getIntValue(Properties cfg, String key, int defValue) {
+ String propValue = cfg.getProperty( key );
+ return parseInt( propValue, defValue, "Unable to parse " + key + ": " + propValue );
+ }
+
+}
Modified: search/trunk/src/java/org/hibernate/search/backend/configuration/IndexWriterSetting.java
===================================================================
--- search/trunk/src/java/org/hibernate/search/backend/configuration/IndexWriterSetting.java 2008-06-16 17:15:32 UTC (rev 14771)
+++ search/trunk/src/java/org/hibernate/search/backend/configuration/IndexWriterSetting.java 2008-06-17 13:03:13 UTC (rev 14772)
@@ -94,11 +94,8 @@
* @throws SearchException for unrecognized values
*/
public Integer parseVal(String value) {
- try {
- return Integer.valueOf( value );
- } catch (NumberFormatException ne) {
- throw new SearchException( "Invalid value for " + cfgKey + ": " + value );
- }
+ return ConfigurationParseHelper.parseInt( value,
+ "Invalid value for " + cfgKey + ": " + value );
}
}
Modified: search/trunk/src/java/org/hibernate/search/backend/impl/BatchedQueueingProcessor.java
===================================================================
--- search/trunk/src/java/org/hibernate/search/backend/impl/BatchedQueueingProcessor.java 2008-06-16 17:15:32 UTC (rev 14771)
+++ search/trunk/src/java/org/hibernate/search/backend/impl/BatchedQueueingProcessor.java 2008-06-17 13:03:13 UTC (rev 14772)
@@ -20,6 +20,7 @@
import org.hibernate.search.backend.Work;
import org.hibernate.search.backend.WorkType;
import org.hibernate.search.backend.WorkQueue;
+import org.hibernate.search.backend.configuration.ConfigurationParseHelper;
import org.hibernate.search.backend.impl.jms.JMSBackendQueueProcessorFactory;
import org.hibernate.search.backend.impl.lucene.LuceneBackendQueueProcessorFactory;
import org.hibernate.search.engine.DocumentBuilder;
@@ -50,16 +51,12 @@
this.sync = !"async".equalsIgnoreCase( properties.getProperty( Environment.WORKER_EXECUTION ) );
//default to a simple asynchronous operation
- int min = Integer.parseInt(
- properties.getProperty( Environment.WORKER_THREADPOOL_SIZE, "1" ).trim()
- );
+ int min = ConfigurationParseHelper.getIntValue( properties, Environment.WORKER_THREADPOOL_SIZE, 1 );
//no queue limit
- int queueSize = Integer.parseInt(
- properties.getProperty( Environment.WORKER_WORKQUEUE_SIZE, Integer.toString( Integer.MAX_VALUE ) ).trim()
- );
- batchSize = Integer.parseInt(
- properties.getProperty( Environment.WORKER_BATCHSIZE, "0" ).trim()
- );
+ int queueSize = ConfigurationParseHelper.getIntValue( properties, Environment.WORKER_WORKQUEUE_SIZE, Integer.MAX_VALUE );
+
+ batchSize = ConfigurationParseHelper.getIntValue( properties, Environment.WORKER_BATCHSIZE, 0 );
+
if ( !sync ) {
/**
* choose min = max with a sizable queue to be able to
Modified: search/trunk/src/java/org/hibernate/search/filter/MRUFilterCachingStrategy.java
===================================================================
--- search/trunk/src/java/org/hibernate/search/filter/MRUFilterCachingStrategy.java 2008-06-16 17:15:32 UTC (rev 14771)
+++ search/trunk/src/java/org/hibernate/search/filter/MRUFilterCachingStrategy.java 2008-06-17 13:03:13 UTC (rev 14772)
@@ -5,7 +5,7 @@
import org.apache.lucene.search.Filter;
import org.hibernate.search.Environment;
-import org.hibernate.search.SearchException;
+import org.hibernate.search.backend.configuration.ConfigurationParseHelper;
import org.hibernate.util.SoftLimitMRUCache;
/**
@@ -16,23 +16,12 @@
* @author Emmanuel Bernard
*/
public class MRUFilterCachingStrategy implements FilterCachingStrategy {
- private static final String DEFAULT_SIZE = "128";
+ private static final int DEFAULT_SIZE = 128;
private SoftLimitMRUCache cache;
private static final String SIZE = Environment.FILTER_CACHING_STRATEGY + ".size";
public void initialize(Properties properties) {
- int size;
- try {
- size = Integer.parseInt(
- properties.getProperty( SIZE, DEFAULT_SIZE )
- );
- }
- catch (NumberFormatException nfe) {
- throw new SearchException(
- "Unable to parse " + SIZE + ": " + properties.getProperty( SIZE, DEFAULT_SIZE ), nfe
- );
- }
-
+ int size = ConfigurationParseHelper.getIntValue( properties, SIZE, DEFAULT_SIZE );
cache = new SoftLimitMRUCache( size );
}
Modified: search/trunk/src/java/org/hibernate/search/store/DirectoryProviderFactory.java
===================================================================
--- search/trunk/src/java/org/hibernate/search/store/DirectoryProviderFactory.java 2008-06-16 17:15:32 UTC (rev 14771)
+++ search/trunk/src/java/org/hibernate/search/store/DirectoryProviderFactory.java 2008-06-17 13:03:13 UTC (rev 14772)
@@ -13,6 +13,7 @@
import org.hibernate.search.SearchException;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.backend.LuceneIndexingParameters;
+import org.hibernate.search.backend.configuration.ConfigurationParseHelper;
import org.hibernate.search.backend.configuration.MaskedProperty;
import org.hibernate.search.engine.SearchFactoryImplementor;
import org.hibernate.search.impl.SearchFactoryImpl;
@@ -208,14 +209,7 @@
return new Properties[] { directoryLocalProperties };
} else {
// count shards
- int shardsCount;
- {
- try {
- shardsCount = Integer.parseInt( shardsCountValue );
- } catch (NumberFormatException e) {
- throw new SearchException( shardsCountValue + " is not a number", e);
- }
- }
+ int shardsCount = ConfigurationParseHelper.parseInt( shardsCountValue, shardsCountValue + " is not a number" );
// create shard-specific Props
Properties[] shardLocalProperties = new Properties[shardsCount];
for ( int i = 0; i < shardsCount; i++ ) {
Modified: search/trunk/src/java/org/hibernate/search/store/optimization/IncrementalOptimizerStrategy.java
===================================================================
--- search/trunk/src/java/org/hibernate/search/store/optimization/IncrementalOptimizerStrategy.java 2008-06-16 17:15:32 UTC (rev 14771)
+++ search/trunk/src/java/org/hibernate/search/store/optimization/IncrementalOptimizerStrategy.java 2008-06-17 13:03:13 UTC (rev 14772)
@@ -6,9 +6,9 @@
import org.hibernate.search.engine.SearchFactoryImplementor;
import org.hibernate.search.backend.Workspace;
+import org.hibernate.search.backend.configuration.ConfigurationParseHelper;
import org.hibernate.search.store.DirectoryProvider;
import org.hibernate.search.SearchException;
-import org.hibernate.annotations.common.util.StringHelper;
import org.apache.lucene.index.IndexWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -28,15 +28,8 @@
public void initialize(DirectoryProvider directoryProvider, Properties indexProperties, SearchFactoryImplementor searchFactoryImplementor) {
this.directoryProvider = directoryProvider;
- String maxString = indexProperties.getProperty( "optimizer.operation_limit.max" );
- if ( StringHelper.isNotEmpty( maxString ) ) {
- operationMax = Integer.parseInt( maxString );
- }
-
- maxString = indexProperties.getProperty( "optimizer.transaction_limit.max" );
- if ( StringHelper.isNotEmpty( maxString ) ) {
- transactionMax = Integer.parseInt( maxString );
- }
+ operationMax = ConfigurationParseHelper.getIntValue( indexProperties, "optimizer.operation_limit.max", -1 );
+ transactionMax = ConfigurationParseHelper.getIntValue( indexProperties, "optimizer.transaction_limit.max", -1 );
}
public void optimizationForced() {
Added: search/trunk/src/test/org/hibernate/search/test/configuration/ConfigurationParseHelperTest.java
===================================================================
--- search/trunk/src/test/org/hibernate/search/test/configuration/ConfigurationParseHelperTest.java (rev 0)
+++ search/trunk/src/test/org/hibernate/search/test/configuration/ConfigurationParseHelperTest.java 2008-06-17 13:03:13 UTC (rev 14772)
@@ -0,0 +1,34 @@
+package org.hibernate.search.test.configuration;
+
+import java.util.Properties;
+
+import junit.framework.TestCase;
+
+import org.hibernate.search.SearchException;
+import org.hibernate.search.backend.configuration.ConfigurationParseHelper;
+
+/**
+ * @author Sanne Grinovero
+ */
+public class ConfigurationParseHelperTest extends TestCase {
+
+ public void testIntegerParsers(){
+ assertEquals( 0, ConfigurationParseHelper.parseInt( " 0 ", "not important") );
+ assertEquals( 8, ConfigurationParseHelper.parseInt( null, 8, null ) );
+ assertEquals( 56, ConfigurationParseHelper.parseInt( "56", 8, null ) );
+ Properties props = new Properties();
+ props.setProperty( "value1", "58" );
+ assertEquals( 58, ConfigurationParseHelper.getIntValue( props, "value1", 8 ) );
+ assertEquals( 8, ConfigurationParseHelper.getIntValue( props, "value2", 8 ) );
+ props.setProperty( "value2", "nand" );
+ boolean exceptionLaunched;
+ try {
+ ConfigurationParseHelper.getIntValue( props, "value2", 8 );
+ exceptionLaunched = false;
+ } catch (SearchException e) {
+ exceptionLaunched = true;
+ }
+ assertTrue( exceptionLaunched );
+ }
+
+}
16 years, 6 months
Hibernate SVN: r14771 - search/trunk/src/java/org/hibernate/search/reader.
by hibernate-commits@lists.jboss.org
Author: epbernard
Date: 2008-06-16 13:15:32 -0400 (Mon, 16 Jun 2008)
New Revision: 14771
Modified:
search/trunk/src/java/org/hibernate/search/reader/SharingBufferReaderProvider.java
Log:
unnecessary cast
Modified: search/trunk/src/java/org/hibernate/search/reader/SharingBufferReaderProvider.java
===================================================================
--- search/trunk/src/java/org/hibernate/search/reader/SharingBufferReaderProvider.java 2008-06-16 15:43:48 UTC (rev 14770)
+++ search/trunk/src/java/org/hibernate/search/reader/SharingBufferReaderProvider.java 2008-06-16 17:15:32 UTC (rev 14771)
@@ -48,7 +48,7 @@
if ( multiReader == null ) return;
IndexReader[] readers;
if ( multiReader instanceof MultiReader ) {
- readers = (IndexReader[]) ReaderProviderHelper.getSubReadersFromMultiReader( (MultiReader) multiReader );
+ readers = ReaderProviderHelper.getSubReadersFromMultiReader( (MultiReader) multiReader );
}
else {
throw new AssertionFailure( "Everything should be wrapped in a MultiReader" );
16 years, 6 months