Topia-commits
Threads by month
- ----- 2026 -----
- June
- May
- April
- March
- February
- January
- ----- 2025 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2011 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2010 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2009 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2008 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2007 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2006 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2005 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2004 -----
- December
- November
- October
- September
- August
- July
- June
- May
March 2010
- 3 participants
- 49 discussions
r1845 - in trunk/topia-persistence/src/main/java/org/nuiton/topia: generator persistence
by tchemit@users.nuiton.org 17 Mar '10
by tchemit@users.nuiton.org 17 Mar '10
17 Mar '10
Author: tchemit
Date: 2010-03-17 14:06:52 +0100 (Wed, 17 Mar 2010)
New Revision: 1845
Log:
fix signature of findAllUsages in DAO api
Modified:
trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOAbstractTransformer.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAO.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAOImpl.java
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOAbstractTransformer.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOAbstractTransformer.java 2010-03-17 00:18:04 UTC (rev 1844)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOAbstractTransformer.java 2010-03-17 13:06:52 UTC (rev 1845)
@@ -396,7 +396,7 @@
operation = addOperation(result,
"findAllUsages",
- "Map<Class<?>, List<? extends TopiaEntity>>",
+ "Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>",
ObjectModelModifier.PUBLIC);
addParameter(operation, "E", "entity");
@@ -404,7 +404,7 @@
addAnnotation(result, operation,"Override");
setOperationBody(operation, ""
/*{
- return new HashMap<Class<?>, List<? extends TopiaEntity>>();
+ return new HashMap<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>();
}*/
);
@@ -507,7 +507,7 @@
operation = addOperation(result,
"findAllUsages",
- "Map<Class<?>, List<? extends TopiaEntity>>",
+ "Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>",
ObjectModelModifier.PUBLIC);
addParameter(operation, "E", "entity");
@@ -517,8 +517,8 @@
buffer = new StringBuilder(300);
buffer.append(""
/*{
- Map<Class<?>,List<? extends TopiaEntity>> result;
- result = new HashMap<Class<?>, List<? extends TopiaEntity>>(<%=usagesForclass.size()%>);
+ Map<Class<? extends TopiaEntity>,List<? extends TopiaEntity>> result;
+ result = new HashMap<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>(<%=usagesForclass.size()%>);
List<? extends TopiaEntity> list;
}*/
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAO.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAO.java 2010-03-17 00:18:04 UTC (rev 1844)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAO.java 2010-03-17 13:06:52 UTC (rev 1845)
@@ -348,7 +348,7 @@
* @since 2.3.0
*/
- Map<Class<?>, List<? extends TopiaEntity>> findAllUsages(Entity entity)
+ Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> findAllUsages(Entity entity)
throws TopiaException;
/**
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAOImpl.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAOImpl.java 2010-03-17 00:18:04 UTC (rev 1844)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAOImpl.java 2010-03-17 13:06:52 UTC (rev 1845)
@@ -564,7 +564,7 @@
}
@Override
- public Map<Class<?>, List<? extends TopiaEntity>> findAllUsages(E e)
+ public Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> findAllUsages(E e)
throws TopiaException {
// must be implemented by specialized dao
throw new UnsupportedOperationException();
1
0
r1844 - in trunk/topia-service-replication/src: main/java/org/nuiton/topia/replication/model test/java/org/nuiton/topia/replication
by tchemit@users.nuiton.org 17 Mar '10
by tchemit@users.nuiton.org 17 Mar '10
17 Mar '10
Author: tchemit
Date: 2010-03-17 01:18:04 +0100 (Wed, 17 Mar 2010)
New Revision: 1844
Log:
improve code and tester
Modified:
trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/model/ReplicationModel.java
trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/model/ReplicationNode.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractReplicationEngineTest.java
Modified: trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/model/ReplicationModel.java
===================================================================
--- trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/model/ReplicationModel.java 2010-03-15 10:57:51 UTC (rev 1843)
+++ trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/model/ReplicationModel.java 2010-03-17 00:18:04 UTC (rev 1844)
@@ -72,34 +72,34 @@
public ReplicationModel(TopiaEntityEnum[] contracts, Set<Class<? extends TopiaEntity>> types, String... topiaIds) {
this.contracts = contracts;
this.topiaIds = topiaIds;
- this.replicateAll = false;
- this.nodes = new LinkedHashMap<Class<? extends TopiaEntity>, ReplicationNode>();
- this.order = new ArrayList<ReplicationNode>();
+ replicateAll = false;
+ nodes = new LinkedHashMap<Class<? extends TopiaEntity>, ReplicationNode>();
+ order = new ArrayList<ReplicationNode>();
Map<Class<? extends TopiaEntity>, ReplicationNode> tmpNodes = new HashMap<Class<? extends TopiaEntity>, ReplicationNode>();
for (Class<? extends TopiaEntity> k : types) {
TopiaEntityEnum e = TopiaEntityHelper.getEntityEnum(k, contracts);
ReplicationNode replicationNode = new ReplicationNode(e);
tmpNodes.put(k, replicationNode);
}
- this.nodes = Collections.unmodifiableMap(tmpNodes);
+ nodes = Collections.unmodifiableMap(tmpNodes);
}
public ReplicationModel(TopiaEntityEnum[] contracts, boolean replicateAll, String... topiaIds) {
this.contracts = contracts;
this.topiaIds = topiaIds;
this.replicateAll = replicateAll;
- this.nodes = new LinkedHashMap<Class<? extends TopiaEntity>, ReplicationNode>();
- this.order = new ArrayList<ReplicationNode>();
+ nodes = new LinkedHashMap<Class<? extends TopiaEntity>, ReplicationNode>();
+ order = new ArrayList<ReplicationNode>();
Map<Class<? extends TopiaEntity>, ReplicationNode> tmpNodes = new HashMap<Class<? extends TopiaEntity>, ReplicationNode>();
for (TopiaEntityEnum e : contracts) {
ReplicationNode replicationNode = new ReplicationNode(e);
tmpNodes.put(e.getContract(), replicationNode);
if (!replicateAll) {
// mode restreint : l'ordre est induit par l'ordre sur les contrats passes
- this.order.add(replicationNode);
+ order.add(replicationNode);
}
}
- this.nodes = Collections.unmodifiableMap(tmpNodes);
+ nodes = Collections.unmodifiableMap(tmpNodes);
}
Modified: trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/model/ReplicationNode.java
===================================================================
--- trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/model/ReplicationNode.java 2010-03-15 10:57:51 UTC (rev 1843)
+++ trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/model/ReplicationNode.java 2010-03-17 00:18:04 UTC (rev 1844)
@@ -75,13 +75,13 @@
public ReplicationNode(TopiaEntityEnum contract) {
this.contract = contract;
- this.operator = EntityOperatorStore.getOperator(contract);
- this.associations = new HashMap<String, ReplicationNode>();
- this.dependencies = new HashMap<String, ReplicationNode>();
- this.shell = new HashSet<ReplicationNode>();
- this.associationsToDettach = new HashSet<String>();
- this.dependenciesToDettach = new HashSet<String>();
- this.operations = new ArrayList<ReplicationOperationDef>();
+ operator = EntityOperatorStore.getOperator(contract);
+ associations = new HashMap<String, ReplicationNode>();
+ dependencies = new HashMap<String, ReplicationNode>();
+ shell = new HashSet<ReplicationNode>();
+ associationsToDettach = new HashSet<String>();
+ dependenciesToDettach = new HashSet<String>();
+ operations = new ArrayList<ReplicationOperationDef>();
if (log.isTraceEnabled()) {
log.trace("new node : " + this);
}
@@ -209,14 +209,14 @@
if (getClass() != obj.getClass()) {
return false;
}
- final ReplicationNode other = (ReplicationNode) obj;
- return this.contract == other.contract;
+ ReplicationNode other = (ReplicationNode) obj;
+ return contract == other.contract;
}
@Override
public int hashCode() {
int hash = 7;
- hash = 37 * hash + (this.contract.hashCode());
+ hash = 37 * hash + contract.hashCode();
return hash;
}
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractReplicationEngineTest.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractReplicationEngineTest.java 2010-03-15 10:57:51 UTC (rev 1843)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractReplicationEngineTest.java 2010-03-17 00:18:04 UTC (rev 1844)
@@ -57,7 +57,7 @@
protected TopiaContextImplementor dstCtxt;
protected TopiaReplicationImplementor service;
protected ReplicationModel model;
- static private boolean init ;
+ static protected boolean init ;
static private Long testsTimeStamp;
static private File testsBasedir;
static private final String TEST_BASEDIR = "target%1$ssurefire-tests%1$s%2$td_%2$tm_%2$tY%1$s%2$tH_%2$tM_%2$tS";
@@ -79,8 +79,13 @@
if (!init) {
I18n.init(Locale.FRANCE);
-
- context = createDb("source");
+
+ try {
+ context = createDb("source");
+ } catch (Exception e) {
+ getLog().error("could not create db source.", e);
+ throw e;
+ }
init = true;
}
@@ -185,7 +190,10 @@
Set<?> detectTypes;
detectTypes = service.detectTypes(getContracts(), entity.getTopiaId());
- assertEquals(expectedCouple.length, detectTypes.size());
+ assertEquals("expected types : "+
+ Arrays.toString(expectedCouple) +
+ " but was "+detectTypes,
+ expectedCouple.length, detectTypes.size());
for (Object o : expectedCouple) {
assertTrue(detectTypes.contains(o));
}
@@ -247,7 +255,10 @@
entity.getClass(), getContracts());
assertNotNull(c);
shell = model.getNode(c.getContract()).getShell();
- assertEquals(expected.length, shell.size());
+ assertEquals(
+ "expected shell : "+ Arrays.toString(expected) + ", but was " +
+ shell, expected.length, shell.size());
+
for (int i = 0, j = expected.length; i < j; i++) {
TopiaEntityEnum type = expected[i];
ReplicationNode node = model.getNode(type.getContract());
@@ -256,9 +267,9 @@
}
}
- protected void detectDependencies(TopiaEntity entity,
- TopiaEntityEnum[]... expected) throws
- TopiaException {
+ protected void detectDependencies(
+ TopiaEntity entity,
+ TopiaEntityEnum[]... expected) throws TopiaException {
createModel(entity);
model.detectAssociations();
@@ -440,7 +451,13 @@
protected void assertDbEquals(TopiaEntityEnum[] contracts, TopiaContextImplementor ctxt, TopiaContextImplementor ctxt2) throws TopiaException {
Set<String> ids = new HashSet<String>();
+ if (getLog().isInfoEnabled()) {
+ getLog().info("will verify db for contracts "+ Arrays.toString(contracts));
+ }
for (TopiaEntityEnum c : contracts) {
+ if (getLog().isDebugEnabled()) {
+ getLog().debug("verify for contract " + c);
+ }
TopiaDAO<? extends TopiaEntity> daoSrc = ctxt.getDAO(c.getContract());
TopiaDAO<? extends TopiaEntity> daoDst = ctxt2.getDAO(c.getContract());
long nbSrc = daoSrc.size();
@@ -452,6 +469,9 @@
Collections.sort(idsDst);
assertEquals(idsSrc, idsDst);
for (String id : idsSrc) {
+ if (getLog().isDebugEnabled()) {
+ getLog().debug("verify for entity " + id);
+ }
TopiaEntity eSrc = daoSrc.findByTopiaId(id);
TopiaEntity eDst = daoDst.findByTopiaId(id);
assertEquals(eSrc, eDst);
@@ -476,6 +496,14 @@
getLog().debug("expected : " + expected + " / actual " + actual);
}
TopiaEntityEnum contract = TopiaEntityHelper.getEntityEnum(expected.getClass(), getContracts());
+ if (contract==null) {
+ // this type of entity in not dealed here...
+ getLog().debug("untested property type " + expected.getClass());
+ return;
+ }
+ Assert.assertNotNull(
+ "contract not found for "+ expected.getClass() + " in " +
+ Arrays.toString(getContracts()), contract);
EntityOperator<TopiaEntity> operator = EntityOperatorStore.getOperator(contract);
List<String> associationProperties = operator.getAssociationProperties();
for (String name : associationProperties) {
1
0
r1843 - trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication
by tchemit@users.nuiton.org 15 Mar '10
by tchemit@users.nuiton.org 15 Mar '10
15 Mar '10
Author: tchemit
Date: 2010-03-15 11:57:51 +0100 (Mon, 15 Mar 2010)
New Revision: 1843
Log:
reformat code (80 car max per line) + remove redundant initializer
Modified:
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractReplicationEngineTest.java
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractReplicationEngineTest.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractReplicationEngineTest.java 2010-03-15 10:55:07 UTC (rev 1842)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractReplicationEngineTest.java 2010-03-15 10:57:51 UTC (rev 1843)
@@ -21,7 +21,6 @@
import java.io.File;
import java.util.*;
-import org.junit.BeforeClass;
import org.nuiton.i18n.I18n;
import org.nuiton.topia.persistence.util.EntityOperator;
import org.nuiton.topia.replication.model.ReplicationModel;
@@ -104,7 +103,7 @@
protected abstract TopiaContext createDb(String name) throws Exception;
protected TopiaContext createReplicateDb(Object contract) throws Exception {
- TopiaContext rootCtxt = (TopiaContextImplementor) createDb2(contract.toString() + dbCounter++);
+ TopiaContext rootCtxt = createDb2(contract.toString() + dbCounter++);
return rootCtxt;
}
@@ -185,7 +184,7 @@
Set<?> detectTypes;
- detectTypes = ((ReplicationEngine) service).detectTypes(getContracts(), entity.getTopiaId());
+ detectTypes = service.detectTypes(getContracts(), entity.getTopiaId());
assertEquals(expectedCouple.length, detectTypes.size());
for (Object o : expectedCouple) {
assertTrue(detectTypes.contains(o));
@@ -197,7 +196,9 @@
assertEquals(shouldExist, operation != null);
}
- protected void detectAssociations(TopiaEntity entity, Object... expectedCouple) throws TopiaException {
+ protected void detectAssociations(TopiaEntity entity,
+ Object... expectedCouple)
+ throws TopiaException {
createModel(entity);
model.detectAssociations();
@@ -208,12 +209,15 @@
TopiaEntityEnum src = (TopiaEntityEnum) expectedCouple[2 * i];
String name = (String) expectedCouple[2 * i + 1];
ReplicationNode nodeSrc = model.getNode(src);
+ assertNotNull("association "+name+" not found", nodeSrc);
assertTrue(nodeSrc.hasAssociation());
assertTrue(nodeSrc.getAssociations().containsKey(name));
}
}
- protected void detectDirectDependencies(TopiaEntity entity, Object... expectedCouple) throws TopiaException {
+ protected void detectDirectDependencies(TopiaEntity entity,
+ Object... expectedCouple)
+ throws TopiaException {
createModel(entity);
model.detectDirectDependencies();
@@ -229,7 +233,9 @@
}
}
- protected void detectShell(TopiaEntity entity, TopiaEntityEnum... expected) throws TopiaException {
+ protected void detectShell(TopiaEntity entity,
+ TopiaEntityEnum... expected) throws
+ TopiaException {
Set<ReplicationNode> shell;
createModel(entity);
@@ -237,7 +243,9 @@
model.detectDirectDependencies();
model.detectShell();
- TopiaEntityEnum c = TopiaEntityHelper.getEntityEnum(entity.getClass(), getContracts());
+ TopiaEntityEnum c = TopiaEntityHelper.getEntityEnum(
+ entity.getClass(), getContracts());
+ assertNotNull(c);
shell = model.getNode(c.getContract()).getShell();
assertEquals(expected.length, shell.size());
for (int i = 0, j = expected.length; i < j; i++) {
@@ -248,7 +256,9 @@
}
}
- protected void detectDependencies(TopiaEntity entity, TopiaEntityEnum[]... expected) throws TopiaException {
+ protected void detectDependencies(TopiaEntity entity,
+ TopiaEntityEnum[]... expected) throws
+ TopiaException {
createModel(entity);
model.detectAssociations();
@@ -349,7 +359,7 @@
getLog().info("==========================================================================");
}
}
- private static int dbCounter = 0;
+ private static int dbCounter;
protected void doReplicate(TopiaEntityEnum contract, TopiaEntity... entity) throws Exception {
1
0
r1842 - trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util
by tchemit@users.nuiton.org 15 Mar '10
by tchemit@users.nuiton.org 15 Mar '10
15 Mar '10
Author: tchemit
Date: 2010-03-15 11:55:07 +0100 (Mon, 15 Mar 2010)
New Revision: 1842
Log:
improve TopiaEntityRefTester + add javadoc
Modified:
trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTesterTest.java
Modified: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java 2010-03-15 10:54:46 UTC (rev 1841)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java 2010-03-15 10:55:07 UTC (rev 1842)
@@ -6,15 +6,15 @@
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaEntityEnum;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.SortedMap;
+import java.util.*;
import static java.util.Map.Entry;
/**
- * A abstract class to help testing {@link TopiaEntityRef}
+ * A abstract class to help testing {@link TopiaEntityRef} as detectes types, or
+ * detects or references.
+ * <p/>
+ * An example of use if given in the test {@link TopiaEntityRefTesterTest}.
*
* @author tchemit <chemit(a)codelutin.com>
* @since 2.3.1
@@ -31,6 +31,8 @@
protected T[] contracts;
+ protected int index;
+
protected T[] getContracts() {
if (contracts == null) {
contracts = getContracts0();
@@ -38,6 +40,7 @@
return contracts;
}
+ /** @return all the {@link TopiaEntityEnum} to be used */
protected abstract T[] getContracts0();
@After
@@ -46,9 +49,92 @@
entry = null;
refs = null;
detected = null;
+ index = 0;
}
+ /**
+ * Creates a new entity with the given {@code topiaId} (will use the {@link
+ * TopiaEntityEnum#getImplementation()} class).
+ *
+ * @param constant the constant defining the entity
+ * @param topiaId the topia to assign
+ * @param <T> the type of entity
+ * @return the new entity
+ * @throws IllegalAccessException if can no access entity constructor
+ * @throws InstantiationException if can no instanciate the entity
+ */
+ protected <T extends TopiaEntity> T newEntity(
+ TopiaEntityEnum constant, String topiaId) throws
+ IllegalAccessException,
+ InstantiationException {
+ Class<? extends TopiaEntity> impl = constant.getImplementation();
+ TopiaEntity topiaEntity = impl.newInstance();
+ topiaEntity.setTopiaId(topiaId);
+ return (T) topiaEntity;
+ }
+ /**
+ * Obtain the reference of an association for a given entity.
+ * <p/>
+ * Example, to obtain the Pet 'pudding' on a Person :
+ * <pre>pet[@topiaId='pudding']</pre>
+ * invoke
+ * <pre>getAssociationRef('pet',pet);</pre>
+ *
+ * @param associationName the name of the association
+ * @param e the required entity
+ * @return the reference of the association
+ */
+ protected String getAssociationRef(String associationName, TopiaEntity e) {
+ return getAssociationRef(associationName, e.getTopiaId());
+ }
+
+ /**
+ * Obtain the reference of an association for a given id.
+ * <p/>
+ * Example to obtain the Pet 'pudding' on a Person :
+ * <pre>pet[@topiaId='pudding']</pre>
+ * invoke
+ * <pre>getAssociationRef('pet','pudding');</pre>
+ *
+ * @param associationName the name of the association
+ * @param e the id
+ * @return the reference of the association
+ */
+ protected String getAssociationRef(String associationName, String e) {
+ String s = String.format(
+ TopiaEntityHelper.ASSOCIATION_PATTERN,
+ associationName,
+ e
+ );
+ return s;
+ }
+
+ /**
+ * Obtain the next entry from the iterator.
+ * <p/>
+ * As a side-effect, it will increment the state {@link #index}.
+ */
+ protected void nextEntry() {
+ if (!itr.hasNext()) {
+ throw new IllegalStateException("no more entry to get...");
+ }
+ entry = itr.next();
+ index = 0;
+ }
+
+ /**
+ * Detects the references from the given {@code entity} which have their
+ * topiaId in the given list of {@code ids}.
+ * <p/>
+ * As a side-effect, it will update the states {@code detected} and set the
+ * iterator {@code itr} to the first position on detected entries.
+ *
+ * @param entity the entity to seek
+ * @param nb the required number of entries
+ * @param ids the ids to seek
+ * @throws TopiaException if any pb while visiting entities
+ */
protected void detectReferences(
TopiaEntity entity, int nb, String... ids) throws TopiaException {
detected = TopiaEntityHelper.detectReferences(
@@ -57,6 +143,18 @@
}
+ /**
+ * Detects the references from the given {@code entity} which have their
+ * topiaId in the given list of {@code ids}.
+ * <p/>
+ * As a side-effect, it will update the states {@code detected} and set the
+ * iterator {@code itr} to the first position on detected entries.
+ *
+ * @param entity the entity to seek
+ * @param nb the required number of entries
+ * @param ids the ids to seek
+ * @throws TopiaException if any pb while visiting entities
+ */
protected void detectReferences(
Collection<? extends TopiaEntity> entity,
int nb, String... ids) throws TopiaException {
@@ -65,10 +163,87 @@
assertDetected(nb);
}
+ /**
+ * Detects the type of entities fro the given {@code data}.
+ *
+ * @param expected the array of expected types
+ * @param data the data to seek
+ * @throws TopiaException if any pb while visiting data
+ */
+ protected void detectTypes(Class<?>[] expected,
+ TopiaEntity... data) throws TopiaException {
+ Set<String> fqns = new HashSet<String>(expected.length);
+ Set<Class<? extends TopiaEntity>> actual = null;
+ for (Class<?> c : expected) {
+ fqns.add(c.getName());
+ }
+ try {
+ actual = TopiaEntityHelper.detectTypes(getContracts(), data);
+ Assert.assertEquals(expected.length, actual.size());
+ for (Class<? extends TopiaEntity> c : actual) {
+ Assert.assertTrue(fqns.contains(c.getName()));
+ }
+ } finally {
+ fqns.clear();
+ if (actual != null) {
+ actual.clear();
+ }
+ }
+ }
+
+ /**
+ * Asserts if the given entry definition is equals to the next entry
+ * references on internal state state {@code entry}.
+ *
+ * @param invoker the invoker of the reference
+ * @param invokerProperty the access path of the reference
+ * @param expected the expected topia entities path to access
+ * reference target
+ */
+ protected void assertNextEntityRef(TopiaEntity invoker,
+ String invokerProperty,
+ TopiaEntity... expected) {
+ assertEntityRef(index, invoker, invokerProperty, expected);
+ index++;
+ }
+
+ /**
+ * Asserts if the given entry definition (of an association) is equals to
+ * the next entry reference on internal state {@code entry}.
+ *
+ * @param invoker the invoker of the reference
+ * @param association the association name
+ * @param id the id of the association ( see {@link
+ * #getAssociationRef(String, TopiaEntity)}
+ * @param expected the expected topia entities path to access reference
+ * target
+ */
+ protected void assertNextAssociationEntityRef(TopiaEntity invoker,
+ String association,
+ String id,
+ TopiaEntity... expected) {
+ String invokerProperty = getAssociationRef(association, id);
+ assertNextEntityRef(invoker, invokerProperty, expected);
+ }
+
+ /**
+ * Asserts if the given entry definition is equals to the reference entry at
+ * position {@code index} on internal state {@code entry}.
+ *
+ * @param index the index of the reference to test in {@code
+ * entry}
+ * @param invoker the invoker of the reference
+ * @param invokerProperty the path of the reference
+ * @param expected th expected topia entities path to access
+ * reference target
+ */
protected void assertEntityRef(int index,
TopiaEntity invoker,
String invokerProperty,
TopiaEntity... expected) {
+ Assert.assertNotNull(refs);
+ Assert.assertTrue("no index [" + index + "] in refs of size " +
+ refs.size(), index < refs.size());
TopiaEntityRef actual = refs.get(index);
Assert.assertEquals(actual.getInvoker(), invoker);
Assert.assertEquals(actual.getInvokerProperty(), invokerProperty);
@@ -80,14 +255,44 @@
}
}
- protected void assertEntry(TopiaEntity expected,
- int nbPath,
- Entry<TopiaEntity, List<TopiaEntityRef>> entry) {
+ /**
+ * Asserts if the given {@code expected} entity is equals to the source of
+ * the internal state {@code entry}.
+ *
+ * @param expected the required source of the entry
+ * @param nbPath the expected number of references of the given entry
+ */
+ protected void assertCurrentEntry(TopiaEntity expected,
+ int nbPath) {
+ assertEntry(expected, nbPath, entry);
+ }
+
+ /**
+ * Asserts if the given {@code entry} has a good source and a good number of
+ * references.
+ *
+ * @param expected the expected entry source
+ * @param nbPath the expected number of reference of the entry
+ * @param entry the entry to test
+ */
+ private void assertEntry(TopiaEntity expected,
+ int nbPath,
+ Entry<TopiaEntity, List<TopiaEntityRef>> entry) {
+ Assert.assertNotNull(entry);
Assert.assertEquals(expected, entry.getKey());
refs = entry.getValue();
Assert.assertEquals(nbPath, refs.size());
}
+ /**
+ * Asserts that the number of detected entries (store in internal state
+ * {@code detected}) is ok.
+ * <p/>
+ * As a side-effect, it will reset the internal state {@code itr} on the
+ * first entry of the {@code detected} list.
+ *
+ * @param size the expected number of detected entries
+ */
protected void assertDetected(int size) {
Assert.assertNotNull(detected);
Assert.assertEquals(size, detected.size());
Modified: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTesterTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTesterTest.java 2010-03-15 10:54:46 UTC (rev 1841)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTesterTest.java 2010-03-15 10:55:07 UTC (rev 1842)
@@ -1,10 +1,12 @@
package org.nuiton.topia.persistence.util;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
import org.junit.Test;
-import org.nuiton.topia.TopiaException;
import org.nuiton.topia.TopiaTestDAOHelper.TopiaTestEntityEnum;
-import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.topia.test.entities.*;
+import org.nuiton.topia.test.entities.Person;
+import org.nuiton.topia.test.entities.Pet;
+import org.nuiton.topia.test.entities.Race;
/**
* Test the {@link TopiaEntityRefTester} on
@@ -17,16 +19,18 @@
*/
public class TopiaEntityRefTesterTest extends TopiaEntityRefTester<TopiaTestEntityEnum> {
+ /** Logger */
+ private static final Log log =
+ LogFactory.getLog(TopiaEntityRefTesterTest.class);
+
private static final String PET1 = "pet1";
+ private static final String PET2 = "pet2";
+
private static final String RACE1 = "race1";
private static final String PERSON1 = "person1";
- private static final String PET2 = "pet2";
-
- protected String PET_REF = "pet[@" + TopiaEntity.TOPIA_ID + "=\"%1$s\"]";
-
@Override
protected TopiaTestEntityEnum[] getContracts0() {
return new TopiaTestEntityEnum[]{
@@ -37,88 +41,90 @@
}
@Test
- public void testPet() throws TopiaException {
+ public void testNoReferences() throws Exception {
- Pet pet = new PetImpl();
- pet.setTopiaId(PET1);
+ Pet pet = newEntity(TopiaTestEntityEnum.Pet, PET1);
detectReferences(pet, 0);
- Race race = new RaceImpl();
- race.setTopiaId(RACE1);
+ Race race = newEntity(TopiaTestEntityEnum.Race, RACE1);
detectReferences(race, 0);
- Person person = new PersonImpl();
- person.setTopiaId(PERSON1);
+ Person person = newEntity(TopiaTestEntityEnum.Person, PERSON1);
- detectReferences(race, 0);
+ detectReferences(person, 0);
+ }
+
+ @Test
+ public void testReferences() throws Exception {
+
+ Pet pet = newEntity(TopiaTestEntityEnum.Pet, PET1);
+ Race race = newEntity(TopiaTestEntityEnum.Race, RACE1);
pet.setRace(race);
+ Person person = newEntity(TopiaTestEntityEnum.Person, PERSON1);
detectReferences(pet, 1, RACE1);
- entry = itr.next();
- assertEntry(race, 1, entry);
- assertEntityRef(0, pet, Pet.RACE, pet, race);
+ nextEntry();
+ assertCurrentEntry(race, 1);
+ assertNextEntityRef(pet, Pet.RACE, pet, race);
pet.setPerson(person);
detectReferences(pet, 2, RACE1, PERSON1);
- entry = itr.next();
- assertEntry(person, 1, entry);
- assertEntityRef(0, pet, Pet.PERSON, pet, person);
+ nextEntry();
+ assertCurrentEntry(person, 1);
+ assertNextEntityRef(pet, Pet.PERSON, pet, person);
- entry = itr.next();
- assertEntry(race, 1, entry);
- assertEntityRef(0, pet, Pet.RACE, pet, race);
+ nextEntry();
+ assertCurrentEntry(race, 1);
+ assertNextEntityRef(pet, Pet.RACE, pet, race);
person.addPet(pet);
detectReferences(person, 1, PET1);
- entry = itr.next();
- assertEntry(pet, 1, entry);
- assertEntityRef(0, person, String.format(PET_REF, PET1), person, pet);
+ nextEntry();
+ assertCurrentEntry(pet, 1);
+ assertNextAssociationEntityRef(person, Person.PET, PET1, person, pet);
- Pet pet2 = new PetImpl();
- pet2.setTopiaId(PET2);
+ Pet pet2 = newEntity(TopiaTestEntityEnum.Pet, PET2);
person.addPet(pet2);
detectReferences(person, 3, PET1, PET2, RACE1);
- entry = itr.next();
- assertEntry(pet, 1, entry);
- assertEntityRef(0, person, String.format(PET_REF, PET1), person, pet);
+ nextEntry();
+ assertCurrentEntry(pet, 1);
+ assertNextAssociationEntityRef(person, Person.PET, PET1, person, pet);
+ nextEntry();
+ assertCurrentEntry(pet2, 1);
+ assertNextAssociationEntityRef(person, Person.PET, PET2, person, pet2);
- entry = itr.next();
- assertEntry(pet2, 1, entry);
- assertEntityRef(0, person, String.format(PET_REF, PET2), person, pet2);
+ nextEntry();
+ assertCurrentEntry(race, 1);
+ assertNextEntityRef(pet, Pet.RACE, person, pet, race);
- entry = itr.next();
- assertEntry(race, 1, entry);
- assertEntityRef(0, pet, Pet.RACE, person, pet, race);
-
pet2.setRace(race);
detectReferences(person, 3, PET1, PET2, RACE1);
- entry = itr.next();
- assertEntry(pet, 1, entry);
- assertEntityRef(0, person, String.format(PET_REF, PET1), person, pet);
+ nextEntry();
+ assertCurrentEntry(pet, 1);
+ assertNextAssociationEntityRef(person, Person.PET, PET1, person, pet);
+ nextEntry();
+ assertCurrentEntry(pet2, 1);
+ assertNextAssociationEntityRef(person, Person.PET, PET2, person, pet2);
- entry = itr.next();
- assertEntry(pet2, 1, entry);
- assertEntityRef(0, person, String.format(PET_REF, PET2), person, pet2);
+ nextEntry();
+ assertCurrentEntry(race, 2);
+ assertNextEntityRef(pet, Pet.RACE, person, pet, race);
+ assertNextEntityRef(pet2, Pet.RACE, person, pet2, race);
- entry = itr.next();
- assertEntry(race, 2, entry);
- assertEntityRef(0, pet, Pet.RACE, person, pet, race);
- assertEntityRef(1, pet2, Pet.RACE, person, pet2, race);
-
}
}
1
0
r1841 - trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util
by tchemit@users.nuiton.org 15 Mar '10
by tchemit@users.nuiton.org 15 Mar '10
15 Mar '10
Author: tchemit
Date: 2010-03-15 11:54:46 +0100 (Mon, 15 Mar 2010)
New Revision: 1841
Log:
improve code + fix NPE when no contract found
Modified:
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityHelper.java
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityHelper.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityHelper.java 2010-03-15 10:53:57 UTC (rev 1840)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityHelper.java 2010-03-15 10:54:46 UTC (rev 1841)
@@ -74,6 +74,12 @@
protected static final Byte ZEROB = 0;
/**
+ * Le pattern d'une reference sur une association
+ */
+ public static final String ASSOCIATION_PATTERN =
+ "%1$s[@" + TopiaEntity.TOPIA_ID + "=\"%2$s\"]";
+
+ /**
*
* @param type the type to test
* @return null object (default value for primitive types)
@@ -425,9 +431,11 @@
}
Class<? extends TopiaEntity> contractClass =
getContractClass(contracts, klass);
- for (TopiaEntityEnum t : contracts) {
- if (t.accept(contractClass)) {
- return t;
+ if (contractClass != null) {
+ for (TopiaEntityEnum t : contracts) {
+ if (t.accept(contractClass)) {
+ return t;
+ }
}
}
return null;
@@ -894,10 +902,15 @@
}
accessorExpression.append(name);
if (index > -1) {
- accessorExpression.append("[@topiaId=\"");
- accessorExpression.append(e.getTopiaId());
- accessorExpression.append("\"]");
+ String association = String.format(
+ ASSOCIATION_PATTERN, "", e.getTopiaId());
+ accessorExpression.append(association);
}
+// if (index > -1) {
+// accessorExpression.append("[@topiaId=\"");
+// accessorExpression.append(e.getTopiaId());
+// accessorExpression.append("\"]");
+// }
if (log.isTraceEnabled()) {
log.trace("add to stack : " + e.getTopiaId() +
", new size : " + path.size() + ", path : " +
1
0
r1840 - trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util
by tchemit@users.nuiton.org 15 Mar '10
by tchemit@users.nuiton.org 15 Mar '10
15 Mar '10
Author: tchemit
Date: 2010-03-15 11:53:57 +0100 (Mon, 15 Mar 2010)
New Revision: 1840
Log:
fix javadoc
Modified:
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/Collector.java
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/Collector.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/Collector.java 2010-03-13 21:49:57 UTC (rev 1839)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/Collector.java 2010-03-15 10:53:57 UTC (rev 1840)
@@ -32,7 +32,7 @@
/**
* Un objet qui permet de parcourir des entites (via un
- * {@link CollectorVisitor})et de collecter des donnees pendant le parcours.
+ * {@link CollectorVisitor}) et de collecter des donnees pendant le parcours.
*
* La classe a un type qui est le type de retour de la methode
* {@link #detect(TopiaEntity...)}.
1
0
r1839 - in trunk/topia-persistence/src: main/java/org/nuiton/topia/persistence/util test/java/org/nuiton/topia/persistence/util
by tchemit@users.nuiton.org 13 Mar '10
by tchemit@users.nuiton.org 13 Mar '10
13 Mar '10
Author: tchemit
Date: 2010-03-13 22:49:57 +0100 (Sat, 13 Mar 2010)
New Revision: 1839
Log:
introduce TopiaEntityRefTester to help test of refs + reformat code
Added:
trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTesterTest.java
Modified:
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityHelper.java
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityHelper.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityHelper.java 2010-03-12 20:15:11 UTC (rev 1838)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityHelper.java 2010-03-13 21:49:57 UTC (rev 1839)
@@ -27,7 +27,6 @@
import org.nuiton.topia.TopiaException;
import org.nuiton.topia.persistence.TopiaDAO;
import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.topia.persistence.util.Collector.CollectorVisitor;
import org.nuiton.util.FileUtil;
import java.io.ByteArrayOutputStream;
@@ -52,6 +51,7 @@
import java.util.TreeMap;
import org.apache.commons.beanutils.MethodUtils;
import org.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.util.ObjectUtil;
/**
* Une classe avec des méthodes utiles sur les entités.
@@ -62,10 +62,15 @@
/** to use log facility, just put in your code: log.info(\"...\"); */
private static final Log log = LogFactory.getLog(TopiaEntityHelper.class);
+
protected static final Integer ZERO = 0;
+
protected static final Float ZEROF = 0f;
+
protected static final Long ZEROL = 0l;
+
protected static final Double ZEROD = 0.;
+
protected static final Byte ZEROB = 0;
/**
@@ -73,7 +78,7 @@
* @param type the type to test
* @return null object (default value for primitive types)
* @deprecated since 2.3.0, prefer use the
- * {@link org.nuiton.util.ObjectUtil#getNullValue(Class)} method
+ * {@link ObjectUtil#getNullValue(Class)} method
*/
@Deprecated
protected static Object getNullValue(Class<?> type) {
@@ -106,7 +111,7 @@
* @return {@code true} if value is null or default value for primitive
* types)
* @deprecated since 2.3.0, prefer use the
- * {@link org.nuiton.util.ObjectUtil#isNullValue(Object)} method
+ * {@link ObjectUtil#isNullValue(Object)} method
*/
@Deprecated
public static boolean isNullValue(Object value) {
@@ -156,7 +161,8 @@
/**
* Récupère une entité qui doit exister à partir de son id.
* <p/>
- * Si l'entité n'existe pas, on déclanche une exception {@link IllegalArgumentException}.
+ * Si l'entité n'existe pas, on déclanche une exception
+ * {@link IllegalArgumentException}.
*
* @param dao la dao pour récupérer la valeur
* @param topiaId l'id de l'entité recherchée
@@ -165,10 +171,13 @@
* @throws TopiaException pour tout pb lors de la récupération de l'entité
* @throws IllegalArgumentException si l'entité n'existe pas.
*/
- public static <E extends TopiaEntity> E getExistingEntity(TopiaDAO<E> dao, String topiaId) throws TopiaException, IllegalArgumentException {
+ public static <E extends TopiaEntity> E getExistingEntity(
+ TopiaDAO<E> dao, String topiaId) throws TopiaException,
+ IllegalArgumentException {
E entity = dao.findByTopiaId(topiaId);
if (entity == null) {
- throw new IllegalArgumentException("could not find entity with topiaId " + topiaId);
+ throw new IllegalArgumentException(
+ "could not find entity with topiaId " + topiaId);
}
return entity;
}
@@ -182,7 +191,8 @@
* @param <E> le type de l'entité
* @return l'entité trouvée, ou <code<null</code< si elle n'est pas trouvée.
*/
- public static <E extends TopiaEntity> E getEntityByTopiaId(Collection<E> entities, String topiaId) {
+ public static <E extends TopiaEntity> E getEntityByTopiaId(
+ Collection<E> entities, String topiaId) {
if (entities != null) {
for (E e : entities) {
if (topiaId.equals(e.getTopiaId())) {
@@ -202,13 +212,16 @@
* @throws IllegalStateException si l'entité n'a pas de topiaId
* @throws NullPointerException si l'entité est null
*/
- public static <E extends TopiaEntity> void checkNotNullAndExistingEntity(String paramName, E bean) throws IllegalStateException, NullPointerException {
+ public static <E extends TopiaEntity> void checkNotNullAndExistingEntity(
+ String paramName, E bean) throws IllegalStateException,
+ NullPointerException {
if (bean == null) {
throw new NullPointerException(paramName + " can not be null");
}
if (bean.getTopiaId() == null) {
// can not create bean here
- throw new IllegalStateException("can not create " + bean.getClass() + " here...");
+ throw new IllegalStateException(
+ "can not create " + bean.getClass() + " here...");
}
}
@@ -221,13 +234,16 @@
* @throws NullPointerException si l'entité est nulle
* @throws IllegalStateException si l'entité possède un topiaId.
*/
- public static <E extends TopiaEntity> void checkNotNullAndNoneExistingEntity(String paramName, E bean) throws NullPointerException, IllegalStateException {
+ public static <E extends TopiaEntity> void checkNotNullAndNoneExistingEntity(
+ String paramName, E bean) throws NullPointerException,
+ IllegalStateException {
if (bean == null) {
throw new NullPointerException(paramName + " can not be null");
}
if (bean.getTopiaId() != null) {
// can not create bean here
- throw new IllegalStateException("can not update " + bean.getClass() + " here...");
+ throw new IllegalStateException(
+ "can not update " + bean.getClass() + " here...");
}
}
@@ -241,7 +257,11 @@
* @throws IOException if any io exception
* @throws NullPointerException if parameters are null
*/
- public static void createDBFromSQL(File dbDirectory, TopiaContext topiaContext, URI resource) throws IOException, TopiaException, NullPointerException {
+ public static void createDBFromSQL(
+ File dbDirectory,
+ TopiaContext topiaContext,
+ URI resource) throws IOException,
+ TopiaException, NullPointerException {
if (dbDirectory == null) {
throw new NullPointerException("dbDirectory can not be null");
}
@@ -255,10 +275,16 @@
File databaseDump;
if (resource.isOpaque()) {
- ByteArrayOutputStream output = FileUtil.readBytesFrom(resource.toURL().openStream(), 8048);
+ ByteArrayOutputStream output =
+ FileUtil.readBytesFrom(resource.toURL().openStream(), 8048);
File tempFile = File.createTempFile("topiaDumpDatabase", ".sql.gz");
- output.writeTo(new FileOutputStream(tempFile));
+ FileOutputStream stream = new FileOutputStream(tempFile);
+ try {
+ output.writeTo(stream);
+ } finally {
+ stream.close();
+ }
tempFile.deleteOnExit();
databaseDump = tempFile;
@@ -298,7 +324,9 @@
* @throws NullPointerException if parameters are null
* @throws IOException if could not create gzipFile container directory
*/
- public static void saveDB(File gzipFile, TopiaContext topiaContext) throws TopiaException, IOException, NullPointerException {
+ public static void saveDB(
+ File gzipFile, TopiaContext topiaContext)
+ throws TopiaException, IOException, NullPointerException {
if (gzipFile == null) {
throw new NullPointerException("gzipFile can not be null");
}
@@ -307,7 +335,8 @@
}
if (!gzipFile.getParentFile().exists()) {
if (!gzipFile.getParentFile().mkdirs()) {
- throw new IOException("could not create directory " + gzipFile.getParentFile());
+ throw new IOException("could not create directory " +
+ gzipFile.getParentFile());
}
}
log.info("store database to [" + gzipFile + "]");
@@ -353,7 +382,9 @@
* @return the list of filtered entities for the given entity type in the list
* @since 2.1.4
*/
- public static List<TopiaEntity> filter(Collection<TopiaEntity> entities, Class<? extends TopiaEntity> filterClass) {
+ public static List<TopiaEntity> filter(
+ Collection<TopiaEntity> entities,
+ Class<? extends TopiaEntity> filterClass) {
List<TopiaEntity> result = new ArrayList<TopiaEntity>();
for (TopiaEntity e : entities) {
if (filterClass.isAssignableFrom(e.getClass())) {
@@ -363,14 +394,19 @@
return result;
}
- public static Class<? extends TopiaEntity> getContractClass(TopiaEntityEnum[] contracts, Class<? extends TopiaEntity> klass) {
+ public static Class<? extends TopiaEntity> getContractClass(
+ TopiaEntityEnum[] contracts,
+ Class<? extends TopiaEntity> klass) {
if (contracts == null || contracts.length == 0) {
// pas de contract connus...
return null;
}
// on recupere l'ensemble des interfaces connues pour la klass donnee
- Set<Class<? extends TopiaEntity>> klassInterfaces = getInterfaces(klass, new HashSet<Class<? extends TopiaEntity>>());
+ Set<Class<? extends TopiaEntity>> klassInterfaces = getInterfaces(
+ klass,
+ new HashSet<Class<? extends TopiaEntity>>()
+ );
for (TopiaEntityEnum contract : contracts) {
Class<? extends TopiaEntity> contractClass = contract.getContract();
@@ -381,12 +417,14 @@
return null;
}
- public static TopiaEntityEnum getEntityEnum(Class<? extends TopiaEntity> klass, TopiaEntityEnum... contracts) {
+ public static TopiaEntityEnum getEntityEnum(
+ Class<? extends TopiaEntity> klass, TopiaEntityEnum... contracts) {
if (contracts == null || contracts.length == 0) {
// pas de contract connus...
return null;
}
- Class<? extends TopiaEntity> contractClass = getContractClass(contracts, klass);
+ Class<? extends TopiaEntity> contractClass =
+ getContractClass(contracts, klass);
for (TopiaEntityEnum t : contracts) {
if (t.accept(contractClass)) {
return t;
@@ -404,10 +442,14 @@
* @return l'ensemble des contrats filtres
* @since 2.2.0
*/
- public static Set<Class<? extends TopiaEntity>> retainContracts(TopiaEntityEnum[] contracts, Set<Class<? extends TopiaEntity>> classes) {
- Map<Class<? extends TopiaEntity>, Class<? extends TopiaEntity>> dico = new HashMap<Class<? extends TopiaEntity>, Class<? extends TopiaEntity>>();
+ public static Set<Class<? extends TopiaEntity>> retainContracts(
+ TopiaEntityEnum[] contracts,
+ Set<Class<? extends TopiaEntity>> classes) {
+ Map<Class<? extends TopiaEntity>, Class<? extends TopiaEntity>> dico;
+ dico = new HashMap<Class<? extends TopiaEntity>, Class<? extends TopiaEntity>>();
try {
- Set<Class<? extends TopiaEntity>> result = new HashSet<Class<? extends TopiaEntity>>();
+ Set<Class<? extends TopiaEntity>> result =
+ new HashSet<Class<? extends TopiaEntity>>();
for (Class<? extends TopiaEntity> c : classes) {
Class<? extends TopiaEntity> contractClass = dico.get(c);
@@ -434,13 +476,15 @@
}
/**
- * Ontenir l'ensemble des contrats d'entites a partir des descriptions d'entites.
+ * Ontenir l'ensemble des contrats d'entites a partir des descriptions
+ * d'entites.
*
* @param contracts les contracts connus
* @return l'ensemble des contrats d'entites
* @since 2.2.0
*/
- public static Class<? extends TopiaEntity>[] getContracts(TopiaEntityEnum[] contracts) {
+ public static Class<? extends TopiaEntity>[] getContracts(
+ TopiaEntityEnum[] contracts) {
Class<?>[] result = new Class<?>[contracts.length];
int index = 0;
for (TopiaEntityEnum e : contracts) {
@@ -461,14 +505,20 @@
*
* @throws TopiaException
*/
- public static Set<Class<? extends TopiaEntity>> detectTypes(final TopiaEntityEnum[] contracts, TopiaEntity... entities) throws TopiaException {
+ public static Set<Class<? extends TopiaEntity>> detectTypes(
+ final TopiaEntityEnum[] contracts,
+ TopiaEntity... entities) throws TopiaException {
- Collector<Set<Class<? extends TopiaEntity>>> collector = new Collector<Set<Class<? extends TopiaEntity>>>(contracts) {
+ Collector<Set<Class<? extends TopiaEntity>>> collector;
+ collector =
+ new Collector<Set<Class<? extends TopiaEntity>>>(contracts) {
+
/**
* La liste des types d'entités détectées
*/
- protected Set<Class<? extends TopiaEntity>> detectedTypes = new HashSet<Class<? extends TopiaEntity>>();
+ protected Set<Class<? extends TopiaEntity>> detectedTypes =
+ new HashSet<Class<? extends TopiaEntity>>();
@Override
protected boolean onStarting(TopiaEntity e) {
@@ -482,8 +532,10 @@
}
@Override
- protected Set<Class<? extends TopiaEntity>> afterAll(CollectorVisitor visitor, TopiaEntity... entities) {
- Set<Class<? extends TopiaEntity>> result = TopiaEntityHelper.retainContracts(contracts, detectedTypes);
+ protected Set<Class<? extends TopiaEntity>> afterAll(
+ CollectorVisitor visitor, TopiaEntity... entities) {
+ Set<Class<? extends TopiaEntity>> result =
+ retainContracts(contracts, detectedTypes);
return result;
}
};
@@ -506,14 +558,19 @@
*
* @throws TopiaException
*/
- public static Map<Class<? extends TopiaEntity>, List<TopiaEntity>> detectEntities(final TopiaEntityEnum[] contracts, final Set<Class<? extends TopiaEntity>> types, TopiaEntity... entities) throws TopiaException {
+ public static Map<Class<? extends TopiaEntity>, List<TopiaEntity>>
+ detectEntities(final TopiaEntityEnum[] contracts,
+ final Set<Class<? extends TopiaEntity>> types,
+ TopiaEntity... entities) throws TopiaException {
- Collector<Map<Class<? extends TopiaEntity>, List<TopiaEntity>>> collector = new Collector<Map<Class<? extends TopiaEntity>, List<TopiaEntity>>>(contracts) {
+ Collector<Map<Class<? extends TopiaEntity>, List<TopiaEntity>>> collector;
+ collector = new Collector<Map<Class<? extends TopiaEntity>, List<TopiaEntity>>>(contracts) {
/**
* le dictionnaire des références détectées indexées par leur type
*/
- protected Map<Class<? extends TopiaEntity>, List<TopiaEntity>> detectedRefs = new HashMap<Class<? extends TopiaEntity>, List<TopiaEntity>>();
+ protected Map<Class<? extends TopiaEntity>, List<TopiaEntity>> detectedRefs =
+ new HashMap<Class<? extends TopiaEntity>, List<TopiaEntity>>();
@Override
protected void onStarted(TopiaEntity e, boolean enter) {
@@ -531,19 +588,21 @@
List<TopiaEntity> refs = detectedRefs.get(entityClass);
if (refs == null) {
- refs = new java.util.ArrayList<TopiaEntity>();
+ refs = new ArrayList<TopiaEntity>();
detectedRefs.put(entityClass, refs);
}
refs.add(e);
}
@Override
- protected Map<Class<? extends TopiaEntity>, List<TopiaEntity>> afterAll(CollectorVisitor visitor, TopiaEntity... entities) {
+ protected Map<Class<? extends TopiaEntity>, List<TopiaEntity>>
+ afterAll(CollectorVisitor visitor, TopiaEntity... entities) {
return detectedRefs;
}
};
- Map<Class<? extends TopiaEntity>, List<TopiaEntity>> result = collector.detect(entities);
+ Map<Class<? extends TopiaEntity>, List<TopiaEntity>> result =
+ collector.detect(entities);
return result;
}
@@ -561,14 +620,19 @@
*
* @throws TopiaException
*/
- public static Map<Class<? extends TopiaEntity>, List<String>> detectEntityIds(final TopiaEntityEnum[] contracts, final Set<Class<? extends TopiaEntity>> types, TopiaEntity... entities) throws TopiaException {
+ public static Map<Class<? extends TopiaEntity>, List<String>>
+ detectEntityIds(final TopiaEntityEnum[] contracts,
+ final Set<Class<? extends TopiaEntity>> types,
+ TopiaEntity... entities) throws TopiaException {
- Collector<Map<Class<? extends TopiaEntity>, List<String>>> collector = new Collector<Map<Class<? extends TopiaEntity>, List<String>>>(contracts) {
+ Collector<Map<Class<? extends TopiaEntity>, List<String>>> collector;
+ collector = new Collector<Map<Class<? extends TopiaEntity>, List<String>>>(contracts) {
/**
* le dictionnaire des références détectées indexées par leur type
*/
- protected Map<Class<? extends TopiaEntity>, List<String>> detectedRefs = new HashMap<Class<? extends TopiaEntity>, List<String>>();
+ protected Map<Class<? extends TopiaEntity>, List<String>> detectedRefs =
+ new HashMap<Class<? extends TopiaEntity>, List<String>>();
@Override
protected void onStarted(TopiaEntity e, boolean enter) {
@@ -593,12 +657,14 @@
}
@Override
- protected Map<Class<? extends TopiaEntity>, List<String>> afterAll(CollectorVisitor visitor, TopiaEntity... entities) {
+ protected Map<Class<? extends TopiaEntity>, List<String>>
+ afterAll(CollectorVisitor visitor, TopiaEntity... entities) {
return detectedRefs;
}
};
- Map<Class<? extends TopiaEntity>, List<String>> result = collector.detect(entities);
+ Map<Class<? extends TopiaEntity>, List<String>> result =
+ collector.detect(entities);
return result;
}
@@ -615,8 +681,12 @@
*
* @see TopiaEntityRef
*/
- public static SortedMap<TopiaEntity, List<TopiaEntityRef>> detectReferences(final TopiaEntityEnum[] contracts, final String[] expressions, TopiaEntity entities) throws TopiaException {
- return detectReferences(contracts, expressions, Collections.singleton(entities));
+ public static SortedMap<TopiaEntity, List<TopiaEntityRef>> detectReferences(
+ TopiaEntityEnum[] contracts,
+ String[] expressions,
+ TopiaEntity entities) throws TopiaException {
+ return detectReferences(contracts, expressions,
+ Collections.singleton(entities));
}
/**
@@ -632,14 +702,25 @@
*
* @see TopiaEntityRef
*/
- public static SortedMap<TopiaEntity, List<TopiaEntityRef>> detectReferences(final TopiaEntityEnum[] contracts, final String[] expressions, Collection<? extends TopiaEntity> entities) throws TopiaException {
+ public static SortedMap<TopiaEntity, List<TopiaEntityRef>>
+ detectReferences(
+ final TopiaEntityEnum[] contracts,
+ final String[] expressions,
+ Collection<? extends TopiaEntity> entities) throws TopiaException {
- Collector<SortedMap<TopiaEntity, List<TopiaEntityRef>>> collector = new Collector<SortedMap<TopiaEntity, List<TopiaEntityRef>>>(contracts) {
+ Collector<SortedMap<TopiaEntity, List<TopiaEntityRef>>> collector;
+ collector = new Collector<SortedMap<TopiaEntity, List<TopiaEntityRef>>>(
+ contracts) {
/** la liste des ids a accepter ou rejecter selon acceptMode */
List<String> ids = Arrays.asList(expressions);
+
/** le dictionnaire des références détectées indexées par leur type */
- SortedMap<TopiaEntity, List<TopiaEntityRef>> refs = new TreeMap<TopiaEntity, List<TopiaEntityRef>>(TopiaEntityHelper.getTopiaIdComparator());
+ SortedMap<TopiaEntity, List<TopiaEntityRef>> refs;{
+ refs = new TreeMap<TopiaEntity, List<TopiaEntityRef>>(
+ getTopiaIdComparator());
+ }
+
/** le path courant depuis le depart */
Deque<TopiaEntity> path = new LinkedList<TopiaEntity>();
StringBuilder accessorExpression = new StringBuilder();
@@ -681,7 +762,9 @@
}
@Override
- protected boolean onVisiting(TopiaEntity e, String name, Class<?> type, Object value) {
+ protected boolean onVisiting(TopiaEntity e,
+ String name,
+ Class<?> type, Object value) {
TopiaEntity e1 = getTopiaValue(value);
if (e1 != null) {
// on est sur une entite
@@ -696,7 +779,8 @@
if (visitor.getAlreadyExplored().contains(e1)) {
boolean contains = visitor.getStack().contains(e1);
if (log.isDebugEnabled()) {
- log.debug("already enter " + e1.getTopiaId() + ", can reenter ? " + !contains);
+ log.debug("already enter " + e1.getTopiaId() +
+ ", can reenter ? " + !contains);
}
if (!contains) {
try {
@@ -718,7 +802,10 @@
}
@Override
- protected void onVisited(TopiaEntity e, String name, Class<?> type, Object value, boolean enter) {
+ protected void onVisited(TopiaEntity e,
+ String name,
+ Class<?> type,
+ Object value, boolean enter) {
super.onVisited(e, name, type, value, enter);
if (enter) {
removePath();
@@ -726,7 +813,11 @@
}
@Override
- protected boolean onVisiting(TopiaEntity e, String name, Class<?> collectionType, Class<?> type, int index, Object value) {
+ protected boolean onVisiting(TopiaEntity e,
+ String name,
+ Class<?> collectionType,
+ Class<?> type,
+ int index, Object value) {
TopiaEntity e1 = getTopiaValue(value);
if (e1 != null) {
addPath(e1, name, index);
@@ -740,7 +831,8 @@
if (visitor.getAlreadyExplored().contains(e1)) {
boolean contains = visitor.getStack().contains(e1);
if (log.isDebugEnabled()) {
- log.debug("already enter " + e1.getTopiaId() + ", can reenter ? " + !contains);
+ log.debug("already enter " + e1.getTopiaId() +
+ ", can reenter ? " + !contains);
}
if (!contains) {
try {
@@ -762,15 +854,21 @@
}
@Override
- protected void onVisited(TopiaEntity e, String name, Class<?> collectionType, Class<?> type, int index, Object value, boolean enter) {
- super.onVisited(e, name, collectionType, type, index, value, enter);
+ protected void onVisited(TopiaEntity e,
+ String name,
+ Class<?> collectionType,
+ Class<?> type,
+ int index, Object value, boolean enter) {
+ super.onVisited(e, name, collectionType, type, index, value,
+ enter);
if (enter) {
removePath();
}
}
@Override
- protected SortedMap<TopiaEntity, List<TopiaEntityRef>> afterAll(CollectorVisitor visitor, TopiaEntity... entities) {
+ protected SortedMap<TopiaEntity, List<TopiaEntityRef>> afterAll(
+ CollectorVisitor visitor, TopiaEntity... entities) {
return refs;
}
@@ -796,10 +894,14 @@
}
accessorExpression.append(name);
if (index > -1) {
- accessorExpression.append("[@topiaId=\"" + e.getTopiaId() + "\"]");
+ accessorExpression.append("[@topiaId=\"");
+ accessorExpression.append(e.getTopiaId());
+ accessorExpression.append("\"]");
}
if (log.isTraceEnabled()) {
- log.trace("add to stack : " + e.getTopiaId() + ", new size : " + path.size() + ", path : " + accessorExpression.toString());
+ log.trace("add to stack : " + e.getTopiaId() +
+ ", new size : " + path.size() + ", path : " +
+ accessorExpression.toString());
}
}
@@ -808,13 +910,17 @@
if (path.isEmpty()) {
accessorExpression.setLength(0);
} else {
- int index = accessorExpression.lastIndexOf(TopiaEntityRef.SEPARATOR);
+ int index = accessorExpression.lastIndexOf(
+ TopiaEntityRef.SEPARATOR);
if (index > -1) {
- accessorExpression.delete(index, accessorExpression.length());
+ accessorExpression.delete(index,
+ accessorExpression.length());
}
}
if (log.isTraceEnabled()) {
- log.trace("remove from stack : " + e.getTopiaId() + ", new size : " + path.size() + ", path : " + accessorExpression.toString());
+ log.trace("remove from stack : " + e.getTopiaId() +
+ ", new size : " + path.size() + ", path : " +
+ accessorExpression.toString());
}
}
@@ -830,18 +936,28 @@
String expression = accessorExpression.toString();
// add the path for the detected
- list.add(new TopiaEntityRef(root, e, expression, path.toArray(new TopiaEntity[path.size()])));
+ list.add(new TopiaEntityRef(
+ root,
+ e,
+ expression,
+ path.toArray(new TopiaEntity[path.size()]))
+ );
if (log.isDebugEnabled()) {
- log.debug(expression + " (" + e.getTopiaId() + ") - " + list.size() + " , root:" + root.getTopiaId());
+ log.debug(expression + " (" + e.getTopiaId() + ") - " +
+ list.size() + " , root:" + root.getTopiaId());
}
if (log.isTraceEnabled()) {
- log.trace(e.getTopiaId() + " : new size " + list.size() + ", path : " + expression);
+ log.trace(e.getTopiaId() + " : new size " + list.size() +
+ ", path : " + expression);
}
}
};
- SortedMap<TopiaEntity, List<TopiaEntityRef>> result = collector.detect(entities.toArray(new TopiaEntity[entities.size()]));
+ SortedMap<TopiaEntity, List<TopiaEntityRef>> result =
+ collector.detect(
+ entities.toArray(new TopiaEntity[entities.size()])
+ );
return result;
}
@@ -851,7 +967,8 @@
* @param entities la liste des entités
* @return la liste des topiaId
*/
- public static List<String> getTopiaIdList(List<? extends TopiaEntity> entities) {
+ public static List<String> getTopiaIdList(
+ List<? extends TopiaEntity> entities) {
List<String> ids = new ArrayList<String>(entities.size());
for (TopiaEntity entity : entities) {
ids.add(entity.getTopiaId());
@@ -860,16 +977,19 @@
}
/**
- * Construit une list d'entite dont les ids sont tous dans la liste d'ids donnee.
+ * Construit une list d'entite dont les ids sont tous dans la liste d'ids
+ * donnee.
+ *
* @param <E> le type des entites de la liste
* @param list la liste a filter
* @param topiaIds la liste des ids a retenir
* @return la nouvelle liste filtree
*/
- public static <E extends TopiaEntity> List<E> retainEntities(List<E> list, List<String> topiaIds) {
+ public static <E extends TopiaEntity> List<E> retainEntities(
+ List<E> list, List<String> topiaIds) {
- List<E> r = new ArrayList<E>(list.size());
- if (list!=null) {
+ List<E> r = new ArrayList<E>(list == null ? 0 : list.size());
+ if (list != null) {
for (E e : list) {
if (topiaIds.contains(e.getTopiaId())) {
r.add(e);
@@ -885,20 +1005,22 @@
* @param <E> le type des entites
* @param referentiel la liste considere comme reference
* @param locale la liste a mettre a jour
- * @return le dictionnaire des etats des entites ajoutees, modifiees ou obsoletes.
+ * @return le dictionnaire des etats des entites ajoutees, modifiees ou
+ * obsoletes.
*
* @see DiffState
* @since 2.2.0
*/
- public static <E extends TopiaEntity> EnumMap<DiffState, List<String>> buildDifferentiel(List<E> referentiel, List<E> locale) {
+ public static <E extends TopiaEntity> EnumMap<DiffState, List<String>>
+ buildDifferentiel(List<E> referentiel, List<E> locale) {
EnumMap<DiffState, List<String>> result = DiffState.newMap();
// construction des deux listes d'id
List<String> referentielIdList = getTopiaIdList(referentiel);
List<String> localeIdList = getTopiaIdList(locale);
- for (int i = 0; i < referentiel.size(); i++) {
- TopiaEntity referentielEntity = referentiel.get(i);
+ for (E aReferentiel : referentiel) {
+ TopiaEntity referentielEntity = aReferentiel;
String refId = referentielEntity.getTopiaId();
if (localeIdList.contains(refId)) {
// id existant sur le storage locale
@@ -913,7 +1035,8 @@
break;
}
}
- boolean wasModified = referentielEntity.getTopiaVersion() > localeEntity.getTopiaVersion();
+ boolean wasModified = referentielEntity.getTopiaVersion() >
+ localeEntity.getTopiaVersion();
if (wasModified) {
result.get(DiffState.MODIFIED).add(refId);
@@ -938,7 +1061,9 @@
return result;
}
- public static Set<Class<? extends TopiaEntity>> getInterfaces(Class<? extends TopiaEntity> klass, Set<Class<? extends TopiaEntity>> klassInterfaces) {
+ public static Set<Class<? extends TopiaEntity>> getInterfaces(
+ Class<? extends TopiaEntity> klass,
+ Set<Class<? extends TopiaEntity>> klassInterfaces) {
if (klassInterfaces.contains(klass)) {
// deja traite
return klassInterfaces;
@@ -955,17 +1080,26 @@
if (interfaces.length > 0) {
// des interfaces detectees, on les ajoutes
for (Class<?> interfac : interfaces) {
- getInterfaces((Class<? extends TopiaEntity>) interfac, klassInterfaces);
+ getInterfaces(
+ (Class<? extends TopiaEntity>) interfac,
+ klassInterfaces
+ );
}
}
- if (klass.getSuperclass() != null && TopiaEntity.class.isAssignableFrom(klass.getSuperclass())) {
- getInterfaces((Class<? extends TopiaEntity>) klass.getSuperclass(), klassInterfaces);
+ if (klass.getSuperclass() != null &&
+ TopiaEntity.class.isAssignableFrom(klass.getSuperclass())) {
+ getInterfaces(
+ (Class<? extends TopiaEntity>) klass.getSuperclass(),
+ klassInterfaces
+ );
}
return klassInterfaces;
}
- protected static void addInterface(Set<Class<? extends TopiaEntity>> interfaces, Class<? extends TopiaEntity> klass) {
+ protected static void addInterface(
+ Set<Class<? extends TopiaEntity>> interfaces,
+ Class<? extends TopiaEntity> klass) {
Iterator<Class<? extends TopiaEntity>> iterator = interfaces.iterator();
for (; iterator.hasNext();) {
Class<? extends TopiaEntity> next = iterator.next();
Added: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java (rev 0)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java 2010-03-13 21:49:57 UTC (rev 1839)
@@ -0,0 +1,96 @@
+package org.nuiton.topia.persistence.util;
+
+import org.junit.After;
+import org.junit.Assert;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.SortedMap;
+
+import static java.util.Map.Entry;
+
+/**
+ * A abstract class to help testing {@link TopiaEntityRef}
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.3.1
+ */
+public abstract class TopiaEntityRefTester<T extends TopiaEntityEnum> {
+
+ protected SortedMap<TopiaEntity, List<TopiaEntityRef>> detected;
+
+ protected Iterator<Entry<TopiaEntity, List<TopiaEntityRef>>> itr;
+
+ protected Entry<TopiaEntity, List<TopiaEntityRef>> entry;
+
+ protected List<TopiaEntityRef> refs;
+
+ protected T[] contracts;
+
+ protected T[] getContracts() {
+ if (contracts == null) {
+ contracts = getContracts0();
+ }
+ return contracts;
+ }
+
+ protected abstract T[] getContracts0();
+
+ @After
+ public void after() {
+ itr = null;
+ entry = null;
+ refs = null;
+ detected = null;
+ }
+
+
+ protected void detectReferences(
+ TopiaEntity entity, int nb, String... ids) throws TopiaException {
+ detected = TopiaEntityHelper.detectReferences(
+ getContracts(), ids, entity);
+ assertDetected(nb);
+
+ }
+
+ protected void detectReferences(
+ Collection<? extends TopiaEntity> entity,
+ int nb, String... ids) throws TopiaException {
+ detected = TopiaEntityHelper.detectReferences(
+ getContracts(), ids, entity);
+ assertDetected(nb);
+ }
+
+ protected void assertEntityRef(int index,
+ TopiaEntity invoker,
+ String invokerProperty,
+ TopiaEntity... expected) {
+ TopiaEntityRef actual = refs.get(index);
+ Assert.assertEquals(actual.getInvoker(), invoker);
+ Assert.assertEquals(actual.getInvokerProperty(), invokerProperty);
+
+ TopiaEntity[] path = actual.getPath();
+ Assert.assertEquals(expected.length, path.length);
+ for (int i = 0; i < expected.length; i++) {
+ Assert.assertEquals(expected[i].getTopiaId(), path[i].getTopiaId());
+ }
+ }
+
+ protected void assertEntry(TopiaEntity expected,
+ int nbPath,
+ Entry<TopiaEntity, List<TopiaEntityRef>> entry) {
+ Assert.assertEquals(expected, entry.getKey());
+ refs = entry.getValue();
+ Assert.assertEquals(nbPath, refs.size());
+ }
+
+ protected void assertDetected(int size) {
+ Assert.assertNotNull(detected);
+ Assert.assertEquals(size, detected.size());
+ itr = detected.entrySet().iterator();
+ }
+}
Property changes on: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java
___________________________________________________________________
Added: svn:keywords
+ "Author Date Id Revision HeadURL
Added: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTesterTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTesterTest.java (rev 0)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTesterTest.java 2010-03-13 21:49:57 UTC (rev 1839)
@@ -0,0 +1,124 @@
+package org.nuiton.topia.persistence.util;
+
+import org.junit.Test;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaTestDAOHelper.TopiaTestEntityEnum;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.test.entities.*;
+
+/**
+ * Test the {@link TopiaEntityRefTester} on
+ * <p/>
+ * <ul> <li>{@link Pet}</li> <li>{@link Race}</li> <li>{@link Person}</li>
+ * </ul>
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.3.1
+ */
+public class TopiaEntityRefTesterTest extends TopiaEntityRefTester<TopiaTestEntityEnum> {
+
+ private static final String PET1 = "pet1";
+
+ private static final String RACE1 = "race1";
+
+ private static final String PERSON1 = "person1";
+
+ private static final String PET2 = "pet2";
+
+ protected String PET_REF = "pet[@" + TopiaEntity.TOPIA_ID + "=\"%1$s\"]";
+
+ @Override
+ protected TopiaTestEntityEnum[] getContracts0() {
+ return new TopiaTestEntityEnum[]{
+ TopiaTestEntityEnum.Pet,
+ TopiaTestEntityEnum.Person,
+ TopiaTestEntityEnum.Race,
+ };
+ }
+
+ @Test
+ public void testPet() throws TopiaException {
+
+ Pet pet = new PetImpl();
+ pet.setTopiaId(PET1);
+
+ detectReferences(pet, 0);
+
+ Race race = new RaceImpl();
+ race.setTopiaId(RACE1);
+
+ detectReferences(race, 0);
+
+ Person person = new PersonImpl();
+ person.setTopiaId(PERSON1);
+
+ detectReferences(race, 0);
+
+ pet.setRace(race);
+
+ detectReferences(pet, 1, RACE1);
+
+ entry = itr.next();
+ assertEntry(race, 1, entry);
+ assertEntityRef(0, pet, Pet.RACE, pet, race);
+
+ pet.setPerson(person);
+
+ detectReferences(pet, 2, RACE1, PERSON1);
+
+ entry = itr.next();
+ assertEntry(person, 1, entry);
+ assertEntityRef(0, pet, Pet.PERSON, pet, person);
+
+ entry = itr.next();
+ assertEntry(race, 1, entry);
+ assertEntityRef(0, pet, Pet.RACE, pet, race);
+
+ person.addPet(pet);
+
+ detectReferences(person, 1, PET1);
+
+ entry = itr.next();
+ assertEntry(pet, 1, entry);
+ assertEntityRef(0, person, String.format(PET_REF, PET1), person, pet);
+
+ Pet pet2 = new PetImpl();
+ pet2.setTopiaId(PET2);
+
+ person.addPet(pet2);
+
+ detectReferences(person, 3, PET1, PET2, RACE1);
+
+ entry = itr.next();
+ assertEntry(pet, 1, entry);
+ assertEntityRef(0, person, String.format(PET_REF, PET1), person, pet);
+
+
+ entry = itr.next();
+ assertEntry(pet2, 1, entry);
+ assertEntityRef(0, person, String.format(PET_REF, PET2), person, pet2);
+
+ entry = itr.next();
+ assertEntry(race, 1, entry);
+ assertEntityRef(0, pet, Pet.RACE, person, pet, race);
+
+ pet2.setRace(race);
+
+ detectReferences(person, 3, PET1, PET2, RACE1);
+
+ entry = itr.next();
+ assertEntry(pet, 1, entry);
+ assertEntityRef(0, person, String.format(PET_REF, PET1), person, pet);
+
+
+ entry = itr.next();
+ assertEntry(pet2, 1, entry);
+ assertEntityRef(0, person, String.format(PET_REF, PET2), person, pet2);
+
+ entry = itr.next();
+ assertEntry(race, 2, entry);
+ assertEntityRef(0, pet, Pet.RACE, person, pet, race);
+ assertEntityRef(1, pet2, Pet.RACE, person, pet2, race);
+
+ }
+}
Property changes on: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTesterTest.java
___________________________________________________________________
Added: svn:keywords
+ "Author Date Id Revision HeadURL
1
0
Author: tchemit
Date: 2010-03-12 21:15:11 +0100 (Fri, 12 Mar 2010)
New Revision: 1838
Log:
Utilisation de mavenpom4redmine 2.0.6
Modified:
trunk/pom.xml
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2010-03-11 15:53:22 UTC (rev 1837)
+++ trunk/pom.xml 2010-03-12 20:15:11 UTC (rev 1838)
@@ -9,7 +9,7 @@
<parent>
<groupId>org.nuiton</groupId>
<artifactId>mavenpom4redmine</artifactId>
- <version>2.0.5</version>
+ <version>2.0.6</version>
</parent>
<artifactId>topia</artifactId>
1
0
r1837 - in trunk: . topia-service-index/src/main/java/org/nuiton/topia/index
by echatellier@users.nuiton.org 11 Mar '10
by echatellier@users.nuiton.org 11 Mar '10
11 Mar '10
Author: echatellier
Date: 2010-03-11 16:53:22 +0100 (Thu, 11 Mar 2010)
New Revision: 1837
Log:
Update to lucene 3 (not very usefull, but fix some deprecated warning)
Modified:
trunk/pom.xml
trunk/topia-service-index/src/main/java/org/nuiton/topia/index/LuceneIndexer.java
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2010-03-11 15:49:44 UTC (rev 1836)
+++ trunk/pom.xml 2010-03-11 15:53:22 UTC (rev 1837)
@@ -158,11 +158,10 @@
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
- <version>2.4.1</version>
+ <version>3.0.1</version>
<scope>compile</scope>
</dependency>
-
</dependencies>
</dependencyManagement>
Modified: trunk/topia-service-index/src/main/java/org/nuiton/topia/index/LuceneIndexer.java
===================================================================
--- trunk/topia-service-index/src/main/java/org/nuiton/topia/index/LuceneIndexer.java 2010-03-11 15:49:44 UTC (rev 1836)
+++ trunk/topia-service-index/src/main/java/org/nuiton/topia/index/LuceneIndexer.java 2010-03-11 15:53:22 UTC (rev 1837)
@@ -45,20 +45,26 @@
import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
+import org.apache.lucene.document.Field.Index;
+import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
-import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
+import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Searcher;
+import org.apache.lucene.search.TopDocs;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.NIOFSDirectory;
+import org.apache.lucene.util.Version;
+import org.hibernate.HibernateException;
+import org.hibernate.metadata.ClassMetadata;
import org.nuiton.topia.TopiaNotFoundException;
import org.nuiton.topia.framework.TopiaContextImplementor;
import org.nuiton.topia.persistence.TopiaId;
-import org.hibernate.HibernateException;
-import org.hibernate.metadata.ClassMetadata;
/**
* To use this indexer you must have two properties defined in config file:
@@ -81,21 +87,19 @@
*/
public class LuceneIndexer implements TopiaIndexImplementor {
- private static final String TOPIA_ID = "topiaId";
/** to use log facility, just put in your code: log.info(\"...\"); */
static private Log log = LogFactory.getLog(LuceneIndexer.class);
+
+ private static final String TOPIA_ID = "topiaId";
+
protected File directory = null;
+
protected TopiaContextImplementor context;
+
/** contient les objets a reindexer car creer, modifier ou supprimer. key: id, value: fields values or null for deletion */
protected Map<Object, Object[]> indexationMap = new HashMap<Object, Object[]>();
- /**
- *
- */
- public LuceneIndexer() {
- }
-
- /* (non-Javadoc)
+ /*
* @see org.nuiton.topia.framework.TopiaService#getServiceName()
*/
@Override
@@ -103,7 +107,7 @@
return TopiaIndexService.SERVICE_NAME;
}
- /* (non-Javadoc)
+ /*
* @see org.nuiton.topia.framework.TopiaService#getPersistenceClasses()
*/
@Override
@@ -120,7 +124,7 @@
}
}
- /* (non-Javadoc)
+ /*
* @see org.nuiton.topia.framework.TopiaService#init(org.nuiton.topia.framework.TopiaContextImplementor)
*/
@Override
@@ -135,7 +139,7 @@
String dirname = prop.getProperty("topia.index.lucene.directory");
directory = new File(dirname);
directory.mkdirs();
-
+
return true;
}
@@ -146,13 +150,18 @@
@Override
public void doIndexation() {
+
try {
+ Directory indexDirectory = new NIOFSDirectory(directory);
+ // TODO maybe put in configuration to allow localized analysers
+ Analyzer analyzer = new SimpleAnalyzer();
+
boolean create = false;
- if (!IndexReader.indexExists(directory)) {
+ if (!IndexReader.indexExists(indexDirectory)) {
// si l'index n'existe pas, on force la creation
create = true;
} else {
- IndexReader reader = IndexReader.open(directory);
+ IndexReader reader = IndexReader.open(indexDirectory);
for (Map.Entry<Object, Object[]> e : indexationMap.entrySet()) {
String id = e.getKey().toString();
@@ -161,7 +170,7 @@
reader.close();
}
- IndexWriter writer = new IndexWriter(directory, new SimpleAnalyzer(), create);
+ IndexWriter writer = new IndexWriter(indexDirectory, analyzer, create, IndexWriter.MaxFieldLength.LIMITED);
for (Map.Entry<Object, Object[]> e : indexationMap.entrySet()) {
String id = e.getKey().toString();
Object[] fields = e.getValue();
@@ -209,8 +218,9 @@
String[] names = cm.getPropertyNames();
org.apache.lucene.document.Document doc = new org.apache.lucene.document.Document();
- doc.add(new Field("class", classname, Field.Store.YES, Field.Index.TOKENIZED));
- doc.add(new Field("topiaId", id, Field.Store.YES, Field.Index.TOKENIZED));
+
+ doc.add(new Field("class", classname, Store.YES, Index.ANALYZED));
+ doc.add(new Field("topiaId", id, Store.YES, Index.ANALYZED));
StringBuffer all = new StringBuffer();
for (int i = 0; i < fields.length; i++) {
String name = names[i];
@@ -220,13 +230,13 @@
// do nothing
} else {
String val = String.valueOf(o);
- doc.add(new Field(name, val, Field.Store.YES, Field.Index.TOKENIZED));
+ doc.add(new Field(name, val, Store.YES, Index.ANALYZED));
all.append(val);
all.append(" ");
}
}
if (all.length() > 0) {
- doc.add(new Field("__all__", all.toString(), Field.Store.NO, Field.Index.TOKENIZED));
+ doc.add(new Field("__all__", all.toString(), Field.Store.NO, Index.ANALYZED));
}
writer.addDocument(doc);
}
@@ -241,48 +251,57 @@
}
public SortedSet<IndexEntry> search(String queryText) {
- Hits hits = null;
- if (IndexReader.indexExists(directory)) {
- try {
- Searcher searcher = new IndexSearcher(directory.getAbsolutePath());
- Analyzer analyzer = new SimpleAnalyzer();
+ TopDocs topDocs = null;
+ Searcher searcher = null;
+ try {
+
+ Directory indexDirectory = new NIOFSDirectory(directory);
+ // TODO maybe put in configuration to allow localized analysers
+ Analyzer analyzer = new SimpleAnalyzer();
+
+ if (IndexReader.indexExists(indexDirectory)) {
+ searcher = new IndexSearcher(indexDirectory);
+
if (queryText.equals("") || queryText.length() == 0) {
// la chaine passée en parametre est vide !
log.debug("requete vide, pas de resultat a renvoyer.");
} else {
- QueryParser parser = new QueryParser("__all__", analyzer);
+ QueryParser parser = new QueryParser(Version.LUCENE_30, "__all__", analyzer);
Query luceneQuery = parser.parse(queryText);
if (log.isDebugEnabled()) {
log.debug("Recherche du terme : " + luceneQuery.toString());
}
- hits = searcher.search(luceneQuery);
+
+ // TODO improve doc collectors using
+ topDocs = searcher.search(luceneQuery, null /*filter*/, 100);
searcher.close();
}
- } catch (IOException ioe) {
+ } else {
+ // l'index n'a pas encore ete créé !
if (log.isDebugEnabled()) {
- log.debug(ioe.getMessage(), ioe);
+ log.debug("Index inexistant, pas de resultats à renvoyer !");
}
- } catch (ParseException pe) {
- if (log.isDebugEnabled()) {
- log.debug(pe.getMessage(), pe);
- }
}
- } else {
- // l'index n'a pas encore ete créé !
+ } catch (IOException ioe) {
if (log.isDebugEnabled()) {
- log.debug("Index inexistant, pas de resultats à renvoyer !");
+ log.debug(ioe.getMessage(), ioe);
}
+ } catch (ParseException pe) {
+ if (log.isDebugEnabled()) {
+ log.debug(pe.getMessage(), pe);
+ }
}
+
//retourne les resultats trouves
TreeSet<IndexEntry> result = new TreeSet<IndexEntry>();
- if (hits != null) {
- for (int i = 0; i < hits.length(); i++) {
+ if (searcher != null && topDocs != null) {
+ ScoreDoc[] scoreDocs = topDocs.scoreDocs;
+ for (ScoreDoc scoreDoc : scoreDocs) {
try {
- float score = hits.score(i);
- Document doc = hits.doc(i);
+ Document doc = searcher.doc(scoreDoc.doc);
String topiaId = doc.get(TOPIA_ID);
- IndexEntry ie = new IndexEntry(score, topiaId);
+ IndexEntry ie = new IndexEntry(scoreDoc.score, topiaId);
result.add(ie);
} catch (IOException eee) {
if (log.isWarnEnabled()) {
@@ -331,5 +350,3 @@
return result;
}
}
-
-
1
0
Author: echatellier
Date: 2010-03-11 16:49:44 +0100 (Thu, 11 Mar 2010)
New Revision: 1836
Log:
Update h2 to 1.2.128 (test fails with 1.2.131)
Modified:
trunk/pom.xml
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2010-03-11 15:04:36 UTC (rev 1835)
+++ trunk/pom.xml 2010-03-11 15:49:44 UTC (rev 1836)
@@ -136,7 +136,7 @@
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
- <version>1.1.119</version>
+ <version>1.2.128</version>
<scope>test</scope>
</dependency>
1
0