Author: fdesbois Date: 2010-05-20 12:41:48 +0200 (Thu, 20 May 2010) New Revision: 1964 Url: http://nuiton.org/repositories/revision/topia/1964 Log: Remove method with Id instead of TopiaId. The methods with TopiaId is no longer deprecated. Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContext.java trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaContextImpl.java trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaQuery.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/BeanTransformer.java 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 trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntity.java trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntityAbstract.java trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityHelper.java trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityRef.java trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaTestCase.java trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/ExportXMLVisitor.java trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/EntityOperatorTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityBinderTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/DeleteEntityTest.java trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/ReplicationEngine.java trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachAssociation.java trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachDependency.java trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachLink.java trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractReplicationEngineTest.java trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/ReplicationEngineTest.java trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java trunk/topia-service-security/src/main/java/org/nuiton/topia/security/TopiaSecurityServiceImpl.java trunk/topia-service-security/src/main/java/org/nuiton/topia/security/jaas/TopiaLoginModule.java trunk/topia-service-security/src/main/java/org/nuiton/topia/security/listener/EntityVetoable.java trunk/topia-service-security/src/main/java/org/nuiton/topia/security/listener/PropertyReadListener.java trunk/topia-service-security/src/main/java/org/nuiton/topia/security/listener/PropertyWriteListener.java trunk/topia-service-security/src/main/java/org/nuiton/topia/security/util/TopiaSecurityFactoryFilter.java trunk/topia-service-security/src/main/java/org/nuiton/topia/taas/TaasService.java trunk/topia-service-security/src/main/java/org/nuiton/topia/taas/event/TaasEntityVetoable.java trunk/topia-service-security/src/main/java/org/nuiton/topia/taas/event/TaasEntityVetoableRequestPermission.java trunk/topia-service-security/src/test/java/org/nuiton/topia/security/TopiaSecurityTest.java Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContext.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContext.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContext.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -42,7 +42,7 @@ /** * TODO-FD20100507 : Need javadoc + translate the one on methods. - * + * <p/> * Created: 3 janv. 2006 21:18:34 * * @author poussin <poussin@codelutin.com> @@ -52,6 +52,7 @@ public interface TopiaContext { /* Adders */ + void addTopiaEntityListener(TopiaEntityListener listener); void addTopiaEntityListener( @@ -75,6 +76,7 @@ void addTopiaEntitiesVetoable(TopiaEntitiesVetoable vetoable); /* Removers */ + void removeTopiaEntityListener(TopiaEntityListener listener); void removeTopiaEntityListener( @@ -100,7 +102,7 @@ /** * Return true if specific service is available. * - * @param <E> type of service + * @param <E> type of service * @param interfaceService fqn of the service * @return the service */ @@ -111,7 +113,7 @@ * Return the service. This service must be valid with public static final * SERVICE_NAME property. * - * @param <E> type of service + * @param <E> type of service * @param interfaceService class of the service * @return the service * @throws TopiaNotFoundException if service can't be retrieved @@ -142,7 +144,7 @@ /** * Return a new context containing his own transaction. - * + * * @return new context with transaction * @throws TopiaException if any exception */ @@ -163,24 +165,13 @@ void rollbackTransaction() throws TopiaException; /** - * Permet de rechercher un entite directement par son TopiaId. - * - * @param topiaId l'id de l'entite recherche - * @return l'entite trouvee (ou null si non trouve) - * @throws TopiaException if any exception - * @deprecated since 2.4, use {@link #findById(String)} instead - */ - @Deprecated - TopiaEntity findByTopiaId(String topiaId) throws TopiaException; - - /** * Retrieve {@link TopiaEntity} using its unique {@code id}. * - * @param id unique identifier of the entity in all the application. + * @param topiaId unique identifier of the entity in all the application. * @return the entity found or null if not * @throws TopiaException for errors on retrieving the entity */ - TopiaEntity findById(String id) throws TopiaException; + TopiaEntity findByTopiaId(String topiaId) throws TopiaException; /** * Permet de faire une requete HQL hibernate directement sur la base. @@ -193,9 +184,9 @@ List find(String hql, Object... args) throws TopiaException; /** - * Permet de faire une requete HQL hibernate directement sur la base - * en precisant la fenetre des elements a remonter avec les parametres - * {@code startIndex} et {@code endIndex}. + * Permet de faire une requete HQL hibernate directement sur la base en + * precisant la fenetre des elements a remonter avec les parametres {@code + * startIndex} et {@code endIndex}. * * @param hql la requete a faire * @param startIndex la position du premier element a remonter @@ -218,8 +209,8 @@ int execute(String hql, Object... args) throws TopiaException; /** - * Permet d'ajouter dans le TopiaContext une TopiaEntity créé par un - * autre context. + * Permet d'ajouter dans le TopiaContext une TopiaEntity créé par un autre + * context. * * @param e l'entity a ajouter * @throws TopiaException if any exception @@ -241,10 +232,10 @@ * alors on duplique toutes les entités de la base. * * @param xml le flux XML dans lequel il faut ecrire - * @param entityAndCondition paramètre qui vont par deux, qui represente - * la classe de l'entity a exporter et la - * condition where que doit respecter l'objet - * pour etre exporter (entityClass, condition) + * @param entityAndCondition paramètre qui vont par deux, qui represente la + * classe de l'entity a exporter et la condition + * where que doit respecter l'objet pour etre + * exporter (entityClass, condition) * @throws TopiaException si une erreur survient durant l'export */ void exportXML(Writer xml, Object... entityAndCondition) @@ -259,19 +250,18 @@ * <p/> * <b>Note 2:</b> Il se peut que la replication simple ne soit pas * suffisante (par example si l'on veut repliquer q'une partie d'une - * entité), on utilisera donc la seconde méthode - * {@link #replicateEntities(TopiaContext, List)}. + * entité), on utilisera donc la seconde méthode {@link + * #replicateEntities(TopiaContext, List)}. * * @param dstCtxt le context de la base destination - * @param entityAndCondition paramètre qui vont par deux, qui represente - * la classe de l'entity a exporter et la - * condition where que doit - * respecter l'objet pour etre exporter - * (entityClass, condition) + * @param entityAndCondition paramètre qui vont par deux, qui represente la + * classe de l'entity a exporter et la condition + * where que doit respecter l'objet pour etre + * exporter (entityClass, condition) * @throws TopiaException si une erreur pendant la duplication - * @throws IllegalArgumentException si l'un des context n'est pas ouvert, - * ou si on essaye de dupliquer dans la - * même base. + * @throws IllegalArgumentException si l'un des context n'est pas ouvert, ou + * si on essaye de dupliquer dans la même + * base. */ void replicate(TopiaContext dstCtxt, Object... entityAndCondition) throws TopiaException, IllegalArgumentException; @@ -283,9 +273,9 @@ * @param entity l'entité à répliquer * @param <T> le type des entités à répliquer * @throws TopiaException si une erreur pendant la duplication - * @throws IllegalArgumentException si l'un des context n'est pas ouvert, - * ou si on essaye de dupliquer dans la - * même base. + * @throws IllegalArgumentException si l'un des context n'est pas ouvert, ou + * si on essaye de dupliquer dans la même + * base. */ <T extends TopiaEntity> void replicateEntity(TopiaContext dstCtxt, T entity) throws TopiaException, IllegalArgumentException; @@ -297,9 +287,9 @@ * @param entities les entités à répliquer * @param <T> le type des entités à répliquer * @throws TopiaException si une erreur pendant la duplication - * @throws IllegalArgumentException si l'un des context n'est pas ouvert, - * ou si on essaye de dupliquer dans - * la même base. + * @throws IllegalArgumentException si l'un des context n'est pas ouvert, ou + * si on essaye de dupliquer dans la même + * base. */ <T extends TopiaEntity> void replicateEntities(TopiaContext dstCtxt, List<T> entities) @@ -307,8 +297,8 @@ /** * Sauve la base de données dans un format natif a la base, la - * representation n'est pas portable d'une base a l'autre. Cette methode - * ne doit être utilisé que pour un stockage temporaire utile à une + * representation n'est pas portable d'une base a l'autre. Cette methode ne + * doit être utilisé que pour un stockage temporaire utile à une * application. * * @param file le nom du fichier ou stocker les informations @@ -320,8 +310,8 @@ /** * Supprime toutes les tables et autres elements de la database. * - * @param dropDatabase si vrai alors supprime aussi la base de données - * si la base utilise des fichiers les fichiers seront + * @param dropDatabase si vrai alors supprime aussi la base de données si la + * base utilise des fichiers les fichiers seront * supprimé (ex: h2) ou sera fait sur la base * (postgresql) * @throws TopiaException if any exception Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaContextImpl.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaContextImpl.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaContextImpl.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -457,6 +457,7 @@ /* (non-Javadoc) * @see org.nuiton.topia.TopiaContext#createSchema() */ + @Override public void updateSchema() throws TopiaException { try { @@ -644,7 +645,7 @@ // TOPIA_PERSISTENCE_PROPERTIES_FILE in config. Properties propertiesFromClasspath = TopiaUtil.getProperties(getConfig(). - getProperty(TOPIA_PERSISTENCE_PROPERTIES_FILE)); + getProperty(TOPIA_PERSISTENCE_PROPERTIES_FILE)); if (!propertiesFromClasspath.isEmpty()) { if (log.isDebugEnabled()) { @@ -906,25 +907,16 @@ /* -------------------- GLOBAL OPERATIONS ON SCHEMA ----------------------*/ - /* (non-Javadoc) - * @see TopiaContext#findByTopiaId(java.lang.String) - */ @Override - public TopiaEntity findByTopiaId(String topiaId) throws TopiaException { - TopiaEntity result = findById(topiaId); - return result; - } - - @Override - public TopiaEntity findById(String id) throws TopiaException { + public TopiaEntity findByTopiaId(String id) throws TopiaException { checkClosed(I18n._( "topia.persistence.error.unsupported.operation.on.closed.context", "findById")); Class<TopiaEntity> entityClass = TopiaId.getClassName(id); TopiaDAO<TopiaEntity> dao = getDAO(entityClass); - TopiaEntity result = dao.findById(id); + TopiaEntity result = dao.findByTopiaId(id); return result; } @@ -1018,13 +1010,14 @@ /* (non-Javadoc) * @see org.nuiton.topia.TopiaContext#add(org.nuiton.topia.persistence.TopiaEntity) */ + @Override public void add(TopiaEntity e) throws TopiaException { checkClosed(I18n._( "topia.persistence.error.unsupported.operation.on.closed.context", "add")); - String id = e.getId(); + String id = e.getTopiaId(); Class<TopiaEntity> entityClass = TopiaId.getClassName(id); TopiaDAO<TopiaEntity> dao = getDAO(entityClass); dao.update(e); Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaQuery.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaQuery.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaQuery.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -225,8 +225,8 @@ * @version $Revision$ * @since 2.3.0 * <p/> - * Mise a jour: $Date$ par - * : $Author$ + * Mise a jour: $Date$ + * par : $Author$ */ public class TopiaQuery { @@ -1004,7 +1004,7 @@ TopiaContext transaction, Class<E> entityClass) throws TopiaException, ClassCastException { return executeToEntityMap(transaction, entityClass, - TopiaEntity.ID, String.class); + TopiaEntity.TOPIA_ID, String.class); } /** Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/BeanTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/BeanTransformer.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/BeanTransformer.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -26,20 +26,27 @@ package org.nuiton.topia.generator; import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.nuiton.eugene.GeneratorUtil; import org.nuiton.eugene.java.ObjectModelTransformerToJava; -import org.nuiton.eugene.models.object.*; +import org.nuiton.eugene.models.object.ObjectModelAttribute; +import org.nuiton.eugene.models.object.ObjectModelClass; +import org.nuiton.eugene.models.object.ObjectModelDependency; +import org.nuiton.eugene.models.object.ObjectModelInterface; +import org.nuiton.eugene.models.object.ObjectModelModifier; +import org.nuiton.eugene.models.object.ObjectModelOperation; +import org.nuiton.eugene.models.object.ObjectModelParameter; +import org.nuiton.topia.persistence.TopiaEntity; import java.util.Collection; import java.util.Iterator; import java.util.List; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.persistence.TopiaEntity; /*{generator option: parentheses = false}*/ /*{generator option: writeString = +}*/ + /** * BeanTransformer * <p/> @@ -74,7 +81,7 @@ boolean hasOperations = !clazz.getAllOtherOperations(true).isEmpty() || !clazz.getOperations().isEmpty(); // Generate the Impl class if not already exist in classpath and no operation is defined in model - if(getClass().getResource(resourceName) == null && !hasOperations) { + if (getClass().getResource(resourceName) == null && !hasOperations) { String implName = clazz.getName() + "Impl"; ObjectModelClass resultClassImpl = createClass(implName, clazz.getPackageName()); // set the abstract resulClass as the resultClassImpl super class @@ -84,7 +91,7 @@ } else { resultClass = createClass(clazz.getName(), clazz.getPackageName()); } - + List<ObjectModelAttribute> attributes = (List<ObjectModelAttribute>) clazz.getAttributes(); createForDTO(resultClass, clazz, attributes); @@ -138,35 +145,35 @@ // Set Value ObjectModelOperation setValue = addOperation(resultClass, "set" + attrNameCapitalized, - "void", ObjectModelModifier.PUBLIC); + "void", ObjectModelModifier.PUBLIC); addParameter(setValue, "int", "index"); addParameter(setValue, attrType, "value"); addException(setValue, "java.lang.ArrayIndexOutOfBoundsException"); setOperationBody(setValue, "" - /*{ - if (index >= <%=maxSize%> || index < 0) { - throw new ArrayIndexOutOfBoundsException("Wrong index [" + index + "] for array <%=attrName%>," + - "index must be between 0 and <%=maxSizeMoinsUn%>"); - } - <%=simpleType%>[] oldValue = get<%=attrNameCapitalized%>(); - this.<%=attrName%>[index] = value; - firePropertyChange("<%=attrName%>", oldValue, this.<%=attrName%>); - }*/ + /*{ + if (index >= <%=maxSize%> || index < 0) { + throw new ArrayIndexOutOfBoundsException("Wrong index [" + index + "] for array <%=attrName%>," + + "index must be between 0 and <%=maxSizeMoinsUn%>"); + } + <%=simpleType%>[] oldValue = get<%=attrNameCapitalized%>(); + this.<%=attrName%>[index] = value; + firePropertyChange("<%=attrName%>", oldValue, this.<%=attrName%>); + }*/ ); // Get Value ObjectModelOperation getValue = addOperation(resultClass, "get" + attrNameCapitalized, - attrType, ObjectModelModifier.PUBLIC); + attrType, ObjectModelModifier.PUBLIC); addParameter(getValue, "int", "index"); addException(setValue, "java.lang.ArrayIndexOutOfBoundsException"); setOperationBody(getValue, "" - /*{ - if (index >= <%=maxSize%> || index < 0) { - throw new ArrayIndexOutOfBoundsException("Wrong index [" + index + "] for array <%=attrName%>," + - "index must be between 0 and <%=maxSizeMoinsUn%>"); - } - return this.<%=attrName%>[index]; - }*/ + /*{ + if (index >= <%=maxSize%> || index < 0) { + throw new ArrayIndexOutOfBoundsException("Wrong index [" + index + "] for array <%=attrName%>," + + "index must be between 0 and <%=maxSizeMoinsUn%>"); + } + return this.<%=attrName%>[index]; + }*/ ); attrType += "[]"; @@ -179,10 +186,10 @@ attrType, ObjectModelModifier.PUBLIC); addParameter(getChild, "int", "index"); setOperationBody(getChild, "" - /*{ - <%=simpleType%> o = getChild(<%=attrName%>, index); - return o; - }*/ + /*{ + <%=simpleType%> o = getChild(<%=attrName%>, index); + return o; + }*/ ); // Add getEntity @@ -195,13 +202,13 @@ if (isEntity) { hasEntity = true; ObjectModelOperation getChildEntity = addOperation(resultClass, "get" + attrNameCapitalized, - attrType, ObjectModelModifier.PUBLIC); + attrType, ObjectModelModifier.PUBLIC); addParameter(getChildEntity, String.class.getName(), "topiaId"); setOperationBody(getChildEntity, "" - /*{ - <%=simpleType%> o = getEntity(<%=attrName%>, topiaId); - return o; - }*/ + /*{ + <%=simpleType%> o = getEntity(<%=attrName%>, topiaId); + return o; + }*/ ); } @@ -211,11 +218,11 @@ addParameter(addChild, attrType, attrName); setOperationBody(addChild, "" - /*{ - get<%=attrNameCapitalized%>().add(<%=attrName%>); - firePropertyChange("<%=attrName%>", null, <%=attrName%>); - return <%=attrName%>; - }*/ + /*{ + get<%=attrNameCapitalized%>().add(<%=attrName%>); + firePropertyChange("<%=attrName%>", null, <%=attrName%>); + return <%=attrName%>; + }*/ ); // Add removeChild @@ -224,13 +231,13 @@ addParameter(removeChild, attrType, attrName); setOperationBody(removeChild, "" - /*{ - boolean removed = get<%=attrNameCapitalized%>().remove(<%=attrName%>); - if (removed) { - firePropertyChange("<%=attrName%>", <%=attrName%>, null); - } - return removed; - }*/ + /*{ + boolean removed = get<%=attrNameCapitalized%>().remove(<%=attrName%>); + if (removed) { + firePropertyChange("<%=attrName%>", <%=attrName%>, null); + } + return removed; + }*/ ); // Change type for Multiple attribute @@ -256,9 +263,9 @@ ObjectModelOperation getter = addOperation(resultClass, "get" + attrNameCapitalized, attrType, ObjectModelModifier.PUBLIC); setOperationBody(getter, "" - /*{ - return this.<%=attrName%>; - }*/ + /*{ + return this.<%=attrName%>; + }*/ ); // Add setter operation @@ -266,11 +273,11 @@ ObjectModelModifier.PUBLIC); addParameter(setter, attrType, "newValue"); setOperationBody(setter, "" - /*{ - <%=simpleType%> oldValue = get<%=attrNameCapitalized%>(); - this.<%=attrName%> = newValue; - firePropertyChange("<%=attrName%>", oldValue, newValue); - }*/ + /*{ + <%=simpleType%> oldValue = get<%=attrNameCapitalized%>(); + this.<%=attrName%> = newValue; + firePropertyChange("<%=attrName%>", oldValue, newValue); + }*/ ); // toString append for toString method @@ -286,18 +293,18 @@ addParameter(getChild, "java.util.Collection<T>", "childs"); addParameter(getChild, "int", "index"); setOperationBody(getChild, "" - /*{ - if (childs != null) { - int i = 0; - for (T o : childs) { - if (index == i) { - return o; - } - i++; - } - } - return null; - }*/ + /*{ + if (childs != null) { + int i = 0; + for (T o : childs) { + if (index == i) { + return o; + } + i++; + } + } + return null; + }*/ ); } @@ -310,31 +317,31 @@ addParameter(getEntity, "java.util.Collection<T>", "childs"); addParameter(getEntity, "java.lang.String", "topiaId"); setOperationBody(getEntity, "" - /*{ - if (childs != null) { - for (T o : childs) { - if (topiaId.equals(o.getId())) { - return o; - } - } - } - return null; - }*/ + /*{ + if (childs != null) { + for (T o : childs) { + if (topiaId.equals(o.getTopiaId())) { + return o; + } + } + } + return null; + }*/ ); } // Set body for default constructor setOperationBody(constructor, "" - /*{ - pcs = new PropertyChangeSupport(this);<%=initTabs%> - }*/ + /*{ + pcs = new PropertyChangeSupport(this);<%=initTabs%> + }*/ ); // Add operations for (ObjectModelOperation op : clazz.getOperations()) { String visibility = op.getVisibility(); ObjectModelOperation resultOperation = addOperation(resultClass, op.getName(), op.getReturnType(), - ObjectModelModifier.toValue(visibility), ObjectModelModifier.ABSTRACT); + ObjectModelModifier.toValue(visibility), ObjectModelModifier.ABSTRACT); for (ObjectModelParameter param : op.getParameters()) { addParameter(resultOperation, param.getType(), param.getName()); @@ -350,11 +357,11 @@ ObjectModelModifier.PUBLIC); // FIXME manque Override addImport(resultClass, "org.apache.commons.lang.builder.ToStringBuilder"); setOperationBody(toString, "" - /*{ - String result = new ToStringBuilder(this)<%=toStringAppend%>. - toString(); - return result; - }*/ + /*{ + String result = new ToStringBuilder(this)<%=toStringAppend%>. + toString(); + return result; + }*/ ); } @@ -374,7 +381,7 @@ } for (ObjectModelDependency dependency : inputClass.getDependencies()) { - ObjectModelClass supplier = (ObjectModelClass)dependency.getSupplier(); + ObjectModelClass supplier = (ObjectModelClass) dependency.getSupplier(); // ENTITY dependency // Copy all primitives attributes from the Entity (supplier) to the DTO @@ -407,9 +414,9 @@ "addPropertyChangeListener", "void", ObjectModelModifier.PUBLIC); addParameter(addPropertyChangeListener, propType, "listener"); setOperationBody(addPropertyChangeListener, "" - /*{ - pcs.addPropertyChangeListener(listener); - }*/ + /*{ + pcs.addPropertyChangeListener(listener); + }*/ ); ObjectModelOperation addPropertyChangeListenerPlus = addOperation(resultClass, @@ -417,18 +424,18 @@ addParameter(addPropertyChangeListenerPlus, strType, "propertyName"); addParameter(addPropertyChangeListenerPlus, propType, "listener"); setOperationBody(addPropertyChangeListenerPlus, "" - /*{ - pcs.addPropertyChangeListener(propertyName, listener); - }*/ + /*{ + pcs.addPropertyChangeListener(propertyName, listener); + }*/ ); ObjectModelOperation removePropertyChangeListener = addOperation(resultClass, "removePropertyChangeListener", "void", ObjectModelModifier.PUBLIC); addParameter(removePropertyChangeListener, propType, "listener"); setOperationBody(removePropertyChangeListener, "" - /*{ - pcs.removePropertyChangeListener(listener); - }*/ + /*{ + pcs.removePropertyChangeListener(listener); + }*/ ); ObjectModelOperation removePropertyChangeListenerPlus = addOperation(resultClass, @@ -436,9 +443,9 @@ addParameter(removePropertyChangeListenerPlus, strType, "propertyName"); addParameter(removePropertyChangeListenerPlus, propType, "listener"); setOperationBody(removePropertyChangeListenerPlus, "" - /*{ - pcs.removePropertyChangeListener(propertyName, listener); - }*/ + /*{ + pcs.removePropertyChangeListener(propertyName, listener); + }*/ ); ObjectModelOperation firePropertyChange = addOperation(resultClass, @@ -447,9 +454,9 @@ addParameter(firePropertyChange, objectType, "oldValue"); addParameter(firePropertyChange, objectType, "newValue"); setOperationBody(firePropertyChange, "" - /*{ - pcs.firePropertyChange(propertyName, oldValue, newValue); - }*/ + /*{ + pcs.firePropertyChange(propertyName, oldValue, newValue); + }*/ ); } 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-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOAbstractTransformer.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -30,17 +30,29 @@ import org.apache.commons.logging.LogFactory; import org.nuiton.eugene.GeneratorUtil; import org.nuiton.eugene.java.ObjectModelTransformerToJava; -import org.nuiton.eugene.models.object.*; +import org.nuiton.eugene.models.object.ObjectModel; +import org.nuiton.eugene.models.object.ObjectModelAssociationClass; +import org.nuiton.eugene.models.object.ObjectModelAttribute; +import org.nuiton.eugene.models.object.ObjectModelClass; +import org.nuiton.eugene.models.object.ObjectModelModifier; +import org.nuiton.eugene.models.object.ObjectModelOperation; +import org.nuiton.eugene.models.object.ObjectModelParameter; import org.nuiton.topia.TopiaException; import org.nuiton.topia.framework.TopiaContextImplementor; -import org.nuiton.topia.framework.TopiaQuery; import org.nuiton.topia.persistence.TopiaDAO; import org.nuiton.topia.persistence.TopiaDAOImpl; import org.nuiton.topia.persistence.TopiaEntity; import org.nuiton.util.StringUtil; import java.security.Permission; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -53,15 +65,14 @@ * Created: 13 déc. 2009 * * @author tchemit <chemit@codelutin.com> - * @version $Id$ + * @version $Id: DAOAbstractTransformer.java 1960 2010-05-13 17:18:23Z tchemit + * $ + * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.DAOAbstractTransformer" * @since 2.3.0 - * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.DAOAbstractTransformer" */ public class DAOAbstractTransformer extends ObjectModelTransformerToJava { - /** - * Logger - */ + /** Logger */ private static final Log log = LogFactory.getLog( DAOAbstractTransformer.class); @@ -69,7 +80,7 @@ @Override public void transformFromModel(ObjectModel model) { - + usages = TopiaGeneratorUtil.searchDirectUsages(model); } @@ -101,7 +112,7 @@ } if (log.isDebugEnabled()) { - log.debug("super class = "+extendClass); + log.debug("super class = " + extendClass); } setSuperClass(result, extendClass); @@ -118,7 +129,7 @@ } setConstantPrefix(prefix); - + // imports Collection<ObjectModelOperation> DAOoperations = getDAOOperations(clazz); @@ -134,9 +145,9 @@ addImport(result, TopiaContextImplementor.class); boolean enableSecurity = clazz.hasTagValue(TopiaGeneratorUtil.TAG_SECURITY_CREATE) || - clazz.hasTagValue(TopiaGeneratorUtil.TAG_SECURITY_LOAD) || - clazz.hasTagValue(TopiaGeneratorUtil.TAG_SECURITY_UPDATE) || - clazz.hasTagValue(TopiaGeneratorUtil.TAG_SECURITY_DELETE); + clazz.hasTagValue(TopiaGeneratorUtil.TAG_SECURITY_LOAD) || + clazz.hasTagValue(TopiaGeneratorUtil.TAG_SECURITY_UPDATE) || + clazz.hasTagValue(TopiaGeneratorUtil.TAG_SECURITY_DELETE); if (enableSecurity) { addImport(result, ArrayList.class); @@ -161,7 +172,7 @@ "getEntityClass", "Class<E>", ObjectModelModifier.PUBLIC); - setOperationBody(op,"" + setOperationBody(op, "" /*{ return (Class<E>)<%=clazzName%>.class; }*/ @@ -170,7 +181,7 @@ generateDAOOperations(result, DAOoperations); - generateDelete(clazz,result); + generateDelete(clazz, result); generateNaturalId(result, clazz); @@ -188,7 +199,7 @@ if (clazz instanceof ObjectModelAssociationClass) { ObjectModelAssociationClass assocClass = - (ObjectModelAssociationClass)clazz; + (ObjectModelAssociationClass) clazz; for (ObjectModelAttribute attr : assocClass.getParticipantsAttributes()) { if (attr != null) { if (!GeneratorUtil.isNMultiplicity(attr)) { @@ -200,7 +211,7 @@ } } - if(enableSecurity) { + if (enableSecurity) { // getRequestPermission @@ -208,18 +219,18 @@ "getRequestPermission", "List<Permission>", ObjectModelModifier.PUBLIC); - setDocumentation(op,"Retourne les permissions a verifier pour " + + setDocumentation(op, "Retourne les permissions a verifier pour " + "l'acces a l'entite pour le service Taas"); addException(op, TopiaException.class); - addParameter(op,String.class,"topiaId"); - addParameter(op,int.class,"actions"); + addParameter(op, String.class, "topiaId"); + addParameter(op, int.class, "actions"); StringBuilder buffer = new StringBuilder(); buffer.append("" /*{ List<Permission> resultPermissions = new ArrayList<Permission>(); if ((actions & TaasUtil.CREATE) == TaasUtil.CREATE) { }*/ - ); + ); buffer.append(generateSecurity(result, clazz, TopiaGeneratorUtil.TAG_SECURITY_CREATE)); buffer.append("" @@ -227,7 +238,7 @@ } if ((actions & TaasUtil.LOAD) == TaasUtil.LOAD) { }*/ - ); + ); buffer.append(generateSecurity(result, clazz, TopiaGeneratorUtil.TAG_SECURITY_LOAD)); buffer.append("" @@ -235,7 +246,7 @@ } if ((actions & TaasUtil.UPDATE) == TaasUtil.UPDATE) { }*/ - ); + ); buffer.append(generateSecurity(result, clazz, TopiaGeneratorUtil.TAG_SECURITY_UPDATE)); buffer.append("" @@ -243,7 +254,7 @@ } if ((actions & TaasUtil.DELETE) == TaasUtil.DELETE) { }*/ - ); + ); buffer.append(generateSecurity(result, clazz, TopiaGeneratorUtil.TAG_SECURITY_DELETE)); buffer.append("" @@ -251,10 +262,10 @@ } return resultPermissions; }*/ - ); - - setOperationBody(op,buffer.toString()); - + ); + + setOperationBody(op, buffer.toString()); + // THIMEL : Le code suivant doit pouvoir être déplacé dans DAODelegator ? // getRequestPermission @@ -264,14 +275,14 @@ "getRequestPermission", "List<Permission>", ObjectModelModifier.PROTECTED); - addParameter(op,String.class,"topiaId"); - addParameter(op,int.class,"actions"); - addParameter(op,String.class,"query"); - addParameter(op,Class.class,"daoClass"); - addException(op,TopiaException.class); - setDocumentation(op,"Retourne les permissions a verifier pour " + + addParameter(op, String.class, "topiaId"); + addParameter(op, int.class, "actions"); + addParameter(op, String.class, "query"); + addParameter(op, Class.class, "daoClass"); + addException(op, TopiaException.class); + setDocumentation(op, "Retourne les permissions a verifier pour " + "l'acces a l'entite pour le service Taas"); - setOperationBody(op,"" + setOperationBody(op, "" /*{ TopiaContextImplementor context = getContext(); List<String> result = context.find(query, "id", topiaId); @@ -292,7 +303,7 @@ } Set<ObjectModelClass> usagesForclass = usages.get(clazz); - generateFindUsages(clazz,result,usagesForclass); + generateFindUsages(clazz, result, usagesForclass); } private void generateDelete(ObjectModelClass clazz, @@ -307,18 +318,18 @@ PROP_DEFAULT_PACKAGE) + '.' + modelName + "DAOHelper.getImplementationClass"; for (ObjectModelAttribute attr : clazz.getAttributes()) { - String attrType = GeneratorUtil.getSimpleName(attr.getType()); - String reverseAttrName = attr.getReverseAttributeName(); + String attrType = GeneratorUtil.getSimpleName(attr.getType()); + String reverseAttrName = attr.getReverseAttributeName(); ObjectModelAttribute reverse = attr.getReverseAttribute(); if (!attr.hasAssociationClass() && reverse != null && reverse.isNavigable() && GeneratorUtil.isNMultiplicity(attr) && GeneratorUtil.isNMultiplicity(reverse)) { // On doit absolument supprimer pour les relations many-to-many // le this de la collection de l'autre cote - String attrDBName = TopiaGeneratorUtil.getDBName(attr); - String attrClassifierDBName = TopiaGeneratorUtil.getDBName(attr.getClassifier()); - String attrJoinTableName = TopiaGeneratorUtil.getManyToManyTableName(attr); - String attrReverseDBName = TopiaGeneratorUtil.getReverseDBName(attr); + String attrDBName = TopiaGeneratorUtil.getDBName(attr); + String attrClassifierDBName = TopiaGeneratorUtil.getDBName(attr.getClassifier()); + String attrJoinTableName = TopiaGeneratorUtil.getManyToManyTableName(attr); + String attrReverseDBName = TopiaGeneratorUtil.getReverseDBName(attr); //FIXME_-FC-20100413 Use a TopiaQuery (use HQLin elements) // // Add DAOHelper @@ -353,7 +364,7 @@ "SELECT main.topiaid " + "from <%=attrClassifierDBName%> main, <%=attrJoinTableName%> secondary " + "where main.topiaid=secondary.<%=attrDBName%>" + - " and secondary.<%=attrReverseDBName%>='" + entity.getId() + "'") + " and secondary.<%=attrReverseDBName%>='" + entity.getTopiaId() + "'") .addEntity("main", <%=providerFQN%>(<%=attrType%>.class)).list(); for (<%=attrType%> item : list) { @@ -362,34 +373,34 @@ } }*/ ); - } else if (!attr.hasAssociationClass() && reverse != null + } else if (!attr.hasAssociationClass() && reverse != null && reverse.isNavigable() && !GeneratorUtil.isNMultiplicity(reverse)) { // On doit mettre a null les attributs qui ont cet objet sur les // autres entites en one-to-* // TODO peut-etre qu'hibernate est capable de faire ca tout seul ? - // THIMEL: J'ai remplacé reverse.getName() par reverseAttrName sans certitude + // THIMEL: J'ai remplacé reverse.getName() par reverseAttrName sans certitude builder.addImport(result, attrType); String attrSimpleType = TopiaGeneratorUtil.getClassNameFromQualifiedName(attrType); body.append("" - /*{ - { - List<<%=attrSimpleType%>> list = getContext() - .getDAO(<%=attrSimpleType%>.class) - .findAllByProperties(<%=attrSimpleType%>.<%=getConstantName(reverseAttrName)%>, entity); -// .findAllByProperties("<%=reverseAttrName%>", entity); - for (<%=attrSimpleType%> item : list) { - item.set<%=StringUtils.capitalize(reverseAttrName)%>(null); -}*/ + /*{ + { + List<<%=attrSimpleType%>> list = getContext() + .getDAO(<%=attrSimpleType%>.class) + .findAllByProperties(<%=attrSimpleType%>.<%=getConstantName(reverseAttrName)%>, entity); + // .findAllByProperties("<%=reverseAttrName%>", entity); + for (<%=attrSimpleType%> item : list) { + item.set<%=StringUtils.capitalize(reverseAttrName)%>(null); + }*/ ); - if(attr.isAggregate()){ + if (attr.isAggregate()) { body.append("" /*{ item.delete(); }*/ - ); - } + ); + } body.append("" /*{ } @@ -405,8 +416,9 @@ }*/ ); - setOperationBody(op,body.toString()); + setOperationBody(op, body.toString()); } + private void generateFindUsages(ObjectModelClass clazz, ObjectModelClass result, Set<ObjectModelClass> usagesForclass) { @@ -415,7 +427,7 @@ builder.addImport(result, Map.class.getName()); builder.addImport(result, HashMap.class.getName()); builder.addImport(result, TopiaEntity.class.getName()); - + if (clazz instanceof ObjectModelAssociationClass || usagesForclass.isEmpty()) { // not for an association class // just let a null method @@ -428,8 +440,8 @@ addParameter(operation, "Class<U>", "type"); addParameter(operation, "E", "entity"); addException(operation, TopiaException.class); - addAnnotation(result, operation,"Override"); - setOperationBody(operation,"" + addAnnotation(result, operation, "Override"); + setOperationBody(operation, "" /*{ return new ArrayList<U>(); }*/ @@ -442,7 +454,7 @@ addParameter(operation, "E", "entity"); addException(operation, TopiaException.class); - addAnnotation(result, operation,"Override"); + addAnnotation(result, operation, "Override"); setOperationBody(operation, "" /*{ return new HashMap<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>(); @@ -464,14 +476,14 @@ ObjectModelOperation operation; operation = addOperation(result, - "findUsages", - "<U extends TopiaEntity> List<U>", - ObjectModelModifier.PUBLIC); + "findUsages", + "<U extends TopiaEntity> List<U>", + ObjectModelModifier.PUBLIC); - addParameter(operation,"Class<U>","type"); - addParameter(operation,"E","entity"); - addException(operation,TopiaException.class); - addAnnotation(result, operation,"Override"); + addParameter(operation, "Class<U>", "type"); + addParameter(operation, "E", "entity"); + addException(operation, TopiaException.class); + addAnnotation(result, operation, "Override"); StringBuilder buffer = new StringBuilder(300); buffer.append("" /*{ @@ -517,9 +529,9 @@ String methodName; if (!GeneratorUtil.isNMultiplicity(attr)) { - methodName = "findAllBy"+ StringUtils.capitalize(attrName); + methodName = "findAllBy" + StringUtils.capitalize(attrName); } else { - methodName = "findAllContains"+ StringUtils.capitalize(attrName); + methodName = "findAllContains" + StringUtils.capitalize(attrName); } String daoName = StringUtils.capitalize(usageSimpleType) + "DAO"; @@ -553,7 +565,7 @@ addParameter(operation, "E", "entity"); addException(operation, TopiaException.class); - addAnnotation(result, operation,"Override"); + addAnnotation(result, operation, "Override"); buffer = new StringBuilder(300); buffer.append("" @@ -587,10 +599,12 @@ } /** - * Generation of DAO operations signatures from class. - * These operations are abstract and identified by <<dao>> stereotype in the model. - * The developper must defined these methods in the DAOImpl associated to this DAOAbstract. - * @param result clazz where to add operations + * Generation of DAO operations signatures from class. These operations are + * abstract and identified by <<dao>> stereotype in the model. The + * developper must defined these methods in the DAOImpl associated to this + * DAOAbstract. + * + * @param result clazz where to add operations * @param operations operations to generate */ private void generateDAOOperations(ObjectModelClass result, @@ -599,7 +613,7 @@ for (ObjectModelOperation op : operations) { //TODO: add to transformer cloneOperation - + ObjectModelOperation op2; op2 = addOperation(result, op.getName(), @@ -609,7 +623,7 @@ setDocumentation(op2, op.getDocumentation()); // parameters - + for (ObjectModelParameter param : op.getParameters()) { ObjectModelParameter param2 = addParameter(op2, param.getType(), param.getName()); @@ -620,7 +634,7 @@ Set<String> exceptions = op.getExceptions(); exceptions.add(TopiaException.class.getName()); for (String exception : exceptions) { - addException(op2,exception); + addException(op2, exception); } } } @@ -630,11 +644,11 @@ ObjectModelClass clazz, String securityTagName) { StringBuilder buffer = new StringBuilder(); - - if (clazz.hasTagValue(securityTagName)) { - String security = clazz.getTagValue(securityTagName); + + if (clazz.hasTagValue(securityTagName)) { + String security = clazz.getTagValue(securityTagName); Pattern propertiesPattern = Pattern - .compile("((?:[_a-zA-Z0-9]+\\.)+(?:_?[A-Z][_a-zA-Z0-9]*\\.)+)attribute\\.(?:([_a-z0-9][_a-zA-Z0-9]*))#(?:(create|load|update|delete))"); + .compile("((?:[_a-zA-Z0-9]+\\.)+(?:_?[A-Z][_a-zA-Z0-9]*\\.)+)attribute\\.(?:([_a-z0-9][_a-zA-Z0-9]*))#(?:(create|load|update|delete))"); String[] valuesSecurity = security.split(":"); for (String valueSecurity : valuesSecurity) { @@ -650,7 +664,7 @@ String query = ""; String daoClass = ""; - if(className.equals(clazz.getQualifiedName())) { + if (className.equals(clazz.getQualifiedName())) { query = "select " + attributeName + ".topiaId from " + clazz.getQualifiedName() + " where topiaId = :id"; daoClass = clazz.getAttribute(attributeName).getClassifier().getQualifiedName(); } else { @@ -678,9 +692,9 @@ protected void generateNoNMultiplicity(String clazzName, ObjectModelClass result, ObjectModelAttribute attr, - boolean isAssoc) { - String attrName = attr.getName(); - String attrType = attr.getType(); + boolean isAssoc) { + String attrName = attr.getName(); + String attrType = attr.getType(); String propertyName = attrName; if (!isAssoc && attr.hasAssociationClass()) { propertyName = TopiaGeneratorUtil.toLowerCaseFirstLetter( @@ -693,8 +707,8 @@ ObjectModelModifier.PUBLIC); addException(op, TopiaException.class); addParameter(op, attrType, "v"); - setDocumentation(op, "Retourne le premier élément trouvé ayant comme valeur pour l'attribut "+ attrName + " le paramètre."); - setOperationBody(op,"" + setDocumentation(op, "Retourne le premier élément trouvé ayant comme valeur pour l'attribut " + attrName + " le paramètre."); + setOperationBody(op, "" /*{ E result = findByProperty(<%=clazzName + "." + getConstantName(propertyName)%>, v); return result; @@ -709,7 +723,7 @@ addParameter(op, attrType, "v"); setDocumentation(op, "Retourne les éléments ayant comme valeur pour " + "l'attribut " + attrName + " le paramètre."); - setOperationBody(op,"" + setOperationBody(op, "" /*{ List<E> result = findAllByProperty(<%=clazzName + "." + getConstantName(propertyName)%>, v); return result; @@ -746,7 +760,7 @@ " l'attribut " + TopiaGeneratorUtil.toLowerCaseFirstLetter(assocClassName) + " le paramètre."); - setOperationBody(op,"" + setOperationBody(op, "" /*{ List<E> result = findAllByProperty(<%=clazzName + "." + getConstantName(TopiaGeneratorUtil.toLowerCaseFirstLetter(assocClassName))%>, value); return result; @@ -756,8 +770,8 @@ } protected void generateNMultiplicity(String clazzName, ObjectModelClass result, ObjectModelAttribute attr) { - String attrName = attr.getName(); - String attrType = attr.getType(); + String attrName = attr.getName(); + String attrType = attr.getType(); ObjectModelOperation op; op = addOperation(result, @@ -767,8 +781,8 @@ addException(op, TopiaException.class); addParameter(op, attrType + "...", "v"); setDocumentation(op, "Retourne le premier élément trouvé dont " + - "l'attribut " +attrName + " contient le paramètre." ); - setOperationBody(op,"" + "l'attribut " + attrName + " contient le paramètre."); + setOperationBody(op, "" /*{ //FIXME TC-20100129 : really strange behaviour : contains on sub-sub properties instead of sub properties ? //E result = findContainsProperties(<%=clazzName + "." + getConstantName(TopiaGeneratorUtil.toLowerCaseFirstLetter(attrName))%>, Arrays.asList(v)); @@ -832,7 +846,7 @@ } private void generateNaturalId(ObjectModelClass result, - ObjectModelClass clazz) { + ObjectModelClass clazz) { List<ObjectModelAttribute> props = TopiaGeneratorUtil.getNaturalIdAttributes(clazz); @@ -865,9 +879,9 @@ addParameter(existByNaturalId, attr.getType(), propName); addParameter(create, attr.getType(), propName); - searchProperties += + searchProperties += ", " + clazzName + '.' + getConstantName(propName) + - ", " + propName; + ", " + propName; //params += ", " + propName; } searchProperties = searchProperties.substring(2); @@ -878,7 +892,7 @@ return findByProperties(<%=searchProperties%>); }*/ ); - + setOperationBody(existByNaturalId, "" /*{ return existByProperties(<%=searchProperties%>); 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-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAO.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -55,12 +55,12 @@ * TopiaDAO is used to manipulate entities corresponding to {@code E} type : * create, delete, update or find entities using properties of {@link * TopiaQuery}. - * <p /> + * <p/> * This interface is implemented by {@link TopiaDAOImpl} overriden by generation * from {@link DAOTransformer} for specific entity interface, {@link * DAOAbstractTransformer} for abstract implementation and {@link * DAOImplTransformer} for final implementation class. - * + * <p/> * TODO-fdesbois-20100508 : Need translation of javadoc. * * @author poussin <poussin@codelutin.com> @@ -259,13 +259,10 @@ */ TopiaQuery createQuery(String entityAlias); - @Deprecated E findByTopiaId(String k) throws TopiaException; - E findById(String k) throws TopiaException; - E findByProperty(String propertyName, Object value) - throws TopiaException; + throws TopiaException; /** * @param propertyName le nom de la propriété @@ -373,22 +370,22 @@ * @throws TopiaException for Topia errors * @since 2.4 */ - boolean existById(String id) throws TopiaException; + boolean existByTopiaId(String id) throws TopiaException; /** - * Check the existence of an entity with {@code propertyName} with - * {@code propertyValue}. {@code others} properties can be added to test + * Check the existence of an entity with {@code propertyName} with {@code + * propertyValue}. {@code others} properties can be added to test * existence. * - * @param propertyName first property name to test existence + * @param propertyName first property name to test existence * @param propertyValue first property value to test existence - * @param others altern propertyName and propertyValue + * @param others altern propertyName and propertyValue * @return true if entity exists, false otherwise * @throws TopiaException for Topia errors * @since 2.4 */ boolean existByProperties(String propertyName, Object propertyValue, - Object... others) throws TopiaException; + Object... others) 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-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAOImpl.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -465,15 +465,10 @@ @Override public E findByTopiaId(String id) throws TopiaException { - return findById(id); + return findByQuery(createQuery().add(TopiaEntity.TOPIA_ID, id)); } @Override - public E findById(String id) throws TopiaException { - return findByQuery(createQuery().add(TopiaEntity.ID, id)); - } - - @Override public E findByProperty(String propertyName, Object value) throws TopiaException { Map<String, Object> properties = new HashMap<String, Object>(); @@ -529,7 +524,7 @@ @Override public List<String> findAllIds() throws TopiaException { - return createQuery().setSelect(TopiaEntity.ID).execute(); + return createQuery().setSelect(TopiaEntity.TOPIA_ID).execute(); } @Override @@ -603,8 +598,8 @@ } @Override - public boolean existById(String id) throws TopiaException { - boolean result = existByProperties(TopiaEntity.ID, id); + public boolean existByTopiaId(String id) throws TopiaException { + boolean result = existByProperties(TopiaEntity.TOPIA_ID, id); return result; } @@ -626,8 +621,7 @@ } /** - * Count number of existing entities using {@link - * TopiaQuery#executeCount(TopiaContext)} + * Count number of existing entities using {@link TopiaQuery#executeCount(TopiaContext)} * * @return a long for the number of entities in database */ @@ -649,8 +643,8 @@ * errors */ private Map<String, Object> convertPropertiesArrayToMap(String propertyName, - Object propertyValue, - Object... others) + Object propertyValue, + Object... others) throws IllegalArgumentException { Map<String, Object> properties = new HashMap<String, Object>(); properties.put(propertyName, propertyValue); Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntity.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntity.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntity.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -72,77 +72,20 @@ @SearchFields public interface TopiaEntity extends Serializable { - /** @deprecated since 2.4 use {@link #ID} instead */ - @Deprecated String TOPIA_ID = "topiaId"; - /** @deprecated since 2.4 use {@link #CREATE_DATE} instead */ - @Deprecated String TOPIA_CREATE_DATE = "topiaCreateDate"; - /** @deprecated since 2.4 use {@link #ENTITY_VERSION} instead */ - @Deprecated String TOPIA_VERSION = "topiaVersion"; - /** Property name of the unique technical {@code id} of the entity */ - String ID = "topiaId"; - - /** Property name of the technical {@code createDate} of the entity */ - String CREATE_DATE = "topiaCreateDate"; - - /** Property name of the technical {@code version} of the entity */ - String ENTITY_VERSION = "topiaVersion"; - /** - * @return the id - * @deprecated since 2.4 use {@link #getId()} instead - */ - @Deprecated - String getTopiaId(); - - /** - * @param v the new id - * @deprecated since 2.4 use {@link #setId(String)} instead - */ - @Deprecated - void setTopiaId(String v); - - /** - * @return the entity version - * @deprecated since 2.4 use {@link #getEntityVersion()} instead - */ - @Deprecated - long getTopiaVersion(); - - /** - * @param v the new entity version - * @deprecated since 2.4 use {@link #setEntityVersion(long)} instead - */ - @Deprecated - void setTopiaVersion(long v); - - /** - * @return the creation date of the entity - * @deprecated since 2.4 use {@link #getCreateDate()} - */ - @Deprecated - Date getTopiaCreateDate(); - - /** - * @param topiaCreatedate the creation date of the entity - * @deprecated since 2.4 use {@link #setCreateDate(Date)} - */ - @Deprecated - void setTopiaCreateDate(Date topiaCreatedate); - - /** * Unique technical Id of the entity. This id contains the full qualified * name of the entity interface. This id has also an index and his used to * identify uniquely the entity in the database. * * @return the technical Id of the entity */ - String getId(); + String getTopiaId(); /** * Set the technical {@code id} of the entity. Careful, use this method only @@ -151,7 +94,7 @@ * * @param id technical id to set */ - void setId(String id); + void setTopiaId(String id); /** * Technical property to keep versionning of the entity. The version is @@ -159,7 +102,7 @@ * * @return the current version of the entity */ - long getEntityVersion(); + long getTopiaVersion(); /** * Set the technical {@code version} of the entity. Careful, use this method @@ -168,7 +111,7 @@ * * @param version technical version to set */ - void setEntityVersion(long version); + void setTopiaVersion(long version); /** * Technical date creation of the entity. This date doesn't change through @@ -177,7 +120,7 @@ * * @return the creation date of the entity */ - Date getCreateDate(); + Date getTopiaCreateDate(); /** * Set the technical creation {@code date} of the entity. Careful, use this @@ -186,7 +129,7 @@ * * @param date technical create date to set */ - void setCreateDate(Date date); + void setTopiaCreateDate(Date date); @Deprecated TopiaContext getTopiaContext(); @@ -204,19 +147,19 @@ void postCreate() throws TopiaException; /** + * @throws TopiaException if any pb * @deprecated since 2.4 : context will no longer be keeped by the entity, * so it will be impossible to do such operation. Use {@link * TopiaDAO#update(TopiaEntity)} instead. - * @throws TopiaException if any pb */ @Deprecated void update() throws TopiaException; /** + * @throws TopiaException if any pb * @deprecated since 2.4 : context will no longer be keeped by the entity, * so it will be impossible to do such operation. Use {@link * TopiaDAO#delete(TopiaEntity)} instead. - * @throws TopiaException if any pb */ @Deprecated void delete() throws TopiaException; @@ -238,7 +181,7 @@ * Add listener for property writing. * * @param propertyName name of property to listen - * @param listener the listener to register + * @param listener the listener to register */ void addPropertyChangeListener(String propertyName, PropertyChangeListener listener); @@ -269,7 +212,7 @@ * Add listener for property reading. * * @param propertyName the property name to listen - * @param listener the listener to register + * @param listener the listener to register */ void addPropertyListener(String propertyName, PropertyChangeListener listener); Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntityAbstract.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntityAbstract.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntityAbstract.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -25,18 +25,24 @@ /******************************************************************************* * TopiaEntityAbstract.java - * + * * Created: 28 déc. 2005 22:50:42 - * + * * @author poussin <poussin@codelutin.com> - * + * * @version $Revision$ - * + * * Last update: $Date$ by : $Author$ */ package org.nuiton.topia.persistence; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.framework.TopiaContextImplementor; + import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.beans.VetoableChangeListener; @@ -44,18 +50,12 @@ import java.util.Date; import java.util.List; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.framework.TopiaContextImplementor; - /** * Classe de base de toutes les entités, cela permet de concentrer le code * technique dans cette classe. L'identifiant peut-etre n'importe quoi Aucune * restriction n'est faite dessus, il peut meme changer entre deux types * d'entité si cela ne pose pas d'autre probleme (heritage entre ces entités). - * + * * @author poussin <poussin@codelutin.com> * @version $Id$ */ @@ -74,44 +74,17 @@ transient protected VetoableChangeSupport readVetoables = new VetoableChangeSupport(this); + transient protected PropertyChangeSupport readListeners = new PropertyChangeSupport(this); + transient protected VetoableChangeSupport writeVetoables = new VetoableChangeSupport(this); + transient protected PropertyChangeSupport writeListeners = new PropertyChangeSupport(this); @Override - public String getId() { - return getTopiaId(); - } - - @Override - public void setId(String id) { - setTopiaId(id); - } - - @Override - public long getEntityVersion() { - return getTopiaVersion(); - } - - @Override - public void setEntityVersion(long version) { - setTopiaVersion(version); - } - - @Override - public Date getCreateDate() { - return getTopiaCreateDate(); - } - - @Override - public void setCreateDate(Date date) { - setTopiaCreateDate(date); - } - - @Override public String getTopiaId() { return topiaId; } @@ -148,7 +121,7 @@ /** * @param context The context to set. - * @throws TopiaException if any pb ? + * @throws TopiaException if any pb ? */ public void setTopiaContext(TopiaContext context) throws TopiaException { if (topiaContext == null) { @@ -189,11 +162,11 @@ */ @Override public int hashCode() { - Date date = getCreateDate(); + Date date = getTopiaCreateDate(); //TC-20100220 : il se peut que la date de creation soit nulle // lorsque l'entite est utilise comme objet d'edition d'un formulaire // par exemple... - int result = date == null ? 0 :date.hashCode(); + int result = date == null ? 0 : date.hashCode(); return result; } @@ -212,10 +185,10 @@ return false; } TopiaEntity other = (TopiaEntity) obj; - if (getId() == null || other.getId() == null) { + if (getTopiaId() == null || other.getTopiaId() == null) { return false; } - boolean result = getId().equals(other.getId()); + boolean result = getTopiaId().equals(other.getTopiaId()); return result; } @@ -248,7 +221,7 @@ } protected void fireOnPreWrite(String propertyName, Object oldValue, - Object newValue) { + Object newValue) { TopiaContextImplementor contextImplementor = (TopiaContextImplementor) getTopiaContext(); if (contextImplementor != null) { @@ -258,7 +231,7 @@ } protected void fireOnPostWrite(String propertyName, Object oldValue, - Object newValue) { + Object newValue) { TopiaContextImplementor contextImplementor = (TopiaContextImplementor) getTopiaContext(); if (contextImplementor != null) { @@ -268,7 +241,7 @@ } protected void fireOnPostWrite(String propertyName, int index, - Object oldValue, Object newValue) { + Object oldValue, Object newValue) { TopiaContextImplementor contextImplementor = (TopiaContextImplementor) getTopiaContext(); if (contextImplementor != null) { @@ -280,7 +253,7 @@ @Override public void addPropertyChangeListener(String propertyName, - PropertyChangeListener listener) { + PropertyChangeListener listener) { writeListeners.addPropertyChangeListener(propertyName, listener); } @@ -291,7 +264,7 @@ @Override public void addVetoableChangeListener(String propertyName, - VetoableChangeListener vetoable) { + VetoableChangeListener vetoable) { writeVetoables.addVetoableChangeListener(propertyName, vetoable); } @@ -302,7 +275,7 @@ @Override public void removePropertyChangeListener(String propertyName, - PropertyChangeListener listener) { + PropertyChangeListener listener) { writeListeners.removePropertyChangeListener(propertyName, listener); } @@ -313,7 +286,7 @@ @Override public void removeVetoableChangeListener(String propertyName, - VetoableChangeListener vetoable) { + VetoableChangeListener vetoable) { writeVetoables.removeVetoableChangeListener(propertyName, vetoable); } @@ -324,7 +297,7 @@ @Override public void addPropertyListener(String propertyName, - PropertyChangeListener listener) { + PropertyChangeListener listener) { readListeners.addPropertyChangeListener(propertyName, listener); } @@ -335,7 +308,7 @@ @Override public void addVetoableListener(String propertyName, - VetoableChangeListener vetoable) { + VetoableChangeListener vetoable) { readVetoables.addVetoableChangeListener(propertyName, vetoable); } @@ -346,7 +319,7 @@ @Override public void removePropertyListener(String propertyName, - PropertyChangeListener listener) { + PropertyChangeListener listener) { readListeners.removePropertyChangeListener(propertyName, listener); } @@ -357,7 +330,7 @@ @Override public void removeVetoableListener(String propertyName, - VetoableChangeListener vetoable) { + VetoableChangeListener vetoable) { readVetoables.removeVetoableChangeListener(propertyName, vetoable); } 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-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityHelper.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -25,13 +25,13 @@ package org.nuiton.topia.persistence.util; -import java.util.Iterator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuiton.topia.TopiaContext; import org.nuiton.topia.TopiaException; import org.nuiton.topia.persistence.TopiaDAO; import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.TopiaEntityEnum; import org.nuiton.util.FileUtil; import java.io.ByteArrayOutputStream; @@ -47,13 +47,13 @@ import java.util.Deque; import java.util.HashMap; import java.util.HashSet; +import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; -import org.nuiton.topia.persistence.TopiaEntityEnum; /** * Une classe avec des méthodes utiles sur les entités. @@ -65,11 +65,9 @@ /** to use log facility, just put in your code: log.info(\"...\"); */ private static final Log log = LogFactory.getLog(TopiaEntityHelper.class); - /** - * Le pattern d'une reference sur une association - */ + /** Le pattern d'une reference sur une association */ public static final String ASSOCIATION_PATTERN = - "%1$s[@" + TopiaEntity.ID + "=\"%2$s\"]"; + "%1$s[@" + TopiaEntity.TOPIA_ID + "=\"%2$s\"]"; /** * Bind les valeurs techniques depuis une entitée vers une autre. @@ -79,32 +77,33 @@ */ public static void bindTechnical(TopiaEntity from, TopiaEntity dst) { if (from == null) { - dst.setId(null); - dst.setEntityVersion(0); - dst.setCreateDate(null); + dst.setTopiaId(null); + dst.setTopiaVersion(0); + dst.setTopiaCreateDate(null); } else { - dst.setId(from.getId()); - dst.setEntityVersion(from.getEntityVersion()); - dst.setCreateDate(from.getCreateDate()); + dst.setTopiaId(from.getTopiaId()); + dst.setTopiaVersion(from.getTopiaVersion()); + dst.setTopiaCreateDate(from.getTopiaCreateDate()); } } /** * 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 * @param <E> le type de l'entité * @return l'entité recherché - * @throws TopiaException pour tout pb lors de la récupération de l'entité + * @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 { + IllegalArgumentException { E entity = dao.findByTopiaId(topiaId); if (entity == null) { throw new IllegalArgumentException( @@ -114,19 +113,20 @@ } /** - * Récupère une entité dans une liste d'entités à partir de - * son {@link TopiaEntity#getTopiaId()}. + * Récupère une entité dans une liste d'entités à partir de son {@link + * TopiaEntity#getTopiaId()}. * * @param entities la liste des entités à scanner * @param topiaId l'id de l'entité recherchée * @param <E> le type de l'entité - * @return l'entité trouvée, ou <code<null</code< si elle n'est pas trouvée. + * @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) { if (entities != null) { for (E e : entities) { - if (topiaId.equals(e.getId())) { + if (topiaId.equals(e.getTopiaId())) { return e; } } @@ -145,11 +145,11 @@ */ public static <E extends TopiaEntity> void checkNotNullAndExistingEntity( String paramName, E bean) throws IllegalStateException, - NullPointerException { + NullPointerException { if (bean == null) { throw new NullPointerException(paramName + " can not be null"); } - if (bean.getId() == null) { + if (bean.getTopiaId() == null) { // can not create bean here throw new IllegalStateException( "can not create " + bean.getClass() + " here..."); @@ -167,11 +167,11 @@ */ public static <E extends TopiaEntity> void checkNotNullAndNoneExistingEntity( String paramName, E bean) throws NullPointerException, - IllegalStateException { + IllegalStateException { if (bean == null) { throw new NullPointerException(paramName + " can not be null"); } - if (bean.getId() != null) { + if (bean.getTopiaId() != null) { // can not create bean here throw new IllegalStateException( "can not update " + bean.getClass() + " here..."); @@ -192,7 +192,7 @@ File dbDirectory, TopiaContext topiaContext, URI resource) throws IOException, - TopiaException, NullPointerException { + TopiaException, NullPointerException { if (dbDirectory == null) { throw new NullPointerException("dbDirectory can not be null"); } @@ -233,7 +233,7 @@ } log.info("create database from [" + databaseDump + "] at [" + - dbDirectory + "]"); + dbDirectory + "]"); TopiaContext ctxt = topiaContext.beginTransaction(); @@ -270,7 +270,7 @@ if (!gzipFile.getParentFile().exists()) { if (!gzipFile.getParentFile().mkdirs()) { throw new IOException("could not create directory " + - gzipFile.getParentFile()); + gzipFile.getParentFile()); } } log.info("store database to [" + gzipFile + "]"); @@ -288,8 +288,9 @@ } /** - * Obtain a new {@link Comparator} pour {@link TopiaEntity} based - * on the {@link TopiaEntity#getTopiaId()} method. + * Obtain a new {@link Comparator} pour {@link TopiaEntity} based on the + * {@link TopiaEntity#getTopiaId()} method. + * * @return the new instanciated comparator */ public static Comparator<TopiaEntity> getTopiaIdComparator() { @@ -297,21 +298,21 @@ @Override public int compare(TopiaEntity o1, TopiaEntity o2) { - if (o1.getId() == null) { + if (o1.getTopiaId() == null) { return -1; } - if (o2.getId() == null) { + if (o2.getTopiaId() == null) { return 1; } - return o1.getId().compareTo(o2.getId()); + return o1.getTopiaId().compareTo(o2.getTopiaId()); } }; } /** * Filter a list of entities, and keep only the ones from a given type. - * - * @param entities the list of entities to filter + * + * @param entities the list of entities to filter * @param filterClass the type of entities to keep * @return the list of filtered entities for the given entity type in the * list @@ -393,7 +394,7 @@ * des entites. * * @param contracts les contracts connus - * @param classes l'ensemble des classes a filter + * @param classes l'ensemble des classes a filter * @return l'ensemble des contrats filtres * @since 2.2.0 */ @@ -451,14 +452,14 @@ /** * Collecte l'ensemble des types d'entites (via un parcours en profondeur). + * <p/> + * On retourne toujours les contrats des entites et jamais les + * implantations. * - * On retourne toujours les contrats des entites et jamais les implantations. - * * @param contracts les definitions d'entites connues - * @param entities les entites a parcourir + * @param entities les entites a parcourir * @return l'ensemble des types d'entites decouverts (uniquement les * contrats des entites). - * * @throws TopiaException if a problem while visiting entities */ public static Set<Class<? extends TopiaEntity>> detectTypes( @@ -470,31 +471,31 @@ 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>>(); + /** + * La liste des types d'entités détectées + */ + protected Set<Class<? extends TopiaEntity>> detectedTypes = + new HashSet<Class<? extends TopiaEntity>>(); - @Override - protected boolean onStarting(TopiaEntity e) { - super.onStarting(e); - Class<? extends TopiaEntity> entityClass = e.getClass(); - if (log.isDebugEnabled()) { - log.debug(entityClass + " : " + e.getId()); - } - detectedTypes.add(entityClass); - return true; - } + @Override + protected boolean onStarting(TopiaEntity e) { + super.onStarting(e); + Class<? extends TopiaEntity> entityClass = e.getClass(); + if (log.isDebugEnabled()) { + log.debug(entityClass + " : " + e.getTopiaId()); + } + detectedTypes.add(entityClass); + return true; + } - @Override - protected Set<Class<? extends TopiaEntity>> afterAll( - CollectorVisitor visitor, TopiaEntity... entities) { - Set<Class<? extends TopiaEntity>> result = - retainContracts(contracts, detectedTypes); - return result; - } - }; + @Override + protected Set<Class<? extends TopiaEntity>> afterAll( + CollectorVisitor visitor, TopiaEntity... entities) { + Set<Class<? extends TopiaEntity>> result = + retainContracts(contracts, detectedTypes); + return result; + } + }; Set<Class<? extends TopiaEntity>> result = collector.detect(entities); return result; @@ -503,15 +504,15 @@ /** * Collecte l'ensemble des entites (via un parcours en profondeur) avec un * filtrage sur les types d'entites a retourner. + * <p/> + * On retourne toujours les contrats des entites et jamais les + * implantations. * - * On retourne toujours les contrats des entites et jamais les implantations. - * * @param contracts les definitions d'entites connues - * @param types l'ensemble des types acceptables - * @param entities les entites a parcourir + * @param types l'ensemble des types acceptables + * @param entities les entites a parcourir * @return l'ensemble des entites decouverts (on converse uniquement les * entites dont le contract est dans l'ensemble voulu). - * * @throws TopiaException if a pb while visiting entities */ public static Map<Class<? extends TopiaEntity>, List<TopiaEntity>> @@ -539,7 +540,7 @@ } if (log.isDebugEnabled()) { - log.debug(entityClass + " : " + e.getId()); + log.debug(entityClass + " : " + e.getTopiaId()); } List<TopiaEntity> refs = detectedRefs.get(entityClass); @@ -563,17 +564,17 @@ } /** - * Collecte l'ensemble des ids d'entites (via un parcours en profondeur) avec un - * filtrage sur les types d'entites a retourner. + * Collecte l'ensemble des ids d'entites (via un parcours en profondeur) + * avec un filtrage sur les types d'entites a retourner. + * <p/> + * On retourne toujours les contrats des entites et jamais les + * implantations. * - * On retourne toujours les contrats des entites et jamais les implantations. - * * @param contracts les definitions d'entites connues - * @param types l'ensemble des types acceptables - * @param entities les entites a parcourir - * @return l'ensemble des ids d'entites decouverts (on converse uniquement les - * entites dont le contract est dans l'ensemble voulu). - * + * @param types l'ensemble des types acceptables + * @param entities les entites a parcourir + * @return l'ensemble des ids d'entites decouverts (on converse uniquement + * les entites dont le contract est dans l'ensemble voulu). * @throws TopiaException if a pb while visiting entities */ public static Map<Class<? extends TopiaEntity>, List<String>> @@ -601,7 +602,7 @@ } if (log.isDebugEnabled()) { - log.debug(entityClass + " : " + e.getId()); + log.debug(entityClass + " : " + e.getTopiaId()); } List<String> refs = detectedRefs.get(entityClass); @@ -609,7 +610,7 @@ refs = new ArrayList<String>(); detectedRefs.put(entityClass, refs); } - refs.add(e.getId()); + refs.add(e.getTopiaId()); } @Override @@ -628,13 +629,11 @@ * Collecte toutes les references d'un ensemble d'entites donnees par leur * topiaId sur un ensemble d'entites donne. * - * @param contracts les definitions d'entites connues + * @param contracts les definitions d'entites connues * @param expressions l'ensemble des ids a detecter - * @param entities les entites a parcourir + * @param entities les entites a parcourir * @return l'ensemble des references decouvertes. - * * @throws TopiaException if a pb while visiting entities - * * @see TopiaEntityRef */ public static SortedMap<TopiaEntity, List<TopiaEntityRef>> detectReferences( @@ -642,20 +641,18 @@ String[] expressions, TopiaEntity entities) throws TopiaException { return detectReferences(contracts, expressions, - Collections.singleton(entities)); + Collections.singleton(entities)); } /** * Collecte toutes les references d'un ensemble d'entites donnees par leur * topiaId sur un ensemble d'entites donne. * - * @param contracts les definitions d'entites connues + * @param contracts les definitions d'entites connues * @param expressions l'ensemble des ids a detecter - * @param entities les entites a parcourir + * @param entities les entites a parcourir * @return l'ensemble des references decouvertes. - * * @throws TopiaException if a pb while visiting entities - * * @see TopiaEntityRef */ public static SortedMap<TopiaEntity, List<TopiaEntityRef>> @@ -679,7 +676,9 @@ /** le path courant depuis le depart */ Deque<TopiaEntity> path = new LinkedList<TopiaEntity>(); + StringBuilder accessorExpression = new StringBuilder(); + TopiaEntity root; @Override @@ -694,7 +693,7 @@ @Override protected boolean onStarting(TopiaEntity e) { - log.debug(e.getId()); + log.debug(e.getTopiaId()); if (root == null) { // start come in start method since // last clear method invocation @@ -735,8 +734,8 @@ if (visitor.getAlreadyExplored().contains(e1)) { boolean contains = visitor.getStack().contains(e1); if (log.isDebugEnabled()) { - log.debug("already enter " + e1.getId() + - ", can reenter ? " + !contains); + log.debug("already enter " + e1.getTopiaId() + + ", can reenter ? " + !contains); } if (!contains) { try { @@ -787,8 +786,8 @@ if (visitor.getAlreadyExplored().contains(e1)) { boolean contains = visitor.getStack().contains(e1); if (log.isDebugEnabled()) { - log.debug("already enter " + e1.getId() + - ", can reenter ? " + !contains); + log.debug("already enter " + e1.getTopiaId() + + ", can reenter ? " + !contains); } if (!contains) { try { @@ -816,7 +815,7 @@ Class<?> type, int index, Object value, boolean enter) { super.onVisited(e, name, collectionType, type, index, value, - enter); + enter); if (enter) { removePath(); } @@ -840,7 +839,7 @@ } boolean accept(TopiaEntity e) { - return ids.contains(e.getId()); + return ids.contains(e.getTopiaId()); } void addPath(TopiaEntity e, String name, int index) { @@ -851,18 +850,18 @@ accessorExpression.append(name); if (index > -1) { String association = String.format( - ASSOCIATION_PATTERN, "", e.getId()); + ASSOCIATION_PATTERN, "", e.getTopiaId()); accessorExpression.append(association); } // if (index > -1) { // accessorExpression.append("[@topiaId=\""); -// accessorExpression.append(e.getId()); +// accessorExpression.append(e.getTopiaId()); // accessorExpression.append("\"]"); // } if (log.isTraceEnabled()) { - log.trace("add to stack : " + e.getId() + - ", new size : " + path.size() + ", path : " + - accessorExpression.toString()); + log.trace("add to stack : " + e.getTopiaId() + + ", new size : " + path.size() + ", path : " + + accessorExpression.toString()); } } @@ -875,13 +874,13 @@ TopiaEntityRef.SEPARATOR); if (index > -1) { accessorExpression.delete(index, - accessorExpression.length()); + accessorExpression.length()); } } if (log.isTraceEnabled()) { - log.trace("remove from stack : " + e.getId() + - ", new size : " + path.size() + ", path : " + - accessorExpression.toString()); + log.trace("remove from stack : " + e.getTopiaId() + + ", new size : " + path.size() + ", path : " + + accessorExpression.toString()); } } @@ -905,12 +904,12 @@ ); if (log.isDebugEnabled()) { - log.debug(expression + " (" + e.getId() + ") - " + - list.size() + " , root:" + root.getId()); + log.debug(expression + " (" + e.getTopiaId() + ") - " + + list.size() + " , root:" + root.getTopiaId()); } if (log.isTraceEnabled()) { - log.trace(e.getId() + " : new size " + list.size() + - ", path : " + expression); + log.trace(e.getTopiaId() + " : new size " + list.size() + + ", path : " + expression); } } }; @@ -932,7 +931,7 @@ List<? extends TopiaEntity> entities) { List<String> ids = new ArrayList<String>(entities.size()); for (TopiaEntity entity : entities) { - ids.add(entity.getId()); + ids.add(entity.getTopiaId()); } return ids; } @@ -941,8 +940,8 @@ * 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 <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 */ @@ -952,7 +951,7 @@ List<E> r = new ArrayList<E>(list == null ? 0 : list.size()); if (list != null) { for (E e : list) { - if (topiaIds.contains(e.getId())) { + if (topiaIds.contains(e.getTopiaId())) { r.add(e); } } @@ -963,12 +962,11 @@ /** * Construit le dictionnaire des differences entre deux listes d'entites. * - * @param <E> le type des entites + * @param <E> le type des entites * @param referentiel la liste considere comme reference - * @param locale la liste a mettre a jour + * @param locale la liste a mettre a jour * @return le dictionnaire des etats des entites ajoutees, modifiees ou * obsoletes. - * * @see DiffState * @since 2.2.0 */ @@ -982,7 +980,7 @@ for (E aReferentiel : referentiel) { TopiaEntity referentielEntity = aReferentiel; - String refId = referentielEntity.getId(); + String refId = referentielEntity.getTopiaId(); if (localeIdList.contains(refId)) { // id existant sur le storage locale @@ -991,13 +989,13 @@ // ordre, on parcourt donc la liste cible pour retrouver // l'entité cible for (TopiaEntity e : locale) { - if (e.getId().equals(refId)) { + if (e.getTopiaId().equals(refId)) { localeEntity = e; break; } } - boolean wasModified = referentielEntity.getEntityVersion() > - localeEntity.getEntityVersion(); + boolean wasModified = referentielEntity.getTopiaVersion() > + localeEntity.getTopiaVersion(); if (wasModified) { result.get(DiffState.MODIFIED).add(refId); @@ -1049,7 +1047,7 @@ } if (klass.getSuperclass() != null && - TopiaEntity.class.isAssignableFrom(klass.getSuperclass())) { + TopiaEntity.class.isAssignableFrom(klass.getSuperclass())) { getInterfaces( (Class<? extends TopiaEntity>) klass.getSuperclass(), klassInterfaces Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityRef.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityRef.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityRef.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -29,29 +29,27 @@ /** * Definition of a reference of an entity from a root entity. - * + * <p/> * the method {@link #getAccessorExpression()} return the jxpath to access the * ref from the root object. - * + * <p/> * TODO Javadoc... - * + * * @since 2.2.0 */ public class TopiaEntityRef implements Comparable<TopiaEntityRef> { public static final String SEPARATOR = "/"; - /** - * the root entity - */ + + /** the root entity */ TopiaEntity root; - /** - * the entity ref - */ + + /** the entity ref */ TopiaEntity ref; - /** - * the jxpath used to acces ref from root - */ + + /** the jxpath used to acces ref from root */ String accessorExpression; + TopiaEntity[] path; public TopiaEntityRef(TopiaEntity root, TopiaEntity ref, String accessorExpression, TopiaEntity[] path) { @@ -99,6 +97,6 @@ @Override public int compareTo(TopiaEntityRef o) { - return ref.getId().compareTo(o.getRef().getId()); + return ref.getTopiaId().compareTo(o.getRef().getTopiaId()); } } Modified: trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaTestCase.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaTestCase.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaTestCase.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -25,10 +25,14 @@ package org.nuiton.topia.generator; -import java.util.Properties; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.hibernate.cfg.Environment; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; import org.nuiton.topia.TopiaContext; import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; @@ -38,21 +42,17 @@ import org.nuiton.topiatest.CompanyDAO; import org.nuiton.topiatest.Department; import org.nuiton.topiatest.DepartmentDAO; -import org.hibernate.cfg.Environment; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import java.util.Properties; + /** * TopiaTestCase. * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ public class TopiaTestCase { @@ -65,19 +65,17 @@ /** TopiaContext */ protected static TopiaContext context; - /** - * Init les proprietes de connection a la base - */ + /** Init les proprietes de connection a la base */ @BeforeClass public static void init() { config = new Properties(); - config.setProperty("topia.persistence.classes",TopiaTestDAOHelper.getImplementationClassesAsString()); + config.setProperty("topia.persistence.classes", TopiaTestDAOHelper.getImplementationClassesAsString()); config.setProperty(Environment.USER, "sa"); config.setProperty(Environment.PASS, ""); config.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread"); - config.setProperty(Environment.DIALECT,"org.hibernate.dialect.H2Dialect"); - config.setProperty(Environment.DRIVER,"org.h2.Driver"); + config.setProperty(Environment.DIALECT, "org.hibernate.dialect.H2Dialect"); + config.setProperty(Environment.DRIVER, "org.h2.Driver"); config.setProperty(Environment.URL, "jdbc:h2:file:target/" + TopiaTestCase.class.getSimpleName() + "/db/data_" + System.currentTimeMillis()); } @@ -85,17 +83,15 @@ public static void after() throws TopiaException { // destroy database context.clear(true); - + // TODO directory target/TopiaTestCase is not deleted } - /** - * Create base with schema created. - */ + /** Create base with schema created. */ @Before public void setUp() { - - if(log.isInfoEnabled()) { + + if (log.isInfoEnabled()) { log.info("Junit beforeTest"); } @@ -105,16 +101,16 @@ try { context.createSchema(); } catch (TopiaException e) { - log.error("Erreur à la creation du schema",e); + log.error("Erreur à la creation du schema", e); } } catch (TopiaNotFoundException e) { - log.error("Erreur à la creation du topia context",e); + log.error("Erreur à la creation du topia context", e); } } @Test public void testCompositeAssociations() { - if(log.isInfoEnabled()) { + if (log.isInfoEnabled()) { log.info("Junit Test testCompositeAssociations"); } @@ -154,15 +150,15 @@ companyDAO = TopiaTestDAOHelper.getCompanyDAO(newContext); - company = companyDAO.findByTopiaId(company.getId()); + company = companyDAO.findByTopiaId(company.getTopiaId()); - Assert.assertEquals(company.getName(),"Ma société"); - Assert.assertEquals(company.getDepartment().size(),4); + Assert.assertEquals(company.getName(), "Ma société"); + Assert.assertEquals(company.getDepartment().size(), 4); newContext.commitTransaction(); newContext.closeContext(); } catch (TopiaException e) { - log.error("Erreur pendant le test testCompositeAssociations",e); + log.error("Erreur pendant le test testCompositeAssociations", e); } } } Modified: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/ExportXMLVisitor.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/ExportXMLVisitor.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/ExportXMLVisitor.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -35,38 +35,38 @@ * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ @Ignore public class ExportXMLVisitor implements EntityVisitor { /** log. */ private static Log log = LogFactory.getLog(ExportXMLVisitor.class); - + protected StringBuffer buffer; - + public ExportXMLVisitor() { buffer = new StringBuffer(); } @Override public void start(TopiaEntity e) { - if(log.isDebugEnabled()) { + if (log.isDebugEnabled()) { log.debug("start : " + e); } buffer.append("<").append(e.getClass().getName()); - buffer.append(" topiaId=\"").append(e.getId()).append("\""); - buffer.append(" topiaCreateDate=\"").append(e.getCreateDate()).append("\""); - buffer.append(" topiaVersion=\"").append(e.getEntityVersion()).append("\""); + buffer.append(" topiaId=\"").append(e.getTopiaId()).append("\""); + buffer.append(" topiaCreateDate=\"").append(e.getTopiaCreateDate()).append("\""); + buffer.append(" topiaVersion=\"").append(e.getTopiaVersion()).append("\""); buffer.append(">\n"); } @Override public void visit(TopiaEntity e, String name, Class<?> type, Object value) { - if(log.isDebugEnabled()) { + if (log.isDebugEnabled()) { log.debug("visit : " + e); } @@ -75,7 +75,7 @@ @Override public void visit(TopiaEntity e, String name, Class<?> collectionType, Class<?> type, - Object value) { + Object value) { } @Override @@ -85,13 +85,13 @@ @Override public void end(TopiaEntity e) { - if(log.isDebugEnabled()) { + if (log.isDebugEnabled()) { log.debug("end : " + e); } buffer.append("</").append(e.getClass().getName()).append(">\n"); } - + @Override public String toString() { String content = buffer.toString(); @@ -104,5 +104,4 @@ } - } Modified: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/EntityOperatorTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/EntityOperatorTest.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/EntityOperatorTest.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -25,7 +25,6 @@ package org.nuiton.topia.persistence.util; -import java.util.Collection; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; @@ -40,23 +39,35 @@ import org.nuiton.topiatest.EmployeImpl; import org.nuiton.topiatest.Personne; import org.nuiton.topiatest.PersonneImpl; -import static org.junit.Assert.*; -/** - * - * @author tchemit <chemit@codelutin.com> - */ +import java.util.Collection; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** @author tchemit <chemit@codelutin.com> */ public class EntityOperatorTest { public EntityOperatorTest() { } + static EntityOperator<Company> operationC; + static EntityOperator<Employe> operationE; + static EntityOperator<Personne> operationP; + static EntityOperator<Department> operationD; + Company c; + Department d; + Employe e; + Personne p; @BeforeClass @@ -91,9 +102,7 @@ p = null; } - /** - * Test of newOperator method, of class EntityOperator. - */ + /** Test of newOperator method, of class EntityOperator. */ @Test public void testGet() { @@ -124,9 +133,7 @@ assertFalse(((Collection<?>) actual).isEmpty()); } - /** - * Test of set method, of class EntityOperator. - */ + /** Test of set method, of class EntityOperator. */ @Test public void testSet() { @@ -139,9 +146,7 @@ assertEquals(name, e.getName()); } - /** - * Test of getChild method, of class EntityOperator. - */ + /** Test of getChild method, of class EntityOperator. */ @Test public void testGetChild() { Object actual; @@ -164,16 +169,14 @@ actual = operationC.getChild(Company.DEPARTMENT, c, topiaId); assertNull(actual); - d.setId(topiaId); + d.setTopiaId(topiaId); actual = operationC.getChild(Company.DEPARTMENT, c, topiaId); assertNotNull(actual); assertEquals(d, actual); } - /** - * Test of addChild method, of class EntityOperator. - */ + /** Test of addChild method, of class EntityOperator. */ @Test public void testAddChild() { @@ -184,9 +187,7 @@ assertEquals(d, c.getDepartment().iterator().next()); } - /** - * Test of isChildEmpty method, of class EntityOperator. - */ + /** Test of isChildEmpty method, of class EntityOperator. */ @Test public void testIsChildEmpty() { @@ -201,9 +202,7 @@ assertFalse(actual); } - /** - * Test of sizeChild method, of class EntityOperator. - */ + /** Test of sizeChild method, of class EntityOperator. */ @Test public void testChildSize() { @@ -222,9 +221,7 @@ assertEquals(0, actual); } - /** - * Test of removeChild method, of class EntityOperator. - */ + /** Test of removeChild method, of class EntityOperator. */ @Test public void testRemoveChild() { Modified: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityBinderTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityBinderTest.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityBinderTest.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -47,8 +47,11 @@ } public static class CompanyDTO { + protected String name; + protected int siret; + protected String id; public String getName() { @@ -67,7 +70,7 @@ this.siret = siret; } - public String getId() { + public String getTopiaId() { return id; } @@ -87,7 +90,7 @@ BinderBuilder builder = new BinderBuilder(); builder.createBinderModel(Company.class, CompanyDTO.class); builder.addSimpleProperties(Company.NAME, Company.SIRET); - builder.addProperties(TopiaEntity.ID, "id"); + builder.addProperties(TopiaEntity.TOPIA_ID, "id"); BinderProvider.registerBinder(builder); Binder<Company, CompanyDTO> binder = 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-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -31,7 +31,12 @@ import org.nuiton.topia.persistence.TopiaEntity; import org.nuiton.topia.persistence.TopiaEntityEnum; -import java.util.*; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.SortedMap; import static java.util.Map.Entry; @@ -90,11 +95,11 @@ */ protected <T extends TopiaEntity> T newEntity( TopiaEntityEnum constant, String topiaId) throws - IllegalAccessException, - InstantiationException { + IllegalAccessException, + InstantiationException { Class<? extends TopiaEntity> impl = constant.getImplementation(); TopiaEntity topiaEntity = impl.newInstance(); - topiaEntity.setId(topiaId); + topiaEntity.setTopiaId(topiaId); return (T) topiaEntity; } @@ -111,7 +116,7 @@ * @return the reference of the association */ protected String getAssociationRef(String associationName, TopiaEntity e) { - return getAssociationRef(associationName, e.getId()); + return getAssociationRef(associationName, e.getTopiaId()); } /** @@ -268,7 +273,7 @@ TopiaEntity... expected) { Assert.assertNotNull(refs); Assert.assertTrue("no index [" + index + "] in refs of size " + - refs.size(), index < refs.size()); + refs.size(), index < refs.size()); TopiaEntityRef actual = refs.get(index); Assert.assertEquals(actual.getInvoker(), invoker); Assert.assertEquals(actual.getInvokerProperty(), invokerProperty); @@ -276,7 +281,7 @@ TopiaEntity[] path = actual.getPath(); Assert.assertEquals(expected.length, path.length); for (int i = 0; i < expected.length; i++) { - Assert.assertEquals(expected[i].getId(), path[i].getId()); + Assert.assertEquals(expected[i].getTopiaId(), path[i].getTopiaId()); } } Modified: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/DeleteEntityTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/DeleteEntityTest.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/DeleteEntityTest.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -38,8 +38,6 @@ package org.nuiton.topiatest.deletetest; -import java.net.URL; -import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.After; @@ -55,13 +53,20 @@ import org.nuiton.topiatest.Personne; import org.nuiton.topiatest.PersonneDAO; import org.nuiton.util.Resource; -import static org.junit.Assert.*; +import java.net.URL; +import java.util.Properties; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + /** - * Deleting tests with DAO and Entities generated with ToPIA (diagram delete-test in topiatest.zargo). - * Different case of deleting, with inheritance or NMultiplicity relationship between two entities, or both. - * Initiate from an issue with DAOAbstractGenerator delete method generation. - * Tests with H2 Database. Configuration in src/test/resources/TopiaContextImpl.properties + * Deleting tests with DAO and Entities generated with ToPIA (diagram + * delete-test in topiatest.zargo). Different case of deleting, with inheritance + * or NMultiplicity relationship between two entities, or both. Initiate from an + * issue with DAOAbstractGenerator delete method generation. Tests with H2 + * Database. Configuration in src/test/resources/TopiaContextImpl.properties */ public class DeleteEntityTest { @@ -88,7 +93,7 @@ log.info("Context Ready !"); } } catch (Exception ex) { - log.error("Initialize error !!",ex); + log.error("Initialize error !!", ex); } } @@ -107,9 +112,10 @@ } /** - * Test for deleting entities with inheritance. Delete from the DAO linked with the subclass - * entity and from the DAO linked with the superclass entity. In the test model, the two entities have - * NMultiplicity relationship without association class entity. + * Test for deleting entities with inheritance. Delete from the DAO linked + * with the subclass entity and from the DAO linked with the superclass + * entity. In the test model, the two entities have NMultiplicity + * relationship without association class entity. */ @Test public void testDeleteEntityWithInheritance() { @@ -121,9 +127,9 @@ PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction); log.debug("CREATE PERSONNE : Bob Marley"); - Personne personne = dao.create(Personne.NAME,"Bob Marley"); + Personne personne = dao.create(Personne.NAME, "Bob Marley"); transaction.commitTransaction(); - String idPersonne = personne.getId(); + String idPersonne = personne.getTopiaId(); assertNotNull(idPersonne); log.debug("ENTITY PERSONNE SAVED !"); @@ -135,9 +141,9 @@ log.debug("ENTITY PERSONNE DELETED !"); log.debug("CREATE PERSONNE : Ziggy Marley"); - Personne personne2 = dao.create(Personne.NAME,"Ziggy Marley"); + Personne personne2 = dao.create(Personne.NAME, "Ziggy Marley"); transaction.commitTransaction(); - String idPersonne2 = personne2.getId(); + String idPersonne2 = personne2.getTopiaId(); assertNotNull(idPersonne2); log.debug("ENTITY PERSONNE SAVED !"); @@ -153,15 +159,17 @@ transaction.closeContext(); } catch (TopiaException ex) { - log.error("TopiaException",ex); + log.error("TopiaException", ex); } log.debug("END TEST"); } /** - * Test for deleting entities with NMultiplicity relation without association class entity. - * Test DAO generation for deleting references between two entities with NMultiplicity relation. - * In the test model, the two entities have both inheritance. + * Test for deleting entities with NMultiplicity relation without + * association class entity. Test DAO generation for deleting references + * between two entities with NMultiplicity relation. In the test model, the + * two entities have both inheritance. + * * @see DAOAbstractTransformer */ @Test @@ -173,18 +181,18 @@ PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction); log.debug("CREATE PERSONNE : Bob Marley"); - Personne personne = dao.create(Personne.NAME,"Bob Marley"); + Personne personne = dao.create(Personne.NAME, "Bob Marley"); transaction.commitTransaction(); - String idPersonne = personne.getId(); + String idPersonne = personne.getTopiaId(); assertNotNull(idPersonne); log.debug("ENTITY PERSONNE SAVED !"); Contact2DAO contactDAO = TopiaTestDAOHelper.getContact2DAO(transaction); log.debug("CREATE CONTACT : jaja@codelutin.com"); - Contact2 contact = contactDAO.create(Contact2.CONTACT_VALUE,"jaja@codelutin.com"); + Contact2 contact = contactDAO.create(Contact2.CONTACT_VALUE, "jaja@codelutin.com"); transaction.commitTransaction(); - String idContact = contact.getId(); + String idContact = contact.getTopiaId(); assertNotNull(idContact); log.debug("ENTITY CONTACT SAVED !"); @@ -213,7 +221,7 @@ transaction.closeContext(); } catch (TopiaException ex) { - log.error("TopiaException",ex); + log.error("TopiaException", ex); } log.debug("END TEST"); } Modified: trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/ReplicationEngine.java =================================================================== --- trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/ReplicationEngine.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/ReplicationEngine.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -25,9 +25,19 @@ package org.nuiton.topia.replication; -import org.nuiton.topia.replication.model.ReplicationOperationDef; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.framework.TopiaContextImplementor; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.TopiaEntityEnum; +import org.nuiton.topia.persistence.util.TopiaEntityHelper; import org.nuiton.topia.replication.model.ReplicationModel; import org.nuiton.topia.replication.model.ReplicationNode; +import org.nuiton.topia.replication.model.ReplicationOperationDef; +import org.nuiton.topia.replication.model.ReplicationOperationPhase; + import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -36,41 +46,34 @@ import java.util.Map; import java.util.ServiceLoader; import java.util.Set; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.framework.TopiaContextImplementor; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaEntityEnum; -import org.nuiton.topia.persistence.util.TopiaEntityHelper; -import org.nuiton.topia.replication.model.ReplicationOperationPhase; + import static org.nuiton.i18n.I18n._; /** * Implantation du service de replication. - * + * * @author chemit */ public class ReplicationEngine implements TopiaReplicationImplementor { /** to use log facility, just put in your code: log.info(\"...\"); */ private static final Log log = LogFactory.getLog(ReplicationEngine.class); - /** - * le contexte sur la base source de la replication - */ + + /** le contexte sur la base source de la replication */ protected TopiaContextImplementor context; + /** - * la liste des operations disponibles (chargee automatiquement via un + * la liste des operations disponibles (chargee automatiquement via un * ServiceLoader sur le contract {@link TopiaReplicationOperation}) * - * @see #preInit(TopiaContextImplementor) + * @see #preInit(TopiaContextImplementor) */ protected static TopiaReplicationOperation[] operations; //-------------------------------------------------------------------------- //-- TopiaService implementation ------------------------------------------- //-------------------------------------------------------------------------- + @Override public String getServiceName() { return SERVICE_NAME; @@ -123,6 +126,7 @@ //-------------------------------------------------------------------------- //-- TopiaReplicationService implementation -------------------------------- //-------------------------------------------------------------------------- + @Override public ReplicationModel prepare(TopiaEntityEnum[] contracts, String... entities) throws TopiaException { ReplicationModel model = createModel(contracts, entities); @@ -215,6 +219,7 @@ //-------------------------------------------------------------------------- //-- TopiaReplicationImplementor implementation ---------------------------- //-------------------------------------------------------------------------- + @Override public ReplicationModel createModel(TopiaEntityEnum[] contracts, String... topiaIds) throws TopiaException { Set<Class<? extends TopiaEntity>> detectTypes = detectTypes(contracts, topiaIds); @@ -382,7 +387,7 @@ public static <E extends TopiaEntity> List<E> getEntities(TopiaContextImplementor srcCtxt, List<E> entityList, boolean canBeNull) throws TopiaException { List<E> srcList = new ArrayList<E>(entityList.size()); for (E e : entityList) { - E e2 = (E) srcCtxt.findById(e.getId()); + E e2 = (E) srcCtxt.findByTopiaId(e.getTopiaId()); if (e2 == null && !canBeNull) { if (!canBeNull) { throw new IllegalStateException("topia.replication.engine.error.entity.must.exists"); @@ -398,7 +403,7 @@ TopiaEntity[] srcList = new TopiaEntity[entityList.length]; int index = 0; for (String id : entityList) { - TopiaEntity e2 = srcCtxt.findById(id); + TopiaEntity e2 = srcCtxt.findByTopiaId(id); srcList[index++] = e2; } return srcList; @@ -407,7 +412,7 @@ public static List<? extends TopiaEntity> getEntitiesList(TopiaContext srcCtxt, String... entityList) throws TopiaException { List<TopiaEntity> srcList = new ArrayList<TopiaEntity>(entityList.length); for (String id : entityList) { - TopiaEntity e2 = srcCtxt.findById(id); + TopiaEntity e2 = srcCtxt.findByTopiaId(id); srcList.add(e2); } return srcList; Modified: trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachAssociation.java =================================================================== --- trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachAssociation.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachAssociation.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -25,11 +25,6 @@ package org.nuiton.topia.replication.operation; -import org.nuiton.topia.replication.*; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuiton.topia.TopiaException; @@ -37,32 +32,40 @@ import org.nuiton.topia.persistence.TopiaEntity; import org.nuiton.topia.persistence.util.EntityOperator; import org.nuiton.topia.persistence.util.TopiaEntityHelper; +import org.nuiton.topia.replication.ReplicationEngine; +import org.nuiton.topia.replication.TopiaReplicationOperation; import org.nuiton.topia.replication.model.ReplicationModel; import org.nuiton.topia.replication.model.ReplicationNode; import org.nuiton.topia.replication.model.ReplicationOperationDef; import org.nuiton.topia.replication.model.ReplicationOperationPhase; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; + import static org.nuiton.i18n.I18n._; /** * Pour attacher une association. - * + * <p/> * Deux cas peuvent se produire : - * + * <p/> * - le noeud de l'operation est la source de l'association, dans ce cas la - * <code>nodeEntities</code> contient les entites sources de l'association et - * on retrouve les entites associes a partir du type de l'association - * + * <code>nodeEntities</code> contient les entites sources de l'association et on + * retrouve les entites associes a partir du type de l'association + * <p/> * Ce premier cas est verifie quand reverse (le econd parametre) est a false - * + * <p/> * - le noeud de l'operation est la cible de l'association, dans ce cas la * <code>nodeEntities</code> contient les entities associes (cibles) de * l'assocation et on retrouve les entities a partir d'un troisieme parametre * qui donne le node source des entities sources. - * - * Note : cette operation est interne, et n'est pas creable par - * l'utilisateur via la methode - * {@link #register(ReplicationModel, ReplicationNode, ReplicationOperationPhase, Object...)}. - * + * <p/> + * Note : cette operation est interne, et n'est pas creable par l'utilisateur + * via la methode {@link #register(ReplicationModel, ReplicationNode, + * ReplicationOperationPhase, Object...)}. + * * @author chemit */ public class AttachAssociation implements TopiaReplicationOperation { @@ -78,10 +81,10 @@ @Override public void run(ReplicationOperationDef operationDef, - TopiaContextImplementor srcCtxt, - TopiaContextImplementor dstCtxt, - List<? extends TopiaEntity> nodeEntities, - Map<Class<? extends TopiaEntity>, List<String>> data) throws TopiaException { + TopiaContextImplementor srcCtxt, + TopiaContextImplementor dstCtxt, + List<? extends TopiaEntity> nodeEntities, + Map<Class<? extends TopiaEntity>, List<String>> data) throws TopiaException { String name = (String) operationDef.getParameters()[0]; Boolean reverse = (Boolean) operationDef.getParameters()[1]; @@ -175,7 +178,7 @@ // l'entite repliquee a laquelle on veut attacher l'association - TopiaEntity dst = dstCtxt.findById(src.getId()); + TopiaEntity dst = dstCtxt.findByTopiaId(src.getTopiaId()); // les association cibles connues pour l'entite sur la base destination Collection<?> dstTargetEntities = (Collection<?>) ownerOperator.get(name, dst); @@ -188,8 +191,8 @@ TopiaEntity assosiationSrc = (TopiaEntity) a; // on verifie que l'association doit etre rattachee - if (associationsId.contains(assosiationSrc.getId())) { - if (dstTargetAssociationsId.contains(assosiationSrc.getId())) { + if (associationsId.contains(assosiationSrc.getTopiaId())) { + if (dstTargetAssociationsId.contains(assosiationSrc.getTopiaId())) { // deja attache if (log.isDebugEnabled()) { log.debug("already attached association '" + name + "' : " + assosiationSrc); @@ -200,7 +203,7 @@ // la donnees doit etre attachee - TopiaEntity assosiationDst = dstCtxt.findById(assosiationSrc.getId()); + TopiaEntity assosiationDst = dstCtxt.findByTopiaId(assosiationSrc.getTopiaId()); ownerOperator.addChild(name, dst, assosiationDst); if (log.isDebugEnabled()) { log.debug("will attach association '" + name + "' : " + assosiationDst); @@ -212,7 +215,7 @@ if (shouldUpdate) { if (log.isTraceEnabled()) { - log.trace("will update " + dst.getId()); + log.trace("will update " + dst.getTopiaId()); } //FIXME: on ne peut pas updater l'objet car l'objet peut rentre // en conflit dans la session hibernate Modified: trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachDependency.java =================================================================== --- trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachDependency.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachDependency.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -25,29 +25,31 @@ package org.nuiton.topia.replication.operation; -import org.nuiton.topia.replication.*; -import java.util.List; -import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuiton.topia.TopiaException; import org.nuiton.topia.framework.TopiaContextImplementor; import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.replication.TopiaReplicationOperation; import org.nuiton.topia.replication.model.ReplicationModel; import org.nuiton.topia.replication.model.ReplicationNode; import org.nuiton.topia.replication.model.ReplicationOperationDef; import org.nuiton.topia.replication.model.ReplicationOperationPhase; + +import java.util.List; +import java.util.Map; + import static org.nuiton.i18n.I18n._; /** * Pour attacher une dependance. - * + * <p/> * TODO non implante pour le moment + * <p/> + * Note : cette operation est interne, et n'est pas creable par l'utilisateur + * via la methode {@link #register(ReplicationModel, ReplicationNode, + * ReplicationOperationPhase, Object...)}. * - * Note : cette operation est interne, et n'est pas creable par - * l'utilisateur via la methode - * {@link #register(ReplicationModel, ReplicationNode, ReplicationOperationPhase, Object...)}. - * * @author chemit */ public class AttachDependency implements TopiaReplicationOperation { @@ -56,15 +58,15 @@ @Override public void register(ReplicationModel model, ReplicationNode ownerNode, ReplicationOperationPhase phase, Object... parameters) { - throw new UnsupportedOperationException(_("topia.replication.operation.error.uncreatable",getClass())); + throw new UnsupportedOperationException(_("topia.replication.operation.error.uncreatable", getClass())); } @Override public void run(ReplicationOperationDef operationDef, - TopiaContextImplementor srcCtxt, - TopiaContextImplementor dstCtxt, - List<? extends TopiaEntity> nodeEntities, - Map<Class<? extends TopiaEntity>, List<String>> data) throws TopiaException { + TopiaContextImplementor srcCtxt, + TopiaContextImplementor dstCtxt, + List<? extends TopiaEntity> nodeEntities, + Map<Class<? extends TopiaEntity>, List<String>> data) throws TopiaException { throw new UnsupportedOperationException(_("topia.replication.operation.error.notImplemented", getClass())); @@ -99,15 +101,15 @@ // // les association connues // TopiaEntity target = (TopiaEntity) ownerOperator.get(name, src); // -// if (target == null || !targetIds.contains(target.getId())) { +// if (target == null || !targetIds.contains(target.getTopiaId())) { // // pas de donnees a attacher, ou pas pour ce src // continue; // } // // // l'entite cible -// TopiaEntity dst = dstCtxt.findById(src.getId()); +// TopiaEntity dst = dstCtxt.findByTopiaId(src.getTopiaId()); // -// target = dstCtxt.findById(target.getId()); +// target = dstCtxt.findByTopiaId(target.getTopiaId()); // // ownerOperator.set(name, dst, target); // Modified: trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachLink.java =================================================================== --- trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachLink.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachLink.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -25,11 +25,6 @@ package org.nuiton.topia.replication.operation; -import org.nuiton.topia.replication.*; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuiton.topia.TopiaException; @@ -37,33 +32,41 @@ import org.nuiton.topia.persistence.TopiaEntity; import org.nuiton.topia.persistence.util.EntityOperator; import org.nuiton.topia.persistence.util.TopiaEntityHelper; +import org.nuiton.topia.replication.ReplicationEngine; +import org.nuiton.topia.replication.TopiaReplicationOperation; import org.nuiton.topia.replication.model.Link; import org.nuiton.topia.replication.model.ReplicationModel; import org.nuiton.topia.replication.model.ReplicationNode; import org.nuiton.topia.replication.model.ReplicationOperationDef; import org.nuiton.topia.replication.model.ReplicationOperationPhase; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; + import static org.nuiton.i18n.I18n._; /** * Pour attacher une association. - * + * <p/> * Deux cas peuvent se produire : - * + * <p/> * - le noeud de l'operation est la source de l'association, dans ce cas la - * <code>nodeEntities</code> contient les entites sources de l'association et - * on retrouve les entites associes a partir du type de l'association - * + * <code>nodeEntities</code> contient les entites sources de l'association et on + * retrouve les entites associes a partir du type de l'association + * <p/> * Ce premier cas est verifie quand reverse (le econd parametre) est a false - * + * <p/> * - le noeud de l'operation est la cible de l'association, dans ce cas la * <code>nodeEntities</code> contient les entities associes (cibles) de * l'assocation et on retrouve les entities a partir d'un troisieme parametre * qui donne le node source des entities sources. - * - * Note : cette operation est interne, et n'est pas creable par - * l'utilisateur via la methode - * {@link #register(ReplicationModel, ReplicationNode, ReplicationOperationPhase, Object...)}. - * + * <p/> + * Note : cette operation est interne, et n'est pas creable par l'utilisateur + * via la methode {@link #register(ReplicationModel, ReplicationNode, + * ReplicationOperationPhase, Object...)}. + * * @author chemit */ public class AttachLink implements TopiaReplicationOperation { @@ -79,10 +82,10 @@ @Override public void run(ReplicationOperationDef operationDef, - TopiaContextImplementor srcCtxt, - TopiaContextImplementor dstCtxt, - List<? extends TopiaEntity> nodeEntities, - Map<Class<? extends TopiaEntity>, List<String>> data) throws TopiaException { + TopiaContextImplementor srcCtxt, + TopiaContextImplementor dstCtxt, + List<? extends TopiaEntity> nodeEntities, + Map<Class<? extends TopiaEntity>, List<String>> data) throws TopiaException { Link link = (Link) operationDef.getParameters()[0]; @@ -163,7 +166,7 @@ // l'entite repliquee a laquelle on veut attacher l'association - TopiaEntity dst = dstCtxt.findById(src.getId()); + TopiaEntity dst = dstCtxt.findByTopiaId(src.getTopiaId()); // les association cibles connues pour l'entite sur la base destination Collection<?> dstTargetEntities = (Collection<?>) ownerOperator.get(name, dst); @@ -176,8 +179,8 @@ TopiaEntity assosiationSrc = (TopiaEntity) a; // on verifie que l'association doit etre rattachee - if (associationIds.contains(assosiationSrc.getId())) { - if (dstTargetAssociationsId.contains(assosiationSrc.getId())) { + if (associationIds.contains(assosiationSrc.getTopiaId())) { + if (dstTargetAssociationsId.contains(assosiationSrc.getTopiaId())) { // deja attache if (log.isDebugEnabled()) { log.debug("already attached association '" + name + "' : " + assosiationSrc); @@ -188,7 +191,7 @@ // la donnees doit etre attachee - TopiaEntity assosiationDst = dstCtxt.findById(assosiationSrc.getId()); + TopiaEntity assosiationDst = dstCtxt.findByTopiaId(assosiationSrc.getTopiaId()); ownerOperator.addChild(name, dst, assosiationDst); if (log.isDebugEnabled()) { log.debug("will attach association '" + name + "' : " + assosiationDst); @@ -200,7 +203,7 @@ if (shouldUpdate) { if (log.isTraceEnabled()) { - log.trace("will update " + dst.getId()); + log.trace("will update " + dst.getTopiaId()); } //FIXME: on ne peut pas updater l'objet car l'objet peut rentre // en conflit dans la session hibernate 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-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractReplicationEngineTest.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -25,47 +25,62 @@ package org.nuiton.topia.replication; -import java.io.File; -import java.util.*; - +import org.apache.commons.logging.Log; +import org.junit.Assert; import org.nuiton.i18n.I18n; -import org.nuiton.topia.persistence.util.EntityOperator; -import org.nuiton.topia.replication.model.ReplicationModel; -import org.nuiton.topia.replication.model.ReplicationOperationDef; -import org.nuiton.topia.replication.model.ReplicationNode; +import org.nuiton.topia.TopiaContext; import org.nuiton.topia.TopiaException; +import org.nuiton.topia.framework.TopiaContextImplementor; +import org.nuiton.topia.persistence.TopiaDAO; import org.nuiton.topia.persistence.TopiaEntity; import org.nuiton.topia.persistence.TopiaEntityEnum; - -import org.nuiton.topia.TopiaContext; -import org.junit.Assert; - -import org.apache.commons.logging.Log; -import org.nuiton.topia.framework.TopiaContextImplementor; -import org.nuiton.topia.persistence.TopiaDAO; +import org.nuiton.topia.persistence.util.EntityOperator; import org.nuiton.topia.persistence.util.EntityOperatorStore; import org.nuiton.topia.persistence.util.TopiaEntityHelper; +import org.nuiton.topia.replication.model.ReplicationModel; +import org.nuiton.topia.replication.model.ReplicationNode; +import org.nuiton.topia.replication.model.ReplicationOperationDef; +import java.io.File; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Set; + /** * ReplicationEngineTest. - * + * <p/> * Created: 07 jun. 09 17:14:22 * * @author tchemit * @version $Revision$ - * - * Last update: $Date$ - * by : */ + * <p/> + * Last update: $Date$ + * by : + */ public abstract class AbstractReplicationEngineTest extends Assert { static protected TopiaContext context; + static protected TopiaContext ctxt; + protected TopiaContextImplementor dstCtxt; + protected TopiaReplicationImplementor service; + protected ReplicationModel model; - static protected 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"; public static void after() throws Exception { @@ -123,11 +138,12 @@ protected abstract Log getLog(); protected <E extends TopiaEntity> E update(E e) throws TopiaException { - return (E) ((TopiaContextImplementor) ctxt).findById(e.getId()); + return (E) ((TopiaContextImplementor) ctxt).findByTopiaId(e.getTopiaId()); } /** * Test of detectTypes method, of class ReplicationServiceImplementor. + * * @throws Exception if any error */ public void testDetectTypes() throws Exception { @@ -135,6 +151,7 @@ /** * Test of getOperation method, of class ReplicationServiceImplementor. + * * @throws Exception if any error */ public void testGetOperation() throws Exception { @@ -142,6 +159,7 @@ /** * Test of detectAssociations method, of class ReplicationModel. + * * @throws Exception if any error */ public void testDetectAssociations() throws Exception { @@ -149,6 +167,7 @@ /** * Test of detectDirectDependencies method, of class ReplicationModel. + * * @throws Exception if any error */ public void testDetectDirectDependencies() throws Exception { @@ -156,6 +175,7 @@ /** * Test of detectShell method, of class ReplicationModel. + * * @throws Exception if any error */ public void testDetectShell() throws Exception { @@ -163,6 +183,7 @@ /** * Test of detectDependencies method, of class ReplicationModel. + * * @throws Exception if any error */ public void testDetectDependencies() throws Exception { @@ -170,6 +191,7 @@ /** * Test of detectObjectsToDettach method, of class ReplicationModel. + * * @throws Exception if any error */ public void testDetectObjectsToDettach() throws Exception { @@ -177,6 +199,7 @@ /** * Test of detectOperations method, of class ReplicationModel. + * * @throws Exception if any error */ public void testDetectOperations() throws Exception { @@ -184,6 +207,7 @@ /** * Test of doReplicate method, of class ReplicationService. + * * @throws Exception if any error */ public void testDoReplicate() throws Exception { @@ -193,11 +217,11 @@ Set<?> detectTypes; - detectTypes = service.detectTypes(getContracts(), entity.getId()); - assertEquals("expected types : "+ - Arrays.toString(expectedCouple) + - " but was "+detectTypes, - expectedCouple.length, detectTypes.size()); + detectTypes = service.detectTypes(getContracts(), entity.getTopiaId()); + assertEquals("expected types : " + + Arrays.toString(expectedCouple) + + " but was " + detectTypes, + expectedCouple.length, detectTypes.size()); for (Object o : expectedCouple) { assertTrue(detectTypes.contains(o)); } @@ -221,7 +245,7 @@ TopiaEntityEnum src = (TopiaEntityEnum) expectedCouple[2 * i]; String name = (String) expectedCouple[2 * i + 1]; ReplicationNode nodeSrc = model.getNode(src); - assertNotNull("association "+name+" not found", nodeSrc); + assertNotNull("association " + name + " not found", nodeSrc); assertTrue(nodeSrc.hasAssociation()); assertTrue(nodeSrc.getAssociations().containsKey(name)); } @@ -247,7 +271,7 @@ protected void detectShell(TopiaEntity entity, TopiaEntityEnum... expected) throws - TopiaException { + TopiaException { Set<ReplicationNode> shell; createModel(entity); @@ -260,9 +284,9 @@ assertNotNull(c); shell = model.getNode(c.getContract()).getShell(); assertEquals( - "expected shell : "+ Arrays.toString(expected) + ", but was " + - shell, expected.length, shell.size()); - + "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()); @@ -291,7 +315,7 @@ // // Iterator<List<ReplicationNode>> order = dependencies.iterator(); // if (entity != null) { -// getLog().info("for " + entity.getId()); +// getLog().info("for " + entity.getTopiaId()); // } // int index = 0; // for (TopiaEntityEnum[] expectedLevel : expected) { @@ -346,7 +370,7 @@ if (entity == null) { prepareModel(); } else { - prepareModel(entity.getId()); + prepareModel(entity.getTopiaId()); } // createModel(entity); // model.detectAssociations(); @@ -362,7 +386,7 @@ getLog().info("resume of operations for all "); } else { - getLog().info("resume of operations for entity " + entity.getId()); + getLog().info("resume of operations for entity " + entity.getTopiaId()); } for (ReplicationNode node : model.getOrder()) { @@ -374,6 +398,7 @@ getLog().info("=========================================================================="); } } + private static int dbCounter; protected void doReplicate(TopiaEntityEnum contract, TopiaEntity... entity) throws Exception { @@ -398,7 +423,7 @@ dstCtxt = (TopiaContextImplementor) rootCtxt.beginTransaction(); for (TopiaEntity e : entity) { - TopiaEntity actual = dstCtxt.findById(e.getId()); + TopiaEntity actual = dstCtxt.findByTopiaId(e.getTopiaId()); assertNotNull(actual); assertEquals(e, actual); } @@ -440,7 +465,7 @@ service.doReplicate(model, dstCtxt); - getLog().info("replication is done for "+Arrays.toString(entity)+", will verify data..."); + getLog().info("replication is done for " + Arrays.toString(entity) + ", will verify data..."); TopiaContextImplementor ctxt2 = (TopiaContextImplementor) ctxt; dstCtxt = (TopiaContextImplementor) rootCtxt.beginTransaction(); @@ -456,7 +481,7 @@ Set<String> ids = new HashSet<String>(); if (getLog().isInfoEnabled()) { - getLog().info("will verify db for contracts "+ Arrays.toString(contracts)); + getLog().info("will verify db for contracts " + Arrays.toString(contracts)); } for (TopiaEntityEnum c : contracts) { if (getLog().isDebugEnabled()) { @@ -476,8 +501,8 @@ if (getLog().isDebugEnabled()) { getLog().debug("verify for entity " + id); } - TopiaEntity eSrc = daoSrc.findById(id); - TopiaEntity eDst = daoDst.findById(id); + TopiaEntity eSrc = daoSrc.findByTopiaId(id); + TopiaEntity eDst = daoDst.findByTopiaId(id); assertEquals(eSrc, eDst); assertEntityEquals(eSrc, eDst, ids); } @@ -488,26 +513,26 @@ if (treated == null) { treated = new HashSet<String>(); } - if (treated.contains(actual.getId())) { + if (treated.contains(actual.getTopiaId())) { return; } if (getLog().isDebugEnabled()) { getLog().debug(expected); } - assertEquals(actual.getId(), expected.getId()); - treated.add(actual.getId()); + assertEquals(actual.getTopiaId(), expected.getTopiaId()); + treated.add(actual.getTopiaId()); if (getLog().isDebugEnabled()) { getLog().debug("expected : " + expected + " / actual " + actual); } TopiaEntityEnum contract = TopiaEntityHelper.getEntityEnum(expected.getClass(), getContracts()); - if (contract==null) { + 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); + "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) { @@ -563,8 +588,8 @@ protected void createUnsupportedBeforeOperation(TopiaEntityEnum contract, TopiaEntity entity, Class<? extends TopiaReplicationOperation> operationClass, Object... parameters) throws Exception { - getLog().info("entity " + entity.getId()); - prepareModel(entity.getId()); + getLog().info("entity " + entity.getTopiaId()); + prepareModel(entity.getTopiaId()); service.addBeforeOperation(model, contract, operationClass, parameters); // on ne doit pas avoir le droit de creer cette operation @@ -573,8 +598,8 @@ protected void createUnsupportedAfterOperation(TopiaEntityEnum contract, TopiaEntity entity, Class<? extends TopiaReplicationOperation> operationClass, Object... parameters) throws Exception { - getLog().info("entity " + entity.getId()); - prepareModel(entity.getId()); + getLog().info("entity " + entity.getTopiaId()); + prepareModel(entity.getTopiaId()); // model = service.createModel(getContracts()); // model.detectDirectDependencies(); service.addAfterOperation(model, contract, operationClass, parameters); @@ -604,7 +629,7 @@ } protected void createModel(TopiaEntity entity) throws TopiaException { - model = service.createModel(getContracts(), entity.getId()); + model = service.createModel(getContracts(), entity.getTopiaId()); } protected void prepareModel(String... ids) throws TopiaException { Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/ReplicationEngineTest.java =================================================================== --- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/ReplicationEngineTest.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/ReplicationEngineTest.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -248,11 +248,11 @@ } /** - * Cette methode montre pourquoi la simple replication - * ne peut pas fonctionne :) + * Cette methode montre pourquoi la simple replication ne peut pas + * fonctionne :) * <p/> - * Le replicateur ne deplique pas dans le bon ordre et on - * a donc des violations de clef etrangeres... + * Le replicateur ne deplique pas dans le bon ordre et on a donc des + * violations de clef etrangeres... * * @throws Exception pour toute erreur */ @@ -261,7 +261,7 @@ TopiaContext dstRootCtxt = createDb2("testSimpleReplicateFailed"); - //model = service.prepare(contracts, pet.getId()); + //model = service.prepare(contracts, pet.getTopiaId()); TopiaContext srcCtxt = ctxt.beginTransaction(); dstCtxt = (TopiaContextImplementor) dstRootCtxt.beginTransaction(); @@ -280,11 +280,11 @@ } /** - * Cette methode montre comment manuellement on peut effectuer la replication - * (en dettachant les dependances qui forment des cyles) + * Cette methode montre comment manuellement on peut effectuer la + * replication (en dettachant les dependances qui forment des cyles) * <p/> - * La methode utilisee ici peut ne pas fonctionner : si une clef metier - * est posee sur une dependance alors cela ne fonctionne pas. + * La methode utilisee ici peut ne pas fonctionner : si une clef metier est + * posee sur une dependance alors cela ne fonctionne pas. * * @throws Exception pour toute erreur */ @@ -293,7 +293,7 @@ TopiaContext dstRootCtxt = createDb2("testSimpleReplicateNotSure"); - //model = service.prepare(contracts, pet.getId()); + //model = service.prepare(contracts, pet.getTopiaId()); TopiaContext srcCtxt = ctxt; dstCtxt = (TopiaContextImplementor) dstRootCtxt.beginTransaction(); @@ -312,13 +312,13 @@ srcCtxt.replicateEntity(dstCtxt, person); dstCtxt.commitTransaction(); - ((Pet) dstCtxt.findById(pet.getId())).setPerson((Person) dstCtxt.findById(person.getId())); + ((Pet) dstCtxt.findByTopiaId(pet.getTopiaId())).setPerson((Person) dstCtxt.findByTopiaId(person.getTopiaId())); dstCtxt.commitTransaction(); srcCtxt.rollbackTransaction(); person = update(person); - assertEntityEquals(person, dstCtxt.findById(person.getId()), null); + assertEntityEquals(person, dstCtxt.findByTopiaId(person.getTopiaId()), null); } finally { srcCtxt.rollbackTransaction(); //srcCtxt.closeContext(); @@ -327,16 +327,17 @@ } /** - * Cette methode montre comment manuellement on peut effectuer la replication - * (en dettachant les associations qui forment des cyles) + * Cette methode montre comment manuellement on peut effectuer la + * replication (en dettachant les associations qui forment des cyles) * <p/> * La methode utilisee ici fonctionne mieux que la precedante : il parrait * dificille de pose une une clef metier sur une association :). * <p/> - * On remarque que l'on dettache l'assocation qui forme un cycle et que l'on est - * pas obligee de la reattachee car elle est bi-directionnelle. + * On remarque que l'on dettache l'assocation qui forme un cycle et que l'on + * est pas obligee de la reattachee car elle est bi-directionnelle. * <p/> - * On doit optimiser l'algorithme dans la methode {@link ReplicationModel#adjustOperations(Map)}. + * On doit optimiser l'algorithme dans la methode {@link + * ReplicationModel#adjustOperations(Map)}. * * @throws Exception pour toute erreur */ @@ -345,7 +346,7 @@ TopiaContext dstRootCtxt = createDb2("testSimpleReplicateSure"); - //model = service.prepare(contracts, pet.getId()); + //model = service.prepare(contracts, pet.getTopiaId()); TopiaContext srcCtxt = ctxt; dstCtxt = (TopiaContextImplementor) dstRootCtxt.beginTransaction(); @@ -361,7 +362,7 @@ srcCtxt.rollbackTransaction(); dstCtxt.commitTransaction(); - //((Person) dstCtxt.findById(person.getId())).addPet(((Pet) dstCtxt.findById(pet.getId()))); + //((Person) dstCtxt.findByTopiaId(person.getTopiaId())).addPet(((Pet) dstCtxt.findByTopiaId(pet.getTopiaId()))); //dstCtxt.commitTransaction(); srcCtxt.rollbackTransaction(); @@ -374,7 +375,7 @@ person = update(person); - assertEntityEquals(person, dstCtxt.findById(person.getId()), null); + assertEntityEquals(person, dstCtxt.findByTopiaId(person.getTopiaId()), null); } finally { dstCtxt.closeContext(); Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java =================================================================== --- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -25,20 +25,16 @@ package org.nuiton.topia.replication; -import java.io.File; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; -import org.nuiton.topia.framework.TopiaContextImplementor; -import org.nuiton.topia.test.entities.*; -import org.junit.Test; - -import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; +import org.junit.Test; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaTestDAOHelper.TopiaTestEntityEnum; +import org.nuiton.topia.framework.TopiaContextImplementor; import org.nuiton.topia.persistence.TopiaEntityEnum; import org.nuiton.topia.replication.model.ReplicationOperationPhase; import org.nuiton.topia.replication.operation.AttachAssociation; @@ -49,26 +45,40 @@ import org.nuiton.topia.replication.operation.FakeOperation; import org.nuiton.topia.replication.operation.UncreatableOperation; import org.nuiton.topia.replication.operation.UnregistredOperation; +import org.nuiton.topia.test.entities.Person; +import org.nuiton.topia.test.entities.PersonImpl; +import org.nuiton.topia.test.entities.Pet; +import org.nuiton.topia.test.entities.PetImpl; +import org.nuiton.topia.test.entities.Race; +import org.nuiton.topia.test.entities.RaceImpl; +import java.io.File; +import java.util.Properties; + /** * ReplicationEngineTest on model TopiaTest - * + * <p/> * Created: 07 jun. 09 17:14:22 * * @author tchemit * @version $Revision$ - * - * Last update: $Date$ - * by : $Author$ + * <p/> + * Last update: $Date$ + * by : $Author$ */ public class TopiaReplicationOperationTest extends AbstractReplicationEngineTest { /** to use log facility, just put in your code: log.info(\"...\"); */ private static final Log log = LogFactory.getLog(ReplicationEngineTest.class); + protected static final TopiaEntityEnum[] contracts = {TopiaTestEntityEnum.Person, TopiaTestEntityEnum.Pet, TopiaTestEntityEnum.Race}; + protected static final String entitiesList = PersonImpl.class.getName() + "," + PetImpl.class.getName() + "," + RaceImpl.class.getName(); + static protected Person person, person2; + static protected Pet pet, pet2; + static protected Race race, race2; @AfterClass @@ -100,12 +110,14 @@ } // @Ignore + @Test(expected = NullPointerException.class) public void testGetOperation_nullOperationClass() throws Exception { service.getOperation(null); } // @Ignore + @Test(expected = IllegalStateException.class) public void testGetOperation_serviceNotInit() throws Exception { ReplicationEngine.operations = null; @@ -123,6 +135,7 @@ } // @Ignore + @Test @Override public void testGetOperation() throws Exception { @@ -138,12 +151,14 @@ } // @Ignore + @Test(expected = NullPointerException.class) public void testCreateOperation_nullModel() throws Exception { service.createOperation(null, null, null, null); } // @Ignore + @Test(expected = NullPointerException.class) public void testCreateOperation_nullType() throws Exception { @@ -152,6 +167,7 @@ } // @Ignore + @Test(expected = NullPointerException.class) public void testCreateOperation_nullPhase() throws Exception { @@ -160,6 +176,7 @@ } // @Ignore + @Test(expected = NullPointerException.class) public void testCreateOperation_nullOperationClass() throws Exception { @@ -168,6 +185,7 @@ } // @Ignore + @Test(expected = IllegalArgumentException.class) public void testCreateOperation_noNode() throws Exception { @@ -177,6 +195,7 @@ } // @Ignore + @Test(expected = IllegalArgumentException.class) public void testCreateOperation_noOperation() throws Exception { @@ -186,119 +205,137 @@ } // @Ignore + @Test(expected = UnsupportedOperationException.class) public void testCreateUnsupportedBeforeOperation_Duplicate() throws Exception { createUnsupportedBeforeOperation(TopiaTestEntityEnum.Person, person, Duplicate.class); } // @Ignore + @Test(expected = UnsupportedOperationException.class) public void testCreateUnsupportedBeforeOperation_AttachAssociation() throws Exception { createUnsupportedBeforeOperation(TopiaTestEntityEnum.Person, person, AttachAssociation.class); } // @Ignore + @Test(expected = UnsupportedOperationException.class) public void testCreateUnsupportedBeforeOperation_DetachAssociation() throws Exception { createUnsupportedBeforeOperation(TopiaTestEntityEnum.Person, person, DettachAssociation.class); } // @Ignore + @Test(expected = UnsupportedOperationException.class) public void testCreateUnsupportedBeforeOperation_AttachDependency() throws Exception { createUnsupportedBeforeOperation(TopiaTestEntityEnum.Person, person, AttachDependency.class); } // @Ignore + @Test(expected = UnsupportedOperationException.class) public void testCreateUnsupportedBeforeOperation_DetachDependency() throws Exception { createUnsupportedBeforeOperation(TopiaTestEntityEnum.Person, person, DettachDependency.class); } // @Ignore + @Test(expected = UnsupportedOperationException.class) public void testCreateUnsupportedAfterOperation_Duplicate() throws Exception { createUnsupportedAfterOperation(TopiaTestEntityEnum.Person, person, Duplicate.class); } // @Ignore + @Test(expected = UnsupportedOperationException.class) public void testCreateUnsupportedAfterOperation_AttachAssociation() throws Exception { createUnsupportedAfterOperation(TopiaTestEntityEnum.Person, person, AttachAssociation.class); } // @Ignore + @Test(expected = UnsupportedOperationException.class) public void testCreateUnsupportedAfterOperation_DetachAssociation() throws Exception { createUnsupportedAfterOperation(TopiaTestEntityEnum.Person, person, DettachAssociation.class); } // @Ignore + @Test(expected = UnsupportedOperationException.class) public void testCreateUnsupportedAfterOperation_AttachDependency() throws Exception { createUnsupportedAfterOperation(TopiaTestEntityEnum.Person, person, AttachDependency.class); } // @Ignore + @Test(expected = UnsupportedOperationException.class) public void testCreateUnsupportedAfterOperation_DetachDependency() throws Exception { createUnsupportedAfterOperation(TopiaTestEntityEnum.Person, person, DettachDependency.class); } // @Ignore + @Test(expected = UnsupportedOperationException.class) public void testCreateUnsupportedBeforeOperation_UncreatableOperation() throws Exception { createUnsupportedBeforeOperation(TopiaTestEntityEnum.Person, person, UncreatableOperation.class); } // @Ignore + @Test(expected = UnsupportedOperationException.class) public void testCreateUnsupportedAfterOperation_UncreatableOperation() throws Exception { createUnsupportedAfterOperation(TopiaTestEntityEnum.Person, person, UncreatableOperation.class); } // @Ignore + @Test(expected = IllegalArgumentException.class) public void testCreateOperation_wrongParameterNumber() throws Exception { - model = service.createModel(contracts, pet.getId()); + model = service.createModel(contracts, pet.getTopiaId()); service.addBeforeOperation(model, TopiaTestEntityEnum.Pet, FakeOperation.class); } // @Ignore + @Test(expected = IllegalArgumentException.class) public void testCreateOperation_wrongParameterNumber2() throws Exception { - model = service.createModel(contracts, pet.getId()); + model = service.createModel(contracts, pet.getTopiaId()); service.addBeforeOperation(model, TopiaTestEntityEnum.Pet, FakeOperation.class, String.class, String.class); } // @Ignore + @Test(expected = IllegalArgumentException.class) public void testCreateOperation_wrongParameterType() throws Exception { - model = service.createModel(contracts, pet.getId()); + model = service.createModel(contracts, pet.getTopiaId()); service.addBeforeOperation(model, TopiaTestEntityEnum.Pet, FakeOperation.class, Integer.class); } // @Ignore + @Test(expected = IllegalArgumentException.class) public void testCreateOperation_nullParameter() throws Exception { - model = service.createModel(contracts, pet.getId()); + model = service.createModel(contracts, pet.getTopiaId()); service.addBeforeOperation(model, TopiaTestEntityEnum.Pet, FakeOperation.class, (Object) null); } // @Ignore + @Test public void testCreateOperation() throws Exception { - model = service.createModel(contracts, pet.getId()); + model = service.createModel(contracts, pet.getTopiaId()); service.addBeforeOperation(model, TopiaTestEntityEnum.Pet, FakeOperation.class, "before"); service.addAfterOperation(model, TopiaTestEntityEnum.Race, FakeOperation.class, "after"); } // @Ignore + @Test(expected = NullPointerException.class) public void testDoReplicate_nullModel() throws Exception { @@ -306,6 +343,7 @@ } // @Ignore + @Test(expected = NullPointerException.class) public void testDoReplicate_nullDstCtxt() throws Exception { Modified: trunk/topia-service-security/src/main/java/org/nuiton/topia/security/TopiaSecurityServiceImpl.java =================================================================== --- trunk/topia-service-security/src/main/java/org/nuiton/topia/security/TopiaSecurityServiceImpl.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-service-security/src/main/java/org/nuiton/topia/security/TopiaSecurityServiceImpl.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -25,24 +25,6 @@ package org.nuiton.topia.security; -import static org.nuiton.topia.security.util.TopiaSecurityUtil.CREATE; -import static org.nuiton.topia.security.util.TopiaSecurityUtil.DELETE; -import static org.nuiton.topia.security.util.TopiaSecurityUtil.TOPIA_SECURITY_PERSISTENCE_CLASSES; -import static org.nuiton.topia.security.util.TopiaSecurityUtil.UPDATE; - -import java.security.AccessController; -import java.security.Permission; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.security.auth.Subject; -import javax.security.auth.login.Configuration; - import org.apache.commons.collections.map.ReferenceMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -76,40 +58,68 @@ import org.nuiton.topia.security.util.TopiaSecurityCaching; import org.nuiton.topia.security.util.TopiaSecurityUtil; +import javax.security.auth.Subject; +import javax.security.auth.login.Configuration; +import java.security.AccessController; +import java.security.Permission; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.nuiton.topia.security.util.TopiaSecurityUtil.CREATE; +import static org.nuiton.topia.security.util.TopiaSecurityUtil.DELETE; +import static org.nuiton.topia.security.util.TopiaSecurityUtil.TOPIA_SECURITY_PERSISTENCE_CLASSES; +import static org.nuiton.topia.security.util.TopiaSecurityUtil.UPDATE; + /** * Implantation du manager pour la securite. C'est le point d'acces a l'ensemble * des fonctionnalites de la securite. - * + * * @author ruchaud */ public class TopiaSecurityServiceImpl implements TopiaSecurityService, - TopiaTransactionVetoable { + TopiaTransactionVetoable { /** to use log facility, just put in your code: log.info(\"...\"); */ static private Log log = LogFactory.getLog(TopiaSecurityServiceImpl.class); - + /* Context ToPIA */ + private TopiaContext rootContext; + private TopiaContext securityContext; - + /* Listeners */ + private EntityVetoable entityVetoable = new EntityVetoable(this); + private PropertyReadListener read = new PropertyReadListener(this); + private PropertyWriteListener write = new PropertyWriteListener(this); + private PropertyVetoable propertyVetoable = new PropertyVetoable(read, write); - + /* Policy */ + private TopiaPolicy policy = new TopiaPolicy(this); - + /* Cache */ + transient private TopiaSecurityCaching entitiesLoadingCache = new TopiaSecurityCaching(2); + transient private Map<String, Permission> authorizationsCache = - Collections.synchronizedMap(new ReferenceMap(ReferenceMap.SOFT, ReferenceMap.SOFT)); + Collections.synchronizedMap(new ReferenceMap(ReferenceMap.SOFT, ReferenceMap.SOFT)); + transient private Map<String, Set<Permission>> permissionsCache = - Collections.synchronizedMap(new ReferenceMap(ReferenceMap.SOFT, ReferenceMap.SOFT)); - + Collections.synchronizedMap(new ReferenceMap(ReferenceMap.SOFT, ReferenceMap.SOFT)); + /** - * Constructeur. Initialise la s�curit� � partir du contexte passer en param�tre + * Constructeur. Initialise la s�curit� � partir du contexte passer en + * param�tre */ public TopiaSecurityServiceImpl() { } @@ -117,15 +127,17 @@ /* (non-Javadoc) * @see org.nuiton.topia.framework.TopiaService#getServiceName() */ + @Override public String getServiceName() { return SERVICE_NAME; } - + /* - * (non-Javadoc) - * @see org.nuiton.topia.security.TopiaSecurityManager#getPersistenceClasses() - */ + * (non-Javadoc) + * @see org.nuiton.topia.security.TopiaSecurityManager#getPersistenceClasses() + */ + @Override public Class<?>[] getPersistenceClasses() { return TOPIA_SECURITY_PERSISTENCE_CLASSES; @@ -135,15 +147,17 @@ * (non-Javadoc) * @see org.nuiton.topia.security.TopiaSecurityManager#init() */ + @Override public boolean preInit(TopiaContextImplementor context) { return true; } - + /* - * (non-Javadoc) - * @see org.nuiton.topia.security.TopiaSecurityManager#init() - */ + * (non-Javadoc) + * @see org.nuiton.topia.security.TopiaSecurityManager#init() + */ + @Override public boolean postInit(TopiaContextImplementor context) { rootContext = context; @@ -152,15 +166,16 @@ rootContext.addTopiaEntityVetoable(entityVetoable); rootContext.addTopiaEntityListener(propertyVetoable); rootContext.addTopiaTransactionVetoable(this); - + policy.installPolicy(); Configuration.setConfiguration(new TopiaConfiguration("topia", this)); - + return true; } /** * Permet de propager la s�curit� sur l'ensemble des contextes + * * @param event */ @Override @@ -175,8 +190,9 @@ * (non-Javadoc) * @see org.nuiton.topia.security.TopiaSecurityManager#getSecurityContext() */ + public TopiaContext getSecurityContext() throws TopiaException { - if(securityContext == null) { + if (securityContext == null) { securityContext = rootContext.beginTransaction(); } return securityContext; @@ -184,6 +200,7 @@ /** * Permet de r�cup�rer le DAO dans le contexte de s�curit�. + * * @return DAO du TopiaUser */ public TopiaUserDAO getTopiaUserDAO() { @@ -197,6 +214,7 @@ /** * Permet de r�cup�rer le DAO dans le contexte de s�curit�. + * * @return DAO du TopiaGroup */ public TopiaGroupDAO getTopiaGroupDAO() { @@ -210,6 +228,7 @@ /** * Permet de r�cup�rer le DAO dans le contexte de s�curit�. + * * @return DAO du TopiaAuthorization */ public TopiaAuthorizationDAO getTopiaAuthorizationDAO() { @@ -223,6 +242,7 @@ /** * Permet de r�cup�rer le DAO dans le contexte de s�curit�. + * * @return DAO du TopiaEntityAuthorization */ public TopiaEntityAuthorizationDAO getTopiaEntityAuthorizationDAO() { @@ -236,6 +256,7 @@ /** * Permet de r�cup�rer le DAO dans le contexte de s�curit�. + * * @return DAO du TopiaExpressionLinkDAO */ public TopiaExpressionLinkDAO getTopiaIdLinkDAO() { @@ -249,6 +270,7 @@ /** * Permet de r�cup�rer le DAO dans le contexte de s�curit�. + * * @return DAO du TopiaAssociationAuthorization */ public TopiaAssociationAuthorizationDAO getTopiaAssociationAuthorizationDAO() { @@ -262,25 +284,27 @@ /** * Permet d'ajouter dans le cache les permissions pour un principal donn�. - * @param principalName nom du principal pour lequel on doit charg� les permissions + * + * @param principalName nom du principal pour lequel on doit charg� les + * permissions * @return la liste des permissions * @throws TopiaException */ public Set<Permission> putPermissionsCache(String principalName) throws TopiaException { TopiaAuthorizationDAO authorizationDAO = getTopiaAuthorizationDAO(); Collection<TopiaAuthorization> authorizations = authorizationDAO.findAll(); - + Set<Permission> permissions = new HashSet<Permission>(); permissionsCache.put(principalName, permissions); - + String className = TopiaId.getClassNameAsString(principalName); // AddEmptyPrincipals pr�cise si il faut les autorisations dont les principals sont vide boolean addEmptyPrincipals = className.equals(TopiaUser.class.getName()); - + for (TopiaAuthorization authorization : authorizations) { Set<?> principals = authorization.getPrincipals(); - if(principals.contains(principalName) - || addEmptyPrincipals && principals.isEmpty()) { + if (principals.contains(principalName) + || addEmptyPrincipals && principals.isEmpty()) { Permission permission = getAuthorizationCache(authorization); permissions.add(permission); } @@ -290,69 +314,76 @@ } /** - * Permet de r�cup�rer dans le cache l'encapsulation de l'autorisation en permission - * et cr�er l'encapsulation si elle n'existe pas dans le cache - * @param authorization autorisation recherch� + * Permet de r�cup�rer dans le cache l'encapsulation de l'autorisation en + * permission et cr�er l'encapsulation si elle n'existe pas dans le cache + * + * @param authorization autorisation recherch� * @return permission encapsulation de l'autorisation en permission */ private Permission getAuthorizationCache(TopiaAuthorization authorization) { - String topiaIdAuthorization = authorization.getId(); + String topiaIdAuthorization = authorization.getTopiaId(); Permission permission = authorizationsCache.get(topiaIdAuthorization); - if(permission == null) { + if (permission == null) { permission = new TopiaPermission(authorization); authorizationsCache.put(topiaIdAuthorization, permission); } return permission; } - + /** - * Permet de r�cup�rer depuis le cache les permissions pour un principal donn�. + * Permet de r�cup�rer depuis le cache les permissions pour un principal + * donn�. + * * @param principalName nom du principal * @return permmissions d'un principal */ public Set<Permission> getPermissionsCache(String principalName) { return permissionsCache.get(principalName); } - + /** * Permet de mettre dans le cache pour l'utilisateur en cours si il a droit * l'autorisation ou non de charger une entit�. - * @param topiaId identification de l'entit� - * @param authorized autorisation sur l'entit�, true pour autoris� et false pour - * non autoris� + * + * @param topiaId identification de l'entit� + * @param authorized autorisation sur l'entit�, true pour autoris� et false + * pour non autoris� */ public void putEntitiesLoadingCache(String topiaId, boolean authorized) { String userPrincipal = TopiaSecurityUtil.getUserPrincipal(); - if(userPrincipal != null) { + if (userPrincipal != null) { entitiesLoadingCache.put(authorized, userPrincipal, topiaId); } } - + /** - * Permet de r�cup�rer dans le cache pour l'utilisateur en cours si il a droit - * l'autorisation ou non de charger une entit�. + * Permet de r�cup�rer dans le cache pour l'utilisateur en cours si il a + * droit l'autorisation ou non de charger une entit�. + * * @param topiaId identification de l'entit� - * @return autorisation sur l'entit�, true pour autoris� et false pour - * non autoris� + * @return autorisation sur l'entit�, true pour autoris� et false pour non + * autoris� */ public Boolean getEntitiesLoadingCache(String topiaId) { String userPrincipal = TopiaSecurityUtil.getUserPrincipal(); - if(userPrincipal != null) { + if (userPrincipal != null) { return (Boolean) entitiesLoadingCache.get(userPrincipal, topiaId); } return null; } - + /** * Permet de supprimer un entr�e dans le cache pour un utilisateur + * * @param userPrincipal principal de l'utilisateur */ public void removeEntitiesLoadingCache(String userPrincipal) { entitiesLoadingCache.clear(userPrincipal); } - + /** * Permet de tester le cache + * * @param topiaId identification de l'entit� * @return vrai si il trouve sinon faux */ @@ -360,35 +391,37 @@ Boolean authorized = getEntitiesLoadingCache(topiaId); return authorized != null; } - + /** - * Renvoi les identifiants qui remplacent l'identifiant en cours d'apr�s la table - * de correspondance TopiaExpressionLink. + * Renvoi les identifiants qui remplacent l'identifiant en cours d'apr�s la + * table de correspondance TopiaExpressionLink. + * * @param topiaId identifiant � remplacer * @return retourne l'identifiant remplac� */ //FIXME : Voir si on peut mettre en relation un objet vers plusieurs objets protected List<String> getRealExpressions(String topiaId) { try { - List<String> allBy = getSecurityContext().find("select distinct link.by from " + + List<String> allBy = getSecurityContext().find("select distinct link.by from " + TopiaExpressionLink.class.getName() + " link where link.replace=:replace", "replace", topiaId); - getSecurityContext().commitTransaction(); - - if(allBy == null) { + getSecurityContext().commitTransaction(); + + if (allBy == null) { allBy = new ArrayList<String>(); - } - - allBy.add(topiaId); - return allBy; + } + + allBy.add(topiaId); + return allBy; } catch (TopiaException te) { throw new SecurityException("Replace expression for link failed", te); } } - + /** - * Permet de determiner seulement les actions pour lesquelles on doit v�rifier - * les actions. + * Permet de determiner seulement les actions pour lesquelles on doit + * v�rifier les actions. + * * @param topiaId identifiant de l'entit� ToPIA * @param actions actions � v�rifier * @return actions r�ellement � v�rifer @@ -396,13 +429,13 @@ protected int getRealActions(String topiaId, int actions) { try { Class<?> klass = TopiaId.getClassName(topiaId); - + //if(TopiaSecurityUtil.isImplement(klass, NoSecurityLoad.class)) { if (NoSecurityLoad.class.isAssignableFrom(klass)) { //LOAD actions &= UPDATE + DELETE + CREATE; } - + /* TODO: if(TopiaSecurityUtil.isImplement(klass, NoSecurityUpdate.class)) { // UPDATE @@ -411,7 +444,7 @@ ... */ } catch (TopiaNotFoundException te) { - if(log.isDebugEnabled()) { + if (log.isDebugEnabled()) { log.debug("Real actions failed", te); } } @@ -420,6 +453,7 @@ /* (non-Javadoc) * @see org.nuiton.topia.security.TopiaSecurityService#checkPermission(java.lang.Class, int) */ + @Override public void checkPermission(Class<?> entityClass, int actions) throws SecurityException { if (log.isTraceEnabled()) { @@ -435,15 +469,16 @@ /* (non-Javadoc) * @see org.nuiton.topia.security.TopiaSecurityService#checkPermission(java.lang.String, int) */ + @Override public void checkPermission(String topiaId, int actions) throws SecurityException { int realActions = getRealActions(topiaId, actions); /* Il reste des actions � v�rifier */ - if(realActions != 0) { + if (realActions != 0) { Subject subject = Subject.getSubject(AccessController.getContext()); if (subject != null) { List<String> expressions = getRealExpressions(topiaId); - + boolean authorized = false; for (String expression : expressions) { TopiaEntityAuthorization authorization = new TopiaEntityAuthorizationImpl( @@ -456,12 +491,12 @@ authorized = false; } } - - if(!authorized) { + + if (!authorized) { throw new SecurityException("Access denied to object \"" + topiaId + "\" for \"" + subject + "\""); } } else { - if(log.isWarnEnabled()) { + if (log.isWarnEnabled()) { log.warn("Use doAs() and login first"); } } Modified: trunk/topia-service-security/src/main/java/org/nuiton/topia/security/jaas/TopiaLoginModule.java =================================================================== --- trunk/topia-service-security/src/main/java/org/nuiton/topia/security/jaas/TopiaLoginModule.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-service-security/src/main/java/org/nuiton/topia/security/jaas/TopiaLoginModule.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -37,14 +37,14 @@ package org.nuiton.topia.security.jaas; -import static org.nuiton.topia.security.util.TopiaSecurityUtil.SECURITY_MANAGER_KEY; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.security.TopiaSecurityServiceImpl; +import org.nuiton.topia.security.entities.user.TopiaGroup; +import org.nuiton.topia.security.entities.user.TopiaUser; +import org.nuiton.topia.security.entities.user.TopiaUserDAO; -import java.security.Principal; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; @@ -52,17 +52,18 @@ import javax.security.auth.callback.PasswordCallback; import javax.security.auth.login.LoginException; import javax.security.auth.spi.LoginModule; +import java.security.Principal; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.security.TopiaSecurityServiceImpl; -import org.nuiton.topia.security.entities.user.TopiaGroup; -import org.nuiton.topia.security.entities.user.TopiaUser; -import org.nuiton.topia.security.entities.user.TopiaUserDAO; +import static org.nuiton.topia.security.util.TopiaSecurityUtil.SECURITY_MANAGER_KEY; /** - * LoginModule permettant l'authentification d'un utilisateur au pr�s du syst�me. + * LoginModule permettant l'authentification d'un utilisateur au pr�s du + * syst�me. + * * @author ruchaud */ public class TopiaLoginModule implements LoginModule { @@ -70,8 +71,11 @@ private Log log = LogFactory.getLog(TopiaLoginModule.class); private Subject subject; + private CallbackHandler callbackHandler; + private Set<Principal> principals; + private TopiaSecurityServiceImpl securityManager; /* (non-Javadoc) @@ -81,17 +85,19 @@ * java.util.Map, * java.util.Map) */ + public void initialize(Subject subject, CallbackHandler callbackHandler, - Map<String,?> sharedState, Map<String,?> options) { + Map<String, ?> sharedState, Map<String, ?> options) { this.subject = subject; this.callbackHandler = callbackHandler; principals = null; - securityManager = (TopiaSecurityServiceImpl)options.get(SECURITY_MANAGER_KEY); + securityManager = (TopiaSecurityServiceImpl) options.get(SECURITY_MANAGER_KEY); } /* (non-Javadoc) * @see javax.security.auth.spi.LoginModule#login() */ + public boolean login() throws LoginException { if (callbackHandler == null) { throw new LoginException("CallbackHandler cannot be null"); @@ -131,34 +137,34 @@ TopiaUserDAO topiaUserDAO = securityManager.getTopiaUserDAO(); TopiaUser user = topiaUserDAO.findByLogin(login); - if(user != null && user.checkPassword(password)) { + if (user != null && user.checkPassword(password)) { // R�cup�ration des principals principals = new HashSet<Principal>(); - - String topiaIdUser = user.getId(); + + String topiaIdUser = user.getTopiaId(); principals.add(new TopiaPrincipal(topiaIdUser)); securityManager.putPermissionsCache(topiaIdUser); securityManager.removeEntitiesLoadingCache(topiaIdUser); - + // Force le rechargement des groupes d'o� la non utilisation de // la m�thode : user.getTopiaGroup() Set<TopiaGroup> groups = new HashSet<TopiaGroup>(securityManager.getSecurityContext().find( "select topiaGroup from " + TopiaGroup.class.getName() + - " topiaGroup join topiaGroup.topiaUser as topiaUser where topiaUser = :user", "user", user)); - - if(groups != null) { - for(TopiaGroup group : groups) { - for (TopiaGroup superGroup : (List<TopiaGroup>)group.getAllSuperGroup()) { - String topiaIdGroup = superGroup.getId(); + " topiaGroup join topiaGroup.topiaUser as topiaUser where topiaUser = :user", "user", user)); + + if (groups != null) { + for (TopiaGroup group : groups) { + for (TopiaGroup superGroup : (List<TopiaGroup>) group.getAllSuperGroup()) { + String topiaIdGroup = superGroup.getTopiaId(); principals.add(new TopiaPrincipal(topiaIdGroup)); securityManager.putPermissionsCache(topiaIdGroup); } - String topiaIdGroup = group.getId(); + String topiaIdGroup = group.getTopiaId(); principals.add(new TopiaPrincipal(topiaIdGroup)); securityManager.putPermissionsCache(topiaIdGroup); } } - + securityManager.getSecurityContext().commitTransaction(); } else { // Echec d'authentification @@ -181,6 +187,7 @@ /* (non-Javadoc) * @see javax.security.auth.spi.LoginModule#commit() */ + public boolean commit() throws LoginException { subject.getPrincipals().addAll(principals); return true; @@ -189,6 +196,7 @@ /* (non-Javadoc) * @see javax.security.auth.spi.LoginModule#abort() */ + public boolean abort() throws LoginException { //On effectue les m�mes actions que logout return logout(); @@ -197,6 +205,7 @@ /* (non-Javadoc) * @see javax.security.auth.spi.LoginModule#logout() */ + public boolean logout() throws LoginException { //On lib�re les ressources subject.getPrincipals().removeAll(principals); Modified: trunk/topia-service-security/src/main/java/org/nuiton/topia/security/listener/EntityVetoable.java =================================================================== --- trunk/topia-service-security/src/main/java/org/nuiton/topia/security/listener/EntityVetoable.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-service-security/src/main/java/org/nuiton/topia/security/listener/EntityVetoable.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -37,10 +37,6 @@ package org.nuiton.topia.security.listener; -import static org.nuiton.topia.security.util.TopiaSecurityUtil.CREATE; -import static org.nuiton.topia.security.util.TopiaSecurityUtil.DELETE; -import static org.nuiton.topia.security.util.TopiaSecurityUtil.LOAD; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuiton.topia.TopiaNotFoundException; @@ -50,17 +46,22 @@ import org.nuiton.topia.persistence.TopiaId; import org.nuiton.topia.security.TopiaSecurityServiceImpl; +import static org.nuiton.topia.security.util.TopiaSecurityUtil.CREATE; +import static org.nuiton.topia.security.util.TopiaSecurityUtil.DELETE; +import static org.nuiton.topia.security.util.TopiaSecurityUtil.LOAD; + /** * Listenner permettant de vérifier les autorisations pour la création ou la - * suppression d'une entité. + * suppression d'une entité. + * * @author ruchaud */ public class EntityVetoable implements TopiaEntityVetoable { private static Log log = LogFactory.getLog(EntityVetoable.class); - + private TopiaSecurityServiceImpl securityManager; - + public EntityVetoable(TopiaSecurityServiceImpl securityManager) { this.securityManager = securityManager; } @@ -68,7 +69,7 @@ @Override public void create(TopiaEntityEvent event) { TopiaEntity entity = event.getEntity(); - String topiaId = entity.getId(); + String topiaId = entity.getTopiaId(); Class<? extends TopiaEntity> clazz; try { clazz = TopiaId.getClassName(topiaId); @@ -76,7 +77,7 @@ // Ne devrait jamais ce produire throw new SecurityException("Access denied to entity creation", e); } - + if (log.isDebugEnabled()) { log.debug("[Security] create entity : " + clazz.getName()); } @@ -85,7 +86,7 @@ @Override public void delete(TopiaEntityEvent event) { - String topiaId = event.getEntity().getId(); + String topiaId = event.getEntity().getTopiaId(); if (log.isDebugEnabled()) { log.debug("[Security] delete entity : " + topiaId); } @@ -93,10 +94,10 @@ } @Override - public void load(TopiaEntityEvent event) { + public void load(TopiaEntityEvent event) { boolean authorized = true; TopiaEntity entity = event.getEntity(); - String topiaId = entity.getId(); + String topiaId = entity.getTopiaId(); if (log.isDebugEnabled()) { log.debug("[Security] load entity : " + topiaId); @@ -104,15 +105,15 @@ /* Vérification dans le cache */ boolean contain = securityManager.containEntitiesLoadingCache(topiaId); - - if(!contain) { + + if (!contain) { try { securityManager.checkPermission(topiaId, LOAD); - + } catch (SecurityException te) { authorized = false; } - + /* Mise en cache */ securityManager.putEntitiesLoadingCache(topiaId, authorized); } Modified: trunk/topia-service-security/src/main/java/org/nuiton/topia/security/listener/PropertyReadListener.java =================================================================== --- trunk/topia-service-security/src/main/java/org/nuiton/topia/security/listener/PropertyReadListener.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-service-security/src/main/java/org/nuiton/topia/security/listener/PropertyReadListener.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -25,20 +25,21 @@ package org.nuiton.topia.security.listener; -import static org.nuiton.topia.security.util.TopiaSecurityUtil.LOAD; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.topia.persistence.TopiaEntityAbstract; +import org.nuiton.topia.security.TopiaSecurityServiceImpl; import java.beans.PropertyChangeEvent; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.persistence.TopiaEntityAbstract; -import org.nuiton.topia.security.TopiaSecurityServiceImpl; +import static org.nuiton.topia.security.util.TopiaSecurityUtil.LOAD; /** * Listenner permettant de vérifier les autorisations pour la chargement d'une * propriété sur une entités. + * * @author ruchaud */ //TODO: Gestion d'une sécurité partiel ou total c'est à dire retour d'une valeur par défaut @@ -47,7 +48,7 @@ private static Log log = LogFactory.getLog(PropertyReadListener.class); private TopiaSecurityServiceImpl securityManager; - + public PropertyReadListener(TopiaSecurityServiceImpl securityManager) { this.securityManager = securityManager; } @@ -56,21 +57,21 @@ public void vetoableChange(PropertyChangeEvent event) throws PropertyVetoException { Object source = event.getSource(); TopiaEntityAbstract entity = (TopiaEntityAbstract) source; - + /* Vérification dans le cache */ - Boolean authorized = securityManager.getEntitiesLoadingCache(entity.getId()); - if(authorized != null) { - if(!authorized) { - throw new SecurityException("Access denied to Read entity " + entity.getId() + " on " + event.getPropertyName()); + Boolean authorized = securityManager.getEntitiesLoadingCache(entity.getTopiaId()); + if (authorized != null) { + if (!authorized) { + throw new SecurityException("Access denied to Read entity " + entity.getTopiaId() + " on " + event.getPropertyName()); } } else { // Sinon try { - securityManager.checkPermission(entity.getId(), LOAD); + securityManager.checkPermission(entity.getTopiaId(), LOAD); } catch (SecurityException te) { if (log.isWarnEnabled()) { - log.warn("[Security] Read denied to : " + entity.getId(), te); + log.warn("[Security] Read denied to : " + entity.getTopiaId(), te); } - throw new SecurityException("Access denied to Read entity " + entity.getId() + " on " + event.getPropertyName(), te); + throw new SecurityException("Access denied to Read entity " + entity.getTopiaId() + " on " + event.getPropertyName(), te); } } Modified: trunk/topia-service-security/src/main/java/org/nuiton/topia/security/listener/PropertyWriteListener.java =================================================================== --- trunk/topia-service-security/src/main/java/org/nuiton/topia/security/listener/PropertyWriteListener.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-service-security/src/main/java/org/nuiton/topia/security/listener/PropertyWriteListener.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -25,20 +25,21 @@ package org.nuiton.topia.security.listener; -import static org.nuiton.topia.security.util.TopiaSecurityUtil.UPDATE; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.topia.persistence.TopiaEntityAbstract; +import org.nuiton.topia.security.TopiaSecurityServiceImpl; import java.beans.PropertyChangeEvent; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.persistence.TopiaEntityAbstract; -import org.nuiton.topia.security.TopiaSecurityServiceImpl; +import static org.nuiton.topia.security.util.TopiaSecurityUtil.UPDATE; /** * Listenner permettant de vérifier les autorisations pour le modification d'une * propriété sur une entités. + * * @author ruchaud */ public class PropertyWriteListener implements VetoableChangeListener { @@ -46,7 +47,7 @@ private static Log log = LogFactory.getLog(PropertyWriteListener.class); private TopiaSecurityServiceImpl securityManager; - + public PropertyWriteListener(TopiaSecurityServiceImpl securityManager) { this.securityManager = securityManager; } @@ -56,12 +57,12 @@ Object source = event.getSource(); TopiaEntityAbstract entity = (TopiaEntityAbstract) source; try { - securityManager.checkPermission(entity.getId(), UPDATE); + securityManager.checkPermission(entity.getTopiaId(), UPDATE); } catch (SecurityException te) { if (log.isWarnEnabled()) { - log.warn("[Security] Write denied to : " + entity.getId(), te); + log.warn("[Security] Write denied to : " + entity.getTopiaId(), te); } - throw new SecurityException("Access denied to Write entity " + entity.getId() + " on " + event.getPropertyName(), te); + throw new SecurityException("Access denied to Write entity " + entity.getTopiaId() + " on " + event.getPropertyName(), te); } } Modified: trunk/topia-service-security/src/main/java/org/nuiton/topia/security/util/TopiaSecurityFactoryFilter.java =================================================================== --- trunk/topia-service-security/src/main/java/org/nuiton/topia/security/util/TopiaSecurityFactoryFilter.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-service-security/src/main/java/org/nuiton/topia/security/util/TopiaSecurityFactoryFilter.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -25,61 +25,64 @@ package org.nuiton.topia.security.util; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.security.TopiaSecurityService; + import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.security.TopiaSecurityService; - /** - * La classe permet de filtrer n'importe quel objet (Collection, List, TopiaEntity, ...) - * par rapport à une permission. + * La classe permet de filtrer n'importe quel objet (Collection, List, + * TopiaEntity, ...) par rapport à une permission. + * * @author ruchaud */ public class TopiaSecurityFactoryFilter { - + /** to use log facility, just put in your code: log.info(\"...\"); */ static private Log log = LogFactory.getLog(TopiaSecurityUtil.class); private static final long serialVersionUID = 1L; - + private TopiaSecurityService securityManager; - + public TopiaSecurityFactoryFilter(TopiaSecurityService securityManager) { this.securityManager = securityManager; } - public void filter(Collection<TopiaEntity> entities, int actions, String ... fields) { + public void filter(Collection<TopiaEntity> entities, int actions, String... fields) { //TODO: Gestion des autorisations sur les champs (cf TopiaEntityAuthorization) throw new UnsupportedOperationException(); } - + /** * Filtre une entité - * @param entity entité à filtrer + * + * @param entity entité à filtrer * @param actions la filtre * @return null si non autorisé sinon l'entité */ public TopiaEntity filter(TopiaEntity entity, int actions) { try { - securityManager.checkPermission(entity.getId(), actions); + securityManager.checkPermission(entity.getTopiaId(), actions); } catch (SecurityException e) { - if(log.isDebugEnabled()) { + if (log.isDebugEnabled()) { log.debug("Return Null because : " + e); } return null; } return entity; } - + /** * Filtre une collection + * * @param entities la collection à filtrer - * @param actions le filtre + * @param actions le filtre * @return la collection filtrée */ public <E extends TopiaEntity> Collection<E> filter(Collection<E> entities, int actions) { @@ -87,10 +90,10 @@ for (Iterator<?> iterator = result.iterator(); iterator.hasNext();) { TopiaEntity entity = (TopiaEntity) iterator.next(); try { - securityManager.checkPermission(entity.getId(), actions); + securityManager.checkPermission(entity.getTopiaId(), actions); } catch (SecurityException e) { iterator.remove(); - if(log.isDebugEnabled()) { + if (log.isDebugEnabled()) { log.debug("Removed because : " + e); } } @@ -100,12 +103,13 @@ /** * Filtre sur une liste + * * @param entities la liste à filtrer - * @param actions le filtre + * @param actions le filtre * @return la liste filtrée */ public <E extends TopiaEntity> List<E> filter(List<E> entities, int actions) { - return (List<E>) filter((Collection<E>)entities, actions); + return (List<E>) filter((Collection<E>) entities, actions); } - + } Modified: trunk/topia-service-security/src/main/java/org/nuiton/topia/taas/TaasService.java =================================================================== --- trunk/topia-service-security/src/main/java/org/nuiton/topia/taas/TaasService.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-service-security/src/main/java/org/nuiton/topia/taas/TaasService.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -36,17 +36,6 @@ package org.nuiton.topia.taas; -import java.lang.reflect.Constructor; -import java.security.AccessController; -import java.security.Permission; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; - -import javax.security.auth.Subject; -import javax.security.auth.login.Configuration; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuiton.topia.TopiaContext; @@ -63,7 +52,6 @@ import org.nuiton.topia.taas.entities.TaasAuthorizationImpl; import org.nuiton.topia.taas.entities.TaasPrincipalImpl; import org.nuiton.topia.taas.entities.TaasUserImpl; - import org.nuiton.topia.taas.event.TaasAccessEntity; import org.nuiton.topia.taas.event.TaasEntityVetoable; import org.nuiton.topia.taas.jaas.TaasConfiguration; @@ -72,39 +60,52 @@ import org.nuiton.topia.taas.jaas.TaasPolicy; import org.nuiton.topia.taas.jaas.TaasSubjectFinder; import org.nuiton.topia.taas.jaas.TaasSubjectFinderImpl; + +import javax.security.auth.Subject; +import javax.security.auth.login.Configuration; +import java.lang.reflect.Constructor; +import java.security.AccessController; +import java.security.Permission; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Properties; + import static org.nuiton.topia.taas.TaasUtil.getPrincipalNames; /** * Service pour la s�curit� - * <p> - * Pour utiliser le service taas, il suffit de rajouter les lignes suivantes dans - * le TopiaContext.properties :<p> - * topia.service.taas=org.nuiton.topia.taas.TaasService + * <p/> + * Pour utiliser le service taas, il suffit de rajouter les lignes suivantes + * dans le TopiaContext.properties :<p> topia.service.taas=org.nuiton.topia.taas.TaasService * topia.service.taas.event=org.nuiton.topia.taas.event.TaasEntityVetoable * topia.service.taas.subject=org.nuiton.topia.taas.jaas.TaasSubjectImpl - * + * * @author julien - * */ public class TaasService implements TopiaService, TopiaTransactionVetoable { static private Log log = LogFactory.getLog(TaasService.class); public static final String SERVICE_NAME = "taas"; + public static final String SERVICE_LOGIN_MODULE = TaasLoginModule.class.getName(); + public static final String SERVICE_EVENT = "topia.service.taas.event"; + public static final String SERVICE_SUBJECT = "topia.service.taas.subject"; private TaasPolicy policy = new TaasPolicy(this); + private TopiaContextImplementor rootContext; + private TopiaContext rootContextNoSecure; private TaasAccessEntity accessEntity; + private TaasSubjectFinder subjectFinder; - - /** - * Contructeur par d�faut - */ + + /** Contructeur par d�faut */ public TaasService() { } @@ -112,9 +113,10 @@ * (non-Javadoc) * @see org.nuiton.topia.framework.TopiaService#getPersistenceClasses() */ + @Override public Class<?>[] getPersistenceClasses() { - return new Class<?>[] { + return new Class<?>[]{ TaasUserImpl.class, TaasPrincipalImpl.class, TaasAuthorizationImpl.class, @@ -125,6 +127,7 @@ * (non-Javadoc) * @see org.nuiton.topia.framework.TopiaService#getServiceName() */ + @Override public String getServiceName() { return SERVICE_NAME; @@ -134,39 +137,40 @@ * (non-Javadoc) * @see org.nuiton.topia.framework.TopiaService#preInit(org.nuiton.topia.framework.TopiaContextImplementor) */ + @Override public boolean preInit(TopiaContextImplementor context) { rootContext = context; initSecurity(rootContext); try { org.hibernate.cfg.Configuration configuration = rootContext.getHibernateConfiguration(); - + // Recuperation du parametre pour l'evenemnt String eventString = configuration.getProperty(SERVICE_EVENT); - if(eventString != null && !"".equals(eventString)) { + if (eventString != null && !"".equals(eventString)) { Class<?> eventClass = Class.forName(eventString); Constructor<?> eventConstructor = eventClass.getConstructor(TaasService.class); accessEntity = (TaasAccessEntity) eventConstructor.newInstance(this); } else { accessEntity = new TaasEntityVetoable(this); } - + // Recuperation du parametre pour le subject String subjectString = configuration.getProperty(SERVICE_SUBJECT); - if(subjectString != null && !"".equals(subjectString)) { + if (subjectString != null && !"".equals(subjectString)) { Class<?> subjectClass = Class.forName(subjectString); subjectFinder = (TaasSubjectFinder) subjectClass.newInstance(); } else { subjectFinder = new TaasSubjectFinderImpl(); } - + // Recupere un context root sans securite Properties config = rootContext.getConfig(); config.remove("topia.service.taas"); String persistences = config.getProperty("topia.persistence.classes"); for (Class<?> klass : getPersistenceClasses()) { - persistences += "," + klass.getName(); + persistences += "," + klass.getName(); } config.setProperty("topia.persistence.classes", persistences); @@ -175,7 +179,7 @@ } catch (Exception e) { throw new SecurityException("Init security error", e); } - + return true; } @@ -184,22 +188,23 @@ TopiaContext context = event.getSource(); initSecurity(context); } - + /** * Initialisation des vetoables + * * @param context context topia en cours */ private void initSecurity(TopiaContext context) { List<Class<?>> entitiesClasses = rootContext.getPersistenceClasses(); for (Class<?> clazz : entitiesClasses) { - context.addTopiaEntityVetoable((Class)clazz, accessEntity); + context.addTopiaEntityVetoable((Class) clazz, accessEntity); } - + Class<?>[] noLoadClasses = getPersistenceClasses(); for (Class<?> clazz : noLoadClasses) { - context.addTopiaEntityVetoable((Class)clazz, accessEntity); + context.addTopiaEntityVetoable((Class) clazz, accessEntity); } - + context.addTopiaEntitiesVetoable(accessEntity); context.addTopiaTransactionVetoable(this); } @@ -208,12 +213,13 @@ * (non-Javadoc) * @see org.nuiton.topia.framework.TopiaService#postInit(org.nuiton.topia.framework.TopiaContextImplementor) */ + @Override public boolean postInit(TopiaContextImplementor context) { policy.installPolicy(); - + // Si pas de configuration autre que celle par d�faut - if(Configuration.getConfiguration() == null) { + if (Configuration.getConfiguration() == null) { Configuration.setConfiguration(new TaasConfiguration(SERVICE_NAME, this)); } return true; @@ -221,6 +227,7 @@ /** * Permet d'obtenir le context root + * * @return context root */ public TopiaContextImplementor getRootContext() { @@ -229,25 +236,29 @@ /** * Permet de recuperer un context root sans securite + * * @return context root non securise * @throws TopiaException */ public TopiaContext getRootContextNoSecure() throws TopiaException { - return rootContextNoSecure; + return rootContextNoSecure; } /** * Permet de r�cup�rer le subject en cours + * * @return subject */ public Subject findSubject() { return subjectFinder.findSubject(); } - + /** - * Permet de verifier les authorizations sur une collection et de supprimer les donnees non autoris�es + * Permet de verifier les authorizations sur une collection et de supprimer + * les donnees non autoris�es + * * @param entities collection d'entites - * @param actions actions + * @param actions actions * @throws SecurityException en cas d'erreur de s�curit� */ public void check(Collection<? extends TopiaEntity> entities, int actions) throws SecurityException { @@ -256,7 +267,7 @@ for (Iterator<? extends TopiaEntity> iterator = entities.iterator(); iterator.hasNext();) { TopiaEntity entity = iterator.next(); try { - AccessController.checkPermission(new TaasPermission(entity.getId(), actions)); + AccessController.checkPermission(new TaasPermission(entity.getTopiaId(), actions)); } catch (SecurityException se) { if (log.isDebugEnabled()) { log.debug(getPrincipalNames(subj) + " does not have permissions to load: " + entity); @@ -271,17 +282,18 @@ /** * Permet de v�rifier les authorizations - * @param entity entit� + * + * @param entity entit� * @param actions actions * @throws SecurityException en cas d'erreur de s�curit� */ public void check(TopiaEntity entity, int actions) throws SecurityException { - Subject subj = findSubject(); + Subject subj = findSubject(); if (subj != null) { try { - AccessController.checkPermission(new TaasPermission(entity.getId(), actions)); + AccessController.checkPermission(new TaasPermission(entity.getTopiaId(), actions)); } catch (SecurityException se) { - throw new SecurityException("Access denied to object \"" + entity.getId() + "\" for \"" + getPrincipalNames(subj) + "\""); + throw new SecurityException("Access denied to object \"" + entity.getTopiaId() + "\" for \"" + getPrincipalNames(subj) + "\""); } } else { throw new SecurityException("Use doAs() and login first"); @@ -290,12 +302,13 @@ /** * Permet de v�rifier les authorizations + * * @param topiaId id de l'entite * @param actions actions * @throws SecurityException en cas d'erreur de s�curit� */ public void check(String topiaId, int actions) throws SecurityException { - Subject subj = findSubject(); + Subject subj = findSubject(); if (subj != null) { try { AccessController.checkPermission(new TaasPermission(topiaId, actions)); @@ -309,21 +322,22 @@ /** * Permet de v�rifier les authorizations - * @param entity entit� + * + * @param entity entit� * @param actions actions * @throws SecurityException en cas d'erreur de s�curit� */ public void checkRequestPermission(TopiaEntity entity, int actions) throws SecurityException { - Subject subj = findSubject(); + Subject subj = findSubject(); if (subj != null) { List<Permission> permissions = getRequestPermission(entity, actions); - if(permissions == null) { + if (permissions == null) { try { - AccessController.checkPermission(new TaasPermission(entity.getId(), actions)); + AccessController.checkPermission(new TaasPermission(entity.getTopiaId(), actions)); } catch (SecurityException se) { - throw new SecurityException("Access denied to object \"" + entity.getId() + "\" for \"" + getPrincipalNames(subj) + "\""); + throw new SecurityException("Access denied to object \"" + entity.getTopiaId() + "\" for \"" + getPrincipalNames(subj) + "\""); } } else { for (Permission permission : permissions) { @@ -331,7 +345,7 @@ AccessController.checkPermission(permission); break; } catch (SecurityException se) { - throw new SecurityException("Access denied to object \"" + entity.getId() + "\" for \"" + getPrincipalNames(subj) + "\""); + throw new SecurityException("Access denied to object \"" + entity.getTopiaId() + "\" for \"" + getPrincipalNames(subj) + "\""); } } } @@ -341,22 +355,24 @@ } /** - * Permet de v�rifier les authorizations sur une collection et de supprimer les donn�es non autoris�es + * Permet de v�rifier les authorizations sur une collection et de supprimer + * les donn�es non autoris�es + * * @param entities collection d'entit�s - * @param actions actions + * @param actions actions * @throws SecurityException en cas d'erreur de s�curit� */ public void checkRequestPermission(Collection<? extends TopiaEntity> entities, int actions) throws SecurityException { - Subject subj = findSubject(); + Subject subj = findSubject(); if (subj != null) { for (Iterator<? extends TopiaEntity> iterator = entities.iterator(); iterator.hasNext();) { TopiaEntity entity = iterator.next(); List<Permission> permissions = getRequestPermission(entity, actions); - if(permissions == null) { + if (permissions == null) { try { - AccessController.checkPermission(new TaasPermission(entity.getId(), actions)); + AccessController.checkPermission(new TaasPermission(entity.getTopiaId(), actions)); } catch (SecurityException se) { iterator.remove(); } @@ -378,12 +394,13 @@ /** * R�cup�ration des requests permissions dans les DAOs - * @param entity entit� + * + * @param entity entit� * @param actions actions * @return permissions � v�rifier */ public List<Permission> getRequestPermission(TopiaEntity entity, int actions) { - String topiaId = entity.getId(); + String topiaId = entity.getTopiaId(); Class<? extends TopiaEntity> klass; try { Modified: trunk/topia-service-security/src/main/java/org/nuiton/topia/taas/event/TaasEntityVetoable.java =================================================================== --- trunk/topia-service-security/src/main/java/org/nuiton/topia/taas/event/TaasEntityVetoable.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-service-security/src/main/java/org/nuiton/topia/taas/event/TaasEntityVetoable.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -30,38 +30,38 @@ import org.nuiton.topia.event.TopiaEntitiesEvent; import org.nuiton.topia.event.TopiaEntityEvent; import org.nuiton.topia.persistence.TopiaEntity; -import static org.nuiton.topia.security.util.TopiaSecurityUtil.UPDATE; import org.nuiton.topia.taas.TaasService; -import static org.nuiton.topia.taas.TaasUtil.CREATE; -import static org.nuiton.topia.taas.TaasUtil.DELETE; -import static org.nuiton.topia.taas.TaasUtil.LOAD; import org.nuiton.topia.taas.entities.TaasAuthorization; import org.nuiton.topia.taas.entities.TaasPrincipal; import org.nuiton.topia.taas.entities.TaasUser; import java.util.List; +import static org.nuiton.topia.security.util.TopiaSecurityUtil.UPDATE; +import static org.nuiton.topia.taas.TaasUtil.CREATE; +import static org.nuiton.topia.taas.TaasUtil.DELETE; +import static org.nuiton.topia.taas.TaasUtil.LOAD; + public class TaasEntityVetoable implements TaasAccessEntity { private static Log log = LogFactory.getLog(TaasEntityVetoable.class); - + protected TaasService taasService; - - /** - * Contructeur par defaut - */ + + /** Contructeur par defaut */ public TaasEntityVetoable(TaasService taasService) { this.taasService = taasService; } - + /* (non-Javadoc) - * @see org.nuiton.topia.event.TopiaVetoableEntityListener#createEntity(org.nuiton.topia.event.TopiaVetoableEntityEvent) - */ + * @see org.nuiton.topia.event.TopiaVetoableEntityListener#createEntity(org.nuiton.topia.event.TopiaVetoableEntityEvent) + */ + public void create(TopiaEntityEvent event) { TopiaEntity entity = event.getEntity(); - String topiaId = entity.getId(); + String topiaId = entity.getTopiaId(); Class<? extends TopiaEntity> clazz; - + if (log.isDebugEnabled()) { log.debug("[Security] create entity : " + topiaId); } @@ -71,10 +71,11 @@ /* (non-Javadoc) * @see org.nuiton.topia.event.TopiaVetoableEntityListener#deleteEntity(org.nuiton.topia.event.TopiaVetoableEntityEvent) */ + public void delete(TopiaEntityEvent event) { TopiaEntity entity = event.getEntity(); - String topiaId = entity.getId(); - + String topiaId = entity.getTopiaId(); + if (log.isDebugEnabled()) { log.debug("[Security] delete entity : " + topiaId); } @@ -85,9 +86,10 @@ * (non-Javadoc) * @see org.nuiton.topia.event.TopiaVetoableEntityLoadListener#loadEntity(org.nuiton.topia.event.TopiaVetoableEntityLoadEvent) */ - public void load(TopiaEntityEvent event) { + + public void load(TopiaEntityEvent event) { // TopiaEntity entity = event.getEntity(); -// String topiaId = entity.getId(); +// String topiaId = entity.getTopiaId(); // // if (log.isDebugEnabled()) { // log.debug("[Security] load entity : " + topiaId); @@ -98,30 +100,32 @@ /* (non-Javadoc) * @see org.nuiton.topia.event.TopiaVetoableEntityListener#updateEntity(org.nuiton.topia.event.TopiaVetoableEntityEvent) */ + public void update(TopiaEntityEvent event) { TopiaEntity entity = event.getEntity(); - String topiaId = entity.getId(); + String topiaId = entity.getTopiaId(); if (log.isDebugEnabled()) { log.debug("[Security] update entity : " + topiaId); } taasService.check(entity, UPDATE); } - + /* - * (non-Javadoc) - * @see org.nuiton.topia.event.TopiaEntitiesVetoable#load(org.nuiton.topia.event.TopiaEntitiesEvent) - */ + * (non-Javadoc) + * @see org.nuiton.topia.event.TopiaEntitiesVetoable#load(org.nuiton.topia.event.TopiaEntitiesEvent) + */ + public <E extends TopiaEntity> List<E> load(TopiaEntitiesEvent<E> event) { if (log.isDebugEnabled()) { log.debug("[Security] load entities"); } - + List<E> entities = event.getEntities(); - - if(!entities.isEmpty()) { + + if (!entities.isEmpty()) { E entity = entities.get(0); - if(!(entity instanceof TaasUser || + if (!(entity instanceof TaasUser || entity instanceof TaasPrincipal || entity instanceof TaasAuthorization)) { taasService.check(entities, LOAD); Modified: trunk/topia-service-security/src/main/java/org/nuiton/topia/taas/event/TaasEntityVetoableRequestPermission.java =================================================================== --- trunk/topia-service-security/src/main/java/org/nuiton/topia/taas/event/TaasEntityVetoableRequestPermission.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-service-security/src/main/java/org/nuiton/topia/taas/event/TaasEntityVetoableRequestPermission.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -30,35 +30,35 @@ import org.nuiton.topia.event.TopiaEntitiesEvent; import org.nuiton.topia.event.TopiaEntityEvent; import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.taas.TaasService; + +import java.util.List; + import static org.nuiton.topia.security.util.TopiaSecurityUtil.UPDATE; -import org.nuiton.topia.taas.TaasService; import static org.nuiton.topia.taas.TaasUtil.CREATE; import static org.nuiton.topia.taas.TaasUtil.DELETE; import static org.nuiton.topia.taas.TaasUtil.LOAD; -import java.util.List; - public class TaasEntityVetoableRequestPermission implements TaasAccessEntity { private static Log log = LogFactory.getLog(TaasEntityVetoableRequestPermission.class); - + protected TaasService taasService; - - /** - * Contructeur par defaut - */ + + /** Contructeur par defaut */ public TaasEntityVetoableRequestPermission(TaasService taasService) { this.taasService = taasService; } - + /* (non-Javadoc) - * @see org.nuiton.topia.event.TopiaVetoableEntityListener#createEntity(org.nuiton.topia.event.TopiaVetoableEntityEvent) - */ + * @see org.nuiton.topia.event.TopiaVetoableEntityListener#createEntity(org.nuiton.topia.event.TopiaVetoableEntityEvent) + */ + public void create(TopiaEntityEvent event) { TopiaEntity entity = event.getEntity(); - String topiaId = entity.getId(); + String topiaId = entity.getTopiaId(); Class<? extends TopiaEntity> clazz; - + if (log.isDebugEnabled()) { log.debug("[Security] create entity : " + topiaId); } @@ -68,10 +68,11 @@ /* (non-Javadoc) * @see org.nuiton.topia.event.TopiaVetoableEntityListener#deleteEntity(org.nuiton.topia.event.TopiaVetoableEntityEvent) */ + public void delete(TopiaEntityEvent event) { TopiaEntity entity = event.getEntity(); - String topiaId = entity.getId(); - + String topiaId = entity.getTopiaId(); + if (log.isDebugEnabled()) { log.debug("[Security] delete entity : " + topiaId); } @@ -82,9 +83,10 @@ * (non-Javadoc) * @see org.nuiton.topia.event.TopiaVetoableEntityLoadListener#loadEntity(org.nuiton.topia.event.TopiaVetoableEntityLoadEvent) */ + public void load(TopiaEntityEvent event) { // TopiaEntity entity = event.getEntity(); -// String topiaId = entity.getId(); +// String topiaId = entity.getTopiaId(); // // if (log.isDebugEnabled()) { // log.debug("[Security] load entity : " + topiaId); @@ -95,20 +97,22 @@ /* (non-Javadoc) * @see org.nuiton.topia.event.TopiaVetoableEntityListener#updateEntity(org.nuiton.topia.event.TopiaVetoableEntityEvent) */ + public void update(TopiaEntityEvent event) { TopiaEntity entity = event.getEntity(); - String topiaId = entity.getId(); + String topiaId = entity.getTopiaId(); if (log.isDebugEnabled()) { log.debug("[Security] update entity : " + topiaId); } taasService.checkRequestPermission(entity, UPDATE); } - + /* - * (non-Javadoc) - * @see org.nuiton.topia.event.TopiaEntitiesVetoable#load(org.nuiton.topia.event.TopiaEntitiesEvent) - */ + * (non-Javadoc) + * @see org.nuiton.topia.event.TopiaEntitiesVetoable#load(org.nuiton.topia.event.TopiaEntitiesEvent) + */ + public <E extends TopiaEntity> List<E> load(TopiaEntitiesEvent<E> event) { if (log.isDebugEnabled()) { log.debug("[Security] load entities"); Modified: trunk/topia-service-security/src/test/java/org/nuiton/topia/security/TopiaSecurityTest.java =================================================================== --- trunk/topia-service-security/src/test/java/org/nuiton/topia/security/TopiaSecurityTest.java 2010-05-14 14:18:23 UTC (rev 1963) +++ trunk/topia-service-security/src/test/java/org/nuiton/topia/security/TopiaSecurityTest.java 2010-05-20 10:41:48 UTC (rev 1964) @@ -25,22 +25,19 @@ package org.nuiton.topia.security; -import static org.nuiton.topia.security.util.TopiaSecurityUtil.LOAD; -import static org.nuiton.topia.security.util.TopiaSecurityUtil.UPDATE; -import java.io.File; -import java.security.PrivilegedExceptionAction; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import javax.security.auth.Subject; -import javax.security.auth.login.LoginContext; - +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; import org.nuiton.topia.TestUtils; import org.nuiton.topia.TopiaContext; import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; import org.nuiton.topia.TopiaSecurityDAOHelper; +import org.nuiton.topia.TopiaTestDAOHelper; import org.nuiton.topia.security.entities.authorization.TopiaAssociationAuthorization; import org.nuiton.topia.security.entities.authorization.TopiaAssociationAuthorizationDAO; import org.nuiton.topia.security.entities.authorization.TopiaEntityAuthorization; @@ -55,37 +52,43 @@ import org.nuiton.topia.security.util.TopiaSecurityFactoryFilter; import org.nuiton.topia.test.entities.Person; import org.nuiton.topia.test.entities.PersonDAO; +import org.nuiton.topia.test.entities.PersonImpl; import org.nuiton.topia.test.entities.Pet; import org.nuiton.topia.test.entities.PetDAO; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.nuiton.topia.TopiaTestDAOHelper; -import org.nuiton.topia.test.entities.PersonImpl; import org.nuiton.topia.test.entities.PetImpl; import org.nuiton.topia.test.entities.RaceImpl; +import javax.security.auth.Subject; +import javax.security.auth.login.LoginContext; +import java.io.File; +import java.security.PrivilegedExceptionAction; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import static org.nuiton.topia.security.util.TopiaSecurityUtil.LOAD; +import static org.nuiton.topia.security.util.TopiaSecurityUtil.UPDATE; + /** - * Tests unitaires. - * Ne pas oublier de lancer le script d'initialisation de la base données. + * Tests unitaires. Ne pas oublier de lancer le script d'initialisation de la + * base données. * * @author ruchaud */ public class TopiaSecurityTest { protected static TopiaContext context; + protected static TopiaSecurityService securityManager; + protected static TopiaSecurityFactoryFilter factoryFilter; // FIXME comment il trouve les autres tout seul ? // The grande question !!! + protected static String entitiesList = PersonImpl.class.getName() + "," + - PetImpl.class.getName() + "," + - RaceImpl.class.getName(); + PetImpl.class.getName() + "," + + RaceImpl.class.getName(); @BeforeClass public static void init() throws Exception { @@ -209,45 +212,45 @@ TopiaEntityAuthorization authorizationForAdmin = topiaEntityAuthorizationDAO.create(); authorizationForAdmin.setExpression("*"); authorizationForAdmin.setActions(15); - authorizationForAdmin.setPrincipals(admin.getId()); + authorizationForAdmin.setPrincipals(admin.getTopiaId()); topiaEntityAuthorizationDAO.update(authorizationForAdmin); childContext.commitTransaction(); TopiaEntityAuthorization authorizationForRuchaud = topiaEntityAuthorizationDAO.create(); authorizationForRuchaud.setExpression(Person.class.getName() + "#*"); authorizationForRuchaud.setActions(LOAD); - authorizationForRuchaud.setPrincipals(groupRuchaud.getId()); + authorizationForRuchaud.setPrincipals(groupRuchaud.getTopiaId()); topiaEntityAuthorizationDAO.update(authorizationForRuchaud); childContext.commitTransaction(); TopiaEntityAuthorization authorizationForThimel = topiaEntityAuthorizationDAO.create(); - authorizationForThimel.setExpression(jacques.getId()); + authorizationForThimel.setExpression(jacques.getTopiaId()); authorizationForThimel.setActions(LOAD); - authorizationForThimel.setPrincipals(thimel.getId()); + authorizationForThimel.setPrincipals(thimel.getTopiaId()); topiaEntityAuthorizationDAO.update(authorizationForThimel); childContext.commitTransaction(); /* Création d'une autorisation Link */ TopiaExpressionLink link = linkDAO.create(); - link.setReplace(mylene.getId()); - link.setBy(jacques.getId()); + link.setReplace(mylene.getTopiaId()); + link.setBy(jacques.getTopiaId()); linkDAO.update(link); childContext.commitTransaction(); /* Création d'une authorisation association */ TopiaAssociationAuthorization associationAuthorization = topiaAssociationAuthorizationDAO.create(); - associationAuthorization.setIdBeginAssociation(jacques.getId()); + associationAuthorization.setIdBeginAssociation(jacques.getTopiaId()); associationAuthorization.setNameAssociation("pet"); associationAuthorization.setActions(LOAD); - associationAuthorization.setPrincipals(ruchaud.getId()); + associationAuthorization.setPrincipals(ruchaud.getTopiaId()); topiaAssociationAuthorizationDAO.update(associationAuthorization); childContext.commitTransaction(); associationAuthorization = topiaAssociationAuthorizationDAO.create(); - associationAuthorization.setIdBeginAssociation(mylene.getId()); + associationAuthorization.setIdBeginAssociation(mylene.getTopiaId()); associationAuthorization.setNameAssociation("pet"); associationAuthorization.setActions(UPDATE); - associationAuthorization.setPrincipals(ruchaud.getId()); + associationAuthorization.setPrincipals(ruchaud.getTopiaId()); topiaAssociationAuthorizationDAO.update(associationAuthorization); childContext.commitTransaction();